Disproving Euler proposition by brute force in C

Note: At some point, this review drifted into the realm of assembler and GMP. An actual review is at the end of this post, whereas the first section discusses the runtime-problems concerning pow, wrong data types and arbitrary large integers.

No life time for run time

  Would there be any way (on my current machine) to get this to run in my lifetime?

There's a great saying in carpentry: measure twice, cut once. It concerns cutting wood or other material, where you have to throw away your resources if you accidentally cut at the wrong place.

A similar saying is there for software engineers: you can't optimize what you can't measure. There are several ways to measure your code, e.g. benchmarking, profiling, or looking at the generated assembler to see how many instructions a certain part of your code will take.

Here, we will take the latter route, start with the assembler, take considerations step by step and see where we end up.

A study in assembly

Lets have a look at your code. Well, not yours, but the assembler the compiler generates. You can use gcc -S -O3. On my platform, this results in the following "hot" section in main:

.L6:
        add     rbx, 1
        cmp     rbx, 500000
        je      .L18
.L8:
        mov     rax, QWORD PTR .LC0[rip]
        movsd   xmm0, QWORD PTR [rsp+40]
        movq    xmm1, rax
        call    pow                        ; (1)
        mov     rax, QWORD PTR .LC0[rip]
        movsd   QWORD PTR [rsp+8], xmm0
        movsd   xmm0, QWORD PTR [rsp+48]
        movq    xmm1, rax
        call    pow                        ; (2)
        mov     rax, QWORD PTR .LC0[rip]
        movsd   QWORD PTR [rsp+16], xmm0
        movsd   xmm0, QWORD PTR [rsp+32]
        movq    xmm1, rax
        call    pow                        ; (3)
        mov     rax, QWORD PTR .LC0[rip]
        movsd   QWORD PTR [rsp+24], xmm0
        pxor    xmm0, xmm0
        cvtsi2sd        xmm0, rbx
        movq    xmm1, rax
        call    pow                        ; (4)
        movsd   xmm2, QWORD PTR [rsp+8]
        addsd   xmm2, QWORD PTR [rsp+16]
        movapd  xmm1, xmm0
        movsd   xmm0, QWORD PTR [rsp+24]
        addsd   xmm0, xmm2
        ucomisd xmm0, xmm1
        jp      .L6
        jne     .L6

