Building and querying an immutable phone book

Your indentation needs cleaning up.

The compiler says:

$ scalac -deprecation phoneBook.scala
phoneBook.scala:5: warning: overriding method main in trait App is deprecated: main should not be overridden

Following the example in the documentation, inside the App, you should just put your code in the object itself, without any main function.

Translating the three verbs into a numeric code is unnecessary obfuscation.  Trying to handle all three kinds of commands in the same doAction function is also cumbersome.

Converting the Iterator into a Stream is counterproductive, when you intend to process each line just once.  It just makes you have to (rawLines drop 1) explicitly.

You're starting with an empty phone book (cryptically named acc).  Then you want to have each command transform it and pass it along to the next command.  Instead of explicit recursion in the doAction function, you would be better off using a fold.

Instead of instantiating scala.collection.immutable.HashMap, you can just use a Map and let Scala do the right thing.

import scala.io.Source.fromInputStream

object phoneBook extends App {

  def add(phoneBook: Map[Int,String], number: Int, name: String) = {
    phoneBook + (number -> name)
  }

  def del(phoneBook: Map[Int,String], number: Int) = {
    phoneBook - (number)
  }

  def find(phoneBook: Map[Int,String], number: Int) = {
    println(phoneBook.getOrElse(number, "not found"))
    phoneBook
  }

  lazy val lines = fromInputStream(System.in).getLines
  val nQueries = lines.next.toInt

  lines.take(nQueries).foldLeft(Map.empty[Int,String])((phoneBook, line) => {
    line.split(" ") match {
      case Array("add", number, name) => add(phoneBook, number.toInt, name)
      case Array("find", number)      => find(phoneBook, number.toInt)
      case Array("del", number)       => del(phoneBook, number.toInt)
    }
  })

}

Actually, there is no need to convert the phone numbers to integers, unless you want to ensure that they are indeed numeric.  In fact, in general, phone numbers should not be treated as integers, since they may contain many digits, or may have significant leading zeroes.


Clarify the requirement

You state 'remove duplicate characters' but then your code checks for upper and lower case matches - is the requirement to check for distinct letters, or distinct characters?

Sort out the bugs

I sense premature optimisation here, and it is the root of some evil:

int len = str.length();
for (int i = 0; i < len - 1; ++i)
{
    for (int j = i + 1; j < len - 1; ++j)
    {
        if (str[i] == std::toupper(str[j])
            || str[i] == std::tolower(str[j]))
        {
            str.erase(str.begin() + j);
            flag = 1;
        }
    }
}

What is the value of len? The length of the original string. And what is the value of len after we have erased a duplicate character? Still the same. So if we do find some duplicates, we will then happily run out of bounds in both loops. You can manually update len, or you could just call length() - it is constant complexity so you aren't rescanning the string each time. I would opt for comparing to length() until a profiler tells you otherwise.

Getting an idea of computational complexity

The complexity of the pair of loops is O(n2). But inside that, you do an erase - imagine we erase from the middle of the string (which is the average case); then we will need to copy about n/2 characters into the previous positions. This gives us O(n3).

There are things we can do to improve a bit - we can continue scanning for further duplicates before erasing, so that abccccccccd only required one copy, collecting all the duplicate c in one go.

Without preserving order, we can do O(n log n)

The easy way to improve the complexity is just to sort the characters in the string:

std::sort(str.begin(), str.end());

And then run through removing adjacent duplicates.

Is it possible to remove duplicates with O(n log n) (or better) complexity whilst maintaining order?

Consider the decision whether to elide some character halfway through the string. This character could be any of (assuming 1 byte chars) 256 values, so the bare minimum storage needed to make the decision is 256 bits. The requirements are not clear - 'one or two additional variables' could easily cover a 256 element std::bitset (should be 64 bytes), but could also not cover it if they are angling for a specific solution.

If we can keep that std::bitset, then we can mark each byte value that we've seen in the array and erase any contiguous blocks of duplicates we see. Marking a value in a fixed size array is constant time (O(1)), so the cost of detecting whether each character is a duplicate is still only O(n). But if we erase them each time we find them, we will end up in O(n2) land again, copying the last character in the string into successive locations.

Remove_if to the rescue

There is a way to remove all those duplicates without copying each later character more than once; imagine two position markers, one to the character we are assessing, and one to an earlier position at the end of the deduplicated string. If we copy each character directly into it's final position then the space left by duplicate characters will bubble to the end:

abcdeaafg_
    ^^
abcdeaafg_
    ^ ^
abcdefafg_
     ^ ^
abcdefgfg_
      ^ ^
abcdefg_

But instead of having to cope with all the details, we can call remove_if, which does just that job for us, at a cost of n calls to the predicate. The predicate (boolean test function) will look up the character value in the bitset:

static_assert((CHAR_MAX - CHAR_MIN <= 256), "Implementation requires 8 bit char");
std::bitset<256> seenChars;
auto newEnd = remove_if(str.begin(), str.end(),
   [&seenChars](auto & c) {    // capture seenChars so we can use it
       if(seenChars[c%256])   // have seen it before, so remove
           return true;
       seenChars[c%256] = true; // we have seen it now
       return false;             // but we won't remove this one
    });

(Edited this after replacing array with bitset)

To unpack that a little: we are removing any character for which the predicate returns true. The predicate simply checks whether the character has been seen (by casting the character to int and using it modulo 256 as the index into the bitset), and either returns true or marks this character value for next time and returns false. The [&seenChars] captures the bitset so that we can use it inside the predicate without having to pass it in; it forms part of the context of the function body.

The hardcoded 256 is not ideal, perhaps, although I wouldn't want to make it general to larger numbers (instead just failing a static_assert) because of the implication for storage.

remove_if itself returns an iterator to the new end position of the string; it has copied the latter values into the earlier positions, but not resized the string. We resize, then:

str.resize(std::distance(str.begin(), newEnd));

Et voila, we have removed duplicates, in place, with a space requirement of 256 bits and a time complexity of O(n). Not too shabby.

By the way, you can detect the removal of duplicates by comparing the original string length with the final string length. If they differ, duplicates were indeed found.


I don't code in java or python so I don't fully follow the methods provided in the commented link under the question.

I've decided to write a method that avoids the incremental checking for palindromic integers.  Instead, it uses arithmetic based on a few preliminary string function results to discover the closest greater palindromic integer.  Note, there are limitations to my method because the input and output are integers rather than strings.  I can conclude after testing that my method will stay true into the 10's of trillions.

Code: (Demo)

function nextPalindromicInteger($integer) {
    if ($integer < 9) {
        $next = $integer + 1;
        return "$integer => $next (+1) " . ($next != strrev($next) ? "FAIL" : "PASS") . "\n";
    }
    $size = strlen($integer);
    $psize = ceil($size / 2);  // find length of rhs & lhs including pivot when length is odd
    $npsize = $size - $psize;  // find length of rhs & lhs excluding pivot when length is odd
    $rnplhs = (int)strrev(substr($integer, 0, $npsize));  // reverse nplhs
    $nprhs = (int)substr($integer, -$npsize);  // store right hand side integer excluding pivot  //KEEP
    $trimmed=strlen(rtrim(substr($integer, 0, $psize), '9')); // store length of rtrim'd plhs
    if ($rnplhs > $nprhs) {
        $bump = 0;
    } elseif (!strlen(trim($integer, '9'))) {
        $bump = 2;
        $nprhs = 0;
        $rnplhs = 0;
    } else {
        if ($psize != $npsize) {  // odd integer length
            if ($trimmed == 1) {
                $exponent = 1;  // dictates $bump=11
            } else {
                $exponent = $npsize;
            }
        } else {  // even integer length
            $exponent = $trimmed;
        }
        $bump = pow(10, $exponent);
        if ($psize == $npsize || $trimmed < $psize) {
            $bump += pow(10, $exponent - 1);
        }
    }
    $next = $integer + $rnplhs - $nprhs + $bump;
    return "$integer => $next (+" . ($next - $integer) . ") " . ($next != strrev($next) ? "FAIL" : "PASS") . "\n";
}
for ($x = 0; $x < 14; ++$x) {
    $integer = rand(pow(10, $x), pow(10, $x + 1) - 1);
    echo nextPalindromicInteger($integer);
}

If I spent some more time refining, I could probably write my function more eloquently, but for the purposes of this question it is sufficient to reveal (to me at least) some of the fringe cases.

I found in my development and testing that it was important to test against:

a range of integers, some with even length and some with odd length.
integers with a pivot (shared middle digit) of nine.
integers with an odd length and a non-9 pivot.
integers consisting entirely of 9's.
integers where the reversed left-hand-side component minus the right-hand-side component is:  >0, =0, and <0

Once I isolated the patterns that exist with certain sequences, I could declare the correct "bump" or adjustment.  Some bumps are static, others depend on the length or value of the left-hand-side component.

As for your relevant numbers to check using your method, I can't think of any that would cause trouble because you are looping and checking each iteration.  Perhaps the challenge was assuming that you would try to write a method without loops as I did or run "inside out" string comparison checks on each side's digits.

As for checking "large-ish" numbers, I found that once I had perfected the bumps from 1 to 9999, all integers above that were accounted for.

Possible Output:

9 => 11 (+2) PASS
75 => 77 (+2) PASS
776 => 777 (+1) PASS
4891 => 4994 (+103) PASS
92764 => 92829 (+65) PASS
999539 => 999999 (+460) PASS
7059657 => 7060607 (+950) PASS
48756572 => 48766784 (+10212) PASS
633149324 => 633151336 (+2012) PASS
2096785014 => 2096886902 (+101888) PASS
80448359477 => 80448384408 (+24931) PASS
237762850363 => 237763367732 (+517369) PASS
7730351516591 => 7730351530377 (+13786) PASS
79541453924626 => 79541455414597 (+1489971) PASS


Welford's online variance calculation algorithm for vectors

I can't say I understand exactly what your algorithm does. Even when looking at Wikipedia it is hard to see. So, why don't you just use the reference implementation from there? It has functions with nice names and everything (well, not quite PEP8 compatible, but that could be changed).
Alternatively, once you have vectors of numbers and want to perform fast calculations on them, you probably want to use numpy, which allows you to easily perform some operation on the whole vector, like taking the difference between two vectors, scaling a vector by a scalar, taking the sum, etc.
import numpy as np

MAGIC_CUTOFF = 0.4375

class WrongFaceException(Exception):
    pass

def norm(x):
    return np.sqrt((x**2).sum())

