The tl;dr answer to your questions are: Timing differences are related to your coding, and not the algorithm itself. Mostly due to how you handle arrays in-place, or methods for copying.

With that out of the question, let us review the code and in particular the code smells:

In general nicely written code – Let us start with the positive. Your code is mostly clean and easy to read. Good spacing, and reasonable names for variables and methods.
Functions within functions – Hiding the actual sorting methods within the benchmark methods, removes the potential for using your methods outside of the actual benchmark methods. Not wise. I could understand hiding the partition() method as that is intrinsic to the quicksort() implementation, and similar for the merge() to be included within mergesort(). As that would still expose the main sorting functions.
In-place vs new arrays – Your quicksort() changes the array in-place, and doesn't use extra storage, whilst the mergesort() creates a bunch of extra arrays whilst it is dividing and conquering. This gives the quicksort() and unfair advantage, and renders the quicksort() with a nasty sideeffect of changing the array. This could be a wanted effect in some cases, but mostly you do not want to change the array passed into the function.
Try to avoid While True: – In general, a lot of these can be avoided by flipping and turning the statements a little. Especially when used to loop to a certain point, where you use break to exit the loop, it is a lot nicer to flip it around. Instead of this:

i = low - 1
while True:
  i += 1
  if array[i] >= pivot
    break

do this:

i = low
while array[i] < pivot:
  i += 1

Note that the initial values has changed, and the condition has been flipped around. But the end result is the same, and the latter is easier to read and understand.
Swapping of variables – The technique you use for swapping the array elements, can be replaced by a neater statement in Python:

array[i], array[j] = array[j], array[i]

Behind the scenes, this will work exactly like your swapping, but it slightly easier on the eye, and avoids the unnecessary temp variable.
Avoid multiple len(m) on the same array – There is actually time to spare by not doing this operation multiple times when the array in question doesn't change.
range() vs xrange() – In Python 2, there is a bit of a difference between these two. The first generates the list, whilst the latter is a generator giving each number as we move on. This has a memory and performance impact when the range is getting large, like for 2**24...
Looping vs slicing – Python has some really nice slice operators which means that stuff like:

for i in range(j, len(left)):
  result.append(left[i])

can be replaced with:

