texts: Chatty AI that saves .txt files to remember

texts:
This is a basic AI that I created.  It has a teach function that creates a .txt file with user inputed info for future use.  If you type teachme you have the option to type in something that you have already taught it and it will tell you what you taught it.
Any tips to make this better are appreciated.  (I'm OK if you tell me I completely messed up.)

@echo off
COLOR A
     echo.>"c:\users\Joe\desktop\charinfo.txt"
    if not exist charinfo.txt goto :charinfo
    goto :load
TITLE
:charinfo
cls
echo Make an avatar please.
echo.
set /p name=Name:
cls
set /p sex=Sex:
echo.
cls
echo What would you like my name to be?
set /p botname=
TITLE %botname%
cls
set /p colour=Program Color ID:
cls
(
echo %name%
echo %sex%
echo %botname%
echo %colour%
 ) > charinfo.txt

cls
:load
(
set /p name=
set /p sex=
set /p botname=
set /p colour=
) < charinfo.txt

:start
color %colour%
TITLE %botname%
cls
echo.
echo.
echo Hello, my name is '%botname%'
if %name%==restart goto :start
echo.
:q1
echo Hi %name%!  How are you doing?
set /p mood=
if %mood%==good goto :good
if %mood%==bad goto :bad
if %mood%==fine goto :good
if %mood%==awesome goto :awesome
if %mood%==ok goto :ok
if %mood%==* goto :ok
if %mood%==bored goto :bored
if %mood%==idk goto :bored
if %mood%==crappy goto :bad
if %mood%==happy goto :good
if %mood%==sad goto :bad
if %mood%==great goto :awesome
if %mood%==meh goto :meh
if %mood%==restart goto :start
if %mood%==teach goto :q3
if %mood%==teachme goto :learned
if %mood%==tips goto :tips

:good
echo That's great! I'm doing pretty good today as well.
goto :q2
:bad
echo Well that sux.  I hope you get better though!
goto :q2
:awesome
echo Cool! My day has been pretty good.
goto :q2
:ok
echo That's good, the day can only get better!
goto :q2
:bored
echo Well find something to do then!
goto :q2
:meh
echo Well at least you're not doing too bad!
goto :q2
echo.
:teaching

cls
echo In one word tell me what you want to teach me?
echo.
set /p cat=:
if exist "c:\users\Joe\desktop\AI_BRAIN(MINE)\brain\%cat%.txt" goto :already
if not exist "c:\users\Joe\desktop\AI_BRAIN(MINE)\brain\%cat%.txt" goto :idk

:learned
cls
echo If you've told me about it!  I'll remember it
echo what do you want to learn about?
echo.
set /p cat=:
if not exist "c:\users\Joe\desktop\AI_Brain(MINE)\brain\%cat%.txt" goto :idk
(
::set /p cat=
set /p catinfo=
) < "c:\users\Joe\desktop\AI_Brain(MINE)\brain\%cat%.txt"
type "c:\users\Joe\desktop\AI_Brain(MINE)\brain\%cat%.txt"
::pause >nul
goto :p5

:idk
cls
echo I don't know anything about %cat%. Can you tell me what you know.
echo.
set /p catinfo=:
echo %catinfo% >> "c:\users\chuggaaconroy\desktop\AI_Brain(MINE)\brain\%cat%.txt"
set txt=That's cool, now I know.
set txt=Cool now I know about %cat%.
goto :q4

:q2
cls
echo Have you done anything cool today?
set /p activity=
if %activity%==restart goto :start
if %activity%==teach goto :teaching
if %activity%==teachme goto :learned
if %activity%==tips goto :tips
echo cool!
echo I havn't really done much today, I kind've just sat around all day :\
:q3
cls
echo Would you like to teach me about something?
set /p answer1=Say Yes or no:

if %answer1%==no goto :info1
if %answer1%==yes goto :teaching

:info1
cls
echo OK!  If you ever want to teach me something please type in "teach"
goto :q4
:already
echo I think I've already learnt that!
goto :q3
:tips
cls
echo If at any time you would like to restart, please type 'restart' without the '' then press enter
echo.
echo If you want to teach me something, type in teach
echo.
echo if you want me to tell you something that you've taught me. Type in teachme
echo.
echo If you would like to view these tips again, type in tips at anytime.
goto :end
:q4
echo Awesome! now I know!  If you want me to tell you about it later, just type in teachme.
goto :end
:p5
echo Told you I would remember!
goto :end
:end
echo You have reached the end
pause


texts:
If given two lists a: ['the', 'a', 'and', 'for'] and b: [0.2, 0.3, 0.4, 0.1], the positions of the numbers in b represents the weights for the respective probabilities of obtaining the corresponding word. E.g. the : 20%, a : 30%, etc. Create a function that will generate words based on their corresponding probabilities.

My solution:

import random
def weighted_word_selection(words, weights):
    """
    words : an array of strings (words)
    weights : an array of floats (corresponding probabilties based on)
              index number.
    """
    start = 0
    for i in range(len(weights)):
        weights[i] = start+weights[i]
        start += weights[i]
    r = random.uniform(0, 1.0)
    for i in range(len(weights)):
        if r < weights[i]:
            return words[i]

Questions:

What are some alternative ways to solve this, bearing in mind the requirement to optimize performance as the array words and the array weights approaches a large n? Any detailed explanations of underlying processes such as Cython/C based Python solutions are helpful.
Can you discuss the \$O(n)\$ based complexity of the problem and some performance issues in my solution, and how those are addressed in your suggested solution at scale?


texts:
I wrote the following (static) class to read files easily in C#. However, it is a static class, so I wonder if there would be a gain to make it a non static method (and therefore, passing arguments as the separator and the path as attributes of the class).

Besides, the OrderedDictionary class may not be a good choice (it is not generic but it preserves the order of the columns), and I don't know if there is a nice workaround for this.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;

namespace MySolution.FileUtils
{
    /// <summary>
    /// Various helpers to read through the lines of a file.
    /// </summary>
    public static class LinesEnumerator
    {
        public static string ReadFirstLine(string path)
        {
            using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader sr = new StreamReader(fs))
            {
                return sr.ReadLine();
            }
        }

        /// <summary>
        /// Enumerates the lines of a file.
        /// </summary>
        /// <param name="path">The path of the file.</param>
        /// <param name="maxLines">The maximum number of lines to read.</param>
        /// <returns>The lines of a file, as a IEnumerable</returns>
        public static IEnumerable<string> LinesReader(string path, int maxLines = Int32.MaxValue)
        {
            string line;
            int lineNumber = 0;
            using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader sr = new StreamReader(fs))
            {
                while ((line = sr.ReadLine()) != null && lineNumber < maxLines)
                {
                    lineNumber++;
                    yield return line;
                }
            }
        }

        /// <summary>
        /// Reads the lines of a CSV file and enumerates them through a csv file
        /// </summary>
        /// <param name="path">Path to the CSV file</param>
        /// <param name="separator">Separator used by the CSV file</param>
        /// <returns>A collection of ordered dictionaries, corresponding to the lines of the file</returns>
        public static IEnumerable<OrderedDictionary> DictReaderCSV(string path, char separator)
        {
            using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader sr = new StreamReader(fs))
            {
                string[] header = sr.ReadLine().Split(separator);
                string line = "";
                while ((line = sr.ReadLine()) != null)
                {
                    string[] splittedLine = line.Split(separator);
                    OrderedDictionary od = new OrderedDictionary();
                    for (int i = 0; i < header.Length; i++)
                        od.Add(header[i], splittedLine[i]);
                    yield return od;
                }
            }
        }
    }
}


texts:
I am using the following code to password protect pages on my site. This is how I am including it on a page:

<?php include("/path/to/password_protect.php"); ?>

After that line I have the rest of the page code, which is not displayed if the user is not logged in.

This is the password protect code itself, included on every page I want secured:

password_protect.php

<?php

#  SETTINGS START

$LOGIN_INFORMATION = array(
  'admin' => 'admin'
);
// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);
// User will be redirected to this page after logout
define('LOGOUT_URL', '/hub');
// time out after NN minutes of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 0);
// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

#  SETTINGS END

// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);
// logout?
if(isset($_GET['logout'])) {
  setcookie("verify", '', $timeout, '/'); // clear password;
  header('Location: ' . LOGOUT_URL);
  exit();
}
if(!function_exists('showLoginPasswordProtect')) {
// show login form
function showLoginPasswordProtect($error_msg) {
?>

  <title>Please enter password to access this page</title>

  <form method="post">

Please enter password to access this page

    <?php echo $error_msg; ?>

<?php if (USE_USERNAME) echo 'Username:
<input type="input" name="access_login" />
Password:
'; ?>
    <input type="password" name="access_password" />

<input type="submit" name="Submit" value="Submit" />
  </form>

<?php
  // stop at this point
  die();
}
}
// user provided password
if (isset($_POST['access_password'])) {
  $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  $pass = $_POST['access_password'];
  if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) )
  ) {
    showLoginPasswordProtect("Details Incorrect");
  }
  else {
    // set cookie if password was validated
    setcookie("verify", md5($login.'%'.$pass), $timeout, '/');

    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }
}
else {
  // check if password cookie is set
  if (!isset($_COOKIE['verify'])) {
    showLoginPasswordProtect("");
  }
  // check if cookie is good
  $found = false;
  foreach($LOGIN_INFORMATION as $key=>$val) {
    $lp = (USE_USERNAME ? $key : '') .'%'.$val;
    if ($_COOKIE['verify'] == md5($lp)) {
      $found = true;
      // prolong timeout
      if (TIMEOUT_CHECK_ACTIVITY) {
        setcookie("verify", md5($lp), $timeout, '/');
      }
      break;
    }
  }
  if (!$found) {
    showLoginPasswordProtect("");
  }
}
?>

This is not to secure anything highly sensitive (e.g. credit card details), but is to password protect analytics dashboards for client websites. To that end it needs to be moderately secure. My questions would be:

1) Are there any improvements I could make to the code to make it more streamlined?

2) Are there any large security issues that I need to address? As I said above it is not protecting hugely sensitive data but if there is a major problem or an easy improvement that would be great.

Thanks for any feedback!


texts: Building balanced BST from sorted array: recursive and iterative approaches

texts:
I am implementing an algorithm to solve the following problem:

  Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.

The solution of this problem using recursion is quite straightforward:

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def build_bst_recursive(array):
    size = len(array)
    return _build_bst(array, first=0, last=size - 1)

def _build_bst(array, first, last):
    if last < first:
        return None
    mid = (first + last) // 2
    node = Node(mid)
    node.left = _build_bst(array, first, mid - 1)
    node.right = _build_bst(array, mid + 1, last)
    return node

Out of curiosity I also would like to solve the same problem using an iterative algorithm. Here is what I came up with:

