Determine which sentences contain the set of phrases

Your code is fairly readable, but I find it quite dense. Here are some general things you could do to improve it:

Use vertical white space to separate different areas of the code.
Provide a docblock at the top outlining the algorithm you are using.
Use more than one function to break your code into smaller chunks.

With that advice out of the way, let's look at your performance with an eye to the worst possible case:

def textQueries(sentences, queries):
    for query in queries:             # Worst case: 10,000 times
        ...
        for query_word in query_words:  # Worst case: 10 times
            if query_word in word_map:
                    final_set.intersection  # Worst case: O(10,000) in C
            else:
                for ... in enumerate(sentences):  # Worst case: 10,000 times
                if ... else:
                    final_set.intersection  # Worst case: O(10,000) in C

According to me, your code runs worst case in \$O(Q \times W \times S)\$ where \$Q\$ is the number of queries, \$W\$ is the number of words in the query, and \$S\$ is the number of sentences. (The number of words in the sentences is hidden behind a split, but it's in C so we'll let it go by.)

There's no question you need to split the sentences and split the queries into separate words, somehow. But you are nesting your loops when the "best" way to loop is to do them one after the other. If you can convert from this:

for q in Q:
    for s in Q:
        pass

to something like this:

for s in S:
    pass

for q in Q:
    pass

You will have converted from \$O(S \times Q)\$ to \$O(S + Q)\$ which is considerably faster.

Your current approach is to define a set of sentences that contain a particular word. You cache these sets, in case the same words appear again. You intersect the sets for each word in the query, producing a final set of all the sentences that contain all the query words.

This is pretty much guaranteed to fail based on the instructions you quoted:

  No word appears in more than 10 sentences.

In other words, the probability of a "cache hit" is 10/10,000, or 0.1%. Any time you spend maintaining the cache is wasted time.

Suppose you just go through the sentences one time, and build the big dictionary of sets:

sentence_words = collections.defaultdict(set)
for i, s in enumerate(sentences):
    for w in s.split():
        sentence_words[s].add(i)

Then you can go through the query words and do what you were doing before, without any caching:

for q in queries:
    matches = functools.reduce(operator.and_, (sentence_words[w] for w in q.split()))
    matches = [-1] if not matches else sorted(matches)

This will seem very similar to what you were doing, but the difference is that these two loops are run one after the other, providing something like \$O(100,000 + 100,000)\$ performance instead of \$O(100,000 \times 10,000)\$. It's that last operator that makes all the difference.


Building multiple parts of formula strings from different inputs in R

1
The function is a bit lengthy indeed. I have some general remarks, but I will hold them off, because I have some suggestions that would fix points 2 and 3.
2
The source of the error is because u + z is not interpreted as a formula, but rather as the addition of two variables. So when you interact with Arg2, an error is thrown. Adding the ~ fixes this, because it is recognized as a formula then.
A workaround for this problem is to combine both parts of the formula into one. This is something other packages in R do as well. (mlogit::mFormula is one example from the top of my head) The combined formula would look like so: y ~ x | u + z. You can then split the RHS at the | and do your work on each part of the formula.
3
Catching the problem is really quite hard, because any interaction with Arg2 will trigger the evaluation of u+z, which in turn throws an error if u or z don't exist.
What you can do is use tryCatch. This function allows you to evaluate an expression and define a function that is executed if an error or warning is thrown.
> tryCatch(is.formula(1+1), error = function(e)stop("bla"))
[1] FALSE
> tryCatch(is.formula(u + z), error = function(e)stop("bla"))
 Error in value[[3L]](cond) : bla
> tryCatch(is.formula(~u + z), error = function(e)stop("bla"))
[1] TRUE

You could add this to the top of your function:
if(!tryCatch(is.formula(1+1),
    error = function(e)FALSE))){
    stop("Arg2 is not a formula, be sure to add \"~\" to the start.")
}

Back to 1
String operations will quickly look very wordy, but that's all fine. You are working with words after all.
You spend 4 lines dissecting the formula for the LHS and the RHS. This can be done a lot more easily by coercing the formula to a string:
> as.character(a+b~c+d)
[1] "~"     "a + b" "c + d"

Before you do coercion, you should test whether the thing you are coercing is actually what you expect it to be. So add a test to the top of the function:
stopifnot(is.formula(Arg1))

We still should separate removing the intercept from the rest of the formula. Because we don't want to see L(diff(-1,-k:k)). So we test whether -1 is in the RHS, remove it if it is and at the end, add it back if necessary:
  removeIntercept <- grepl("-1", RHS)
  if(removeIntercept){
    splitRHS[[1]] <- splitRHS[[1]][!grepl("-1", splitRHS[[1]])]
  }

Putting it back:
  if(removeIntercept){
    ff_RHS <- paste("-1 +", ff_RHS)
  }

If we run with the suggestion in part 2, about combining the formulae, we can drop Arg2. We then split the RHS on |. Because we coerced the formula to character, we can do this with strsplit. We then want to split the formula for each of the terms. Again with strsplit.
The argument data is not used, so we can omit it.
Right now we are returning a string, as per the function in OP, but the function is called buildFormula, so it would be nice to wrap the output in as.formula, so that the name fits the output (or you can rename the function).
The new function would be:
buildFormula <- function(formula){
  stopifnot(is.formula(formula))

  ffAsChar <- as.character(formula)
  LHS <- ffAsChar[2]
  RHS <- strsplit(ffAsChar[3], "[|]")[[1]]

  splitRHS <- strsplit(RHS, "[+]")
  removeIntercept <- grepl("-1", RHS[1])
  if(removeIntercept){
    splitRHS[[1]] <- splitRHS[[1]][!grepl("-1", splitRHS[[1]])]
  }

  ff_RHS <- paste(splitRHS[[1]],
                  paste0("L(diff(",
                         splitRHS[[1]],
                         "),-k:k)"),
                  collapse = " + ",
                  sep = " + ")
  if(length(splitRHS) > 1){
    ff_RHS <- paste0(ff_RHS, "+",
                     paste("L(", splitRHS[[2]], ",1:k)",
                           collapse = " + "))
  }
  if(removeIntercept){
    ff_RHS <- paste("-1 +", ff_RHS)
  }
  paste(LHS, "~", ff_RHS)
}

This will produce the following output:
> buildFormula(Arg1 = y ~ x, data = dat)
[1] "a ~ x + L(diff(x),-k:k)"
>
> buildFormula(Arg1 = y ~ x + u + z, data = dat)
[1] "a ~ x  + L(diff(x ),-k:k) +  u  + L(diff( u ),-k:k) +  z + L(diff( z),-k:k)"
>
> buildFormula(Arg1 = y ~ x | u, data = dat)
[1] "a ~ x  + L(diff(x ),-k:k)+L(  u ,1:k)"
>
> buildFormula(Arg1 = y ~ x | u + z, data = dat)
[1] "a ~ x  + L(diff(x ),-k:k)+L(  u  ,1:k) + L(  z ,1:k)"


import Data.Char (chr, isPunctuation, isSymbol, ord)

decUpper = 127 --Upperbound of normal characters
decLower = 32 --Lowerbound of normal characters
decRange = decUpper - decLower --Total range

type Message = String

-- | Checks if the char is in range
isInRange :: Char -> Bool
isInRange char = ichar <= decUpper && ichar >= decLower
    where ichar = ord char

-- Test if all chars in the Message are in range
isPossible :: Message -> Bool
isPossible = all isInRange

-- Turn a list into a list of pairs
mkPairs :: [a] -> [(a,a)]
mkPairs xs = zip xs (tail xs)

-- no consecutive symbols in Message
isProbable :: Message -> Bool
isProbable = not . any (\(x,y) -> isSym x && isSym y) . mkPairs
  where isSym c = isSymbol c || isPunctuation c

-- Shifts all characters by n
decShift :: Message -> Int -> Message
decShift []     _  = []
decShift (x:xs) n
    | iNewChar > 0 = chr iNewChar : decShift xs n
    | otherwise    = x : decShift xs n
  where iNewChar = ord x + n

-- Returns a list of tuples of the offset used, and the shifted Message
getCombos :: Message -> [(Int,Message)]
getCombos m = [(off,decShift m off) | off <- [negate decRange .. decRange]]

-- Returns a list of tuples of possible decryptions (KeyUsed,Message)
simpDec :: Message -> [(Int, Message)]
simpDec = filter ((\x -> isPossible x && isProbable x) . snd) . getCombos

Changes:

used more function composition
simpDec is really a filter on results. getCombos generates data so a list comprehension makes sense.
simplify isProbable with the definition of mkPairs
simplify isPossible using the all function.
added import line


At a quick glance there doesn't appear to be any memory leaks:

valgrind ./mem_leak_test
==3914== Memcheck, a memory error detector
==3914== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==3914== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==3914== Command: ./mem_leak
==3914==
******* original image ******
0,1,2,3,4,
5,6,7,8,9,
10,11,12,13,14,
15,16,17,18,19,
20,21,22,23,24,
******* rotated image ******
20,15,10,5,0,
21,16,11,6,1,
22,17,12,7,2,
23,18,13,8,3,
24,19,14,9,4,
==3914==
==3914== HEAP SUMMARY:
==3914==     in use at exit: 0 bytes in 0 blocks
==3914==   total heap usage: 12 allocs, 12 frees, 296 bytes allocated
==3914==
==3914== All heap blocks were freed -- no leaks are possible
==3914==
==3914== For counts of detected and suppressed errors, rerun with: -v
==3914== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

Valgrind appears to agree about the lack of memory leaks.

I would just use std::array instead of code such as unique_ptr<int[]> temp(new int[SIZE]);. You get the benefits of automatic memory cleanup at the end of the variables scope from std::array without as much complexity. The main reason I would go for std::array is because you appear to be mostly concerned with memory management and not ownership. However if your intent here is to clearly have single ownership then unique_ptr is a good choice.

std::array will reduce complexity because it contains information about its dimensions. This would completely remove the need for the initializer list for initializing the array. Unless you are going to do something more fancy with it, the initializer list is an overly complex way to iterate over all the indexes of an array.

Assuming we changed this to use std::array the other thing I would do differently is to return the rotated image from rotateImage as opposed to modifying a reference parameter. Fewer side effects tends to keep your code more conceptually simple.