def update(base_encoding, new_face_encoding, v, n):
    delta1 = new_face_encoding - base_encoding
    if norm(delta1) > MAGIC_CUTOFF and n > 1:
        raise WrongFaceException(f"norm(delta1) = {norm(delta1)} > {MAGIC_CUTOFF}")
    new_encoding = base_encoding + delta1 / n
    delta2 = delta1 - new_encoding
    v = v * (n - 1) / n + norm(delta1) * norm(delta2) / n
    return new_encoding, v, n + 1

if __name__ == "__main__":
    new_face_encoding = np.array((0.2, 0.25, 0.4, 0.5) * 32)
    base_encoding = np.array((0.2, 0.3, 0.4, 0.5) * 32)
    v = 0.01
    n = 3

    updated_encoding, v, n = update(base_encoding, new_face_encoding, v, n)
    print(updated_encoding, v, n)

In addition to using numpy, I expanded some of the names so it is clearer what they are, I made the cutoff value a global constant (you should give it a meaningful name), added a custom exception instead of just dying (the pass after it was unneeded and unreachable BTW), which makes it more clear what happened, wrapped the calling code under a if __name__ == "__main__": guard to allow importing from this script without running it and followed Python's official style-guide, PEP8, by having operators surrounded by one space.
Instead of this norm function, you can also use scipy.linalg.norm, which might be even faster.

To answer if you used the math correctly, I would say partially yes. It looks like you implemented the explicit formula given for the sample variance:
\$\sigma^2_n = \frac{(n - 1)\sigma^2_{n-1} + (x_n - \bar{x}_{n-1})(x_n - \bar{x}_n)}{n}\$
However, note that Wikipedia also mentions that this formula suffers from numerical instabilities, since you "repeatedly subtract a small number from a big number which scales with \$n\$".
Instead you want to keep the sum of the squared differences \$M_{2,n} = \sum_{i=1}^n (x_i - \bar{x}_n)^2\$ around and update that:
\$M_{2,n} = M_{2,n-1} + (x_n - \bar{x}_{n-1})(x_n - \bar{x}_n)\$
with
\$\bar{x}_n = \bar{x}_{n -1} + \frac{x_n - \bar{x}_{n-1}}{n}\$
Then the new population variance is given simply by:
\$\sigma^2_n = \frac{M_{2,n}}{n - 1}\$
This is a bit tricky to implement, since your \$x_i\$ are actually vectors of numbers, so you would need to find out how to properly reduce it in dimension (in your previous formula you used the norm for that).


Here are some things I've observed that may help you improve your code.

Prefer specific instructions to data storage

There is a constant 1 that is loaded into one but there is actually an instruction fld1 which you could use instead.  This would avoid both the storage area and the time taken to access it.

Take advantage of instructions that pop the stack

Many instruction have a version which pops the top of the FPU stack.  The code currently includes this:

greater:
    fstp result
    fstp result
    loop lp

However it appears that the only reason for those two fstp instructions is to pop the operands off the stack -- they're not actually needed later.  A better way to do that would be this:

    faddp st(1), st(0)

    ; if point is inside the circle increase counter
    fcomip st(0), st(1)
    ja greater
    inc eax
greater:
    loop lp

By using the p suffix on both the faddp and fcomip instructions, the stack is already adjusted.

Think carefully about instruction ordering

The fxch instruction is not really needed.  Instead, you could simply load each random number as needed onto the top of the stack by moving the second of the fild instructions to where the fxch is now.

Avoid branching where practical

Branching is a costly operation to the processor, so avoiding (that is conditional or unconditional jumps) saves cycles and time.  In this code, we have this:

    fadd st(0), st(1)
    ; if point is inside the circle increase counter
    fcomi st(0), st(2)
    ja greater
    inc eax
greater:
    fstp result
    fstp result
    loop lp

I've already addressed changing that to this by using the stack-popping versions to get this:

    faddp st(1), st(0)
    ; if point is inside the circle increase counter
    fcomip st(0), st(2)
    ja greater
    inc eax
greater:
    loop lp

We can do still better, though. The carry flag is set by the fcomip instruction if we should be incrementing eax. We can take advantage of this directly and avoid a branch:

    faddp st(1), st(0)
    ; if point is inside the circle increase counter
    fcomip st(0), st(2)
    adc eax, edx
    loop lp

This assumes that edx is set to 0 which can easily be done the same place that eax is initially set to zero.

Use stack space instead of named variables

Having named variables is very useful for starting out and troubleshooting, but doing so prevents your routine from being reentrant.  That is, if the code is called by more than one thread simultaneously, either or both will work incorrectly because there is only one copy of the variables.  If you instead allocate those on the stack, this potential problem is eliminated.

Consider refining the mathematics

At the moment, the loop scales each random number, squares each, adds the products and compares.  Mathematically, if \$a\$ and \$b\$ are the two random numbers, we calculate

\$(a k)^2 + (b k)^2 < 1\$ but we can certainly manipulate that because \$k\$ is a constant. Specifically, we can convert this to \$a^2 + b^2 < \frac{1}{k^2}\$.  This would allow calculating the constant term \$\frac{1}{k^2}\$ once outside the loop and minimizing the operations within the loop.

Consider reformatting the code

It compiles as is, but typical formatting of assembly language code put only labels and directives in the first column and all code is indented.

Consider the merits of SSE

To answer your question, yes, SSE would speed things up. In particular, you could calculate multiple numbers in parallel. This would allow the code to effectively use fewer loops for the same precision.


Automatically select the table rows between two selected rows

Easiest thing you can do is properly name your variables and add comments.

Seeing things like this is very frustrating:

aIndex.push(k);
vMatched = k;

It's completely meaningless except to the developer who wrote it. It's a form of hungarian notation, except nothing is preventing you from making aIndex a String instead of an Array or vMatched and array instead of a var. (I'm assuming v is for var, which is also a hint this naming style isn't going to work here).

I'd expect for-loops to start using i not k. No need to declare it at the top either. You should always declare variables in the most local scope.

Here you're adding the numbers 0-a onto a list. You don't need to do that since you already have a. If you need to store the length at that time, you can.

for (var a = 0; a < this.getView().byId("monTable").getItems().length; a++) {
    aIndex.push(a);
}

In your nested loops it looks like you are getting the indexes that match based on a criteria. You should really do this in a method, hopefully with comments to make it easier to read. You can use lambdas expressions if you're comfortable with them. However without better context I cannot provide a concrete alternative.

You should use a method for getting the min/max amounts from an array. Methods make everything easier to read & easier to refactor.

You can use Arrays.sort() then take the first / last item of the array to get the min/max.


1.) Your search only looks for the first substring only (e.g. "ab"), it will never match the others given (e.g. "cd").
Why? Because You wrote:

String word = search.substring(0,i);

That would give us "ab+cd" for the second substring (maybe this is an error and you wanted to grab "cd"?)
Anyway, for the first substring found you are setting break1 and therefore exiting the loop.
But instead of setting break-variables, you can break directly by writing "break;". This  would be faster and makes your code more readable.

2.) Always make tests (write JUnit-Tests) for your code. You can post them, too. In many companies you cannot check in your code without a corresponding test with full code coverage.
If you have input="axb" and search="ab+", then it would match! Is this really intended? I think it's an error, and you would have found out if you wrote tests.

3.) Many times you wrote :

((search.charAt(i)=='*')||(search.charAt(i)=='+'))

This is a double DRY (Don't Repeat Yourself, clean code red grade) coding practice violation.
Just evaluate search.charAt() once and store it in a variable "currentChar". Then evaluate the whole expression once and store it in a boolean variable "isDelimiter".
Your code:

if (search.charAt(i)!='*' && search.charAt(i)!='+') {
    counter++;
}
...
if ((search.charAt(i)=='*')||(search.charAt(i)=='+')) {
...

would be reduced to:

char currentChar = search.charAt(i);
boolean isDelimiter = (currentChar=='*' || currentChar=='+');
if (!isDelimiter) {
    counter++;
}
...
if (isDelimiter) {
...

4.) Generally code is written once, but read on average about 10 times. That's why we have the coding practice to use meaningful names (clean code orange grade, source code conventions).
So change "break1" to "isInvalidSeachString", "break2" to "hasNoMatch", "notgood" to "bad", "counter" to "validCharacterCounter" and "c" to "matchingCharacterCounter"

5.) Follow the Single level of abstraction principle.(clean code, orange grade)
You are doing too much in a single method. You are verifying the correctness of the search string. Then you are tying to grab each substring and then match each substring.
Meaningful names are much better than a meaningless separator like "///////...".
Your structure should be following

public boolean isMatchingWholeSearch(String input, String search)
{
  boolean searchIsCorrect = hasNoStartingPlus(search) && hasNoDoublePlus(search);
  if (searchIsCorrect) searchForAllMatches(input, search);
}
private boolean searchForAllMatches(String input, String search)
{
  for (int i=0, max=search.length(); i<max; i++) { // performance optimized for-loop
      boolean isSubstringSuffix = (search.charAt(i)=='+');
      if (isSubstringSuffix) {
          String substring = getSubstringBefore(search, i);
          boolean isFound = searchForSingleMatch(input, substring);
          if (isFound) return true;
      }
  }
  return false;
}
private boolean searchForSingleMatch(String input, String search)
{
  // here goes your inner loop.
  ...
}
private boolean hasNoStartingPlus(String search)
{
   ...
}
private boolean hasNoDoublePlus(String search)
{
   ...
}

6.) For not reinventing the wheel, you could use java streams String.chars() with lambda expressions, or String.split() methods and regular expressions for verifying. That would make your code much more readable and very short. But maybe you can only use an old java version. Tell me if you can use a new one, and I'll give you code samples for each.


I have written APL code on VM/CMS and in DEC's VAX-11 interpreter.

No, I don't see a better way that would shorten the code.


What you did well on:

Your program is easy to read.
You are allocating memory, even though it is unsafe in certain cases (other answers have addressed this, so I won't cover it).
You prepare for some corner cases.

Things you could improve:

You are returning 0 when your program runs into a problem (except
in one spot where there are too many parameters being entered).

return 0;

0 is typically the return code for a exiting successfully.  If we
run into a problem in our program, we should return something to
indicate we ran into a problem.  I prefer to return negative numbers.

return -1;

Also, you should return different numbers for different errors.  A user generated error such as malformed input should not return the same error code as an internal error.  This makes debugging a lot easier when you are trying to determine the cause of an error.

However, since you are returning an int*, it would be better to return NULL instead.  This is what you are doing right now, in a somewhat abnormal way by returning 0.  Just return NULL.

return NULL;

You should mark ints as unsigned if they are never going to be negative.

unsigned int start;

You are not maximizing how many Fibonacci you can produce using only an int, or even an unsigned int.  An unsigned int has a maximum value of 2147483647, where a long long unsigned int has a maximum value of 18446744073709551615.  That's 8589934562 times larger!
Declare i inside of your for loops.  This is part of the C99 standard, so you may have to adjust how you compile your program.

for (unsigned int i = 1; i <= n; i++)

I don't see the point of the start variable.  Unless this is part of some problem you are trying to solve, I would just print the whole sequence.  It would cut down on your lines of code a lot as well.
The Fibonacci series is a great place to practice recursion.

long long unsigned int fibonacci(long long unsigned int n)
{
   if (n < 2) return n;
   else return (fibonacci(n-1) + fibonacci(n-2));
}

This algorithm here is short, and gets the job done just has you did in less lines of code.  We could even shorten it a bit further if we wanted to (with ternary operators).

long long unsigned int fibonacci(long long unsigned int n)
{
    return (n < 2)? n : fibonacci(n-1) + fibonacci(n-2);
}

We have to be careful though to avoid repeating the calculation of results for previously processed inputs; to do this we should use memoization. I've implemented this in my final program.
Keep in mind that sometimes recursion will make your algorithm a bit
slower with time-complexity, which can be the case here (depending on your implementation of an iterative solution).  Here is the fastest iterative algorithm I could work up (this may still be a bit slower with the pow() function).

long long unsigned int fibonacci(long long unsigned int n)
{
    return (1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n));
}

However, using this method requires the use of doubles, and the return will make an implicit cast that could cause some rounding problems.  Therefore, we will round() the result in our final code.
You should test if you input is a number, and not some malformed input.

if (scanf("%i", &num) <= 0)
{
    puts("Invalid input.");
    return -1;
}

Final code:

Iterative: O(1)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

long long unsigned int fibonacci(long long unsigned int n)
{
    return round((1/sqrt(5)) * (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)));
}

int main(void)
{
    unsigned int num = 0;

    printf("Enter how far to calculate the series: ");
    if (scanf("%i", &num) <= 0)
    {
        puts("Invalid input.");
        return -1;
    }

    for(unsigned int n = 1; n < num + 1; ++n) printf("%llu\n", fibonacci(n));
}

Recursion: O(n)

#include <stdio.h>
#include <stdlib.h>

#define ARRAYLENGTH 100 // keep in mind the result must fit in an llu int (fibonacci values grow rapidly)
                        // you will run into issues after 93, so set the length at 100
long long int memoization[ARRAYLENGTH];

long long unsigned int fibonacci(long long unsigned int n)
{
    if (memoization[n] != -1) return memoization[n];

    return (n < 2)? n : (memoization[n] = fibonacci(n-1) + fibonacci(n-2));
}

int main(void)
{
    unsigned int num = 0;

    for(unsigned int i = 0; i < ARRAYLENGTH; i++) memoization[i] = -1; // preset array

    printf("Enter how far to calculate the series: ");
    if (scanf("%i", &num) <= 0)
    {
        puts("Invalid input.");
        return -1;
    }
    if (num < ARRAYLENGTH)
    {
        for(unsigned int n = 1; n < num + 1; ++n) printf("%llu\n", fibonacci(n));
    }
    else
    {
        puts("Input number is larger than the array length.");
        return -2;
    }
}


I am fully agree with what @Jamal has said. Apart from that I would like to add some more points.
Use consistency in your code
Although PEP8 says there is no strict rule for naming convention, if you stick to one particular convention it'll be easier for you and the reviewers to follow.
In your code you have used reply, seconds which starts with lowercase letter but Age starts with uppercase letter.
I use the following convention

normal variables: lowercase_with_underscore
class names: CamelCase.
constants: UPPERCASE

And about the function which you defined inside the while loop
Only in certain cases(like in decorators) you should define your function
inside an enclosing scope. Defining a function inside while loop means, whenever the while condition become true it will encounter that function block which is time consuming.
Better define your function outside the while block and it improves readability.
Hard coding
You have hard coded the numbers like 1, 90, 31536000. Giving names to these number will help you a lot in the future.
Creating function
Creating a function for the calculation of age-in-seconds will allow you for the re-usability of your work.
After changing all the stuff, my function is looking like the following
SECONDS_IN_A_YEAR = 31536000
LOWEST_AGE = 1
HIGHEST_AGE = 90

def splitthousands(x, sep=','):
    '''
    Inserts a comma after every three digits from the right.
    '''
    if len(x) <= 3:
        return x

    return splitthousands(x[:-3], sep) + sep + x[-3:]

def calc_age_in_seconds(age):
    '''
    calculates the given age in seconds

    :raises: ValueError
    '''

    if age < LOWEST_AGE or age > HIGHEST_AGE:
        raise ValueError

    return age * SECONDS_IN_A_YEAR

def ask_user_and_calc_age_in_seconds():

    print('*'*44+'\n****How Many Seconds Have You Been Alive****\n'+'*'*44)

    while True:
        try:
            print('\n--------------------------------------------')
            age = int(input('\nHow old are you?: '))

            seconds = str(calc_age_in_seconds(age))

        except(TypeError,ValueError):
            print('(Input Error)*Enter Valid Age*')
            continue

        print('\nYou have been alive for '+splitthousands(seconds, sep=',')+' seconds.')
        print('\n--------------------------------------------')

        while True:
            try:
                reply = str(input('\nDo you want to play again(Y/N)?: ').title())

            except(TypeError,ValueError):
                print('(Input Error)*Enter Valid Option*')
                continue

            if reply.startswith('Y'):
                break

            else:
                raise SystemExit

if __name__ == '__main__':
    ask_user_and_calc_age_in_seconds()


Use np.cumsum()
import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
WALKER_STEPS: int = 5_000

# random orientation converted from degrees to radians
directions: np.array = rd.uniform(low=0, high=360, size=WALKER_STEPS) * np.pi / 180

x = np.cos(directions).cumsum()
y = np.sin(directions).cumsum()

plt.plot(x, y)
plt.show()


Determine whether three sides form a valid triangle, and classify the triangle

Add a __name__ == "__main__" guard, and move the logic into a function separate from the I/O:
def triangle_type(a, b, c):
    '''Return a string indicating the type of triangle
       (Equilateral, Isosceles, Scalene, Impossible)
    '''
    # implementation here...

def main():
    getcontext().prec = 3
    getcontext().rounding = ROUND_HALF_UP

    #Needs to be divided to re-set decimal place I think
    a = Decimal(input("Length of side a = ")) / 1
    b = Decimal(input("Length of side b = ")) / 1
    c = Decimal(input("Length of side c = ")) / 1

    print(f"This is a {triangle_type(a, b, c)} triangle")

if __name__ == "__main__":
    main()

In the implementation, we can save a lot of "or" tests by sorting the lengths before we start:
a, b, c = sorted([a, b, c])

if a + b <= c:
    # N.B. automatically catches a < 0, since b <= c
    return 'Impossible'
if a != b != c:
    return 'Scalene'
elif a == c:
    return 'Equilateral'
else:
    return 'Isosceles'

Modified code
def triangle_type(a, b, c):
    '''
    Return a string indicating the type of triangle
    (Equilateral, Isosceles, Scalene, Impossible)
    '''

    a, b, c = sorted([a, b, c])

    if a + b <= c:
        return 'Impossible'
    if a != b != c:
        return 'Scalene'
    if a == c:
        return 'Equilateral'
    return 'Isosceles'

def main():
    a = input("Length of side a: ")
    b = input("Length of side b: ")
    c = input("Length of side c: ")
    print(f"({a}, {b}, {c}) is a {triangle_type(a, b, c)} triangle")

if __name__ == "__main__":
    main()

Further improvement
Use the doctest module to write the tests:
def triangle_type(a, b, c):
    '''
    Return a string indicating the type of triangle
    (Equilateral, Isosceles, Scalene, Impossible)

    >>> triangle_type(1, 1, 2)
    'Impossible'
    >>> triangle_type(-1, -1, -1)
    'Impossible'
    >>> triangle_type(1, 1.0, 1)
    'Equilateral'
    >>> triangle_type(1, 2, 2)
    'Isosceles'
    >>> triangle_type(2, 3, 2)
    'Isosceles'
    >>> triangle_type(2, 3, 4)
    'Scalene'
    '''

    a, b, c = sorted([a, b, c])

    if a + b <= c:
        return 'Impossible'
    if a != b != c:
        return 'Scalene'
    if a == c:
        return 'Equilateral'
    return 'Isosceles'

if __name__ == "__main__":
    import doctest
    doctest.testmod()


Floating point representation in IEEE 754 format

I just don't get what you're trying to do. JavaScript does not know of integers, floats or any other numeric type, except for Number.
This data-type just happens to be a 64bit IEEE754 floating point value (or double in most strong-typed languages). This is clearly described in the official language specs

primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value
NOTE A Number value is a member of the Number type and is a direct representation of a number.

So a float representation of a number is the number itself. If you want n number of significant digits, then there's a handy method for that:
var num = 123.321;
console.log(num.toFixed(2));//123.32

If you want the integer part of a non-integer number:
parseInt(num, 10);//123 (best to specify the radix)

If you want the remainder, either one of the following approaches will do:
num - parseInt(num, 10);
//or
num%1//modulo || remainder of division by 1

Note that in this last case, you will see the rounding errors of the IEE754 spec show up, so:
num = 123.321;
//get length of string rep for total number - int length,  -1 for .
var fix = (""+num).length - (""+parseInt(num, 10)).length - 1;
(num%1).toFixed(fix);