class Stack:
    class _Node:
        def __init__(self, value):
            self.value = value
            self.next_node = None

    def __init__(self):
        self.head_node = None

    def is_empty(self):
        return self.head_node is None

    def push(self, value):
        node = self._Node(value)
        node.next_node = self.head_node
        self.head_node = node

    def pop(self):
        if self.is_empty():
            raise Exception("Stack is empty.")
        node = self.head_node
        self.head_node = node.next_node
        return node.value

def build_bst_iterative(array):
    size = len(array)

    # Stack stores tuples of the first and the last indices of half-segments:
    stack_indices = Stack()
    stack_indices.push((0, size - 1))

    # Stack stores tree nodes:
    stack_nodes = Stack()

    # Add to the stack a node that will be a root of the tree:
    root_node = Node(None)
    stack_nodes.push(root_node)

    while not stack_indices.is_empty():
        first, last = stack_indices.pop()
        node = stack_nodes.pop()

        if last < first:
            # The segment is degenerated. Keep the node empty.
            continue
        elif last == first:
            # Assign the value, it is the last bottom node.
            node.value = array[last]
            continue

        mid = (first + last) // 2
        node.value = array[mid]
        node.left = Node(None)
        node.right = Node(None)

        # Update stacks:
        # (right half-segment)
        stack_indices.push((mid + 1, last))
        stack_nodes.push(node.right)
        # (left half-segment)
        stack_indices.push((first, mid - 1))
        stack_nodes.push(node.left)
    assert stack_nodes.is_empty()

    return root_node

I would highly appreciate if you could review the code and suggest any approaches for improvement. For example, I am trying to understand if it is possible to use only one stack.

EDIT After looking into my code in the morning, I realise that there is no need for two stacks because I always push and pop to the two stacks at the same time. Here there is an updated version of the code:

def build_bst_iterative_one_stack(array):
    size = len(array)

    # Add to the stack a node that will be a root of the tree:
    root_node = Node(None)

    # Stack stores tuples of the current node, and the first and the last indices of half-segments:
    stack = Stack()
    stack.push((root_node, 0, size - 1))

    while not stack.is_empty():
        node, first, last = stack.pop()

        if last < first:
            # The segment is degenerated. Do nothing.
            continue
        elif last == first:
            # Assign the value, it is the last bottom node.
            node.value = array[last]
            continue

        mid = (first + last) // 2
        node.value = array[mid]
        node.left = Node(None)
        node.right = Node(None)

        # Update the stack with the left and the right half-segment:
        stack.push((node.right, mid + 1, last))
        stack.push((node.left, first, mid - 1))
    assert stack.is_empty()

    return root_node


texts: Lock-free segmented shared memory buffer in C++

texts:
Summary

The code operates three memory mapped file segments:

just finished
currently active
next to write

Potentially slow operations of closing just finished and opening next to write are done in a dedicated background thread.

Concurrent writers know how much they need for a single operation and request that much from the segmented buffer at a time.

The writer that fails to check out the required size finalizes the currently active file (writing a marker and requesting background thread to close the file and prepare one more).

Source code on github: audit_buffer.hpp, the respective benchmark with usage demonstration: audit_benchmarks.cpp

The central part (which I am primarily concerned about) is below. I would appreciate general feedback on the implementation (specifically, code simplification and speedup), and also ideas on getting rid of the spin-lock.

/**
 * Reserves the  requred space in the buffer, jumping to the next segment if required
 */
std::shared_ptr<char> reserve(size_t required_size) {
    if (unlikely(required_size > filesize_ - 1))
        throw std::runtime_error("too much memory requested");

    std::shared_ptr<log_segment> segment;
    size_t pos = 0u;
    do {
        auto const segment_idx = segment_idx_.load(std::memory_order_acquire);
        auto const psegment = &segments_[segment_idx % segments_.size()];

        { // effectively std::atomic_load with custom spinlock
            guard_t guard {mutex_};
            segment = *psegment;
        }

        if (likely(segment)) {
            pos = segment->reserve(required_size);
            auto const last_pos = segment->size() - 1;
            if (unlikely(pos < last_pos && (pos + required_size >= last_pos))) {
                // it's this request that crossed the segment capacity

                { // effectively std::atomic_store with custom spinlock
                    guard_t guard {mutex_};
                    psegment->reset();
                }

                request_next_segment_();

                *(segment->memory() + pos) = 0x19; // End-of-Media
                segment.reset();

                // publish the next segment
                segment_idx_.store(segment_idx + 1, std::memory_order_release);
            }
            else if (unlikely(pos >= last_pos)) {
                segment.reset();
            }
        }
    } while (unlikely(!segment));

    return {segment, segment->memory() + pos}; // aliased shared_ptr to hold the segment alive
}


texts: Passing a value from my Gruntfile to an external Grunt task

texts:
In my Gruntfile, I use the grunt-contrib-watch task to watch a directory for file changes:

watch: {
    releases: {
        files: ['source/md/releases/*.md'],
        tasks: ['process:auto']
    }
}

Also, in the Gruntfile, I have a "watch" event handler. Inside this handler, I temporarily store the file path of the file that was modified, so that my task can read this information and only process that file:

grunt.event.on('watch', function (action, filepath, target) {
    if (target === 'releases') {
        grunt.file.write('filepath.txt', filepath);
    }
});

Then, inside my Grunt task (which is located in "tasks/process.js"), I read that file:

if (this.target === 'auto') {
    path = grunt.file.read('filepath.txt');

    // process file at given path

    grunt.file.delete('filepath.txt'); // delete this temporary file
}

Having to share the file path information via a file certainly doesn't seem optimal, but I haven't found a better solution yet. Note that writing the file path information directly into the configuration of my task from within the "watch" handler:

grunt.config('process.auto.filepath', filepath);

only works with the spawn:false setting in the "watch" configuration. I cannot set this option because then there is a 10 second delay between "watch" events (i.e. file modifications are ignored in that period).


texts:
This approach was born out of wanting to pass a logical expression (E.G. ">=10000") as a parameter to a function.

So, I built an Enum and a function to use it to evaluate logical expressions.

Is this a good, maintainable, scalable approach?

Public Enum comparisonOperator
    '/ Used [[ ]] because the outer set escape the inner brackets for the Enum list, which will then escape the operator when chosen as a value. E.G. they will appear as "Operator = [<]" in code.
    [[<]] = 1
    [[<=]] = 2
    [[=]] = 3
    [[>=]] = 4
    [[>]] = 5
End Enum

Public Function ComparisonIsTrue(ByVal sourceValue As Variant, ByVal operator As comparisonOperator, ByVal comparisonValue As Variant) As Boolean

    Dim isTrue As Boolean

    Select Case operator

        Case Is = 1 '/ <
        isTrue = (sourceValue < comparisonValue)

        Case Is = 2 '/ <=
        isTrue = (sourceValue <= comparisonValue)

        Case Is = 3 '/ =
        isTrue = (sourceValue = comparisonValue)

        Case Is = 4 '/ >=
        isTrue = (sourceValue >= comparisonValue)

        Case Is = 5 '/ >
        isTrue = (sourceValue > comparisonValue)

        Case Else
        '/ Error Handling
        Stop

    End Select

    ComparisonIsTrue = isTrue

End Function


texts:
I am a newcomer to design patterns. I read some articles about the abstract factory pattern, and wrote the following simple example:

public interface ParserFactory {
   List<ITransport> getBusList();
   List<ITransport> getTrainList();
   List<ITransport> getPlaneList();
}

public abstract class XMLParserFactory implements ParserFactory{ }
public abstract class CSVParserFactory implements ParserFactory{ }

public class DOMTransportParser extends XMLParserFactory{

    public List<ITransport> getBusList(){ return null;  }
    public List<ITransport> getTrainList(){ return null; }
    public List<ITransport> getPlaneList(){ return null; }
 }

 public class CSVTransportParser extends CSVParserFactory{

    public List<ITransport> getBusList(){   return null; }
    public List<ITransport> getTrainList(){ return null; }
    public List<ITransport> getPlaneList(){ return null; }
 }

}

Is anything wrong with this code? Can it be improved? Do I understand the abstract factory pattern correctly?


texts:
Given this piece of code, what is a better way to write it (cleaner).
It is taken for granted that data will not be null, nor its length will be 0, so this check is skipped.

private byte[] process(byte[] bytes) {
    int from = 0;
    if (bytes[0] == '\n') {
        from = 1;
    } else if (bytes[0] == '\r' && bytes[1] == '\n') {
        from = 2;
    }
    return Arrays.copyOfRange(bytes, from, bytes.length);
}

I thought about converting it to String, then applying a regex (^[\r\n]), but that means some encoding has to be used for the conversion and then I would have to convert it back to byte[], which does not comply with my needs.
Is there any clearer way to write this?


texts:
The method must search Products found by criteria and store them in @products.

The criteria are as follows:

If the user enters something in text_field (:search_keywords) then the product's name needs to be matched with that word
If the user specifies product_type (:product[:type]) then all the found products must be of that type.

def search
  if params[:search_keywords] && params[:search_keywords] != ""
    @products = Product.where("name LIKE '%" + params[:search_keywords] + "%'")
    if params[:product] && params[:product][:type] && params[:product][:type] != ""
      @products = Product.where("name LIKE '%" + params[:search_keywords] + "%' AND product_type_id = " + params[:product][:type])
    end
  else
    if params[:product] && params[:product][:type] && params[:product][:type] != ""
      @products = Product.find_all_by_product_type_id(params[:product][:type])
    else
      @products = Product.all
    end
  end
end


texts:
I have this logic that seems complicated checking the length and adding a colon. I'd like to see if any of you C# experts can help me simplify it. If the replace remove the full text then I am just adding the word Result. If it removes the make then I am just displaying the model.

Is there a way I can remove the if statement and combine into one?

namespace DupName
{
    public class Program
    {
        static void Main(string[] args)
        {
            StringBuilder childName = new StringBuilder();

            List<Item> items = new List<Item>()
                .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi" })
                .AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" })
                .AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" });

            foreach (var item in items)
            {

                string temp = item.ChildName.Replace(item.Name, "").Trim();

                if (temp.Length == 0)
                {
                    Console.WriteLine(string.Format("{0}","Result"));

                }else
                {

                    Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
                }
            }
        }
    }

    public static class Extensions
    {
        public static List<T> AddAlso<T>(this List<T> list, T item)
        {
            list.Add(item);
            return list;
        }
    }

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ChildName { get; set; }
    }

Output

Result: A3 Premium Plus - Audi
Result
Result
Result: S5 Premium Plus 3.0 TFSI quattro - Audi
Result: S3 Premium Plus 3.0 TFSI quattro - Audi


texts:
I just finished chasing a Heisenbug that was entirely my fault. I'd like to avoid it happening again.

I have a function which formats a date to a certain preset format. Turns out I was not allocating enough space:

char* FormatDate(DT dateTime)
{
    char* formattedDate;
    formattedDate = (char*)malloc(
      6 //That was my bug, I had 5. For the record, I forgot a comma, not the terminal null...
      + numlen(dateTime.Year)
      + numlen(dateTime.Month)
      + numlen(dateTime.Day)
      + numlen(dateTime.Hour)
      + numlen(dateTime.Minute)
      + numlen(dateTime.Second)
      );
      sprintf(formattedDate,"%d,%d,%d,%d,%d,%d", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);
    return formattedDate;
}

numlen calculates the number of characters the number would take if printed in "%d" format.

And yes, the calling function has the duty to free the response.

What I'd like to know is how to avoid having the hardcoded 6, which arguably could change. sprintf does return the numbers of characters written, but that's a lot like the chicken and the egg... Is there another approach with pre-allocating that's safe? And not, say allocate a space of 250 just to make sure anything fits.


texts: Equated Monthly Installment (EMI) for Home Loan and Amortization Schedule

texts:
Any comment on my code?
Data model
public class LoanRepaymentPlan
{
    public decimal TotalRepaymentAmount { get; private set; }
    public decimal CurrentOutstandingAmount { get; private set; }
    public decimal MonthlyRepaymentInterestAmount { get; private set; }
    public decimal MonthlyRepaymentAmount { get; private set; }
    public DateTime RepaymentDate { get; private set; }

    private LoanRepaymentPlan(decimal TotalRepaymentAmount, decimal CurrentOutstandingAmount, decimal MonthlyRepaymentAmount)
    {
        this.TotalRepaymentAmount = TotalRepaymentAmount;
        this.CurrentOutstandingAmount = CurrentOutstandingAmount;
        this.MonthlyRepaymentAmount = MonthlyRepaymentAmount;
    }

    public static LoanRepaymentPlan Create(decimal TotalRepaymentAmount, decimal CurrentOutstandingAmount, decimal MonthlyRepaymentAmount)
    {
        return new LoanRepaymentPlan(TotalRepaymentAmount, CurrentOutstandingAmount, MonthlyRepaymentAmount);
    }
}

Main calculation
static void Main(string[] args)
{
    Console.WriteLine("Equated Monthly Installment (EMI) for Home Loan");

    Console.WriteLine("Total Loan Amount: ");
    var principal = Convert.ToDouble(Console.ReadLine());

    Console.WriteLine("Interest Rate Per Annum (%): ");
    var interestRatePerAnnum = Convert.ToDouble(Console.ReadLine()) / 100;

    Console.WriteLine("Loan Period (in years): ");
    var years = Convert.ToDouble(Console.ReadLine());

    Console.WriteLine("------------------------------------------------");

    Console.WriteLine("Monthly installment: " + HousingLoanInterest(principal, interestRatePerAnnum, years).ToString("C2"));

    decimal totalRepaymentAmount = 0;
    var monthlyRepaymentAmount = HousingLoanInterest(principal, interestRatePerAnnum, years);
    var tenure = years * 12;
    var principalAndInterest = CompoundInterest(principal, interestRatePerAnnum, 12, years);
    List<LoanRepaymentPlan> repaymentPlans = new List<LoanRepaymentPlan>();

    while (tenure >= 0)
    {
        totalRepaymentAmount = totalRepaymentAmount + (decimal)monthlyRepaymentAmount;
        tenure = tenure - 1;

        repaymentPlans.Add(LoanRepaymentPlan.Create(totalRepaymentAmount,
            (decimal)principalAndInterest - totalRepaymentAmount, (decimal)monthlyRepaymentAmount));
    }

    var table = new ConsoleTable("Current Outstanding Amount", "Monthly Repayment Amount", "Total Repayment Amount");
    foreach (var item in repaymentPlans)
    {
        table.AddRow(item.CurrentOutstandingAmount, item.MonthlyRepaymentAmount, item.TotalRepaymentAmount);
    }
    table.Write();
}

Helper methods
static double CompoundInterest(double principal, double interestRate, int timesPerYear, double years)
{
    // (1 + r/n)
    double body = 1 + (interestRate / timesPerYear);

    // nt
    double exponent = timesPerYear * years;

    // P(1 + r/n)^nt
    return principal * Math.Pow(body, exponent);
}

static double HousingLoanInterest(double loanAmount, double interestRate, double years)
{
    return (loanAmount * Math.Pow((interestRate / 12) + 1,
         (years * 12)) * interestRate / 12) / (Math.Pow
         (interestRate / 12 + 1, (years * 12)) - 1);
}

There are some inaccuracy of the calculation but I will try to figure out later. One thing bothers me is the Math.Pow which uses double. I have tried to convert the calculation to decimal but unable to do so at the moment.


texts: How to configure view to carryout two operations from GET request Django

texts:
I'm trying to build a wish list for my website. So I created a view that will

render out the wish list and to
add items to the wish list - using ajax

Those two tasks are carried out by the same view. Here's how I did it,
views.py
@login_required(login_url='/login')
def wishlist(request):

    wishes = Wishlist.objects.filter(customer=request.user.customer).prefetch_related(
        Prefetch('product',
                 queryset=Product.objects.prefetch_related(
                     Prefetch(
                         'productimage_set',
                         ProductImage.objects.filter(place='Main Product Image'),
                         to_attr='main_image'
                        ),
                 ),
                 to_attr='wished_dish'
        ),
    )

    # delete wished dish
    if request.method == 'POST':
        dish_to_delete = request.POST.getlist('delete_items')
        print(dish_to_delete)

        Wishlist.objects.filter(pk__in=dish_to_delete).delete()

# question is related to below statements

    if request.method == 'GET':
        try:
            dish_id = request.GET['dish_id']

            dish = Product.objects.get(id=dish_id)

            wish, created = Wishlist.objects.get_or_create(
                customer=request.user.customer,
                product=dish
            )

            if created:
                return HttpResponse('Dish {} Added to wish list!'.format(dish.name))
            else:
                return HttpResponse('Dish {} is already in your wish list!'.format(dish.name))
        except:
            pass

    context = {
        'wishes': wishes,
    }

    return render(request, 'store/wishlist.html', context)

As you can see I've used a try:... except: pass block for GET requests to separate the adding functionality and viewing functionality.
It works fine but is this the optimal way to achieve the intended goal?


texts: Loop through array while creating one div.row and appending three div.col-lg-4

texts:
As a newbie to Javascript (or coding for that matter), I'm sure I overdid this, but I couldn't get anything else to work.  Here's what I'm doing:

allData in createDiv has anywhere from 20-500 elements ["string", "string",...] (created elsewhere)
I need it to create a div.row (I'm using bootstrap) and send to DOM
Append three elements from allData to that created div.row in DOM
Then repeat that cycle for allData.length

I couldn't figure out any other way to add one row and append three elements from the array to it.

createRow: function(number) {
    var parentDiv = document.getElementById("displayQuoteHere");
    var createRow = document.createElement("div");
        createRow.className = "row row-border";
        createRow.id = number;

    parentDiv.appendChild(createRow);
},
createDiv: function() {
    debugger;
    var allData = this.finalDellEqArray(); // allData = [100 or so elements]
    var incr = 0; // use this to go through my if else statements
    var parentRow = ''; // blank until first iteration - will be assigned according to [i]
    for (var i = 0; i < allData.length; i++) {
        if (incr === 0) {
            this.createRow(i); // run my createRow function and assign it an id (i) to use later in appendChild
            parentRow = document.getElementById(i);
            var createDiv = document.createElement("div");
                createDiv.className = "col-lg-4 text-center";  // using bootstrap to create three columns
                createDiv.innerHTML = allData[i]; // assign innerHTML to each element in array
            parentRow.appendChild(createDiv);
            incr++; // increase this to goto next else-if without creating a row
        } else if (incr === 1) {
            var createDiv2 = document.createElement("div");
                createDiv2.className = "col-lg-4 text-center"; //dito
                createDiv2.innerHTML = allData[i];
            parentRow.appendChild(createDiv2);
            incr++; // increase this to goto next else-if without creating a row
        } else {
            var createDiv3 = document.createElement("div");
                  createDiv3.className = "col-lg-4 text-center";
                createDiv3.innerHTML = allData[i];
            parentRow.appendChild(createDiv3);
            incr = 0; // set incr back to zero so it will start again and create a row.
        }
    }
},

I don't want to use any libraries as I'm trying to learn Javascript.  Suggestions or tips to make this better would be much appreciated!


texts:
I have been testing a number of kernel builds and I decide to have a go at writing some Python code. The idea is to select which kernel to boot on the next reboot. I could have done it in Bash but fancied a new experience, hence I had a go at Python.
I've been testing under bash under Linux(Debian)
Would love some feedback:
Summary:

Read the /boot/grub/grub.cfg file
Extract the kernel names
Present a simple menu
Select the kernel
Exit, printing the grub-reboot command (not executed)

#!/usr/bin/env python
#
# Read a grub.cfg file and parse the entries
import re
from simple_term_menu import TerminalMenu

# Get current kernels from grub.cfg in correct format
def get_kernels(menu_items):
    majorcount=0
    mincount=0
    with open('/boot/grub/grub.cfg',mode='r') as file:
        for line in file:
            # Check if line will contains either the string 'menu' or 'submenu'
            if re.match(r'^menu',line) or re.match(r'^submenu',line):
                try:
                    # Find the menu string between single quotes
                    entry = re.search('\'(.+?)\'', line).group(1)
                    menu_items.append('{} - {}'.format(majorcount,entry))
                    majorcount += 1

                except:
                    continue
            # Check to see if the line begins with <TAB>menu if so looks like a submenu entry
            elif re.match(r'\tmenu',line):
                entry = re.search('\'(.+?)\'', line).group(1)
                menu_items.append('{}>{} - {}'.format(majorcount,mincount,entry))
                mincount +=1
        #
        # Before we return add an Exit to the end of the menu
        majorcount += 1
        menu_items.append('{} - Exit'.format(majorcount))

        return
#########
#
# Print a simple Menu on the screen
def print_menu(menu_items):
    cli_menu_title=' Grub Kernel Selection \n'
    cli_menu=TerminalMenu(menu_items,title=cli_menu_title,clear_screen=True,
                          clear_menu_on_exit=False)
    menu_index=cli_menu.show()

    return menu_index
#########
def main():

    menu_items=[]
    get_kernels(menu_items)
    index=print_menu(menu_items)
    #
    # Now extract the string to pass to 'grub-reboot'. If 'Exit' choosen then just end
    # As 'Exit' will be the last entry if the index == the length of menu_items then assume 'Exit'
    # NB index starts at zero so will never match the length of menu_items, so increment it first
    if (index + 1) != len(menu_items):
        print(' grub-reboot {}'.format(re.match("(.*?) ",menu_items[index]).group()))
    else:
        print('Exiting not kernel selected..')
#########
if __name__ == '__main__':
    main()


texts: Decide if 4 lengths form a square, rectangle or neither

texts:
I have a list of lists of 4 integers, each representing the length of one side of a tetragon in clockwise order (so each number is the length of the side of the right-hand-adjacent-side of the previous one). Integers can be negative or positive or 0.

My idea is that if any of the sides are less than or equal to 0 then it's not a valid tetragon. Then if the lengths of all the sides are equal then it can form a square. Then if lengths of opposing sides are equal then it can form a rectangle, otherwise it's neither.

tgons=[[1,1,1,1],[1,2,1,2],[1,2,3,4],[-1,-2,-1,-2],[1,0,1,0]]
squares=0
rects = 0
neithers = 0
for gon in tgons:
    if any(n <= 0 for n in gon): #if any integers <= 0, it's invalid
        neithers+=1
    elif len(set(gon)) == 1: #if all integers are equal, it's a square
        squares+=1
    elif gon[0] == gon[2] and gon[1] == gon[3]: #if both pairs of opposing sides have equal length, it's a rectangle
        rects+=1
    else:
        neithers+=1
print squares,rects,neithers

This code apparently fails one out of a few test cases (on a certain website). I've thrown all the test cases I could think of at it and I've not been able to get it to fail so far. Is there really a test case that it fails?


texts: Logic Gate Simulator - Proper Encapsulation

texts:
So I was checking out the courses on InteractivePython, and I came across this example to demonstrate inheritance.

My focus is on the Connector class and how it interacts with BinaryGate and UnaryGate via the setNextPin method.

class LogicGate:

    def __init__(self,n):
        self.name = n
        self.output = None

    def getName(self):
        return self.name

    def getOutput(self):
        self.output = self.performGateLogic()
        return self.output

class BinaryGate(LogicGate):

    def __init__(self,n):
        LogicGate.__init__(self,n)

        self.pinA = None
        self.pinB = None

    def getPinA(self):
        if self.pinA == None:
            return int(input("Enter Pin A input for gate "+self.getName()+"-->"))
        else:
            return self.pinA.getFrom().getOutput()

    def getPinB(self):
        if self.pinB == None:
            return int(input("Enter Pin B input for gate "+self.getName()+"-->"))
        else:
            return self.pinB.getFrom().getOutput()

    def setNextPin(self,source):
        if self.pinA == None:
            self.pinA = source
        else:
            if self.pinB == None:
                self.pinB = source
            else:
                print("Cannot Connect: NO EMPTY PINS on this gate")

class AndGate(BinaryGate):

    def __init__(self,n):
        BinaryGate.__init__(self,n)

    def performGateLogic(self):

        a = self.getPinA()
        b = self.getPinB()
        if a==1 and b==1:
            return 1
        else:
            return 0

class OrGate(BinaryGate):

    def __init__(self,n):
        BinaryGate.__init__(self,n)

    def performGateLogic(self):

        a = self.getPinA()
        b = self.getPinB()
        if a ==1 or b==1:
            return 1
        else:
            return 0

class UnaryGate(LogicGate):

    def __init__(self,n):
        LogicGate.__init__(self,n)

        self.pin = None

    def getPin(self):
        if self.pin == None:
            return int(input("Enter Pin input for gate "+self.getName()+"-->"))
        else:
            return self.pin.getFrom().getOutput()

    def setNextPin(self,source):
        if self.pin == None:
            self.pin = source
        else:
            print("Cannot Connect: NO EMPTY PINS on this gate")

class NotGate(UnaryGate):

    def __init__(self,n):
        UnaryGate.__init__(self,n)

    def performGateLogic(self):
        if self.getPin():
            return 0
        else:
            return 1

class Connector:

    def __init__(self, fgate, tgate):
        self.fromgate = fgate
        self.togate = tgate

        tgate.setNextPin(self)

    def getFrom(self):
        return self.fromgate

    def getTo(self):
        return self.togate

def main():
   g1 = AndGate("G1")
   g2 = AndGate("G2")
   g3 = OrGate("G3")
   g4 = NotGate("G4")
   c1 = Connector(g1,g3)
   c2 = Connector(g2,g3)
   c3 = Connector(g3,g4)
   print(g4.getOutput())

main()

And so the output might look like this:

Input Pin A for gate G1 --> 0
Input Pin B for gate G1 --> 0
Input Pin A for gate G2 --> 1
Input Pin B for gate G2 --> 0
1

So everything is working as intended, but my concern is the "two-way access" between, for example, BinaryGate and Connector.

It's bothering me that BinaryGate.getPinA can call (Connector).getFrom().getOutput() in the line return self.pinA.getFrom().getOutput(), while Connector.__init__() calls BinaryGate.setNextPin

In my mind, there should only be one direction of "visibility" between the two objects - either a *Gate can access members of a Connector, or vice-versa, but not both ways at once. Is this a flawed assumption?

Does the code as-is break encapsulation? If so, how can the code be refactored to have proper encapsulation? If not, why not?

Edit:

Just to be clear for future viewers, this is not my code, it's from InteractivePython's Data Structures course.


texts: lodash get method equivalent in javascript

texts:
I wanted to build similar to lodash get method. Where you put the object and key name to get value if exist. I have done this but just wanted to have more better approach. Here is what has been done so bar.

var x = {
  d: 'new vale',
  a: {
    b: {
      c: {
        e: 'value'
      }
    }
  }

}

function getVal(obj, key) {
  var keys = obj[key];
  if (!keys) {
    for (var i in obj) {
      if (Object.prototype.toString.call(obj[i]) === '[object Object]') {
        return getVal(obj[i], key)
      }

    }
  } else {
    return obj[key]
  }

}

console.log(getVal(x, 'c'))


texts:
Does this snippet take too much memory? How can I let the connection opened with the function connectTo outside the forever loop?

import Control.Concurrent
import Network
import System.IO
import Control.Monad
import System.Environment

main = do
    [host,port]<-getArgs
    let pn1 = fromIntegral ( read port::Int)
    forever $ do
        h <- connectTo host $ PortNumber pn1
        hSetBuffering h NoBuffering
        getLine >>= hPutStrLn h
        forkIO $ hGetContents h >>= putStrL

If I put the line forever ... after the line hSetBuffering, the connection is lost after one input.

It seems to me that this code open too much connection.


texts:
In my library Transfuse I use a code generator to build a handful of classes that look up resources.  Each of these look up classes are proxied by a static utility class so they may be referenced before the generated class is built.  For instance, the Parcels class can be used to wrap an object with a generated Parcelable class:

ExampleParcel parcel = new ExampleParcel();
Parcelable parcelable = Parcels.wrap(parcel);
// ... load into bundle as extra, etc

Parcels proxies a generated class called Transfuse$Parcels.

Parcels:

public final class Parcels {

    public static final String PARCELS_NAME = "Parcels";
    public static final String PARCELS_REPOSITORY_NAME = "Transfuse$Parcels";
    public static final String PARCELS_PACKAGE = "org.androidtransfuse";

    private static ParcelRepository instance;

    static{
        try{
            Class injectorClass = Class.forName(PARCELS_PACKAGE + "." + PARCELS_REPOSITORY_NAME);
            instance = (ParcelRepository) injectorClass.newInstance();
        } catch (ClassNotFoundException e) {
            instance = null;
        } catch (InstantiationException e) {
            throw new TransfuseRuntimeException("Unable to instantiate generated ParcelRepository", e);
        } catch (IllegalAccessException e) {
            throw new TransfuseRuntimeException("Unable to access generated ParcelRepository", e);
        }
    }

    private Parcels(){
        // private utility class constructor
    }

    public static Parcelable wrap(Object input) {
        if(instance == null){
            throw new TransfuseRuntimeException("Unable to find " + PARCELS_REPOSITORY_NAME + " class");
        }
        return instance.wrap(input);
    }
}

Transfuse$Parcels:

@Generated(value = "org.androidtransfuse.TransfuseAnnotationProcessor", date = "01/12/2013 16:56:02 MST")
public class Transfuse$Parcels
    implements ParcelRepository
{

    private final Map<Class, ParcelableFactory> parcelWrappers = new HashMap<Class, ParcelableFactory>();

    public Transfuse$Parcels() {
        parcelWrappers.put(...);
    }

    @Override
    public Parcelable wrap(Object input) {
        return parcelWrappers.get(input.getClass()).buildParcelable(input);
    }
    // Define ParcelableFactory classes...
}

Is this technique of loading the generated class using the static initialization block optimal?  As you can see, if the class is not found (not generated possibly) then the ParcelRepository instance ends up being null and wrap() would always return null.  Should wrap() throw a runtime exception if an instance is not found instead?

If you take a look at the library, the code above is a simplification for example purposes: Parcels


texts:
Obviously, everyone should use a password manager to generate and store long unique random strings of characters for the vast majority of their passwords. However, one still needs to memorize a master password for their password vault! I figured that I would write my own little script to generate such a password, XKCD style:

(require '(clojure [string :as str])
         '(clojure.java [io :as io]))

(import (java.security SecureRandom)
        (java.util ArrayList
                   Collections))

(defn secure-shuffle [coll]
  (let [al (ArrayList. coll)]
    (Collections/shuffle al (SecureRandom.))
    (vec al)))

(defn lines [x]
  (with-open [rdr (io/reader x)]
    (doall (line-seq rdr))))

(defn password [n words]
  (str/join \space (take n (secure-shuffle words))))

(def filename "words.txt")

(def url "https://github.com/dwyl/english-words/raw/master/words.txt")

(if-not (.exists (io/file filename))
  (spit filename (slurp url)))

(println (password 4 (lines filename)))

Any comments on code style are very much appreciated, but I am more interested in the security of this script. To be specific, if I run this using lein-exec 0.3.6 on an Ubuntu 15.10 machine with Java 8u74 and Leiningen 2.6.1 installed, can I be confident that the resulting password has \$4 \log_2 354986 \approx 74\$ bits of entropy and is safe to use as my master password?


texts:
Project Euler #2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here is my solution:
public class EvenFibonacciFinder {

    private static final double PHI = 1.618033989;
    private static final double _PHI = -(PHI - 1);
    private static final double SQRT_5 = Math.sqrt(5);
    private static final int MAX_NUM = 4_000_000;

    public static void main(String[] args) {
        long time = System.nanoTime();
        double max = MAX_NUM * SQRT_5;
        long sum = 0;
        for (int i = 3, result = (int) Math.round(2 * SQRT_5); result < max; result = (int) Math.round(Math.pow(PHI, i += 3) - Math.pow(_PHI, i))) {
            sum += result;
        }
        sum = Math.round(sum / SQRT_5);
        System.out.println("Result: " + sum + "\nTime used for calculation in nanoseconds: " + (System.nanoTime() - time));
    }

}

Output:

 Result: 4613732
 Time used for calculation in nanoseconds: 60243

Questions:

Is this the most efficient way of doing it?
Is there any "bad code" in the short solution?


texts:
My code takes a string and replaces all characters which are not:

English letters
Numbers
, / -

I have tested it and it seems to generally work well enough. But it may have some catastrophic bug in it and/or can be simplified.

x <- "dog/John is a cutting-edge pilot^¢„þ"
gsub("[^a-zA-Z0-9,-:space:]+", " ", x, perl = TRUE)
"dog/John is a cutting-edge pilot "


texts:
The ConcurrentHashQueue data structure is a FIFO queue that at the same time allows look-ups of items based on a key in O(1) like a dictionary. It can be used as a cache when the number of cached items is a constant and the eviction strategy is FIFO. This makes sense when the cost of computing/creating an evicted item is not so high to justify the book-keeping costs of a LRU cache.

This implementation is also intended to be thread-safe.

internal class ConcurrentHashQueue<TKey, TValue>
{
    private readonly object _syncRoot = new object();
    private readonly int _capacity;
    private readonly Dictionary<TKey, TValue> _map;
    private readonly Queue<TKey> _queue;

    public ConcurrentHashQueue(int capacity)
    {
        _capacity = capacity;
        _map = new Dictionary<TKey, TValue>(capacity);
        _queue = new Queue<TKey>(capacity);
    }

    public TValue GetOrAdd(TKey key, Func<TValue> createValue)
    {
        TValue value;
        // first try to get the value without locking
        // ReSharper disable once InconsistentlySynchronizedField
        if (_map.TryGetValue(key, out value))
        {
            return value;
        }

        // the value needs to be created and added
        lock (_syncRoot)
        {
            // recheck existence within critical section to avoid racing conditions
            if (_map.TryGetValue(key, out value))
            {
                return value;
            }
            value = createValue();
            Add(key, value);
        }
        return value;
    }

    private void Add(TKey key, TValue value)
    {
        if (_map.Count == _capacity) // capacity reached
        {
            RemoveFirst();
        }
        _map.Add(key, value);
        _queue.Enqueue(key);
        Debug.Assert(_map.Count == _queue.Count, "The count of the queue should always equal to the count of the map.");
        Debug.Assert(_map.Count <= _capacity, "The count of items should never exceed the capacity.");
    }

    private void RemoveFirst()
    {
        TKey first = _queue.Dequeue();
        _map.Remove(first);
    }
}


texts:
I'm writing some crypto code, and as part of it, we have to implement modular exponentiation.
I have it working, both with the right-to-left binary method and with the Montgomery formula.

While they both work, the Montgomery calculations take three times longer than the right-to-left binary method. This is extremely frustrating, as I worked out the right-to-left in an afternoon, but it's taken me three days solid work to figure out the Montgomery. I thought it would be faster, so I'm guessing it's my implementation - three different function calls are used to work it out.

Here is the code, if anyone can see anything that would speed it up I'd be delighted to hear it.

First I needed a function to get the values for Extended Euclid -

private static BigInteger[] extendedEuclid(BigInteger p, BigInteger q) {

if(q.compareTo(BigInteger.ZERO) == 0)
    return new BigInteger[] {p, BigInteger.ONE, BigInteger.ZERO};

BigInteger[] vals = extendedEuclid(q, p.mod(q));
BigInteger d = vals[0];
BigInteger a = vals[2];
BigInteger divBit = p.divide(q);
BigInteger mulBut = divBit.multiply(vals[2]);
BigInteger b = vals[1].subtract(mulBut);
return new BigInteger[] {d, a, b};
}

This works but calculates value I never need - all I use is values[1] but to get it I need to calculate the others, I think?

Next we have the helper function monPro :

private static BigInteger monPro(BigInteger aBar, BigInteger bBar, BigInteger r, BigIntegernPrime, BigInteger n) {

    BigInteger t = aBar.multiply(bBar);
    BigInteger m = (t.multiply(nPrime)).mod(r);
    BigInteger u = (m.multiply(n).add(t)).divide(r);

    if(u.compareTo(n) >= 0)
        return u.subtract(n);
    else return u;
}

This is needed to use the final function, modExp -

private static BigInteger modExp(BigInteger M, BigInteger e, final BigInteger n) {
BigInteger r = new BigInteger("2").pow(n.bitLength());
BigInteger[] values = extendedEuclid(r, n);
BigInteger rInverse = values[1].mod(n);
BigInteger mBar = M.multiply(r).mod(n);
BigInteger xBar = new BigInteger("1").multiply(r).mod(n);
BigInteger nPrime = n.negate().modInverse(r);

for(int i = e.bitLength() -1 ; i >= 0 ; i--) {
    xBar = monPro(xBar, xBar, r, nPrime, n);
    if (e.testBit(i) == true)
        xBar = monPro(mBar, xBar, r, nPrime, n);
    }
    BigInteger returnValue = monPro(xBar, BigInteger.ONE, r, nPrime, n);
    return returnValue;
    }
}

I'm almost certain the running time is due to the amount of time the actual modExp functon calls monPro. Euclid is only called once so I can't see that being the huge deal, I could be wrong. Anyway, any tips or pointers much appreciated, this has turned out to be an extremely frustrating exercise (optimize for three days and slow it down by a factor of three....booooooo!)

PS - I'm not allowed use the BigInteger function modPow.


texts: Improving response time of flask endpoint

texts:
The flask endpoint is supposed to take a table name as a parameter, and then return the entire contents of the table as JSON. The table has 200,000 rows and I was wondering if there is any way to improve the response time which is currently about 7 seconds.
@app.route('/tableToJson')
def retrieve_dataset():
    '''
    Accepts a table name as a parameter and returns the output of the table as JSON
    '''
    table_name = request.args.get('table', type = str)
    if not table_name:
        content = {'success':False,'message':'A table name must be provided','status':400}
        return make_response(jsonify(content), 400)
    db = PGConnect()
    result = db.query_table(table_name)
    content = {'success':False,'data':result,'status':200}
    return make_response(jsonify(content), 200)

The function querying the table looks like this:
def query_table(self, table_name):
    query = f'''SELECT jsonb_agg(to_jsonb(t))
                FROM (
                SELECT *
                from {table_name}
                ) t'''
    self.cursor.execute(query)
    return self.cursor.fetchall()


texts: Bash script to create directories and files with a numbered prefix

texts:
I wrote a pretty simple bash script. It takes a directory with subdirectories with incremental prefixes in their names (01test, 02test, 03test), creates a new directory with the next highest prefix and creates a couple of files and fills them with some default text.

I'd like to do this in fewer lines of code and eliminate redundancies.

#!/bin/bash

LAST=`exec ls example_dir | sed 's/\([0-9]\+\).*/\1/g' | sort -n | tail -1`
PREFIX="${LAST:0:2}"
PREFIX=$((PREFIX + 1))
PREFIX="$PREFIX"_
ARGS=$@
TESTNAME="${ARGS// /_}"
DIRNAME="example_dir/$PREFIX$TESTNAME"

mkdir $DIRNAME
mkdir $DIRNAME/some_directory
mkdir $DIRNAME/expected

touch $DIRNAME/first.txt
touch $DIRNAME/second.txt
touch $DIRNAME/third.json

echo "{" >> $DIRNAME/test.json
echo -e "\t\"enabled\": true" >> $DIRNAME/test.json
echo "}" >> $DIRNAME/test.json

echo "{" >> $DIRNAME/some_directory/$PREFIX.json
echo -e "  \"entities\": [" >> $DIRNAME/some_directory/$PREFIX.json
echo "  ]" >> $DIRNAME/some_directory/$PREFIX.json
echo "}" >> $DIRNAME/some_directory/$PREFIX.json


texts:
I am creating my models manually. I have five tables in my database as follows:

Members
MemberTypeMasters
Payments
Relationships
StatusMasters

My database looks like this:

So far I have 6 files containing auto-implemented properties as below:

Models
 |-- DBCS.cs
 |-- Member.cs
 |-- MemberTypeMaster.cs
 |-- Payment.cs
 |-- Relationship.cs
 |-- StatusMaster.cs

DBCS.cs

using System;
using System.Data.Entity;

namespace Munim_File_Sharing.Models
{
    public class DBCS : DbContext
    {
        public DbSet<Member> Members { get; set; }
        public DbSet<MemberTypeMaster> MemberTypeMasters { get; set; }
        public DbSet<Payment> Payments { get; set; }
        public DbSet<Relationship> RelationShips { get; set; }
        public DbSet<StatusMaster> StatusMasters { get; set; }
    }
}

Member.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Munim_File_Sharing.Models
{
    public class Member
    {
        [Key]
        public int MemberID { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string MobileNo { get; set; }
        public string FileName { get; set; }
        public Nullable<DateTime> MemberSince { get; set; }
        public int MemberTypeID { get; set; }

        public virtual MemberTypeMaster MemberTypeMaster { get; set; }
        public virtual ICollection<Payment> Payments { get; set; }
        public virtual ICollection<Relationship> RelationshipSenders { get; set; }
        public virtual ICollection<Relationship> RelationshipReceivers { get; set; }
    }
}

MemberTypeMaster.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Munim_File_Sharing.Models
{
    public class MemberTypeMaster
    {
        [Key]
        public int MemberTypeID { get; set; }
        public string MemberType { get; set; }

        public ICollection<Member> Members { get; set; }
    }
}

Payment.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Munim_File_Sharing.Models
{
    public class Payment
    {
        [Key]
        public int PaymentID { get; set; }
        public decimal Amount { get; set; }
        public DateTime DateOfReceipt { get; set; }
        public int MemberID { get; set; }

        public virtual Member Member { get; set; }
    }

}

Relationship.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Munim_File_Sharing.Models
{
    public class Relationship
    {
        [Key]
        public int RelationshipID { get; set; }
        public int RequestSenderID { get; set; }
        public int RequestReceiverID { get; set; }
        public int StatusID { get; set; }

        public virtual Member RequestSender { get; set; }
        public virtual Member RequestReciever { get; set; }
        public virtual StatusMaster Status { get; set; }
    }
}

StatusMaster.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Munim_File_Sharing.Models
{
    public class StatusMaster
    {
        [Key]
        public int StatusID { get; set; }
        public string Status { get; set; }

        public virtual ICollection<Relationship> Relationships { get; set; }
    }
}

connectionString in web.Config:

<connectionStrings>
    <add name="DBCS" connectionString="server=.; database=FileSharingDB; Integrated Security = SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>

Is there any problem in my above classes? Am I forgetting anything in Models?


texts:
I have an api endpoint that, when called, initiates the generation of a report. This is time consuming process and response could come pretty late. So, we came up with caching architecture and once finished the response is saved to redis.
However, on the frontend side we dicided to make a request once in a while, until it is ready. To face the issue of overlapping queries when one report is initialized several times in a row, I decided to make a temporary file, that exists only when the report is being generated, and the api response is "This report is already being generated". Once the generation is finished, file is deleted and response is already cached.
This is mockup of what I am doing
def post(self):
   serialized_data = self.serializer().deserialize({
            'task': json.loads(request.values.get('task')),
            'media_company': json.loads(request.values.get('mediaCompany'))
    })

   if not os.path.exists('/root/progress_data'):
        os.mkdir('/root/progress_data')

    self.build_range(serialized_data)

    serialized_data['media_company']['date_from'] = \
                                        self.date_from.strftime("%Y-%m-%d")
    serialized_data['media_company']['date_to'] = \
                                        self.date_to.strftime("%Y-%m-%d")
    progress_hash = hashlib.sha256(str(serialized_data).encode()).hexdigest()

    if self.progress_check(progress_hash):
        return json_response({
            "success": False,
            'result': "This report is already being generated",
        })

    file = open(f'/root/progress_data/{progress_hash}', 'w+')
    file.close()
    try:
        report = self.generate_report(serialized_data)
    except:
        os.remove(f'/root/progress_data/{progress_hash}')
        return json_response({
            "success": False,
            'result': "Error while generating report",
        })
    os.remove(f'/root/progress_data/{progress_hash}')
    return json_response({
        "success": True,
        'data': report,
    })

I think that this is not really production-ready solution, but I could not come up with something better.
Also, there are some holes where the file is not being deleted in all cases.
Could you show me potential holes and may be another way of checking the progress


texts: Code which pulls from SQL and dumps in Excel

texts:
I have a working code that pulls data from SQL and dumps in a column. Unfortunately it is extremely slow as it takes around half a second to pull each data point and it needs to be much faster. Are there any ways I can make this more efficient? Is there a different way to do this rather than go row by row?

Sub PopulatePreviousPrice()
Dim mydata As New SQLConnection
Dim sql As String

Call Input_SQLAdd_and_DatabaseName
Dim Duplicate As Long
Duplicate = -2147217900
Dim NoPrice As Integer
NoPrice = 3021
#Error code for SQL error
On Error GoTo Errorhandler

Dim tbl As ListObject
Dim PriceDate As Date
Dim PriceDateText As String
Dim sqlVal
Dim j As Integer

Set tbl = ActiveSheet.ListObjects("DailyTable")

j = 1

PriceDate = tbl.DataBodyRange(1, 25)
PriceDateText = CStr(Format(PriceDate, "dd/mmm/yyyy hh:mm:ss"))

For j = 1917 To 1 Step -1

PriceDate = tbl.DataBodyRange(j, 25)
PriceDateText = CStr(Format(PriceDate, "dd/mmm/yyyy hh:mm:ss"))

sql = "SELECT ClosingPrice " & _
  " FROM ZIPTrading.instrument.DailyPriceBondPref" & _
  " WHERE PriceDate = (SELECT max(PriceDate) From ZIPTrading.instrument.DailyPriceBondPref WHERE PriceDate < '" & PriceDateText & "' AND FIGI = '" & tbl.DataBodyRange(j, 1) & "')" & _
  " AND FIGI = '" & tbl.DataBodyRange(j, 1) & "';"

sqlVal = mydata.SelectResult(sql)

    If IsNull(sqlVal(0, 0)) = False Then

        tbl.DataBodyRange(j, 20) = sqlVal(0, 0)

    Else

    End If
sqlVal(0, 0) = ""

Next j

MsgBox ("All previous prices in table")

Errorhandler:
                If Err = Duplicate Then
                MsgBox ("Error! Data for this date already exists in the data base or data entry error. Check date and BBG pulled values")
                ElseIf Err = NoPrice Then
                    Resume Next
                    'Some securities have no price data at all and this ends the macro without warning. It's dealt with here
                Else
                msg = "Error # " & Str(Err.Number) & " was generated by " _
                & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
                MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext

                End If

End Sub


texts: Filter children component via input component

texts:
I'm trying to break down the individual functionality of a advanced table UI into different react components (right now all table components are really heavy).

I came up with this way of exposing properties of a component to the parent component which allows components to talk to each other. It's quite messy and I'm looking for better ways of achieving this.

Here's the working demo.

function filter (value, caseSensitive, children) {
  return main.recursion (children, function (children, recursion, wrapper) {
    return _.filter(children, wrapper(function (child) {
      if (typeof child.props.children !== 'string') {
        var result = recursion(child.props.children)
        return Boolean(result.length)
      } else {
        var flag = (caseSensitive) ? '' : 'i'
        var pattern = new RegExp(value, flag)
        return (child.props.children.match(pattern))
      }
    }))
  })
}

var FilterChildren = React.createClass({
  displayName: 'FilterChildren',
  propTypes: {
    children: React.PropTypes.node,
    provideFilter: React.PropTypes.func,
    provideFilterChildren: React.PropTypes.func,
    onFilter: React.PropTypes.func,
    caseSensitive: React.PropTypes.bool,
    selector: React.PropTypes.string
  },
  getInitialState: function () {
    return {
      children: this.props.children
    }
  },
  componentWillMount: function () {
    if (this.props.provideFilter) this.props.provideFilter(this.filter)
    if (this.props.provideFilterChildren) this.props.provideFilterChildren(this.filterChildren)

  },
  filterChildren: function (children) {
    this.children = children
  },
  filter: function (value) {
    this.props.onFilter(filter(value, this.props.caseSensitive, this.children))
  },
  render: function () {
    return this.state.children
  }
})

var StatefulChildren = React.createClass({
  displayName: 'StatefulChildren',
  propTypes: {
    children: React.PropTypes.node,
    provide: React.PropTypes.func,
    supply: React.PropTypes.func,
    element: React.PropTypes.string
  },
  getInitialState: function () {
    return {
      children: this.props.children
    }
  },
  componentWillMount: function () {
    if (this.props.provide) this.props.provide(this.setChildren)
    if (this.props.supply) this.props.supply(this.props.children)
  },
  setChildren: function (children) {
    this.setState({
      children: children
    })
  },
  render: function () {
    return React.createElement(
      this.props.element,
      null,
      this.state.children
    )
  }
})

var Page = React.createClass({
  invokeFilter: function (event) {
    return this.filter(event.target.value)
  },
  handleFilter: function (nodes) {
    this.setTbodyChildren(nodes)
  },
  provideFilter: function (filter) {
    this.filter = filter
  },
  provideFilterChildren: function (filterChildren) {
    this.filterChildren = filterChildren
  },
  provideSetTbodyChildren: function (setTbodyChildren) {
    this.setTbodyChildren = setTbodyChildren
  },
  supplyTbodyChildren: function (tbodyChildren) {
    this.filterChildren(tbodyChildren)
  },
  render: function () {
    return (

        <input type='text' onChange={this.invokeFilter}></input>

          <FilterChildren provideFilter={this.provideFilter} provideFilterChildren={this.provideFilterChildren} onFilter={this.handleFilter}>
            <StatefulChildren element='tbody' provide={this.provideSetTbodyChildren} supply={this.supplyTbodyChildren}>

                French Fries
                Mimes
                Discotech

                Bread
                Coffee
                Wine

            </StatefulChildren>
          </FilterChildren>

    )
  }
})

React.render(<Page/>, document.body)


texts:
I am setting a few vars in JavaScript. I typically like to make my code really readable so that it's easy to go back and edit.  I have a few questions about the code below:

1) Is this is a good way to break up the setting of the vars?  The comment seems redundant, but it seems to really help break up the code into relevant chunks.

2) When I set a var like this ~~ $IPPWrapper = $("div.iqPaginItemsPerPageWrapper") ~~ I always include the HTML element, in this case the "div".  Is this overkill? Is there a performance hit or benefit? I know in the CSS best practices, it's frowned upon.

