Eliminating repetitions of subsequent items in a list

While aepot answer is a good answer and got my upvote it does only work for type int.  Which I know the question for an example uses int in their code but if wanting it to work for all data types will need to change the code a bit.
public static class EnumerableExtensions
{
    public static IEnumerable<TSource> FilterRepeatingElements<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                var item = enumerator.Current;
                yield return item;

                while (enumerator.MoveNext())
                {
                    if (!comparer.Equals(item, enumerator.Current))
                    {
                        item = enumerator.Current;
                        yield return item;
                    }
                }
            }
        }
    }

    public static IEnumerable<TSource> FilterRepeatingElements<TSource>(this IEnumerable<TSource> source)
    {
        return FilterRepeatingElements(source, EqualityComparer<TSource>.Default);
    }
}

This would work for any type and takes the same parameters as linq Distinct does since we are doing a "kind of" distinct.
var data = new int[] { 1, 12, 3, 3, 3, 8, 5, 5 };
var postData = data.FilterRepeatingElements().ToArray();

var items = new string[] { "A", "A", "B", "C", "C", "D", "D" };
var postItems = items.FilterRepeatingElements().ToArray();


Remove last odd number from number list in Python

By my interpretation, if the list contains no odd numbers, then the function should make no change.  Your first function, since it unconditionally ends with numbers.pop(max), will crash with an UnboundLocalError: local variable 'max' referenced before assignment.

count += 1 is awkward.  Counting loops are normally written using some kind of range() or enumerate().

The first implementation is inefficient, since it examines the entire list from the beginning.

The second function, as you noted, is inefficient in that it makes two copies of the list.  Furthermore, rev_num.remove(num) is fully O(n): it performs another linear search, and then it copies the rest of the elements to fill the hole.

I would write a solution this way.  This function mutates the list, and also indicates which index was removed, if any.

def remove_last_odd(numbers):
    for i in range(len(numbers) - 1, -1, -1):
        if numbers[i] % 2:
            numbers.pop(i)
            return i
    return None

Here is another way to do it, using enumerate() and reversed(), which iterates backwards without copying the list.  Note that it returns a negative index.

def remove_last_odd(numbers):
    for i, num in enumerate(reversed(numbers), 1):
        if num % 2:
            numbers.pop(-i)
            return -i
    return None


Bugs in nonContiguous

If your input string contains spaces then your nonContiguous function produces arbitrary output regardless of whether you are correct or not.

False positive: As mentioned in the comments, input string "X Z" will print as a non-contiguous subset of itself.
False negative: What if the input string is "   " (three spaces)?  When you build a substring of the first space with the third space this should still count as a non-contiguous subset.

Other problems

Base case: If input="" then your base case of recursion (substring.length() == 1) does not work.
Naming: substring is not a good name for the parameter in your function.  While the name does indicate what the value represents, its name may confuse someone into thinking that it holds the non-contiguous substring when really it just holds the unvisited portion of the original string.  For a lack of a better name, I will simply call this value str.

Another approach

This is a fairly poor analogy but here it goes anyway.  What if I told you to flip through a deck of cards and tell me if there are any Jokers?  Which approach do you think is better?

A) When you see a Joker you insert a Queen into the deck after the Joker and look for that Queen afterwards (not knowing if there were any Queens in the original deck or not).
B) When you see a Joker you write down that you saw a Joker on a scratch sheet of paper.

I hope we can agree that B is the simpler approach.  In this case the Jokers are simply gaps between characters chosen from the input string.

The problem with integrating this logic with your approach is the order in which the recursion is performed.  You know when you skip a character (currently when you are adding a " ") but you need to know that another character is added after the skip for you to declare the string as non-contiguous.  The method is shown below:

public static void main(String[] args) throws java.lang.Exception
{
    /** Parses input and calls powerSet method with input */
    String input = "abcde";
    nonContiguousSubstrings("", input, true, false);
}

public static void nonContiguousSubstrings(String base, String str, boolean contiguous, boolean skipped)
{
    // This stop condition is simpler and safer.
    // If the original input is empty it stops the recursion here
    if (str.length() == 0)
    {
        // only print the string if it is not contiguous
        if(!contiguous)
        {
            System.out.println(base);
        }
    }
    else
    {
        // This is the recursion where we skip a character here
        // Set skipped only if we already had a character in base
        // Even if we already had a character in base, we cannot say this skip makes the string non-contiguous unless we add a character to it later
        nonContiguousSubstrings(base, str.substring(1), contiguous, base.length() != 0);

        // Below is the recursion where we add a character here
        // Since we are adding a character to the string, set contiguous to false if we skipped a character previously, otherwise retain its value.
        contiguous = contiguous && !skipped;
        nonContiguousSubstrings(base + str.charAt(0), str.substring(1), contiguous, skipped);
    }
}

Yet Another Approach

By restructuring the recursion we can remove the skipped parameter.  The trick is to use recursion only when needed.  Iteration suffices to skip indices but we "must" recurse to choose an arbitrary number of elements from input.

Here is a simple substring printer (powerset) using this method:

public static void main(String[] args) throws java.lang.Exception
{
    String input = "abcde";

    // Initially the substring is empty
    allSubstrings(input, "");
}

public static void allSubstrings(String str, String substring)
{
    for (int i = 0; i < str.length(); i++)
    {
        // For each i, we skip i characters when generating the substring
        allSubstrings(str.substring(i + 1), substring + str.charAt(i));
    }

    System.out.println(substring);
}

Now you just want to be able to detect if there is a gap in each substring.  This can be done quite simply if you keep track of whether you ever add a gap.  Use a boolean instead of manipulating the string.

public static void main(String[] args) throws java.lang.Exception
{
    String input = "abcde";

    // Initially the substring is empty and deemed contiguous
    nonContiguousSubstrings(input, "", true);
}

public static void nonContiguousSubstrings(String str, String substring, boolean contiguous)
{
    for (int i = 0; i < str.length(); i++)
    {
        // There is a gap here iff i doesn't equal 0 (we skip characters) AND we are not creating the first character of the substring.
        boolean gapHere = (i != 0) && (substring.length() != 0);

        // The substring is still contiguous iff it was already contiguous and there is no gap here
        nonContiguousSubstrings(str.substring(i + 1), substring + str.charAt(i), contiguous && !gapHere);
    }

    if(!contiguous)
    {
        System.out.println(substring);
    }
}


Iterating in Python

In Python if you find yourself writing something like:

while index < (length):

There is good chance you are not writing Pythonic code.  Looping over an index is just not needed that often.  I will start with showing some ways to improve your code.  And then at the end will show a more Pythonic solution.

I would suggest changing your looping statement to:

for index, di_dah in enumerate(morse_code.strip() + ' '):

enumerate() is used to iterate over an object and give the index of of the current element.  The str.strip() removes leading and trailing spaces, and the + ' ' at the end removes the need special casing after the loop.  This fairly simple change can greatly simplify the code needed inside the loop:

def decodeMorse2(morse_code):
    clear_text = ''
    char = ''

    for index, di_dah in enumerate(morse_code.strip() + ' '):
        if di_dah != ' ':
            char += di_dah
        elif char:
            clear_text += MORSE_CODE[char]
            char = ''
            if index < len(morse_code) - 2:
                if morse_code[index: index + 3] == '   ':
                    clear_text += " "

    return clear_text

More Pythonic?

I don't have access to the test cases, but I read the spec I think this would do the job:

def decodeMorse(morse_code):
    return ' '.join(
        ''.join(MORSE_CODE[char] for char in word.split())
        for word in morse_code.strip().split('   ')
    )

How does this work?

This code uses two nested loops in the form of generator expressions.  It uses str.split() to initially split the words in the outer loop and then again to split the characters in the inner loop.  Then does a character lookup and finally uses str.join() to build the sentence.


The code is not a bad implementation of Quicksort but it has a flaw, inherent to the Quicksort algorithm, that you can easily fix.  I tested the code with this main:

const int testsize = 100000;

int main(void)
{
    int tab[testsize];
    int i;

    for(i = 1; i < testsize; i++)
        tab[i] = i;

    tab[0] = testsize+1;
    quickSort(tab, 0, testsize-1);
    return 0;
}

As you can see, this is deliberately the worst case scenario for Quicksort in which it takes \$O(n^2)\$ time to sort.  This code took 11.85 seconds on my machine.  Quicksort works best on randomly arranged data, so paradoxically, you can often actually improve sorting time by randomly shuffling the data before you start.  I wrote this rather simple-minded shuffle routine:

void shuffle(int tab[], int begin, int end)
{
    for (; begin < end/2; ++begin)
        swap(tab, begin, rand()%end);
}

When I inserted a call to shuffle() just before the call to quickSort() in main, the time to sort the same data dropped to 0.026 seconds.  By comparison, the standard qsort() sorts in 0.006 seconds on this same machine.

Also, more generally, I'd be inclined to pass two pointers to swap rather than an array and two indices.  The code may be very slightly faster, but it's certainly more general.

The code could also be made more general by using the same parameters as the qsort() routine in <stdlib.h> but then, that's already written. :)


A vs. B type questions are seldom good questions for a code review. Often the answer is "C".

That's true this time too.

You don't need a go routine for the "ticker".
Your second implementation only waits for 1 second, instead of 2.
your "quit" channels don't need to be buffered

Why don't you just do:

func main() {
    for t := range time.NewTicker(2 * time.Second).C {
        periodicFunction(t)
    }
}


Pretty print directory structure in a JSON recursively

You could take a single loop without reversing the array and hand over the prefix for the next level indentation.

const
    print = (data, indentation, prefix = '') => data
        .map(({ name, data }) => Array.isArray(data)
            ? prefix + name + '\n' + print(data, indentation, (prefix || '|') + '_'.repeat(indentation))
            : prefix + name
        )
        .join('\n'),
    dirStructure = [{ name: 'root_dir', data: [{ name: 'dir_a', data: [{ name: 'file_00.txt', data: 'file_00 content' }, { name: 'dir_b', data: [{ name: 'dir_c', data: [{ name: 'file_01.txt', data: 'file_01 content' }, { name: 'file_02.txt', data: 'file_02 content' }, { name: 'file_03.txt', data: 'file_03 content' }, { name: 'file_04.txt', data: 'file_04 content' }] }, { name: 'file_05.txt', data: 'file_05 content' }, { name: 'file_06.txt', data: 'file_06 content' }] }, { name: 'dir_d', data: [{ name: 'file_07.txt', data: 'file_07 content' }, { name: 'file_08.txt', data: 'file_08 content' }] }] }] }],
    result = print(dirStructure, 2);

   console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Your comments don't help much.  They should explain why you're doing what you're doing, not just paraphrase the code.  If you can't tell the reader anything more than the code already does, then a comment is pretty much just noise.