Might be required.
As far as the fraction representation of a number is concerned, that is going to take some work. Thankfully, it's all been done before and the code is available on github.
I don't know what you mean by: "It does not consider negative numbers", because, like I said before: there is but one type for numbers in JS, and so it's always signed. Just use the absolute value, and keep track of the what the number was initially (prositive or negative) like so:
function processNumber(num)
{
    var sign = !(num > 0);//bool, true if num is negative
    var workVal = Math.abs(num);//get absolute value
    var returnObj = {};
    returnObj.intVal = parseInt(workVal, 10);
    returnObj.floatPart = (workVal%1).toFixed((""+workVal).length - (""+returnObj.intVal).length - 1);
    returnObj.fixed2 = workVal.toFixed(2);
    //and so on...
    if (sign === true)
    {
        for (prop in returnObj)
        {
            if (returnObj.hasOwnProperty(prop))
            {//they're all strings, just prepend the sign...
                returnObj[prop] = '-' + returnObj[prop];
            }
        }
    }
    return returnObj;


Improve your file handling:

Don't use a hard coded file name for temporary files.
Don't spew temporary files into the current directory.
Make sure you clean up temporary files even on error.

The first two can be addressed by leveraging mktemp. The last can be addressed with a trap.

branchesfile=$(mktemp)
trap "{ rm -f $branchesfile; }" EXIT

You should also honor the user's choice of default editor, rather than require nano. You can get the user's editor preference with git var GIT_EDITOR:

$(git var GIT_EDITOR) $branchesfile

Git tools typically honor the exit code of the editor. If the editor exited with error, this should stop the script:

if [ $? -ne 0 ]; then
    exit 1
fi

This allows the user to cancel the operation if they spot a problem they don't want to fix at the moment.

Putting this all together:

#!/usr/bin/env bash
branchesfile=$(mktemp)
trap "{ rm -f $branchesfile; }" EXIT

# Remove references to remote branches that no longer exist.
git remote prune origin
# Create a file containing list of all merged branches.
git branch --merged > $branchesfile

$(git var GIT_EDITOR) $branchesfile
if [ $? -ne 0 ]; then
    exit 1
fi

# Trim trailing and leading whitespace etc.
sed 's/^[ \t]*//;s/[ \t]*$//' < $branchesfile
# Soft delete all branches left in the file and then remove tmp file.
xargs git branch -d < $branchesfile

There's one other issue: your script will try to keep going if any other commands error out. set -e is one option to solve this, but there are caveats to using it. If you choose to use set -e, you'll need to revise the exit code checking of the editor, since bash will exit before it gets to the if.


Methods in C# are written in PascalCase, so let's change isPrime to IsPrime.

You can use LINQ to make the code a bit clearer. Instead of

for (var i = 0; i < numbers.Length; i++)
{
    Assert.IsTrue(Numbers.isPrime(numbers[i]));
}

You can write

Assert.IsTrue(numbers.All(Numbers.IsPrime));

Instead of

for (var i = 0; i < numbers.Length; i++)
{
    Assert.IsFalse(Numbers.isPrime(numbers[i]));
}

You can write

Assert.IsFalse(numbers.Any(Numbers.IsPrime));

or

Assert.IsTrue(numbers.All(n => !IsPrime(n)));

whichever you find easier to read (I prefer the former).

In fact, I would be a bit lazy and copy a big list of prime numbers from somewhere and then write

var primes = Enumerable.Range(0, 1000000).Where(Numbers.IsPrime);
Assert.IsTrue(primes.SequenceEqual(PrimesLessThanOneMillion));

If you take @mleyfman's suggestion to test with randomly generated primes, be sure to seed the random number generator. Unit tests must be reproducible.

That is, never do this

var random = new Random();

but do this

var random = new Random(42);

One of the benefits of unit tests is that if they fail, you know it is due to a change in the code, and can then git bisect (or similar) to find the breaking commit. If a unit test fails due to something that is not a change to the code (e.g. a different RNG seed) you have lost this important benefit.

Edit: as @svick pointed out, using the same seed may not generate the same sequence between different versions or implementations of .NET. See these answers on StackOverflow. If all dev machines (including the build server) are running the same version of .NET, you should be fine.


Collecting Parameter vs overloading addition

One benefit of a collecting parameter is writers can add multiple items to the list.  The collecting parameter can descend deeper into the stack and each method is free to add as many items to the list as necessary.

If what was added to the list was restricted to the return value of the method, then it becomes the sender's responsibility to know how to add the receiver's return values to the list, and the receiver cannot return another value other than what would have been added to it.

The collecting parameter seems more flexible because any number of receivers may write to it and still be able to return values.


Your XOR-step is nonsense, it doesn't add any security.

The reason is the way the CTR mode works: It encrypts a counter (thus the name) using the key (and the IV as starting point), and XORs the plaintext with the result.
XORing the plaintext with some other constant before encryption can be undone by XORing it with the same value after encryption.

Still, CTR mode (with or without this XOR) should be enough for protection, as long as your IV is non-repeating. To break it with some known plaintext, you basically have to brute-force encrypt the counter with different keys, until you get the same output as plaintext XOR ciphertext (for one block).

Also, you are using a simple MD5 hash for integrity protection. While MD5 might be fine in this case, it now has the reputation of being broken (i.e. there are quite easy collision attacks), which makes it not safe. Use a MAC algorithm for integrity protection, for example with hash_hmac (and a strong hash function like sha256, which you used before).

Other than that, PHP's rijndael-192 is not one of the AES algorithms. AES is Rijndael with block size of 128 bits (and key sizes of 128, 192 or 256 bits), and you are using an 192-bit block size version here. (This does not necessarily mean it is less secure, you just shouldn't call it AES. It did receive less cryptoanalysis than the variant that got standardized as AES, though.)


Graph degree as solution for undirected graph paint

It is not. Consider a triangle graph which has tree nodes and three edges. All vertices has degree two but three colors are required to color it. Your function would fail for that input.

In fact, the problem is NP-complete meaning that it is not known if an efficient algorithm can be constructed for solving it. So if you can do it, you'll win fame and fortune and also a very large monetary prize.


Overall a very cleanly written class.  It is easy to follow and understand.

A couple of suggestions though.

Make the reader class variable a Property with a private setter.  This will eliminate the ability to reassign it from outside of the class.  I would also rename it Reader to fit with C# coding standards.

Most C# coding standards I have read suggest prefixing private class variables with a _.  This will allow you to remove the this. statement whenever you need to access one of the class variables.  I think doing that will make you code much easier to read.

I'm not sure what the SelectSync method is used for.  I see it as a way to do a non-async query into the database.  If that is the case, I would move it to a different class as it interferes with the async nature of the one you have written.  Maybe rename this class to DataAccessAsync, and have a second one DataAccess?  Its hard to say without an example of a call to that method.

I can't see much more at this point.


Compare two tables and arrange the values in a new array

you can create an array of finished and unfinished which contain stack_id and then use array_diff method in PHP.


Speed performance of sqlite3 queries looped in python

There are multiple things that I would like to point out to you, just to help you improve coding style. Currently you are not noticing as performance issues as they are hidden due to you DB performance.

Fixed values: You are computing fixed list every time through 'range'. Try to store them in list. As this is unnecessary compute overhead.

File writing: You are opening and closing file per record. This can cause huge disk performance issues once you start noticing. Try to collect record in list and maybe write to file once every 'hour'.

Always try to add 'Indexes' on DB. They are made for purpose of speeding up searching.


You can rewrite it like this:

// you have to be in both 'group' and 'board' to get access
$has_access = $is_in_group && $is_in_board;
// you must have access or be a superuser
if (!($has_access || $is_superuser)) die('No access');

I don't think an explanation is needed.

Alternatively you could even write:

// you have to be in both 'group' and 'board' to get access
$has_access = $is_in_group && $is_in_board;
// you must have access or be a superuser
if ($has_access || $is_superuser) {
  // ....
  // do whatever requires access
  // ....
} else die('No access');


Your testcases are far too simple to be certain your algorithm works. This might be an issue on the challenge's side. Both these testcases have symmetrical solutions. For these testcases, it's best to always rob every second layer. No test cases cover instances where the left side of the tree might follow a different pattern to the right side. Take for example the testcase:

{ 3, 8, 5, 1, 3, 10, 1 }

On the left branch, you'd expect the 8 to be robbed on the second layer, while the right side is more beneficial to rob the third layer, foregoing the first layer altogether.

That said, your algorithm appears to handle this correctly. That, along with the caching you do, appears to be working quite well.


Single-letter variable names are usually a bad practice, with few exceptions (loop counters, caught exception objects). Importing modules with single-letter names is very silly indeed. So don't do this:

from threading import Thread as T
from Queue import Queue as Q
from random import randint as R

Just stick to good old-fashioned:

from threading import Thread
from Queue import Queue
from random import randint

This is not a very interesting experiment with threading and a Queue. Check out the documentation, it's quite basic but much more interesting, and really using threading and a Queue.


Fizz Buzz function that returns an array

I am hoping to seek advice on adding conditional checking such as: 1) if the value n is less than 4, it will return the string: "Please insert a value greater than or equal to 4" and 2) if the function is passed no value, it should return an empty array. I am not sure where to add and should I be using if...else or simply if for each conditional checking.

If we check for n < 4 and returns a fixed string "Please insert a value greater than or equal to 4" anyway, do we really need to do anything before it? If we don't need to do anything before it, where should we put it?
Same goes for 2) if the function is passed no value, it should return an empty array

For the code itself, some points
1. Let's look at the loop
for (let i = 1; i < n; i++) {
  if (n === 1) {
    // blah
    return arr.reverse();
  } else {
    // blah
    return fizzBuzz(n - 1, arr);
  }
}

On every iteration this will return something. The for loop won't even need to go through the next iteration, it will always break and return on any iteration(!). You are doing recursion and loop at the same time.
2. arr.push('' + n);
Maybe use toString() method for numbers arr.push(n.toString());
3. if-else and returns
if (n === 1) {
    arr.push('1');
    return arr.reverse();
} else {
    // blah
}

Since the if block will always return, we don't need the else. This can be rewritten as
if (n === 1) {
    arr.push('1');
    return arr.reverse();
}