3) I need to create an array, but I don't know the best type to use. Basically, I am just storing messages that I will use later in popups.  Is there a more common or better way to create this array?

Thanks in advance for any advice or helpful comments.

// GENERAL VARS
var UpRate = 250,
    DownRate = UpRate,
    OpenHeight = "25px";

// SET IPP VARS
var $IPPWrapper = $("div.iqPaginItemsPerPageWrapper"),
    $IPPDefault = $IPPWrapper.children("div.iqPaginDefault"),
    $IPPNonDefault = $IPPWrapper.children("div.iqPaginNonDefault"),
    $IPPOptions = $IPPWrapper.children("div.ItemsPerPage"),
    $IPPValue = $("span#ItemsPerPageValue");

// SET SB VARS
var $SBWrapper = $("div.iqPaginSortByWrapper"),
    $SBDefault = $SBWrapper.children("div.iqPaginDefault"),
    $SBNonDefault = $SBWrapper.children("div.iqPaginNonDefault"),
    $SBOptions = $SBWrapper.children("div.SortBy"),
    $SBValue = $("span#SortByValue");

// CREATE SB TEXT ARRAY
var SBTextArray = new Array();
    SBTextArray[1] = "Company Name A - Z";
    SBTextArray[2] = "Company Name Z - A";
    SBTextArray[3] = "Product Name A - Z";
    SBTextArray[4] = "Product Name Z - A";
    SBTextArray[5] = "Model Number A - Z";
    SBTextArray[6] = "Model Number Z - A";