result.extend(left[j:len(left)]

Note that I've also switched to extend, and not append, to proper handle the case if the slice is empty, and not actually add the slice to result.

Speed implications

When trying to compare the various implementations I had to make some slight changes to original code, so here are the simple changes with the new names of the main sorting method:

quicksort – Your original code but with a duplication of the array to be sorted, to even out the playing field, and giving all sorters the same array to sort.
hquicksort – My implementation flipping the while True statements around, and implementing the slightly simpler swap method. I also removed references to i and j, with low and right. Code included at end.
sort – An quicksort implementation as implemented in Quicksort with Python. A rather fast recursive, new array, no indices implementation.
SOquicksort – The in-place solution of the same thread (linked above).
mergesort – Your implementation of mergesort.
hmergesort – Your implementation with replacing of the len(m) with precalculated values, and using xrange() instead of range(). Code not included.
imergesort – Taking it even one step further, using slicing instead of the loop appending of the results. Code included at end.
sorted – Using the Python default sorting methods of sorted().

The timing of these using timeit for n=2**14 with 10 testruns gave the following (when run using repl.it (Do note that the code given there are messy and more of a sandbox rather than a good example of coding :-)) result:

quicksort  : 0.645922899246
hquicksort : 0.563888788223
sort       : 0.527070045471
SOquicksort: 0.455115795135

mergesort  : 1.35985612869
hmergesort : 0.970368146896
imergesort : 0.714356899261
sorted     : 0.0575048923492

As can be seen the quicksort was improved quite a bit with even relatively small changes in your code, but better implementations does exist. For the mergesort I didn't look for alternative implementations, but the changes I made it ran in half the time, resulting in a faster time compared to your implementation of quicksort.

Do also note that the timings varied slightly between runs, but the relation between the order was usually kept as given in the listing. As seen by the timing on sorted, we've not reinvented the wheel in any of these implementations, and for practical purposes we're better of using the default sort methods which runs in 1/10th of the time!

Code inclusion

hquicksort

def hquicksort(array, low, high):
  if low < high:
    p = hpartition(array, low, high)
    hquicksort(array, low, p)
    hquicksort(array, p+1, high)

def hpartition(array, low, high):
  pivot_index = random.randint(low, high)

  pivot = array[pivot_index]

  while True:
    while array[low] < pivot:
      low += 1

    while array[high] > pivot:
      high -= 1

    if low >= high:
      return high

    array[low], array[high] = array[high], array[low]

    low += 1
    high -= 1

I could possibly also get rid of the remaining While True:, but the revision does show my point. Note that to get it to work exactly like your code, I also had to add the two last lines to move the index pointers forward.

imergesort

def imergesort(m):
  len_m = len(m)
  middle = len_m//2

  if len_m <= 1:
    return m

  return imerge(imergesort(m[:middle]), imergesort(m[middle:]))

def imerge(left,right):
  result = []
  len_left = len(left)
  len_right = len(right)
  i, j = 0, 0

  while i < len_left and j < len_right:
    if left[i] <= right[j]:
      result.append(left[i])
      i += 1
    else:
      result.append(right[j])
      j += 1

  result.extend(left[i:len_left])
  result.extend(right[j:len_right])

  return result


Allow users to add custom queries to Mustache variables

I don't know anything about Mustache, so just a note about the code: $_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php' is duplicated, it could be extracted out to a local variable:

$userFile = $_SERVER['BASE_DIR'] . '/customcontents/' . $username . '.php'
if (file_exists($userFile)) {
   include($userFile);
}

(You might have ideas for a better name.)

Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler:

  Put the result of the expression, or parts of the expression,
  in a temporary variable with a name that explains the purpose.

And Clean Code by Robert C. Martin, G19: Use Explanatory Variables.


Just a small comment from me.  I'm not so sure about the need for the method SetJob().  It seems like there is a requirement for this method to be called before the Start() and once called you wouldn't call it again?

Hence perhaps I might look at moving this to the constructor that would hopefully imply this concept?  Also that way you can't change the job.  This is of course made with the assumption you aren't looking at changing jobs once a new ScheduledJob has been setup.

Also probably what Stylecop might pick up anyway as suggested by Leonid;

I personally wouldn't recommend using an _ for a variable within a method i.e. _nowMin
Same applies for the private method _timer_elapsed()


Client Side JavaScript [aka Greasemonkey] Key Event Handler

Future-proofing
The unreachable else that's not entirely unreachable
In your final else-statement you have an alert that screams at the user "too many characters!". First of all, don't use alert(..), especially for something the user has no control over. Use console.error(..) instead, or just ignore it.
If each handler is executed sequentially after the last one is executed, the else statement can not be reached. There is however no guarantee that this is the case as far as I know. Consider writing at least a bit defensively and notice that the situation where more than commandLength character actually means that your character was added before the other handler cut the characters.
The keys command that is actually not a command
You are abusing the $commands variable to store the keys of that array. If in the future you decide that you want to have commands of length 4... you have a problem. Instead use let keys = Object.keys($commands);.
Clearing the keyQueue
You are clearing the queue after you are executing $commands[keyQueue]();. Depending on how long executing that function takes, that can take a long time. Do it as soon as you can.
Magic number
The -2 in keyQueue.slice(-2); is a magic number. What you actually meant to say is likely keyQueue.slice(-commandLength + 1);. Future-proof your code by eliminating that number and replace it by the actual calculation. You can probably even move this code to the top to group together with the other code to determine the key combination.
Issues with style
ES6 and var
You are using const in your code. If you decide to use const, also use let for non-const variables, as they behave much better than variables declared with var.
Comma-seperated declaration of variables
I am not a fan of comma-seperated declaration of variables. If the declaration is split over multiple lines, it is error-prone and easily allows you to drop variables in the global scope. If it is on one line, like you did, it becomes unreadable and falls off the right side of the screen. Just declare each variable on a single line.
Braces
Your usage of braces is inconsistent. I recommend always having a newline after an opening brace.
Mixing of logical or and logical and
Know which operator is evaluated first, the logical or operator or the logical and operator? Yes? Congratulations, because many developers don't. To avoid ambiguity and possible errors in your code, add parenthesis when you have both a logical or and a logical and in a boolean expression.
Unused variable
nOffset does not seem to be used. Lets just delete it.

I would rewrite your code like this:
/* Key Event Handler */
(function () {
  const commandLength = 3;

  //Last pressed keys
  let keyQueue = "";

  let keys = Object.keys($commands);

  document.onkeypress = function (oPEvt) {
    let oEvent = oPEvt || window.event;
    let nChr = oEvent.charCode;
    let sNodeType = oEvent.target.nodeName.toUpperCase();

    if (nChr === 0 ||
        oEvent.target.contentEditable.toUpperCase() === "TRUE" ||
        sNodeType === "TEXTAREA" ||
        (sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT")
       ) {
      return true;
    }

    keyQueue = keyQueue.slice(-commandLength + 1) + String.fromCharCode(nChr);
    if (keys.includes(keyQueue)) {
      keyQueue = "";
      $commands[keyQueue]();
    }

    return true;
  }
}());


Profiling and Benchmarking
Rather than benchmarking, which just does total time, you would be better off profiling, which is like recursive benchmarking.  I recommend you use the ruby-prof gem.
I profiled your code thusly:
require 'ruby-prof'

n = 500000
puts "========================DOM 1============================="
RubyProf.start
(1..n).each { |n| probability_dominant_1(n, n, n) }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

puts "========================DOM 2============================="
RubyProf.start
(1..n).each { |n| probability_dominant_2(n, n, n) }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

puts "========================DOM 3============================="
RubyProf.start
(1..n).each { |n| probability_dominant_3(n, n, n) }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

And got the following results:
========================DOM 1=============================
Measure Mode: wall_time
Thread ID: 1975060
Fiber ID: 22475080
Total: 4.755476
Sort by: self_time

 %self      total      self      wait     child     calls  name
 55.06      4.501     2.618     0.000     1.883   500000   Object#probability_dominant_1
 11.69      0.556     0.556     0.000     0.000  1434466   Fixnum#*
 10.14      0.482     0.482     0.000     0.000  1433660   Bignum#+
  7.95      0.378     0.378     0.000     0.000  1500000   Float#*
  6.60      0.314     0.314     0.000     0.000   934466   Bignum#-
  5.34      4.755     0.254     0.000     4.501        1   Range#each
  3.13      0.149     0.149     0.000     0.000   500000   Float#/
  0.08      0.004     0.004     0.000     0.000    24252   Fixnum#+
  0.00      4.755     0.000     0.000     4.755        1   Global#[No method]

* indicates recursively called methods
========================DOM 2=============================
Measure Mode: wall_time
Thread ID: 1975060
Fiber ID: 22475080
Total: 2.474247
Sort by: self_time

 %self      total      self      wait     child     calls  name
 60.31      2.258     1.492     0.000     0.766   500000   Object#probability_dominant_2
 10.67      0.264     0.264     0.000     0.000   952579   Bignum#+
  8.73      2.474     0.216     0.000     2.258        1   Range#each
  5.38      0.133     0.133     0.000     0.000   500000   Fixnum#*
  5.17      0.128     0.128     0.000     0.000   500000   Float#/
  4.73      0.117     0.117     0.000     0.000   500000   Float#+
  4.73      0.117     0.117     0.000     0.000   500000   Float#*
  0.28      0.007     0.007     0.000     0.000    31037   Fixnum#+
  0.00      2.474     0.000     0.000     2.474        1   Global#[No method]

* indicates recursively called methods
========================DOM 3=============================
Measure Mode: wall_time
Thread ID: 1975060
Fiber ID: 22475080
Total: 4.334434
Sort by: self_time

 %self      total      self      wait     child     calls  name
 50.85      4.074     2.204     0.000     1.870   500000   Object#probability_dominant_3
 17.44      0.756     0.756     0.000     0.000  2364956   Bignum#+
 16.66      0.722     0.722     0.000     0.000  3000000   Float#*
  6.00      4.334     0.260     0.000     4.074        1   Range#each
  5.42      0.235     0.235     0.000     0.000  1000000   Float#/
  3.39      0.147     0.147     0.000     0.000   476830   Bignum#-
  0.23      0.010     0.010     0.000     0.000    46340   Fixnum#+
  0.00      4.334     0.000     0.000     4.334        1   Global#[No method]

* indicates recursively called methods

Foreach function, these tables show the number of calls and time spent on function call, recursively all the way down.  Some portions, like the "range#each" can be ignored as part of of our testing overhead.
Looking at the results, I can spot why dominant_2 is the fastest.  Integer operations (FixNum) on a processor will always be faster.  Floating point (Float) is slow and floating point divisiondividing is slow, and big integers (integer numbers bigger than that hardware can natively support, typically 2^32 or 2^64) will also be slower.

Dom1 has 2M Float, ~2.4M BigNum, and ~1.4M FixNum operations.
Dom2 has 1.5M Float, ~1M BigNum, and ~530K FixNum operations.
Dom3 has 4M Float, ~2.3M BigNum, and ~46K FixNum operations.

Dom2 was the fastest because it has the fewest number of operations by far.
As a weak rule of thumb, when optimizing math, try to avoid BigNum and Float when feasible.  Also try to avoid things like converting numbers to strings and then back to numbers.
Conclusion
Know that more often though, that your slowdown will usually come from lots of branching and flow control, and being inefficient (like calculating the same things over and over rather than caching them), and those are the places to optimize.  If this problem were part of a larger, more complicated task, I can practically guarantee that your bottleneck would not be ANY of these functions, but something else entirely.


In play_match, the Club class should be responsible for updating its own score. You could define an update_points method taking the same parameter as the computes_point one (and calling it). Also, shouldn't compute_points be responsible for the conversion to int ?

I find it a bit awkward to have the __eq__ and the __gt__ base their logic on completely different fields.

In a club_index : as a general rule, you do not iterate that way over object in Python.
The pythonic way to write

def club_index(club_to_find, clubs):
    index = 0
    while index < len(clubs):
        club = clubs[index]
        if club.name == club_to_find:
            return i
        index += 1
    return -1

is

def club_index(club_to_find, clubs):
    for i,club in enumerate(clubs)
        if club.name == club_to_find:
            return index
    return -1

Now, if I was to write such a program, I wouldn't even create a class ( you can have a look at http://www.youtube.com/watch?v=o9pEzgHorH0 ). A dictionnary to map club names to score is pretty much everything you need but that's a different way to see the problem I guess.

Edit : Actual tested code added.

def get_new_scores(home_score,away_score,result):
    rating_diff = home_score - away_score + 100
    home_expected = 1 / (1 + 10**(-rating_diff/400))
    away_expected = 1 / (1 + 10**(+rating_diff/400))
    home_return = int(32 * ((result  )-home_expected))
    away_return = int(32 * ((1-result)-away_expected))
    return home_score+home_return,away_score+away_return

def main():
    with open("club.txt") as file:
        matches = file.readlines()

    clubs = dict()
    for match in matches:
        (home_str, away_str, result) = match.split(" ")
        clubs[home_str],clubs[away_str] = get_new_scores(clubs.setdefault(home_str,1000), clubs.setdefault(away_str,1000), float(result))

    for club in sorted(clubs, key=clubs.get, reverse=True):
        print(club + ": " + str(clubs[club]) + "\n")

if __name__ == "__main__":
    main()


To compute the length of a set difference, you only need to subtract the length of the intersection from the length of the set.
You could make use of the intersection when computing the differences. Subtracting the intersection gives the same result but processes fewer elements.

tags = set(tags)
predicted = set(predicted)

tp = len(tags & predicted)
fp = len(predicted) - tp
fn = len(tags) - tp

Note that I added spaces around operators to improve readability. I also used the & operator instead of the intersection method as a matter of preference.


Note: I'm assuming collection and unscoped are some sort of Enumerable objects.

The key to improving performance is to not do any unnecessary work. You're doing quite a bit of unnecessary work in #update_priority.

all_count = collection.find.count creates an Enumerator that isn't used. Let's get rid of that.

all_count = collection.find.count calculates the size is of that enumerator inefficiently. #count iterates the collection and counts how many elements it has. It is an O(n) operation. #size on the other hand, doesn't iterate the collection. It is an O(1) operation.

If this only happened once, this wouldn't be so bad, but this happens for every element of unscoped. Suppose unscoped has 100 elements and collection has 1000 elements. We're doing the same calculation a 100 times. That's a 100,000 unnecessary iterations! We can do better: only calculate the size once in #recalculate_priorities.

collection.find(_id: self._id).update('$set' => {priority: priority}) suffers from a similar problem. For each unscoped element at least 1 database query is performed. Again, we can do better: use a single query to update many records at once (a batch query) in #recalculate_priorities.

I've written some example code below. As I don't know any MongoDB, I made up an API for it.

def new_priority(collection_size)
  top      = 100
  priority = 0
  random   = rand(top)

  if TARIFFS[seller.tariff].cover?(random)
    lower = collection_size - top
    upper = collection_size

    return rand(lower..upper) # Floats are unnecessary
  else
    return rand(1..collection_size)
  end
end

def recalculate_priorities
  new_priorities = unscoped.map { |el| el.new_priority(collection.size) }

  unscoped.update(:priority => new_priorities)
end


Refactor PHP | Laravel Code, Optimisation needed to make code clean

You could exploit Laravel collections to achieve what you need.

Most of your code is checking for the presence/absence of props on your arrays. Laravel internally exposes and uses the Illuminate\Support\Arr class that contains a lot of useful methods to work with arrays without the hassles of checking for key existance.
It also allows you to use dot notation to get nested properties in a really simple way.

Laravel collection methods (documentation)  use this class where needed. Therefore, the refactored code would become really intuitive and should look like this (it may need a little bit of tweaking based on your userNotificationPreference and preferences arrays and how you retrieve them from the model:

$recipients->map->getUser()
    ->where("userNotificationPreference.preferences.{$sendMethod}", true)
    ->where("userNotificationPreference.preferences.specific-templates.0.{$notification->getTemplateCode()}.0.{$sendMethod}", true);

Note that I used ->map->getUser() that would be equivalent to:

$recipients->map(function ($recipient) {
    return $recipient->getUser();
})

However, if you really need to pluck the user instance through the user repository then you can do:

$recipients->map(function ($recipient) use ($userRepository) {
    return $userRepository->findByParams([
        'email' => $recipient->getUser()->email
    ]);
})->where(...);

and chain the where calls after that.

If any part of my code is unclear or doesn't work, let me know in the comments and I'll explain/fix it.


You shouldn't need to call Dispose and new up another context in the Save method. SaveChanges should be good enough.  I would recommend you make ClientService IDisposable and when that class disposes then dispose of the context as well.

Update from comment

to implement IDisposable on the IClientService

public interface IClientService : IDisposable

The will now require a Dispose method on any class that implements IClientService.  In the dispose method you should call the dispose method of the context.


Writing functions

A palindrome-checking function should accept a string parameter and return a result.  Your function takes its input from the keyboard (or stdin), which makes it not reusable.  If you want to accept keyboard input, it should be done outside the function.

Even more unusual is the fact that you return None if it's a palindrome, and return 0000 if it's not.  Why so many zeroes?  Why are both return values falsy?  The convention would be to return True or False.

Implementation

You're doing a lot of unnecessary things.

You can index and iterate over strings directly.  There is no need to convert it into a list.

There is no need to handle odd and even lengths as separate cases.

Der_Lett (a cryptic abbreviation for "dernière lettre"?) actually isn't the index to the last letter — it's off by one.  (Your code is correct, but weird.)

Style

PEP 8 naming conventions apply to your variable names, même en français.  That is, they should be lowercase.

Counting loops are nearly always better done using of range(), xrange(), enumerate(), or something from itertools.

Suggested solutions

Here is a simple loop that does the job.

def verifier_palindrome(mot):
    centre = len(mot) // 2
    for decompte in range(centre + 1):
        if mot[decompte] != mot[-decompte - 1]:
            return False
    return True

Here is a more compact way to write it, using a generator expression:

def verifier_palindrome(mot):
    return all(mot[i] == mot[-i - 1] for i in range(len(mot) // 2 + 1))


Unit testing a bash script manipulating the working directory path

Just 2 cents:

I'd quote the right hand side of the [[ ... = ... ]] to avoid pattern interpretation. Cf.

x=123
y=*2*
[[ $x =  $y  ]] && echo Equal without quotes
[[ $x = "$y" ]] || echo Not equal with quotes

I like naming the tests. I'd probably add a third parameter to assertEquals and include it in the report. It also improves readability. Inspired by Test::More for Perl.


Alternative way for checking an anagram pair

This wont ever work entirely correctly. What you did here can also be seen as calculating the hash of the 2 Strings. And just like you cannot use a hash to compare equality of 2 objects, you can't use your sumOfChars to compare if 2 strings are anagrams or not. (Simple counter example are the strings "ac" and "bb".)

On the other hand, that doesn't mean this idea is useless for exactly the same reasons as why we still provide a hashCode method when implementing equals.

If the 2 strings are more often NOT anagrams then they ARE anagrams, it can be a lot cheaper to first check if the sums are equal, and after that check for actual "anagram equality".

I suggest to update your isAnagram method to something like this:

public static boolean isAnagram(String s1, String s2) {
    if(s1.length() != s2.length() return false;
    if(sumOfChars(s1) != sumOfChars(s2)) return false;
    return sameLetterCount(s1, s2);
}

Notice that I also put the length() check in this method as well. The idea is actually the same. You start with a really cheap test that returns early in certain cases (strings of different length). Then you do a bit more expensive test that takes out most (but still not all) cases to return early again.
When those tests didn't fail, you got some good candidates to do the expensive actual checking for containing the same letters.

I have written it in my example so that it calls a different method. But you might as well just implement some letter counting algorithm right after the 2 if checks.


Finding nearest points and points within a radius

Bug

The internalPoints method has a bug:
you count the number of points that fall within the radius,
but then, instead of adding those points in the output array,
you take the first N points of the input array,
some of which may not be within the radius.
Try for example with this input:

Point[] points = {
        new Point(1, 2),
        new Point(19, 29),
        new Point(2, 3),
        new Point(5, 2)
};

Comparing distances

Do you really need to compare \$\sqrt{dx^2 + dy^2}\$ ?
Computing the square root can be expensive,
and comparing \$dx^2 + dy^2\$ would be enough.

public double dsquare(Point p) {
    double dx = p.x - this.x;
    double dy = p.y - this.y;
    return dx * dx + dy * dy;
}

Finding the nearest point

In this loop, the distance between point and the nearest point may be repeatedly recalculated:

Point p = points[0];
for (int i = 0; i < points.length; i++) {
    if (points[i].distance(point) < p.distance(point)) {
        p = points[i];
    }
}
return p;

You could save the known nearest distance in a variable to avoid repeated computations. Also, you could start iterating from i = 1 instead of i = 0:

Point nearest = points[0];
double nearestDistance = point.dsquare(nearest);
for (int i = 1; i < points.length; i++) {
    double distance = points[i].dsquare(point);
    if (distance < nearestDistance) {
        nearest = points[i];
        nearestDistance = distance;
    }
}
return nearest;

Simplify

The s variable in toString is pointless, you could directly return the concatenated value.


/* Asks the user for string input.
 * Returns a pointer to the string entered by the user.
 * The pointer must be freed.
 */

Slightly misleading in that this function doesn't ask for input. (As written it is not responsible for printing the prompt.)

Perhaps also should clarify the intended behavior:

If there is input that is not terminated by a newline, is that string returned?
When input is terminated with a newline, is the newline preserved in the returned string?

char* input()
{
    char *s = malloc(sizeof(char));  /* For the null character */

In C, char by definition is 1 byte. sizeof (char) is unnecessary and adds visual noise.

    if (s == NULL) {
        fprintf(stderr, "Error: malloc\n");
        exit(1);

It's usually considered poor behavior if calling a library function causes the entire program to terminate.  You should return an error value (e.g. NULL) and leave that decision up to the caller.

    }
    s[0] = '\0';

    /* Read characters one by one */
    char ch;

ch must be an int.  getchar returns an int precisely so that it can return a value outside the range of char (technically unsigned char) to indicate failure (i.e., the EOF value).  Otherwise you would not be able to distinguish EOF from a legitimate byte value.

    size_t s_len = 0;
    while((ch = (char) getchar()) != '\n') {
        if (ch == EOF) {

It's more idiomatic to check for EOF in the loop condition and then check for character values inside the loop body:

int ch;
while ((ch = getchar()) != EOF) {
    if (ch == '\n') {
        ...

Checking for EOF in the loop condition allows you to safely truncate ch to char throughout the entire loop body, which makes it a bit easier to reason about.

            exit(0);

Same thing here about terminating the program.  It's especially weird here since this exits with a success code and doesn't return the string to the caller.

        }
        s_len++;
        s = realloc(s, (s_len * sizeof(char)) + sizeof(char));

Never do x = realloc(x, ...).  If realloc fails and returns NULL, you will have lost the old value of x and will be unable to free it, resulting in a memory leak.  You instead should use a temporary variable:

char* newBuffer = realloc(s, ...);
if (newBuffer == NULL) {
  ...
}
s = newBuffer;

Again, sizeof (char) is noise.  You additionally should generally avoid sizeof (Type); it's not robust if the types change since you would need to edit more places (and neglecting to do so could lead to silent buffer overflows and introduce security vulnerabilities).  It's better to use sizeof expression where expression is based on the corresponding variable.  For example, if you want the code to be robust if the type of s changes (e.g. if you wanted to adapt the code to support wchar_t), you should do:

char* newBuffer = realloc(s, (s_len + 1 /* NUL */) * sizeof *s);
...

Finally, calling realloc for every byte read is grossly inefficient.  A better approach is to maintain a buffer where you keep track of its allocated size and to grow it exponentially (e.g. doubling in size) whenever you need more space.

        if (s == NULL) {
            fprintf(stderr, "Error: realloc\n");
            exit(1);

Same thing about terminating the program.  Also should do free(s); along this path.

int main()
{
    printf("Name: ");

I/O is normally buffered.  You should call fflush(stdout) afterward to ensure that the prompt is printed to the screen before waiting for input.


Is there a way to shorten a set of conditionals like this?

In short, the CSV parser is using the wrong data types. Whenever you have contiguous variable names, it screams "use an array!" If you at all, possibly can, use an array. That allows you to operate on it much, much more naturally, it's more flexible, and it's way less prone to human error.

If you used an array, this would be much, much simpler:

foreach ($this->sl as $k => $sl) {
    $this->sl = ($sl === null) ? "0" : $sl;
}

Since you seemingly can't use an array, your best bet is probably to either process it into an array, or use some nasty variable-variable hackiness to pretend it's an array.

$sl = array();
for ($i = 1; isset($this->{'sl' . $i}; ++$i) {
    $sl[] = $this->{'sl' . $i};
}

Or if (for some reason) you don't want to use an array:

for ($i = 1; isset($this->{'sl' . $i}; ++$i) {
    $this->{'sl' . $i} = ($this->{'sl' . $i} === null) ? "0" : $this->{'sl' . $i};
}


If using C++ is an option for you (which your tags suggest), then you might consider using std::swap for swapping the characters. You might also want to use isspace to check for whitespace other than ' '.

You could also write it all in a single function:

void reverse_every_word(char* s)
{
    char* front;
    char* back;
    while(*s != '\0')
    {
        // handle whitespace
        while(*s != '\0' && isspace(*s))
            s++;

        // skip to the end of the current word
        front = s;
        while(*s != '\0' && !isspace(*s))
            s++;

        // reverse
        back = s-1;
        while (front < back)
            std::swap(*front++, *back--);
    }
}


Implementing timeout of a resource (in this case a database connection)

Code

Acquire not aquire.
The scoped_thread move constructor is missing a &, and should have the signature scoped_thread(scoped_thread&&) = delete.
system_clock is the wrong clock type to use, as it's not monotonic (the user can adjust it whenever they choose). steady_clock would probably be the right choice here.
Since scoped_thread stores the thread object as a member, the scoped_thread constructor could use variable template arguments and perfect forwarding, rather than passing in a std::thread object. This makes the user code slightly shorter.
When declaring time constants (tlim, sleeping_time), it would be better to use std::chrono types at the point of declaration, rather than later on in the code, so that the constant has units associated with it directly.
(Style/Opinion:) Vertical spacing makes code easier to read:

using clock_type = chrono::system_clock;
using shared_deadline = std::atomic<clock_type::time_point>;

constexpr auto tlim=100;

template<typename T> void timeout(T& shared_resource,const shared_deadline& deadline)

With a little extra spacing, it's a lot easier to parse this visually as two using declarations, a constant and the start of a function.

Design - locking

There are a couple of places where the resource is locked and then unlocked again rapidly, e.g.:

    if((*shared_resource.aquire())==0)
    {
        *shared_resource.aquire()=1; // will replace by database connect
        std::cout << "Setting resource to " << (*shared_resource.aquire()) << "\n";

Maintaining the lock would be better, otherwise what's printed to std::cout may not be what you expect:

    auto proxy = shared_resource.aquire();

    if (*proxy == 0)
    {
        *proxy = 1; // will replace by database connect
        std::cout << "Setting resource to " << *proxy << "\n";

Design - cancelling / timeout behaviour

If you comment out every line after creating the timeout object:

auto th = std::make_unique<scoped_thread>(std::thread(timeout<LockWrapper<int>>, std::ref(shared_resource), std::cref(deadline)));

main() won't complete until the timeout finishes. This is probably not desirable behaviour.
There is no way to cancel the timeout without manually setting a deadline zero seconds in the future (i.e. dodgy hacks). Furthermore, the fixed sleep of 1 second inside timeout() means you may have to wait up to a second anyway.
Sleeping for one second in a loop seems like strange behaviour, since we know exactly how long we actually need to sleep for before waking up.
It is error-prone to manually increase the deadline every time an operation that requires the connection is used.

Changes

Some of the problems above can be solved by encapsulating the timeout functionality in a class, and using a std::condition_variable to do the timed waiting. This also allows the callback to be cancelled (or called immediately) if desired.

class ThreadedCallback
{
public:

    using clock_t = chrono::steady_clock;
    using duration_t = clock_t::duration;
    using action_t = std::function<void()>;

    ThreadedCallback(duration_t timeout, action_t const& action)
    {
        start(timeout, action);
    }

    ~ThreadedCallback()
    {
        cancel();
    }

    ThreadedCallback(ThreadedCallback&&) = delete;
    ThreadedCallback(ThreadedCallback const&) = delete;

    void restart(duration_t timeout, action_t const& action)
    {
        cancel();

        start(timeout, action);
    }

    void cancel()
    {
        {
            std::lock_guard<std::mutex> lock(m_mutex);

            if (!m_cancelled)
            {
                m_cancelled = true;
                m_cv.notify_one();
            }
        }

        assert(m_thread.joinable());
        m_thread.join();
    }

private:

    void start(duration_t timeout, action_t const& action)
    {
        assert(!m_thread.joinable());
        m_thread = std::thread([=] () { run(timeout, action); });
    }

    void run(duration_t timeout, action_t const& action)
    {
        std::unique_lock<std::mutex> lock(m_mutex);

        m_cancelled = false;
        m_cv.wait_for(lock, timeout, [&] () { return m_cancelled; });

        // note: this check can be removed (and cancel() renamed to call_now())
        // or a boolean flag added to cancel() to indicate whether the action should still be called anyway
        if (!m_cancelled)
            action();
    }

    std::thread m_thread;
    std::mutex m_mutex;
    std::condition_variable m_cv;
    bool m_cancelled;
};

int main()
{
    int int_value = 1;
    LockWrapper<int> shared_resource(&int_value);

    auto disconnect = [&] ()
    {
        auto proxy = shared_resource.acquire();
        *proxy = 0; // will replace by database disconnect
        std::cout << "Setting resource to " << *proxy << " after timeout occurred in thread " << std::this_thread::get_id() << ".\n";
    };

    auto timeout = std::chrono::seconds(5);
    ThreadedCallback callback(timeout, disconnect);

    constexpr auto tlim = std::chrono::seconds(50);
    constexpr auto sleeping_time = std::chrono::seconds(2);
    for (auto t = std::chrono::seconds(0); t < tlim; t += sleeping_time) // This loop simulates repeated database access
    {
        std::cout << "Slept for " << t.count() << " seconds. Sleeping for another " << sleeping_time.count() << " seconds\n";
        std::this_thread::sleep_for(sleeping_time);

        auto proxy = shared_resource.acquire();

        if (*proxy == 0)
        {
            *proxy = 1; // will replace by database connect
            std::cout << "Setting resource to " << *proxy << "\n";

            callback.restart(timeout, disconnect);
        }
        else
        {
            callback.restart(timeout, disconnect);
        }
    }

    std::cout << "done!" << std::endl;
}

This still doesn't solve the issue of manually restarting the timer with every access operation. Perhaps a timeout class like this would be better kept in the resource (or LockWrapper) itself.

For example, since we want the time after the last access, the Proxy class destructor could start the timeout (e.g. call a function in the LockWrapper to create a ThreadedCallback in a unique_pointer), and the Proxy constructor could call a function to clear that pointer (cancelling the disconnect operation).

Then the timeout would be directly tied to the access itself, and not have to be reset manually by user code.


Almost all of your conditions are error handling, so there's not a lot to clean up.  For clarity's sake, I would make your initial error handler a guard condition, which makes it much more obvious what's going on.  I would then break out all your inner functions into labeled functions, which makes it clear what you're trying to achieve:

QuestionGroupModel.find({group: group_name}).exec(function(err, groups) {
    if (err) {
        console.info("Error while lookup group info", err);
        return;
    }

    var deleteGroup = function(group) {
        QuestionGroupModel.find({group: groups[0].group}).remove(function(err) {
            console.info.apply(null, (err) ? ['error while deleting group', err] : ['groups %s was deleted', group]);
        });
    };

    var saveGroup = function(group) {
        group.save(function(err2) {
            if(err2)
                console.info('error while updating group info');
        });
    };

    groups[0].cnt = groups[0].cnt - questions.length;

    if (groups[0].cnt > 0) {
        saveGroup(groups[0]);  // That you have two different arguments for similar operations is a code smell.
    } else {
        deleteGroup(groups[0].group);
    }
});

I don't have a clear picture of your QuestionGroupModel, but that they take different arguments for similar operations shows that the model itself has problems, and may require refactoring.


To start with:  You are currently not using the wb Workbook object after setting it.  Is it needed in other code, or can it be removed?

If you are just trying to 'flatten' the range to get rid of any formula, you can just use <Range>.Value = <Range>.Value, instead of Copy / PasteSpecial

Range("S" & FoundCell1.Row + 1 & ":S" & FoundCell2.Row - 1).Select
'Selection.Copy
'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
     :=False, Transpose:=False
Selection.Value = Selection.Value

You can also use a With Statment to replace the requirement for a Select or Selection.

'Range("S" & FoundCell1.Row + 1 & ":S" & FoundCell2.Row - 1).Select
With w.Range("S" & FoundCell1.Row + 1 & ":S" & FoundCell2.Row - 1)
    .Value = .Value
End With
'Selection.Copy
'Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
     :=False, Transpose:=False

And, this is personal preference, but you could use .Offset, .EntireRow and .Column to define the range instead of building a text string address:

With ws.Range(FoundCell1.Offset(1, 0), FoundCell2.Offset(-1, 0)).EntireRow.Columns("S")
    .Value = .Value
End With

(This only requires "Column S" to be defined once, in case you need to change it later - the other option would be to have it in a Const at the start of the Sub)

As yet-another-alternative, you could use WorksheetFunction.Match to retrieve the Rows directly (TangoRow = WorksheetFunction.Match(WHAT_TO_FIND1, ws.Columns("A"), 0) would give the same result as FoundCell1.Row)


Extracting specific words from PANDAS dataframe

If you're dealing with a lot of data, and especially if your data fits in a dataframe, you should use dataframe methods as much as possible.

Your sample data is not a dataframe, but since you specifically mentioned Pandas and dataframes in your post, lets assume that your data is in a dataframe. Using Pandas' str methods for pre-processing will be much faster than looping over each sentence and processing them individually, as Pandas utilizes a vectorized implementation in C.

Also, since you're trying to count word occurrences, you can use Python's counter object, which is designed specifically for, wait for it, counting things.

The current code:

def countWords(data_frame, selected_words):
    words_dict = {}

    for sentence in data_frame:
        remove = string.punctuation
        remove = remove.replace("'", "") # don't remove hyphens
        pattern = r"[{}]".format(remove) # create the pattern

        test = re.sub(pattern, "", str(sentence)) #compile

        splited_words = str(test).split(' ')

        for word in splited_words:
            word = word.strip()
            word = word.lower()

could be reduced to something like:

def count_words(df, selected_words):
    ...
    df.sentences = df.sentences.replace(r"[{}]".format(string.punctuation.replace("'","")),"")
    df.sentences = df.sentences.str.strip().str.lower().str.split()
    for sentence in df.sentences:
       ...

Then if you were to use a Counter, you could filter and update the Counter in 1 line using a generator expression.

from collections import Counter

def count_words(df, selected_words):
    words_count = Counter()

    ...

    for sentence in df.sentences:
        words_count.update(x for x in sentence if x in selected_words)

Alternatively, if you are going to be searching for different word groups, you could count all the words and filter afterwards.

One more thing to note is that selected words in the sample input is a list. However, searching over a list will normally require O(n) time. In this case, searching over m sentences, it would then take n*m time. This can be improved by changing the list to a set, which has O(1) lookup, therefore reducing the time complexity of the search to just O(m).

This can be even further improved if you have the physical memory for it, by skipping the for loop and the counter and doing the entire thing in Pandas. Pandas' str.split function takes a parameter, expand, that splits the str into columns in the dataframe. When combined with .stack(), this results in a single column of all the words that occur in all the sentences.

The column can then be masked to filter for just the selected words, and counted with Pandas' series.value_counts() function, like so:

words = df.sentences.str.split(expand=True).stack()
words = words[words.isin(selected_words)]
return words.value_counts()

In fact, it would probably be faster to skip all the for loops altogether and implement it like this, as vectorized implementations will be much faster than loops. If you don't have enough memory for this, you can process it in chunks and it should still be faster than using for loops.


I would say the DISTINCT keywords in the following quote are superfluous. I would recommend to explicitely use INNER JOIN but even as it is, your JOIN clauses should implicitly compute that already. The only time I would use DISTINCT would be if I suspected that one anime had duplicate records of multiple of the same studio/genre.

GROUP_CONCAT(DISTINCT genre.name ORDER BY LOWER(genre.name)) AS genres,
GROUP_CONCAT(DISTINCT studio.name) AS studio_names,
GROUP_CONCAT(DISTINCT studio.link) AS studio_links

Your use of GROUP_CONCAT() should not cause much if any performance difference, as it computes that on the result set to display it differently. I'm curious about the reason you are using LEFT JOIN and joining a subquery, can you clarify?


Find sum of K largest elements in an array

While the idea is perfectly sound, there are reasons to prefer a min heap approach:

The min heap guarantees an \$O(n \log k)\$ time complexity. Your method
may degenerate to \$O(nk)\$ for nearly sorted data.
The min heap works with streaming data. Your method requires the
entire data set to be present.
The min heap preserves the original order. Your method rearranges
data.

You may also gain some performance with tail recursion elimination:

First, convert the getKthLargestIndex into really tail recursive form:

    if (k == rank) {
        return p;
    if ( k < rank) {
        h = p - 1;
    }
    else {
        k -= rank;
        l = p + 1;
    }
    return getKthLargestIndex(a, k, l , h);

Now replace the recursion with a loop:

    private int getKthLargestIndex(int[] a, int k, int l, int h) {
        while (1) {
            int p = partition(a, l, h);
            int rank = p - l +1;

            if (rank == k) {
                return p;
            }

            if ( k < rank) {
                h = p - 1;
            }
            else {
                k -= rank;
                l = p + 1;
            }
        }
    }


A static Java method for multi-indexing a collection

First up, nice touch with BADCAFE :)

Then, for my two cents:

To me it feels a bit strange using Collection for the element supplier type. Since we are indexing values, it would seem strange to use it on a Set for example, as it does not impose order.
On a similar note, using a Collection for the indices parameter seems strange as well, for the same reasons. A Set also implies uniqueness, so no two equal indices would be passed.

Both would seem to make more sense being Lists to me. But this is something I am just saying based on what I am feeling :)

Continuing:

You can relax the type bound on the input parameter of the elements supplier, like so:

public static <T> List<T> multiIndex(final Collection<? extends T> collection, ...

Now you can pass a collection parameterized with T or with a subtype of T, which makes it more versatile.
Seeing as you are extracting elements, you can annotate the array cast with a SuppressWarnings, as it is safe:

@SuppressWarnings("unchecked")
final T[] array = (T[]) collection.toArray();

Finally, I'd generally think twice before using forEach on a Stream, as it implies using stateful operations. Personally, I think in this case it can be more cleanely written as:

@SuppressWarnings("unchecked")
T[] array = (T[]) collection.toArray();
return indices.stream()
        .map(index -> array[index])
        .collect(Collectors.toList());


Your algorithm is faulty, because it only tries to eliminate redundant lamps in the order in which they were installed.

Consider a 1 × 9 array with 7 initial lamps L0 … L6 at positions 2 … 8.

Your algorithm would first eliminate L0 at position 5, then L1 at position 4.  It would consider L2 and L3 essential.  Then it would eliminate L4 at position 7.  L5 and L6 would be essential.  Total lamps eliminated: three.

An optimal solution would eliminate four lamps at positions 3, 4, 6, 7.


Find the next multiple of N that is a perfect square number

I'm afraid we need to use… math.

Take any square number and look at its prime factorization. For example, \$ 100 = 2^2·5^2 \$; \$ 144 = 2^4·3^2 \$; \$ 729 = 3^6 \$. The thing that's common to all of these examples is that the exponent of each prime in the factorization is even. And that's because if you take any number \$ n \$, with factorization $$ n = 2^a·3^b·5^c\dotsm $$ then its square is $$ n^2 = 2^{2a}·3^{2b}·5^{2c}\dotsm $$ where all the exponent are even.

So if you want to find the smallest multiple of \$ m \$ that's a square, then you can factorize $$ m = 2^a·3^b·5^c\dotsm $$ find the odd exponents among \$ a, b, c, \dotsc \$, and then multiply by the appropriate primes to make all the exponents even.

Let's take the number \$ 12 \$ as an example. First, factorize \$ 12 = 2^2·3^1 \$. Then note that \$ 3 \$ is raised to an odd exponent in the factorization. So we need to multiply by \$ 3 \$ to get \$ 2^2·3^2 = 36 \$ which is \$ 6^2 \$.

A bigger example: \$ 24696 \$. First, factorize \$ 24696 = 2^3·3^2·7^3 \$. Then note that both \$ 2 \$ and \$ 7 \$ are raised to odd exponents in the factorization. So we need to multiply by \$ 2·7 \$ to get \$ 2^4·3^2·7^4 = 345744 \$ which is \$ 588^2 \$.


The code is way too "linear", too deep, too hard to follow with all the indexing and generic column-cell referencing.

I prefer foreach over for.  Simpler, cleaner, easier to read.
For each row, you can reference the DataGridViewCellCollection property by column name-value: theRow.Cells['theColumnName'].Value
Create a method that takes a DataGridViewRow parameter and simply copies its column values into a "CSVrow" object - a class you create.

override ToString and build the CSV string there.

Create a "CSVrowCollection" class to hold the CSV objects.

Its main purpose is to build the CSV file. Do this in a ToString override

.

class CSV {
    public CSV (DataGridViewRow timeStampRow) {  }

    public override string ToString() {
        // note the single quote characters wrapping the complete string
        return string.Format('"{0}","{1}","{2}","{3}","{4}","{5}"',
                            Timestamp, Value, Events, Comment, User);
    }
}

class CSVcollection {
    protected List<CSV> CsvList { get; set; }

    public void Add(CSV aCsvObject) { }

    public override string ToString() {
        // building the value names string not shown.
        StringBuilder me = new StringBuilder();  //System.Text

        foreach (var record in CsvList)
           me.AppendLine(record);  //implicit ToString call

        return me.ToString();
    }
}


Find out max duplicate number between 1 to N numbers

You can use GroupBy to count the duplicates.

Then you should sort the result and get the first item once, instead of sorting it each time you use it:

int[] _input = new int[] {
  5, 45, 184, 594, 14, 8, 5, 184, 1841, 184, 594, 5, 78, 594, 14, 8, 18, 4, 18, 14, 8, 594
};

IGrouping<int, int> max =
  _input.GroupBy(n => n)
  .OrderByDescending(g => g.Count())
  .First();

Console.WriteLine(
  "Maximum number repeated is " + max.Key +
  " and it is repeated " + max.Count() + " times"
);


One inefficiency of your solution is that is calls reverse. This means that it will have to traverse an entire row. It also means it won't work with infinite lists.

The best implementation I've found is Data.Universe.Helpers.diagonals from the universe-base package.

It can even operate on an infinite list of infinite lists:

import Data.Universe.Helpers
import Control.Monad

mat = [ [i..] | i <- [1..] ]

example n = forM_ (take n $ diagonals mat) $ print

e.g.:

ghci> example 4
[1]
[2,2]
[3,3,3]
[4,4,4,4]

More info available at this SO answer: https://stackoverflow.com/a/32469565/866915


Fantasy Game Inventory - Automate the Boring Stuff with Python

Style

I suggest you check PEP0008 https://www.python.org/dev/peps/pep-0008/ the official Python style guide for writing a more Pythonic code and Flake8 http://flake8.pycqa.org/en/latest/ for style enforcement. The following goes accordingly:

Blank lines: Surround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

No blank lines between the function and what's above:

# this function prints the players inventory in a list and reports the total items
def display_inventory(inventory):

and same goes to the other function.
f-strings: Since you're using Python 3.x I can tell from the print statements F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. You could use f-strings for readability enhancement in the following way:

This line:

print("\nTotal number of items: " + str(item_total))

is written:

print(f'\nTotal number of items: {item_total!s}')

as well as:

print(str(v) + " " + str(k))

is written:

print(f'{v!s} {k!s}')

Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include docstrings to your functions indicating what they do and what they return.

Example:

def add_to_inventory(inventory: dict, added_items: list):
    """Update and return inventory."""

And note the type hints to indicate the types of these parameters.
Indentation: your function add_to_inventory body is over indented (8 spaces instead of 4) and 4 spaces is the common convention in Python.

Code

A function returns: functions are meant to return, not to print.

def display_inventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + " " + str(k))
        item_total = item_total + int(v)
    print("\nTotal number of items: " + str(item_total))

And since there is no particular sophisticated printing pattern required, the display function can be replaced by print() statement(s).
Augmented assignment: Python supports augmented assignment using +=

item_total = item_total + int(v) is written: item_total += int(v)
main guard: Use if __name__ == '__main__': at the end of your script and call your functions from there. to allow the module to be imported by other modules without running the whole script.

And the code can be a one-liner:

from collections import Counter

def update_inventory(inventory: dict, new_items: list):
    """Update and return inventory."""
    return Counter(inventory) + Counter(new_items)

if __name__ == '__main__':
    inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
    dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
    new_inventory = update_inventory(inventory, dragon_loot)
    for item, number in new_inventory.items():
        print(f'{number} {item}')
    print(f'\nTotal number of items: {sum(new_inventory.values())}')


Maybe, this is marginally cleaner, based on @Gareth's comment:

'{0:%d} {0:%b} {0:%Y} {0:%I}:{0:%M}:{0:%S}.{1:03d} {0:%p}'.format(now, now.microsecond // 1000)

The not so great part is treating now.microseconds differently from the rest. But since the vale is an integer in the range 0..999999, and you want the value divided by 1000, I don't see a way around. For example if the value is 12345, you would want to get 012. Padding with zeros is easy, once the number is divided by 1000. Or you could pad with zeros up to 6 digits and take the first 3 characters, but I couldn't find a formatting exceptions to do that.

The advantage of this way over the original is instead of 2 calls to strftime and a string concatenation and a string slicing, there's now a single .format call.


Get array of pressed buttons using extension method

Rather than using an array to return you should use a List<T> which can be easily appended to:

public static List<Buttons> GetPressedButtons( this GamePadState gamePadState )
{
    var pressedButtons = List<Buttons>();

    foreach ( Buttons button in Enum.GetValues( typeof(Buttons) ) )
    {
        if ( gamePadState.IsButtonDown( button ) )
        {
            pressedButtons.Add(button);
        }
    }

    return pressedButtons;
}

However this can be simplified still with the use of LINQ. The for loop basically selects all buttons which are pressed:

public static List<Buttons> GetPressedButtons(this GamePadState gamePadState)
{
    return Enum.GetValues(typeof(Buttons))
               .Cast<Buttons>()
               .Where(b => gamePadState.IsButtonDown(b))
               .ToList();
}

The Cast<T> is required because GetValue returns a non-generic Array.


Your definition of d is not quite right.  It produces incorrect results for some values of i and it has two special cases which are not necessary.  A possible definition is:

  (define (d i)
    (cond
      ((divisible? (+ i 1) 3)
       (* (/ (+ i 1) 3) 2))
      (else 1)))

This is because i is 1-indexed (series begins with i = 1).  If you want a decimal instead of a fraction as your result, change the multiplier to 2.0 and the else value to 1.0.

Another way to write d is:

  (define (d i)
    (let
        ((d-value (* (/ (+ i 1) 3) 2)))
      (if (integer? d-value) d-value 1)))


Before you write another line of code, watch this Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset).

Everyone here wants to help you but, and I know that you read this,  you have got to stop selecting and activating cells.  You also need to describe your data.  Posting screenshots wouldn't hurt either.  So if I sound mean but you wrote 72 lines of code to copy maybe 12 values.

Range.Copy, Range.Cut, Range.Insert and by default act on only the visible cells.

Sub FilterAndCopy()
    Dim Source As Range, Target As Range

    With Workbooks("Epson ASINs.xlsx").Worksheets("Sheet1")
        Set Source = .Range("U2", .Range("U" & .Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
    End With

    With Workbooks("Epson Itemcodes.xlsm").Worksheets("Sheet1")
        Set Target = .Range("U" & .Rows.Count).End(xlUp).Offset(1)
    End With

    Source.Offset(1).Copy Desination:=Target

End Sub


I think I came up with a better and more declarative way using Joi schemas in nested dictionaries.
The idea is that we first figure out these three things:

Is the user editing themselves? (bool)
What type of user is the editor? (admin, etc)
What type of user is being edited? (admin, etc)

And based on those three things, we can lookup the correct Joi schema to use.
So the schema dictionary looks like this for the PATCH route:
// No one is allowed to edit their own user type, everyone can edit their own name.
const selfEditSchemas: { [key in UserType]?: Joi.Schema } = {
  [UserType.superAdmin]: Joi.object({
    userType: Joi.forbidden(),
    name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
  }),
  [UserType.admin]: Joi.object({
    userType: Joi.forbidden(),
    name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
  }),
  [UserType.user]: Joi.object({
    userType: Joi.forbidden(),
    name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
  }),
};

// We only allow admins and super admins to edit others, and we use different schemas
// depending on what type of user they are trying to edit.
const otherEditSchemas: { [key in UserType]: { [key in UserType]?: Joi.Schema } } = {
  [UserType.superAdmin]: {
    [UserType.admin]: Joi.object({ // (superAdmin can edit admins according to this schema)
      userType: Joi.string().valid(...Object.values(UserType)).optional(),
      name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
    }),
    [UserType.user]: Joi.object({ // (superAdmin can edit regular users according to this chema)
      userType: Joi.string().valid(...Object.values(UserType)).optional(),
      name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
    }),
  },
  [UserType.admin]: {
    [UserType.user]: Joi.object({ // (admin can edit regular users according to this schema)
      userType: Joi.forbidden(), // (admin cannot promote regular users)
      name: Joi.string().pattern(/^[a-zA-Z0-9_\-. ]{3,100}$/).optional(),
    }),
  },
  [UserType.user]: {}, // (user is not allowed to edit anyone else)
};

And now the logic for validating edits becomes a lot simpler and less error-prone IMO:
function validateUserEdit(req: express.Request, res: express.Response, next: express.NextFunction) {
  const userReq = req as UserRequest;

  const isSelf = userReq.user.id === userReq.otherUser.id;
  const schema = isSelf
    ? selfEditSchemas[userReq.user.userType]
    : otherEditSchemas[userReq.user.userType][userReq.otherUser.userType];

  if (!schema) {
    return res.status(403).json({
      message: 'Not allowed to edit that user.',
      code: ErrorCodes.FORBIDDEN_TO_EDIT_USER,
    });
  }

  const validateRes = schema.validate(req.body, { stripUnknown: true });
  if (validateRes.error) {
    res.status(400).json({
      message: `Invalid arguments: ${validateRes.error}`,
      code: ErrorCodes.INVALID_ARGUMENTS,
    });
  } else {
    req.body = validateRes.value;
    next();
  }
}


Instead of wrapping your code in $(document).ready(function(){, you should put the <script> tag at the bottom of file ( right before closing </body> ), then you script will get executed right after the DOM is ready.
Do not use innerHTML for working with DOM
Stop selecting DOM element each time you want to do something with it. It is an expensive operation. Instead get the element once and store in a variable.
Your trim() method initializes obj twice.
Do not use .length in loops. Instead assign value to variable and reuse it.

And, honestly, get rid of jQuery. You are not using for anything special. Only simple DOM manipulations.


Transform poor CSS into a more beatiful form in Dart

Sorting the properties alphabetically does not yield "the same code". Properties that appear later in a rule override properties that occur earlier in the same rule. Mozilla Developer Network gives an example of a tricky edge case:

  A value which is not specified is set to its initial value. That sounds anecdotal, but it really means that it overrides previously set values. Therefore:

background-color: red;
background: url(images/bg.gif) no-repeat top right;

  will not set the color of the background to red but to background-color's default, transparent, as the second rule has precedence.

If you reverse the properties in that example, you would get a different result.


Exception handling for timing CouchBase fetch

You could use Try utility.

But the main concern is that it doesn't support finally statement out-of-the-box.

This can be achieved with some Try enhancement's value class (by Viktor Klang):

implicit class TryOps[T](val t: Try[T]) extends AnyVal {
  def eventually[Ignore](effect: => Ignore): Try[T] = {
    val ignoring = (_: Any) => { effect; t }
    t transform (ignoring, ignoring)
  }
}

Consider this code:

val timer = couchbaseMetricsTimer.time()
val tryClient =
  Try(couchBaseClient.get(key)) map { //convert success result
    Option(_)
  } recover { //process failure result
    case e: Exception => couchbaseFailureMetricCounter.inc(); throw e
  } eventually { //perform "finally" block
    timer.stop()
  }

//return actual result
tryClient.get

It's not less, by more idiomatic, so it's up to you which way to choose.

Here are more references to discover.

Note: you can put TryOps into package object of some of your root package f.e. com.mycompany, and then you can use it everywhere in your project.


Find minimum singular value in a sorted array

for (int i = 0; i < array.length; i++) {
        int countOccurence = 0;
        for (int j = 0; j < array.length; j++) {
            if (array[i] == array[j]) {
                countOccurence ++;
            }
        }
        if(countOccurence == 1) {
            return array[i];
        }
    }
    return 0;

When I look at this, the problem that I see is that you are scanning the entire array to look for duplicates.  The array is sorted!  Consider

    int i = 0;
    while (i + 1 < array.length) {
        // array[i] has a duplicate iff it is the same as array[i + 1]
        if (array[i] != array[i + 1]) {
            return array[i];
        }

        // skip to the next possible smallest value not a duplicate
        while (i + 1 < array.length && array[i] == array[++i]) ;
    }

    // figure out if the last element has no duplicate
    return (array.length == 0 || array[i] == array[i - 1]) ? 0 : array[i];

While it may look like it has nested loops, both iterate over the same variable.  So the number of comparisons is linear relative to the size of the array.

This works because the array is sorted.  All duplicates are adjacent to each other.

The ++i increments i and then returns the now incremented value.  i++ stores the value of i, then increments it, and finally returns it.  So i++ + 1 is the same thing as ++i.  Or vice versa.

class Incrementable {

    private int i = 0;

    // ++i
    public int preincrement() {
        i = i + 1;
        return i;
    }

    // i++
    public int postincrement() {
        int original = i;
        i = i + 1;
        return original;
    }

}

The two forms ++i and i++ are the equivalents of the preincrement and postincrement in this class.

So let's go through

        while (i + 1 < array.length && array[i] == array[++i]) ;

The form

while (isTrue()) ;

just keeps iterating until isTrue returns false.  It does nothing in the body of the loop, thus the empty ;.  We could also write it

while (isTrue()) {

}

But that just seems longer.

The i + 1 < array.length just keeps us from falling off the back of the array.  I.e. we never want to do array[array.length], as that's an error (attempt to access outside the array).

So the meat of the statement is the array[i] == array[++i].  On any particular iteration, this is just the same as array[i] == array[i + 1].  So long as that is true, we're still processing the same duplicate.  But replacing i + 1 with ++i has the same effect on an individual iteration and moves along.  So we have something like an array of

  1, 1, 2, 2, 2, 2, 3

i = 0, array[i] = 1, array[++i] = 1, i = 1; equal so keep going
i = 1, array[i] = 1, array[++i] = 2, i = 2; not equal so stop and do the outer while
i = 2, array[i] = 2, array[++i] = 2, i = 3; equal so keep going
i = 3, array[i] = 2, array[++i] = 2, i = 4; equal so keep going
i = 4, array[i] = 2, array[++i] = 2, i = 5; equal so keep going
i = 5, array[i] = 2, array[++i] = 3, i = 6; not equal so stop and do the outer while

While i is 6, we'll drop out of the inner loop and the outer loop, because 6 + 1 is not less than array.length, which is 7.


rolfl's answer pretty well explains why this isn't really a realistically reasonable approach to cracking passwords.  I'm going to set that answer aside, ignore it, and address some of the specific ways in which this code could be improved if it were part of a more realistic program.

As a start, this code has one massive, massive problem: What happens when we actually find a match?

NSLog("Found");

And that's it.

We don't log the password.  We don't post a notification, return it, tell a delegate.  We don't save it as a local variable.  We just post a borderline useless log statement claiming we found it.

And what's worse?  WE KEEP CALCULATING!

We're done with this call to brute_implWithChar, but as soon as it returns, the loop in brute_sequentialWithMaxLength: is on another iteration and we jump right back in brute_implWithChar..., and go through all of that, and then return and do it all again, etc.

This is a major problem which should be addressed.

We can speed this up by using fast enumeration in brute_implWithChar...

But to do that, let's first talk about: pm_maskArray.  You don't show this anywhere, but I can only assume it's an array of NSString objects.  I'm going to recommend instead that we use an array of NSNumber objects.

And why NSNumber?  Because NSNumber can also hold characters:

NSNumber *theCapitalLetterC = @'C';
char theCStyleCapicalCChar = [theCapitalLetterC characterValue];

So... presuming we've built pm_maskArray into an appropriate array of NSNumber objects, our loop is now going to look something more like this:

for (NSNumber *aChar in pm_maskArray) {
    char alph = [aChar characterValue];

    // all your checking stuff
    // when/if a match is found, we can:
    break;
    // to stop the loop and return executing at the first line after the loop
    // or in this case we can also:
    return;
    // to exit the method entirely.
}

As it stands, this forin loop will already allow you SEVERAL more guesses per second, as it will send a message to the pm_maskArray about once for every 16 times your version of the code was sending the message (approximately).

And looking back to my first point, we probably want to change this method to return an NSString object, rather than void.  Then, if we find a match, we return it, otherwise, we return nil.

I'm also going to rename this method to strip the "and"s out of it, as they're inappropriate.

So if our method looks like this:

-(NSString *)brute_implWithChar:(char*)str index:(int)index depth:(int)depth
// returns matching password or nil

Then the loop in which we call it can look like this:

NSString *crackedPassword = nil;
while ((crackedPassword = [self brute_implWithChar:but index:0 depth:i]) == nil
    && i <= length) {
    ++i;
}
return crackedPassword;

Now, on every unsuccessful call of brute_implWithChar:index:depth: for which we don't find a password, nil is returned and assigned to crackedPassword.  If crackedPassword == nil evaluates to true AND i is still not larger than length, the loop will iterate again.

Meanwhile, the loop will stop iterating as soon as crackedPassword evaluates to anything non-nil.  And since we're returning the password from the inner method, the outer method can return it to its caller as well.  If the password isn't found before i <= length evaluates false, then nil will be returned, indicating that the password wasn't found--otherwise, the password is returned.


There is a much more efficient way to do this, involving two pointers, a 'right', and a 'left' pointer. They both start at 0.

The trick is to inspect the value at the right pointer. If it is negative, increment the right pointer. If it is positive, move it to the left pointer, and increment both pointers.

This allows you to move all the positive values to the beginning of the array, in the order they were found. All you need to do then, is to zero out all the values from the left pointer to the right....

I assume that 0 is considered to be 'not positive'....

void shift_positives(int values[], int num_values) {
    int left = 0;
    for (int right = 0; right < num_values; right++) {
        if (values[right] > 0) {
            values[left++] = values[right];
        }
    }
    while (left < num_values) {
        values[left++] = 0;
    }
}

This performs the operation in \$O(n)\$ time. See it running on ideone


Project Euler #10 - sum of primes below two million

Well, first of all, sorry, but your code is buggy. You are missing 2 and 3, because of this:

if ((i % 2 == 0 || i % 3 == 0)

...since this will be true for 2 and 3. So your result is off by 5.

Also this part is 100% useless:

(i!=2 || i!=3 || i!=5))

How many values for i you can imagine for which this statement is false?

Let's try i = 1 -> true, because 1 != 2 (i != 2)
Now we try i = 2 -> true, because 2 != 3 (i != 3)
Now we try i = 3 -> true, because 3 != 2 (i != 2)
Last try: i = 5 -> true, because 5 != 2 (i != 2)

So, this statement is always true.

Anyway, another solution (getting more speed by sacrificing memory) would be to not calculate if every number is a prime, but do something like this...

final int limit = 2000 * 1000;

final boolean[] knownNotPrime = new boolean[limit + 1];

long sum = 0;

for (int i = 2; i < limit; i++) {

    if (!knownNotPrime[i]) {
        sum += i;

        for (int j = 2; j <= (limit / i); j++) {
            knownNotPrime[j * i] = true;
        }
    }

}

In other words, for every prime you calculate the multiples (up to the limit) and store them in a boolean array (you could decrease the memory by a factor of 8 by using a bitfield, just didn't want to complicate the whole thing).

Since "being not a multiple of any number lesser than itself" is pretty much the definition of "prime", you already know if a number is a prime when you reach it and it's not marked in the array. And if it isn't, you know that it's a multiple of some lesser prime - and thus, all it's multiples will already be known as non-prime, no need to re-calculate them.

Your code takes around 217ms to run, mine takes 17, but on the other hand, mine takes way more than 12 times the memory, even if you used a bitfield.

Note: After using google and trying to remember what I learned in school, this is probably a variation of the Sieve of Eratosthenes and I have no idea how good this implementation is. Probably there are much better solutions out there, I guess.


You don't need to have the where clause on your struct. General, rust coders prefer to only restrict the impl blocks and not the structs.

You can avoid Clone, by unpacking the Entry enum, like so:

fn get(&mut self, input: U) -> &W {
    use std::collections::hash_map::Entry;
    match self.values.entry(input) {
        Entry::Occupied(entry) => entry.into_mut(),
        Entry::Vacant(entry) => {
            let value = (self.calculator)(entry.key());
            entry.insert(value)
        }
    }
}

This is, in fact, close to how or_insert_with is implemented.

Note that this calls the function with &U not U. Your calculator cannot take ownership of the key if you also plan to put into the hashmap. This is awkward for your code because it is using &str as the keys. Hence the type passed to the calculator is &&str. We can resolve this by using the borrow trait. The Borrow traits knows that it can convert &&str to &str, so we could implement it as follows.

// Leave the struct unconstrained
struct Cache<T, U, W> {
    calculator: T,
    values: HashMap<U, W>,
}

// The impl block only constrains for Eq + Hash of the keys.
impl<T, U, W> Cache<T, U, W>
    where
          U: Eq + Hash
         {

    fn new(calculator: T) -> Cache<T, U, W> {
        Cache {
            calculator,
            values: HashMap::new(),
        }
    }

    // We take a new type parameter, Y.
    // The calculation function takes &Y as a parameter
    // It does not need to be sized because we only use references to it.
    fn get<Y:?Sized>(&mut self, input: U) -> &W
        where
             // Our calculator must take a reference to Y.
             T: Fn(&Y) -> W,
             // The borrow trait will let us convert a &U to a &Y
             U: std::borrow::Borrow<Y> {
        use std::collections::hash_map::Entry;
        match self.values.entry(input) {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let value = (self.calculator)(entry.key().borrow());
                entry.insert(value)
            }
        }
    }
}


Compressed vs. non

        return normalLength < compressedLength? jsonData:compressedData;

Isn't this backwards?  Consider

        return normalLength <= compressedLength? jsonData : compressedData;

or

        return compressedLength < normalLength ? compressedData : jsonData;

Both alternatives do the same thing.  The second version is one character shorter and may be a little clearer about what it is doing.  If the compressedLength is less than the normalLength substitute the compressedData for the normal data.

The original returns a compressed version, which has to be uncompressed, when the compressed and the uncompressed data are the same length.  This version returns the uncompressed version in that case.  Same space, but less time (because it can just use the data rather than decompressing it first).

It's not going to be a big deal either way.  Not only is this likely to be rare, it has little impact when it does happen.  It just struck me as being off and easy to fix.

What does close actually do?

    GZIPOutputStream zos = null;
    try {
        zos = new GZIPOutputStream(rstBao);
        zos.write(srcTxt.getBytes());
        zos.finish();

        byte[] bytes = rstBao.toByteArray();
        return Base64.encodeBase64String(bytes);

    }
    finally {
        zos.close();
        rstBao.close();

    }

You don't need to close rstBao for two reasons.

First, look at the Javadoc for close:

  Writes remaining compressed data to the output stream and closes the underlying stream.

Note the last part.  The "underlying stream" in this case is rstBao.  So closing zos automatically closes rstBao for you.

Second, if you look at the Javadoc for ByteArrayOutputStream, the close method:

  Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

So it is entirely unnecessary to close rstBao.  But you are effectively doing it twice:  once implicitly by closing zos and once explicitly.

The smallest change would drop the second close, but a larger change may better use the notions of the try format.  Consider

    try (GZIPOutputStream zos = new GZIPOutputStream(rstBao)) {
        zos.write(srcTxt.getBytes());
    }

    byte[] bytes = rstBao.toByteArray();
    return Base64.encodeBase64String(bytes);

This moves the byte array manipulations out of the try block, as they don't throw exceptions nor do they require the compression stream.

Moving them out also means that it's not necessary to call finish explicitly.  When the try-with-resources finishes, it will automatically close the the stream and write the data.

This still closes rstBao implicitly, but as discussed it won't do anything.  This is how a ByteArrayOutputStream is designed to operate.  It ignores the close the format requires and continues.


Consider using enum class

Instead of having a regular enum inside its own namespace, use an enum class:

enum class UsartSpace: u32 {
    usart0 = XPAR_PS7_UART_0_BASEADDR,
    usart1 = XPAR_PS7_UART_1_BASEADDR,
};

Then, to ensure someone cannot instantiate a Usart with the wrong base address, make the constructor take this enum as a parameter:

template <typename T>
Usart<T>::Usart(UsartSpace usartSpace): usartNumber(static_cast<u32>(usartSpace)) {
}

Also, "Space" is a bit of a generic word that doesn't say much, but you can't call the enum Usart since you already have class Usart. Consider moving the enum to inside class Usart, and since it refers to a port, just call it Port. And perhaps keep the distinction between port number and address clear:

template <typename T>
class Usart: public Platform {
private:
    u32 baseAddress;
    static const u32 addresses[] = {
        XPAR_PS7_UART_0_BASEADDR,
        XPAR_PS7_UART_1_BASEADDR,
    };

public:
    enum class Port {
        usart0,
        usart1,
    };

    Usart(Port port);
    ...
};

...

template <typename T>
Usart<T>::Usart(Port port):
    baseAddress(addresses[static_cast<size_t>(port)])
{
}

In code that uses this class, you would then write:

Usart<sometype> usart(Usart::Port::usart0);

Use better names

What you call a usartNumber looks like an base address to me, so call it baseAddress instead. In any case, don't repeat the name of the class in the member variable names.

Also, dataValue is not the value of some piece of data, it's the size of the data you want to read or write. So call it size, and if possible use size_t as its type:

status transmit(T *pData, size_t size);
status receive (T *pData, size_t size);

Is it status or StatusSpace?

I feel this is another case of an enum in its own namespace being used as a way to declare constants of another type. I would instead define:

enum class Status {
    ok,
    error,
    ...
};

Use array notation where appropriate

Instead of writing *(pByteData + byteCounter), just write the more ideomatic pByteData[byteCounter].

Use const where appropriate

You wouldn't expect the function transmit() to modify the data that you want to send. So make this explicit:

template <typename T>
class Usart: public Platform {
    ...
    status transmit(const T *pdata, size_t size);
    ...
}

Consider templating transmit() and receive() instead of the whole class

The only things that depend on the template parameter T are the transmit() and receive() functions. By making the class templated, you basically lock the type of data you can send and receive when you instantiate the class. Consider instead templating just those two functions, so you can send and receive different data types on the same UART without having to reinstantiate the class:

class Usart: public Platform {
    ...
    template <typename T>
    status transmit(const T *pData, size_t size);

    template <typename T>
    status receive(T *pData, size_t size);
    ...
};

Use Doxygen to document your code

You are documenting your code, which is good practice, but consider doing it in Doxygen's format, so you can have Doxygen create cross-referenced documentation in HTML, PDF and other forms. Doxygen can also check that you documented all the functions and all the parameters to the functions.


Variable declaration closer to usage Vs Declaring at the top of Method

I agree with Guffa and dreza, variables should only be declared at an outer scope if it is really really necessary as doing so is confusing and error prone. Also, if a method is long enough that having the variable declaration at the top means it isn't close to it's use then it could probably benefit from refactoring into separate methods. Doing this will also help readability because you'll have method names explaining what's happening.

Some examples (quotes as this is only my opinion):

1: "Bad" example

As an outside coder, if I saw this I would wonder why the variables are declared at the outer scope and would waste time worrying there was a special reason for it.

string emailAddress = string.Empty;
string managerEmailAddress = string.Empty;

if (//condition)
{
  emailAddress = Foo();
  EmailMessage.To = emailAddress;
}
else
{
  emailAddress = Bar();
  // Do something different with emailAddress;
}

// No more usages of emailAddress

2: "Improved" example:

This is better because the variables are defined where they are used so there is no need to go looking around for other usages.

if (//condition)
{
  var emailAddress = Foo();
  EmailMessage.To = emailAddress;
}
else
{
  var emailAddress = Bar();
  // Do something different with emailAddress;
}

3: "Even better" example:

I think this is the best it can get because the method names will help with understanding the code.

if (//condition)
{
  ExplanatoryName1(//pass anything in that is required);
}
else
{
  ExplanatoryName2(//pass anything in that is required);
}

4: If you need a return from the methods:

var methodReturn = condition ? ExplanatoryName1(args) : ExplanatoryName2(args);


Okay so first of the obligatory Singletons are bad practice so you probably shouldn't make it easy to write bad code.

Ignoring the fact that the class probably shouldn't exist at all we can look at the code.

static T& GetInstance() {
  static MemGuard g; // clean up on program end
  if (!m_instance) {
    m_instance = new T();
  }
  return *m_instance;
}

If multiple threads access this instance simultaneously before it is created, you have a data race and m_instance may end up be being constructed multiple times or other kinds of undefined behaviour. You need to add mutex locks around the if block or use std::call_once which is preferred.

As it is supposed to be a singleton you're not supposed to be able to create more instances as the meaning of a singleton is to just have one instance but it appears that it is fully possible to construct multiple instances of Test  simply by creating them as local variables. So this is a design flaw in your template.

A much better way of creating a singleton is to rely on C++11 Magic Statics (N2660). And simply do this:

class Test{
private:
    Test(); // Disallow instantiation outside of the class.
public:
    Test(const Test&) = delete;
    Test& operator=(const Test &) = delete;
    Test(Test &&) = delete;
    Test & operator=(Test &&) = delete;

    static auto& instance(){
        static Test test;
        return test;
    }
};

Which is much easier to write than your code, it's thread safe and fixes the issues with allowing Test to be instantiated. The properties of magic statics guarantee that test will be initialised exactly once the first time the function body is entered by any thread, even in the presence of multiple threads that might otherwise cause a data-race. The instance will be deconstructed when your main() function returns (in the static destruction stage) which makes the whole MemGuard thing unnecessary.


Most efficient JavaScript countdown timer implementation

document.querySelector("#id") is just a costly version of document.getElementById("id"). document.getElementById is the fastest way to select an element in your page (to the smartasses of you: besides document.head, document.body etc)

document.querySelector("tagname") is also just a costly version of document.getElementsByTagName("tagname")[0]. Coincidentally, that's the second fastest way to get an element.

document.querySelector and its array-like version are only useful for compound statements that are either too long or too difficult to do with "regular" DOM methods. One might argue that if your html is compound and complex, you're doing it wrong, and they'd most likely be right.

If I were you, I'd also do future-you a favor and name your variables in a way that makes sense.

So, what do we have so far?

var output = document.getElementsByTagName("output")[0],
    minutes = document.getElementById("m"),
    seconds = document.getElementsById("m"),
    start = document.getElementById("start");

Moving on. The event listener is fine, now about parsing integers...

Try this piece of code: parseInt("08"). The result is 0. Why, you ask? Well, if you don't pass a radix as a second parameter, parseInt will be nice enough to guess what you mean. parseInt sees that your string begins in a 0 and, of course, assumes the number is in octal! Why wouldn't it be?

Point: either pass a radix like this: parseInt(string, 10) or use parseFloat, which will always assume a decimal number. Whichever you like best, though I once heard that parseFloat is faster, dunno if that's true. I personally prefer parseFloat, for no obvious reason

So we get:

var mm = parseFloat(minutes.value),
    ss = parseFloat(seconds.value);

Magnificent.

This line:

timer =

Contains one of the most widely made errors in javascript. It's called implied global.

Basically, when you omit the var statement, the variable definition list gets appended to the global object (which window refers to). So:

function foo() { answer = 42; }
foo();
window.answer === 42;

Never omit the var statement. Even if you do wish to append a variable to the global object, do it explicitly (window.answer = 42;). Better that then let someone scratch their head trying to figure out how magic variables appeared from seemingly nowhere.

Besides one more thing, your code is fine. What's that other thing, you ask? setTimeout

When you pass a string to setTimeout, it's the same as calling eval. It evaluates the string. That's slow and bad. Instead, pass a function to it:

setTimeout(timer, 1000);

Since timer is a function, you can pass it around like any other value.

Now, one might ask: "How do I call func with parameters?"

setTimeout(function() {
    func(something, somethingElse);
}, 1000);
//or
setTimeout(func, 1000, something, somethingElse);

About your actual code? it's fine. It's not the best piece of code I've ever, but it's not the worse as well. It's not too long for a timer, since all that's done is decrementing and calling itself again. I'd move the < 10 checks to their own function, but maybe that's because I'm insane and not that "your way" is worse.

tl;dr Your code contains errors, but other than that, it's fine.


Finding all prime numbers within a range

I am trying to find all primes less than 2,000,000 and sum them
  together. My code currently takes 1'36" to run. Is there a faster way
  to get my solution?

Yes. For example,

142913828922
3.860761ms

versus your

142913828922
1m35.090248409s

prime.go:

package main

import (
    "fmt"
    "time"
)

const (
    prime    = 0x00
    notprime = 0xFF
)

func oddPrimes(n uint64) (sieve []uint8) {
    sieve = make([]uint8, (n+1)/2)
    sieve[0] = notprime
    p := uint64(3)
    for i := p * p; i <= n; i = p * p {
        for j := i; j <= n; j += 2 * p {
            sieve[j/2] = notprime
        }
        for p += 2; sieve[p/2] == notprime; p += 2 {
        }
    }
    return sieve
}

func sumPrimes(n uint64) uint64 {
    sum := uint64(0)
    if n >= 2 {
        sum += 2
    }
    for i, p := range oddPrimes(n) {
        if p == prime {
            sum += 2*uint64(i) + 1
        }
    }
    return sum
}

func main() {
    start := time.Now()

    var n uint64 = 2000000 - 1
    sum := sumPrimes(n)
    fmt.Println(sum)

    fmt.Println(time.Since(start))
}

Reference: Sieve of Eratosthenes - Wikipedia

Go was designed for Google scale. Therefore, Go package testing includes benchmarking tools. For example,

$ go test -bench=. -benchmem
BenchmarkPeterSO-8     500        3805125 ns/op    1007621 B/op     1 allocs/op
BenchmarkNightman-8      1    95703259026 ns/op    5866752 B/op    31 allocs/op
$

  Comment: You have presented an alternative solution, but haven't
  reviewed the code. Please explain your reasoning (how your solution
  works and why it is better than the original) so that the author and
  other readers can learn from your thought process. – Martin
  R

The thought process is simple, obvious, and well-known.

The prime number problem is well-known.

Therefore, Standing on the shoulders of giants - Wikipdia.

"If I have seen further it is by standing on the sholders [sic] of Giants." Isaac Newton

For example, Sieve of Eratosthenes - Wikipedia.

The algorithm given in the question is much slower than Eratosthenes' well-known algorithm, approximately 25,000 times slower.

In real-world code reviews, code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. The code in the question is not reasonably efficient.


Matrix problem, the path that is the flattest

Don't take this the wrong way, but my first thought when I looked at your code was "ugh do I really want to read this?"  You have (probably) been thinking a lot about A, S, n, and D over the last few hours, but if you look at this again in 2 years, it will look like nonsense.  So your number one goal should be to fix readability.  Then you can start thinking about correctness and performance.

I would recommend reading through a C++ style guide for general tips.  Here is one, but there are many others.  I'll still list a few of the biggest mistakes:

You should avoid single letter variable names
Try to express your logic in functions
Don't use global variables
Indent consistently (or better yet, automatically with help from your IDE)

All of these have been written about extensively in style guides, programming manuals, other code reviews, etc...

fin>>n;

What if n > 21?  If you have some reason to believe it cannot be, then you should assert(n < 22).  But in this case, it's easy enough to support any n with std::vector.

i<=n-1

The canonical way to write this is i < n.

`S[i-1][j]+abs(A[i][j]-A[i-1][j])`

I think this section is correct, but I have more style comments!

This is complicated looking for no reason.  You're making yourself think harder than you have to which means you will accomplish less stuff with your mental bandwidth.  How about something like costOfStep(i-1, j)?
This gets exactly repeated twice and a very similar statement is also repeated twice.  That's a telltale sign you should at least use a variable or better yet write a function to compute this.

Isn't the snipped below easier to read?

for(int i = 1; i < n; i++) {
    for(int j = 1; j < n; j++) {
        int costOfStepDown = costOfStep(i - 1, j);
        int costOfStepRight = costOfStep(i, j - 1);
        minCosts[i - 1][j] = std::min(costOfStepDown, costOfStepRight);
    }
}

//a new matrix to identify the path and memorize the down/right moves
int i,j,x;
i=n-1;
j=n-1;
x=1;

From this point on, I think you are using more time/memory than necessary.  I believe you can refactor your code so that you only store one matrix for both the input array and one for the cumulative array (or two matrices if it's clearer, but not more).  And you can store your path as a 1D vector.  Doing two passes leads to unnecessary code which leads to pointless bugs and wasted time.  Keep it minimal!  You were following a decently minimal algorithm until this part...

Also, here are my thoughts while reading this snippet:

Nice a comment... Where is the new matrix?
Oh some single named variables.  No idea what these do.  Hopefully I can figure it out.
Huh they are not initialized.  I hope the author was careful not to use uninitialized values.

That's a lot of thinking for not very much action.  How about this:

Matrix path;
path[0][0] = inputMatrix[size - 1][size - 1];
for (int i = 0, j = 0; i < size && j < size; /*increment in body*/) {
    ...

This is more of a general tip than a specific comment.  I hope you find it useful.

Many dynamic programming problems are easy to solve with recursion.  Here's some pseudo-code for this problem:

// return the min cost of traveling from pos to the bottom-right of inputMatrix
int minCost(Matrix const& input, Position const pos = top-left) {
    if (pos == bottom-right) {
        return 0;
    }
    return std::min(minCost(input, pos.right), minCost(input, pos.down));
}

Position could be std::pair<int, int> and Matrix could be std::vector<std::vector<int>>.

This function will calculate the correct answer, but it is slow because it repeatedly calculates the min cost of the same position many times.  Fix that:

int minCostHelper(Matrix const& input, Position const pos, Cache cache) {
    if (cache.hasSeen(pos)) {
        return cache.valueOf(pos);
    }
    if (pos == bottom-right) {
        return 0;
    }
    auto result = std::min(minCost(input, pos.right), minCost(input, pos.down));
    cache.insert(pos, result);
    return result;
}

int minCost(Matrix const& input) {
    Cache cache;
    return minCostHelper(input, top-left, cache);
}

Cache could be an std::map.

The technical term for "fix" in this case is "memoize."  I think this style is easier to read/debug than manually creating arrays.  It's a question of personal preference though.

Here is a challenge: can you write a function that will memoize another function?

template <typename Function>
Function memoize(Function);


Reduce the number of code if possible when creating a folder

The built in file system package (fs) provides you with a commands to create directories.

fs.mkdirSync(path[, options]) for synchronous

fs.mkdir(path[, options], callback) for asynchronous

According to their documentation, you can add an option for recursively creating a folder. It also notes

"Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false."

With this information, you should be able to force it to always create the folder using only this logic:

const fs = require('fs')
fs.mkdir( directory, { recursive: true }, (err) => {
  if (err) throw err;
});


What you're doing there is copying the array, not its contents. I.e. it's a shallow copy.

As mherzig mentions in a comment, what you end up with is an extra array containing references to the same elements as the first one. As long as those elements are primitive/immutable values, you're fine. But not so with other objects.

Besides, the conventional way of copying an array is to use slice() or slice(0) - not concat() (although the result is the same).

Anyway, as an example:

var obj = { foo: "bar" };
var array1 = [1, 2, obj];

// shallow copy
var array2 = array1.concat();

// changing a primitive works as you might expect
array2[0] += 10;
console.log(array1); // => [1, 2, { foo: "bar" }]
console.log(array2); // => [11, 2, { foo: "bar" }]

// but the object hasn't been copied, merely referenced in two places,
// so changing it via one array means it's changed in the other as well
array2[2].foo = "Hello, world!";
console.log(array1); // => [1, 2, { foo: "Hello, world!" }]
console.log(array2); // => [11, 2, { foo: "Hello, world!" }]

Hence why people go to great lengths to make deep copies, where the entire contents is copied, so there are no shared references to the same things.

Basically, you want shallow copies if you're just going to be manipulating the array itself (e.g. calling push, pop, splice, sort etc.), and don't want side-effects. E.g. a function that takes an array as its argument is usually best served making a shallow copy, if it intends to mess around with that array.

You want deep copies if you truly want to copy everything, because you're going to be changing the contents, or because you want to avoid other code altering something you hold a reference to.