// the else blah
```


rand_ranged_inclusive(a, b) is a surprisingly long function name, for how little information it communicates to the reader. I have frequently seen versions of this function named randint(a, b) or randint0(b) — but where the possible outputs are between 0 inclusive and b exclusive!
Using "half-open ranges" like this has huge advantages in C, because C uses half-open ranges for everything else. To pick a random element from an array, you want randint0(NELEM(a)). To pick a random character from a string, you want randint0(strlen(s)). And so on.
if (min > max)
    SWAP_INT(min, max);

Here and throughout, I strongly recommend curly-bracing all your control flow, including if and for bodies which are currently only one line long. These braces may one day save you from a goto fail bug.
Also, I think it's un-idiomatic that you are going out of your way to produce well-defined behavior for rand_ranged_inclusive(6, 1). I claim that that kind of input clearly indicates a bug in the caller, and you should be using assert(min <= max) here. (Or, if you switch to half-open ranges, assert(min < max).)
Your choice to handle rand_ranged_inclusive(6, 1) becomes even weirder when you consider that you do not handle seemingly valid parameters such as rand_ranged_inclusive(-10, INT_MAX). (The caller who tries that gets integer overflow and undefined behavior.)
int range = max-min+1;
int biased_interval = RAND_MAX%(range-1);

The use of RAND_MAX % ... instead of (RAND_MAX+1) % ... is an immediate red flag for me, after our discussion of half-open ranges. (RAND_MAX is an endpoint-which-is-included, similar to INT_MAX.) All these +1 and -1 would go away if you switched to half-open ranges. I bet they're hiding some off-by-one errors. Let's trace through a sample input.
Suppose min=1, max=6, RAND_MAX=10. (This is legitimately the first input I traced.) Then range=6, biased_interval=0... so the do-while loop runs only once before dropping out... but you end up choosing 1-4 twice as often as 5-6.
Did you test this code at all?  How did you test it?
I think the algorithm you want here is more like
int range = max - min + 1;
int discard_top_k = ((RAND_MAX % range) + 1) % range;
int real_max = RAND_MAX - discard_top_k;
do {
    x = rand();
} while (x > real_max);

int j = rand_ranged_inclusive(i, len-1);

Your Fisher-Yates shuffle looks correct; but notice again that you're having to add a -1 to fix up the lack of half-open ranges in your random-number code.

if (c < 0 || c > 52)
    printf("Joker\n");

Is this situation possible? If it's supposed to be impossible, you should assert(0 <= c && c < 52) (hey look! half-open ranges!)
Also notice the off-by-one error in your code because of (say it with me) the lack of half-open ranges.

char const *argv[]

I agree with Linus on this one. Prefer
const char **argv


Invocation list implementation (signals/slots)

I mentioned in the comments the following improvement to operator() using range-based loops:

for (auto target : _targets) target(args...);

I've also identified another potential issue: with the code as originally posted, the user must not destroy the invocation_list instance during invocation (i.e., inside a target function). This situation could easily arise if, for example, the invocation list is used to implement a "close" event, and inside the "close" event "handler" the user wants to delete the object that "triggered" the event.

To allow this, the subscribe() function must first make a copy of the std::list of targets before iterating over it. This allows the invocation list itself to be safely destroyed (per the "suicide" rules):

void operator()(Args... args) const
{
    list_type targets(_targets);
    for (auto target : targets) target(args...);
}

This reduces performance since the list of targets has to be copied for every invocation, but allows more robust usage. If anyone knows any alternatives that don't require copying the list but still allow this usage pattern, I'm all ears! Thanks!


Find the highest unique element in an array

Your approach is a little bit complicated: you're building a TreeMap that is sorted in descending order of their keys. The value for each key is the number of times it appears in the input. Then you are iterating the map to find the first key having the value of 1. There are a couple of notes though.

Use built-in methods

You are constructing a TreeMap sorting in reverse order of their keys with

// Used TreeMap to store data in descending order to return maximum unique value
Map<Integer, Integer> map = new TreeMap<Integer, Integer>(
        new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);
            }
        });

You actually do not need to create a custom comparator for that case. You can use the built-in Collections.reverseOrder(). Also, since Java 7, you can omit the type-declaration with the diamond operator. So you could just have:

Map<Integer, Integer> map = new TreeMap<>(Collections.<Integer>reverseOrder());

Use Java 8 constructs

Starting with Java 8, you can replace the following code

if (map.containsKey(input))
    map.put(input, map.get(input) + 1);
else
    map.put(input, 1);

with the built-in merge(key, value, remappingFunction) method. This will put the given key with the given value if there was no mapping for that key, else it will invoke then given remapping function with the old value and the new one. In this case, we can then replace that code with

map.merge(input, 1, Integer::sum);

which will put the mapping with 1 if there was no key or add 1 to the current value if the mapping already exists.

Add curly braces!

This may sound like a nitpick but it is in fact very important. There are part of your code that doesn't add curly braces, or have it partially, like

if (map.containsKey(input))
    map.put(input, map.get(input) + 1);
else
    map.put(input, 1);

with no curly braces, or

if (map.containsValue(1)) {
    // ...
} else
    System.out.println(-1);

with partial curly braces.

Better to make it consistent and use curly braces everywhere.

Simpler approach

In this problem, we're only interested in keeping the highest number that appear only one time. This means that every numbers which appears more than once can be ignored: we know that it won't be the result. As such, there is no need to store a map with the exact count of each number: we only want to know if it is 1 or not.

Consider the following approach:

We keep a Set with the running encoutered numbers.
We keep a Set with the running highest unique numbers.
For each input, those two sets are updated:

If the input was already encountered, we remove it from the set of uniques
If the input wasn't encoutered, we add it to both the encoutered and the uniques.

An implementation would be the following:

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Set<Integer> encounteredInts = new HashSet<>(n);
Set<Integer> uniques = new HashSet<>(n);
for (int i = 0; i < n; i++) {
    int input = sc.nextInt();
    if (encounteredInts.contains(input)) {
        uniques.remove(input);
    } else {
        encounteredInts.add(input);
        uniques.add(input);
    }
}

if (uniques.isEmpty()) {
    System.out.println(-1);
} else {
    System.out.println(Collections.max(uniques));
}

There are clear advantages:

We do not store information that we don't need in a map: this is net-gain in memory usage.
We use a Set for look-up, insertion and deletion, which is constant-time: this is net-gain in performance.
From the final set, we only keep the highest according to the natural ordering of the integer. This is the only operation which runs in linear time, but it is done only once, at the end, when the set will have the minimum amount of numbers to consider.


Code for creating combinations taking a long time to finish

You take the combinations in a way too convoluted way. For starter, I would simplify the retrieval of "same memberid" questions:

for memberid in IncorrectQuestions.memberid.unique():
    questions = IncorrectQuestions[IncorrectQuestions.memberid == memberid].questionid

No need to groupby here since you’re already filtering by the one memberid you’re interested in. Thus producing combinations can be as simple as:

    for elem in itertools.combinations(questions, 2):
        question_pairs.append(list(elem))

Now, I don't see why you want to explicitly turn the tuples returned by itertools.combinations into lists as it adds up time and memory usage. So I suggest dropping it.

Now in the for loop, the use of unique() plus filtering on these unique values is the exact use-case for groupby. So you can rewrite it:

for member_id, questions in IncorrectQuestions.groupby('memberid'):
    for pair in itertools.combinations(questions.questionid, 2):
        question_pairs.append(pair)

I would then turn it into a function for better reusability/testing and use Python naming conventions:

def generate_combination_of_questions(dataframe):
    question_pairs = []
    for _, questions in dataframe.groupby('memberid'):
        for pair in itertools.combinations(questions.questionid, 2):
            question_pairs.append(pair)
    return question_pairs

But the combo var = [] + for loop + var.append should be turned into either a list-comprehension or a generator for better performances:

def generate_combination_of_questions(dataframe):
    return = [
        pair
        for _, questions in dataframe.groupby('memberid')
        for pair in itertools.combinations(questions.questionid, 2)
    ]

or

def generate_combination_of_questions(dataframe):
    for _, questions in dataframe.groupby('memberid'):
        yield from itertools.combinations(questions.questionid, 2)

The second version uses Python 3 syntax and is called as follow:

question_pairs = list(generate_combination_of_questions(IncorrectQuestions))

If you don't have Python 3 available, you can use the more verbose:

def generate_combination_of_questions(dataframe):
    for _, questions in dataframe.groupby('memberid'):
        for pair in itertools.combinations(questions.questionid, 2):
            yield pair

Your timing procedure can also be enhanced by the use of either time.perf_counter() or, better, the timeit module

Example code with timeit:

import itertools

def generate_combination_of_questions(dataframe):
    for _, questions in dataframe.groupby('memberid'):
        yield from itertools.combinations(questions.questionid, 2)

if __name__ == '__main__':
    import timeit
    setup = """\
import pandas as pd
from __main__ import generate_combination_of_questions
incorrect = pd.read_csv(<...>)"""

    print(timeit.timeit(
        'list(generate_combination_of_questions(incorrect))',
        setup=setup, number=1))

Reading at the various comments about the size of your dataset, you definitely want the generator version (the one with yield instead of return) as it will allow you to iterate over the results one by one and not store all of them in memory before. Otherwise, the list will fill up all your memory.

For instance, writing each pair into a file might look like:

import itertools
import csv
import pandas as pd

def generate_combination_of_questions(dataframe):
    for _, questions in dataframe.groupby('memberid'):
        yield from itertools.combinations(questions.questionid, 2)

def main(file_in, file_out):
    incorrect_questions = pd.read_csv(file_in)
    with open(file_out, 'w') as output:
        writer = csv.writer(output)
        for pair in generate_combination_of_questions(incorrect_questions):
            writer.writerow(pair)

if __name__ == '__main__':
    main(<path1>, <path2>)

But you're obviously free to do any form of processing while iterating over the generator; writing to a file is just the simplest example.


In the general case, the answer to any question regarding sed is "use something else."

Not that sed is not useful! It definitely is!  It's just that it's best for simple tasks that have compact, obvious solutions.

In particular, Perl is good at replacing sed scripts, thanks to its more expressive regular expressions and uncomplicated access to conventional programming constructs.   It even comes with an automated tool to do the translation from sed to Perl, called s2p.

perl -pli.bak -e'
    next unless s/^(\s*)(#\s*)?(?=server_names_hash_bucket_size)/$1/;
    tr/\d//d;
    s/;/64;/;
' nginx.conf

The newlines are optional and included for readability.  Line by line:

-p means "print each line after running this code against it."  This should be familiar since sed works exactly the same way.
-l means "remove newlines before running the code and reinstate them before printing."
-i.bak means "edit in-place and save the original as original.bak".
-e means the same thing as in sed.

We're only interested in lines with server_names_hash_bucket_size, so skip to the next line if the replace fails (the unmodified line still prints; we're skipping the rest of this code but not the printing).
We need to include lines that had no #, so make the # match optional with ? after (#\s*).
(?=...) is a lookahead; the text must exist but is not included in the left side of the substitution, so we don't need to include it on the right side.   Only the (optional) leading whitespace ($1) needs to be reinstated on the RHS.

tr works like y in sed.  This line is equivalent to s/[0-9]//g (as far as we're concerned.  Technically, there are digits other than 0-9 but they aren't going to appear in your nginx.conf.)
Same as sed.

You can simplify even further by recognizing that the only significant parts of a server_names_hash_bucket_size line, after you throw away the number, are the leading whitespace and terminal comments.

Preserve the indent as before, throw away as many non-comment characters as possible ([^#]*) and rewrite the line in one replace operation:

perl -pli.bak -e' s/^(\s*)(?:#\s*)?(server_names_hash_bucket_size)[^#]*/$1$2 64;/ ' nginx.conf

(?: makes that group non-capturing, so the second capture ($2) will be server_names_hash_bucket_size.

At this point, we're back in "simple enough for sed" territory:

s/^\([[:blank:]]*\)\(#[[:blank:]]*\)*\(server_names_hash_bucket_size\)[^#]*/\1\3 64;/


You can gain some efficiency by wrapping the writer in a BufferedWriter.

If you are using java 7 or better you should use try-with-resources to auto close the writer, otherwise you should use a try-finally:

try(BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))){
    //the for loops
}

with try-finally:

BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
try{
    //the for loops
}finally{
    writer.close();
}

This ensures that the writer is closed should an exception occur.

Second appending Strings for output is not the most performant thing that should be done instead pass each string separately:

writer.write(user);
writer.write(",");
writer.write(item.getItemID());
writer.write(",");
writer.write(item.getValue()
writer.newLine();//only available in BufferedWriter

As a more general suggestion there is a better method than reading the entire file doing some processing and then writing the output. Instead you can read only as far as you need to process a part of the data and then write the result out again. Whether you can depends on what you are actually doing with the data. This is only possible if you have a 1-pass transform.


Separate method for a single line code? Or embed in the caller function?

I'm guessing that your boss's argument is that a well named function would make the code more readable, and I agree with that in general. I often do that myself even when the function contains a single line.

In this particular example I would not bother though. The comment above the json-call says the same thing as the function name would, and there are no obvious advantages to make a function for a single call.

So if your question is specifically for this example, then I agree with you - keep it as it is, but if you want a more general answer, then I agree with your boss.

For example - if this one-liner is something that you use in more than one place, i.e. if calling the "processKeyVal()" function in more than one place makes sense. Then I say you should make a function of it even if it would contain only one line of code.

Or to put it another way - it is not (always) the number of code lines that should determine if you make a separate function of a code snippet.


Design

Since you want only one instance of preferences, you can make use of the singleton pattern:

var prefs = (function () {
    var instance;

    return {
        getInstance: function () {
            if (!instance) instance = new Prefs();
            return instance;
        }
    };
})();

Then you can call the method wherever needed: prefs.getInstance().

You can also encapsulate initialisation logic into a constructor, it seems like you wanted to use OOP anyway:

function Prefs() {
    // init your properties here, use 'this', e.g:
    this.answers = [];
}

Prefs.prototype.addAnswer = function (answer, correct) {
    // use 'this' just as you did in your code
};

localStorage

The way you deal  with localStorage seems ok to me. If you want, you can turn correctAnswers and wrongAnwsers into setters, tough syntax for them is a bit baroque:

Object.defineProperty(Prefs.prototype, 'correctAnswers', {
    set: function (val) {
        localStorage.setItem('correctAnswers', val);
        return val;
    }
});

Use it as you previously did: this.correctAnswers++.

Minor issues

This line is useless:

var localStorage = window['localStorage'];

You can skip toString here:

localStorage.setItem("correctAnswers", this.correctAnswers.toString());

topValue and bottomValue don't have default values. They will be NaN if there is no such item in localStorage.


Custom indexOf for strings javascript with regex

Too sad, it's not O(1).
There is a cost for:

Constructing the regex into a DFA
Calling test() or match() on the regex for the value

Complexities:

A well implemented regex construction will be O(M) where M is the length of the key.
While test/matching it afterwards will be O(N) where N is the length of the value. (best case, e.g. regexes with backtracking can result in horrible complexities)

So a couple of improvements can be:

if the key is always the same. Construct the regex for the key only once.
first start with comparing the length of the value and key before calling the more expensive test()-match() methods.
apart from that, the idea of a regex is ok but I don't know if it's the most understandable way of writing an indexOf.
Reference: Regex Complexities on SO


Some suggestions:

There's no need for the negative assertion. You're testing Ruby more than you're testing your own code and in the end, we don't actually care. It only matters that our attempt to order the results behaves as expected. Assuming they're un-ordered otherwise (or at least order isn't guaranteed).
Favor RSpec's 'let' over instance variables and constants in your tests.
RSpec's 'should' syntax will be deprecated in the next release. Favor using the new 'expect' syntax instead.
Use string literals when you can.
Use a shared example to DRY up your tests a bit.
Modify the underlying implementation and the public API in your code for better symmetry between ordering by 'interestingness' and 'qualifiedness'. I suspect there's some code duplication in there given the current API that could also be eliminated.

Do all that, and you could end up with a test that looks something like this:

shared_examples_for 'a ordered request' do |order_type, dev|
  it "orders by #{order_type}" do
    result = Request.call(:order, { order_type, :developer => dev })
    result.map! { |r| r.send("#{order_type}_for", dev) }
    expect(result).to be_in_order
  end
end

describe Request do
  let(:list_length) { 10 }
  let(:skills) { FactoryGirl.create_list(:skill, list_length) }
  let(:developer) { FactoryGirl.create(:user) }
  let(:requests) { FactoryGirl.create_list(:request, list_length) }

  before { list_length.times { |i| requests[i].skills = skills[0..i] } }

  describe '#order' do
    context 'when ordering by interestingness'
      before { developer.add_interested_skills(skills) }
      it_behaves_like 'a ordered request', 'interestingness', developer
    do

    context 'when ordering by qualifiedness' do
      before { developer.add_proficient_skills(skills) }
      it_behaves_like 'a ordered request', 'qualifiedness', developer
    end
  end
end

I'd also recommend checking out this site which is a pretty good, but still growing style guide for writing behavior tests in RSpec.


Great work overall implementing these algorithms! I really liked that you extracted some of the common pieces into methods, and even a header file! Also it's great that you're attempting these algorithms on your own, before looking at standard implementations.

For the Bubble Sort portion

The do-while is generally less readable than using a for-loop, and is preferably only used when it's very necessary - for example, if you need to ensure at least one execution of the loop.

For the Binary Search portion

A more standard-used naming convention for the variables used in binary search are:

i: low (indicating the start of the search segment)
count: high (the end of the search segment)
midval(): mid (the middle value you compute once, and compare to in a given iteration)
search: target (the value you are searching for)

You are repeating the call to the midval function several times in the code. Instead, you can compute this value once at the start of the loop, and use the computed value later on.

General comments

As you did with some parts of your code, you should also extract out separate functions for Bubble Sort and Binary Search. This not only improves reusability, but also makes your code more readable.
It will be very helpful as you learn more to look for standard implementations of different algorithms to solidify your understanding and style (after you try to implement them yourself of course!). Generally you want to write code that's readable to other people, which is easier to do when you use standard practices.


The code looks good and should work properly. Here is some feedback nevertheless.
I don't really understand why the file is named as a "lock". A lock file is typically used to prevent multiple instances of a program to run, or synchronise acess to a resource between different processes.

Usage of Timer

The Timer was effectivelly replaces by Executors, more specifically ScheduledThreadPoolExecutor as mentioned in the javadoc of Timer. Oneimmediate advantage is that you can submit tasks as Runnable with a lambda expression.

Deletion of tempFolder

Make sure that the DeepDelete.deepDelete(tempFolder); does not fail if tempFolder doesn't exist. If the application terminates due to an error (such as the failure to write to tempFolder, you would have a second exception.

Duplicated code

Extract the following to a method, which appears twice. It will also do always the error handling:

   private static void writeFile(Path tempFolder) {
    try {
        Path lockFile = tempFolder.resolve(LOCKNAME);
        Files.write(lockFile, ByteBuffer.allocate(Long.BYTES).putLong(System.currentTimeMillis()).array());
    } catch (IOException e) {
        System.err.println("Failed to secure avaliability of temp folder, exiting!");
        e.printStackTrace();
        System.exit(-1);
    }
}

Hardcoded values

Define hardcoded values in constants. It will be easier to maintain.

private static final Integer DELAY_MS = 60_000;
private static final Integer DELETE_THRESHOLD_MS = 5 * 60_000;

Read safely

ByteBuffer.wrap(Files.readAllBytes(lock)).getLong() < currentTime - 60_000 * 5;

The entire file will be read to memory and only then the first Long.BYTES bytes are read as a long. This could be a problem if the file happens to be very large, even though it's not expected.
It would be better to only read the first Long.BYTES of the file.

Inconsistency?

Looking at

if (!Files.isRegularFile(lock))
  return true;
try {
  return ByteBuffer.wrap(Files.readAllBytes(lock)).getLong() < currentTime - 60_000 * 5;
} catch (IOException e) {
  e.printStackTrace();
  return false;
}

There seems to be an inconsistency. If the file doesn't exist, the directory is kept. If the file exists but its content is unexpected, we delete the directory. Both situations represent a corrupted temporary folder of the program and it seems to me that both situations should have the same handling.


Instead of pushing to an array outside of the map function, just return obj.get() in each callback and use the return value of the map call.


Optimise nested loops used to compare champions which have abilities which have effects

Well the inner loop is something like 120*5*5 => 1200 cycles and I really don't know if it can become an issue with today's PC power. But improvements can always be made, and reading your code, I see that some lines are duplicated :

   foreach (CounterChampion champion2 in returnList)
    {
        foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))
        {

As as first step toward performance and code structuration, I suggest to compute the ability/effect in returnList once, and reuse it after. Typically, you may have something like this :

class EffectByChampion{
  CounterChampion Champion,
  List<string> Effects
}

then you may fill the following list ONCE

List<EffectByChampion>

and after you may reuse it 3 times through your existing code with :

    foreach (string effects1 in ability1.Effects)
    {
      foreach(EffectByChampion effectByChampion in EffectByChampionList)
      {
       foreach(string effects2 in effectByChampion)

This way, you have 3 foreach loops removed.
Hope this help !


Your solution seems to work fine fine for square matrix(where n = m). However, when presented with non-square matrix, the result becomes purely sporadic. This may or may not be problematic, depending on which kind of matrix you have to deal with.
Modulo % is quite expensive.
You are copying the array item by item. It is not the best way to it, especially when you are copying a continuous section within an array (where m > 1)
You should cache the result of values.GetLength(0), and more importantly values[0].GetLength(0), as they are expensive.

public static IEnumerable<T[,]> ViewAsNByM2<T>(this T[,] values, int n, int m)
{
    int height = values.GetLength(0), width = values.GetLength(1);
    int rows = height / n, columns = width / m;

    for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns; column++)
        {
            var matrix = new T[n, m];
            for (int i = 0; i < n; i++)
            {
                Array.ConstrainedCopy(
                    values, (row * n + i) * width + column * m,
                    matrix, i * m,
                    m);
            }
            yield return matrix;
        }
    }
}


Generic object pooler implementation for Unity prefabs

Interesting code! Am about to write something similar for a quite extreme case (decoration elements for procedurally generated terrain) so I could share a few thoughts I had:

That mechanism for prePooledObjects feels a bit too entwined with the pooling system itself. Why not provide a single function like:

PrePoolObjects(GameObject go, int count);

That would directly prepool a number of objects without the need for that extra struct and all that. Your concept is only necessary if you really want to provide the information what needs to be prePooled a single time and also clear the pool regularly for some reason.

Consider adding more than one new object when the queue is empty. For memory access reasons, it tends to be faster to instantiate multiple instances one after another than to instantiate multiple times at separate times.

Together with the above, it might make sense to shrink the number of pooled objects over time. At least if there are rare moments when a ton of a particular object is needed.

A really, really smart pooling system would evaluate the size of the pool constantly in the background (for example once every 5 physics updates) and ensure that there are not too few and not too many objects held "in stock". Important for that is a hysteresis, because of course you do not want to immediately grow the pool whenever a single instance was removed from it and vice versa. Only when it is too full or too empty for a certain period of time, it would start destroying or creating instances. Such a system would nicely adapt to the current need and not load up the memory when a single level progresses.
Admittedly this concept might be more necessary for my infinite-terrain game than for a game that's based on levels where you can flush the pool when switching scenes.

Last but not least: Using .name and perform that dictionary search every time could be replaced with custom constants that just hold an int and are the indices in an array/list of pool queues.
Then instead of providing the prefab to the GetPooledObject call, you provide that int constant and it takes the relevant queue from the array/list without any lookup operation.
The downside of this concept is the slight inconvenience of not being able to use prefabs immediately but first needing to define that constant. Also that might make using drag and drop with the prefabs more complicated or impossible.


Is there some way of taking advantage of code reuse in this example?

You can absolutely refine the code to reuse the for loop. You can put the for loop in a function, which take the int value as input and return the index of value. Let's call it "iteration". If not found the value in elementData, just return -1 instead.

public int getIndex(int value) {
    for(int count = 0; count < size; count ++) {
        if(elementData[count] == value) {
            return count;
        }
    }
    return -1;
}

In your remove function, if you get -1 as the return value of the "iteration" function, do nothing. If you get a positive value, remove elementData[index]. Similar in the contains function.


Concatenate the square of all the digits of a number

Separate out combinators that apply some perspective to your data.

squareDigit = overAbs $ overDigits $ concatMap $ digs . (^ 2) where
  overAbs f n = signum n * f (abs n)
  overDigits f = foldl (\acc x -> x + (acc * 10)) 0 . f . digs


Looking at the hill of indents seems like this can be improved

As we do not know the task given we cannot fully review. While the code itself looks reasonable there is some smell.
date
To me it is very smelly, that a function named id() returns a date
start_date = ids('DIR', '348')

This is also requiring a switch inside your function, so most probably there are two functions intermingled that should not be.
data structure
list() is a bad structure to search in. While this may be the data format you read or get passed, you most probably should convert it to a structure allowing direct lookup (converting once). The description of the current structure is missing, also we do not know if there are other functions accessing the data.


I've never played with mysql, so this may be completely wrong, but if I get it right the WHILE loop would be the equivalent of a T-SQL CURSOR, which is inherently slow.

You're essentially looping on payment_id, incrementing at each iteration - this assumes the ID's are contiguous, which isn't a safe assumption to make with data: if records were deleted, you have more iterations than records:

SET @start = (SELECT MIN(payment_id) FROM payment);
SET @stop  = (SELECT MAX(payment_id) FROM payment);

WHILE @start <= @stop
DO
    UPDATE payment AS p
        INNER JOIN customer AS c
            ON p.customer_id = c.customer_id
    SET real_payment = (p.amount * c.multiplier)
    WHERE p.payment_id = @start;
    SET @start = @start + 1;
END WHILE;

In pseudo-code, this can read as follows:

For each payment_id in payment...
... update the real_payment column to p.amount*c.multiplier

I don't see why you need a loop to do this, I think this would be equivalent... and faster:

UPDATE payment AS p
    INNER JOIN customer AS c
        ON p.customer_id = c.customer_id
SET real_payment = (p.amount * c.multiplier)


Just a quick shot
This

public override bool Equals(object obj)
{
    return base.Equals(obj);
}
public override int GetHashCode()
{
    return base.GetHashCode();
}

doesn't buy you anything. Overriding a method and the calling the base method is just rubbish which lays around in the codebase.


Accessing parent isolated scope in directive

In your HTML

  <form>

          <input required-role/>
          <input required-role/>
          <input required-role/>
          <input required-role/>
          <input />

              <input required-role/>

          <input required-role/>
          <input required-role/>
          <input required-role/>
          <input required-role="Admin"/>

      <button required-role="Admin">Save</button>
      <button required-role="User">Send to review</button>
  </form>

You create a div just to inherit from it, this is bad practice, unless there is more than one element inside that div that is going to inherit from the div

in the second group of code you actually do it the right way, not sure why you were inconsistent with the first block.

you should write it like this

<form>

        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input />
        <input required-role="User"/>

        <input required-role/>
        <input required-role/>
        <input required-role/>
        <input required-role="Admin"/>

    <button required-role="Admin">Save</button>
    <button required-role="User">Send to review</button>
</form>

I also assume that this is Example HTML as you don't give any of those input tags ID's  which makes them unusable.

In your Javascript

  var getRequiredRoleFromParent = function(element){
      var par = element.parent();
      if (!par) return;
      var is = par.isolateScope();
      if (is && is.requireRole) return is.requireRole;
      return getRequiredRoleFromParent(par);
  };

You could take the negative check out of there, it doesn't make sense that way, instead perform a positive check, if it's true then you can perform what is after that.

The "after that" stuff should be changed to a ternary statement, it looks cleaner to me and it is equivalent.  It is slightly nested but it shows the flow of the code brightly.

var getRequiredRoleFromParent = function(element){
    var par = element.parent();
    if (par) {
        var is = par.isolateScope();
        return (is && is.requireRole)
            ? is.requireRole
            : getRequiredRoleFromParent(par);
    }
};

The Recursion of this function looks good, I don't see an issue with the recursive nature of this function.


using namespace std; is a bad habit. It's not that tedious to write std:: a few times and you get less name collisions on things you define.

Your indentation is inconsistent. This makes it difficult to follow the control flow.

The even parity can be discovered with repeated xors:

int has_even_parity(int c) {
   c ^= c >> 4;
   c ^= c >> 2;
   c ^= c >> 1;
   return ! (c&1);
}

short int l_ = 0b0000000;
c_ = l_ | c_;

This doesn't do anything.

I suggest adding some underscores in the binary literals to group the digits:

unsigned short int mask = 0b0111_1111_1000_0000;

This makes it easier to tell at a glance that there are 7 zeros at the end and that you meant for them to be there. Though once you are more comfortable with hexadecimal then 0x7f80 is just as clear.


Printf format

I noticed that at the end of your program you had 3 cases due to trying to print the number of cents out correctly.  You can do it all in 1 case by using the %02i format.  This format prints an integer with 2 digit width and pads the leading digits with zeros.

Simplifying the logic

Right now, your logic for each denomination gets more and more complicated as you go along because you are subtracting more and more things from the total on each step.  If you simply subtracted the amount from the total right away, you wouldn't have to repeat it on each step.  For example:

int getHundreds = getDollars / 100;
getDollars -= getHundreds * 100;
int getFifties = getDollars / 50;
getDollars -= getFifties * 50;
int getTwenties = getDollars / 20;
getDollars -= getTwenties * 20;
// etc.

Using functions

Now that you have simplified the logic, you can put that logic into a function.  For example:

/**
 * @param        pAmount          Points to amount of money.  Returns the amount
 *                                minus the amount used up by this denomination.
 * @param        denomination     The value of this denomination.
 * @return                        The number of units of this denomination.
 */
int makeChange(int *pAmount, int denomination)
{
    int ret = *pAmount / denomination;

    *pAmount -= ret * denomination;
    return ret;
}

int main(void) {
    // ...
    int remainingDollars = getDollars;
    int getHundreds = makeChange(&remainingDollars, 100);
    int getFifties  = makeChange(&remainingDollars,  50);
    int getTwenties = makeChange(&remainingDollars,  20);
    // etc.
}

Reducing the number of variables

Since you aren't actually printing out how many of each bill/coin you are using, you don't need so many variables.  You only actually need to know how many bills plus coins you need.  So you could change your code to:

    int remainingDollars  = getDollars;
    int numBillsPlusCoins = 0;

    numBillsPlusCoins += makeChange(&remainingDollars, 100);
    numBillsPlusCoins += makeChange(&remainingDollars,  50);
    numBillsPlusCoins += makeChange(&remainingDollars,  20);
    // etc.

Using arrays

There's still a lot of repetition.  It would be nice to not have to copy/paste one line per denomination.  You can use arrays to handle each denomination in a loop instead.  You just need to create an array with the possible bill denominations and one for the coin denominations.

Some other miscellany:

I added my own GetFloat() function because I don't have whatever library you are using.
I removed the use of roundf() and just did the rounding myself.
I used a DIM() macro which returns the dimensions of a given array.  You will encounter this in C a lot for loops which need to loop over a statically defined array.

Here is the final code:

#include <stdio.h>

#define DIM(array)        (sizeof(array)/sizeof(array[0]))

float GetFloat(void)
{
    float ret = 0;
    scanf("%f", &ret);
    return ret;
}

/**
 * @param       pAmount         Points to amount of money.  Returns the amount
 *                              minus the amount used up by this denomination.
 * @param       denomination    The amount for this denomination.
 * @return                      The number of units of this denomination.
 */
int makeChange(int *pAmount, int denomination)
{
    int ret = *pAmount / denomination;

    *pAmount -= ret * denomination;
    return ret;
}

int main(void)
{
    // declare float
    float money;
    const int billDenominations[] = { 100, 50, 20, 10, 5, 1 };
    const int coinDenominations[] = { 25, 10, 5, 1 };

    // Get user input and check if input is positive
    do
    {
        printf("Please input the some amount of money you would like to "
                "make change for:  \n");
        money = GetFloat();
    } while (money < 0);

    // Get the Dollars from the Float
    int numDollars = (int) money;

    // Get the cents from the Float (rounded to nearest cent)
    int numCents = (int) ((money - numDollars) * 100 + 0.5f);

    int remainingDollars = numDollars;
    int remainingCents   = numCents;
    int numBillsAndCoins = 0;

    // Greedy Algorithm for Dollars
    for (int i = 0;i < DIM(billDenominations);i++)
        numBillsAndCoins += makeChange(&remainingDollars, billDenominations[i]);

    // Greedy Algorithm for Cents
    for (int i = 0;i < DIM(coinDenominations);i++)
        numBillsAndCoins += makeChange(&remainingCents, coinDenominations[i]);

    printf("\nThe least possible steps you can make change from "
            "$%i.%02i is %i. \n", numDollars, numCents, numBillsAndCoins);
}


Python RPC Design Pattern - is bidrectional coupling a good idea?

On the coding side, every Node has an attribute Server and the Server has a reference to the Node it belongs to. Node calls Server's methods, and Server reads Node's attributes, so they currently are inseparable classes. I would suggest refactoring this, and - personally - I would just merge the two classes.
I'm also not sure why RpcCall needs to be a callable class, other than for the sake of enforcing OOP. It looks like a simple function (or another method in Node) would do just as well. Then again, maybe your real scenario needs it to be a separate class.
for neb in self.neb_ports:
    await self.replicate(...)

This line defeats the purpose of asyncronous IO, because you are waiting for each call to finish before starting the next one. You could look into Asyncio.gather to start and await multiple such calls in parallel instead of sequentially.

Regarding reliability, you - unfortunately - have none. If one node fails, it will bring peer-nodes down at the next attempt to sync the key-value store. The reason is that you are awaiting a function that will timeout and raise and Exception if a connection can't be established. You are not handling this exception anywhere, so the calling node will halt. If keys are updated often enough, your entire cluster will die due to this.
If a connection can be established, I'm not sure what will happen if either node dies. I briefly searched aiomas, but couldn't find related documentation. My guess is that the call will just hang indefinitely. This is potentially worse than a clean crash because your node will be leaky and silently suffer a death by a thousand cuts. Log messagees (if any) will likely point you into the wrong direction, making this problem hard to debug.
On the point of fault-tolerant because "there is no data loss because nodes replicate preemptively" it really isn't just that simple.
The sore point is the hierarchy among nodes, or rather the lack thereof. If the network for one node dies temporarily, it won't receive any further updates. To the node, the faulty network and not getting state changes look alike, so it will continue running happily. To the other nodes of the cluster it looks like the node died, and - assuming you add exception handling - they will continue to change state jointly. After the network issue is resolved, the lost node will reappear in the cluster and continue serving happily. However, it is now out of sync and will serve potentially outdated key-value pairs or report missing values for new ones that were set during the network outage.
Assume this happens to multiple nodes; you'll end up with a heterogenious cluster and - because you lack hierarchy among your nodes - it is impossible to say what the correct state should be. Currently, you can't differentiate the order in which state-changes occurred, so rebuilding the state is ambiguous. You will need to define merging and conflict resolution mechanisms to re-establish synced state.
You may also wish to establish a heartbeat for the cluster so that a node can discover connection issues. How it should handle them is context-dependent, but an easy first idea is for the node to simply suicide.
Instead of creating a homebrew design-pattern for this, it may be easier to follow an established consensus method such as RAFT or PAXOS. This will take care of a lot of edge cases and may make your life considerably easier.


Binary search that gets ALL matching results

Unless I wrongly understood your question (like if you want to use binary search), it seems you merely look for the fastest solution.

I was curious to try with what I found the simplest method, using a filter:

function getBrandsSimple(letter) {
  return brands.filter( item => item.name.charAt(0).toLowerCase() == letter);
}

Then I created a big array of 3000 items from 15 brands with 200 ids each, and tested your solution getBrands against the simple one above getBrandsSimple.
The results are:

not surprisingly the time needed by getBrands differ considerably depending on the choosen letter (and also depending on the array order, see below)
obviously, at the opposite the time needed by getBrandsSimple is rather constant
in the worst case I noticed, getBrandsSimple needs less than 2x the time needed by getBrands
in other cases, getBrands may need till 4x the time needed by getBrandsSimple

In additon, getBrands often returns wrong results.
From the definition of my test array, each case should return exactly 200 items, while getBrands frequently returns only 196 items, and sometimes only 1.

Moreover, I added an option to shuffle the array: then getBrands returns most often only 1 result or no result at all (undefined)!
I didn't dive into your code to look for what turns wrong.

You may check all that using this snippet:

var brandsList = [
      'Apple',
      'Basketball',
      'Cooking',
      'Dinosaurs',
      'ES6',
      'Features',
      'Golf',
      'Highlighting',
      'Informatics',
      'JSON',
      'KiloBytes',
      'Lambda',
      'More...',
      'Nothing',
      'Original',
    ],
    filler = new Array(200).fill(''),
    brands = brandsList.reduce( (result, brandName) =>
      result.concat(
        filler.map((item, index) => {
          return {name: brandName, id: index + 1};
        })
      )
    , []);

getBrandsSimple = function(letter) {
  return brands.filter( item => item.name.charAt(0).toLowerCase() == letter);
}

getBrands = function(letter) {
    let brands = this.brands,
        _firstLetter = brand => {
            if ('hasOwnProperty' in brand && brand.hasOwnProperty('name')) {
                return brand.name.slice(0, 1).toLowerCase();
            }
            return false;
        },
        _traverse = (up, arr, i) => {
            let store = [],
                direction = up ? 1 : -1;
            while (_firstLetter(arr[i]) === letter) {
                store.push(arr[i]);
                i = i + direction;
                if (typeof arr[i] === 'undefined') {
                    break;
                }
            }
            return store;
        },
        _each = (arr, callback) => {
            let i = 0,
                len = arr.length - 1;
            while (++i < len) {
                callback(arr[i]);
            }
        },
        _compare = (brand, letter) => {
            let brandLetter = _firstLetter(brand);
            if (brandLetter === letter) {
                return 0;
            } else if (brandLetter < letter) {
                return 1;
            } else if (brandLetter > letter) {
                return -1;
            }
        },
        _all = (arr, i) => {
            let store = [],
                down = false,
                up = true;
            _each(_traverse(down, arr, i - 1), match => {
                store.push(match);
            });
            _each(_traverse(up, arr, i + 1), match => {
                store.push(match);
            });
            store.push(arr[i]);
            return store;
        },
        _binarySearchAll = (arr, val, compare) => {
            let start = 0,
                stop = arr.length - 1,
                mid = (start + stop) >> 1;
            while (start < stop) {
                let result = compare(arr[mid], val);
                if (result === 0) {
                    return _all(arr, mid);
                } else if (result > 0) {
                    start = mid + 1;
                } else if (result < 0) {
                    stop = mid - 1;
                }
                mid = (start + stop) >> 1;
            }
        };
    return _binarySearchAll(brands, letter, _compare);
}

function exec(funcName, func, letter) {
  console.time(funcName);
  result = func(letter);
  console.timeEnd(funcName);
  if (result) {
    // console.log(result.length + ' items:', result);
    console.log(result.length + ' items');
  } else {
    console.log(result);
  }
}

function shuffle(a) { // (thanks to http://stackoverflow.com/a/6274381/3415269)
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

var letter = prompt('Enter a letter', 'j');
if (confirm('Shuffle the brands array?')) {
  shuffle(brands);
}
exec('getBrands', getBrands, letter);
exec('getBrandsSimple', getBrandsSimple, letter);


Some initial comments:

Good use of string slicing to extract each field, though ideally we should not need to make a copy of the string. I propose a different way of doing this below.
while len(temp): works, but a more Pythonic way of writing this would be while temp: because any object can be tested for a truth value in Python, and non-empty strings evaluate to true.
A popular new way of string interpolation introduced in Python 3.6 is the f-string. So instead of 'tag: {}'.format(temp[0:2]) you could do f'tag: {temp[0:2]}' which I personally find much easier to read.

To avoid copying the string tlv we can instead work with an iterator over the characters in the string, i.e. iter(tlv). Then we can use itertools, a nice built-in library for working with iterators, specifically itertools.islice to extract/consume chunks of arbitrary length from the iterator:

from itertools import islice

TAG_FIELD_LENGTH = 2
LENGTH_FIELD_LENGTH = 3

def tlv_parser(tlv_string):
    it = iter(tlv_string)
    while tag := "".join(islice(it, TAG_FIELD_LENGTH)):
        length = int("".join(islice(it, LENGTH_FIELD_LENGTH)))
        value = "".join(islice(it, length))
        yield (tag, length, value)

Notes on the above:

The strategy of parsing is very similar to yours, with the only difference being that we're working with an iterator of characters, and we're consuming from the iterator chunk by chunk so we don't need to calculate indices for field boundaries.
We're concatenating the characters in each iterator to a string with "".join(...), i.e. str.join.
:= is the "walrus operator" (introduced in Python 3.8) that binds values to variables as part of a larger expression, so we're binding the value of "".join(islice(it, TAG_FIELD_LENGTH)) to tag and at the same time testing its truth value.
The yield keyword makes tlv_parser a generator of 3-tuples of (tag, length, value).

Example usage:

>>> tlv = "01011Lorem ipsum02014dolor sit amet03027consectetur adipiscing elit"

>>> for t in tlv_parser(tlv):
...     print(t)
...
('01', 11, 'Lorem ipsum')
('02', 14, 'dolor sit amet')
('03', 27, 'consectetur adipiscing elit')

>>> for tag, length, value in tlv_parser(tlv):
...     print(f"tag: {tag}")
...     print(f"length: {length}")
...     print(f"value: {value!r}\n")
...
tag: 01
length: 11
value: 'Lorem ipsum'

tag: 02
length: 14
value: 'dolor sit amet'

tag: 03
length: 27
value: 'consectetur adipiscing elit'