EDIT ~~ Is this a better way of coding the above array?

// CREATE SB TEXT ARRAY
var SBTextArray = [
        "Company Name A - Z", "Company Name Z - A",
        "Product Name A - Z", "Product Name Z - A",
        "Model Number A - Z", "Model Number Z - A",
    ];


texts:
Question statement:

  A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2   =   0.5
1/3   =   0.(3)
1/4   =   0.25
1/5   =   0.2
1/6   =   0.1(6)
1/7   =   0.(142857)
1/8   =   0.125
1/9   =   0.(1)
1/10  =   0.1

  Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

  Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

Link: https://projecteuler.net/problem=26

I tried to solve it in Python:

My approach:

For every d, assume you are solving for 1 / d by hand.
In case the 1 is completely divisible by d, it means the cycle length is 0.
If a value you have already divided appears again, it means you've found the cycle.
The cycle would have length of the number of times you've repeated the first step minus the first time the cycled value appears as we have to remove non-cycling values.

Here's my code following the above steps in Python:

LIMIT = 1000

# The maximum length
maxi = 0

# The 'd' that has maximum length
maxi_d = 1

for d in range(1, LIMIT):
    quotient = [] # Stores the decimal quotient
    cur_value = 1 # Variable used to perform division as if by hand

    len_recur = 0 # Recurring length

    # Performing division as if by hand.
    while cur_value not in quotient:
        if not cur_value:   # If the value is not recurring:
            break           # break as the rucurring length must be 0

        len_recur += 1
        quotient.append(cur_value)

        cur_value = (cur_value % d) * 10

    if not cur_value:
        continue

    # Remove number of values that do not recur
    len_recur -= quotient.index(cur_value) + 1

    if len_recur > maxi:
        maxi = len_recur
        maxi_d = d

print(maxi_d)

I'd like to make this code as fast as possible. This currently takes ~3.5 seconds for LIMIT = 2000 and grows exponentially larger.

PS: I know len_recur can be replaced by len(quotient), but I want the code to be as fast as possible.


texts: Positioning a container next to its menu

texts:
I'm a beginner in CSS and need help with a suggestion.