I'm assuming in real production the values aren't hard coded and will be passed in.  Then you will want to make some guard clauses.  What is the array is empty or value of one?

You also have more variables than you need, which isn't so bad just still if you know the start and the length of the run you don't need end position.  You can also move startofrun inside the loop.  Also better naming of variable would help.

You don't need to do math.abs when dealing with ints. Just add one and see if the next one is the same value.

Also while it's legal in C# to increase the for loop counter it's not intuitive to someone coming after you.  I would recommend both of them being while loops since the control variable is changing in the loop

For a reference a method like this.  I took out the printing as that's not what this method is intended for

static IEnumerable<int> LongestStreak(params int[] values)
{
    // guard clauses
    if (values == null)
    {
        return Enumerable.Empty<int>();
    }

    // If zero or one then return it right away
    if (values.Length <= 1)
    {
        return values;
    }

    int currentPosition = 0;
    int currentLongestRun = 0;
    int startOfLongestRun = 0;
    while (currentPosition < values.Length - 2)
    {
        int startOfRun = currentPosition;
        while (currentPosition < values.Length - 1 &&
               values[currentPosition] + 1 == values[currentPosition + 1])
        {
            currentPosition++;
        }

        if (currentPosition - startOfRun > currentLongestRun)
        {
            startOfLongestRun = startOfRun;
            currentLongestRun = currentPosition - startOfRun;
        }
        // move to check next sequence
        currentPosition++;
    }

    // C# zero based array so need to add one to the streak
    int[] result = new int[currentLongestRun + 1];
    Array.Copy(values, startOfLongestRun, result, 0, currentLongestRun + 1);
    return result;

}


Searching and sorting ranges in excel with toggle buttons

Some basic things. You need your code to be indented consistently. That way you can see the levels of your code. If you had that you would see that on the last line of SorterenOpdrachten is a Next without a For. This won't compile.

In Tegels you have missed your first End If. And the second End If. And your third, fourth and fifth.

You haven't defined tglopel or TglChevrolet


looking for review of code organization for jQuery/javascript code

In JavaScript, there is no sure-fire way to organize framework code. As proof, just take a look at the different frameworks that reside on GitHub. You will see that every developer has his/her own way of organizing code.

Here's what I can recommend in your case:

I see that in your code, you seem to be namespacing your utility functions into deep structures. What I can suggest is to have a built-in function that extends your top app namespace instead of having to manually type in, check it that level exists and create. Have that extend function nest and check it for you.

Also, with extending, it would be great if the extended functions have some access to some inner objects as well

(function(app,$){

    //some stuff you want seen by extensions
    var extensionExtras = {
       cache : {}
    }

    //an extend function that checks, nests and creates namespaces
    function extend(nesting,fname,handler){
        //split nesting order
        //recursively check for the namespace
            //if it does not exist, create an object for it
            //else, go through it
        //attach function with name
        //overwriting is up to you
        deepNamespaceReference[fname] = function(){
            handler.call(this,extensionExtras);
        }
    }

    extend('app.from.inside.module','extendedInside',function(){
        //functionality here
    });

    //expose extend
    app.extend = extend;

})(window.app = window.app || {},jQuery);

//extend from the outside:
app.extend('app.some.deep.namespace','fromOutside',function(){
    //functionality here
});

//and then we can use:
app.from.inside.module.extendedInside();
app.some.deep.namespace.fromOutside();

However...

Namespacing technique in JavaScript actually uses objects and properties that contain objects. Deeply nested object structures in JavaScript incur a very minor performance drawback but a drawback still. I suggest you keep your namespace levels a minimum to avoid the performance penalties.


Generate random records for table in SQL

Randomness
Using NEWID() seems like a pretty smart way of getting random records, and it is. There is however a better function for this purpose. Say hello to the CRYPT_GEN_RANDOM() function.
The CRYPT_GEN_RANDOM() has a parameter that we need to provide, the length of the random string it is going to generate. For what we need, 4 or 5 characters is plenty.
I will update my answer with the proof when I find the time, but my own testing found CRYPT_GEN_RANDOM() generates less predictable records than NEWID().
The Random Stored Procedure
I have no idea what your Random stored procedure entails, but might I suggest an alternate method of generating a random number...
WITH Numbers(I) AS
(
    SELECT 1000

    UNION ALL

    SELECT I+1
    FROM Numbers
    WHERE I<5000
)

SELECT TOP 1 @amount = I
FROM Numbers
ORDER BY CRYPT_GEN_RANDOM(4)
OPTION (MAXRECURSION 0)

First, this generates a table of numbers 1000 to 5000 using a recursive CTE, then selects one randomly using the CRYPT_GEN_RANDOM() that we discussed earlier.
To If or Not to If
Might I also suggest an alternate method of generating the @payment_way. Instead of using an If, might I suggest using a Simple Case Statement.
Personally I find this
SET @payment_way =
CASE @amount % 2
    WHEN 1
    THEN 'cash'
    ELSE 'credit card'
END

To be a more SQL friendly way of writing it.
Putting it all together
This is what I ended up with. It's not any smaller, but it doesn't rely on any external stored procedures.
ALTER PROCEDURE generate_invoices
AS
BEGIN
    DECLARE
        @id_employee INT = (SELECT TOP 1 id_employee FROM Employee ORDER BY CRYPT_GEN_RANDOM(4)),
        @id_client INT = (SELECT TOP 1 id_client FROM Client ORDER BY CRYPT_GEN_RANDOM(4)),
        @id_service INT = (SELECT TOP 1 id_service FROM Service ORDER BY CRYPT_GEN_RANDOM(4)),
        @amount INT,
        @payment_way VARCHAR(20)

    SET @id_employee
    SET @id_client
    SET @id_service

    WITH Numbers(I) AS
    (
        SELECT 1000

        UNION ALL

        SELECT I+1
        FROM Numbers
        WHERE I<5000
    )
    SELECT TOP 1 @amount = I
    FROM Numbers
    ORDER BY CRYPT_GEN_RANDOM(4)
    OPTION (MAXRECURSION 0)

    SET @payment_way =
    CASE @amount % 2
        WHEN 1
        THEN 'cash'
        ELSE 'credit card'
    END

    INSERT INTO Invoice VALUES (@id_employee, @id_clienta, @id_service, @amount, @payment_way)
END
GO


What do you mean with "efficient" in this case?
From the performance perspective its slow, because it handles one element after the other and for handling one element it needs to wait for an async call.
As a result the browser will note be able to execute multiple requests at once.
You could try to move the getImage request into the html with the async pipe.
Then the browser will be able to fire multiple requests simultaniously.
Beside that i personaly would divide the code in a few methods. So it would look like this:
__HTML__
<img [src]="getImage(link.img) | async"

__TypeScript__
interface Link{
    id: string,
    img: string,
    name: string,
    bio: string
};

...
this.links = this.getLinks(userRef);
...

private getLinks(userRef: ??? ): Link[] {
    return userRef.collection('links', ref.where('pendingRequest', '==', false)).get()
        .pipe(
            map(querySnap => mapSnapToLinks(querySnap))
        )
}

private mapSnapToLinks(querySnap: ???):Link[]{
    querySnap.forEach(async doc => {
        const val = doc.get('otherUser').get().then(userData => this.mapUserToLink(userData));
        ret.push(val);
    });
}

private mapUserToLink(userData): Link {
    return {
        id: userData.id,
        img: userData.get('profilepic'),
        name: userData.get('name'),
        bio: userData.get('bio')
    }
}


Control.java

I don't like this name as it's not specific. I'd suggest 'CalculatorApp' instead.

You don't need the inifinite loop. The application will already continue until the user closes the program.

// you can remove all of this:
boolean exit = false;
while(!exit) {
}

Calculator.java

If you didn't write the program, would you know what Calculator.calculate(String) does? The naming is very ambiguous and the code itself looks very complicated (thankfully the heavy complicated, heavy lifting is done by an external library). You should add a javadoc to both the class & method at the very least.

You could have done this entire assignment without JavaScript. You may have gotten more learning out of it if you didn't use ScriptEngine. To me it seems hacky. I do give you bonus points for cleverness, though.

Gui.java

You have 2 unused imports (Level & Logger)

Avoid using wildcards (.*) in your imports. It clutters the local namespace and It makes it harder to tell which libraries are doing what. It will also cause a compiler error when there are two classes with the same name.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

If you're using an IDE you should see a warning about your class not having a serialversionUID. You can allow your IDE to auto-generate one for you:

private static final long serialVersionUID = 1L;

Avoid magic numbers & magic strings Your class would be easier to maintain & read if you used static variables declared at the top. E.G:

private static final int WIDTH = 400;
private static final int HEIGHT = 400;
...
//The frame
setSize(WIDTH, HEIGHT);

No need to count the number of values in an array yourself, instead use array.length. This will make maintenance easier as you don't have to re-count the values every time:

JButton button[] = new JButton[buttonText.length];
for(int i = 0; i < buttonText.length; i++) {

Alternatively use a 'for-each' loop since you don't need the index.

'17' should definitely be a variable here, as it's currently unreadable. Same goes for your other magic strings/variables:

else if(i == 17) {

This is probably one of, if not the worst thing you can possibly do. You may not think it matters now but trust me, this is a really bad habit and the best way to use good practices is to never learn the bad ones.  Please use a throws declaration if you don't want to handle errors:

catch (Exception ex) {
}


Sieve of Eratosthenes JavaScript implementation - performance very slow over a certain number

In a real Sieve implementation, your "sieve" is the array that keeps track of the multiples of primes. You'll also want to remember the values of the primes, since the array is basically an array of Boolean values.

Thus, the first thing you do is create the array. It has to be as big as the biggest target value:

function primesBelow(n) {
  var sieve = new Array(n);

Upon initialization, that array is empty, and thankfully in JavaScript empty array elements look false.  So we start with 2:

  var primes = [];
  for (var test = 2; test < n; ++test) {
    if (sieve[test]) {
      // NOT PRIME
    }
    else {

If the sieve value is unset at a particular test number, that means that that value is the multiple of no known prime. Hence, we can tick off that sieve entry (even though we'll never see it again) and all multiples of that newly-found prime:

      primes.push(test);
      for (var pm = test; pm < n; pm += test)
        sieve[pm] = true;
    }
  }

(Note that we really could start the value of pm at test * test, because the first composite number bigger than test for which test will be the only prime factor will be its square.)

When we start the loop at 2, the first prime we find is, clearly, 2 itself, since the sieve is freshly created and completely empty. So all the multiples of 2 will be set to true on the first pass. The second value to test is 3, and sieve[3] will still be false, because 3 is not a multiple of 2 and is therefore also prime.

The first composite number encountered will be 4, because its slot in the sieve will have been set to true when we found 2. Then 5 will be tested, and its sieve slot will also be empty, so it's prime too.

Note that the first odd composite number to be found is 9, which is not prime because its sieve slot will have been set to true when the loop found 3.

The complete code:

function primesBelow(n) {
  var sieve = new Array(n);
  var primes = [];
  for (var test = 2; test < n; ++test) {
    if (sieve[test]) {
      // NOT PRIME
    }
    else {
      primes.push(test);
      for (var pm = test; pm < n; pm += test)
        sieve[pm] = true;
    }
  }
  return primes;
}


Integer version of c++ standard library midpoint

Naming things
The variable names are not very clear. I assume the _2x stands for "2's complement" instead for "times 2", but for someone who doesn't know the context, it will be hard to follow. I'm not sure what the best way to name them is though, but as shown below you can avoid the issue altogether.
Don't use a template parameter for a derived type
If you make Unsigned a template parameter, it means someone can override it to something nonsensical. If you want to have a named type that is a derivative of another type, use using inside the function body:
template<typename Integer>
Integer midpoint(Integer a, Integer b)
{
    using Unsigned = std::make_unsigned_t<Integer>;
    ...
}

Simplifying the code
Most of the temporary variables can be removed. I would keep the variable diff, as it is the most important one where the casts are essential, and since it is used twice:
template<typename Integer>
Integer midpoint(Integer a, Integer b)
{
    using Unsigned = std::make_unsigned_t<Integer>;
    Unsigned diff = Unsigned(b) - Unsigned(a);
    return a + (b < a ? -Integer(Unsigned(-diff) / 2) : Integer(diff / 2));
}

The return expression is still reasonably short, and I don't think any information was lost. Adding some comments explaining why the casts are necessary would be helpful though.


Swap Nodes in Pairs in singly linked list

Once again, splitting this into different parts would benefit the solution. Basically:

A method, which swaps the first two elements in a given list if there are at least two elements. Then return the new first element. (Just return the one element if there is only one.)
A method which iterates: call the first method on the list head, then advance the current pointer twice, then call the method again and update the next pointer of the current node. Repeat until finished.

In general: always try to split a problem into parts which you can tackle separately.

Due to the comments below, I feel compelled to break my personal rule of not just posting code. Thus, here's a working (not thorougly tested) approach which uses the idea presented above. I hope that makes it clearer. (Note: succ == successor, that is the naming I learned at scool a long time ago...)

private static <T> ListNode<T> pairSwapHead(ListNode<T> head) {
    if(head == null || head.succ == null)
        return head;
    ListNode<T> next = head.succ;
    head.succ = next.succ;
    next.succ = head;
    return next;
}

private static <T> ListNode<T> pairSwapList(ListNode<T> head) {
    ListNode<T> curr = pairSwapHead(head);
    ListNode<T> res = curr; // result of first swap is new head == return value

    while(curr != null && curr.succ != null) {
        // second node of the current pair, which needs the next pointer
        // adjusted after the sublist starting at offset 2 gets swapped
        ListNode<T> needsNewNext = curr.succ;
        curr = curr.succ.succ;     // advance to sublist at offset two
        curr = pairSwapHead(curr); // swap first two elements
        needsNewNext.succ = curr;  // and adjust the pointer
    }
    return res;
}


Project Euler #5 in Ruby with Prime class

Shortening

Building arrays by concatenating results to an empty list is inelegant.  You should strive to define the result "all at once":

a = (2..20).flat_map { |n| Prime.prime_division(n) }

Usually, one-blocks should be written using { … }.  Use do … end if it spans multiple lines.

In the second half, n[0] should always be a prime number, so I don't see why it would ever be 0 or nil.  Therefore, you could finish up by writing

puts a.uniq.map { |prime, power| prime }.inject(:*)

Refining

To find the maximum power of each prime, use Enumerable#group_by.

require 'prime'

puts (2..20).flat_map { |n| Prime.prime_division(n) }
            .group_by { |prime, power| prime }.values
            .map { |factors| factors.max_by { |prime, power| power } }
            .map { |prime, power| prime ** power }
            .inject(:*)


The code is short and nicely done, so I don't have much comment

In branch, you could use void instead of return ()

branch cmd 'y' = system cmd >> void
branch cmd 'n' = putStrLn "Command Cancelled" >> getChar >> void

In your 'n' match, you use "getChar". I think it's to prevent the console from closing, right? Be aware that there is other ways, but it really depend on how you want to use your program.

Haskell use camelCase, so shutdown_path and rundll32_path should be shutdownPath and rundll32Path

Check

Your actual check functions are fine. But if you have more case like this, you should really consider this:

You could make the check function a top level one like this

check :: String -> Maybe a -> a
check _ (Just s) = s
check errorMsg Nothing   = error errorMsg

The check call from findCmdOrFail will remain practically unchanged, you just have to add your error message

The interesting part is the one from extractCmdOrFail, you have to use an helper function that I didn't find on hackage

whenMaybe :: (a -> Bool) -> a -> Maybe a
whenMaybe predicate x = if predicate x then Just x else Nothing

then your extractCmdOrFail will looks like this

extractCmdOrFail = getArgs >>= check (whenMaybe  $ {-your predicate-}) "Wrong Number of arguments"


Your coding style is clean enough, although you could add longer more descriptive names, and use functions instead of doing everything at the top level. However your main issues are related to choice of algorithm for finding the prime numbers.

Your algorithm is currently to test whether it is dividable by all numbers below it self. And this you repeat for each new number. This is by far the most ineffective algorithm for finding primes, so here are some basic stuff to do better algorithms:

No need to check even numbers – Your loop could skip every even number since the division by 2 should eliminate all other even numbers...
No need to check beyond square root of \$n\$ – If none of the numbers below the square root divides it, then none above will divide it either. This makes sense as if it's not prime you'll have that \$a*b = n\$, and if \$a\$ is larger than the square root, \$b\$ has to be lower.
Avoid multiplies of 3's (as well as 2's) – Another optimization of the brute force is to change the incrementation from 2, as in the sequence: 5, 7, 9, 11, 13, 15, 17, 19, 21, ... One can see that to avoid the 3's (in bold) one adds +2, +4, +2, +4. This can be simplified to an initial value of increment = 2 and then let increment = 6 - increment.
Keep track of earlier primes – Finally, still using a naive approach, you should keep track of earlier primes, as for lower values testing for division against non-primes is also a waste of time.

However you should probably look into more efficient algorithms (see Wikipedia's Generating primes. One good candidate is the Sieve of Erasthones, i.e. like in this answer which has a cool animation as well.


Some problems that could be seen without actually understanding code:

Unhelpful and possibly misleading comments: // the selected year is not null
Repeating type in variable name : brandProfitAndLossCurrentYear
Using ad hoc code instead of using appropriate library methods: list.size() <= 0 instead of list.isEmpty() and list.size() > 0 instead of !list.isEmpty()
Long method doing more than one thing: initComparisonDatatable retrieve data from form, calculate something based using said data, modify form using calculated data
Feature Envy: Since initComparisonDatatable acts on brandActionForm and uses only data from brandActionForm it belongs to brandActionForm.
Repetitive code: body of the three loops are repeated with minor variations.

There are probable design issues, but those cannot be addressed properly without further clarification. For example new BrandProfitAndLoss().getAllRateComparisonRecords suggests BrandProfitAndLoss has some data access code in it, therefore should be moved elsewhere; it probably is a class method instead of an instance method; and since it is a class method it probably has dependency issues, I can smell an evil singleton from here.

How refactored code could look like, (since loops and conditional statements have been changed these will definitely break something, so do not try to use it in production without proper unit testing):

    private void initComparisonDatatable() {
        List<BrandProfitAndLoss> comparisonDatatable = listForDatatable(
                brandActionForm.getBrandProfitLossComparisonList(),
                brandActionForm.getBrandProfitLossList(),
                brandActionForm.getDateMode());

        brandActionForm.setBrandProfitLossComparisonListForDatatable(comparisonDatatable);
    }

    private static List<BrandProfitAndLoss> listForDatatable(
            List<BrandProfitAndLoss> brandProfitLossComparisonList,
            List<BrandProfitAndLoss> brandProfitLossList, Object dateMode) {
        List<BrandProfitAndLoss> comparisonDatatable = new ArrayList<BrandProfitAndLoss>();

        int prevYearSize = brandProfitLossComparisonList.size();
        int currentYearSize = brandProfitLossList.size();
        int size = Math.max(prevYearSize, currentYearSize);

        for (int i = 0; i < size; i++) {
            BrandProfitAndLoss ofPreviousYear = (i < prevYearSize)
                    ? brandProfitLossComparisonList.get(i)
                    : null;

            BrandProfitAndLoss ofCurrentYear = (i < currentYearSize)
                    ? brandProfitLossList.get(i)
                    : null;

            if (ofPreviousYear == null) {
                ofPreviousYear = new BrandProfitAndLoss(
                        ofCurrentYear.getDate(), dateMode, Consts.CURRENT_YEAR);
            }

            if (ofCurrentYear == null) {
                ofCurrentYear = new BrandProfitAndLoss(
                        ofPreviousYear.getDate(), dateMode, Consts.CURRENT_YEAR);
            }

            comparisonDatatable.add(ofCurrentYear);
            comparisonDatatable.add(ofPreviousYear);
            comparisonDatatable
                    .add(new BrandProfitAndLoss().getAllRateComparisonRecords(
                            ofCurrentYear, ofPreviousYear));
        }

        return comparisonDatatable;
    }


Please pick a consistent brace style.

i has the connotation of being an integer counter.  I would pick a different variable name for iterating over the properties of an object.

I don't see any need for obj[i] && in the else if test.

If you use recursion properly, you shouldn't need to have a third parameter at all.

function findPropPath(obj, name) {
    for (var prop in obj) {
        if (prop == name) {
            return name;
        } else if (typeof obj[prop] == "object") {
            var result = findPropPath(obj[prop], name);
            if (result) {
                return prop + '.' + result;
            }
        }
    }
    return null;    // Not strictly needed, but good style
}

var myObj = {'a': {'b': {'c': {'x': 1, 'y': 2 }}}};
console.log(findPropPath(myObj, 'x'));


Don't waste time on micro-optimizations. Use the simplest possible techniques that are known to perform well. In your specific case, it means replacing your multiple lists with one single array and using the standard fisher-yates-shuffle.
Naming conventions
In good C# code, local variables are camelCase beginning with a lower case letter. I renamed most of your variables to better express intent.

Generating the strings
You'll get a performance increase of about 30%-40% by using an array instead of a list (not much to be gained here).
Don't bother with string concatenation instead of string.Format, there is hardly any measurable difference in speed, but a huge difference in readability and maintainability.
string[] elements = new string[columns * rows];
for (int column = 0; column < columns; column++)
    for (int row = 0; row < rows; row++)
        elements[columns * row + row] = string.Format("{{{0},{1}}}", column, row);

Shuffling them
Whenever you remove from a list, all the remaining elements have to be shifted to fill the gap. Use your array instead and use the fisher-yates-shuffle; don't attempt inventing your own.
for (int i = elements.Length - 1; i > 0; i--)
{
    int swapIndex = random.Next(i + 1);
    string tmp = elements[i];
    elements[i] = elements[swapIndex];
    elements[swapIndex] = tmp;
}

This runs about 160 times as fast as your shuffling implementation.

Don't reinvent the wheel
When saving the results to disk, use File.WriteAllLines which does exactly what you were doing with the StreamWriter - in a single line.
File.WriteAllLines(outputFilename, elements);

Complete code (argument parsing omitted)
Once you've realized that a few milliseconds more or less don't matter, it would be good to split this up into several methods that each do exactly one thing. I'll leave that as an exercise to you.
string[] elements = new string[columns * rows];
for (int column = 0; column < columns; column++)
    for (int row = 0; row < rows; row++)
        elements[column*rows + row] = string.Format("{{{0},{1}}}", column, row);

Random random = new Random(seed);
for (int i = elements.Length - 1; i > 0; i--)
{
    int swapIndex = random.Next(i + 1);
    string tmp = elements[i];
    elements[i] = elements[swapIndex];
    elements[swapIndex] = tmp;
}

File.WriteAllLines(outputFilename, elements);


Update multiple records with Entity Framwork

This is the usual way how to update properties in EF, and in your case, I'd say it seems the only proper way. You can surely attach and update - but then you'll loose all other properties in your entity. To sum up - if you'd need to update one property in entities, you'll need to do SELECT (your query), modify entities (foreach) and then do UPDATE (SaveChanges).


In terms of the php code itself, the only thing I notice is your use of the $_POST superglobal in your class. This isn't wrong per say but I typically try to avoid use of $_POST in my objects, and instead pass the data in via parameters. Keeping all of your $_POST access in the same place makes it easier to manager changes, especially this the contents of $_POST is so easy to change. Same is also true for $_GET and $_REQUEST.

The same is also kind of true for the $_SESSION variable. It's not as important where it is, but stick to access within a limited set of locations.

Here's a few points to consider in terms of how you've constructed your class. They're not really php things, more good object construction practice.

Make sure you're always returning something from your methods. In many you have a return if things go right, but nothing if things go wrong. This will result in a NULL being returned but it's better practice to define this for reliable and consistent operation.

To take a more MVC approach, and to make your code easier to change and maintain, you shouldn't be echoing your errors in the class. Rather set the message to an error variable that can be retrieved by the calling code if needed, and then return FALSE. Echoing the error as it happens can be good during development but I recommend against it for production. If you still do want to see the error, best to handle it in the calling code so that you can easily change how the error is displayed. You could use a debugMode flag in the class if you want the best of both.

Your code indenting could really be improved.

private function get_user_hash($username){
    try {
        $stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username AND active="Yes" ');
        $stmt->execute(array('username' => $username));
        $row = $stmt->fetch();
        return $row['password'];
    } catch(PDOException $e) {
        echo '
'.$e->getMessage().'
';
    }
}

Lastly I recommend using CamelCase for your method names. The use of lowercase and underscores to me is a bit oldschool and more difficult to read.

private function getUserHash($username)


Bloom Filters

I suggest a new data structure, specifically a Bloom Filter.  A bloom filter is a boolean array of length m.  You will also need k different hashing algorithms (more on m and k in a moment). Each hash should accept complete word and return a number 0 through m.

A bloom filter is a big hashing data structure that returns one of two results when checking if an item is in the hash:
1) The item is definitely not in the data structure
2) The item is maybe in the data structure

To use the bloom filter, you will load it with every word in your list.  Specifically, for every word, load the first two letters, then first three, then so on, until the whole word is loaded.  I like the idea of using a period to mark the end of the word, so do that too.  For example, for the word 'cart', you would load your filter with ['ca', car', 'cart'].

Then, on the boggle array, you can do an exhaustive DFS search fromevery starting position. if the letter combination (with or without period) is in the list, then you keep branching and searching.  If the combination isn't in the list, you choose a different path, etc.

Simple concrete example

Here is a simple example of a bloom filter being used.  Let's set m=100 (array of 100 booleans, initialized to true) and k=2 (use two different hashing algorithms).

When hashing the word 'cat', hash1 might return 7 and hash2 might return 36, so you set indexes 7 and 36 to false.  When hashing the word 'dog', hash1 might return 7 and hash2 might return 70, so those indices are set to false.  Next, we check to see if 'fish' is in the array.  Hash1 returns 80 and hash2 returns 7.  Because all the indices are not false, we know that 'fish' is definitely not in the array.  Finally, we check if 'bird' is in the array.  Hash1 returns 70 and Hash2 returns 7.  'Bird' might be in the array and we will have to check the actual wordlist to confirm.

Some notes

1) You should be able to search using only the bloom filter until you are checking for a complete word (For example when checking for 'car.', and not checking 'car' as a substring of 'cart.' or 'carriage.').  Otherwise if the bloom filter says it's probably in the list, just assume it's true.
2) Depending on how thorough your edge cases are, it may be possible to occasionally miss a possible word depending on the hash algoirthms chosen, size of filter, etc.  In general, I would say that while you are not 100% guaranteed to find the highest scoring word, you will definitely find a high scoring word.
3) The bloom filter here is chosen to reduce the memory space of the search.  The running time may very well be longer than the trie structure.
4) When confirming a word exist in your word list, you should, of course, use a binary search.