Even though you might not know assembler, you can see those four calls to pow. The first thing you need to know is that call is slow compared to those other operations. Those four calls happen in the innermost loop. The compiler removed the call to prop and instead replaced it by its code (that's faster).

mov* assigns values to registers, add* adds values, and so on. The registers with xmm* are double precision registers, meant for double variables. So we're basically calling pow with the right values and then add, subtract and modify our small little double values.

Double trouble

But wait a second. We're trying to solve a completely integral problem! Why does our generated program use those registers at all?

This should raise a red flag. And indeed, if we remember pow's signature, it should be clear that it's not the right tool. It takes a double base and exponent, which indicates that it's suitable for terms like \$15.12151^{3.1415926}\$. This is a total overkill for your problem.

Using proper functions

So let's use another pow version instead:

long int pow4(long int x){
    return x * x * x * x;
}

Note that your compiler should create something like this from that:

movq    %rdi, %rax
imulq   %rdi, %rax
imulq   %rax, %rax
ret

but if your compiler doesn't recognize this potential (micro) optimization, you can use

long int pow4(long int x){
    const long int t = x * x;
    return t * t;
}

instead.

We also need to change prop:

int prop(long int A, long int B, long int C, long int D) {
  return (pow4(A) + pow4(B) + pow4(C) == pow4(D));
}

Allright. Now, before I show the times of the new program, let's check the output of your old one:

a = 1, b = 1, c = 1000, time = 114.156000s

That's when I hit ^C. How does the one using pow4 hold up?

a = 1, b = 1, c = 1000, time = 0.296000s
a = 1, b = 1, c = 2000, time = 0.578000s
a = 1, b = 1, c = 3000, time = 0.859000s
a = 1, b = 1, c = 4000, time = 1.140000s
a = 1, b = 1, c = 5000, time = 1.421000s
a = 1, b = 1, c = 6000, time = 1.703000s
a = 1, b = 1, c = 7000, time = 1.984000s
a = 1, b = 1, c = 8000, time = 2.265000s
a = 1, b = 1, c = 9000, time = 2.546000s
a = 1, b = 1, c = 10000, time = 2.828000s
a = 1, b = 1, c = 11000, time = 3.109000s
a = 1, b = 1, c = 12000, time = 3.390000s
a = 1, b = 1, c = 13000, time = 3.687000s
a = 1, b = 1, c = 14000, time = 3.968000s
a = 1, b = 1, c = 15000, time = 4.250000s
a = 1, b = 1, c = 16000, time = 4.531000s

Which is 0,2% of your original time, or a 500x speedup.

However, this comes at a cost: pow4(500000) is too large for a int64_t, since \$\log_2(500000^4) \approx 76\$. The greatest number you could check with a uint64_t is 65535, \$2^{16}-1\$, which shouldn't be very surprising. As the standard does not provide int128_t or similar, you should make sure that your numbers don't exceed those bounds.

You can either write your own large integer logic for this, or use GMP.

Proper bounds and parameter estimation

Next up, you can increase the lower bounds of b and c, so that \$a \le b \le c\$. And for d, well, if we have a, b, c, then there is only one solution for d. We can directly search for that solution with binary search.

The binary search makes a \$\mathcal O (n^3 \log n)\$ algorithm from your current \$\mathcal O (n^4)\$ one, which should provide a lot more speed than the previous speedup.

Even better, if you used the appropriate bounds for a, b and c, we can bound d by

$$d^4 = a^4 + b^4 + c^4 \le c^4 + c^4 + c^4 = 3c^4$$

and therefore get

$$c \le d \le \sqrt[4]{3}\,c.$$

With the proper binary algorithm,you can finish the first a=1,b=1 case quickly:

…
a = 1, b = 1, c = 481000, time = 0.031000s
a = 1, b = 1, c = 482000, time = 0.031000s
a = 1, b = 1, c = 483000, time = 0.031000s
a = 1, b = 1, c = 484000, time = 0.031000s
a = 1, b = 1, c = 485000, time = 0.031000s
a = 1, b = 1, c = 486000, time = 0.031000s
a = 1, b = 1, c = 487000, time = 0.031000s
a = 1, b = 1, c = 488000, time = 0.031000s
a = 1, b = 1, c = 489000, time = 0.031000s
a = 1, b = 1, c = 490000, time = 0.031000s
a = 1, b = 1, c = 491000, time = 0.031000s
a = 1, b = 1, c = 492000, time = 0.031000s
a = 1, b = 1, c = 493000, time = 0.031000s
a = 1, b = 1, c = 494000, time = 0.031000s
a = 1, b = 1, c = 495000, time = 0.031000s
a = 1, b = 1, c = 496000, time = 0.031000s
a = 1, b = 1, c = 497000, time = 0.031000s
a = 1, b = 1, c = 498000, time = 0.031000s
a = 1, b = 1, c = 499000, time = 0.031000s
a = 1, b = 1, time = 0.031000s

Which brings us back into the realm of your lifetime.

Exercise

Write a function, that given a, b and c checks whether there exist a d, such that your property holds. It should return -1 if there does not exist such a d, and the d otherwise.

Use that function in your code. Make sure that you need roughly \$\log d_{\text{max}}\$ iterations in that function.

Important remark about integer sizes

Keep in mind that long int is usually just a 64 bit integer, which means that the largest integer you can store is \$2^{63}-1\$. Integer types with more bits have greater bounds, but are platform specific. Also, multiplication can be a tad slower, since multiplying 128bit numbers isn't as easy as multiplying 64bit numbers.

See the next section how to get multiplications down.

An actual review

Our pow4 is now essentially two multiplications. However, we're still using pow4 too often. After all, we don't need to recalculate \$a^4\$ in every iteration. The compiler happily does, since it doesn't optimize aggressively enough.

Which brings us to the actual review: your code is cleanly written, easy to read and to understand. Unfortunately, well-written, modular code often doesn't squeeze the last bit (heh) out of your hardware, unless your compiler/runtime is very smart (and thus often expensive).

So let's get back to the drawing board for a final review of your code:

Includes

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

I would sort them by name, but that's fine. You don't include anything that's not necessary, nor did you forget something (and got saved by a non-standard compliant compiler).

Declaration

int main() {
    long int a, b, c, d;
    clock_t t;
    t = clock();

Depending on whether you write ANSI-C or C99, I would defer declaration of variables as long as possible. For example, at the moment it's easy to accidentally change c to some bogus value, or forget a { and accidentally check the prop after the loops or similar:

for (a = 1; a < 100000; a++)
    for (b = 1; b < 300000; b++)
        for (c = 1; c < 500000; c++)
            for (d = 1; d < 500000; d++)
                printf("inner loop");
                if (prop(a,b,c,d))
                    printf("FOUND IT!\na = %ld\nb = %ld\nc = %ld\nd = %ld\n", a, b, c, d);

Whoops. The if doesn't get checked, and you don't get a warning (in older compiler versions; new ones do warn about possible whitespace issues). If you declare your variables later (e.g. C99-style), errors like that cannot happen (although it introduces possible shadowing):

for (long int a = 1; a < 100000; a++)
    for (long int b = 1; b < 300000; b++)
        for (long int c = 1; c < 500000; c++)
            for (long int d = 1; d < 500000; d++)
                printf("inner loop");
                if (prop(a,b,c,d))
                    printf("FOUND IT!\na = %ld\nb = %ld\nc = %ld\nd %ld\n", a, b, c, d);

This will now lead to a compiler error, since a, b and so on are out of scope. Either way, that depends on the language standard you want to use. Some people prefer one way, others the other one. Choose yours.

Types

Given that all values should be strictly greater than zero, long int is not the appropriate type, as it can be negative. We should accommodate that. However, instead of using long unsigned int throughout our code, let's use a type synonym in case we want to change it later to a type with a greater range:

 typedef long unsigned int Number;

You can probably come up with a better name.

Cache results (by hand)

One thing that strikes me most is that you recalculate \$a^4\$ and so on every time. We can easily treat this with more variables (using your declaration style):

int main() {
    long int a, b, c, d;
    long int a4, b4, c4, d4; // new variables
    clock_t t;
    t = clock();

    for (a = 1; a < 100000; a++) {
        a4 = pow4(a);                             // remember
        for (b = a; b < 300000; b++) {
            b4 = pow4(b);                         // remember
            for (c = b; c < 500000; c++) {
                c4 = pow4(c);                     // the fourth power
                for (d = c; d < 500000; d++) {
                    d4 = pow4(d);                 // of this member
                    if (a4 + b4 + c4 == d4)
                        printf("FOUND IT!\na = %ld\nb = %ld\nc = %ld\nd = %ld\n", a, b, c, d);
…

Remember how I said that nicely written, modular code isn't often optimal? This is one of those unfortunate examples where you have to help the compiler (unless you know exactly what optimization flags you have to use or your compiler is overly aggressive). The prop is gone, the calls to pow4 are now in your loop.

But the compiler cannot make a mistake here anymore: it's now very clear that a4 doesn't need to be recalculated 300000*500000*500000 times.

That being said, we should apply the other suggestions like the type synonym and the late declaration:

typedef long unsigned int Number;

int main() {
    clock_t t;
    t = clock();

    for (Number a = 1; a < 100000; a++) {
        const Number a4 = pow4(a);                         // remember
        for (Number b = a; b < 300000; b++) {
            const Number b4 = pow4(b);                     // remember
            for (Number c = b; c < 500000; c++) {
                const Number c4 = pow4(c);                 // the fourth power
                for (Number d = c; d < 500000; d++) {
                    const Number d4 = pow4(d);             // of this member
                    if (a4 + b4 + c4 == d4)
                        printf("FOUND IT!\na = %ld\nb = %ld\nc = %ld\nd = %ld\n", a, b, c, d);
…

While const isn't necessary here, it will make sure that we don't change our cached results accidentally.

The time has come

Although our code is now more verbose, there is one small piece of code that repeats itself three times throughout your main:

((double)(clock() - t))/CLOCKS_PER_SEC)

That's quite hard to read, isn't it? It's a perfect candidate for a function:

static inline seconds_since(clock_t t){
    return ((double)(clock() - t))/CLOCKS_PER_SEC;
}

This changes your printf from

printf("a = %ld, b = %ld, c = %ld, time = %fs\n", a, b, c, ((double)(clock() - t))/CLOCKS_PER_SEC);

to

printf("a = %ld, b = %ld, c = %ld, time = %fs\n", a, b, c, seconds_since(t));

Ah. Much easier to read. That's what inline functions are for. Note that any sophisticated compiler should inline that function anyway, so you may also drop inline if you don't want to use C99.


Managing database connections for unit tests

Did you tried to move this logic to the helper itself ? It can receive a varargs of SessionType to connect and keep them until you tell him to destroy them. It can maintains a Map<SessionType, DatabaseConnection> to give access to them.

/* WARN; This is not production ready. Validation and exceptions handling
 * is missing and the "destroy" method can be improved.
 */
public class DatabasesHelper {
  private final Map<SessionType, DatabaseConnection> connections = new HashMap<>();

  public void prepare(SessionType... sessions) {
    for(SessionType session : sessions) {
      connections.put(session, this.DoLogin(session));
    }
  }

  public void destroy() {
    for(SessionType session : sessions) {
      this.DoLogout(connections.get(session));
    }
    sessions.clear();
  }

}

Please note that your methods names does not follow the Java, naming conventions. You should use lowerCamelCase for them.


std::lock implementation in C with pthreads

It does not look like your code will deadlock.
That said, I am not very keen on the spin lock like attempt, as I can see situations where it may not be great in efficiency.
It (std::lock) guarantees that no matter what order you specify the locks in the parameter list you will not fall into a deadlock situation.
A common technique (simple enough you could use (but the standard does not specify whether this technique is used by std::lock)) is to make sure the locks are ordered in some way. This basically means that the order you lock the mutexes in must be consistent (thus independent of the order they are in the parameter list).

The actual order should be defined in terms of some immutable property of the underlying mutex (such as its address).
This also means that if a lock in the list is already locked it must be released so that the locks are acquired in the correct order (Note: not all lockables can safely call try_lock() so you can't always determine if you should unlock).

Example of deadlock occurring when locks are not acquired in order:
 Time:     Thread-1          Thread-2
           lock(g2, g1)      lock(g1, g2)

   0       lock(&g2)

   1                         lock(&g1)

   2       lock(&g1) // Can never succeed

   3                         lock(&g2) // Can never succeed

Metal deadlock.
Thread 1 is now waiting for g1 (held by thread 2), while thread 2 is waiting for g2 (held by thread 1).


I think using memory size is an interesting idea. You may want to define the values  with an expression (e.g. startingChunks = round(memSize / 600) * 2 + 8), rather than an else-if chain, tho if you want to target specific devices, an if-else chain is acceptable.

Old:

if (memSize < 256) {
    _startingChunks = 0;
    _chunkSize = 0;
    _chunksToGenerate = 0;
    _maxZoom = 0.00;
} else if (memSize >= 256 && memSize < 800) {
    //ipod 5 is in this range
    _startingChunks = 8;
    _chunkSize = 16;
    _chunksToGenerate = 4;
    _maxZoom = 0.45;
}

Underscores are annoying, is there any reason you use them in those variable names? If it's supposed to denote constants, doesn't the name work well enough? It shouldn't be doubted that chunkSize, for instance, won't change if you know how the app works. And if in a future update you want it to change, you could change it without renaming.
if (memSize < 256) {} else {} – in the else block, memSize must be >= 256. So there's really no need to add that to the else if.

With my changes:

if (memSize < 256) {
    startingChunks = 0;
    chunkSize = 0;
    chunksToGenerate = 0;
    maxZoom = 0.00;
} else if (memSize < 800) {
    //ipod 5 is in this range
    startingChunks = 8;
    chunkSize = 16;
    chunksToGenerate = 4;
    maxZoom = 0.45;
}


Schedule Global Task by using static System.Timers

There's no reason to expose timer1 as a public member, I would just have a static method DoFoo() that calls timer1.Start().

There are a few issues with the way you implement you thread passing.  With the short interval and the immediate stop it seems that you are trying to just pass the job to another thread.  This can fail in a variety of ways:

Multiple calls to DoFoo() in quick succession will result in just one invocation of timer1_Elapsed
Under heavy load or immediately after startup, it may take more than 100 ms to reach time1.Stop().  This way one call to DoFoo() can result in multiple invocations of timer1_Elapsed.
Sleeping in a thread is the last thing you want to do.  You are occupying this thread for 6 hours for no good reason.  Further, your application may not be running in 6 hours.

So how do you fix it?  If you really need to sleep for 6 hours and the task is important, you need to save the job to an external store (like a database) in case your process terminates.  If it's just about scheduling work on another thread, that's what the ThreadPool is for.  If you do need the delay but it's not critical work, you can create a Timer with the long delay.  Make a new one for each call, and make sure you store a reference so it doesn't get GC'ed before it fires.


Indeed, both versions you have are iterative. I'm not actually sure that a recursive solution makes sense in this case---usually a recursive approach is for the classical pattern of holding the result of operating on the first item, then recursing into the remaining items. Calculating the GCD doesn't fit that pattern.

One small suggestion: you can use (zero? b) instead of (= 0 b).


There are lots of ways to improve this hard-to-read code but all of them are unimportant compared to the fact that this is massively insecure against common attacks.  You are implementing a component of a security system; you need to build a threat model and understand what you are doing.  Implementing a security system is not a beginner task!

An important rule to follow is never use System.Random for a security purpose.

A random number generator needs to be genuinely unpredictable for it to be used in a security system that depends on unpredictability. System.Random is not truly random, and nor is it crypto strength pseudo random.

Why does this matter? Because an attacker who knows anything about the system used to generate the passwords can make good guesses about what passwords it will generate, much better than chance. How does the attacker get information about the system? A generated password leaks information about the state of the system.

That is, given a collection of passwords generated by this algorithm allows an attacker to determine the internal state of System.Random and then from that they can make good guesses as to all past and future passwords that will be generated. That's bad! The whole point of a randomly-generated password is to make it hard to guess.

Use a crypto-strength PRNG instead.


Don't quote $things:
for i in "1 2 3 4"; do
   echo "i=$i"
done
i=1 2 3 4
# Better is
for i in 1 2 3 4; do
   echo "i=$i"
done
i=1
i=2
i=3
i=4

When my_program is written well, errors are written to stderr and normal output to stdout. Your bash code is working well, so the program already uses the right returncode.
Can you change the my_program? When you can add an option -s (silent/summary), the program can make sure only 1 line is written to stdout (when OK) or stderr (when NOK):
for thing in ${things}; do
    my_program -s "${thing}"
done

Or without for-loop
printf "%s\n" ${things} | xargs -L1 -I{} my_program -s "{}"

When you can't change my_program, or you don't want to, move the special handling to a function and remove the additional echo commands:
tail_my_program() {
   output=$(my_program $* 2>&1)
   if (( $? == 0 )); then
      tail -1 <<< "${output}"
   else
      tail -1 <<< "${output}" >&2
   fi
}

for thing in ${things}; do
    tail_my_program "${thing}"
done

Your original solution and my function have a small bug: When my_program writes something to stdout after writing an error message to stderr, the stdout message is selected after an exit 1. This might never happen.


Get a map containing elements which are present in unordered map A but are not present in unordered map B

At first sight, this looks good - you let a standard library algorithm and two standard library class constructors do the heavy lifting. But this approach ships with a drawback, especially the linear (given that the input is sorted) copy construction of the two local std::maps can be quite a bottleneck, e.g. when the keys are long enough to not fit into the SSO buffer. Together with std::set_difference, you have a time complexity of approximately O(N1 + N2) (neglecting constant factors) plus that of the insertion into the resulting map (which is inevitable).

You could consider a simpler, more manual approach. Recall that element lookup by a key is constant time in a hash map, so doing that inside a loop over all elements doesn't add much overhead to the function:

std::map<std::string, int> getDiff(const std::unordered_map<std::string, int>& src,
        const std::unordered_map<std::string, int>& exclude)
{
    std::map<std::string, int> diff;

    for (const auto& node : src) {
        const auto lookup = exclude.find(node.first);

        if (lookup == src.cend() || node.second != lookup->second)
            diff.insert(node);
    }

    return diff;
}

First note that I have renamed the function arguments here. Whether src and exclude is the clearest choice might be debatable, but it should be better than unordered_mapA and unordered_mapB, which duplicates info already present in the type of these arguments. This has an improved time complexity of O(N1) (again, without constant factors or counting std::map::insert).

This can be taken one step further to make it more reusable, as there aren't any specific requirements on key and value types that should be nailed down (besides the ability to check whether objects of the value type compare equal).

template <class Key, class Value>
std::map<Key, Value> getDiff(const std::unordered_map<Key, Value>& src,
        const std::unordered_map<Key, Value>& exclude)
{
    // Exactly as above...
}

You can use type deduction for saving some keyboard strokes upon the invocation:

std::unordered_map<std::string, int> a{/* ... */};
std::unordered_map<std::string, int> b{/* ... */};

const auto diff = getDiff(a, b));

And one last, idiomatic level of indirection could then be to not commit to a specifiy return type, but instead pass an output iterator that accepts a std::pair<Key, Value>:

template <class Key, class Value, class OutputIt>
OutputIt getDiff(const std::unordered_map<Key, Value>& src,
        const std::unordered_map<Key, Value>& exclude, OutputIt dest)
{
    // As above...

        if (...)
            dest = node; // instead of diff.insert(node);

    return dest;
}

Here, it is convention to return the output iterator at the end of the function. You can instantiate and invoke the above template as follows.

std::map<std::string, int> diff;
getDiff(a, b, std::inserter(diff, diff.end()));

Or, if you later decied that you need cache locality for the result of the operation:

std::vector<std::pair<std::string, int>> seqDiff;
getDiff(a, b, std::inserter(seqDiff, seqDiff.end()));

Note that you still want more abstraction, you could also hide the src argument behind input iterators, as the loop over this container isn't specific to the hash map type.


QuickSort in Java with Lomuto Partition or Hoare Partition

public static void main(String... args) {
    int array[] = {2, 3, 4, 1, 11, 5, 7, 0, 10, -1, 99, 23};
    quickSort(array);
    System.out.println(Arrays.toString(array));
}

I like that you're testing your code, but you have to visually verify your program's correctness. It would be better to use a testing framework and automate that task.

private static void quickSort(int array[], int l, int r) {

One letter variable names are hard to read.
It would be better to use left and right here.
Alternatively, lhs and rhs are common abbreviations for "left hand side" and "right hand side".
I don't care for them, but they're common enough that I let them slide through code reviews at work.

   int p = lomutoPartition(array, l, r);//hoarePartition(array, l, r);//lomutoPartition(array, l, r);

There's dead code here...
It happened because you're physically changing the code in order to switch between your two different strategies.
It would be better to actually implement the strategy pattern.

You could create a PartitioningStrategy like this.

interface PartitioningStrategy {
    int partition(int numbers[], int left, int right);
}

And then have two implementations.

public class HoarePartitioningStrategy implements PartitioningStrategy {
    public int partition(int numbers[], int left, int right) {
        //...
    }
}

public class LomutoPartitioningStrategy implements PartitioningStrategy {
    public int partition(int numbers[], int left, int right) {
        //...
    }
}

Then you can decide which strategy to use in your main.

public static void main(String... args) {
    int array[] = {2, 3, 4, 1, 11, 5, 7, 0, 10, -1, 99, 23};
    quickSort(array, new LomutoPartitioningStrategy());
    System.out.println(Arrays.toString(array));
}

Nice and clean. Keeps your code open for extension, but closed for modification.


Accumulate ids to make a single ajax request

I was able to somehow encapsulate the logic be creating a function generator that holds the previous two functions like this:

  const fakeData = [{
      id: 1,
      name: 'foo'
    },
    {
      id: 2,
      name: 'bar'
    },
    {
      id: 3,
      name: 'baz'
    }
  ];

  function makeGetter(fetchFunc, debounceTime = 400) {
    let idsToFetch = [];

    let getItemsPromise, resolve, reject;

    const fetchItems = _.debounce(() => {
      console.log('fetching items...');
      const currentResolve = resolve;
      const currentReject = reject;
      const currentIdsToFetch = idsToFetch;

      Promise.resolve(fetchFunc(currentIdsToFetch))
        .then(res => currentResolve(res))
        .catch(err => currentReject(err));

      getItemsPromise = resolve = reject = null;
      idsToFetch = [];
    }, debounceTime);

    const getItems = (ids) => {
      idsToFetch = ids.filter((id) => !idsToFetch.includes(id)).concat(idsToFetch);
      if (!getItemsPromise) {
        getItemsPromise = new Promise((_resolve, _reject) => {
          resolve = _resolve;
          reject = _reject;
        });
      }

      fetchItems();

      return getItemsPromise
        .then((res) => {
          return res.filter((item) => ids.includes(item.id));
        })
    }

    return getItems;
  }

  const getItems = makeGetter((ids) => {
    // simulating ajax request
    return new Promise((resolve, reject) => {
      setTimeout(function() {
        const result = ids.map((id) => fakeData.find(item => item.id == id));
        resolve(result);
      }, 400);
    })
  });

  setTimeout(() => {
    console.log('first request start');
    getItems([1]).then(res => console.log('first result:', res));
  }, 100);
  setTimeout(() => {
    console.log('second request start');
    getItems([1, 2]).then(res => console.log('second result:', res));
  }, 200)
  setTimeout(() => {
    console.log('third request start');
    getItems([1, 3]).then(res => console.log('third result:', res));
  }, 300)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>


Splitting a string into words or double-quoted substrings

Seems like a job for a regular expression:

string baseString = "This is a \"Very Long Test\"";
var re = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");
var strings = re.Matches(baseString).Cast<Match>().Select(m => m.Value).ToArray();

What the regular expression (?<=")[^"]*(?=")|[^" ]+ does is that it either finds a sequence of zero or more characters that are not " ([^"]*) preceded by a " ((?<=")) and followed by a " ((?=")) or a sequence of one or more character that are not " or a space ([^" ]+).

For the sample input, it gives the same output as your version. The code itself is much simpler, but the regular expression might be hard to understand, especially if you're not used to them.


Move update_attributes into class and check for non-nil params to update only

class Customer
  def update_customer params
    update_attributes(:city_id => params[:city],
                      :zip_code => params[:zip],
                      :first_name => params[:first_name],
                      :last_name => params[:last_name],
                      :phone => phone_number_digest(params[:phone]),
                      :street1 => params[:street1],
                      :street2 => params[:street2],
                      :email => params[:email])
  end

  def phone_number_digest *numbers
    numbers.map{ |s| s.gsub!(/\D+/,'')}
  end

end

In your controller

@cust = Customer.find(params[:customer_id])
@cust.update_customer(params)

This keeps it relatively clean and logically separates your persistence logic.

Also to answer your questions.

@cust = Customer.find(params[:customer_id])
if @cust.update_customer(params)
  #do something
else
  #do something else
end

Ruby executes the code in conditionals, so you could just have it like I have above.
you would probably want to do this logic in the controller, as only allow the keys with non nil params to work.  This one is bit trickier, but definitely can be done.  Perhaps you want to build your sanitized hash of params then pass it in.  in that case, perhaps the ** operator(double splat for keyword args) would be useful.
Definitely worth your time. Naming is quite possibly one of the most important ideas in programming.  You want to read code that you worked on a year or 2 ago without having to dive into the internals, and if you properly name you classes and methods, it becomes much simpler.


Your code is good but it may be overly complex. The more concise the code the easier it is to read (for me anyway). In this example below I have just used some example words, this code of course is just a quick example for demonstration. There is not anything in place if you get the word or want to guess the word etc. I couldn't really find a reason to use a class for simpler games because although the functions are 'closely related' in your functions, comprehension can save a lot of time and code.

The while loop is useful because it gives a consistent input option which can be as user friendly as you make it. I think its essential for the users experience when making something like a text RPG.

import random

words = ['cheese', 'biscuits', 'hammer', 'evidence']
word_choice = [i.lower() for i in random.choice(words)]
lives = 3
cor_guess = []
while True:
  print('Letters found: {}\nWord length: {}'.format(cor_guess, len(word_choice)))
  if lives == 0:
      print('Your dead homie!\nThe word was: ', word_choice)
      break
  guess = str(input('Guess a letter: '))
  if guess in word_choice:
      print(guess, 'is in the word!\n')
      cor_guess.append(guess)
  else:
      print('Your dying slowly!\n')
      lives -= 1

Example of the output:

Letters found: []
Word length: 8
Guess a letter: v
v is in the word!

Letters found: ['v']
Word length: 8
Guess a letter: i
i is in the word!

Letters found: ['v', 'i']
Word length: 8
Guess a letter: r
Your dying slowly!

Letters found: ['v', 'i']
Word length: 8
Guess a letter: b
Your dying slowly!

Letters found: ['v', 'i']
Word length: 8
Guess a letter: o
Your dying slowly!

Letters found: ['v', 'i']
Word length: 8
Your dead homie!
The word was:  ['e', 'v', 'i', 'd', 'e', 'n', 'c', 'e']


Number of zeroes at the end of a factorial

There is a problem with your solution for large numbers ( >= 5^13 to be exact) because mulFive=mulFive*5; will go negative as the int overflows.

To protect against this, you could do

 while(num/5!=0)
 {
     zeroCount=zeroCount+ (num/5);
     num = num/5;
 }

i.e. divide the number rather than multiply the divisor, then only the size of num is a limit (2^31-1)


Converting between different units of temperature

Numerical consts are double, either add them eg as 5.0f or use double.
Define a constants for 0°C = 273.15K and also for Fahrenheit to Celsius conversation (avoid repeated magic constants 273.15, 9.0 / 5.0, 32.0).
In check the distance from 273.15 is not symmetric, probably a typo.
The name check doesn't imply what is checked, meaningful names not limited to this function would be a recommended.

A modified version could include:

#include <math.h>

const double Celsius2KelvinShift = 273.15;
const double Fahrenheit2KCelsiusShift = 32.0;
const double Fahrenheit2CelsiusFactor = 5.0 / 9.0;

/** check if kelvin temperature is celsius 0 **/
int checkIf0Celsius(double N)
{
    const double tol = 0.001; /** I had to set this limit. There is no other way. **/
    return fabs(N - Celsius2KelvinShift) < tol;
}

/*** Fahrenheit ***/
double Fahrenheit2Kelvin(double F)
{
    return Fahrenheit2CelsiusFactor * (F - Fahrenheit2KCelsiusShift) + Celsius2KelvinShift;
}

double Fahrenheit2Celsius(double F)
{
    return Fahrenheit2CelsiusFactor * (F - Fahrenheit2KCelsiusShift);
}

/** Celsius **/
double Celsius2Kelvin(double C)
{
return C + Celsius2KelvinShift;
}

double Celsius2Fahrenheit(double C)
{
    return C / Fahrenheit2CelsiusFactor - Fahrenheit2KCelsiusShift;
}

/*** Kelvin ***/
double Kelvin2Celsius(double K)
{
    return K - Celsius2KelvinShift;
}

double Kelvin2Fahrenheit(double K) {
    return (K - Celsius2KelvinShift) / Fahrenheit2CelsiusFactor - Fahrenheit2KCelsiusShift;
}


velocity profile of laminar flow in a pipe

I think this is a good starting point, but some better code organization will help you in the long run

I would first summarize a few main problems I see:

Unclear input parameters
Ambiguous path execution
The most important part is hard-coded
Too many output parameters
Repetition of code (i.e. violation of DRY)

All of this basically boils down to code organization.  Rather than just showing you a different solution, I think its best to explain the issues:

The usage of db and v_average is such that it isn't immediately clear how to use your method.  It's best if a user can look at your method and see exactly how it is supposed to be called.  Some docstrings would help.  Also, since these parameters are optional, they should be named parameters, not positional ones: def flow(diameter, viscosity, len_pipe, dp=False, v_average=False).  Otherwise they have to pass in False to dp in order to use v_average, and that is less than ideal.
Your code will break if someone passes False in both for dp and v_average.  You want a nice guard up top: if not dp and not v_average: raise ValueError('You must provide either dp or v_average)  This makes your code self-documenting, and avoids bugs.  Also, you should have a guard to return an error if both have a value.  That is just as much a user mistake, and will have an ambiguous return value if the two passed in values don't agree.
The post important thing in your code is the locations where you want the flow velocity.  This is the entire point of your function: to calculate flow velocity at some points.  However, you have the points hard-coded.  Sure, you want it at 7 points right now, but what if your needs change?  You have to re-write your function.  That's no good.  Just let x be an input parameter, and let the user provide it.
You are returning too many things as output parameters.  This is basically a violation of separation of concerns.  All you should really be returning is v, which is easier if the user passes in x.  You don't have to return dp or v_average.  Effectively, your function is doing 5 things: calculating some x values of interest, calculating dp if v_average is provided, calculating v_average if dp is provided, calculating v, and calculating vmax.  You need a function that does less.

Also, while I don't know much about laminar flows, the statistician/physicist in me says that you are using a strange definition of average velocity: v_average = vmax / 2.  I'm going to assume for now that v_average doesn't refer to an actual statistical average, but that it has a different definition in your particular use-case.

Small Changes

So what do you do about this?  Personally, I think you should just separate this into two separate functions: flow_from_dp and flow_from_v_average.  Pass in x, lose the extraneous input parameter, and return only v.  If the user wants to figure out vmax, then make a separate function: calculate_vmax.  Similarly, I would make helper functions that can calculate dp from v_average and vice-versa.  Having more functions that do less is actually a good thing in this case.  Each function will have a clear calling sequence and return only one thing.  That is exactly what you want.  I'll leave actually making that change as an exercise for the reader :)

Big Changes

Another option would be to make this code OOP.  I would envision a pipe class that has a diameter and length.  You could also have a fluid class that has a viscosity and dp or v_average.  It would then automatically calculate the one given the other.  Your flow method would then become bound to one of the classes, or it could be a method that simply accepts a pipe and a fluid and calculates the velocity at a given set of points.  I'm not going into a crazy amount of detail here simply because I don't know whether or not that might be a useful suggestion for you, as that largely depends on your level of familiarity with OOP.  If you are interested, I would be happy to give an example of what an OOP solution would look like.


Looping through an Array of objects to find an ID in a sub array

I cannot say about AngularJS, but in normal JavaScript I would do something like this:

var tagObjects = TagFactory.retrieveTags();

if (findTag(tagObjects, tagObj.tag_id)) {
    // remove tag
}
else {
    // add tag
}

function findTag(tagObjects, tag_id) {
    return tagObjects
        .reduce(function (total, obj) { return total.concat(obj.tags); }, [])
        .find(function (tag) { return tag.tag_id === tag_id; })
    ;
}

Note that find is a part of upcoming es6 standard. So you might need to use es6-shims (like I do) or write your own version. It's very easy.

Or, if TagFactory.retrieveTags() returns some special structure — shouldn't it also provide findTag method?


Longest contiguous Increasing Subset in java

For an input array of N values, the current implementation creates N instances of ArrayList. But you only need 2:

One to store the longest sequence seen so far
One to store the currently tracking sequence

For example the input 5, 6, 7, 1, 2, 3, 4, walking through the elements from the start:

5: the first element -> add it to the current sequence
6: greater than the previous -> add it to the current sequence
7: greater than the previous -> add it to the current sequence
1: the current sequence is broken -> the current sequence is longer than the longest sequence -> update the longest sequence = [5, 6, 7]
2: greater than the previous -> add it to the current sequence
3: greater than the previous -> add it to the current sequence
4: greater than the previous -> add it to the current sequence
Reached the end -> the current sequence is longer than the longest sequence -> the longest sequence is [1, 2, 3, 4]

The implementation can be simplified to:

public static List<Integer> findLIS(int[] array) {
    List<Integer> longest = new ArrayList<>();
    List<Integer> current = new ArrayList<>();

    int previous = Integer.MAX_VALUE;
    for (int value : array) {
        if (value <= previous) {
            if (longest.size() < current.size()) {
                longest = current;
            }
            current = new ArrayList<>();
        }
        current.add(value);
        previous = value;
    }

    return longest.size() < current.size() ? current : longest;
}

Some other tips on the original code:

Avoid arrays of generic types such as ArrayList<Integer>[]
Prefer interface types in declarations and method return types, such as List instead of ArrayList
When initializing generic types, Java 7 can guess the correct type parameter, so instead of new ArrayList<Integer>() you can write new ArrayList<>() (also known as the diamond operator <>)
The indentation and formatting was inconsistent, use an IDE to format the code nicely
Instead of printing elements of LIS one by one, System.out.println(LIS) would easily produce an output that's just as readable
A more compact writing style to initialize an array: int[] array = { 7, 1, 3, 8, 11 };


Pasting Values To/From a Calculation Model

Excel is not a database

I cannot stress this strongly enough. Excel has many excellent uses, but please don't ever get in the habit of thinking that it is a viable alternative to a proper Database.

Never assume that you know where the performance bottleneck is

If you could accurately forecast where a performance bottleneck would be, then you wouldn't have an unbearably slow Macro in the first place.

Rule #1 of performance increases is to benchmark everything, because it will never be where you thought it would be.

Poor man's VBA benchmarking (only accurate to the nearest 1/100th of a second):

Public Sub SplitTimer(ByVal printMessage As String, ByRef oldTimer As Double)
    '/ prints message and time diff between current timer and previous timer
    '/ then updates previous timer with current timer

    Dim currentTimer As Double
    currentTimer = Timer()

    Debug.Print printMessage & " - " & (currentTimer - oldTimer) & " s"

    oldTimer = currentTimer

End Sub

Then, in your Macros:

    Dim timerStore As Double
    timerStore = Timer()

    ws2.Range("B3").Value = ws1.Range("D" & i).Value
    SplitTimer "B3", timerStore

    ws2.Range("B4").Value = ws1.Range("E" & i).Value
    SplitTimer "B4", timerStore

    ws2.Range("B5").Value = ws1.Range("F" & i).Value
    SplitTimer "B5", timerStore

    ws2.Range("B6").Value = ws1.Range("G" & i).Value
    SplitTimer "B6", timerStore

And so on. You'll then get a list of how long each section of your code took to execute. In general, there will be one section that's responsible for ~98% of the runtime:

'/ (hypothetical output)
B3 - 1.40625 s
B4 - 0 s
B5 - 0 s
B6 - 0.041796875 s

Take that operation, split it into smaller pieces, benchmark. Repeat until you've found the source of your slow runtime. Then you can experiment yourself, or take that very specific opeation to SO for performance ideas.

In your specific case, I have a hunch.

Copy/Pasting actually doesn't take a lot of time (per operation). 20 operations in 2 minutes, I'd expect it to be less than 1% of runtime. What takes time is all the Events that trigger when you change a worksheet.

In particular, every calculation is going to re-calculate every time you paste a new value in.

Try this:

Application.Calculation = xlCalculationManual

For i = 4 To selection

    '/ Paste operations

    '/ Paste operations

    '/ Paste operations

    Application.Calculate '/ we only calculate once per iteration, when everything's set up and ready.

    ws1.Range("AO" & i).Value = ws2.Range("M4").Value

Next i

And see if it makes a noticeable difference to your performance.


It looks really good to me. All I have a very minor quibbles/suggestions.

Since you're using FactoryGirl, you should be able to use create_list :user, 4 instead of the 4.times.map { ... } block

You might as well check that a new record be_kind_of User. Just checking if it's an ActiveRecord is a little loose.

You don't need to create many users for some of these tests (like #show and #destroy). It's fine to do so of course, but the more tests you accumulate the faster you'll want your tests to be. And fully creating several records may be a bottleneck, especially for something like user models that likely have a uniqueness validation. That'll cause Rails to perform extra queries (one to check if the record is unique, and another to insert it in the DB).

Lastly, try running rspec with the --format documentation option, if you're not already. It'll format the output like so

UsersController
    #index
        assigns all users to @users
        success
    #show
        ...

which I personally prefer because it reads well (and, as the name implies, documents stuff). But for that same reason, you may want to change success to succeeds and when valid to something like with valid params just so you get nicer sentences.

Again, this is all really minor stuff.


Activating items in some randomized arrays

Interacting with the DOM is one of the slowest operations in JavaScript.  I'd suggest selecting all your elements before the loop, then referring to the cached elements inside.
On the same token, do not perform any DOM manipulation in a loop if you can help it.  Since it doesn't look like you can, another approach is to detach all DOM elements you're going to rearrange before the loop, perform the manipulation inside the loop, then re-attach them to the DOM at the end.
A reverse while loop would be faster than the for.
If you're using a version of jQuery prior to 1.6, the .data() method carries a lot of overhead.  In checkAgainstEl(), use $.data($($item.select).get(val), 'personId') instead.
It looks like you're re-wrapping jQuery objects in new jQuery objects unnecessarily, and in multiple places.  Like in #4.  I'm assuming variables prefixed with a $ are jQuery objects; if they are, no need to wrap them in $() again.

Your biggest problem is the DOM interaction inside a loop.  Cut that out any way you can and you'll be golden.


Select the element out of the array if its index is a Fibonacci number

Some notes:

fibonacci_numbers = numbers.select { |num| fibonacci.include?(num) }. Array#include? is O(n), this will be very slow. With this approach, fibonacci should be a set.
Since you have to store a the fibonacci values, the space complexity won't be nice for big inputs.
Your algorithm only works for arrays, it would be nice if it worked with enumerables.

I'd write:

def remove_fib_indexes(xs)
  Enumerator.new do |yielder|
    fib_a, fib_b = [0, 1]
    xs.each.with_index do |x, idx|
      if idx == fib_a
        # skip the repeated 1 in the sequence [0, 1, 1, 2, 3, 5, ...]
        fib_a, fib_b = (fib_b == 1) ? [1, 2] : [fib_b, fib_a + fib_b]
      else
        yielder.yield(x)
      end
    end
  end
end

xs = (0..Float::INFINITY).lazy.map(&:to_s)
remove_fib_indexes(xs).take(10).to_a
#=> ["4", "6", "7", "9", "10", "11", "12", "14", "15", "16"]


I know I'm late to the game, but each filter function contains essentially the same lines of code. Only the container element differs:

function processFilter($container) {
    $container.find("li.checked").removeClass("checked");
    $container.find("li:first").addClass("checked");
    $container.find("ul").scrollTop(0);
}

switch (clicked_id) {
    case "contain-word":
        processFilter($("#specie_filter"))
        // fall-through...
    case "specie_filter":
        processFilter($("#cell_filter"));
        // fall-through...
    case "cell_filter":
        processFilter($("#factor_filter"));
        // fall-through...
}

EDIT: @toto2, thanks for the reminder. Yeah, comments are useful in this case since omitting the breaks in a switch statement is not normally encountered.

Also, if you want to get a little crazy with the jQuery API, this could also work:

function processFilter(selector) {
    $(selector)
        .find("ul").scrollTop(0)
        .find("li.checked").removeClass("checked")
        .parent()
        .find("li:first").addClass("checked");
}

switch (clicked_id) {
    case "contain-word":
        processFilter("#specie_filter");
        // fall-through...
    case "specie_filter":
        processFilter("#cell_filter");
        // fall-through...
    case "cell_filter":
        processFilter("#factor_filter");
        // fall-through...
}


int size = sizeof(array)/sizeof(array[0]);

Just so you know, sizeof() returns size_t.
You can use a vector instead of an array.

vector<int> data = {2,4,6,8,10};

Simplify squaring using std::transform() and use a lambda expression
    in place of a function object:

#include <iostream>
#include <algorithm>
#include <functional>

using std::cout;
using std::transform;
using std::vector;

int main()
{

    vector<int> data = {2,4,6,8,10};

    transform(data.begin(), data.end(), data.begin(), [](int x){return x*x;});

    for(auto i : data)
        cout << i << " ";

}


Load title from database based on member country

Formatting

Your code has some formatting issues, reducing the readability of it:

spacing: your spacing around = seems arbitrary and you are missing spaces around ..
indentation: 2 spaces aren't really enough, use at least 4.
you should also indent the queries after a linebreak a bit more to increase readability.
your curly brackets are not consistent.

Security

Depending on who can add members and ranks, you may be vulnerable to XSS as the name is echoed unencoded. Even if this isn't a problem now because only you can add them, your requirements may change. Encoding input is always a good idea.

Also, depending on the type and changability of id you may be vulnerable to SQL injection. Always use prepared statements.

Structure

You should add functions to increase the maintainability - readability, reusability, changability, etc - of your code.

For example, selectMembersByCountry($country) or selectMemberRanksByID($id), which would then return an array of members and/or ranks.

Naming

zeile isn't a good name. First of all, your variable names shouldn't switch languages, and ideally they should all be in English.

But row wouldn't be much better. What is it really? Well, $result contains a list of members, right? So its name could reflect that, and then zeile could be member, which would give you: $member = $membersResult->fetch_assoc().

Simplify SQL

You could put all the logic directly into the query, but I don't think that that is necessary, so I'll leave that to someone else (although you may want to change your table structure first, see below).

I would say that it's fine the way it is. Especially when you extract the queries to functions, you would have well-defined and reusable functions.

Putting all the logic directly in the query is likely to be less readable and harder to maintain, and I doubt that it will give you a noticeable performance benefit (definitely not if you limit by 2).

Table Structure

Why do your mapping tables have their own id? This doesn't seem necessary.
For a 1:n relationship, you don't actually need a mapping table.
member-country doesn't actually seem to be a 1:n relationship, but n:m; A member can have multiple countries, and a country can have multiple members.
Because of the last point, you actually have duplications in your country2memb table (multiple entries of US for example). What you should do is have  a member table, a country table, and a memberCountry table to map between them.


At the very least, use verbose mode so you can see the whole thing at once.  Remember to explicitly include whitespace.

lineformat = re.compile(r"""
   (?P<ipaddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+
   -\s+
   -\s+
   \[(?P<dateandtime>\d{2}\/[a-z]{3}\/\d{4}:\d{2}:\d{2}:\d{2} (\+|\-)\d{4})\]\s+
   \"GET (?P<url>.+?(?=\ http\/1.1")) http\/1.1"\s+
   \d{3}\s+
   \d+\s+
   "-"\s+
   (?P<http_user_agent>.+?(?=\ ))\s+
   "-"\s+
   "(?P<x_forwaded_for>(.+?))"\s+
   "(?P<http_xb_user>(.+?))"\s+
   (?P<request_time>[+-]?([0-9]*[.])?[0-9]+)
   """,
   re.IGNORECASE | re.VERBOSE)


1
You are repeating condition ? '0' + integer : integer 3 times.
This can be reduced with const zeroPad = (num, places) => String(num).padStart(places, '0')
and doing
  hours = zeroPad(hours, 2);
  minutes = zeroPad(minutes, 2);
  seconds = zeroPad(seconds, 2);

The 2 is now a repeated magic number and you may wish to store it in a variable with a descriptive name.
2

Usually, there are no spaces around the equals sign:

3
I'm not familiar with JavaScript, but I would replace the nested setTimeout:
function showTime() {
  // ...
  setTimeout(showTime, 1000)
}

with a setInterval:
setInterval(showTime, 1000);
I would also place a space after the comma.
4
For formatting the time, take a look at this answer which suggests using:
hours = hours % 12;
hours = hours ? hours : 12;

5
You use document.querySelector('div') but this "returns the first Element within the document that matches the specified selector".
I would suggest using

 and document.getElementById


Project Euler # 24 Lexicographic permutations in Python

You’re building up a huge list of permutations in order to get to exactly one permutation. This is needlessly using time (computing all permutations that come before it) and memory (storing all those permutations in a list.

If you have 9 objects, you can have 9! = 3,628,800 permutations.  So with the 10 digits, 0 through 9, the first 362,880 permutations will be 0#########, the next 362,880 permutations will be 1#########, and you’ll reach the millionth permutation 274,240 permutations in to the 2#########’s.  So, 1 digit down, 9 to go.

With 8 objects, you can have 8! = 40,320 permutations.  Again, you can determine you’ll cross the 274,240’th permutation during the 7th group of permutations of the 9 objects: 013456789 ... so the your millionth permutation will be of the form 27########.

Repeat for the rest of the digits: a calculator works fine.   Or write a program to solve this, and the answer will be returned directly in a fraction of a second.


Scalability of running commands from user input

As requested.

An unstructured array may only be searched in linear order. To get better asymptotics you need a more search-friendly structure. A simplest solution would be to presort the Command array, and apply a binary search to find the command. A definite advantage here is a possibility to use standard library. You may even have the array sorted during build time.

For hundreds of thousands of commands the binary search would complete in about 20 lookups. If this is unacceptable, and your commands' names let you come up with a perfect hash function, hash is a way to go. Beware that a hash function must be really perfect - that is, almost no conflicts and almost no misses. Otherwise, the asymptotic constant would defeat all the advantages of O(1).

Update: assuming a unixish environment, the best way to sort at the build time is to have a commands.c file as

static Commands commands[] = {
#include "command-list.c"
};

with a command-list.txt text file

"time", getTime
"day", getDay

and a Makefile rule saying something like (may require some backslashes)

%.c: %.txt
    sort $< | sed -e 's/.*/{&},/' > $@


Comparing JSON documents for changes to values

Your code look good, but there is some room for improvements.

Comment your code

Its is a good pratice to comment the behavior that you code should have.
There is a good article written by Jeff Atwood called "Code Tells You How, Comments Tell You Why",
when you have time you should read it, but the best way that i find to write comments its to write them
before the code itself.

So if i had to write your code myself my first step would be something like:

// iterate all properties
    // check if the the first value is defined
        // ...
    // if the value is not defined then
        // ...

The hard part its (almost) never writing the code itself but thinking about it, if you have no problems
writing these comments you should have no problems writing the code itself. This helps you to make sure that
you undertand the problem that you are trying to solve with code, if If you find diffucults in this step you
should spend more time thinking about the problem.

Iterators

You are using forEach but seems that you only need to iterate until the first positive result so you may use some,
so your function will not need to iterate all the elements, so your function would be something like:

angular.some(model2, function(m2Val, m2Key){
  if((m2Key === m1Key) && (m2Val !== m1Val)){
      console.log(m1Key +" - " + m1Val + "  CHANGED TO  " + m2Key +" - " + m2Val);
      if((m2Val === decline) && !(m1Val)){
          nullDec = true;
      }
      if(((m2Val) && (m2Val !== decline)) && !(m1Val)){
          nullVal = true;
      }
  }
  return nullDec && nullVal;
})

Conditionals

Inside the if(!m1Val) you have the conditionals (m2Val === decline) && !(m1Val) and (m2Val) && (m2Val !== decline)) && !(m1Val),
you don't need to check m1Val again because its was already checked, the same its true to the block of code of your else statment.

Complexity

If you are sure that all the keys in model1 is always exist in model2 you don't need to iterate model2 to get its value.

Instead of the second forEach if the (m2Key === m1Key) you can get the value of the m1Key in the model2 object without the second loop;

This code have O(n^2) complexity:

angular.forEach(model1, function(m1Val, m1Key){
   if(!m1Val){
      angular.forEach(model2, function(m2Val, m2Key){
          if((m2Key === m1Key) && (m2Val !== m1Val)){

          }
      })
   }
}

This one below have O(n), but will need to make sure that all model1 and model2 have the same keys, or add some conditionals to
make sure that the behavior is correct.

angular.forEach(model1, function(m1Val, m1Key){
    if (!m1Val) {
        if (m1Val !== model2[m1Key]) {
            // ...
        }
    }
}

Even without these improvements your code passed all the test cases that i could come up with, so you just need to adjust your
style and get deep understanding of the JS api. I can see that you tried to cover all possible cases that is pretty good, you should continue aim for this as much as possible.


ChocolatesByNumbers- Find the number of N chocolates in a circle

I think to brute force this kind of question is the wrong path to take to begin with.
Quoting the wikipedia on Brute Force Search :

While a brute-force search is simple to implement, and will always find a solution if it exists, its cost is proportional to the number of candidate solutions – which in many practical problems tends to grow very quickly as the size of the problem increases. Therefore, brute-force search is typically used when the problem size is limited, or when there are problem-specific heuristics that can be used to reduce the set of candidate solutions to a manageable size. The method is also used when the simplicity of implementation is more important than speed.

As @WinstonEwert has pointed out, the number of chocolates that you can eat, is related to the least common multiplier. And, here is one fast way of computing it making use of the Euclidean Algorithm :
static int gcf(int a, int b)
{
    while (b != 0)
    {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

static int lcm(int a, int b)
{
    return (a / gcf(a, b)) * b;
}

Credit to @AffluentOwl's answer
However, LCM is not the final answer, but it is the number of chocolate that we care, we have to divide lcm by M. And, we can simplify all this :
public static int PrintNChocolatesInaCircle(int N, int M)
{
    // these already have a known answer
    if (M == 1) return N;
    if (M == N) return 1;

    int a = N, b = M;
    while (b != 0)
    {
        var temp = b;
        b = a % b;
        a = temp;
    }

    return N / a;
}

Lastly, make sure you respect the requirements :

Write a function:
class Solution { public int solution(int N, int M); }


Find cycles in Graph using Union Find Algorithm on Adjacency List

addnode(self, key1, key2, edge=0)

The parameter edge is not used.  Either remove it, or use it, but keeping it with a default value and not using it is obfuscation.

self.graph is a defaultdict(list), so testing if key2 is not present, and setting that key’s value to an empty list if it isn’t present, which is the raison d’être for the defaultdict(list), isn’t using that class properly.  You want the key to exist, but don’t want to add any values to it.  Simply use:

_ = self.graph[key2]

findcycle(self)

This function returns True or None.  It would be much easier to write documentation for the function if it returned only one “kind” of value.  Add return False to the end of the function.

Test cases

Put your test cases inside a __name__ == '__main__' guard.  Then you can import this as a module into another file without the tests running, but running this file by itself will still execute the tests.

if __name__ == '__main__':
    g = graph()
    g.addnode(0, 1)
    # ...

PEP8

Follow the PEP8 standard guidelines.  Put a space after all commas, don’t put a space before the parentheses in function calls.  Use an automatic checker (pylint, pyflakes, ...) to ensure you don’t violate these guidelines.


Complexity, Usability and Readability of FluentAPIs - Sample: FluentMethodInvoker

Kirk Woll makes some excellent points in his comment which could have been an answer IMHO.

  Fluent APIs are not better ipso facto.

You are entirely right in wanting to refactor your given code sample in the edit, but it might be worthwhile to first explore some other possibilities before deciding on using a fluent API.

A first concern is the Context class, as it looks like this is a global which is accessed from any location (A, B, C, ...). If there is any way to remove this global state, that might already be a more important improvement.

Using only your given code sample (assuming a IProcess interface), you could already improve it by writing something like this:

Dictionary<IProcess, int> executeOperations = new Dictionary<IProcess, int>
{
    { A, 1 }, { B, 1 }, { C, 1 }, { D, 1 }, { E, 1 }, { F, 1 },
    { Z, 100 }
}

foreach ( var executeItem in executeOperations )
{
    if ( !Context.WannaShutDown )
    {
        for ( int i = 0; i <= executeItem.Value; ++i )
        {
            executeItem.Key.Process();
        }
    }
}

It's not clear what the condition in your code sample is meant to be, or why only Z needs to check for it, but for demonstration purposes I believe the above example shows there are other ways of refactoring your given code without having to rely on fluent syntax. You could replace the int value in the dictionary to a struct containing more execution parameters.

That said, I believe your supplied sample is still too small to conclusively say whether or not using fluent syntax could be justified.


php swiftmailer two message instances with one mailer instance?

Note: this is intended to be a Community wiki since it was taken from a deleted answer by yannis; The suggestion to do this was here

Using two message instances is fine as is most of your code. There is one major issue though, you don't validate the email, you just check if the $_POST variable was set and is not empty but you don't check if the email format is "name@domain.tld". The simplest thing you could do is:
$email =
    isset($_POST["email"]) && !empty($_POST["email"])
    ? filter_var($email, filter_var($_POST["email"], FILTER_SANITIZE_EMAIL) )
    : "No data";

The filter extension greatly helps you sanitize and validate variables. It's on by default since PHP 5.2, if you are working on an earlier version, you can substitute it with an email validation regular expression. By the way, if you are unfamiliar with the conditional format I'm using, it's called ternary operator and it goes something like this:
$variable =
    ( condition )
    ? ( value if condition is true )
    : ( value if condition is false );

When actually sending the email, you should do:
if( $email != "No Data" && send_email($info) ) {
  header("Location:/thank-you");
} else {
  header("Location:/error");
}

That way and since the check $email != "No Data" is first, send_email($info) will never execute for a missing or invalid email. So the 2 instances of a hefty library will never instantiate needlessly.
Lastly, a very minor change, that might be considered a matter of style. Here:
if ($mailer->send($message) && $mailer->send($message2))
    return true;
else
    return false;

You are returning a boolean value based on the boolean return of $mailer->send($message) && $mailer->send($message2). You can simply rewrite as:
return $mailer->send($message) && $mailer->send($message2);


I think there are many things you could improve, I will try to review your code and give some pointers.

Instead of using React.Component, you should directly access Component:

import React, { Component } from 'react';

class SearchList extends Component {

In older examples, you could find it in the way you do it, but more recent example use this form.

Not sure why you call so many times the setState() method, it is not needed and not a good practice, as every time you call it React will re-render the component.

If you change some data that effects the visualization, you will find out that your component is rendered many times. Of course if you do not change something that impacts the visualization, you won't see, but the engine will run silently, until one day in the far future a small change will turn in such case.

handleOnchange(value) {
  const dataItem = this.state.data
  let searchedListItems = dataItem.filter(dataItem => dataItem.includes(this.state.searchInput));
  var listToRender = [];
  if (searchedListItems) {
    listToRender.push(searchedListItems);
  } else {
    var itemToRemove = this.state.searchedListItems
    listToRender.remove(listToRender, itemToRemove);
  }
  this.setState({
      showDropdown: true,
      searchInput: value,
      searchedList: listToRender
  });
}

About variable names: data is a very bad name for a variable, you should avoid. Believe me, I know as I used so many times and eventually I figured out I shouldn't do.

Maybe you can use allItems instead.

About the method logic.

Array.filter() will always return an array even empty. So your check:

if (searchedListItems) {

is always true, you should:

if (searchedListItems.length > 0) {

About: listToRender.remove(listToRender, itemToRemove)

listToRender should be an empty list, no way there are values inside, according to your code. Anyway I'm sure you never arrive here, because javascript Array does not have the method remove().

I think you can just improve your filter, if you want to remove more items.

this.setState({
    showDropdown: true,
    searchInput: value,
    searchedList: this.state.allItems
      .filter(dataItem =>
          (dataItem.includes(this.state.searchInput) ||
           this.state.searchedListItems.indexOf(dataItem) !== -1))
});

Or you could assign it directly, as you did't change the list before this line, but if you are going to add more logic the concat method should do the stuff. Then just access the array directly.

I don't know where you saw this thing but don't do it:

this.setState( prevState => ({
  cursor: prevState.cursor - 1
}))

You could just simply do:

this.setState({ cursor: this.state.cursor -1 })

Much better.

Another issue with the following method is that you duplicate to much code and use to many time the this.setState().

handleKeyPress(e) {
  const { cursor, searchedList } = this.state;
  const arrowUp = 38;
  const arrowDown = 40;
  const enter = 13;

  if (e.keyCode === arrowUp && cursor > 0) {
    this.setState( prevState => ({
      cursor: prevState.cursor - 1
    }))
  } else if (e.keyCode === arrowDown && cursor < searchedList[0].length - 1) {
    this.setState( prevState => ({
      cursor: prevState.cursor + 1
    }))
  } else if (e.keyCode === enter && cursor >= 0) {
    this.setState({
      searchInput: searchedList[0][this.state.cursor],
      showDropdown: false,
      cursor: 0
     });
  }
}

You don't have to do it:

handleKeyPress(e) {
  const {
      searchedList,
      arrowUp,          // you can move this in your state
      arrowDown,        // or better as module const
      enter             // but not inside the method.
  } = this.state;

  let cursorIncr = 1;
  let newState = {
      cursor: this.state.cursor
  };

  if (e.keyCode === arrowUp && cursor > 0) {
    newState.cursor -= 1;
  } else if (e.keyCode === arrowDown && cursor < searchedList[0].length - 1) {
    newState.cursor += 1;
  } else if (e.keyCode === enter && cursor >= 0) {
    newState.cursor = 0;
    newState["searchInput"] = searchedList[0][this.state.cursor];
    newState["showDropdown"] = false;
  }

  this.setState(newState);
}

And now I jump back a bit for this:

listToRender.push(searchedListItems);

I see you read the data like:

searchedList[0]...

Looks like you never care about more lists inside this array of arrays, and it's ok as you always have one.
So consider to use concat:

listToRender = listToRender.concat(searchedListItems);

Consider to move this method as a stateless component:

renderSearchList() {
  const { cursor } = this.state
  if (this.state.searchedList[0]) {
    const searchList = this.state.searchedList[0].map((data, index) =>  {          return (
          <SearchListItem
            key={index}
            id={index}
            handleClickedItem={this.handleClickedItem.bind(null, data)}
            isActive={cursor === index ? 'active dropdown-li' : 'dropdown-li'}
            data={data} />
        );
      });
    return (

          {searchList}

    );
  }
}

Like this:

const SearchListItems = ({handleClick, cursor, items}) => {
    const searchItems = items.map((item, index) => (<SearchListItem
                key={index}
                id={index}
                handleClickedItem={handleClick}
                isActive={cursor == index ? 'active dropdown-li' : 'dropdown-li'}
                data={item}/>));

    return (
{searchItems}
)
}

Just a function and it reads the props from the input parameter, using the spread operator of ecmascript-6.

You could have this stateless component in the same file, or place in another, as it is convenient for your use case.

Maybe you could have a better names.

Then change your render to use the new component:

render() {
   return (

    <form onSubmit={this.submitForm} >
      <input
        className="input"
        type="text"
        value={this.state.searchInput}
        onChange={event => this.handleOnchange(event.target.value)}
        onKeyDown={this.handleKeyPress} />
    </form>
    { this.state.showDropdown &&
           <SearchListItems
            handleClick={this.handleClickedItem.bind(null, data)}
            cursor={this.state.cursor}
            items={this.state.searchedList[0]}/>}

)
}


This solution is inefficient:

There is no point counting the characters in the entire string: once you found a duplicate, you can stop counting, because you know the result is false

This also implies that the map of counts is wasted space

Iterating over the alphabet to check character counts is inefficient: it would be better to iterate over the map values

Instead of a map, it would be more efficient to use a set.

Instead of a set, you could also consider a boolean array of the size of the alphabet, values initialized to false,
and use that to track characters seen so far.
The disadvantage of this approach over a set is that it might use more space.

You are also violating some good practices:

using namespace std is considered bad practice
readString is poorly named: it doesn't "read a string", it initializes a map of character counts to all zero values
No need to pass stringLength together with testString. You can derive that value from testString


Your code is actually "off-topic" because it doesn't work.  You should really
include a short main that illustrates its use and allows it to be tested.  All the same, here are some comments.

Be consistent with spacing.  My preference is for no spaces around -> and
for a space after keywords (if, while etc).

Variable naming.  Your names are not to my taste, often too long:

Rename previous as prev, current_elements as n_elements
Rename this globally as list - this means nothing whereas list is
clearly a list.
Rename item as data.  It is called data within the node structure so
why not be consistent?
new_listset would perhaps be more consistent with the other functions if
named listset_new.  It also needs a void parameter list.

Function listset_lookup tests the wrong condition in the loop.  Better to
test for the end of the list:

struct node *listset_lookup(const struct listset *list, int data)
{
    struct node *n = list->head;
    while (n) {
        if (data == n->data) {
            break;
        }
        n = n->next;
    }
    return n;
}

Notice also that the parameter list is const (as you don't alter it).  Also
note that writing this with a short variable name makes it much more readable
compared to the dense text that results from a longer name.  In a ten line
function with only 3 variables there is really nothing wrong (and a lot right)
with using such a short name.

Your listset_add is missing two terms in the else clause and should test
for malloc failure (and return something to show whether it failed).  I
would also rename new_node as simple n - again, it is a short function (as
most should be) and so this is ok.

static struct node* listset_add(struct listset *list, int data)
{
    struct node *n = malloc(sizeof(struct node));
    if (n) {
        n->data = data;
        n->next = NULL;
        if (!list->head) {
            n->prev = NULL;
            list->head = list->tail = n;
        } else {
            n->prev = list->tail; // new
            list->tail->next = n;
            list->tail = n;       // new
        }
        list->n_elements++;
    }
    return n;
}

Your listset_remove is hard to read and wrong.  Again, a shorter variable
name would help.  You should also avoid long lines such as:

if(elem_remove->next && elem_remove->previous) elem_remove->previous->next = elem_remove->next;

This is much clearer as:

if (n->next && n->previous) {
    n->previous->next = n->next;
}

All the same, it is perhaps wrong.  And this:

else if (elem_remove->previous && !elem_remove->previous){

is quite clearly not sensible.  You also don't decrement the element count.
The correct function is:

static void listset_remove(struct listset *list, int data)
{
    struct node *n = listset_lookup(list, data);
    if (!n) return;

    if (n->prev) {
        n->prev->next = n->next;
    } else {
        list->head = n->next;
    }
    if (n->next) {
        n->next->prev = n->prev;
    } else {
        list->tail = n->prev;
    }
    list->n_elements--;
    free(n);
}

Here's what I used to test it:

static void listset_print(const struct listset *list)
{
    struct node *n = list->head;
    while (n) {
        printf("%d ", n->data);
        n = n->next;
    }
    printf(" : ");

    n = list->tail;
    while (n) {
        printf("%d ", n->data);
        n = n->previous;
    }
    printf("\n");
}

int main(void)
{
    struct listset *list = new_listset();
    listset_add(list, 1);
    listset_add(list, 2);
    listset_add(list, 3);
    listset_add(list, 4);
    listset_add(list, 5);
    listset_print(list);
    listset_remove(list, 6);
    listset_print(list);
    listset_remove(list, 1);
    listset_print(list);
    listset_remove(list, 5);
    listset_print(list);
    listset_remove(list, 3);
    listset_print(list);
    listset_remove(list, 2);
    listset_print(list);
    listset_remove(list, 4);
    listset_print(list);
    return 0;
}


Script to monitor a folder and compress the content

Slightly different than @kojiro's answer, using find for everything:

find /path \
     -type f \
     ! -iname "*.zip" \
     ! -exec /usr/sbin/lsof -n "{}" \; \
     ! -exec test -f "{}.zip" \; \
     -exec zip -q "{}.zip" "{}" \; \
     -exec rm "{}" \;

(last step only if the removal of the original is required).


Creating a pure Ruby object (PORO) to email files in a Rails application

Good job on

Tightly focused methods that do what their name says
Non-surprising formatting
Testable design

This is pretty good code

Environment variable

There's a few things that bother me about this class's use of the S3_BUCKET environment variable.

It makes unit test awkward, as the test must either set the environment variable and then restore it, or it must stub ENV#[], either of which is a minor pain.
It hard-codes the environment variable name

My first thought was to have the class take the bucket name as an argument with a default:

def initialize(files, params, bucket_name = ENV['S3_BUCKET'])

But I think that is a half measure.  Instead, let's just pass in the bucket:

def initialize(files, params, bucket)

bucket is an instance of this class, which does a lazy fetch of the AWS::S3 bucket:

require 'forwardable'
require 'memoist'

class Bucket

  extend Forwardable

  def initialize(bucket_name = ENV['S3_BUCKET'])
    @client = AWS::S3.new
    @bucket_name = bucket_name
  end

  def_delegator :bucket, :objects

  private

  def bucket
    @client.buckets[@bucket_name]
  end
  memoize :bucket

end

The memoist gem Is a fancy version of "@bucket ||= ...".
Forwardable#def_delegator delegates the #object method to the result of the #bucket method.

The use of the Bucket class has these advantages:

FileSharingService:

no longer has to know about the environment variable.
does not have to concern itself with lazy-initialization and caching.
can now be easily tested in isolation--just give it a test double for its bucket instance.

Bucket can be easily tested in isolation.

Checking email addresses

I would consider taking the regular expression in this expression:

email !~ /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

And, at a minimum, give it a constant.  The goal is to make the code more self-documenting:

WELL_FORMED_EMAIL_ADDRESS = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
...
email !~ WELL_FORMED_EMAIL_ADDRESS

I might go one step farther and move the entire check into another class.  Make it someone else's responsibility to know what's a good email address and what's not:

EmailAddress.well_formed?(email)

params

The only use the class makes of params is of @params[:emails].  If that is unlikely to change in the future, I would consider just passing in the email addresses, and not concerning this class with params at all.

def initialize(files, email_addresses, ...)


Deck of cards program using a card value map

I haven't followed your previous reviews, so a few of these may be things that have already been pointed out.

Anyway, here's my go at it.

The Card:: is invalid on the following:

Card::Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}
Card::Card() : value(0), rank(' '), suit(' ') {}

The suit should likely be an enum (in particular, a strongly typed one as you're using C++11).

The comparators in Card are non-sensical. Why do you sometimes compare value and sometimes compare suit? How are a Jack of Spades and a 2 of Spades equal just because they're both a Spade?

For maintainability, try to define comparators in terms of each other: bool operator!=(const Card &rhs) const {return !(suit == rhs.suit);} and so on.

Don't use bare unsigned. Use unsigned int.

(Personal preference really on this one)

Even better yet, define the types as public typedefs. Like Deck::size_type, Card:suit_type and so on (standard library-esque).

Why make the maximum size be 52?

You could either have the size be templated and default to 52, or you could have it be a constructor parameter (in which case you'd have to use a vector rather than std::array).

Is the mapping in retrieveMap ever meant to be used by consuming code? If not, make it static in Deck.cpp.

Card::deal has no business outputting anything. If dealing can't be done, throw an exception.

Rather than having to think in reverse iteration, you could think of the top of the deck as being 0. This would likely simplify a lot of the logic.

Are you happy being stuck with a 52 card deck? What if you don't want Jokers? What if you want some completely different kind of card system? A

Basically what I'm saying is that a deck shouldn't be responsible for filling itself up with cards.

In fact, constructing objects in a construct tends to be an anti-pattern: http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/. Note that "new" in this context is talking about Java, not C++. Though the terminology is Java centric, what it actually means is is construction in general. Constructing objects in a construct tends to imply that the objects should be provided to the constructor rather than be created in there.

Rather than having the deck populate itself with a traditional set of cards, have a utility method:

Deck classDeck = Deck::makeClassicDeck();

This lets you have the convenience that you currently have, but it doesn't hold you to a certain set of cards (you could also go the two constructors route).

Why are you trying to hide the Card class? You should probably trust your consuming code to handle cards. How do you know that the code isn't going to be used for some very odd game that involves a deck composed of a normal deck and 6 extra jokers? If you let the consumer of Deck decide what to put it in, it's a lot more flexible.

As a person about to make a program that involves card game logic, why should I use your Deck class? What does it offer me over using a simple std::deqeue (or std::stack or std::vector) of Card? The way I see it at the moment, it offers basically nothing over a vector. It just has a more convenient shuffle.

MAX_SIZE should be a std::size_t

empty should return a bool

size should return a std::size_t

I'm not sure if I'd bother defining an ostream<<. Might be more useful to let each application determine how it wants to print a deck rather than tie it to one format.

I'd go with a more idiomatic shuffling approach:

std::random_shuffle(cards.begin(), cards.end());

I don't like SUITS. Why is it the only all caps variable?

I don't like aDeck and aCard. A const Deck& is obviously a Deck. Just call it deck or something. Names beginning with an article seem odd (imagine if Deck::cards were instead theCards).

Since it's private, it's not as important, but Card::Card(unsigned v, char r, char s) should still have proper names for the parameters.

Crazy paranoid moment: deal() is not exception safe (well, technically it is since Card::Card never throws, but there's no hard gaurantee of that in place).

You could theoretically encounter an exception in the card constructor which would mean the card would properly be removed from the deck, but the consuming code would not be able to have it.

Then again, this is complete paranoia, especially since Card's constructor never throws for the time being.

(Just happened to think of it since the oddity of std::stack's pop() returning void has always been an interesting little necessity to me.)


Queue with O(1) enqueue and dequeue with JS arrays

Review
I find your indentations and line breaks rather difficult to read.

Object.defineProperty(this,"head",{ value   : 0
                                  , writable: true
                                  });

I would suggest you use the idiomatic style.
After { move to the next line and indent once. Place the comma at the end of lines and spaces after commas if not at end of line
Object.defineProperty(this, "head", {
    value: 0,
    writable: true
});

or if the line is short
Object.defineProperty(this, "head", {value: 0, writable: true});

or
Object.defineProperty(
    this,
    "head", {
        value: 0,
        writable: true
    }
);

Same again with the ternary.

return this.head < this.length ? ( first = this[this.head]
                                 , delete this[this.head++]
                                 , first
                                 )
                               : void 0;

Why use the operator void that requires the additional expression 0 when you can just express undefined.
I understand the reasoning for breaking up the group, but the indent is way to great. The idiomatic style is far more readable.
return this.head < this.length ? (
        first = this[this.head],
        delete this[this.head++],
        first
    ) :
    undefined;

or
return this.head < this.length ?
    (first = this[this.head], delete this[this.head++], first) :
    undefined;

Unsafe encapsulation
Extending the Array with the behaviors enqueue and dequeue is just asking for bugs as any of the existing functions can damage state.
Rules of code: "If it is there it will be used."
Good code enforces the rules by not exposing properties and behaviors that can damage state.
Even just the basic use of Queue is un-trusted because you expose head.
JS Queue
Complexity and performance are two side of the same coin. Though linked they are vastly difference. With shift at \$O(1)\$ its performance is still 10 times slower than pop
However you use delete to remove items. Again it is \$O(1)\$ but it is even slower than shift.
Linked list
I have found that a simple linked list is the most effective and performant solution for a queue in JS
Implementing it as a factory function allows closure to hold its state safely isolated from the code using the queue.
function Queue() {
    var head, tail;
    return Object.freeze({
        enqueue(value) {
            const link = {value, next: undefined};
            tail = head ? tail.next = link : head = link;
        },
        dequeue() {
            if (head) {
                const value = head.value;
                head = head.next;
                return value;
            }
        },
        peek() { return head?.value }
    });
}

This style offers robust encapsulation, maintains the ideal \$O(1)\$ for enqueue and dequeue without sacrificing performance.
Test
The test compares the execution time of your Queue against a linked list version of a queue.
There are two test cycles, First for 1000 items, then when done click the button for 500,000 items.
I Have made minor changes to your code to favor performance. Not using define property and not returning the array in enqueue.

var size = 1000;
const COOL = 200;

class Queue extends Array {
  constructor(){
    super();
    this.head = 0;
  }
  enqueue(x) { this.push(x) }
  dequeue() {
    var first;
    return this.head < this.length ?
        (first = this[this.head] , delete this[this.head++] , first) :
        void 0;
  }
  peek() { return this[this.head] }
}

function QueueLinked() {
    var head, tail;
    return Object.freeze({
        enqueue(value) {
            const link = {value, next: undefined};
            tail = head ? tail.next = link : head = link;
        },
        dequeue() {
            if (head) {
                const value = head.value;
                head = head.next;
                return value;
            }
        },
        peek() { return head?.value }
    });
}

function fillQueue(queue, count = size) {
    while (count--) { queue.enqueue(count) }
    return queue;
}
function testOPQueue() {
    const q = fillQueue(new Queue());
    var ii = 0, val = 0;
    do {
        ii += val;
        val = q.dequeue();
    } while (val !== undefined);
    return ii;
}
function testLinkedQueue() {
    const q = fillQueue(QueueLinked());
    var ii = 0, val = 0;
    do {
        ii += val;
        val = q.dequeue();
    } while (val !== undefined);
    return ii;
}

if (testOPQueue() !== testLinkedQueue()) { throw new Error("Test results differ") }

const funcTest = (name, call, bias = 1) => ({name, call, time: 0, cycles: 0, bias});

timeFunctions(50, 500, "1000 items:",
    funcTest("Array Queue", testOPQueue),
    funcTest("Linked Queue", testLinkedQueue),
).then(() => {
    test2.classList.remove("hide");
    test2.addEventListener("click", () => {
        test2.classList.add("hide");
        size = 500000;
        timeFunctions(50, 3, "500,000 items:",
            funcTest("Array Queue", testOPQueue),
            funcTest("Linked Queue", testLinkedQueue),
        );
    });
});

function timeFunctions(testCount, cycles, name, ...functions) {
    return new Promise(done => {
        const testGroup = () => {
            var i;
            for (const func of functions) {
                i = cycles;
                const now = performance.now();
                while (i--) { func.call() }
                func.time += performance.now() - now;
                func.cycles += cycles;
            }
        }
        const test = () => {
            testGroup();
            console.clear();
            console.log(name + " " + (testCount - count + 1) + " of " + testCount);
            for (const func of functions) {
                console.log(
                    func.name.padEnd(maxNameLen + 2,".") + ": " +
                    (((func.time / func.cycles) / func.bias).toFixed(3) + "ms").padStart(9," ") +
                    (" Total: " + func.time.toFixed(3) + "ms")
                );
            }
            if (--count) { setTimeout(test, COOL) }
            else { done() }
        }
        var count = testCount;
        var maxNameLen = 0
        for (const func of functions) {
            func.time = 0;
            func.cycles = 0;
            maxNameLen = Math.max(maxNameLen, func.name.length);
        }
        setTimeout(test, COOL);
    });
}
.hide { display: none }
<button id="test2" class="hide">Test 500000 items</button>


There's probably much more to say about this code, but there's one point that deserves immediate and serious attention: You're handling errors the way vba and vb6 did it... but this code can only be vb.net:

Handles tsbEditNeighbour.Click

In the .NET world, you throw away all this On Error GoTo Madness, and work with Exceptions instead.

Exceptions are a much more robust way of handling errors, and give you much more information than just an error number and description (including the whole stack trace, and the exact code file and line number that threw the exception): see System.Exception on MSDN.

The basic idea is that you try some code, and catch to handle any exceptions thrown:

Try
    'some code
Catch ex As Exception
    'error-handling
End Try

See Try-Catch-Finally statements on MSDN for the full syntax.

I'll get back to this post later, to review other points.


Find property and value pairs between two objects

As @Pimgd explained, it's not good to recreate an anonymous function in every iteration of a loop. Move the function outside of the loop:

function where(collection, source) {
  var arr = [];
  var keys = Object.keys(source);

  function match(x) {
    return x in collection[i] && source[x] == collection[i][x];
  }

  for (var i = 0; i < collection.length; i++) {
     if (keys.every(match)) {
       arr.push(collection[i]);
     }
  }

  return arr;
}

I suggest to go one step further.
Instead of creating an array and appending to it,
you can benefit from the Array.prototype.filter method:

function where(collection, search) {
  function filter(item) {
    function matchSearchValue(key) {
      return key in item && search[key] == item[key];
    }
    return Object.keys(search).every(matchSearchValue);
  }
  return collection.filter(filter);
}

Finally, notice how I renamed everything to better explain their purpose.


Implementation of static_for to iterate over elements of std::tuple using C++17 features

IMHO, I think this is indeed pretty ugly. Assuming you just want to iterate over all of the elements of tuple (which is what you've done here), you can simplify this both in implementation and in usage:

template <class Tup, class Func, std::size_t ...Is>
constexpr void static_for_impl(Tup&& t, Func &&f, std::index_sequence<Is...> )
{
    ( f(std::integral_constant<std::size_t, Is>{}, std::get<Is>(t)),... );
}

template <class ... T, class Func >
constexpr void static_for(std::tuple<T...>&t, Func &&f)
{
    static_for_impl(t, std::forward<Func>(f), std::make_index_sequence<sizeof...(T)>{});
}

int main()
{
    auto t = std::make_tuple( 1, 22, 3, 4 );

    std::size_t weighted = 0;
    static_for(t, [&] (auto i, auto w) { weighted += (i+1) * w; });

    std::cout << "Weighted: " << weighted << std::endl;

    return 0;
}

This is more like for_each, or maybe for_each + enumerate from python. On the implementation side, you no longer need this wrapper stuff. On the usage side, the lambda just directly gets passed the index and the the element, so it doesn't need to extract it from the tuple. Note that I pass the integer by "type" so that you can do crazy things with it but for most purposes it would probably just be simpler to pass an actual size_t as the first argument. Though integral_constant does implicitly convert anyhow.

If you wanted to iterate over multiple tuples or something like that (very rare), you could take my approach and modify it so that the lambda only gets passed the first argument, and then captures the tuple and uses std::get<i> to index into it. But you still don't need the wrapper struct or w.n.


That's not a toggle

Toggle has a very specific meaning and comes with the benefit of not having to supply the new state when called. Your function is not a toggle and should be called something along the lines of  setFormDisableState(formElements, disable = true) or setFormState(formElements, disable)

Argument order

If not using a default parameter use the right to left assignment rule when defining argument order. Eg assignment is right to left for a = b. Your function is assigning a state to elements in the object elArr, the elArr should be to the left of the toggle.

Danger! implied type

elArr is not an array. That is most defiantly a bad name as it implies the incorrect type.

The shortest form.

For all attributes defined in the DOM set the values directly. You only use the attribute functions for attributes not defined by the DOM. Using the longer version to do anything in code adds unneeded noise.

Keep the source DRY

Don't Repeat Yourself (code). The field iterators elArr.fields.forEach are almost identical, with only the state changing.

You have two if statements. You don't need to do the second test. If not disabling then must be enabling.

Alternatives
function toggleFormState(formDesc) { // Desc is short for description
  const newState = ! formDesc.btn.disabled;
  formDesc.btn.innerHTML = newState ? '' : "Submit";
  formDesc.btn.disabled = newState;
  for (const element of formDesc.fields) { element.disabled = newState }
}

Or
function setFormState(formDesc, disable) {
  formDesc.btn.innerHTML = disable ? '' : "Submit";
  formDesc.btn.disabled = disable;
  for (const element of formDesc.fields) { element.disabled = disable }
}


Object-Orientated

your code is very procedural (honestly, it's just one long main methode) not very object-orientated... seperate your code into seperate concern(Segregation of concerns), at least a kind of DistanceParser class and a ErrorHandler class. Doing this make your ready open for the open-closed principal

DistanceParser fileParser = DistanceParser.fileInstance(inputFile);   //applying dependecy injection
fileParser.setErrorHandler(new FileErrorHandler(logFile));
fileParser.parse();

if you would apply that logic you were able to create easily any other parser (maybe DistanceParser.inputStreamInstance(inputStream) ), you could easily replace your FileErrorHandler with any other ErrorHandler and you were able to test your functionality with a proper unit test

@Test
DistanceParser fileParser = DistanceParser.fileInstance(invalidInput);
ErrorHandler errorHandlerMock = mock(ErrorHandler.class);
fileParser.setErrorHandler(errorHandlerMock );
fileParser.parse(); //errors during execution are handled by the errorHandler (handleError())
verify(errorHandlerMock , atLeastOnce()).handleError();

You know you could implement interfaces on your Parser class and your Errorhandler class, so you can apply Liskovs Substitution Principal ...

Tell, don't ask

another minor issue is naming of your methods, i'm still wondering about your testDoubleLow() methode. if you would use proper names your code would be far more readable.

misleading naming here:

testDouble(String s) should be named into isDouble(String doubleAsString)
testDoubleLow(String token, double l) should be named into isBiggerThan(String doubleAsString, double minimalValue)


You should use more descriptive names than f, o, u and rf. It makes your code harder to read, even if it's all quite small and contained.

def unrar():
    for rar in os.listdir(dpath):
        filepath = os.path.join(dpath, rar)
        opened_rar = rarfile.RarFile(filepath)
        for f in opened_rar.infolist():
            print (f.filename, f.file_size)
        opened_rar.extractall(xpath)

Note that I still use f for the files you iterate over in the opened_rar, because single letter variables are occasionally ok. Especially in limited contexts, where they're commonly used (f will often refer to a file when iterating). But using multiple ones together can easily be confusing and less readable.

Your function should also take xpath and dpath as parameters, rather than using constants. This makes it easier to reuse the function and have it run on different files or in different places, rather than having to manually change the constant values. It's also easy to change:

def unrar(dpath, xpath):

And then just call it with:

unrar(dpath, xpath)

Also Python has a great tool called context managers. These will basically ensure that your file is always closed no matter what happens. Every time you open a file with Python it needs to be closed again. And you actually never closed yours, so it's better practice to use a context manager, like this:

def unrar(dpath, xpath):
    for rar in os.listdir(dpath):
        filepath = os.path.join(dpath, rar)
        with rarfile.RarFile(filepath) as opened_rar:
            for f in opened_rar.infolist():
                print (f.filename, f.file_size)
            opened_rar.extractall(xpath)

Everything inside the with block is now what happens with the opened_rar file. Once you exit that block, the file is always closed. Crucially, this holds true even if an error causes your script to end prematurely. I haven't worked with rar files, but I can tell you that when using zip files you can lose your data by having errors interrupt your script. A context manager prevents this data loss, making it safer.