I'm working on a project, in which I managed to position container_main right next to container_menu giving the remaining dimension of the screen, giving it relative position and floating it to the right. container_menu has a dimension and a fixed position specified.

body {
  font-size: 16px;
  font-family: 'Open Sans', sans-serif;
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
}

/*Contenedor de la barra de navegacion: Columna*/
.container_menu {
  height: 100%;
  width: 18rem;
  /*display: inline-block;*/
  position: fixed;
  background-color: gray;
}

/*Barra de navelación: Elemento
*/
.container_menu .menu {
  width: 100%;
  padding: 0;
}

.container_menu ul {
  list-style-type: none;
}

.container_menu .menu li a{
  color: white;
  display: block;
  padding: 1rem 1.5rem;
  background-color: gray;
}

.container_menu .menu li a:hover {
  color: white;
  background-color: black;
}

.container_main {
  height: 100%;
  width: 66.31rem;
  background-color: black;
  position: relative;
  float: right;
}

p {
  color: white;
  background-color: blue;
  width: 30rem;
  height: 20rem;
  border: .7rem solid white;;
  padding: 5rem;
  margin: 10rem;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="css/style.css" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300i,400" rel="stylesheet">
  <title>MDN - Mockup</title>

Teaching Activities

Web Literacy

Leadership Opportunities

Tools

Comunity

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
      ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
      laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
      voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
      non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
       ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
       laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
       voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
       non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
       ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
       laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
       voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
       non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

  <

I would like to know if the characteristics I gave the containers are ideal, or if there is a better way to get the same result using other properties.


texts:
I have a range of two columns that I want to search for a "key" and then find the corresponding value in the directly adjacent column. The key is stored in a dictionary that I populated earlier in the program. I then store the value with its corresponding key in the dictionary to display later.
I am using .Find to search the range for the key and then getting the value using .Offset to get the adjacent cell. The code follows:
Dim key As Variant
Dim filRange As Range
Dim found As Range

Set filRange = ws.Range("D2:E36419").SpecialCells(xlCellTypeVisible)

Dim count As Integer
Dim i As Long

For i = 0 To partsDict.count - 1
    key = partsDict.Keys(i)
    Set found = filRange.Find(key)

    If Not found Is Nothing Then
        count = found.Offset(0, 1).value
        partsDict(i) = count
    Else
        partsDict(i) = Empty
    End If

Next i

The code functions as expected and I am able to print all values later in the program. The issue is the program takes over 15 seconds to run. I've seen the .Find method is slow and feel like there is a better way to search and retrieve my values. Should I store the range in an array somehow? Use another dictionary? Thanks!


texts: Compute the XOR of all the elements in the upper left triangular of a square matrix

texts:
Given a dimension \$D\$. We generate a \$D\times D\$ matrix with elements that start from \$0\$. For example, if we're given a dimension \$4\$ this is what our matrix looks like:
$$
    \begin{bmatrix}
     0 & 1 & 2 & 3 \\
     4 & 5 & 6 & 7 \\
     8 & 9 & 10& 11\\
     12& 13& 14& 15\\
    \end{bmatrix}
$$

Now compute the XOR all of the elements in the upper triangular of the square matrix

0 ^ 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 8 ^ 9 ^ 12 gives us 10

def computeXOR(dimension):
    XOR = 0
    begin = 0
    for i in range(dimension):
        for j in range(dimension-i):
            XOR ^= begin + (j + i*dimension )
    return XOR

#computeXOR(4) returns 10

I'm trying to think of a faster algorithm to XOR all of the elements in the upper triangular of a square matrix. My current solution is \$O(n^2)\$.


texts: Summing up ints in vectors for education

texts:
To get started with C++11/14/17, I decided to write a program that brute forces the problem described in this video (and gives a progress update every few seconds):

  Divide the numbers [0, 31] into two sets A and B such that

  \$\sum_A {a} = \sum_B{b}\$
  \$\sum_A {a^2} = \sum_B{b^2}\$
  \$\sum_A {a^3} = \sum_B{b^3}\$
  \$\sum_A {a^4} = \sum_B{b^4}\$

How can I make this code more C++14-ish? My goal is not to make the code more mathematically clever, or necessarily faster. I mainly wanted to use a reasonable to high number of modern C++ standard features to brute-force-solve this problem.

#include <vector>
#include <iostream>
#include <numeric>
#include <chrono>
#include <iomanip>
#include <cstdlib>

int main() {

    uint32_t split {0};
    uint32_t print_mask { 2048 };
    auto lastPrintTime = std::chrono::system_clock::now();
    auto const SLOWER_THRESHOLD = std::chrono::seconds(5) ;
    auto const FASTER_THRESHOLD = std::chrono::seconds(10) ;

    while (split < std::numeric_limits<uint32_t>::max()) {
        if (split % print_mask == 0) {
            double progress_percentage { (split/(double)std::numeric_limits<uint32_t>::max()) * 100.0 };
            std::cout << "Currently checking " << std::setw(20) << std::setfill(' ') << split << ", " << std::fixed << progress_percentage << '%' << std::endl;

            auto now = std::chrono::system_clock::now();
            auto diff = std::chrono::duration_cast<std::chrono::seconds>(now - lastPrintTime);
            lastPrintTime = now;

            if (diff < SLOWER_THRESHOLD) print_mask *= 2;
            if (diff > FASTER_THRESHOLD && print_mask > 10) print_mask /= 2;
        }

        std::vector<int> va;
        std::vector<int> vb;

        uint32_t mask {1};
        for (int i=0; i<32; i++) {
            ((mask & split) != 0 ? va : vb).push_back(i);
            mask = mask << 1;
        }

        int sum_a;
        int sum_b;

        sum_a = std::accumulate(va.begin(), va.end(), 0, [](auto x, auto y){return x + y;});
        sum_b = std::accumulate(vb.begin(), vb.end(), 0, [](auto x, auto y){return x + y;});
        if (sum_a != sum_b) goto next;

        sum_a = std::accumulate(va.begin(), va.end(), 0, [](auto x, auto y){return x + y*y;});
        sum_b = std::accumulate(vb.begin(), vb.end(), 0, [](auto x, auto y){return x + y*y;});
        if (sum_a != sum_b) goto next;

        sum_a = std::accumulate(va.begin(), va.end(), 0, [](auto x, auto y){return x + y*y*y;});
        sum_b = std::accumulate(vb.begin(), vb.end(), 0, [](auto x, auto y){return x + y*y*y;});
        if (sum_a != sum_b) goto next;

        sum_a = std::accumulate(va.begin(), va.end(), 0, [](auto x, auto y){return x + y*y*y*y;});
        sum_b = std::accumulate(vb.begin(), vb.end(), 0, [](auto x, auto y){return x + y*y*y*y;});
        if (sum_a != sum_b) goto next;

        std::cout << "A = " << sum_a << " = [";
        for (auto v: va) {
            std::cout << v << ", ";
        }
        std::cout << ']' << std::endl << "B = " << sum_b << " = [";
        for (auto v: vb) {
            std::cout << v << ", ";
        }
        std::cout << ']' << std::endl;
        break;

        next:
        split++;
    }

    puts("Win");

    return EXIT_SUCCESS;
}

I am especially unhappy with the way I print the vectors. I have seen some code examples about ostream_iterators, but these looked even worse to me.


texts:
I'm looking to add a module to one of my utility classes that functions as a countdown timer for tools that execute tasks after a certain amount of time. The code below is what I have working for PoC, but when I went to make this and check out existing examples, none really seemed this slim/simple without going all-out on lambdas, so I'm worried that I'm doing something wrong, or at the very least very inefficiently.

The time-range expected for the tool will be from 200 milliseconds to a few hours.

using System;

namespace CountdownTimer
{
    class Program
    {
        static int Main(string[] args)
        {
            int aDelay = 2000;
            CountDown(aDelay);
            return 0;
        }

        static void CountDown(int delayInMilliseconds)
        {
            bool finishedCountdown = false;
            DateTime initialTime = DateTime.UtcNow;

            while (!finishedCountdown)
            {
                DateTime timeNow = DateTime.UtcNow;
                TimeSpan timeDifference = timeNow - initialTime;

                if (timeDifference.TotalMilliseconds >= delayInMilliseconds)
                {
                    finishedCountdown = true;
                }
            }
        }
    }
}

I also have this alternative when I was futzing around with async, which I'm kind of new to in C#

using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace CountdownTimer
{
    class Program
    {
        static int Main(string[] args)
        {
            var result = CountDownTimer(5000);
            Console.ReadKey(true);

            return 0;
        }

        async static Task CountDownTimer(int delay)
        {
            Task myDelay = AsyncDelay(delay);
            await myDelay;
        }

        async static Task AsyncDelay(int delay)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(delay));
            Console.WriteLine("Done");
        }
    }
}

I think they're both pretty easy to understand, but my uncertainty with C#'s async for the second solution and the CPU cycles being used for the first worry me...

side note: Any version of .NET is available for use


texts:
I'm solving exercise 2 from lecture 3 of Berkeley's CS 61A (2012):

  Write a function min_element that returns the minimum element in a tuple.

def min_element(tup):
    """ Returns the minimum element in tup.
    >>> a = (1, 2, 3, 2, 1)
    >>> min_element(a)
    1
    """

I know that Python has a built-in min function, but at this point in the course, the only operations on tuples that we have studied are indexing [1] [-1], slicing [1:], and concatenation +, so my solution needs to restrict itself accordingly.

My solution:

def min_element(tup):
    """ Returns the minimum element in tup.
    >>> a = (1, 2, 3, 2, 1)
    >>> min_element(a)
    1
    """
    def find_min(tup, min):
        if not tup:
           return min
        else:
           min = tup[0] if tup[0] < min else min
           return min_element(tup[1:], min)
    if tup:
        return find_min(tup[1:], tup[0])

Can this solution be improved?


texts: Calculate time difference when using time only fields

texts:
Most of the time I used datetime fields, but for this project it is a requirement to use time fields. The problem is calculations with 2 times not on the same date.

I.E.:

23:00 to 03:00 is 4 hours.

In vba I'm using the following code:

Me.TotalTime = IIf(Round(CCur(Nz(DateDiff("n", [startTime], [endTime]) / 60, 0)), 2) < 0, Round(CCur(Nz(DateDiff("n", [startTime], 1) / 60, 0)), 2) + Round(CCur(Nz(DateDiff("n", 0, [endTime]) / 60, 0)), 2), Round(CCur(Nz(DateDiff("n", [startTime], [endTime]) / 60, 0)), 2))

Is this the correct way to calculate and or is there an easier method?


texts: Modify parameter data before creating an instance of a class in PHP

texts:
I have an abstract Badge class, every class extending this class should always correctly set the incoming name (string) and achievedAt (date) fields.
There might be other classes that extend the Badge class, which will get passed different types of values in their constructor (see examples below), the most important thing is that each of these classes extending the badge class should have the correct type of value for name and achievedAt
I currently have the following structure to achieve this:
<?php