Choosing m and k

There is some math involved in choosing m and k.  I'll spare you the finer details and suggest you look at wiki section about choosing optimal sizes.


Some thoughts:

You should strongly consider using appropriate datetime, timestamp, etc. column types when storing date and/or time information in your DB. Unix timestamps may seem simple for working with in PHP, but at some point you will have to query on those fields and having to convert to date/time entities in a query will disallow indexing on that field.
I am concerned that you don't store a flag to indicate if password reset has actually been used (i.e. user clicks on link in email).  Why would you care if a user reset their password 10 times in an hour if they actually completed the whole process each time (something a probing attacker would presumably not be able to do without access to email account)? I would be worried about the number of unused reset attempts.  I would actually also be more concerned with frequent activity coming from a single IP trying to submit different email addresses, but that may require more network-layer security controls.
I think you could simplify your approach by only looking for X number of unused requests within a given time frame. Perhaps 12 per week.  An automated attacker would violate this constraint potentially within seconds anyway, so I don't see why having different thresholds for different periods of time makes much sense, it only adds to complexity. You could possibly remove time threshold altogether and just limit it to X unused attempts total.  At that point you probably either have a legitimate attacker (not likely) or you have a user experience/confusion problem in your process where you might need to give the user more specific guidance, or put them in touch with support, or whatever.
You also may have need to mark a record as expired, that is if there are 10 unsuccessful requests, only the most recent one would actually still work.
I don't like fluent style when performing prepared statements used here, as I think you need to be able to try the prepare first and validate that it worked before trying to execute it.
Consider better name than $num_rows.  You are storing a database record (in this case an array with one element) there, not a row count.


import bisect
f = open('matrix.txt')
matrix = [[int(i) for i in j.split(',')] for j in f]

You could consider using the numpy library, it'll handle multidimensional arrays more neatly and efficiently.

def uniformCostSearch(startNode):

Python convention is to use underscore_with_letters for function names and parameters

    frontier = []
    frontier.append(startNode)

Use frontier = [startNode], it'll be a touch faster

    closedSet = set()
    while not len(frontier) == 0:

Use while frontier:, it does the same thing and due to less operations is going to be a bit faster. You should at least use != rather then not ==

        currentNode = frontier.pop(0)

Popping from the front of a list will be inefficient. Actually, what you really want is a priority queue, see python's deque module.

        if currentNode.x == 79 and currentNode.y == 79:
            return currentNode.priority
        else:
            if not (currentNode.x, currentNode.y) in closedSet:

Move the not over next to in I think it reads clearer. I might also use a 2D array of bools rather then a set here.

                closedSet.add((currentNode.x, currentNode.y))

There isn't really any reason to check if the node is in the set here, you can add the node multiple times. Just add it unconditionally.

        possibleMoves = currentNode.neighbors()
        for move in possibleMoves:

No reason to store it in a local, just combine the previous two lines

            if not (move.x, move.y) in closedSet:
                try:
                    index = frontier.index(move)
                    if move.priority < frontier[index].priority:
                        frontier.pop(index)
                        bisect.insort_left(frontier, move)

Move the last three lines into an else block. That'll make sure only your index line can actually throw things that'll get caught.

                except ValueError:
                    # move is not in frontier so just add it
                    bisect.insort_left(frontier, move)

You do this in either case, I'd move it after the try/except block.
        return -1

class Node:
    def __init__(self, x, y, priority=0):
        self.x = x
        self.y = y
        self.priority = priority

    def neighbors(self):
        tmp = [Node(self.x + 1, self.y), Node(self.x, self.y + 1),
               Node(self.x - 1, self.y), Node(self.x, self.y - 1),]
        childNodes = []
        for node in tmp:
            if node.x >= 0 and node.y >= 0 and node.x <= 79 and node.y <= 79:

I suggest moving 79 into a constant. I'd also do < 80 rather then <= 79.

                node.priority = self.priority + matrix[node.y][node.x]
                childNodes.append(node)