setUpDom() should probably be private.  Or possibly, done away with altogether, and its contents moved into one of the other methods.  It's doing stuff that looks like it should only be done once per XML document, and thus either once over the whole lifetime of the object or once each time you parse.  But it shouldn't be done by anything but your code.
If you can't handle an exception, you shouldn't be catching it.  And "printing a stack trace" is not handling.  :P

Once setUpDom() fails, the object is broken, so it doesn't make much sense to continue.  Let the exceptions propagate (declaring them in a throws clause instead), or throw your own exception type that describes what went wrong, including e as the inner exception.
You don't need to check that nl is an object, or worry about the length.  The Document class should always hand you back a NodeList, and your for loop will already loop 0 times if the list is empty, as the condition i < nl.getLength() will be false before the very first iteration.
The getSpell function and Spell class don't seem to be here.  So there's not a whole lot more to say, other than "fix your indents".  (I half-expect that that is a copy/paste issue, but it should still be mentioned.)

It does appear that Spell has some static variables, though, which is usually not a great solution.  And you're hard-coding where the data comes from and where it goes.

I'd personally suggest a SpellBook class or the like, that holds spells.  You could pass an instance of such a type (and the name of the XML file) either to your constructor or to parse.  Among other things, that leaves open the possibility for multiple sets of spells.

If that's one of your classmates' part, though, and you can't change that...eh.  Carry on.


That's a pretty good start, however I noticed that your code only works on letters. For non-alphabetic characters it returns confusing results e.g. encrypting and decrypting ! gives you ;. I can think of three good ways to handle non-alphabetic characters:

Ignore them
Use ASCII codes to shift them as well (so Z shifted right one becomes [)
Raise an error

Any of those approaches will ensure that decrypting and encrypting are inverses (which should be a property of any cipher!). That also leads you to a nice way to refactor your code: decrypting with a shift of 5 is the same thing as encrypting with a shift of -5. Try rewriting your code to look like this:

def encrypt(str)
  str.split('').map { |char| round(char, @shift) }.join
end

def decrypt(str)
  str.split('').map { |char| round(char, -@shift) }.join
end

private
def round(char, shift)
  # ...
end

Other than that, just a couple tips:

Ways to compare ranges of characters: /[a-z]/i =~ chr or (?A..?Z) === chr
What if @shift is greater than 26? You can use modulus % to account for shifts of any size


Your code is not thread-safe. You should use ConcurrentHashMap instead of HashMap, if this code is ever run in a multithreaded environment.

In Java 8 there was a terrible performance bug in ConcurrentHashMap.computeIfAbsent, which would lock the whole map even if the key already exists. That bug has been fixed in Java 9. See also this question.


I would use newtype instead of data to define Angle, like this:

newtype Angle a = Radians { angleValueRadians :: a }

This will automatically create the angleValueRadians function to get the angle value, and will be a bit more efficient.

Here is a good answer explaining the differences between data, newtype, and type: https://stackoverflow.com/a/21081227/1525759

You could use function composition to define many of your functions instead of pattern matching (pattern matching isn't bad, I just prefer this style):

sinAngle :: (Floating a) => Angle a -> a
sinAngle = sin . angleValueRadians

Also, if you made Angle an instance of Applicative, you could define addAngle like this:

addAngle :: (Floating a) => Angle a -> Angle a -> Angle a
addAngle r1 r2 = (+) <$> r1 <*> r2
-- or even this, because `f <$> x <*> y` is the same as `liftA2 f x y`:
addAngle = liftA2 (+)

Here's how you could do that:

instance Functor Angle where
    fmap f (Radians x) = Radians (f x)

instance Applicative Angle where
    pure = Radians
    Radians f <*> r = fmap f r


Styling and readability

Your indentation is inconsistent. This can lead to developers wrongly assuming code belongs to a different block. I would recommend fixing this for all code.

Your use of whitespace is inconsistent. You sometimes use a space after a comma, you sometimes do not. You sometimes use spaces around operators, you sometimes do not.

Re-inventing the wheel

Your function roundNumber is somewhat re-inventing the wheel. You are basically recreating the toFixed function with a cast back to a number.

function roundNumber(num, places) {
  return Math.round(num * Math.pow(10, places)) / Math.pow(10, places);
}

function roundNumberFixed(num, places) {
  return Number(num).toFixed(places);
}

function roundNumberFixedAsNumber(num, places) {
  return Number(Number( num ).toFixed(places));
}

function test(num, places) {
  console.log("== Testing with", num, "and", places, "==");
  console.log(roundNumber(num, places));
  console.log(roundNumberFixed(num, places) );
  console.log(roundNumberFixedAsNumber(num, places));
}

var testvalues = [["1.234567", 3],
                  [" 1      ", 2],
                  ["123512.2", 2],
                  ["-55.2121", 5],
                  ["13.223  ", 1]];
console.log("=== Starting tests ===");
for(i in testvalues) {
  test(testvalues[i][0], testvalues[i][1]);
}

You seem to be using jQuery. You can use .each (docs) to loop over all elements in an jQuery object. Similarly, you can use .html (docs) to change the innerHTML of an element.

Termination of loop on referenceError

You use a while loop without a way of terminating it. It actually terminates, because you try to modify the innerHTML of undefined. That's... silly.


The line factorial 0 = 1 is redundant. The product of the empty list is already 1.

When writing a function that only works with strings (instead of arbitrary lists), I'd prefer to use "" instead of [] to denote the empty string. This way it's more obvious we're dealing with strings.

Since your isIntegral function will return false for negative numbers (because - is not a digit), you should name it something like isNaturalNumber instead.

Instead of applying read to the result of getLine, you can just use readLn. (Edit: since in your latest revision you do error checking on the string before using read, this no longer applies). Likewise you can use print instead of putStrLn and show.

Instead of having multiple $s on the same line, it is usually preferred to combine .s and $s. However using print you only need print $ factorial number anyway.

There is no point in prefixing a single expression with do, so you should remove the dos from your if and else.

Also since your isIntegral/isNaturalNumber function already returns false for negative numbers, there's no need to check whether the result is negative after calling read, so you can get rid of the if-statement and the duplication of calling main recursively from two different places.


Toggling between light and dark mode using JavaScript

One thing that you could update is how you are using the ternary operator for isDark.
Ternary operators are used for returning something based on a boolean response, so either return X if true, or Y if false.
However, every time it is used it is evaluating the statement being passed to it. In this case both times it is evaluating isDark. For the average website, this won't affect your processing time, but it is something to think about.
Instead a classic if/else statement would allow you to run more code off a single evaluation.
You will notice this isn't as sleek looking as ternary and is even more lines of code, but gives more capabilities when you need it.
if (isDark) {
  toggleIcon.children[1].classList.replace('fa-sun', 'fa-moon')
  imageMode(darkLightTheme[0])
} else {
  toggleIcon.children[1].classList.replace('fa-moon', 'fa-sun')
  imageMode(darkLightTheme[1])
}


Rails create create default database records

Yeah! you are on right path but we can improve it like :

class User < ActiveRecord::Base
  has_many :accounts

  after_save do
    self.accounts.create([{name: "Repairs"}, {name: "Supplies"}])
  end
end

Hopefully! This will help.


Search and Replace (FreeCodeCamp intermediate algorithm scripting)

This kind of test boils down the the familiarity of built-in JavaScript APIs. The naive way to go about this problem is to scan through the string and do the checks manually. However...

Pass a function as second argument of string.replace() and it will call that function for each match it encounters. The return value of this function becomes the replacement. So instead of manually scanning the string, you can let string.replace() do that heavy-lifting. Note that passing a string as first argument to replace only makes it run once, which is why the first argument is a RegExp with a g flag constructed from the string you want replaced.

Also, a minor suggestion. Instead of comparing the first letter with its upper case version to see if it is upper case, you can use regex.test() to see if a character matches a pattern that only matches uppercase. It's a bit shorter, if length is what you're after.

function myReplace(str, before, after) {
  return str.replace(new RegExp(before, 'g'), match => {
    return (/[A-Z]/).test(before[0]) ? `${after[0].toUpperCase()}${after.slice(1)}` : after
  })
}

console.log(myReplace("Let us go to the store", "store", "mall"))
console.log(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"))
console.log(myReplace("This has a spellngi error", "spellngi", "spelling"))
console.log(myReplace("His name is Tom", "Tom", "john"))
console.log(myReplace("Let us get back to more Coding", "Coding", "algorithms"))
console.log(myReplace("foo foo foo foo bar foo", "foo", "baz"))


Find an equation that uses all 9 digits (1-9)

It is extremely inefficient to do this randomly; you could end up checking the same numbers again and again. For a more structured approach, you could use itertools.permutations:

from itertools import permutations

for nums in permutations("123456789"):
    a = int("".join(nums[:4]))
    b = int(nums[4])
    c = int("".join(nums[5:]))
    if a * b == c:
        print "{0} * {1} == {2}".format(a, b, c)
        break # optional - there's more than one answer!

Also, note that:

found=False
while not found:
    ...
    if int(four_digit_num)*single_digit_num==int(multiple):
        found=True

would be neater as:

while True:
    ...
    if int(four_digit_num) * single_digit_num == int(multiple):
        break


Task Wrappers for starting operation only if previous task has finished

I think you might by overengineering it. Have you tried the Task.ContinueWith method which

  Creates a continuation that executes asynchronously when the target Task completes.

There are multiple overloads that let you specify a lot of options with the TaskContinuationOptions enumeration.


Covert html to pdf, calculate the vertical space to the end of the last page faster

Ways to optimize:

Nested loops

You got nested while loops in convert.js script and that requires a particular attention.The outer while loop contains the construction:

...
if (getPageAmount(buffer) === originalPages) {
    while (getPageAmount(buffer) === originalPages) {
...

where if conditional redundantly checks the condition getPageAmount(buffer) === originalPages whereas the underling while loop would check the same condition by itself. Therefore, remove the redundant if "wrapper".

getPageAmount function

Deserves a separate attention (frequently invoked function).

'/Count '. Many-times hardcoded search string '/Count ' begs for extracting into a variable

let searchStr = '/Count ';

index + '/Count '.length. Duplicated expression points to a starting offset for input buffer slicing. Worth to be a variable:

let pos = buffer.indexOf(searchStr);
let startOffset = pos + searchStr.length;
let str = buffer.slice(startOffset, startOffset + 32).toString();

splitting a string by pattern and get the 1st chunk (~~string.trim().split(/\n|\/|\[|\>/)[0]). What it does is splitting the input string by regex pattern /\n|\/|\[|\>/ into array of substrings. Though it creates a new array of strings/chunks in memory - whereas we only need the 1st leftmost chunk .[0].Instead, a much more efficient way is to just find the position of the 1st occurrence of the pattern and slice the input string to that point.That's achievable with String.search + String.slice combination and will go smashingly faster compared to the initial approach.
Eventually the optimized function would look as:

function getPageAmount(buffer) {
    let searchStr = '/Count ',
        pos = buffer.indexOf(searchStr),
        startOffset = pos + searchStr.length;
    let str = buffer.slice(startOffset, startOffset + 32).toString();
    return ~~str.trim().slice(0, str.search(/[\n\/\[\>]/))
}

DOM tree scanning

The "hero" of this section is document.querySelector('#padding-container') which appears in many places within while loops and queries the current document for a specific tag/element.
Such DOM queries become an expensive operations if used frequently, moreover - in massive traversals. Depending on markup complexity and "amount" of traversal such repetative queries may make the processing +50% slower.The solution here is to extract the reference to an element into a top-level variable and reference it in all needed places.

# top-level variables
...
let passes = 0;
let paddingContainer = document.querySelector('#padding-container');

Extracting "padding container" height

Expression ~~paddingContainer.style.height.replace('px', '') is duplicated in many places and is candidate for Extract function technique.Could be even defined as unified function for getting height for the element passed as parameter:

function getElHeight(el):
    return ~~el.style.height.replace('px', '')

...

    ...
    _ => {
        let padding_height = getElHeight(paddingContainer);
        paddingContainer.style.height = `${padding_height * 1.5}px`
    }


As a general sentiment, I can't spot any glaring issues with the code just the one section and a few minor things (you did say you basically copied it; I'd imagine the Material UI team have some idea what they're doing)

{children.map((child, i) => {
  return React.cloneElement(child, {
    ...child.props,
    ...{
      onClick: this.generateOnClick(child.props.onClick),
      key: `${menuId}${i}`
    }
  });
})}

children cannot always be defined as an array, if you pass a single list item it will be given as a single element which will not have map as a property. You should be using React.Children.map instead.

Slipping in a small code style comment here, doing => { just to return something moments later seems like wasted code.

{children.map((child, i) => {
  return React.cloneElement(child, {

When using React.cloneElement, you don't need to manually specify the child props as that's the implication of cloning.

return React.cloneElement(child, {
  ...child.props,

Creating a separate object inside another object just to spread is redundant.

...{
  onClick: this.generateOnClick(child.props.onClick),
  key: `${menuId}${i}`
}

To finish things off here, using the index of the child as part of the key is an anti-pattern. Any time that someone wants to change the children, or reorder the list, React will assume it has already memoized the render during the previous reconcile and give you the wrong render.

There's a number of resources and in-depth explanations if you Google something along the lines of React index as key. Generally when building reusable components, I leave the key generating relative to each implementation, but, that's your decision, however, I would say that some developers want to use their own keys and manually overriding them is blocking that.

key: `${menuId}${i}`

A better implementation would be:

{React.Children.map(children, child =>
  React.cloneElement(child, {
    onClick: this.generateOnClick(child.props.onClick)
  })
)}

Even so, you're cloning all of your children inside each render of the component, with all the information used in that process being loaded in during the initialisation phase.

Everytime you act on the menu, you're performing the same element cloning on all your children again. If I had complex children or even a large amount, this could easily slow the render process.

A few minor points:

buttonChildren would better be named label or menuLabel
Using propTypes is very beneficial, especially if you're trying to create a reusable component/library, not only to the developer in charge of implementation to know what to expect but you (or whoever) in charge of fixing potential bugs in the library.
Usually the Popper component allows you to open and close a menu by clicking it... for whatever reason, you can't close the component by clicking it.
Stick with consistent bracketing around your if/else

if (fn)
  return () => {
    fn();
    this.handleMenuClose();
  };
else {
 return this.handleMenuClose;
}


Extended exception for network errors in Python

Let's go bottom-to-top:

d[attr] = self.__dict__.get(attr)

Manipulating the __dict__ of an object is rarely necessary as it is often cleaner to use getattr or setattr instead. Here, the exact replacement would be d[attr] = getattr(self, attr, None) because dict.get default to None itself. However, here you know in advance that all 3 attributes are set so you could d[attr] = getattr(self, attr) instead.

def as_dict(self):

You can turn that initialization loop into a generator expression and feed that to the OrderedDict constructor. Doing so you’re not modifying d after building it so you could directly return it:

def as_dict(self):
    return OrderedDict((attr, getattr(self, attr)) for attr in ['reason', 'main_url', 'related_exception'])

def _move_kwargs(self, kwargs):

So… you need to get some values out of a dictonary and remove the corresponding entry afterwards: you should look into the dict.pop method:

def _move_kwargs(self, kwargs):
     return kwargs.pop('main_url', None), kwargs.pop('related_exception', None)

In fact, it would feel cleaner to do these operations directly into __init__.

kwargs_copy = dict(kwargs)

You do not need to copy that dictionary to work with parameter value. Deleting or poping items from this dictionary is fine.

Exception.__init__(self, reason, **kwargs_copy)

You should ask super to call the super class __init__ method for you. This is not so much of a difference with this code but it's a good habit to have, especially if you happen to need multiple inheritance or complex inheritance scheme.

super(ExtendedNetworkError, self).__init__(reason, **kwargs)

or, using Python 3, you can simplify the call to:

super().__init__(reason, **kwargs)

So far, the code has been reduced to:

class ExtendedNetworkError(Exception):
    def __init__(self, reason, *args, **kwargs):
        self.reason = reason
        self.main_url = kwargs.pop('main_url', None)
        self.related_exception = kwargs.pop('related_exception', None)
        super().__init__(reason, **kwargs)

    def as_dict(self):
        return = OrderedDict(
            (attr, getattr(self, attr))
            for attr in ['reason', 'main_url', 'related_exception']
        )

Now there is this *args parameter in __init__. Since you’re not using it, you should remove it. This will force the need to use named parameter when specifying more than the reason.

Last thing you can do to improve the code is to add some docstrings explaining what this class is about.


The observation of @juvian, which pointed to the obvious mistake of copying vectors, is good. But I think that the main point is that of recognizing this is a pretty famous problem in Image Processing: Connected Components Labeling. Flood fill is one of the slowest solutions, because of its poor cache usage.

Here I'm using the SAUF algorithm published in Two Strategies to Speed up Connected Component Labeling Algorithms.

In particular this solution works by making two scans of the image and using Union-Find to manage label equivalences. One thing to note is that the second scan is not needed to solve the specific problem, because you can stop without getting the labeled image and just use the vector of blobs. This saves about 20% of the total time.

This takes few milliseconds for the specific image.

I'm sorry for posting this extremely long piece of code, but a lot of additional code is needed for having a working example. What is needed is a way to store images, the UF data structure (here everything is static, but this is not needed), the PerformLabeling function. The PNG image was converted to PBM format for easy loading.

#include <vector>
#include <fstream>
#include <string>
#include <cstdint>
#include <tuple>

using namespace std;

template <typename T>
struct mat {
    size_t rows_, cols_;
    vector<T> data_;

    mat(size_t rows = 0, size_t cols = 0) : rows_(rows), cols_(cols), data_(rows*cols) {}

    const T& operator()(size_t r, size_t c) const { return data_[cols_*r + c]; }
    T& operator()(size_t r, size_t c) { return data_[cols_*r + c]; }

    const T* operator[](size_t r) const { return &data_[cols_*r]; }
    T* operator[](size_t r) { return &data_[cols_*r]; }
};

bool loadPBM(const string& filename, mat<uint8_t>& img)
{
    ifstream is(filename, ios::binary);
    if (!is)
        return false;

    string type;
    size_t w, h;
    is >> type >> w >> h;
    if (type!="P4" || is.get()!='\n')
        return false;

    img = mat<uint8_t>(h, w);

    for (size_t r = 0; r < h; ++r) {
        uint8_t nbits = 0;
        uint8_t buffer;
        for (size_t c = 0; c < w; ++c) {
            if (nbits == 0) {
                if (!is.get(reinterpret_cast<char&>(buffer)))
                    return false;
                nbits = 8;
            }
            img(r, c) = 255 * (1 - (buffer >> --nbits & 1));
        }
    }

    return is.good();
}

bool savePGM(const string& filename, const mat<uint8_t>& img)
{
    ofstream os(filename, ios::binary);
    if (!os)
        return false;

    os << "P5\n" << img.cols_ << " " << img.rows_ << "\n255\n";
    os.write(reinterpret_cast<const char*>(&img.data_[0]), img.cols_*img.rows_);

    return os.good();
}

// Union-find (UF)
class UF {
public:
    static void Alloc(unsigned max_length) {
        P_ = new unsigned[max_length];
    }
    static void Dealloc() {
        delete[] P_;
    }
    static void Setup() {
        P_[0] = 0;// First label is for background pixels
        length_ = 1;
    }
    static unsigned NewLabel() {
        P_[length_] = length_;
        return length_++;
    }
    static unsigned GetLabel(unsigned index) {
        return P_[index];
    }
    static unsigned GetLength() {
        return length_;
    }
    static unsigned Merge(unsigned i, unsigned j)
    {
        // FindRoot(i)
        while (P_[i] < i) {
            i = P_[i];
        }
        // FindRoot(j)
        while (P_[j] < j) {
            j = P_[j];
        }
        if (i < j)
            return P_[j] = i;
        return P_[i] = j;
    }
    static unsigned Flatten()
    {
        unsigned k = 1;
        for (unsigned i = 1; i < length_; ++i) {
            if (P_[i] < i) {
                P_[i] = P_[P_[i]];
            }
            else {
                P_[i] = k;
                k = k + 1;
            }
        }
        return k;
    }
private:
    static unsigned *P_;
    static unsigned length_;
};
unsigned* UF::P_;
unsigned UF::length_;

struct blob {
    size_t x = 0, y = 0, count = 0;
    size_t left = SIZE_MAX, right = 0, top = SIZE_MAX, bottom = 0;
    blob() {}
    void accumulate(size_t r, size_t c) {
        x += c;
        y += r;
        ++count;

        if (left > c)
            left = c;
        if (right < c)
            right = c;
        if (top > r)
            top = r;
        if (bottom < r)
            bottom = r;
    }
    void accumulate(const blob& b) {
        x += b.x;
        y += b.y;
        count += b.count;

        if (left > b.left)
            left = b.left;
        if (right < b.right)
            right = b.right;
        if (top > b.top)
            top = b.top;
        if (bottom < b.bottom)
            bottom = b.bottom;
    }
};

template <typename Blob>
size_t PerformLabeling(const mat<uint8_t>& img, mat<unsigned>& img_labels, vector<Blob>& blobs)
{
    size_t h = img.rows_;
    size_t w = img.cols_;

    img_labels = mat<unsigned>(h, w); // Allocation + initialization of the output image

    UF::Alloc(((img.rows_ + 1) / 2) * ((img.cols_ + 1) / 2) + 1); // Memory allocation of the labels solver
    UF::Setup(); // Labels solver initialization

    vector<Blob> temp_blobs(((img.rows_ + 1) / 2) * ((img.cols_ + 1) / 2) + 1);

    // Rosenfeld Mask
    // +-+-+-+
    // |p|q|r|
    // +-+-+-+
    // |s|x|
    // +-+-+

    // First scan
    for (size_t r = 0; r < h; ++r) {
        // Get row pointers
        const unsigned char *img_row = img[r];
        const unsigned char *img_row_prev = img_row - img.cols_;
        unsigned *img_labels_row = img_labels[r];
        unsigned *img_labels_row_prev = img_labels_row - img_labels.cols_;

        for (size_t c = 0; c < w; ++c) {
#define CONDITION_P c > 0 && r > 0 && img_row_prev[c - 1] > 0
#define CONDITION_Q r > 0 && img_row_prev[c] > 0
#define CONDITION_R c < w - 1 && r > 0 && img_row_prev[c + 1] > 0
#define CONDITION_S c > 0 && img_row[c - 1] > 0
#define CONDITION_X img_row[c] > 0

#define ACTION_1 // nothing to do
#define ACTION_2 img_labels_row[c] = UF::NewLabel(); // new label
#define ACTION_3 img_labels_row[c] = img_labels_row_prev[c - 1]; // x <- p
#define ACTION_4 img_labels_row[c] = img_labels_row_prev[c]; // x <- q
#define ACTION_5 img_labels_row[c] = img_labels_row_prev[c + 1]; // x <- r
#define ACTION_6 img_labels_row[c] = img_labels_row[c - 1]; // x <- s
#define ACTION_7 img_labels_row[c] = UF::Merge(img_labels_row_prev[c - 1], img_labels_row_prev[c + 1]); // x <- p + r
#define ACTION_8 img_labels_row[c] = UF::Merge(img_labels_row[c - 1], img_labels_row_prev[c + 1]); // x <- s + r

            if (CONDITION_X) {
                if (CONDITION_Q) {
                    ACTION_4
                }
                else {
                    if (CONDITION_R) {
                        if (CONDITION_P) {
                            ACTION_7
                        }
                        else {
                            if (CONDITION_S) {
                                ACTION_8
                            }
                            else {
                                ACTION_5
                            }
                        }
                    }
                    else {
                        if (CONDITION_P) {
                            ACTION_3
                        }
                        else {
                            if (CONDITION_S) {
                                ACTION_6
                            }
                            else {
                                ACTION_2
                            }
                        }
                    }
                }
            }
            else {
                ACTION_1
                continue;
            }

            temp_blobs[img_labels_row[c]].accumulate(r, c);
        }
    }

    size_t n_labels = UF::Flatten();

    blobs.resize(n_labels);
    for (size_t i = 0; i < UF::GetLength(); ++i) {
        blobs[UF::GetLabel(i)].accumulate(temp_blobs[i]);
    }

    // Second scan
    for (size_t r = 0; r < img_labels.rows_; ++r) {
        unsigned *img_row_start = img_labels[r];
        unsigned *img_row_end = img_row_start + img_labels.cols_;
        for (; img_row_start != img_row_end; ++img_row_start) {
            *img_row_start = UF::GetLabel(*img_row_start);
        }
    }

    UF::Dealloc(); // Memory deallocation of the labels solver

    return n_labels;
}

int main() {
    mat<uint8_t> img;
    if (!loadPBM("mD6sL.pbm", img))
        return EXIT_FAILURE;

    mat<unsigned> img_labels;

    vector<blob> blobs;
    auto n = PerformLabeling(img, img_labels, blobs);

    blob bmax;
    for (const auto& b :  blobs) {
        if (bmax.count < b.count)
            bmax = b;
    }
    bmax.x /= bmax.count;
    bmax.y /= bmax.count;

    mat<uint8_t> out(img.rows_, img.cols_);
    copy(begin(img_labels.data_), end(img_labels.data_), begin(out.data_));

    for (int i = -50; i <= 50; ++i) {
        out(bmax.y + i, bmax.x) = 255;
        out(bmax.y, bmax.x + i) = 255;
    }
    for (size_t i=bmax.left;i<=bmax.right;++i) {
        out(bmax.top, i) = 255;
        out(bmax.bottom, i) = 255;
    }
    for (size_t i = bmax.top; i <= bmax.bottom; ++i) {
        out(i, bmax.left) = 255;
        out(i, bmax.right) = 255;
    }

    if (!savePGM("out.pgm", out))
        return EXIT_FAILURE;

    return EXIT_SUCCESS;
}


Overall, this seems to be a small but useful template.  However, there are a few things that I think might be improved.

Sorting requires more than swap

While the provided swap function would assist in some kind of sorting, without a comparison operator, we still can't actually sort.  This may well be by design, in which case a comment in the code pointing this out would be helpful.

Consider default constructor

There is no simple way at the moment to create a generic templated origin point (all coordinates zero).  This makes it a bit more difficult to create something like a distance_from_origin function that is generic.

Consider projection operator

It's often useful to project, say, a 3D point onto a 2D canvas.  This could also likely be made generic.

Do a range check

The distance function that measures from an axis does no range checking on the axis number and there does not seem to be a good generic way to add one.  Consider providing a range checking version.


QT - Class For Connecting to Mqtt Broker With QMqttClient

Qt-ness

My QT is a little bit rusty, but you're probably not doing the right thing here. First QObject have their own memory management, usually each QObject constructor takes a parent, this parent takes ownership of the created object. As the setParent() function is always available, interfering with the memory management via std::unique_ptr or std::shared_ptr is usually not a good idea.

Additionally you are containing QMQTTClient for what looks like just configuration reasons, there really doesn't seem to be any need to wrap it in another layer, you might as well just replace your client with QMQTTClient and connect to it. If you want to wrap configuration, a free function will do with much less overhead.

Stack-vs-Heap

Both the QMQTTClient and the MQTTConfig could as well be stack allocated, making everything easier. Passing MQTTConfig by reference will work well enough.

MQTTConfig

The constructor should use initializer lists and not the function body for member variable initialization.

MqttConfig() : hostname("localhost"), port(1883) {}

I'd probably prefer default values for this,

MqttConfig(QString h = "localhost", qint16 p = 1883  ) : hostname(h), port(p) {}

SubscriptionConfig

The default constructor doesn't need to be deleted if you are defining a custom constructor


Filter to block duplicate POST submission on server side

Just some suggestions:

1.Change you UI concept.

Hide Submit button until the server responds.
Show Please Wait notification / dialog

2.Use JavaScript to send request and prevent multiple submits:

if(ignoreSubmitEvent){
    return;
}

hideSubmitButton();
ignoreSubmitEvent = true;

var jqxhr = $.post( "/url...", { submittoken: "unique-one-time-token", name: "dit" });

jqxhr.done(function( data ) {
     [...] // your code
});

jqxhr.fail(function() {
     [...] // your code
});

// DO IT ALLWAYS
jqxhr.always(function() {
    showSubmitButton();
    ignoreSubmitEvent = false;
});

3.It could be a good idea to use HandlerInterceptor instead of Filter

public class OneTimeTokenPostInterceptor extends HandlerInterceptorAdapter {

    private static final String UNIQUE_ONE_TIME_TOKEN = "unique-one-time-token";
    private static final Logger logger                = LoggerFactory.getLogger(OneTimeTokenPostInterceptor.class);

    private Set<String>         tokens                = Collections.synchronizedSet(new HashSet<String>());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getParameter(UNIQUE_ONE_TIME_TOKEN);

        logger.debug("preHandle: token = {}", token);

        if (token == null || tokens.contains(token)) {
            logger.error("token {} is null or allready used", token);
            response.sendError(202); // ignore request
            return false;
        }
        tokens.add(token);
        return true;
    }

    //
    // GET CALLED AFTER CONTROLLER DID HIS JOB
    //

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        String token = request.getParameter(UNIQUE_ONE_TIME_TOKEN);

        logger.debug("postHandle: token = {}", token);

        if (token != null) {
            tokens.remove(token);
        }
    }
}


DECLARE @BadgeName AS NVARCHAR(50) = ##BadgeName:string?Great Answer##;
DECLARE @MyTop AS INT = ##MyTop:int?100##;

SELECT TOP(@MyTop)
    Badges.UserId AS [User Link],
    Users.Reputation,
    @BadgeName AS BadgeName,
    COUNT(Badges.Id) AS NumberOfBadges
FROM  Badges
  INNER JOIN Users ON Users.Id=Badges.UserId
WHERE Badges.Name = @BadgeName
  AND Users.Reputation > 10000
GROUP BY Badges.UserId, Users.Reputation
ORDER BY NumberOfBadges DESC

The DECLARE statements should have semi-colons at the end.

Apparently you need the parentheses when using SELECT TOP with a variable.

As you noticed, you need to put columns in the GROUP BY to include them in the SELECT.  You can get around this by using the variable instead of the column.

I prefer capitalized keywords and a more compact formatting, but that's really up to you.


Turn multiple key presses into single GameAction

var pressedKeys = keyboardState.PressedKeys();
var inputActions = pressedKeys.Select(GetInputAction).ToList();
var downActions = inputActions.Select(ia => ia.Down);

This is what's painted you into the corner you're in. You're not showing your GameActions enum (a better name would be GameAction, or even better, MoveDirection..actually, Direction suffices, since all there is to it is a bunch of values that each represent a direction - the point is, enum type names should not be plural), but I presume it looks something like this:

public enum GameActions
{
    MoveLeft,
    MoveUpLeft,
    MoveUp,
    MoveUpRight,
    MoveRight,
    MoveDownRight,
    MoveDown,
    MoveDownLeft
}

The problem is that MoveUpLeft is a combination of MoveUp and MoveLeft, and since the enum type itself doesn't account for it, your code has to.

I'd suggest using a [Flags] attribute:

[Flags]
public enum Direction
{
    Left = 1,
    Top = 2,
    Right = 4,
    Down = 8
}

Then, instead of downActions being an IEnumerable<GameActions> and using LINQ IEnumearble<T>.Contains extension, you can add the values of all "down actions", and pass ActionRequested an enum value that represents the sum of all pressed directions, be it Left+Top, Down+Right or whatever. The [Flags] attribute merely serves as a visual cue to remind you that these values can be combined and, using bitwise AND operations or simply, the .HasFlag() method, the handler can determine whether the received value 3 contains Direction.Left:

void ActionRequested(Direction direction)
{
    if (direction.HasFlag(Direction.Left))
    {
        // direction contains Direction.Left
    }
    if (direction.HasFlag(Direction.Right))
    {
        // direction contains Direction.Right
    }
    if (direction.HasFlag(Direction.Top))
    {
        // direction contains Direction.Top
    }
    if (direction.HasFlag(Direction.Bottom))
    {
        // direction contains Direction.Bottom
    }
}

It's not clear from your post exactly what GetInputAction does and what downActions means, so it's hard to recommend a change that will fit into your code, but here's some inspiration:

class Program
{
    [Flags]
    public enum Direction
    {
        Left = 1,
        Top = 2,
        Right = 4,
        Bottom = 8
    }

    static void Main(string[] args)
    {
        var direction = (Direction)3;
        Console.WriteLine("Direction: {0}", direction);
        Console.WriteLine("Left: {0}", direction.HasFlag(Direction.Left);
        Console.WriteLine("Top: {0}", direction.HasFlag(Direction.Top);
        Console.WriteLine("Right: {0}", direction.HasFlag(Direction.Right);
        Console.WriteLine("Bottom: {0}", direction.HasFlag(Direction.Bottom);

        Console.ReadLine();
    }
}

Output:


Asynchronous task on every element of an array

From reading it I think it makes more sense to put:

.then(function(result) {
        if (!result) {
          barsDB.push(bar);
        } else {
          bar.goingTonight = result.goingTonight;
        }
      });

Into the promise that is actually executing that code:

function findByIdAsync(bar) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      const result = findById(bar)
      if (result) {
        bar.goingTonight = result.goingTonight;
        resolve("Successfully updated bar")
      } else {
        barsDB.push(bar);
        resolve("Successfully added new bar")
      }
    }, 3000);
  });
}

Then you can just call the array of promises as so:

Promise.all(barsClient.map(findByIdAsync))
  .then(() => {
    console.log("barsClient:", barsClient);
    console.log("barsDB", barsDB);
  });

It seems that the concerns are more aligned this way.


Using jquery to prepare jQuery UI tabs, optimize?

Your code's very nice. My points below are mostly of the "but what if..." variety concerning the DOM manipulation, rather than the JavaScript itself. In other words, your solution seems spot on for the given exercise, whereas my comments mostly refer to situations which are not part of the exercise, but could arise in the real world.

Aside: The exercise could be clearer in its naming. The container element (singular) has a class called tabs (plural), while the DIVs (plural) within it have a class called tab (singular). It's sort of logical, but it gets confusing nonetheless. And I say "sort of logical", because the .tab elements aren't actually tabs - they're "panels" in jQuery UI's terminology. Hence, their class name should really be "panel". But I digress...

First off, what would happen if the page contains several "tabable" sections? The fact that .tabs is a class name - not an ID - suggests that there might be multiple div.tabs container elements, each with their own set of div.tab elements.

Well, with your code, things go a little awry (see here): Both tab containers get tab links for all the panels on the page, even those belonging to another container.

The trick would be to go through each div.tabs (i.e. tab container) element in turn, and manipulate their individual structures one by one:

$("div.tabs").each(function (containerIndex) {
  var container = $(this),
      tabLinks  = $("

");

  container.find("div.tab").each(function (tabIndex) {
    var id = "tabs-" + containerIndex + "-panel-" + tabIndex; // more precise ID

    // your code here ...
  });

  container
    .prepend(tabLinks)
    .tabs();
});

See the result here

Second, what might happen if an
 heading has HTML in its text or has its own child elements? Here are examples of each of those cases:

Literal HTML:
When to use &lt;div&gt; elements

HTML formatting:
When to use div elements

Here's the result, using your code

Now, this is something where there may not be "one right answer" - it all depends on the content you're working with. However, it's worth considering.

In your case, you use .text() to get the text out of the heading, but you don't use .text() to put that text into the the link; you "manually" create a link by concatenating strings.
So, in the first case, the string you get out is When to use
 elements. Notice that the entity-encoded < and > have become plain characters. When you then concatenate that with other strings of HTML to make the link, you end up more HTML than you intended; there's an unclosed DIV in the middle of your link!
In the second case, .text() completely ignores the  tag. That doesn't break the link, but you lose the formatting and semantics of the  tag, which - one might assume - was put there for a reason by whoever wrote the heading. Since you also remove the original
, that formatting is now nowhere to be found.

I said there was no right answer, because to fix the first case, you'd need to use .text() to extract and insert the heading's content, as it prevents the string from being interpreted as HTML. But to fix the other case, you'd need to use .html() instead, to ensure the string is interpreted that way. Now, using .html() would actually solve both cases (preserving already-encoded entities and tags), but the next question is whether you actually want that. What if the heading itself contains a link? Then you'll end up with a link inside a link... This of course doesn't apply only to tabs and headings, but to any situation where you're extracting and inserting content, which is why I brought it up.

But again, I'm just trying to poke holes in things here, so don't let it discourage you. It's more to illustrate the sort of things you might run in to. The possible solutions I can think are outside the scope of this answer though (it'd involve some different approaches), and very much outside the scope of the original exercise.

Speaking of "out of scope", I've rambled plenty here, so I'll stop.


Please excuse my brevity, I'm typing on a phone.

Naming

The rules regarding use of leading underscore in identifiers are a bit complex (https://stackoverflow.com/a/228797/2498188). Although you do not have undefined behavior, I do generally recommend that one avoids leading underscore on identifiers as not everyone knows the rules that well.

Consider using std::packaged_task

While your code can be used with any freestanding function without arguments and no return type, by using packaged task you can use any function with bind and you can get a std::future for the return value or synchronisation of the result. It would make your code more generally usable.

Synchronisation

The value _num_work is never used outside of a mutex look and does thus not have to be atomic, in fact you do not need it at all as you can just use the size() method on the queue.

Edit: I see now that it counts the number of tasks including the ones "in flight", I don't really see how this is useful if you don't provide a method for separately querying the number in flight and the number queued.

Effectivity

Note that you do call yield in your thread loop, this doesn't make the thread wait, it only informs the OS that some other thread can run in its place. If there is no other thread to run, it will run again at the top of your loop essentially pegging all of your CPUs at 100% even without any tasks in the queue. You need to use a std::condition_variable to block your worker threads when there is no work to do, and wake them when work arrives.

Desired methods

You're missing don't methods that are typically desirable, like for example the ability to terminate the thread pool with and without waiting for all jobs to complete.

Finally as a reference I offer up my pool in a previous question: Thread pool worker implementation


Password and confirm password validation in Android Studio

Inconsistent UX

Most validation errors call setError of the relevant input field.
An exception is when the confirmation password doesn't match the first entry,
that pops up a toast.
It would be better to handle validation errors consistently,
by using setError for mismatched confirmation password.

It's ok to use a toast for the result of the registration,
when all form fields are valid.

Creating account with invalid input

Before calling mAuth.createUserWithEmailAndPassword,
the only validation that's really enforced is that the confirmation password is not empty.
That's strange.
It would be better to call this only when all entries of the form are filled and valid.

Style issues

A convention in Java is to use camelCase for variable names.
For example RegisterConfirmPassword should be registerConfirmPassword.

Instead of if (a == false) { it's more natural to write if (!a) {.

It's a convention in Java to place braces like this:

if (cond) {
    // ...
} else {
    // ...
}


Python CSV file import and object manipulation

Style

Use snake_case instead of mixedCase when in Python. In general, follow PEP 8.

Implementation

It seems you have a Player class defined somewhere. Then, you use global functions as getters and setters. This has two problems:

In OOP, getters and setters should be instance methods, e.g. of the Player class.
Python is not Java. Pythonic code wouldn't normally use getters and setters.

Design

Judging by loadCSV, each row of a CSV file will become a Player object. However, all Players do is store attributes for getting and setting. Save the hassle by using a dictionary for a player. Then just store all your dictionaries in a list.

To understand this code, you will need to understand comprehensions.

import csv

# Map row to dictionary (dictionary comprehension)
def player(column_names, row):
    return {column_names[column]: data for column, data in enumerate(row) if column < len(column_names)}

# Map CSV file to list of dictionaries (list comprehension)
players = [player(['name', 'position', 'game_info', 'price'], row) for row in csv.reader(open('dk.csv', 'r'))]

Running this code on the following CSV file

Louis Fernando,Batter,Washington,400
Hose Ricardo,Pitcher,San Fernando,900

sets players to a list of dictionaries as below.

[{'game_info': 'Washington',
  'name': 'Louis Fernando',
  'position': 'Batter',
  'price': '400'},
 {'game_info': 'San Fernando',
  'name': 'Hose Ricardo',
  'position': 'Pitcher',
  'price': '900'}]

Then player objects can be accessed like so

print(players[0]['game_info']) # prints Washington
players[1]['name'] = "James Jones"

Notes

Types

This doesn't take care of types, e.g. the price field maps to a string, not a number. I'm not exactly sure what you're doing overall, so I'll leave that to you.

CSV Format

Columns in your CSV file beyond those named in column_names will be ignored.

e.g. passing four names (['name', 'position', 'game_info', 'price']) to player when a row in the CSV file contains five columns.

Louis Fernando,Batter,Washington,400,lol
Hose Ricardo,Pitcher,San Fernando,900

will produce the same result as the first example.


Moving the player across an ASCII art "world"

A few comments:

You already did a good job with PEP8. The only error I get back is that it expects two blank lines between functions
Regarding PEP257, please add some docstrings and comments to make clear what's the code goal to the potential reader
If find the Move class confusing. The up_down and left_right class attributes seem coordinates. I'd prefer to have a class named, for example, Player with x and y instance attributes. Note the differenct between class and instance attributes if you want to have multiple players in the future
The translation between actions and movements isn't very effective because you need to hardcode all four cases and use up/down/left/right multiple times
If iteration is all what is needed, I recommend using xrange instead of range
If just one iteration is needed (range(1)), just drop the loop for better readability
Use the multiplication operator to get long strings of the same charater instead of loops ('.' * n)

The code I'd have written would be more or less as follows (more comments below, console library not used):

"""ASCII world game."""

class Player(object):

    """Player object with some actions (just move for now)."""

    def __init__(self):
        """Initialize coordinates."""
        self.x = 1
        self.y = 1

    def move(self, dx, dy):
        """Move player to some position.

        :param dx: How much to move in the x axis
        :type dx: int
        :param dy: Move much to move in the y axis
        :type dy: int

        """
        # Ignore invalid movements
        if (self.x + dx) < 1 or (self.y + dy) < 1:
            return

        self.x += dx
        self.y += dy

class GameMap(object):

    """GameMap that shows where the player is."""

    X_OFFSET = 4

    def render(self, player):
        """Render map and player position."""
        def render_empty_row():
            """Render row in which there is no player."""
            print('.' * (player.x + self.X_OFFSET))

        for _ in xrange(player.y):
            render_empty_row()

        print('{} @ {}'
              .format('.' * (player.x - 1),
                      '.' * (self.X_OFFSET / 2)))
        render_empty_row()

class Command(object):

    """Command reader from stdin."""

    # Map text command to player movement
    CMD_TO_MOVE = {
        'u': (0, -1),
        'up': (0, -1),
        'd': (0, 1),
        'down': (0, 1),
        'l': (-1, 0),
        'left': (-1, 0),
        'r': (1, 0),
        'right': (1, 0),
    }

    # Default value for unknown command
    NO_MOVE = (0, 0)

    def read(self):
        """Read command (up, down, left, right) from stdin.

        The command is converted to a movement for the player using the same
        coordinate system.

        :returns: Player movement
        :rtype: tuple(int, int)

        """
        command_str = raw_input('> ')
        return self.CMD_TO_MOVE.get(command_str, self.NO_MOVE)

class Game(object):

    """Game object to keep state and read command for next turn."""

    def __init__(self):
        """Get all the objects needed to run the game."""
        self.player = Player()
        self.game_map = GameMap()
        self.command = Command()

    def run(self):
        """Render map and read next command from stdin."""
        while True:
            self.game_map.render(self.player)
            self.player.move(*self.command.read())

if __name__ == "__main__":
    game = Game()
    game.run()

What I tried to show:

Object oriented design: use the language of the problem space to define a class for each type of object in the problem. In general, when you think about the problem, if it's a name it should be a class, if it's a verb it should be a method
Use docstrings for every class and method (use sphinx format for arguments and return values if possible)
Make a difference about what is command (word) and a movement (delta in the coordinate system)
Use constants instead of harcoded values (X_OFFSET)

Note that not everything should be a class. The command reader could be a function, but I preferred to use class in this case for consistency.

I hope this helps.


Is this the correct usage of ConcurrentDictionary?

There isn't a lot of point of checking ContainsKey.  A thread could sneak in between the ContainsKey and Try* methods you are calling.  The TryGetValue out parameter will be initialized to the default value if it can't find the key.

The GetActiveClientCountFor could become this.

public static int GetActiveClientCountFor(string buildingName)
{
    int clientCount;
    _buildingsSubscribedTo.TryGetValue(buildingName, out clientCount);
    return clientCount;
}

In the IncrementClientCountFor code the value is retrieved and then added to.  If someone came in and updated the value the TryUpdate would fail as the count changed.

What should be used is the AddOrUpdate method.  If the key doesn't exist it will be created and set to one.  If it does exist it will call the update method.  The update method could be called multiple times if the value changed before it could be set and will be set to the last good value.

public static void IncrementClientCountFor(string buildingName)
{
    _buildingsSubscribedTo.AddOrUpdate(buildingName, 1, (s, i) => i++);
}

Same problem with DecrementClientCountFo.  The value is retrieved and checked if less than one.  But again a thread could add to dictionary and the code would remove it from the dictionary with a positive count.  To get an Atomic TryRemove I would create an extension method called TryRemove taken from http://blogs.msdn.com/b/pfxteam/archive/2011/04/02/10149222.aspx

public static class ConcurrentDictionaryExtensions
{
    //http://blogs.msdn.com/b/pfxteam/archive/2011/04/02/10149222.aspx
    public static bool TryRemove<TKey, TValue>(
        this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {
        if (dictionary == null) throw new ArgumentNullException("dictionary");
        return ((ICollection<KeyValuePair<TKey, TValue>>) dictionary).Remove(
            new KeyValuePair<TKey, TValue>(key, value));
    }
}

Now change DecrementClientCountFor to use AddOrUpdate then the Atomic TryRemove

public static void DecrementClientCountFor(string buildingName)
{
    var buildings = _buildingsSubscribedTo.AddOrUpdate(buildingName, s => 0, (s, i) => i--);
    if (buildings < 1)
    {
        _buildingsSubscribedTo.TryRemove(buildingName, buildings);
    }
}

If the value was changed from underneath us after getting the value the TryRemove will fail.  Which is ok since it could be positive or another thread could have removed the key already.


Initialize before using

    int bit_counter, net_bit_counter = 0;

There are a couple problems.  First, if you declare and initialize in the same statement, you should only declare one variable.

    int bit_counter = 0;
    int net_bit_counter = 0;

If you have two variables, declare them on two lines.  Only declare multiple variables on a single line if you initialize none of them.  And some would argue not even then.  There's no functional difference, but it is much easier to read with every initialized declaration on a separate line.

Second, you don't initialize bit_counter.  C does not automatically initialize variables to default values, so this can cause bizarre behavior.  When I first tried to run this code, it gave me a runtime error until I initialized all the variables.

Know your bounds

    while (bit_counter != 33) {

This is a bit fragile.  You currently allow bit_counter to be incremented multiple times per iteration of this loop.  What if when it is 32, you increment to 34 without hitting this check?  The check will keep succeeding until the the program crashes (possibly due to trying to write outside the array).

    while (bit_counter <= 32) {

This is much more robust.  It no longer has to hit the mark exactly to stop.  Now it will stop for any value greater than 32, not just 33.

Another benefit, for readability, is that it now says 32, which is the critical number here.  Previously it said 33, which is one more than the last number.

But this is actually a bug.  It should be

    while (bit_counter < 32) {

because literal_bit_mask is only 32 long.  The first element is 0.  The last element is 31.  Now it won't write past the end of the array.

C has an increment by one operator

            net_bit_counter += 1;
            bit_counter += 1;

You can write this more idiomatically as

            ++net_bit_counter;
            ++bit_counter;

This shouldn't make much functional difference (perhaps not any on many platforms), but most C programmers would find this more recognizable.

I used the prefix form because some C compilers may not be smart enough to avoid the copy step of the postfix form.  I would expect most compilers to optimize that out, but we don't need to rely on that.  It's unlikely to make a noticeable difference here.

++bit_counter increments bit_counter and returns that value.  bit_counter++ returns the value it had before incrementing.  If you don't use the value (as you don't here), there is no real functional difference.  It's possible that the compiler may return different machine instructions.  In particular, it might copy the value to another register and then increment.  That's unnecessary if the

The following are functionally equivalent (leave the variables with the same values at the end):

int var = bit_counter++;

and

int var = bit_counter;
bit_counter++;

and

int var = bit_counter;
++bit_counter;

The following are different from the previous three, but are functionally equivalent to each other:

bit_counter++;
int var = bit_counter;

and

++bit_counter;
int var = bit_counter;

and

int var = ++bit_counter;

If bit_counter starts as 0 and is incremented to 1, then the first three will set var to 0.  The last three will set var to 1.

Many consider it easier to read if the variables are changed on separate lines.  This makes it obvious that the variables are changing.  Doing two things on the same line is less obvious, because people may see one and miss the other.


Project Euler 18/67: Maximum Path Sum Solution

This is pretty good code for a C++ beginner.  I believe you got the right algorithm.  Its running time is linear in the number of entries.  You visit every element once; I don't believe it is possible to do better than that.  Its memory usage is also linear in the number of entries.  The memory usage, however, can be improved.  Instead of processing the rows bottom-up, if you do it top-down, you can process the rows as you read them, keeping just two rows' worth of data at any given time.

It would be slightly more elegant to implement a simple abstraction layer for parsing the input.  I would also avoid hard-coding the filename.

Writing using namespace std; is considered bad practice.

The if-else inside the for-loop is pointless.  It just means that currow >= 0 was a poor termination condition.

I find the "cur…" prefixes on your variable names annoying.  What's "curve c"?  What's "currow" — does it rhyme with "furrow"?  As for "curidx", how about just i?

The timing printout should go to standard error to avoid contaminating the output.  You can avoid the (double) cast by writing 1000.0 to trigger floating-point arithmetic.

#include <ctime>

#include <algorithm>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

template<typename T>
class Input {
  public:
    Input<T>(std::istream &in) : in(in) {}

    bool next_row(std::vector<T> &entries) {
        entries.clear();
        std::string line;
        if (!std::getline(this->in, line)) {
            return false;
        }
        std::stringstream ss(line);
        for (T n; ss >> n; ) {
            entries.push_back(n);
        }
        return true;
    }

  private:
    std::istream &in;
};

int main(int argc, char *argv[]) {
    std::clock_t start_time = clock();

    // Input from either a file or STDIN
    // http://stackoverflow.com/a/2159469/1157100
    std::shared_ptr<std::istream> input(&std::cin, [](...) -> void {});
    if (argc >= 2 && std::string("-") != argv[1]) {
        input.reset(new std::ifstream(argv[1]));
    }
    Input<int> triangle(*input);

    // For each entry in each row "b", add the greater of the two entries in
    // row "a" above.  Row "b" then contains the maximum path sum from the
    // top up to that point.
    std::vector<int> a, b;
    for (triangle.next_row(a); triangle.next_row(b); a = b) {
        b[0] += a[0];
        for (std::vector<int>::size_type i = 1; i < a.size(); i++) {
            b[i] += std::max(a[i - 1], a[i]);
        }
        b[b.size() - 1] += a[a.size() - 1];
    }
    std::cout << *std::max_element(a.begin(), a.end()) << std::endl;

    std::cerr << "Execution time - "
              << ((std::clock() - start_time) * 1000.0 / CLOCKS_PER_SEC)
              << "ms." << std::endl;
}


Find a number which equals to the total number of integers greater than itself in an array

Let's re-think the problem a little. Let's start as you suggest, by discarding negative values and sorting the array (I'm going to use descending order):

A = sorted([x for x in A if x >= 0], reverse=True)

Now that we have all positive values in descending order, we find a really simple solution to this problem: if any value equals its own index in the array (which is equivalent to how many values are greater than it in the array), then we return 1:

return 1 if any(v == i for i, v in enumerate(A)) else -1

You can see this if you consider a sample array--I'll borrow your example--such as [4,7,8,9,11]. Once sorted in descending order, we can pair each value with its index to get [(0, 11), (1, 9), (2, 8), (3, 7), (4, 4)]. Because of the sorting, the index will always represent the number of values in the array greater than the value at that index.

The exception to this trend is when you have multiple, equal integers, in which case we need to modify this list to not keep incrementing when iterating across duplicate values. E.g., for A = [3, 3, 3, 3, 2, 1], we need the resulting list to be [(0, 3), (0, 3), (0, 3), (0, 3), (4, 2), (5, 1)]. You can solve this using a list that retroactively fixes the enumerated list:

for i, v in A[1:]:
    if v == A[i-1][1]:
        A[i][0] = A[i-1][0]

The final function looks like the following:

def solve(A):
    A = sorted([x for x in A if x >= 0], reverse=True)
    A = list(map(list, enumerate(A)))
    for i, v in A[1:]:
        if v == A[i-1][1]:
            A[i][0] = A[i-1][0]
    return 1 if any(v == i for i, v in A) else -1


Thread-safe object cache, for read, high performance in .NET

the .NET Dictionary is thread-safe, as long as it is used only in read access, thus not requiring locks in reading methods.

You are playing with fire here.  Your statement is only true iff no thread will modify the dictionary.  If any of them do, which is about impossible to avoid in a cache, then a lock on both the reading and the writing code is required.  A natural consequence of not being able to reliably read a data structure while it is in the process of being modified.

The ReaderWriterLock/Slim classes were designed to provide you this kind of locking.  You must acquire a reader lock when you read, a writer lock when you write.  Multiple threads can acquire a reader lock so you won't have any serious overhead as long as the cache is productive. The Slim version uses a low cost locking primitive which can reduce the lock cost somewhat.  But it is no cure when there's a lot of write contention, no magic formula exists for that.  If you do have a lot of write contention then double-check if the old ReaderWriterLock may give better throughput.

And be sure to checkout the .NET 4 MemoryCache class.


making your code harder to read:

lack of docstrings
lack of comments
unwarranted indentation using an else: after a "disruptive if"
(transferring execution with return, break, continue)
(Here, you are using this with otherwise empty "if-parts":
you could negate the conditions and just use the former else:-statements. Hello again, indentation.)


Find files by pattern and copy to target location

If you want to recurse also into sub-folders, you should use os.walk:

import os
import shutil

def get_files_recursively(start_directory, filter_extension=None):
    for root, _, files in os.walk(start_directory):
        for file in files:
            if filter_extension is None or file.lower().endswith(filter_extension):
                yield os.path.join(root, file)

def selective_copy(source, target, file_extension=None):
    for file in get_files_recursively(source, file_extension):
        print(file)
        shutil.copy(file, target)
        print("The following file has been copied", file)

if __name__ == "__main__":
    selective_copy("/Users/my_user_name/Desktop/newPDFs",
                   "/Users/my_user_name/Desktop/oldPDFs",
                   ".pdf")

As stated in the documentation, this is actually faster than os.listdir since Python 3.5:

  This function now calls os.scandir() instead of os.listdir(), making
  it faster by reducing the number of calls to os.stat().

I also

added a if __name__ == "__main__": guard to allow importing this module from another script without running the function
pulled the constants out into the calling code to make it re-usable
used is instead of != to compare to None
used str.endswith instead of a regular expression to avoid some overhead
changed the names to adhere to Python's official style-guide, PEP8.


Flux architecture implementation (vanilla JS)

First of all, Flux is not to be confused with Redux. While both have similarities, the main difference is that Flux allows multiple stores while Redux advises only using one store per app for simplicity. The following will talk about Redux.

/*
 * dispatch is a core function, directing every action
 * to the proper reducer depending on the `type`
 */
const dispatch = action => {
  action.type === 'UPDATE_PAGE' ?
    UPDATE_PAGE(model, action.page)
    : null;
};

Dispatch doesn't actually "direct" the action to the right reducer. It simply invokes the reducer, supplying it the current state and the dispatched action. It's actually the reducer that does the pattern matching/selection of what logic runs with which action.

/* a reducer method, more are easily added */
const UPDATE_PAGE = (model, newPage) => {
  let newState = Object.assign({}, model);
  newState.page = newPage;
  updateState(newState);
};

A reducer is a pure function which takes 2 arguments, the current state and the dispatched action and returns the new state, based on the state and the passed action. You can think of it as the "equation" part of the app (yes, like a math equation). Reducers look like:

const initialState = { count: 0 }

const reducer = (state = initialState, action) => {
  switch(action.type){
    case 'INCREMENT':
      return {...state, count: state.count + 1 }
    case 'DECREMENT'
      return {...state, count: state.count - 1 }
    default:
      return state
  }
}

There's several reasons why reducers are designed this way.

The reducer is pure. Its result is not affected by anything other than its inputs, making it stupid easy to test.
It's just a data transformer. You can easily test the logic without fancy mocks, stubs or spies because there's nothing to mock, stub or spy.
You can easily compose reducers. You can divide the state into sections, each with its own reducer. Redux provides a handy combineReducers utility function for it.
At the end of the day, reducers are just functions. Not a fancy service class, not a magical method, not some fancy concept invented by someone, it's just a function.

Redux is so simple, that if you just overheard someone in the pub talking about what it does, you can easily implement it yourself. It's effectively a pub-sub library, except that it also manages and holds state, and only ever emits one kind of event - a state change.

// my-redux.js - The only part that is "Redux"
export const createStore = reducer => {
  const subscribers = []
  let currentState = null

  return {
    getState(){
      return currentState
    },
    subscribe(fn){
      subscribers.push(fn)
      fn(currentState)
    },
    dispatch(action){
      currentState = reducer(currentState, action)
      subscribers.forEach(fn => fn.currentState)
    }
  }
}

// reducer.js - Where your app's logic goes.
const initialState = { count: 0 }

export const reducer = (state = initialState, action) => {
  switch(action.type){
    case 'INCREMENT':
      return {...state, count: state.count + 1 }
    case 'DECREMENT'
      return {...state, count: state.count - 1 }
    default:
      return state
  }
}

// app.js - How the app is brought together
import {createStore} from './my-redux'
import {reducer} from './reducer'
import {YourComponent} from './your-component'

const store = createStore(reducer)

YourComponent({
  mount: 'somewhere',
  onmount(){
    store.subscribe(state => {
      this.setYourState(state)
    })
  },
  render(state) {
    return (<button onclick="store.dispatch({ type: 'STH', data: 'NOT VALID JSX BUT WHATEVER' })">Click Me</button>)
  }
})

You can read more about the three principles of Redux and how it's just a guiding concept rather than an actual implementation.


Attempting a Strategy design pattern in JS

There are some issues with your class, but I don't think that they are so specific to implementing a strategy pattern.

addToPage() {
    this.statement = document.createElement("p")
    this.statement.innerHTML=this.flying.fly()
    document.body.append(this.statement)
}

This assumes there is a global document variable, and that statement is part of the abilities object. If such a method is present, I would expect document to be a parameter of the method and statement to be a local variable. But even that doesn't seem right because you would be mixing representation (a paragraph "p") and a data class.

//interface for behaviors
class FlyBehavior {
    fly() {
        null
    }
 }

Now that doesn't seem right. If you have JS ducktyping then you don't need this class. Furthermore, specifying null is just asking for null pointer exceptions at a later stage.

this.abilities = new DuckAbilities()

OK, so now we have DuckAbilities object but without a valid state, just null, which we then adjust in the next call. There seem to be two ways of resolving this issue:

having the fying behavior as parameter to the DuckAbilities constructor;
removing the DuckAbilities altogether and just assigning the various flybehaviors to a field.

So when we're using classes anyway, lets implement it using those.

I've created an "abstract" class Duck because we require inheritance there. I don't like to create an interface for the strategies because JavaScripts duck-typing should be sufficient.

'use strict'

class Duck { // this is the context
    constructor(flyAbility) {
        // ES2015 only, avoid instantiation of Duck directly
        // if (new.target === Abstract) {
        //  throw new TypeError("Cannot construct Abstract instances directly");
        // }

        this.flyAbility = flyAbility;
    }

    // this is the operation, returning the flyBehavior as a string
    showFlyBehavior() {
        return "This duck " + this.flyAbility.flyBehavior();
    }
}

// Strategy interface is missing due to JS ducktyping

// Strategy #1
class DoesFly {
    // with algorithm #1
    flyBehavior() {
        return "flies";
    }
}

// Strategy #2
class DoesNotFly {
    // with algorithm #2
    flyBehavior() {
        return "doesn't fly";
    }
}

// Context #1
class Mallard extends Duck {
    constructor() {
        super(new DoesFly());
    }
}

// Context #2
class Rubber extends Duck {
    constructor() {
        super(new DoesNotFly());
    }
}

let duck = new Mallard();
console.log(duck.showFlyBehavior());

duck = new Rubber();
console.log(duck.showFlyBehavior());

Sorry about using NodeJS, but in principle only console.log is NodeJS specific ... I hope.


Robust code does not assume the first char in buf is not '\0'.

This is a pedantic point, but user IO is a hacker paradise - best to code defensively.

Instead of:

size_t str_len;
while (fgets(buf, sizeof(buf), fp) != NULL) {
  str_len = strlen(buf);
  if(buf[str_len - 1] != '\n')
    printf("Didn't read whole line!\n");
  else {
    buf[str_len - 1] = '\0';

use to prevent undefined behavior (UB) with buf[str_len - 1].

while (fgets(buf, sizeof(buf), fp) != NULL) {
  size_t str_len = strlen(buf);
  if (str_len == 0 || buf[str_len - 1] != '\n') {
    printf("Didn't read whole line or embedded null character detected!\n");
  } else {
    buf[str_len - 1] = '\0';


Systematically analyzing dice roll outcomes


Increase the speed of this python code for text processing

Getting rid of the print statement fixed it thanks all!

import multiprocessing
import datetime

class line_Worker(object):
    def worker(self, chunks):
        for l in chunks:
            num = 0
            for num in range(100):
                print l, num#clearing this made the time 4 seconds thanks all!!
        return

if __name__ == '__main__':
    lines = [line.rstrip('\n') for line in open('words.txt')] #opens file and saves to list
    chunkNum = len(lines) / 26
    wordLists = [lines[x:x + chunkNum] for x in range(0, len(lines), chunkNum)]#divides list by 4 and saves to list of lists
    jobs = []
    timeStart = str(datetime.datetime.now())

    for i in range(27):
        p = multiprocessing.Process(target=line_Worker().worker, args=(wordLists[i],))
        jobs.append(p)
        p.start()
    for p in jobs:
        p.join()  # wait for the process to finish

    timeStop = str(datetime.datetime.now())

    print timeStart
    print timeStop


Function to return percentages in Python

In Python 3.0 or later, you do not need to explicitly convert your numbers to float. This is because the / operator always does floating point division (the // operator does "floor" division).

For older versions of Python (2.2 or later), you can use:

from __future__ import division

which changes the old meaning of / to the above. This makes the operation of / more predictable as the result no longer depends on the type of the inputs.


Appending to an array

The global iteration variable is used as the index to set objects in the global userArray. This implementation practically appends items to the array:

userArray[iteration] = new Object(),
userArray[iteration].id = info.users[x].id,
userArray[iteration].name = info.users[x].first_name + ' ' + info.users[x].last_name
userArray[iteration].billableHours = 0;
userArray[iteration].totalHours = 0;
iteration++;

A simpler alternative is to use the push method of arrays instead of the iteration variable.
Also, instead of setting the fields one by one,
it will be shorter to use an object literal:

userArray.push({
  id: info.users[x].id,
  name: info.users[x].first_name + ' ' + info.users[x].last_name,
  billableHours: 0,
  totalHours: 0
});

Data structures

In callback2,
for each time entry,
you loop over userArray until you find a user with the matching id.
You could avoid this nested loop by using a mapping of user ids to users.
If you don't need to preserve the ordering of users,
then you can drop userArray in favor of the map.
If you need to preserve the ordering, you can keep both.

Punctuation

The punctuation here is messy and potentially buggy:

userArray[iteration] = new Object(),
userArray[iteration].id = info.users[x].id,
userArray[iteration].name = info.users[x].first_name + ' ' + info.users[x].last_name
userArray[iteration].billableHours = 0;
userArray[iteration].totalHours = 0;
iteration++;

Each line should have ended with a ;, instead of , or nothing.

Don't repeat yourself

The options and options2 variables are almost identical.
Try to avoid copy-pasting,
use helper methods or benefit from JavaScript's prototypal inheritance instead.

Naming

Instead of numbering in names such as options1, callback1, and others,
it would be better to use more meaningful names.


Query for combining two SELECTs to get active users and 1 inactive user

Using a CTE will make this query a lot cleaner and probably speed it up a bit as well.

WITH UnionTable AS
(
    SELECT     pk_userid,
               username,
               1 AS active
    FROM       dbo.tbluser AS u
        INNER JOIN tblCustomer AS customer ON u.pk_userid = customer.fk_userid
    WHERE      ( customer.fk_projectid = @projectid
                 AND customer.fk_orderid = @orderid )
    UNION
    SELECT u.pk_userid,
           u.username AS username,
           0        AS active
    FROM   dbo.tbluser AS u
    WHERE  u.pk_userid = @userid
)
SELECT
        pk_userid
        , username
        , CAST(MAX(active) AS BIT) AS active
FROM UnionTable
GROUP BY pk_userid, username
ORDER BY username

The only thing that concerns me is that you label 2 tables in the first select (nested query) but you don't specify which table you want the pk_userid or username to come from, are they only available in the user table? Even if they only exist in the one table, you should get used to using the aliases you create so that it is clear where the columns are being called from.

You should also make sure that your aliases are meaningful as well.  I changed c to customer but I left u as u because user is a reserved word in SQL


Design-wise, using an Enum is entirely appropriate -- they were added to make "magic" constants easier to work with by giving them informative debugging names and easier containment checks.

Using a dictionary to tie the two enums together is unnecessary in this case as it makes more sense, and is easily possible, to have color be an attribute of each Weekday.

Whether Color is itself an enum depends on what you will be doing with the colors:

do you need actual color values?
is the color value going to be sent to another system, or stay inside your own program?

Whether or not you have a separate Color enum, a good way to combine those two things is like so (shown using aenum1, but can be done with the stdlib Enum2:

from aenum import AutoNumberEnum

class WeekDay(AutoNumberEnum):
    _init_ = 'color'
    #
    MONDAY = 'red'
    TUESDAY = 'green'
    WEDNESDAY = 'blue'
    THURSDAY = 'green'
    FRIDAY = 'red'

and in use:

>>> list(WeekDay)
[<WeekDay.MONDAY: 1>, <WeekDay.TUESDAY: 2>, <WeekDay.WEDNESDAY: 3>, <WeekDay.THURSDAY: 4>, <WeekDay.FRIDAY: 5>]

>>> WeekDay.MONDAY
<WeekDay.MONDAY: 5>

>>> WeekDay['MONDAY']
<WeekDay.MONDAY: 5>

>>> WeekDay.MONDAY.color
'red'

If you decide to use an enum for color, simply assign that instead of, for example, 'red'.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

2 The stdlib version (without the members):

class WeekDay(Enum):
    #
    def __new__(cls, color):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        obj.color = color
        return obj
    #
    # members here


RandomCount class: Randomising numbers in an array and generating them in a random order

Here's a simple algorithm lifted directly from the Collections source code. It is modified to shuffle an int[] in-place. That is, the array passed in will be modified. You probably want to give clients the opportunity to specify their own Random instance in a constructor. If you keep concrete inheritance, it might also make sense for the Random to be stored in RandomCount.

public final class SimpleRandomCount extends RandomCount {
    private final Random random = new Random();

    public SimpleRandomCount(int size) {
        super(size);
    }

    protected void randomise() {
        this.shuffleInPlace(array(), this.random);
    }

    private void shuffleInPlace(final int[] values, final Random random) {
        for (int i = values.length; i > 1; i--) {
            final int swapIndex = random.nextInt(i);
            final int temp = values[i - 1];
            values[i - 1] = values[swapIndex];
            values[swapIndex] = temp;
        }
    }

    public static void main(String [] args){
        RandomCount count = new SimpleRandomCount(5);
        System.out.println("Array is " + Arrays.toString(count.array()));
    }
}

Unrelatedly, it's probably a Bad Idea to expose your raw array in a public method like array(). If you must use extension instead of a RandomCount interface, either make the array member variable protected or provide a protected direct accessor. Clients using the public accessor should only have access to a copy of the array. Otherwise they're going to do Bad Things to it, and that will affect the internals of your class.


Reformatting a structured string like "a-b-c|A-B-C" into "a-A|b-B|c-C"

To start, I must say that I wish I was writing JS like this in 2016. I have only recently been becoming acquainted with the newer features ecmascript-6 has to offer. After looking at the other answers to the post you mentioned I would have suggested they consider using destructuring assignment, but I doubt it would help for your code.
For readability it can be a great idea to use functional code, but yes performance can suffer because each iteration calls a function, which adds to the call stack.
This code makes great use of template literals and arrow functions. It also has consistent indentation.
The template literal may be considered excessive, since it only contains interpolated values. The string concatenation could be achieved with the + operator - instead of:
 part.map((str, index) =>
       `${result[index]}${mainSep}${str}`

It could merely be:
 part.map((str, index) =>
       result[index] + mainSep + str

Which would save a few characters but also should be faster. See this jsBin for a comparison, as well as this answer to Most efficient way to concatenate strings in JavaScript?  which has a link to an updated JSPerf. The graphs don't appear to be loading in my browser but in MacOS FF 77 the concat appears to be fastest with the template literal 4% slower. In Chrome 83.04 the results were similar - template literals appeared to be 22% slower than appending.
I forgot that reduce() started with the 2nd element when no initialValue is supplied. While it may not be a huge improvement it does mean one less iteration...


Dynamic insert function for PDO (for any case)

I don't see any point in this function in its present form.
Given you've got a general purpose query function,
function pdo($pdo, $sql, $args = NULL)
{
    $stmt = $pdo->prepare($sql);
    $stmt->execute($args);
    return $stmt;
}

it will be cleaner, easier to use and more readable to have a conventional SQL than such random rags of a code:
$session_id = '1000000001';
$createdBy  = 12;

$sql = "INSERT INTO web_statistics (session_id, username, createdBy) VALUES (?,?,?)";
pdo($pdo, $sql, [$session_id,  'boss 21', $createdBy]);

The same goes for SELECT and UPDATE. You can find a complete set of examples by the link above.
Update.
Looks like this question got some traction, due to some mysterious ways of Stack overflow. It means it will attract people other than the OP, who may have the same question but have different code, or just curious about Dynamic insert function for PDO in general. Well then, I must admit that the answer is rather a trick and too localized, being focused on the actual code in the OP. For the present code, where different query parts are still hardcoded in the different function parameters, it is indeed makes a lot more sense to have them hardcoded in the form of a conventional SQL query instead.
But of course the common idea of a dynamic insert function for PDO is different. it's rather a function that is called like this:
prepared_insert($pdo, $table_name, $data);

where $data is an associative array like this
$data = [
    'name' => $name,
    'password' => $hashed_password,
];

Well then for this case I've got a simple INSERT helper function for PDO Mysql
function prepared_insert($pdo, $table, $data) {
    $keys = array_keys($data);
    $keys = array_map('escape_mysql_identifier', $keys);
    $fields = implode(",", $keys);
    $table = escape_mysql_identifier($table);
    $placeholders = str_repeat('?,', count($keys) - 1) . '?';
    $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
    $pdo->prepare($sql)->execute(array_values($data));
}

Note that his function will need a helper function of its own,
function escape_mysql_identifier($field){
    return "`".str_replace("`", "``", $field)."`";
}

to protect identifiers added to the query.


Removing the largest values encountered so far in a list

You are using a C++ compiler!

So you should also use its features:

don't declare all variables up front but as late as possible
don't using namespace std; that only gives you trouble later on
you don't need to return 0; at the end of main

Formatting

Your formatting can be improved. You should use more spaces especially around (binary) operators, this makes it easier to parse (or rather tokenize) the code with your eye.

Naming

You have nearly only single letter names which is bad. The fact that two of them look like macro names does not make it better. Consider:

N -> populationHeadCount
M -> executionCount
val -> currentVisitorWealth
visits -> stillLivingWealthiest

Unused variable

The variable i is initialized and incremented but never read.

Inserting "the king"

Your code unconditionally inserts the wealth val even if it is the king (-1), thus introducing even more entries in visits.

Speed up

Reading rules more closely than you have given them here yields:

  You may assume that no two citizens have the same wealth.

Which makes this problem a perfect fit for an std::set (as mentioned by Loki):

#include <iostream>
#include <set>
#include <algorithm>

int main() {
  int populationHeadCount, expectedExecutionCount;
  std::cin >> populationHeadCount >> expectedExecutionCount;
  std::set<int> stillLivingWealthiest;
  int executionNumber = 0;
  while (executionNumber < expectedExecutionCount) {
    int currentVisitorWealth;
    std::cin >> currentVisitorWealth;
    if (currentVisitorWealth == -1) {
      std::cout << *--stillLivingWealthiest.end() << std::endl;
      stillLivingWealthiest.erase(--stillLivingWealthiest.end());
      ++executionNumber;
    } else {
      stillLivingWealthiest.insert(currentVisitorWealth);
    }
  }
}

Explanation: A std::set stores the elements sorted from minimum to maximum, so we only need to look at the end to get and delete the maximal element.