namespace App\Domain\Badge;

use Carbon\Carbon;

abstract class Badge
{
    private string $name;
    private Carbon $achievedAt;

    public function __construct(string $name, Carbon $achievedAt)
    {
        $this->name = $name;
        $this->achievedAt = $achievedAt;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getAchievedAt(): Carbon
    {
        return $this->achievedAt;
    }
}

This is the KilometerBadge, extending the abstract Badge
<?php

namespace App\Domain\Badge;

use Carbon\Carbon;

class KilometerBadge extends Badge
{
    public function __construct(int $kilometers, $activity)
    {
        $name = 'kilometer-badge-' . $kilometers;
        $achievedAt = Carbon::parse($activity['start_date']);

        parent::__construct($name, $achievedAt);
    }
}

This is the ActivityNumberBadge, which builds the name using a different parameter
<?php

namespace App\Domain\Badge;

use Carbon\Carbon;

class ActivityNumber extends Badge
{
    public function __construct(array $activities, $activity)
    {
        $name = 'kilometer-badge-' . count($activities);
        $achievedAt = Carbon::parse($activity['start_date']);

        parent::__construct($name, $achievedAt);
    }
}

I'm wondering if this is the best way to go about this? Thank you!


texts: Calling common async code from a derived method

texts:
I'm implementing a number of classes in C# that have async methods. However, each of these methods needs to implement some boilerplate code that is common to all. Therefore I've implemented the common code in an async method of a base class; the async methods on the derived classes then call this base class method.

Here's the base class, containing the method that does the common stuff (GetResultAsync).

namespace Redacted
{
    abstract class RepositoryBase : IRepository
    {
        protected RepositoryBase(IRepositoryConfiguration configuration)
        {
            Configuration = configuration;
        }

        protected IRepositoryConfiguration Configuration { get; private set; }

        protected FleetContext CreateDatabaseContext()
        {
            return new FleetContext(Configuration.DatabaseConnectionString);
        }

        protected async Task<IApiResult<TValue>> GetResultAsync<TValue>(
            IApiCallerContext context,
            Func<FleetContext, CancellationToken, Task<TValue>> getTask)
        {
            using (new SynchronizationContextChange())
            using (FleetContext db = CreateDatabaseContext())
            {
                bool isSystemOnline = await db.IsSystemOnlineAsync();
                if (!isSystemOnline)
                {
                    return ImmutableApiResult<TValue>.Offline;
                }

                bool isValidSession = await db.IsValidSessionAsync(context.Caller);
                if (!isValidSession)
                {
                    return ImmutableApiResult<TValue>.Blocked;
                }

                Task<TValue> task = getTask(db, context.CancellationToken);
                TValue value = await task;

                return ImmutableApiResult.Create<TValue>(value);
            }
        }
    }
}

Basically, I have an Entity Framework database context (FleetContext) that exists for the duration of the call. I then perform some common DB-related tasks by calling custom async methods that have been added to the context class. Depending on the result of these calls, I may exit the method early: in such cases, the IApiResult object returned by the method is different than when the method runs through to the end normally.

Here's an example of a derived class that contains a method which calls the base class:

namespace Redacted
{
    sealed class CompanyRepository : RepositoryBase, ICompanyRepository
    {
        public CompanyRepository(IRepositoryConfiguration configuration)
            : base(configuration)
        {
        }

        public Task<IApiResult<ICompanyIdentity>> GetCompanyIdentityAsync(int companyId, IApiCallerContext context)
        {
            return GetResultAsync<ICompanyIdentity>(
                context,
                async (db, cancellationToken) =>
                {
                    Company company = await db.Companies.FindAsync(cancellationToken, companyId);
                    return ImmutableCompanyIdentity.Create(company);
                }
                );
        }
    }
}

As you can see I'm using an asynchronous anonymous function to return the Task object required by the GetResultAsync method.

This all works but seems somewhat inside-out to me, in that the API method (GetCompanyIdentityAsync) passes a function to the base class, rather than the more typical approach of the derived class calling the base method as part of its normal processing.

Am I worrying unnecessarily, or are there obvious alternate ways of calling the boilerplate code from the derived classes?


texts: Abstracting getter and setter method references for testing

texts:
Is the following code easy to understand? If not how should it be changed to be more understandable. The purpose of this is reducing similar code in unit tests. This avoids repeating lines for calling getters, setters, and checking for equality.

/**
 * Example string for testing.
 */
private static final String STRING_EXAMPLE="stringExample";

/**
 * Test that a getter and setter are consistent.
 */
@Test
public void testGetterSettersForA() {
    A a = new A();
    assertGetterSetterConsistent(STRING_EXAMPLE,a::setC,a::getC);
}

/**
 * Assert that a getter and setter are consistent.
 * @param input the object to be set.
 * @param setter the setter.
 * @param getter the getter.
 */
private static <T> void assertGetterSetterConsistent(T input, Consumer<T> setter, Supplier<T> getter) {
    boolean consistent =isSetConsistentToGet(input,setter,getter);
    assertTrue("Getter and Setter should be consistent.",consistent);
}

/**
 * Check if the object being set is the same as the object being gotten.
 * @param input the object to be set.
 * @param setter the setter.
 * @param getter the getter.
 * @return whether the object being set is the same as the object being gotten.
 */
private static <T> boolean isSetConsistentToGet(T input, Consumer<T> setter, Supplier<T> getter) {
    setter.accept(input);
    T getValue = getter.get();
    return areEqual(input,getValue);
}

/**
 * Null safe check if two objects are equal.
 * @param first the first object.
 * @param second the second object.
 * @return whether the two objects are equal.
 */
private static <T> boolean areEqual(Object first, Object second) {
    if(first==null) {
        return second==null;
    }
    return first.equals(second);
}

/**
 * Class for testing a getter and setter.
 */
private static final class A{
    /**
     * Variable named c.
     */
    private String c;

    /**
     * Get c.
     * @return c.
     */
    public String getC() {
        return c;
    }

    /**
     * Set c.
     * @param c the value to be set.
     */
    public void setC(String c) {
        this.c = c;
    }
}


texts:
The following code is a computing quiz:

import random

#the questions/answer dictionary
my_dict =   {
            "Base-2 number system" : "binary",
            "Number system that uses the characters 0-F" : "hexidecimal",
            "7-bit text encoding standard" : "ascii",
            "16-bit text encoding standard" : "unicode",
            "A number that is bigger than the maximum number that can be          stored" : "overflow",
            "8 bits" : "byte",
            "1024 bytes" : "kilobyte",
            "Picture Element. The smallest component of a bitmapped image" : "pixel",
            "A continuously changing wave, such as natural sound" : "analogue",
            "the number of times per second that a wave is measured" : "sample rate",
            "A binary representation of a program" : "machine code"
        }

#welcome message
print("Computing Revision Quiz")
print("=======================")

#the quiz will end when this variable becomes 'False'
playing = True

#While the game is running
while playing == True:

    #set the score to 0
    score = 0

    #gets the number of questions the player wants to answer
    num = int(input("\nHow many questions would you like: "))

    #loop the correct number of times
    for i in range(num):

        #the question is one of the dictionary keys, picked at random
        question = (random.choice( list(my_dict.keys())))
        #the answer is the string mapped to the question key
        answer = my_dict[question]

        #print the question, along with the question number
        print("\nQuestion " + str(i+1) )
        print(question  + "?")

        #get the user's answer attempt
        guess = input("> ")

        #if their guess is the same as the answer
        if guess.lower() == answer.lower():
            #add 1 to the score and print a message
            print("Correct!")
            score += 1
        else:
            print("Nope!")

    #after the quiz, print their final score
    print("\nYour final score was " + str(score))

    #store the user's input...
    again = input("Enter any key to play again, or 'q' to quit.")

    #... and quit if they types 'q'
    if again.lower() == 'q':
        playing = False


texts: Find the most efficient combination that equals target number in ArrayList

texts:
I want to implement the following function:

  Given a target sum, return the combination that equals the target sum and is the most efficiënt combination in the array of an ArrayList.

For example:

An ArrayList with the values 9,3,4,6,4,2,1

Then it will return the best possible combination.

You can add 9 + 1, which returns stackId 6.
You can also add 4 + 6 which returns stackId 3, making this one more efficient.

BestCombo Class

import java.util.ArrayList;
import java.util.Stack;

public class BestCombo {

/** Set a value for target sum */
private  final int target;
private int sumInStack, bestStackId;

private Stack<Packet> stack;
private ArrayList<Packet> bestCombination;

public BestCombo(int arrayLength, int targetNumber) {
    this.stack =  new Stack<>();
    this.bestCombination =  new ArrayList<>();
    this.target = targetNumber;
    this.sumInStack = 0;

    // bestStackId is equal to length of data array.
    // if arrayLength is higher then 2 times the target bestStackId equals target times 2 to prevent unnecessary calculations.
    if( arrayLength > targetNumber * 2) {
        this.bestStackId = targetNumber * 2;
    } else {
        this.bestStackId = arrayLength;
    }
}

public int getBestStackId() {
    return bestStackId;
}

public ArrayList<Packet> calculateTarget(ArrayList<Packet> data, int fromIndex, int endIndex) {

    //if solution uses a lower index then the previous
    if (sumInStack == target && fromIndex < bestStackId) {
        this.bestStackId = fromIndex;
        this.bestCombination.clear();
        for (Packet p : stack) {
            bestCombination.add(p);
        }
    }

    for (int currentIndex = fromIndex; currentIndex < endIndex && currentIndex < bestStackId; currentIndex++) {
        if (sumInStack + data.get(currentIndex).getPacketHeight() <= target) {
            stack.push(data.get(currentIndex));
            sumInStack += data.get(currentIndex).getPacketHeight();

            /*
            * Make the currentIndex +1, and then use recursion to proceed
            * further.
            */
            calculateTarget(data, currentIndex + 1, endIndex);
            sumInStack -= stack.pop().getPacketHeight();
        }
    }
    return bestCombination;
}

}

Packet Class

import java.awt.*;
import java.util.ArrayList;
import java.util.Random;

public class Packet{

private int packetCapacityHeight;
private Color color;

public Packet(int packetCapacityHeight){

    /**
     * a packet contains a capacity parameter and a color which is randomly generated.
     */

    this.packetCapacityHeight = packetCapacityHeight;

    Random rand = new Random();

    int  rc = rand.nextInt(255);
    int  gc = rand.nextInt(255);
    int bc = rand.nextInt(255);

    this.color = new Color(rc, gc, bc);
}

public Color getColor() {
    return color;
}

public int getPacketHeight() {
    return packetCapacityHeight;
}

}

You would call the function with:

BestCombo bo = new BestCombo(Order.size(), 10);
bestCombination = bo.calculateTarget(Order, 0, Order.size());

The size of the ArrayList can be anything. The size of the numbers are randomly chosen.

How can I optimize this function to calculate the best option as fast as possible, avoiding unnecessary calculations?