I'd use a yield here, and make this a generator

        return childNodes

    def __eq__(self, node):
        return self.x == node.x and self.y == node.y

This bothers me because multiple nodes will compare equal despite having different priorities.

    def __ne__(self, node):
        return not self.x == node.x and self.y == node.y

    def __cmp__(self, node):
        if self.priority < node.priority:
            return -1
        elif self.priority > node.priority:
            return 1
        else:
            return 0

This really bothers me because you aren't defining your comparisons in a consistent way.


I'd definitely change:

if(instance[i] == undefined) {
    addError("Property Not found", i);
}

to something more robust, e.g.

if (!instance.hasOwnProperty(i)) {
    addError("Property Not found", i);
}

Stylistically I'd change a few things as well:

Add a space between function names and (): function() to function ()
Add a space between if, for etc and (: for(i in schema) to for (i in schema)
Add in semi-colons after defining your functions:

var getType = function(attr) {
    return Object.prototype.toString.call(attr);
}; // <-- here.

Also, because JavaScript doesn't have block scope I like to define all my variables at the top of the function. e.g. you have:

validate = function (schema, instance) {

    // omitted code.

    for(var j=0; j<instance[i].length; j++) {
        errors += validate(zeroSchema, instance[i][j]);
    }

    // more code.
}

Whereas I would prefer j defined at the top of the function (as well as the extra spaces I've added).

Having said all of that, I wonder whether your solution is flexible enough - how would you specify an optional property? A property with a minimum and/or maximum value?


Advice on taming a slow loop required for visualization of large GIS dataset

The nested loop compares each poly to each point, so the complexity is (Npoly * Npts).

If the grid is regular, that is each square in a row has the same top and bottom coordinate, and each square in a column has the same left and right coordinate, then binary searches (bisect in std library) could be used to determine which grid row and column a point falls in.  This would be Npts * log Npoly.  I think this could be combined with .groupby() to eliminate any explicit loops.  I don't have time to post code now,  maybe tomorrow.

(It's tomorrow)

Better yet, use numpy.histogram2d.  On my laptop, it takes about 220ms to bin 2M points:

import numpy as np

min_lat, max_lat = 49.22, 49.30
num_lat_bins = 10

min_long, max_long = -123.23, -122.92
num_long_bins = 20

num_points = 2_000_000

# random coordinates for testing
lats  = np.random.uniform(min_lat,  max_lat,  num_points)
longs = np.random.uniform(min_long, max_long, num_points)

h, lat_edges, long_edges = np.histogram2d(lats, longs,
                                          bins=(10,20),
                                          range=[(min_lat,max_lat), (min_long, max_long)])

Where, h is the histogram, or count in each grid square and lat_edges and 'long_edges are the grid lines.  They look like:

# h  (10 rows by 20 columns)
[[ 9982. 10126. 10124. ... 10218. 10140.  9844.]
 [ 9971. 10096. 10035. ... 10057.  9844.  9923.]
 [ 9940. 10036.  9982. ...  9966. 10034.  9872.]
 ...
 [10025. 10011. 10027. ...  9870.  9942.  9985.]]

# lat_edges
[49.22 , 49.228, 49.236, 49.244, 49.252, 49.26 , 49.268, 49.276,
       49.284, 49.292, 49.3  ]

# long_edges
[-123.23  , -123.2145, -123.199 , -123.1835, -123.168 , -123.1525,
 -123.137 , -123.1215, -123.106 , -123.0905, -123.075 , -123.0595,
 -123.044 , -123.0285, -123.013 , -122.9975, -122.982 , -122.9665,
 -122.951 , -122.9355, -122.92  ]


Use of a regex stored inside a YAML file

If you want to use a regexp in a yaml file you need to use !ruby/regexp

#config/settings.yml
defaults: &defaults

  email_regex: !ruby/regexp '/^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i'

Edit:
 The solution proposed by Mike Bethany is very similar to the yaml implementation.

You can take a look to what is used in Ruby 1.9.2 here (search for "!ruby/regexp"):
https://github.com/tenderlove/psych/blob/master/lib/psych/visitors/to_ruby.rb

PS (and OT): I think, like Mike Bethany, that this basic functionality belong to the Regexp class not yaml, and need to be moved to a Regexp method. What do you think?


A Python decorator for an "observable property", that notifies observers when the data is changed

Private name mangling
The reason why you "can't mutate the self.__position from the __set__ descriptor" is the leading double underscore.  From 6.2.1. Identifiers (Names):

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

In the constructor, self.__position = 0.0 is rewritten to be self._Axis__position = 0.0.  When you are in the descriptor's __set__ method, getattr(obj, '__position') does not exists, because the name is wrong.
If you used a single leading underscore, instead of a double leading underscore, no name mangling will take place, and attribute can be referenced with the same name in both the main class and the descriptors.  This means you can set the initial values in the constructor, as desired.
Boilerplate
    @observable_property(initial_value=Meters(0.0))
    def position(self):
        pass

The def, (self): and pass parts of this are also boilerplate.  If you tried to use actual code, instead of the pass statement, the code would never be executed, because the descriptor's __get__ method is used instead.
The above code is approximately:
    position = observable_property(initial_value=Meters(0.0))(lambda self: pass)

If you removed the unused fget argument from the constructor, or removed the _observable_property constructor entirely, this could be reduced to:
    position = observable_property(initial_value=Meters(0.0))()

Since you don't need (or want) the initial value in the observable property descriptor, you want it in the class constructor, and the previous section showed why it wasn't working and how to fix it, we can remove the initial_value argument entirely, and with it the def observable_property wrapper around the class _observable_property.
Reworked code:
from typing import NewType

class ObservableProperty:

    def __set_name__(self, owner: type, name: str) -> None:
        def add_observer(obj, observer):
            if not hasattr(obj, self.observers_name):
                setattr(obj, self.observers_name, [])
            getattr(obj, self.observers_name).append(observer)

        self.private_name = f'_{name}'
        self.observers_name = f'_{name}_observers'
        setattr(owner, f'add_{name}_observer', add_observer)

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private_name)

    def __set__(self, obj, value):
        setattr(obj, self.private_name, value)
        for observer in getattr(obj, self.observers_name, []):
            observer(value)

Meters = NewType('Meters', float)
Kelvin = NewType('Kelvin', float)

class Axis:

    def __init__(self):
        self._position = Meters(0.0)
        self._temperature = Kelvin(273.0)

    position = ObservableProperty()
    temperature = ObservableProperty()

a = Axis()
print(a.position)     # Initial values from the constructor
print(a.temperature)
a.add_position_observer(lambda newval : print(f'New position for a: {newval}'))
a.add_temperature_observer(lambda newval : print(f'New temperature for a: {newval}'))
a.position = Meters(5.0)
a.temperature = Kelvin(300.0)

Composition
The ObservableProperty descriptor takes away all control of the attribute from the class.  The attribute cannot be calculated.  For instance, an observable attribute celsius could not read self.kelvin + 273, or write self.kelvin = value - 273 because it has no control over the get/set functionality.
What if you made an @observable decorator, which just added the observer capability, which could be used like:
class Axis:

    def __init__(self):
        self._position = 0.0

    @property
    def position(self) -> Meters:
        return self._position

    @observable
    @position.setter
    def position(self, value: Meters) -> None:
        self._position = value

Then, you could have validation in the setter (such as position can't be negative).
And if you wanted, you could create a SimpleProperty, which had the trivial getter & setter, and compose that into ObservableSimpleProperty and so on.


Generally speaking, I would not expect a database call to be made simply by referring to a property, such as with val user = MyRepository.userInfo. If a database call is being made, it's better to have a function for it.
I'd even argue that it would even be better to name the function fetchUserInformation than getUserInformation to be clear that this is not just a simple getter.


Application for converting markdown to PDF

Answers to your specific questions:

  My first question is, have I made any common C errors, like buffer
  overflows or unreleased memory?

A leak is always connected to a resource. A resource is by definition something that you acquire manually, and that you must release manually. Memory is a prime example, but there are other resources, too (file handles, mutex locks, network connections, etc.).

A leak occurs when you acquire a resource, but subsequently lose the handle to the resource so that nobody can release it. A lesser version of a leak is a "still-reachable" kind of situation where you don't release the resource, but you still have the handle and could release it. That's mostly down to laziness, but a leak by contrast is always a programming error.

I don't see any leaks in your code, but I'm only using my half-human side to analyze that.  I would use a more thorough tool such as Valgrind to provide more substantive confirmation.

  I'm compiling the application and dependencies statically, how common
  is this? My main reason for this is that one of the dependencies
  (wkhtmltopdf) is a bit tricky to compile, so I want to be able to
  provide a binary release that doesn't depend on a shared library.

  I have added the dependencies to the repository, not what I'm used to
  from Ruby or Go, but it seems like the most straight forward way. One
  other solution I tried was to download the dependencies using git in
  the Makefile, like this. So they did not have to be added, but that
  did not feel like a good C solution. Feels a bit like a "roll you own"
  solution. How would you do this?

I had a project that was somewhat similar to yours in this aspect.  As long as all those dependencies are available, then there is no problem

The problem for my project to compile was that I couldn't guarantee that. I also didn't want the user scrounging around trying to figure out how to get my application to simply compile.  Here's what I did, I used CMake to handle all of that.  It took a bit of work, but here's the jist of what it does: it takes all of the dependencies that your application relies on and searches the host computer for them.  If it finds them, it stores that location for it's use later when compiling.  If it can't find them, then it manually downloads them and performs it's own build of the dependency which it will then use later for compiling.  The real "fun" part comes in where you dependency has sub-dependencies, which I also had to deal with...

It's a lot more work, but also a whole lot more portable and less stressful for the end user (which should be the ultimate goal really for all developers, making the usage of your application as hassle-free as possible for your consumers).

  Is there anything in the Makefile I could do to make it easier to
  build for various package managers? E.g. apt-get, homebrew, ports,
  pkg?

Another reason to use CMake or another similar build system, so that it generates a Makefile for you based on the system it's running on.

  Are there anything else I should do to be a good *nix citizen? E.g.
  the man page.

man pages are nice.  Besides, how else are you supposed to tell your users to RTFM?

A few comments on the code posted in the question (hopefully not conflicting with @ferada):

I notice some suspiciously similar code in a few places:

if (error_code > 0) {
    fprintf(stderr, "I/O errors found while reading input.\n");
    hoedown_buffer_free(ib);
    fclose(in);
    exit(error_code);
}

The stuff within the conditional could be extracted to a function so that reuse would be possible, and would help your code follow the DRY principles.  This should also shorten your code a bit
You should be declaring your counter variable (int i in this case, within your for loops), so that it is in the smallest scope possible.(C99)
You don't have to memset your char arrays to 0, just initialize them that way.

char nameBuff[23] = "";

Or the more "universal" way to zero out an array (since it works with every type):

char nameBuff[23] = {};

Nice job generating a temporary file safely!  I have one big problem with it though, and it has to do with this line

strncpy(nameBuff, "/tmp/mdpdf-XXXXXX.html", 22);

See that /tmp/ part?  That isn't guaranteed to be the temporary file storage location for every Unix system, making your code a lot less portable.  For example, the location my system prefers to point to is /var/folders/xp/j1l6q2z12n54k9y4r7574l0w0000gn/T/. Here's how I solved the problem, abstracted away in a function:

const char* getTmpDir(void)
{
    char *tmpdir = NULL;
    if ((tmpdir = getenv("TEMP"))) return tmpdir;
    else if ((tmpdir = getenv("TMP"))) return tmpdir;
    else if ((tmpdir = getenv("TMPDIR"))) return tmpdir;
    else return "/tmp/";
}

To which I created a file like such:

// Creates temporary file safely
char flacFile[FILENAME_MAX] = "";
const char *fileRoot = getTmpDir();
snprintf(flacFile, FILENAME_MAX, "%sXXXXXXXXXXXXX.flac", fileRoot);
mkstemps(flacFile, 5); // the 5 is for the length of the suffix ".flac"

Since I can never actually know the length of fileRoot for my static array creation, I just used the maximum length that a filename could be, very helpfully stored in the predefined macro FILENAME_MAX.


Printing factors and prime factors of a number

Welcome to programming! I'm new to code reviews (your StackOverflow post brought me here), but hopefully I have enough other experiences that something that follows will be of value to you.

As to your OOP question, since you're already learning it I would stick to Python rather than learning 2+ languages at once. It still has full support for objects and OOP principles, so there isn't a whole lot to lose. If you had to pick between Simula or SmallTalk, I'd recommend SmallTalk in a heartbeat (and I'd recommend temporarily dropping Python so that you're still only learning one language at a time).

Positives

I don't generally think critiques should only include the negatives, both for psychological reasons and since it's also important to keep doing the good things. At a high level, all of the following are nice. Keep it up.

You're breaking the code up into modular components. In your case, the components happen to be functions rather than objects, and that's fine. Functional code can express many problems more easily than OOP code.
The #--- comments you're using make the code surprisingly pleasant to read. I haven't seen that before, and I rather like it.
The if __name__ == '__main__' bit is a best practice in Python code, allowing different behavior if your program is called as a script or imported.
Your variable names are descriptive. This IS a big deal and makes everyone's lives easier (including yours). This is an important detail that I've noticed most new programmers leave out.

Needs Improvement

This looks like a lot in a big wall of text, but I promise there aren't that many things; I'm just trying to make sure that there's enough explanation that the comments are actually helpful to you.

Using global variables is almost universally recognized as a poor programming practice in every major language. The problem is that as the number of connections between different parts of your code increases, the number of code paths increases exponentially. It becomes very hard to reason about the behavior of your program. By having everything linked to even one (or in this case more than one) global variable, it is hard to analyze any component by itself. Even in your current code, if you tried to find the prime factors of several numbers at once you would likely have hard-to-track-down bugs due to the global variables.

One way to approach that option is to pass more arguments in your functions. As one example, instead of having look4factors() and find_prime_factors() both share the global variable list_of_factors, you could have look4factors() return the local variable list_of_factors, and then that could be an argument to find_prime_factors().
Capitalization schemes should typically be consistent in your code. The occasional use of Prime instead of prime could cause problems down the road.
Having hard-coded values should be avoided as much as possible. It's a lot of work for you, and it makes your code less robust too. With that few prime factors, it wouldn't work for numbers much bigger than 1000000 (approximately your biggest prime number squared).

It would be better to generate those prime numbers at run time. You could do that with trial division (for each new number, check to see if it's prime by checking if all the primes you've found up to the square root of that number so far are factors), or with more complicated algorithms like the Sieve of Eratosthenes. The key point is that by doing so you can handle any size of input instead of just small inputs.
Since you're using Python 2, the use of range() is discouraged when you're just iterating over those values. The range() function creates an object storing every integer you'll iterate over, whereas xrange() simply keeps yielding the new values. It saves a lot of RAM to use xrange(). This is one of the things that broke between Python 2 and Python 3. In Python 3, xrange() doesn't exist by default, and range() behaves like the old xrange() used to.
When you have a list of things (like list_of_Prime_factors) and need to do something special for just the beginning or just the end, rather than having an if statement inside your loop, it's better to have the special case either before or after the loop and have the loop only do the main operation. This matters because

if statements and other branches are more expensive for modern CPU's to deal with than other kinds of operations. Arguably that doesn't matter as much in Python since everything is so abstracted and since some of those branches are inlined by the bytecode compilation step, but maybe it's a tidbit you'll find useful one day.
Nested code is harder to reason about and debug than flat code.
Whether if statements are comparatively more expensive or not, you're still doing a lot of them that you don't need to.

Python has a concept of iterables that you might find helpful in simplifying your code. You can do other things than iterables, but one idea is that instead of writing

 for i in (0, len(thing)):
    # stuff with thing[i]

You can write something like

 for item in thing:
    # stuff with item

Extras

Most libraries, services, and security updates have been implemented in or completely switched to Python 3. If it were only for that, I'd recommend switching. There are some syntactical things that make your life easier too though, even in this code example. In Python 3.6+ you have so-called f-strings which allow arbitrary expressions inside them. Instead of '{}'.format(x) you can just write {x}, and the code runs faster too.

Note that many common things that you can do in a loop have already been implemented in the language. For example, it's possible to replace all of

for index in range (0, len(list_of_Prime_factors)):
    print "{}".format(list_of_Prime_factors[index]),
    if (index + 1 == len(list_of_Prime_factors)):
        pass
    else:
        print "X",

With the following line of code

print ' X '.join(map(str, list_of_Prime_factors))

Or if you'd rather learn about Python's list comprehensions, the following is roughly the same thing (and still works in Python 3 after modifying print to be a function, where the example I just gave would need a little tweaking).

print ' X '.join([str(p) for p in list_of_Prime_factors])


Two setIntervals activating in a sequence to change CSS

What is the game object for? I assume it's for keeping all game states together, which is good, but I can't tell from this example.

let i = -1;
let c = -1;

It's a bit strange to start an index at -1. The names also tells me nothing about what these are. This also makes it hard to follow the exact flow of the code.

const showColors = new Map ...

You are creating a new map for every loop (same with colorKey). These should be declared once, at the start of your program. You could use the game object for this.

if (i >= game.computerMoves.length - 1) {
    clearInterval(start);
}

You are stopping the interval from future calls, but not the current function you are in, which gives an error, since the index is out of bound. Add a return to stop it.

clearInterval(stop);

When the timeout is done, you are clearing the same timeout, which is already done, so this does nothing. You can get rid of it.

You can make a function to turn on or off a light. You can then pass this directly to your timeout. This also gets rid of c.

function setLight(color, isOn) {
    color.style.backgroundColor = isOn ? game.showColors.get(color) : game.colorKey.get(color);
}

The full code then looks like this. I had to make up some HTML, CSS and a few lines of JS to initialize some things, since you didn't include it.

const red = document.getElementById('red');
const green = document.getElementById('green');
const yellow = document.getElementById('yellow');
const blue = document.getElementById('blue');
let game = {};

game.showColors = new Map([
    [green, 'lime'],
    [yellow, 'rgb(255,255,102)'],
    [blue, 'dodgerblue'],
    [red, 'salmon'],
]);
game.colorKey = new Map([
    [green, 'green'],
    [yellow, 'rgb(204,204,0)'],
    [blue, 'blue'],
    [red, 'red']
]);

//a random array representing html divs to change colors
game.computerMoves = [green, red, blue, red, green, green , yellow];

showMoves();

function showMoves() {
    let i = 0;

    const start = setInterval(function() {
        if (i >= game.computerMoves.length) {
            clearInterval(start);
            return;
        }

        const move = game.computerMoves[i];
        setLight(move, true);
        setTimeout(setLight.bind(null, move, false), 1000); //Using bind to preset arguments

        i++;
    }, 2000);
}

function setLight(color, isOn) {
    color.style.backgroundColor = isOn ? game.showColors.get(color) : game.colorKey.get(color);
}
div {
    width: 50px;
    height: 50px;
    display: inline-block;
}
#red {background-color: red;}
#green {background-color: green;}
#yellow {background-color: rgb(204,204,0);}
#blue {background-color: blue;}


Opening a file and printing its contents line by line

Rather than using f.read().splitlines(), you can iterate the file object allowing you to use:

with open('<filename>') as f:
    for line in f:
        print line

Using with is better for various reasons, you don't have to remember to close the file, as you said in the question. It also closes the file, even if an error happened, which the second code doesn't. Take the following:

FILE_NAME = 'test_file.txt'
with open(FILE_NAME, 'w') as f:
    f.write('Hello World')

f = open(FILE_NAME)
try:
    with f:
        raise Exception()
        print f.read()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'

f = open(FILE_NAME)
try:
    raise Exception()
    print f.read()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'

f = open(FILE_NAME)
try:
    try:
        raise Exception()
        print f.read()
    finally:
        f.close()
except Exception:
    try:
        print f.read()
    except ValueError:
        print 'I/O operation on closed file'

This outputs two I/O error messages and one 'Hello World'. The single hello world is using the second way, without a finally to close the file. And so if you did want to use the second method, then you'd want to use something like:

try:
    f=open('<filename>')
    for line in f:
        print line
finally:
    f.close()

And, we all know which is easier to read an write.
For more information about the with statement you can look into PEP 343, which explains why it was added to Python.


Iterators may not be random access iterators which means the length calculation and the advance by half won't compile.

For this there is the distance and advance functions available which use the random access if it is available but fall back to counting and repeated incrementing when it isn't.

You never use the t_elem type def.

In the recursion step both branches are equally likely and equally important, that is best signified and made more readable by using an else branch rather than letting it fall through.

you can also implement as a loop to minimize recursion overhead (micro-optimization admittedly because automatic tail-call optimization would do the same).

template<typename t_iter>
t_iter binarySearch(t_iter begin, t_iter end, typename iterator_traits<t_iter>::value_type q)
{
    auto len = std::distance(begin, end);

    while(len>1)
    {
        t_iter middleElem = begin;
        std::advance(middleElem, len / 2);

        if (*middleElem < q)
        {
            begin = middleElem;
        }
        else
        {
            end = middleElem;
        }
        len = std::distance(begin, end);
    }

    if (*begin == q)
    {
        return begin;
    }
    return end;

}


Been a while since I've done much in the way of heavy C++ & I'm sure others will weigh in with their own suggestions, but my two cents:

I think the best solution is the first one you rejected: add Foo::{Add,Remove}Listener. Yep, it's more code but (a) it solves both the issues you observe with the code & (b) the implementation of these methods will be trivial. It's a compromise: better encapsulation in exchange for a little more code.

If you're really set on your approach, I'm pretty sure you could work around issue #1 by separating EventHandler into two classes (e.g. EventHandler & EventTrigger) & using friends to expose the dirty details, but IMO that's comparatively ugly. This stuff doesn't deserve that kind of hack.

Along that line of thinking but maybe a little cleaner: have EventTrigger derive from EventHandler (the former providing ::Trigger, the latter ::{Add,Remove}Listener), making m_handler an EventTrigger & having Foo::SomeHandler return a pointer to an EventListener -- effectively "hiding" the Trigger method from the outside world. You're still "leaking" here because you'll need to expose a protected instance variable or method (the list of listeners), but this stuff is simple enough that it shouldn't be completely abhorrent.

Depends what you consider a "flaw" :) Implementors of IDelegate might find the fact the method is const to be annoying (but then you might be making assumptions about implementations of IDelegate that I'm not aware of). Other than that & the issues you observed, things look fine to me.


I prefer your solution to his. My reasoning is that:

yours has constants only in the String manipulation
you do not do string concatenation
the logic is distinct for each remainder.

Both options could be better though. The lack of 'breathing space' (white space between keywords, variables, values, and operators) leads to hard-to-read code. Lines like:

for(int i=1;i<=100;i++){

should be:

for (int i = 1; i <= 100; i++) {

Then, your solution would actually be more efficient as a switch statement:

for (int i = 1; i <= 100; i++) {
    switch (i % 15) {
        case 0:
            System.out.println("FizzBuzz");
            break;
        case 3:
        case 6:
        case 9:
        case 12:
            System.out.println("Fizz");
            break;
        case 5:
        case 10:
            System.out.println("Buzz");
            break;
        default:
            System.out.println(i);
    }
}

The switch statement will be optimized so that there does not need to be more than one modulo, and there is no concept of an if/elseif/elsif/else... just a single condition check.


You don't need all that copying and rearranging, all you need is to keep a pointer to where array starts and adjust your index calculation based on that.
Suppose you have an array of integers: [0, 1, 2, 3, 4], current start index is 0. If you rotate 2 to the left, your start index becomes 3: [2, 3, 4, 0, 1]. If you rotate this to the right 4 times, your start index is changed to 2.
You can see a pattern here: moving n cells to the left decreases start index by n and moving right increases start index.

Here's a sample pseudo-code:

startIndex = 0;
foreach operation
   if operation is print
      transformedIndex = operation.index - startIndex
      if(transformedIndex < 0)
         transformedIndex += inputArray.length
      print inputArray[transformedIndex]

   else
      if operation is rotate left
         startIndex -= operation.index
      else
         startIndex += operation.index
      startIndex = startIndex mod inputArray.length
      if startIndex < 0
         startIndex += input.Length


Using T-SQL SEQUENCE with Entity Framework 6

Your C# code looks fine, but using non-cached sequences instead of IDENTITY (which would be much easier to implement in Entity Framework) does not ensure a gapless incrementing identifier.

According to this Microsoft article, sequences can generate gaps in some scenarios:

  The sequence object generates numbers according to its definition, but
  the sequence object does not control how the numbers are used.
  Sequence numbers inserted into a table can have gaps when a
  transaction is rolled back, when a sequence object is shared by
  multiple tables, or when sequence numbers are allocated without using
  them in tables.

So, error on saving changes will have consumed the sequence numbers and thus you obtain gaps.

On the database side, this thread approaches the generation of gapless incrementing identifier, but I am also thinking about generating identifiers within the application layer and restoring the value on save failure:

private int PrevSequenceId;
private int SequenceId;

private void SetCarNr()
{
    var carsToSave = ChangeTracker.Entries().Select(e => e.Entity).OfType<Car>();
    foreach (var c in carsToSave)
    {
        c.CarNr = Interlocked.Increment(ref SequenceId);
    }
}

public override int SaveChanges()
{
    try
    {
        SetCarNr();
        return base.SaveChanges();
        // locking might be required here for thread safety
        PrevSequenceId = SequenceId;
    }
    catch (Exception exc)
    {
        // log stuff if needed

        // locking might be required here for thread safety
        SequenceId = PrevSequenceId;
    }
}

However, this solution may work only if identifiers are generated by the application layer only.


Segment Intersection — Failing on Unknown Edge Cases

Failure cases

I ran your program and was able to find an endless number of failures.  My technique was to have one line touch the origin (0,0) and then generate all lines that pass directly through the origin by simply choosing mirrored coordinates.  I was hoping to find roundoff errors and I did.  Here are just a small sampling of failure cases, all of which print "Do not intersect" instead of "intersect":

0 0 0 5 7 29 -7 -29
0 0 0 5 11 -30 -11 30
0 0 0 5 11 -15 -11 15
0 0 0 5 11 25 -11 -25
0 0 0 5 13 -30 -13 30
0 0 0 5 13 -15 -13 15
0 0 0 5 13 27 -13 -27
0 0 0 5 14 29 -14 -29
0 0 0 5 19 21 -19 -21
0 0 0 5 21 23 -21 -23
0 0 0 5 21 27 -21 -27
0 0 0 5 22 -30 -22 30
0 0 0 5 22 -15 -22 15
0 0 0 5 22 25 -22 -25
0 0 0 5 23 -26 -23 26
0 0 0 5 23 -13 -23 13
0 0 0 5 23 27 -23 -27
0 0 0 5 25 -29 -25 29
0 0 0 5 25 7 -25 -7
0 0 0 5 25 14 -25 -14
0 0 0 5 25 28 -25 -28
0 0 0 5 26 -30 -26 30
0 0 0 5 26 -15 -26 15
0 0 0 5 26 27 -26 -27
0 0 0 5 27 29 -27 -29
0 0 0 5 28 29 -28 -29
0 0 0 5 29 15 -29 -15

Floating point?

My personal opinion about solving this problem correctly is that if your coordinates are constrained to be within -1000..1000, then you can do the whole problem using integers and not use floating point at all.

What you would need to do is create a fraction class that holds a numerator and denominator.  The fraction class needs to be able to: multiply, divide, add, subtract, compare (i.e. everything you are doing with your doubles).  Since the range of coordinates is so small, you shouldn't have a problem with overflow.  By doing this you will be safe from roundoff errors.


Functions that converts day of year to month and day and reverse with error checking

Incorrect yearday limit

// if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 366))) {
if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 365))) {
//                                                             365

month_day() and day_of_year() should use consistent types for month.  Suggest int for both.

// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year,         int month, int day) {

month_day() and day_of_year() should use consistent types for yearday.  Suggest int for both.

// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year, int month, int day) {
void month_day(unsigned int year, int yearday, int *pmonth, int *pday) {

Leap year calculation leap = ((year... is good back to 1583.  For years 4 to 1582 it is  leap = (year % 4 == 0);  1582 has other complications.  Before 4 has complications.
Suggest month_day() return int to indicate success or failure.


Checking screen sizes for responsive site

Personally, I think it's better to make the breaks according to the content of the site, rather than to a fixed size.

This is even more true nowadays with docens of different screen sizes for each type of device.

You should make sure the site will always look good by making the breaks work depending on the design, and no the other way around.


Line by line analysis

Use four spaces to indent python code. Never use tabs.

from random import randint
from sys import exit
import os

It is a good practice to do top-level imports (without importing module members). This way it's easier to understand what package the methods come from.

os.system('clear')
print "Welcome to the dice rolling simulator!"
raw_input("Press enter to begin.")

total = 0

completed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Use list comprehensions.

def roll():

Roll method is confusing. You expect it to roll a die, but it processes iterations of the game. A while loop would be more explicit here.

os.system('clear')
die1 = randint(1, 6)
die2 = randint(1, 6)
global total

Global variables are no-no. Never.

total = die1 + die2
storetotal()
print "Die 1: %d \nDie 2: %d \nTotal: %d." % (die1, die2, total)
print "\n\nRoll again?"
roll_again = raw_input("Press enter to roll again, type 'stats' to view scores, or 'quit' to exit.\n> ")

You're exceeding recommended 80 column length limit.

if roll_again == "":
    roll()

See how I changed this block in a code below.

elif roll_again == "stats":
    stats()
elif roll_again == "quit":
    exit(0)

Return from the method is sufficient here.

else:
    print "I don't know what that means so you get to roll again."
    raw_input("> ")
    roll()

def stats():
global total
print "2s: %d \n3s: %d \n4s: %d \n5s: %d \n6s: %d \n7s: %d \n8s: %d" % (completed[0],                                                                     completed[1], completed[2], completed[3],
                                            completed[4], completed[5], completed[6])
print "9s: %d \n10s: %d \n11s: %d \n12s: %d""" % (completed[7], completed[8],
                                                completed[9], completed[10])

Indentation here is completely messed up.

raw_input("")
roll()

def storetotal():

PEP8: store_total.

if total == 2:
    completed[0] += 1
elif total == 3:
    completed[1] += 1
elif total == 4:
    completed[2] += 1
elif total == 5:
    completed[3] += 1
elif total == 6:
    completed[4] += 1
elif total == 7:
    completed[5] += 1
elif total == 8:
    completed[6] += 1
elif total == 9:
    completed[7] += 1
elif total == 10:
    completed[8] += 1
elif total == 11:
    completed[9] += 1
else:
    completed[10] += 1

roll()

Improved code

I simplified your roll method to roll2d6 and moved all the other code into main.

import random
import os

def roll2d6():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    return die1 + die2

def display_stats(stats):
    for i, result in enumerate(stats):
        print "%ds: %d" % (i + 2, result)

def update_stats(total, stats):
    stats[total - 2] += 1
    return stats

def main():
    stats = [0 for _ in xrange(10)]

    os.system('clear')
    print "Welcome to the dice rolling simulator!"
    raw_input("Press enter to begin.")
    while True:
        os.system('clear')
        total = roll2d6()
        stats = update_stats(total, stats)
        print "Die 1: %d \nDie 2: %d \nTotal: %d." % (die1, die2, total)
        print "\n\nRoll again?"
        roll_again = raw_input((
                "Press enter to roll again, type 'stats' to view scores, "
                "or 'quit' to exit.\n> "))
        if roll_again.lower() == "stats":
            display_stats(stats)
        elif roll_again.lower() == "quit":
            break
        elif roll_again.lower() != "":
            print "I don't know what that means so you get to roll again."

if __name__ == "__main__":
    main()


Transform a javascript object to an array based on value of each key in the original object

const ingredientNames = Object.keys(props.ingredients);

Just be aware that anything that iterates/enumerates an object's keys (Object.keys, for-in, etc.) does not guarantee order. So it might not always be "salad, cheese, cheese, meat, meat" in the end. It just happens that most browsers iterate in the order they were created/added to the object, which is why it appears like so. If you want order, use an array to begin with.

    let burgerIngredientElements = [];
    for(let i=0; i<props.ingredients[ingredientName]; i++) {
        burgerIngredientElements.push(
            <BurgerIngredient type={ingredientName} />
        )
    }
    return [...burgerIngredientElements]

Also, I don't think this code is doing what you think it's doing. You're pushing to an existing array, then spreading it's contents into another array. You're essentially just shallow-cloning. It might look rendered correctly (probably because JSX now does fragments) but the structure is questionable.

Anyways, a more functional way to iterate from 0 to N is to create an array of N items (it doesn't matter what the values are) and operate on that array using array methods. One way this can be achieved is using Array and array.fill.

Also, instead of a loop and an outer variable holding an array, you can use array.reduce with the accumulator being that array. That way, you don't have that extra mutable variable.

Your code could look like this:

function getBurgerIngredients() {
  const ingredients = props.ingredients

  return Object.keys(ingredients).reduce((c, ingredientName) => {
    const range = Array(ingredients[ingredientName]).fill()

    return [...c, ...range.map(() => (<BurgerIngredient type={ingredientName} />))]
  }, []);
}


Which syntax is preferred to create a Hash in Ruby on Rails?

It depends. I prefer the newer syntax because I feel that it is more readable. As others have pointed out, however, the newer syntax is only compatible with Ruby 1.9.2+.

You should be aware, however, that the new syntax does not entirely replace the hash rocket syntax. This is because you can only use the newer syntax with symbols.

{ "text": :hello } #=> syntax error, unexpected ':', expecting =>

If you want to use strings and methods, you will still need to use the has rocket:

{ method_name => :hello }
{ "a_string" => :hello }

Personally, from my experience of reading and watching educational materials, the newer syntax is preferred where possible. It's also less keystrokes: : instead of => is easier for me.


I can think of mutliple ways to improve this code.

First, error handling. In your case, not receiving data from your API call may cause your program to crash.

You will have to add an error variable in your state :

this.state = {
    items: [],
    isLoading: true,
    error: ''
};

And add a .catch at the end of your fetch function (or use the new async/await syntax surrounded by a try/catch block).

You should also put your response formatting here instead of the rendering function, to avoid reformatting your data everytime your component is rerendered :

fetch(`http://opentable.herokuapp.com/api/restaurants?city=${city}`)
    .then(res => res.json())
    .then(json => {
        this.setState({
            isLoading: false,
            items: Object.values(json.restaurants) //Data formatting
        });
    })
    .catch(error =>{
        this.setState({
            isLoading: false,
            error // Sends the error object (or message, I am not sure about the exact syntax)
        });
    });

I also noticed that you set your isLoading state to true when you finished loading and to false in your initial state so I reversed it.

Now, the rendering.

JSX allows you to put conditions inside your HTML, making the syntax of your render way more readable and avoid code duplication :

render() {
    const { isLoading, items, error } = this.state;

    return (

                            {isLoading && <Spinner />}
                            {error &&
Error : {error}
}
                            {!isLoading && !items.length &&
No Data
}

 // Did you forget this node ?
                                {items.map(({ id, reserve_url, address, price, name }) => //Won't do anything if the items array is empty

                                            {name}
                                        {" "}
                                        | {address}{" "}
                                        | Price rating:{" "}
                                        {price}

                                )}

    )
}

I also deconstructed your parameters in the map function.

Working example :

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            items: [],
            isLoading: true,
            error: ''
        };
    }

    componentDidMount() {
        const urlParams = new URLSearchParams(window.location.search);
        const city = urlParams.get("city");

        fetch(`http://opentable.herokuapp.com/api/restaurants?city=London`) // Hard coded London
            .then(res => res.json())
            .then(json => {
                setTimeout(() => { //Just to see the loading element / spinner
                    this.setState({
                        isLoading: false,
                        items: Object.values(json.restaurants)
                    });
                }, 1500)
            })
            .catch(error =>{
                this.setState({
                    isLoading: false,
                    error
                });
            });
    }

    render() {
        const { isLoading, items, error } = this.state;

        return (

                                {isLoading &&
Loading...
}
                                {error &&
Error : {error}
}
                                {!isLoading && !items.length &&
No Data
}

                                    {items.map(({ id, reserve_url, address, price, name }) =>

                                                {name}
                                            {" "}
                                            | {address}{" "}
                                            | Price rating:{" "}
                                            {price}

                                    )}

        )
    }
}

ReactDOM.render(<App/>, document.getElementById('root'))


Calculate the Euler-Mascheroni constant without the math module

Computation of logsum and logsum1 in gamma() are suboptimal. You do costly operations of raising to power, and recompute factorial on each iteration (the latter invokes the quadratic time complexity BTW). Notice that in the \$\sum \dfrac{(-1)^{r-1} k^{r+1}}{(r+1)(r-1)!}\$ a consecutive term can be expressed via the previous one, as\$T_{r+1} = -k\dfrac{r+1}{(r+2)r} T_n\$. Instead of computing each term from scratch, use this recurrence, and enjoy a significant performance boost.

Converting the summation into a Horner schema would likely improve the accuracy, that is to achieve the desired number of digits you'd need less number of terms.
Tree loops in lntwo cry to become a function.


Hash code

  it shouldn't matter what order points 1, 2 and 3 are in

There is a way to ensure that: Sorting. Sort your points locally within your hashcode method, first by their x value, then by their y value.

The algorithm for the hashcode could be this one, as also commented above by radarbob. I will leave it for you to adapt it to your own class.

General

Your class has public fields. It is better to make these private and grant public access to them (if needed) via properties. In this case, for something like a triangle, making it a struct instead of a class might be also suitable.

The following piece of code does not make much sense:

var hashCode = -305700999;
hashCode = hashCode * -1521134295 + [...]

I already added the link to a good implementation of the hash code method above, so I won't go into detail about the algorithm. But what you are doing in the above two lines before the addition is just calculating what could simply be a constant. The compiler will probably even precompute the -305700999 * -1521134295 part. Multiplying the hash code with a prime number (like 23 or 31) should happen before every addition of another value.


Calling a function within stored procedure to derive a value

Calling a function from a stored procedure is absolutely fine.

As far as the code goes, you could reduce the number of statements.

e.g. instead of

 IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
     BEGIN
        SELECT @timeDifference = @timeDifferenceInHours
     END
  ELSE
    BEGIN
        SELECT @timeDifference = -1
    END

I would suggest

  select @timedifference =
    case when @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
         then @timeDifferenceInHours
         else -1
    end


You don't need the bitmasks here, you can do with just basic arithmetic.
You're right that a naive modulo would generate biased letter combinations. Therefore the typical pattern is:

$letters = "aeiouy";
$len = length($letters);
$limit = 255 / $len * $len;   # this must be integer arithmetic
$limit = 255 - 255 % $len;    # alternative spelling for the above line

while (($byte = next_byte()) >= $limit) {
    next;
}
return $letters[$byte % $len];

This pattern consumes less random numbers than yours and still generates a fair distribution.

Your code should not output a space at the end of the line.

To make your code testable, you should write a sub that generates a password from a given stream of bytes. Since this is the completely deterministic part, it's easy to test.

Make sure that the call to read succeeds, since otherwise your randomness gets replaced with undefinedness.

You should use the same code pattern to generate the consonants and vowels, so that the code looks more symmetric. But that's a minor point.


Optimizing nested if statements in switch

I agree with Romoku.  Unless there is a definite requirement to make this faster and a noticeable effect on performance of your application within this method I would consider making it more DRY, more developer friendly and less procedural.

Without more code and explanation of whats there here are some things I would consider:

Try and remove duplicated code.  I notice you repeat your if(u1 == "piece" ... code everywhere.  Consider moving that into a method and passing in the parameters required.

private int GetConversion(UnitsEnum units, int pieceGramsMultipler, int otherMultipler)
{
  return units == UnitsEnum.Piece || units == UnitsEnum.Gram
                 ? pieceGramsMultipler
                 : otherMultipler;
}

Then used like

if (u == 2)
{
   result = quantity * GetConversion(u1, y, z);
}

Consider changing your string literals into enumerations. So "piece" and "gram" might become:

private enum UnitsEnum
{
  Piece,
  Gram
}

Consider changing your case statements into constants or enumerations.  So rather than case 1, it might be case Metric.Ml or ML or Milliliters etc
Offer better names for your variables.  u1, x, y, z gives me no idea of what they are trying to do.
Use if else instead of 2 if statements.  If u == 2 then there is no chance that it will be == 1 so convert your if's into if elses to make that more obvious.

Otherwise, perhaps posting the full code that this piece resides in might get your more help and suggestions.  I get the feeling that there is more help this community can offer you here than just what you have posted.