Functions taking iterables: peaks, compress, and skipper

Your comments are good, but they should all be written as docstrings instead.

When working with iterators, itertools and generator expressions are your friend.  peaks() works with three iterators, so zip() is useful.

Since the function accepts an iterable, it seems fitting that it should be a generator rather than returning a list.

Python supports double-ended inequalities.

from itertools import tee

def peaks(iterable):
    """Generates values in the iterable that are greater than the value
    preceding and following them."""
    before, this, after = tee(iter(iterable), 3)
    next(this)
    next(after)
    next(after)
    for prev, curr, succ in zip(before, this, after):
        if prev < curr > succ:
            yield curr

If you wanted to keep the old interface, which returns a list, then a list comprehension would be a good way to write it.

def peaks(iterable):
    """Returns a list of values in the iterable that are greater than the
    preceding and following value."""
    xs, ys, zs = tee(iter(iterable), 3)
    next(ys)
    next(zs)
    next(zs)
    return [y for (x, y, z) in zip(xs, ys, zs) if x < y > z]

I find your compress() weird, in that it sorts the results.

You can implement the function using just a generator expression.

def compress(values, incl_excl):
    """Keeping only values whose corresponding entry in incl_excl is true,
    generates the sorted filtered list."""
    yield from sorted(val for val, include in zip(values, incl_excl) if include)

In skipper(), the two occurrences of yield next(itr) should be combined.

def skipper(iterable, n=0):
    """Generator that yields the first element, then skips n values between
    results, until the input is exhausted."""
    iterable = iter(iterable)
    while True:
        yield next(iterable)
        for _ in range(n):
            next(iterable)


This cache feels like it could be used like a dict but is nowhere near it. Renaming get to __getitem__ and put to __setitem__ would provide a neater feeling here. Even better, since your main storage is a dict, why not subclass it directly. You would benefit of its interface with almost no additional cost. Just replace every self.dic with a simple self.

Then, to support your requirements, you would implement get based on dict.get and put would be plain __setitem__:

class LruCache(dict):
    ...
    def get(self, key):
        return super().get(key, -1)

    put = __setitem__

Second, you seem to envision using this cache only to store integer keys and integer values. This is a strong assumption here and the cache will misbehave if you ever try to .put(None, 42); or even .put(0, 42) for that matter as you do not distinguish it in you test while not self.history_dic[i]:. Instead, you could delete the associated entry and check for existence (while i not in self.history:).

Lastly, your naming can be improved. _dic as part of names is implementation detail and does not really add meaningful value here; count is the number of updates and should probably be named after that fact; as well as current being the currently know "index" of the least recently used element.

Proposed improvements:

from contextlib import suppress
from typing import Any

class LruCache(dict):
    def __init__(self, capacity: int):
        super().__init__()
        self.capacity = capacity
        self._least_recent = 0
        self._number_of_updates = 0
        self._history = {}
        self._keys_indexes = {}

    def get(self, key: Any) -> Any:
        return super().get(key, -1)

    def __getitem__(self, key: Any) -> Any:
        value = super().__getitem__(key)
        self._update_history(key)
        return value

    def __setitem__(self, key: Any, value: Any):
        self._update_history(key)
        while key not in self and len(self) >= self.capacity:
            while self._least_recent not in self._hitory:
                self._least_recent += 1
            del self[self._history[self._least_recent]]
        super().__setitem__(key, value)

    put = __setitem__

    def __delitem__(self, key: Any):
        super().__delitem__(key)
        index = self._keys_indexes.pop(key)
        del self._history[index]
        if index == self._least_recent:
            self._least_recent += 1

    def _update_history(self, key: Any):
        with suppress(KeyError):
            del self._history[self._keys_indexes[key]]
        self._history[self._number_of_updates] = key
        self._keys_indexes[key] = self._number_of_updates
        self._number_of_updates += 1

You’ll note that I changed the check in capacity into a while loop in case someone would change the cache size halfway through the program such as:

cache = LruCache(10)
cache.put(…)
…
cache.put(…)
cache.capacity = 2
cache.put(…)  # cache shrink from 10 to 2 capacity

Dropping elements as soon as the cache.capacity = 2 line is executed is left as an exercise to the reader.


Implement String's valueOf function, code review request

Since it's easy to convert integer digits to their character values ('0' = 0x30..'9' = 0x39), why not:

public static String stringValueOf(int value) {
  if (value == 0) return "0";
  if (value == Integer.MIN_VALUE) return "-2147483648";

  final boolean negative = value < 0;
  if (negative) value = -value;

  final StringBuilder buf = new StringBuilder();
  while (value != 0) {
    int digit = value % 10;
    buf.append( (char)(0x30 + digit) );
    value = value / 10;
  }
  if (negative) buf.append('-');

  return buf.reverse().toString();
}

It's easy to test this for correctness over the int range; but to do so, I'd extract the StringBuilder construction from the method into a static class variable and just call buf.setLength(0) each time.


Does this method contain multiple implementations?

Seemed fine at first, then I took another look...

The validation function displays the error message?

I'm sorry, but that's indeed a violation of SRP. You'd be better off returning a ValidationResult which you could use. You already HAVE this validation result... so in a way, you've already done what I said.

What's wrong is that your function names do not reflect this. You call validateUsername, but it also displays errors. Rather than changing the validation method to return a ValidationResult (which would imply taking out validateUsername and doing everything in doLogin, you should change the function name instead.


Simple errors
This code includes <cmath> and <cstdlib>, but then calls unqualified sqrt and strtoul.  Implementations are not required to import these names to the global namespace, so they should be qualified with std:: (or include <math.h> and <stdlib.h> instead).
An unsigned long may not be big enough to hold the integer part of sqrt(n) (for example, if Integer is a 128-bit type, and unsigned long is only 32 bits).  The only safe way (short of heavy template metaprogramming) is to use Integer for the counter.
It's probably worth explicitly returning false for 0 and 1, and for any negative values that crazy people feel compelled to test.
Style
We usually use snake_case (or in some projects, camelCase) for functions, and reserve PascalCase for composite types.  But go along with the conventions of your collaborators where necessary.
Performance
I did manage to get a small improvement (from 9½ seconds down to about 9 here, compiled with gcc -march=native -03) by splitting the condition into two (I think this might be allowing the compiler to execute both tests together).
The best results were obtained by simply parallelizing the algorithm (std::atomic<bool> is quite cheap on my hardware):
#include <atomic>
#include <cmath>
#include <cstdlib>

template <class Integral>
bool is_prime(const Integral &n){
    // Get rid of base cases
    if (n < 2) return false;
    if (n==2 || n==3) return true;

    if (n%2 == 0 || n%3 == 0) return false;

    auto const top = (Integral)std::sqrt(n) + 1;
    std::atomic<bool> is_prime = true;
#pragma omp parallel for
    for (Integral i = 3;  i < top;  i += 6) {
        if (!is_prime) continue;
        if (n%(i+2) == 0) is_prime = false;
        if (n%(i+4) == 0) is_prime = false;
    }
    return is_prime;
}

#include <iostream>
int main(int argc, char* argv[]){
    // Check passed arguments
    if (argc != 2){
        std::cerr << "Format: " << argv[0] << " <integer>" << std::endl;
        return -1;
    }

    if (is_prime(std::strtoul(argv[1], NULL, 0))) return 0;
    else return 1;
}

This got my time down to under 1½ seconds elapsed time, making full use of 8 cores.
I don't know how I can break instead of continue in an OpenMP parallel loop, but I found it didn't hurt too much with a simple composite number such as 625, which evaluated in around 20ms.
Loop unrolling
I did gain a speedup of a further 20% or so by unrolling the loop to consider 30 factors at a time:
#include <atomic>
#include <cmath>
#include <cstdlib>
#include <initializer_list>

template<class Integral>
bool is_prime(const Integral &n)
{
    // Values under 30
    if (n < 2) return false;
    for (Integral i: { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 })
        if (n%i == 0) return n==i;

    auto const top = (Integral)std::sqrt(n) + 1;
    std::atomic<bool> is_prime = true;
#pragma omp parallel for
    for (Integral i = 30;  i < top;  i += 30) {
        if (!is_prime) continue;
        if (n%(i+1) == 0) is_prime = false;
        if (n%(i+7) == 0) is_prime = false;
        if (n%(i+11) == 0) is_prime = false;
        if (n%(i+13) == 0) is_prime = false;
        if (n%(i+17) == 0) is_prime = false;
        if (n%(i+19) == 0) is_prime = false;
        if (n%(i+23) == 0) is_prime = false;
        if (n%(i+29) == 0) is_prime = false;
    }
    return is_prime;
}

int main()
{
    return is_prime(0)
        || is_prime(1)
        || !is_prime(2)
        || is_prime(49)
        || is_prime(961)
        || !is_prime(18446744073709551557u);
}

(I've also simplified main() here, to just run auto tests rather than requiring an argument).


Using the tips of the justforfunc #16 video, you could make your tests using a table (tt = testing table) and then iterate on it (tc = test case).

Your test could then look like this:

func TestSigHandler(t *testing.T) {
    jsonHeaders := map[string]string{"Content-Type": "application/json"}

    tt := []struct {
        name    string
        method  string
        uri     string
        payload []byte
        headers map[string]string
    }{
        {"get item", "GET", "/1/sig/id/2021205", nil, nil},
        {"post new item", "POST", "/1/sig/id/2021205", []byte(`{"raw": "a new sig"}`), jsonHeaders},
        {"delete item", "DELETE", "/1/sig/id/1000345", nil, nil},
    }

    for _, tc := range tt {
        t.Run(tc.name, func(t *testing.T) {
            var payload io.Reader
            if tc.payload != nil {
                payload = bytes.NewBuffer(tc.payload)
            }
            req, err := http.NewRequest(tc.method, server.URL+tc.uri, payload)
            if err != nil {
                t.Fatalf("could not create request: %v", err)
            }

            for key, value := range tc.headers {
                req.Header.Set(key, value)
            }

            res, err := http.DefaultClient.Do(req)
            if err != nil {
                t.Fatalf("could not send request: %v", err)
            }

            if res.StatusCode != http.StatusOK {
                t.Fatalf("expected status OK; got %v", res.Status)
            }
        })
    }
}

Looking at your TestMain, I have the feeling that you are doing only integration tests (from the request to the database).

You should split you tests to the individual layers (the current one if for routing: it could use a mocked DB).

With this approach, the TestMain could be deleted (do only the setup that is necessary for each test).


C Primer Plus - Chapter 4 - Task 6 (string output)

Small sugggestion for printWhitespace(). You could do the following:

void printWhitespace(const unsigned int times) {
    printf("%*s", times, " ");
}

I have made the function argument const as it probably isn't meant to be modified. it is generally a good idea to be as "const" as possible as this avoids the mistake of writing to a variable that should be read-only.

I would put the array declarations at the top of the function before any of the code with a blank line between the declarations and the first line of code.

The function scanf can be used with caution... it can lead to buffer overflow attacks in the way it is used in your code. If the user enters a string longer than 19 characters (last character would be filled in as a null terminator in the buffer), scanf will just write on past the end of the buffer.

You could help guard against this by using scanf("%19s", firstName); and scanf("%19s", lastName);. As @chux points out the length is one less than the buffer size. This is because "String input conversions store a terminating null byte ('\0') to  mark end of the input; the maximum field width does not include this terminator." -- quote from man page.

Looked into this a little more and this SO answer, the author says:

  Note that the POSIX 2008 (2013) version of the scanf() family of
  functions supports a format modifier m (an assignment-allocation
  character) for string inputs (%s, %c, %[). Instead of taking a char *
  argument, it takes a char ** argument, and it allocates the necessary
  space for the value it reads

That would be a useful way of avoiding buffer overflow, but you must remember to free() the buffer returned.

The variable numOfWhitespace can also be const. Might put that to top of function too.

Your last bit of code that tries to align the numbers to the end of the words will only align properly if the string length is 9 or less. If the string length is greater then the number will be double digits so you could account for this.

Add return 0; to the end of the function. You reach the end of a non-void function without returning anything...

Hope that helps :)


Simplifying

        for(int i = 0; i < disjointSet.size(); i++) {
            Map<Integer, Set<Integer>> map = disjointSet.get(i);
            if(map.containsKey(first)) {
                firstSet = map.get(first);
            } else if(map.containsKey(second)) {
                secondSet = map.get(second);
            }
        }

Consider instead

        for (Map<Integer, Set<Integer>> map : disjointSet) {
            if (firstSet == null) {
                firstSet = map.get(first);
            }

            if (secondSet == null) {
                secondSet = map.get(second);
            }

            if (firstSet != null && secondSet != null) {
                break;
            }
        }

You don't need i.  Java can iterate over a collection directly, which saves us a line of code.

You don't need to check containsKey before doing get.  If containsKey is false, then get will return null.

You might as well stop as soon as both sets are found.  You don't need to keep going.

A linear scan over all the values is something like \$\mathcal{O}(N \cdot Q)\$, assuming the number of merges is proportional to the number of queries.  Because you have to do one linear scan for each merge.  However, there is an alternative solution that is closer to \$\mathcal{O}(Q)\$.

Alternative data structure

        DisjointSet ds = new DisjointSet();

Consider

        DisjointSet ds = new DisjointSet(N + 1);

Now you can change from

    private List<Map<Integer, Set<Integer>>> disjointSet;

to something fixed size.  The normal representation for a disjoint set is a parent pointer tree with ranks added.  In this case, we need to track the sizes and can use those to represent the rank.  Consider

public class DisjointSet {

    private int[] parents;
    private int[] sizes;

    DisjointSet(int N) {
        parents = new int[N];
        sizes = new int[N];
    }

    public void makeSet(int i) {
        parents[i] = i;
        sizes[i] = 1;
    }

    public void union(int a, int b) {
        int first = find(a);
        int second = find(b);

        // if already part of the same set, no need to union
        if (first == second) {
            return;
        }

        if (sizes[first] < sizes[second]) {
            parents[first] = second;
            sizes[second] += sizes[first];
        } else {
            parents[second] = first;
            sizes[first] += sizes[second];
        }
    }

    public int find(int i) {
        // if not the root
        if (parents[i] != i) {
            // Make the parent the root, so that it will recurse at most once
            // on subsequent calls.
            parents[i] = find(parents[i]);
        }

        // Return the root (as the parent is always the root by this point).
        return parents[i];
    }

    public int getSetSize(int i) {
        return sizes[find(parents[i])];
    }

}

The parents array stores the immediate parent of any element.  If an element is alone in a set, it is its own parent.  Root nodes (terminators) are also their own parents.

For a root node, the sizes array holds the size of the set.  For other nodes, it holds junk data.

This uses both union-by-rank and path compression for an optimal runtime.  It's also reasonably efficient in space, requiring only two integers for each element.


Simple function to generate an HTML-safe string

The Attack
What you are basically talking about is DOM based XSS.
But it's a self-XSS, so the only possible attack vector might be via ClickJacking (depending on the used browser).
Still, it should be defended against, especially for usability reasons.
Proper Defense
Here is OWASPs guide on preventing DOM based XSS. Basically, you should first HTML encode the input, and then JavaScript encode.
For your example, the second part doesn't seem necessary, just encoding <, >, ' and " should be enough.
Your Defense
Well, your defense works.
It could be simplified a bit though. There really doesn't seem to be a need to set this.textContent, and I also do not see the need for replace(/^\s+|\s+$/g, '') (or am I missing something here? Browser compatibility maybe?).
That would leave you with
var safetext = (function(text){
    this.textContent = text;
    return this.innerHTML;
}).bind(document.createElement('div'));

The reason this works seems to be the way textContent works.
But this really seems to be more of a side-effect, and it is never a good idea to use those for security related things.
Conclusion
Regarding performance, security, and readability, a simple replace for <, >, ' and " with their HTML representation seems to be preferable to your method.


Does this one-line text-based terrain generator go against standards?

What does THE standard say about imports :

  Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

What else could easily be improved in your code ?

_ is a usual name for variable whose value is not going to be used.
you do not need to create a list : you can use generator expressions by getting rid of brackets.
you can get rid of the duplicated prefix and suffix in the different choices.
in Python 2.*, you do not need parenthesis to call print.

Your code would become :

from random import choice
from time import sleep
print ''.join('\033[7;' + choice(['1;32','32','1;33','34']) + 'm  \033[0m' for _ in range(40))
sleep(0.5)


Just some thoughts:

Not sure why you don't just flatten the expression tree with a visitor and then return the collection of expressions. This leads to simpler code:

class Program
{
    static void Main(string[] args)
    {
        Expression<Func<int, int, int>> expr = (a, b) => ((a + b) * (a - b));

        //Flatten the entire tree.
        foreach (var elem in expr.Flatten())
        {
            Console.WriteLine(elem.NodeType);
        }

        //Use Linq to select what you want.
        foreach (var elem in expr.Flatten().Where(t => t.NodeType == ExpressionType.Parameter))
        {
            Console.WriteLine(elem.NodeType);
        }
        Console.ReadKey();
    }
}

public static class ExpressionExtensions
{
    public static IEnumerable<Expression> Flatten(this Expression expr)
    {
        return Visitor.Flatten(expr);
    }
}

public sealed class Visitor : ExpressionVisitor
{
    private readonly Action<Expression> nodeAction;

    private Visitor(Action<Expression> nodeAction)
    {
        this.nodeAction = nodeAction;
    }

    public override Expression Visit(Expression node)
    {
        nodeAction(node);
        return base.Visit(node);
    }

    public static IEnumerable<Expression> Flatten(Expression expr)
    {
        var ret = new List<Expression>();
        var visitor = new Visitor(t => ret.Add(t));
        visitor.Visit(expr);
        return ret;
    }
}

Even if, for some reason, you absolutely need to have lazy execution, you're better off making your own expression iterator, rather than trying to pause the execution of a class meant to eagerly visit everything.


Function and method debugging decorator - Part 2

You can improve the following:

            if getargspec(function).args[0] != "self":
                print(self.__format_debug_string(function, *args, **kwargs))
            else:
                print(self.__format_debug_string(function, *args, **kwargs))
                print("[debug] Parent attributes: {}".format(pformat(args[0].__dict__)))

If the code is executed no matter the statement, and it always goes first, move it above the condition: (and don't forget to reverse the condition)

            print(self.__format_debug_string(function, *args, **kwargs))
            if getargspec(function).args[0] == "self":
                print("[debug] Parent attributes: {}".format(pformat(args[0].__dict__)))

As for this:

    debug_string = ""
    debug_string += "[debug] {}\n".format(pformat(function))
    debug_string += "[debug] Passed args: {}\n".format(pformat(args))
    debug_string += "[debug] Passed kwargs: {}\n".format(pformat(kwargs))
    debug_string += "[debug] Locals: {}".format(pformat(function.__code__.co_varnames))
    return debug_string

You can remove the = "" entirely:

    debug_string =  "[debug] {}\n".format(pformat(function))
    debug_string += "[debug] Passed args: {}\n".format(pformat(args))
    debug_string += "[debug] Passed kwargs: {}\n".format(pformat(kwargs))
    return debug_string + "[debug] Locals: {}".format(pformat(function.__code__.co_varnames))

It may not look as visually stimulating, but, it's not as redundant.

  Is it a good idea to create an empty string, and then add to, and re-assign it to build an output string?

If you were directly printing these then it would be a bad idea, but in this case, not really. However, I suppose you could move them to an object, or an array and return the result of a join function.

You could even return it as an array, and print each [debug] result. Which would remove the need for the \ns at the end, and DRY up the [debug] at the beginning of the strings (put it in the loop, not altogether)

You've got a few too long lines, by PEP8 standard:

debug -- Whether or not you want to output debug info. Generally, a global DEBUG variable is passed in here.
debug_string += "[debug] Locals: {}".format(pformat(function.__code__.co_varnames))
print(self.__format_debug_string(function, *args, **kwargs))
print("[debug] Parent attributes: {}".format(pformat(args[0].__dict__)))

As for your documentation:

function, it will print out the arguments of

Keyword arguments:

I'm a bit confused by that, grammatically.

__call__ is a more complex function (in my mind, at least) than __format_debug_string, but it has no documentation.

  Is this Python 3, and Python 2.7 compatible?

It ran fine when I tested it in Python 2.7.9 and 3.1.1


I would declare as required by all classes. It is easy enough to leave an empty method stub in the sub class.


From a quick glance, I would say you're on the right track. It might be worthwhile to bust up the work being done by Config into two components:

Config: the pure configuration elements; workers, queue, rate, burst; and
Env: the (effectful) environment state; supplier, performer, collector.

And then think about creating a few boiler-plate functions (not including the polymorphic Env bits):
new :: Config -> IO Env
close :: Env -> IO ()
check :: Env -> IO Text

withConfig :: Config -> (Config -> Env -> IO ()) -> IO ()
withConfig c cont = bracket (new c) close (cont c)

Once you have this, you can create a new environment, play around with it, and properly close it in a robust way. As it stands, and given my workflow preferences, I would think that runLoadN is too monolithic for easy maintenance and extension.
General descriptions of these refactors include the handle pattern and the service pattern. The three layer cake is classic also though I suspect you don't need the extra complexity.
With runLoadN freed of environment setup and teardown you'll be able to see more clearly the key components of the process.
A few vague guesses about other aspect of the code:

I would work towards refactoring away the convenience functions. Do you really need the extra monadic complexity? Can it all be IO?

the collector looks like a WriterT or logger, and might be simplified by using those patterns.

There are a lot of polymorphic types being thrown around. Both m and IO, in particular, exists in Config, which might suggest some refactoring needed. I reckon you could aim for just an Env without any polymorphism.

If you're always altering pure Config types (with toInt), then it's better to change the Config types instead.

I would suggest that best practice is to define a defaultConfig :: Config explicitly, rather than run through Data.Default and use the anonymising def pattern


Prime Number Generator (6n + 1 or 6n - 1)

How about:

import math

limit = 100000
primes = [2,3]

def calc_potential_primes(n):
    return [6*n-1, 6*n+1]

def is_prime(x):
    for p in primes:
        if p <= math.sqrt(x):
            if x % p == 0:
                return False
        else:
            break
    return True

n = 1
while True:
    possible_primes = calc_potential_primes(n)
    new_primes = [x for x in possible_primes if is_prime(x) and x < limit]
    primes += new_primes

    if sum(i > limit for i in possible_primes) > 0:
        break
    n += 1

print primes

We don't have to check every prime #, only primes up to sqrt(x).

You run the same code block on 2 different inputs, which can lead to potential bugs where you forget to update variable names as pointed out by Aemyl. If you're going to re-use the same code, it's better to put it into a function to keep the code readable and prevent potential bugs.

Maintaining our code logic inside a function also prevents us from having to update a global variable, which can also lead to additional bugs if at any point we forget to or accidentally update it.

Encapsulating your prime calculations within a function that returns a list of primes will also allow us to make updates to how we generate our primes without having to update the rest of our code. By the same logic, if we want to update how we check if a # is prime (maybe we think of a more efficient solution), we only have to update it in one place, instead of twice in the current case. In this case, functions keep our code maintainable and easy to follow.

By always returning a list, if at any point we want to scale or change how we generate prime number candidates, we can simply update the code logic and return the same object as before (a list) and the rest of our code should work as is. In the current case, we would have to set additional variables, then repeat the prime check code block for each additional variable.

Combining lists with Python's list comprehensions allow us to clearly and easily filter for the items (prime #s) that we want, while maintaining readability and efficiency.

Basically, consider using functions and list comprehensions to keep code readable, simple, maintainable and therefore hopefully as bug-free as possible.

With this I get a timeit of 208 ms ± 682 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) when calculating primes up to 100000

versus 4.28 s ± 52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) with yours.


This doesn't do much, so if it's the bottleneck it must be because you're calling it a lot. The first thing to do is to look at the calling pattern. If there are lots of calls with the same value of lambda then you may be able to calculate alpha and beta once rather than each time; you may even be able to cache fg and share it between lots of calls with the same lambda and oversRemaining.

On the level of microoptimisation, pow(lambdaLocal, power + 1.0) is mathematically equal to lambdaLocal * pow(lambdaLocal, power) and * pow(lambdaLocal, -power) is mathematically equal to / pow(lambdaLocal, power); I don't see a numerical reason that pulling that pow out would hurt, and it might shave a couple of cycles off. Then (... / lambdaPower) / fwAtWicket is (...) / (fwAtWicket * lambdaPower) which is another common subexpression.

There's potentially another algebraic tweak: decimalOversRemaining * fg could be refactored by including that extra product in the method:

double calculateFunctionGPrime(const double lambda, const double oversRemaining) const {
    if (version < Version::OCT2014) {
        return oversRemaining;
    }

    if (oversRemaining == 0 || lambda == 0) {
        return 0;
    }

    const double alphaLambda = calculateAlphaLambda(lambda);
    const double betaLambda = calculateBetaLambda(lambda);

    return 50 * pow((oversRemaining / 50.0), -(alphaLambda + betaLambda * oversRemaining));
}

which saves a multiplication in the exceptional cases and an addition in the primary case. Then since the calculations of both alpha and beta have a leading negation those can be removed along with the negation in that last pow:

double calculateFunctionGPrime(const double lambda, const double oversRemaining) const {
    if (version < Version::OCT2014) {
        return oversRemaining;
    }

    if (oversRemaining == 0 || lambda == 0) {
        return 0;
    }

    const double alphaLambda = calculateAlphaLambda(lambda);
    const double betaLambda = calculateBetaLambda(lambda);

    return 50 * pow((oversRemaining / 50.0), alphaLambda + betaLambda * oversRemaining);
}

double calculateAlphaLambda(const double lambda) const {
    return 1.0 / (1.0 + c1 * (lambda - 1) * exp(-c2 * (lambda - 1.0)));
}

double calculateBetaLambda(const double lambda) const {
    return c3 * (lambda - 1.0) * exp(-c4 * (lambda - 1.0));
}


Welcome to the world of vectorization!

Your loop checks all elements in iBins and jBins against each of the elements in J and I. You do in = in | in3 to fill in with all the True values.

Now, this is the prime example of something that can be vectorized. Vectorization means that instead of working with one by one element in a vector, you work with the entire vector at the same time. This is much faster in MATLAB, as it's what MATLAB is designed to do.

A very short example (let's disregard jBins and I for a minute):

iBins = [4  2  3  8  6  4  2]
J     = [1  4  2  6  7]

Now, we can loop through J, and do in = in | in3 to get the following (this is the resulting in after each iteration:

k = 1
in3 = 0  0  0  0  0
in  = 0  0  0  0  0
k = 2
in3 = 0  1  0  0  0
in  = 0  1  0  0  0
k = 3
in3 = 0  0  1  0  0
in  = 0  1  1  0  0
k = 4
in3 = 0  0  0  1  0
in  = 0  1  1  1  0
k = 5
in3 = 0  0  0  0  0
in  = 0  1  1  1  0

The last in = 0 1 1 1 0 is the result after the loop.

Instead of looping like this, we can check the vectors against each other, and create a matrix:

    4  2  3  8  6  4  2
    -  -  -  -  -  -  -
1 | 0  0  0  0  0  0  0
4 | 1  0  0  0  0  1  0
2 | 0  1  0  0  0  0  1
6 | 0  0  0  0  1  0  0
7 | 0  0  0  0  0  0  0

If we check each row for true values, we'll see that we have true values in the second, third and fourth row, the same as above. How to do this?

logical_matrix = bsxfun(@eq, iBins, J.');
in = any(logical_matrix, 2);

Note that I transposed J, so that the two arguments to bsxfun are orthogonal.

Let's bring back jBins and I:

You must have true values in the same positions in the two matrices, so:

logical_matrix = bsxfun(@eq, iBins, J.') & bsxfun(@eq, jBins, I.');
in = any(logical_matrix, 2);

logical_matrix isn't a good name, I just couldn't think of a better word at the moment. You can skip it entirely, and do any(bsxfun..., 2).

If you have MATLAB R2016b or newer you can simply do:

in = any((iBins == J.') & (jBins == I.'), 2);

instead of bsxfun.

The rest of the code:

I recommend having parentheses in the below line, to make it sure what you compare, and make sure MATLAB works in the correct order.

in1 = (zCs > 0.0030) & (zCs < 0.1500);

It behaves the right way in the line above, but it's not always clear which order MATLAB will execute such commands (do == have precedence over < or not?) An example where the order is the other way around:

1 == 1 + 2 == 2
ans = 0
(1 == 1) + (2 == 2)
ans = 2

It might make sense when you know what the entire code does, but I had to read the code many times to understand what in and in3 were. The same goes with zCs.

You never use ncols, so you can do: nrows = size(in1, 1) or [nrows, ~] = size(in1). This is a very fast operation, so speed doesn't really matter, it's up to you to decide what you think is easiest to read and write. Anyway, MATLAB recommends that you separate output arguments with comma: [nrows, ncols] = size(in1) (I'm quite sure the editor gives you a recommendation (orange line in the scroll bar to the right).

waitbar is a time consuming operation, but you might want it there when debugging.


Number of sub strings with same first and last character

First review

It is almost always a good idea to put your logic in a function (or class) that can be easily documented and tested. That way, in anything goes wrong during the optimisation, you'll know it straight-away. Also, this can be useful if you need to measure your result to ensure your optimisation is an actual optimisation.

Just moving the code around, here is what I start with :

def get_nb_substring(s):
    l = len(s)
    return(l + sum([1 for i in range(0,l-1) for j in range(i+1,l) if s[i] == s[j]]))

def test_from_input():
    _ = int(input()) # useful ?
    s = [x for x in input().strip()]
    print(get_nb_substring(s))

def automatic_tests():
    assert get_nb_substring("ababaca") == 14

if __name__ == '__main__':
    automatic_tests()

Now, the actual review may start.

you don't need 0 as a first argument for range.
you usually don't need the length when you are using iterations in Python. When you do need it, it usually means you are doing something wrong.
for that reason, what you are doing with indices can be achieved with itertools.combinations(s, 2)

Now, the code can be rewritten :

def get_nb_substring(s):
    return len(s) + sum(1 for i, j in itertools.combinations(s, 2) if i == j)

which is still 0(n^2).

Optimisations

An idea could be to check where the different letters appear. Then if a letter c appears at positions p1, p2, ..., pn, you know it will contribute for substrings : p1, p1-p2, p1-p3, ..., p1-pn, p2,p2-p3, p2-p4, ... p2-pn, .... pn. There will be 1+2+...+n = n*(n+1)/2 such substrings.

There, if I did everything correctly, I end up with O(n) code :

def get_nb_substring(s):
    position = dict()
    for i, c in enumerate(s):
        position.setdefault(c, []).append(i)
    return sum(l*(l+1)/2 for l in (len (l) for l in position.values()))

On the test example, it seems to work. On other cases, I obtain different results than your code so I don't know which is correct.

I've used a dict to map characters to a list of position but a mapping from characters to number of positions would have been enough. This corresponds to using the Counter collection)

def get_nb_substring(s):
    return sum(v*(v+1)/2 for v in collections.Counter(s).values())


Reading a file and storing the contents in an array

Some comments:

Use std::vector instead of an inflexible array.  You're writing in C++, so you really ought to use the power of that language to write better code.
Don't use memset.  It's generally wise to avoid mixing old-style C library functions such as memset, malloc and so forth, with C++.  Strange things can happen and there's usually a better C++ way to do things without those.
Instead of using string.find, consider using other techniques such as the ones described here to split a line into its constituent pieces.
Rather than printing an error message, throw an exception.  That way your code can be reused in situtations in which std::cout is not present or not visible.
Do NOT embed using namespace std; into code like that!  It's extremely bad practice

EDIT:
Here's a quick alternative using a variation of the string split I pointed to in point #3.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

template <typename Container>
Container& split(Container& result,
  const typename Container::value_type& s,
  const typename Container::value_type& delimiters)
{
  result.clear();
  size_t current;
  size_t next = -1;
  do {
    current = next + 1;
    next = s.find_first_of( delimiters, current );
    result.push_back( s.substr( current, next - current ) );
  } while (next != Container::value_type::npos);
  return result;
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        std::cout << "Usage readarray filename\n";
        return 0;
    }
    const std::string delimiter{","};
    std::vector<std::vector<std::string> > v;
    // fetch the file into v
    std::string line;
    std::vector<std::string> fields;
    for( std::ifstream in(argv[1]); std::getline(in, line); ) {
        v.push_back(split(fields, line, delimiter));
    }
    // now print the results
    for (const auto &i : v) {
        for (const auto &j: i)
            std::cout << "[" << j << "]";
        std::cout << '\n';
    }
}

This uses C++11, but could easily be adapted for old compilers.  Based on this input file:

alpha,frank,ruby,diamond
beta,joseph,emerald,circle
gamma,may,onyx,triangle

The code produces this output:

[alpha][frank][ruby][diamond]
[beta][joseph][emerald][circle]
[gamma][may][onyx][triangle]


It's not possible to avoid undefined behaviour by testing for it after the fact! If the addition overflows then there is already undefined behaviour here:

sum = a + b;

so attempting to test afterwards is too late. You have to test for possible overflow before you do a signed addition. (If you're puzzled by this, read Dietz et al. (2012), "Understanding Integer Overﬂow in C/C++". Or even you're not puzzled: it's an excellent paper!)

If it were me, I'd do something like this:

#include <limits.h>

int safe_add(int a, int b) {
    if (a > 0 && b > INT_MAX - a) {
        /* handle overflow */
    } else if (a < 0 && b < INT_MIN - a) {
        /* handle underflow */
    }
    return a + b;
}

but I'm not entirely sure what the point of having separate cases for overflow and underflow is.

I also use Clang's -fsanitize=undefined when building for test.


Since you are using printf to output the spaces, you may as well use a specific printf format for the output.

Here's a replacement function:

centerQ(){
  textsize=${#1}
  width=$(tput cols)
  span=$((($width + $textsize) / 2))
  printf "%${span}s\n" "$1"
}

What it does is it identifies how long the whole output should be, by adding the text width and screen width together, then dividing by 2. That's a bit complicated to explain, but, the right-side of the text must be half-as-much-of-the-text as the middle of the screen.

For example, if the text is 10 characters, and the screen is 80, then the right side of the output must be at 45, or (10 + 80) / 2

If we know the right-hand side of the output, you can just make that a real printf statement:

printf "%45s" "some text!"

The function above does that, by using the padded %s format, it left-pads the output to 45 characters overall width.

By adding the newline escape \n to the printf you save the echo too.


How do I refine my code in Sikuli? Seems very long and redundant

One way to get started improving your script is to find repeated code, then create a function to hold it.

For example, if your code starting with #BEGIN IMAGE CHECK 1 is duplicated for subsequent image checks, it could become a function that takes a Sikuli image file name - define it somewhere near the top of your file (NOTE: This assumes the same image filename is used consistently across this entire chunk of code, which may not be true in your unedited code):

def check_image(image_filename):
        if not exists(image_filename):
                print("%s not displayed correctly" % image_filename)
        if exists(image_filename):
                print("%s Unable to play" % image_filename)
                click(image_filename)
        else:
                jpgl = jpgl + 1
                click(image_filename)
                wait(1)
                if not exists (image_filename):
                        wait(5)

Then below that you can call the function with:

check_image('foo.jpg')

Then you should have a starting point for incrementally refining your code. At some point creating a class to hold your test logic could be useful as well.

I recommend reading up on functions and classes in Python - solid knowledge in those areas really helps out with Sikuli development:

http://docs.python.org/tutorial/controlflow.html#defining-functions

http://docs.python.org/tutorial/classes.html#tut-classes


Simple chart-viewing JavaFX example on Nashorn

Interesting question,

from a high level, I think it will be hard to write idiomatic JavaScript using libraries that are straight ports out of Java..

In my mind (meaning, this is not canonical), JS tends to do more during initialization so that this

 var data1 = [
     new XYChart.Data(1,2),
     new XYChart.Data(2,1),
     new XYChart.Data(3,9),
     new XYChart.Data(4,5),
     new XYChart.Data(5,7),
     new XYChart.Data(6,6)
];

 var series1 = new XYChart.Series( "Reference portfolio" , data1 );

seems more natural than this

var series1 = new XYChart.Series();
series1.setName("Reference portfolio");

[new XYChart.Data(1,2),
 new XYChart.Data(2,1),
 new XYChart.Data(3,9),
 new XYChart.Data(4,5),
 new XYChart.Data(5,7),
 new XYChart.Data(6,6)
].forEach(function(item){
    series1.data.add(item);
});

Also, from a var declaration perspective, you either group all your var statements on top or you declare them to where you are going to use them. You have a mixture of both approaches. Especially the declaration of lineChart looks needlessly odd, I would simply deal with lineChart at the very end.

var lineChart = new LineChart(xAxis, yAxis); //Could have been on top
lineChart.setTitle("Stock Monitoring 2010");
lineChart.data.add(series1);
lineChart.data.add(series2);

The same goes for primaryStage, I would have set title in the same space as primaryStage.scene = scene which most JS people would have written as  primaryStage.scene = new Scene (lineChart, 800, 600); if you are going to use the variable only once, and you are not in danger of stretching too much horizontally, just do a direct assignment.

This very much looks like sample code, I think your Java'isms will show more once you get into the nitty gritty. So I am looking forward to you posting some of your real JS code.


Wrap a long string to an array of short-enough strings

Bug

You have a small bug. For text="abc \\n def" and max_width=10 the output is incorrectly ['abc', 'def'] instead of ['abc def'].

You can greatly simplify the handling of embedded whitespace characters by using re.split with a pattern r'\s+'.

Don't repeat yourself

This (or almost the same) piece of code appears in multiple places: " ".join((line, words[0])).
Look out for duplication like this and use helper functions to eliminate.

Overcomplicated string joins

Instead of " ".join((line, words[0])),
it would be a lot simpler to write line + " " + words[0].

Simplify the logic

Consider this alternative algorithm:

Create a word generator: from some text as input, extract the words one by one
For each word:

If the word is too long, raise an error
If the current line + word would be too long, then

Append the current line to the list of lines
Start a new line with the current word

If the current line + word is not too long, then append the word to the line

Append the current line to the list of lines

Implementation:

def wrap_text(text, font, max_width):
    def gen_words(text):
        yield from re.split(r'\s+', text)
        # or in older versions of Python:
        # for word in re.split(r'\s+', text):
        #     yield word

    def raise_word_too_long_error(word):
        raise ValueError("\"{}\" is too long to be wrapped.".format(word))

    def too_long(line):
        return font.size(line)[0] > max_width

    words = gen_words(text)
    line = next(words)
    if too_long(line):
        raise_word_too_long_error(line)

    lines = []
    for word in words:
        if too_long(word):
            raise_word_too_long_error(word)

        if too_long(line + " " + word):
            lines.append(line)
            line = word
        else:
            line += " " + word

    lines.append(line)

    return lines

Some doctests to verify it works:

def _wrap_text_tester(text, max_width):
    """
    >>> _wrap_text_tester("hello there", 7)
    ['hello', 'there']

    >>> _wrap_text_tester("I am legend", 7)
    ['I am', 'legend']

    >>> _wrap_text_tester("abc \\n def", 10)
    ['abc def']

    >>> _wrap_text_tester("toobigtofit", 7)
    Traceback (most recent call last):
        ...
    ValueError: "toobigtofit" is too long to be wrapped.

    >>> _wrap_text_tester("in the middle toobigtofit", 7)
    Traceback (most recent call last):
        ...
    ValueError: "toobigtofit" is too long to be wrapped.

    >>> _wrap_text_tester("", 7)
    ['']

    """
    return wrap_text(text, font, max_width)


C++ limiting a method for an rvalue caller, an expression evaluator example

I had a bunch of sections detailing the various aspects of your design that could be improved, but I ended up scrapping most of it, because at the end of the day, it can be resumed in two specific things:

But first: The idea of forcing RValues here is severely misguided. Forcing RValue usage should be limited to cases where things would break otherwise, not to enforce coding practices. What if someone wants to create a complex sub-expression and reuse it a few times? Tough luck!

1. Expression as a wrapper is misguided.

I do not like wrappers that exist just for the sake of giving value semantics to something. Value vs reference semantics should be delegated to the user as much as humanly possible as long as type erasure is not invovled. Specifically, someone will inevitably write std::unique_ptr<Expression> at some point in the future.

2. This is unjustifiably complicated.

You can obtain the same functionallity with bog-standard code, no need to get fancy. The trick is to separate the Sum() function in the API from the Sum type in the implementation.

class Expression {
public:
  virtual ~Expression() {};
  virtual std::unique_ptr<Expression> clone() const = 0;
};

class SumExpr : public Expression {
  std::unique_ptr<Expression> e1_;
  std::unique_ptr<Expression> e2_;
public:
  SumExpr(std::unique_ptr<Expression> e1,
          std::unique_ptr<Expression> e2)
    : e1_(std::move(e1))
    , e1_(std::move(e2)) {}

  std::unique_ptr<Expression> clone() override {
    return std::make_unique<SumExpr>(e1->clone(), e2->clone());
  }
};

std::unique_ptr<Sum> Sum(std::unique_ptr<Expression> e1,
                         std::unique_ptr<Expression> e2) {
  return std::make_unique<SumExpr>(std::move(e1), std::move(e2));
}

Note that is is not "quite" how I'd go about implementing this, but this way matches your current functionality.

Bonus: Implement printing to ostream as operator <<

It's a shame that operator<<(std::ostream&, Sum const&) is not implemented. print() should delegate to it ideally, so that stream << Sum()...; can work

Now, at first glance, it would seem that this would require some really annoying boilerplate, but you can get around that using some crafty CRTP:

class Expression {
public:
  virtual std::ostream& print(std::ostream&) const = 0;
};

template<typename CRTP_T>
class ExpressionImpl : public Expression {
  std::ostream& print(std::ostream& stream) const override {
    return stream << *static_cast<CRTP_T const*>(this);
  }
};

class Sum : public ExpressionImpl<Sum> {
  friend std::ostream& operator<<(std::ostream&, Sum const&) {
    ...
  }
};

As an exercise to the reader, you can similarly create a BinaryExpression<CRTP_T> to avoid having to reimplement the clone() function in every single leaf class.


Optimizing a Solution to an Overdetermined System

Here is how you can completely vectorize your code, making use of matrix functions such as crossprod, colSums, and %*%. Without for loops, your code will be more concise and faster to execute.

The construction of allCards was indeed a problem. Incrementally growing an object like you did is very memory intensive: each time you add a row, a new object is built from scratch. On the other hand, your comment that I've read that making a matrix of the correct size and filling it with NA only to fill in its values later is very memory-intensive is not accurate. Here the object is created once and filled in-place by the for loops.

To summarize: growing an object iteratively is the worst. Initializing an object to its final size and filling it in place via for loops is preferable. Using a vectorized function to create the object in one shot is the best. Hope it helps!

numberOfCards <- 9
numberOfEffects <- 3

allCards <- rbind(
  c(1,2,1,1), # Murloc Raider
  c(2,2,3,1), # River Crocolisk
  c(2,3,2,1), # Bloodfen Raptor
  c(3,5,1,1), # Magma Rager
  c(4,2,7,1), # Oasis Snapjaw
  c(4,4,5,1), # Chillwind Yeti
  c(6,6,7,1), # Boulderfist Ogre
  c(7,7,7,1), # War Golem
  c(7,9,5,1)  # Core Hound
)

cardMana        <- allCards[, 1]
cardValueMatrix <- allCards[, -1]
coefficientsMatrix <- crossprod(cardValueMatrix)
constantsVector <- colSums(cardMana * cardValueMatrix)
effectValues <- solve(coefficientsMatrix, constantsVector, tol = 1e-9)
cat(effectValues, "\n\n")
cardValues <- cardValueMatrix %*% effectValues
cat(sprintf("Card %i: %.3f", seq(numberOfCards), cardValues), sep = "\n")


Request for memory optimizations for solution to Google FooBar challenge, "ion_flux_relabeling,"

The problem description says:

  The domain of the integer \$h\$ is \$1 \le h \le 30\$

In the worst case, where \$h=30\$, the perfect tree has \$2^{31}-1 = 2147483647\$ nodes. And to store each node requires at least 32 bytes for the Tree object:

>>> Tree().__sizeof__()
32

and a further 28 bytes for its data:

>>> (123456).__sizeof__()
28

making at least 128 GB in all.

So this should clue you into the possibility that you might be able to compute the answer without building the tree. After all, the function you're being asked to write takes some numbers and returns some other numbers:

>>> answer(7, [10, 25, 109])
[14, 29, 125]

so there might be some mathematical approach to computing the outputs based only on the numerical values of the inputs. (I won't spoil this for you by giving any more hints than that.)

This doesn't mean your work so far is wasted — as you try to figure out the mathematical approach, you can use the code you've written so far to check that the new code is producing the right answers.

(You didn't show us your original Haskell program, but I suspect it might have worked because Haskell's data structures are lazy — Haskell doesn't actually build them until just before they are needed. If you can figure out exactly which parts of the tree were being built in the Haskell version — and which were not — then maybe that will help you with your Python implementation.)


Your comments are too long (line length).
Your code is also also seems untidy because of them. I would reduce the comments and have use self documenting code.

This seems to short. What happens if l is 2048?

uint ri[15];

I would use a std::vector<uint> here. You can initalize it with length so that it will be the correct size.

You do the iteration twice. Once to generate the random numbers. The second time to use the random number to access your set of characters. Why not do this in a single loop.

Here is your bug:

    if (rs.empty()) randomString(l, charIndex);
    else return rs;

Can't see it! Add braces. and use more vertical space. You should use {} around all sub blocks. It will help avoid issues in the long run.

    if (rs.empty()) {
        randomString(l, charIndex);
    }
    else {
        return rs;
    }

Do you see it now? You forgot the return in the first branch of the if statement. You only return a value in the else section. This means your class has undefined behavior.


can this php function be written to perform better?

Yeah, you can optimize your query,

 $res201 = SQL_Query_exec("SELECT COUNT(torrent) FROM peers WHERE seeder = 'yes' AND userid = $userid");

As this query will first check for seeder which has 'yes' and then for userid. So you can first check for userid, then for seeder. This will improve performance

$res201 = SQL_Query_exec("SELECT COUNT(torrent) FROM peers WHERE userid = $userid" AND seeder = 'yes' );


Don't store passwords on the client side. If your database leak, no one can stop the attacker from sending directly the hash instead of the password. In this case the attacker don't need to know the password at all.
You really want a method redirect in your User class? Think about SRP.
Your User class is half Model and half DAO. And you don't want that. A model full of query SQL isn't a good model. A data access object handles this separation between SQL and Model.


You are leaking the Vertex Buffer handles!

In your create function you allocated two Vertex Buffer Objects (VBOs), one for colors and one for positions, but you never store them anywhere, so your code will leak that memory, since those handles are no longer accessible after newTriangle returns. You should augment your GameObject structure to save those buffer handles and free them at a later time (with glDeleteBuffers). Since there's an allocation function, there should also be some sort of cleanup function in your code (e.g.: some freeGameObject or similar).

One VBO for just one triangle?

This is very inefficient. You should try to group stuff into the same VBO. Normally, you would put an entire 3D model into a buffer. You can very easily write a generic helper function that wraps the OpenGL calls for you. I'd also suggest declaring a helper structure that defines an interleaved vertex (more on this is a moment), so you can make efficient use of graphics memory by packing stuff into as little buffers as possible. Example:

typedef struct
{
    float px, py, pz; // vertex position
    float nx, ny, nz; // vertex normal for lighting
    float r, g, b;    // RGB vertex color
    float u, v;       // texture coordinates
    // anything else you may need
} my_gl_vertex;

// Then a helper to allocate the GL buffers for you,
// taking your generic vertex type:
void create_gl_buffers(const my_gl_vertex * verts_in, int vert_count,
                       GLuint * vao_out, GLuint * vbo_out);

So, what was that about interleaved vertexes again?

Just a fancy name to say that we are packing all the attributes of a model vertex into a structure, thus, we only allocate one VBO and place everything in it, rather than allocating one VBO for positions, one for colors, one for normals, etc. You can find examples of how to set this up in here. You should care about using interleaved data because it performs much better in the rendering, since all relevant data for a vertex will be tightly packed in memory, rather than scattered across different buffers. This will also allocate a single buffer, which might also reduce allocation overhead in the graphics driver side.

Move to indexed drawing

Last basic improvement you can add is to support indexed drawing, or indexed vertex specification. If you try, for instance, to draw a rectangle using two triangles, you'll see that you have to repeat two vertexes. This repetition can add up for larger and more complex 3D models, so if you instead supply a set of unique vertexes and use a separate set of integer indexes into this set of verts to describe the model, you get rid of all vertex duplication! The indexes will repeat, but they consist of small integer numbers, which should be a lot smaller than the average 3D vertex with color, position, whatnot. That's indexed drawing in a nutshell. You can check this tutorial for more details, or just look around in the web and you should find several more.


Getting Pascal's triangle recursively in Python

Similar to your Water Jug solution, this is still not a good recursive algorithm/implementation.  But we can still critic it, and provide useful feedback.

First, the default argument m=1 is awkward, which leads to the odd if m > n+1: and if m == 1: test conditions.  Changing the default argument to zero reduces this oddness:

def RecPascal(n, m=0, prev=[]):
    if m > n:
        return []
    elif m == 0:
        return RecPascal(n, m+1 , [1])
    else:
        return [prev] + RecPascal(n, m+1, calculate(prev))

The elif m == 0: case seems to exist only to seed the algorithm with the first row of Pascal's Triangle.  The default value prev=[] is never used the code; if only one parameter is given, the second value's default causes return RecPascal(n, m+1, [1]) to be executed and prev is not used.  If you instead use [1] as the default value, you can eliminate the n+1-th recursive step.

def RecPascal(n, m=0, prev=[1]):
    if m < n:
        return [prev] + RecPascal(n, m+1, calculate(prev))
    return []

A bit of inspection will reveal that this is (like the Water Jug solution) just a loop disguised as recursion; it can be rewritten without recursion as:

def RecPascal(n):
    triangle = []
    row = []
    for _ in range(n):
        row = calculate(row)
        triangle.append(row)
    return triangle

In the calculate(prev) helper function, you initialize res to a row of zeros, and then fill in the end values with 1:

    res = [0]*(len(prev)+1)
    res[0], res[-1] = 1, 1

You could replace this with initializing res with a row of ones:

    res = [1] * (len(prev)+1)

Of course, then you can't look for the res[i] == 0 values to fill in, but we don't need to look, we know the exact indices that need filling in:

    for i in range(1, len(res)-1):
        res[i] = prev[i-1] + prev[i]

This gives a much cleaner helper function.  We can even get rid of a -1 by using using the len(prev) instead of len(res):

def calculate(prev):
    res = [1] * (len(prev)+1)
    for i in range(1, len(prev)):
        res[i] = prev[i-1] + prev[i]
    return res

If we wanted to be tricky, we could add a 0 to the end of prev, and then add corresponding elements of two slices of the prev list together, and prepend a 1 to the beginning:

def calculate(prev):
    prev = prev + [0]
    return [1] + [x+y for x,y in zip(prev[1:], prev[:-1])]

Which works like this:

prev + [0]  -> [ 1, 3, 3, 1, 0 ]

  prev[1:]  -> [ 3, 3, 1, 0 ]
+ prev[:-1] -> [ 1, 3, 3, 1 ]
-----------------------------
         [1] + [ 4, 6, 4, 1 ]

This gives the correct generation of the first row: calculate([]) --> [1].  If we added 0 to both the start and back, we'd correctly calculate the 1's at each end (0+1 = 1, and 1+0 = 1) but would have to seed the first row with [1].

Since calculate is a helper for RecPascal, and won't be used anywhere else, you can "hide" it by moving it inside of RecPascal, shown here with the alternate calculation (prepending & appending 0's, seeding first row as [1]) method:

def RecPascal(n):

    def calculate(prev):
        prev = [0] + prev + [0]
        return [x+y for x,y in zip(prev[1:], prev[:-1])]

    triangle = []
    row = [1]
    for _ in range(n):
        triangle.append(row)
        row = calculate(row)

    return triangle


Get total count of object's elements and all children objects` elements

Why do you need to make the .ToList() call instead of keeping the IEnumerable objects returned by Select methods?

    public int GetCount(int ID)
    {
        var childrenIDs = DbContext.Taxonomy
            .Where(x => x.ParentID == ID)
            .Select(x => x.TaxID);
        var grandchildrenIDs = DbContext.Taxonomy
            .Where(x => childrenIDs.Contains(x.ParentID))
            .Select(x => x.TaxID);
        var count = DbContext.Table2.Count(x =>
         x.FK_TaxID == ID ||
         childrenIDs.Contains(x.FK_TaxID) ||
        grandchildrenIDs.Contains(x.FK_TaxID));
        return count;
}

This way, the only call to database is the last one.


Project Euler #4 - Largest Palindrome Project - Python

Look at my previous answer

palindrome is divisible by 11
i and j can be only odd
reverse loops 999 -> 1 and 999 -> i - 1 - first found palindrome less than n is our palindrome

Simplify code

str(num) is expensive, do it once

def is_palindrome(num):
    snum = str(num)
    return if snum == snum[::-1]

Instead of prod > largest and prod < num You can write num > prod > largest

Use list comprehension

limits = [int(input().strip()) for _ in range(limit)]


Compound words like firstitem should be camelCase.

Why is the Resource property of TimelineDto a string, when you seem to be filling it with ints?

allItems is a bad name, item is even worse. I have no idea what this represents.

I also have to object to TimelineDto, especially when timeline = new List<TimelineDto>.

var firstitem = allItems.FirstOrDefault(); can return a null, yet you never check this.

Why are you even using the OrDefault version, considering that the first line sorts the result of GetInterestingItems() by StartDate, which would throw an exception if one of the items was null.

Is there a point to all of this:

// Add the first item to first resource
var firstitem = allItems.FirstOrDefault();
var timelineCount = 1;
var timeline = new List<TimelineDto>
{
    new TimelineDto
    {
        itemId = firstitem.Id,
        Resource = timelineCount.ToString(),
        StartTime = firstitem.StartDate,
        EndTime = firstitem.EndDate
    }
};
allItems.Remove(firstitem);

Except for var timelineCount = 1; I don't see how this isn't handled by the logic inside foreach (var item in allItems). Of course you need to rethink var last = timeline.Last(x => x.Resource.Equals(i.ToString())); and if (item.StartDate > last.EndTime), but that seems a more elegant solution than the 10+ lines required to add a first entry to timeline.

This code is repeated three times, so it should be moved to a method:

new TimelineDto
{
    itemId = item.Id,
    Resource = timelineCount.ToString(),
    StartTime = item.StartDate,
    EndTime = item.EndDate
}

WRT your question, I don't see how you can parallelize it without running the risk of duplicate entries.

I do wonder whether it wouldn't be easier (and increase performance) to maintain a Dictionary<int, DateTime> instead of doing var last = timeline.Last(x => x.Resource.Equals(i.ToString())); each time. Key of that dictionary is the Resource, value is the EndTime.

So you'd end up with something like this:

public List<TimelineDto> GetOptimizedTimeline()
{
    var items = GetInterestingItems().OrderBy(x => x.StartDate).ToList();
    if (!items.Any())
    {
        return null;
    }

    var timeline = new List<TimelineDto>();
    var endTimeByResource = new Dictionary<int, DateTime>();
    var timelineCount = 1;

    foreach (var item in items)
    {
        var added = false;
        for (var i = 1; i <= timelineCount; i++)
        {
            DateTime endTime;
            if(endTimeByResource.TryGetValue(i, out endTime)
            {
                if (item.StartDate > endTime)
                {
                    timeline.Add(CreateTimelineDto(item, i));
                    endTimeByResource[i] = item.EndTime;
                    added = true;
                    break;
                }
            }
        }

        if (added)
            continue;

        timelineCount++;
        timeline.Add(CreateTimelineDto(item, i));
        endTimeByResource[i] = item.EndTime;
    }

    return timeline;
}

Beware: I have not tested this code, so there might be some part of the logic missing! I suspect the if(endTimeByResource.TryGetValue(i, out endTime) needs an else where you add a new TimelineDto.

I would even consider getting rid of timelineCount completely and instead do for (var i = 1; i <= endTimeByResource.Keys.Count; i++), that way you might even be able to get rid of added, something like this:

foreach (var item in items)
{
    for (var i = 1; i <= endTimeByResource.Keys.Count; i++)
    {
        DateTime endTime;
        if(endTimeByResource.TryGetValue(i, out endTime)
        {
            if (item.StartDate > endTime)
            {
                timeline.Add(CreateTimelineDto(item, i));
                endTimeByResource[i] = item.EndTime;
                break;
            }
        }
    }
}

Again: this is untested.

I think it can even be reduced to this:

    for (var i = 1; i <= endTimeByResource.Keys.Count; i++)
    {
        DateTime endTime;
        endTimeByResource.TryGetValue(i, out endTime);

        if (item.StartDate > endTime)
        {
            timeline.Add(CreateTimelineDto(item, i));
            endTimeByResource[i] = item.EndTime;
            break;
        }
    }


As far as testing the method itself:
In most testing frameworks, you would create parameterized tests that provide the inputs and expected outputs.

NUnit example below (omitting setup code to build ObjectUnderTest):

[TestCaseSource ("GetPrepTestData")]
public void TestPrepareAndScheduleFlowJob (string inputCoords, FlowJob expectedJob)
{
   var  outputJob = ObjectUnderTest.PrepareAndScheduleFlowModelJob (inputCoords);
   Assert.That (outputJob, Is.EqualTo (expectedJob));
}

private static IEnumerable<TestCaseData> GetPrepTestData ()
{
   yield return new TestCaseData ("some coord string", new FlowJob (expectedId)).SetName ("first test");
   yield break;
}

The private method calls can largely be ignored unless they have external dependencies, in which case you should add some injection and mocking with your parent object.  This will allow you to ensure your private method calls inside PrepareAndScheduleFlowJob execute quickly and return expected results.

edit:
The above solution requires that you override Object.Equals.  You could change the assert to a set of asserts for testing equality, but Object.Equals overrides are preferable, as it will cover FlowJob and any future/current subclasses in addition to providing equality check capability to anyone using the class.  Additionally, in a framework like NUnit, overriding Object.ToString is highly recommended, as many test frameworks will call ToString when printing assert failures, and having something more than just the type name is useful when assessing why your tests may have failed.


Project Euler 67 - Max path through triangle

I guess, you haven't got an answer until now, as there's hardly anything to say. So I must be very critical in order to get a non-empty answer.

getTriangle

Despite Java 8, it's nicely readable. I'm not sure about

            .filter(line -> !line.isEmpty())

as it may hide errors like when someone decides to put multiple input triangles into one file. We know, it won't happen, but still. All I'd do is to drop leading and trailing blank lines, so that such a problem gets immediately detected. However, I can't see a simple way how to achieve this.

The method is called getTriangle, but makes no checks about really reading a triangle. That's mostly fine as it'll blow later anyway, but I'd call it maybe getSourceAsInts in order not to suggest that the result must be a triangle.

maxPath

It ideally should start by checking that the input is indeed a triangle. Otherwise, it may be hard to find the cause of the exception thrown later.
    int[] previous = new int[triangle.length + 1];
    int[] current = new int[previous.length];

Given that the triangle already takes O(n*n), I wouldn't bother with saving memory here (speed-wise it hardly matters). When optimizing hard, I'd consider to overwrite the original triangle. That said, your choice is surely not bad.

You could also use long in order to prevent overflow (Not needed, I know).

// the first value of the top row is the maximum path sum.
return previous[0];

It's a bit confusing as when the top element is previous, what's then current? Maybe using the name combo current and next would be clearer (and maybe not).

main

Nothing to say.

  I get the results for #18 in 0.030ms and for #67 in 0.203ms on my computer.

For #67 it's about the same time as mine, with #18 I'm much slower as my solution uses my other utilities which leads to loading many classes. But I wouldn't care about such small times at all.

(from a comment)

  I don't believe it will be. Even Dijkstra has to visit every node once

Agreed. Your solution is optimized for the given input graph shape, much simpler and faster than general Dijkstra.


Cryptographically Secure Pin Generator using RNGCryptoServiceProvider

Use unsigned integers to avoid the Abs related issues
RightPad is incorrect, since shorter integers need leading zeros. Either use LeftPad or simply ToString("D5")
A bigger integer will reduce the bias.

Thus I'd rewrite the relevant code as:

byte[] buffer = new byte[sizeof(UInt64)];
cryptoRng.GetBytes(buffer);
var num = BitConverter.ToUInt64(buffer, 0);
var pin = num % 100000;
return pin.ToString("D5");


Cancellable progress form using async/await

Clean code, easy to follow its meaning. Some minor remarks:

var progressHandler = new Progress<string>(value => MessageLabel.Text = value);
var progress = progressHandler as IProgress<string>;

This looks like you can just define it as

IProgress<string> progressHandler = new Progress(value => MessageLabel.Text = value);

Or just a Progress<string> type, really:

var progressHandler = new Progress(value => MessageLabel.Text = value);

Unless I'm mistaking, you don't actually need it as an interface. Note that I also removed the explicit type parameter since that should be inferred from the argument passed to it.

MessageLabel.Text = @"Cancelled!";

The verbatim string isn't necessary here

if (token.IsCancellationRequested)
{
    token.ThrowIfCancellationRequested();
}

This seems redundant to me.

It should be either this

if (token.IsCancellationRequested)
{
    throw new OperationCanceledException();
}

or this:

token.ThrowIfCancellationRequested()

This is also reinforced by the documentation

private async void PerformTasks()

Asynchronous methods should return Task or Task<T>, the former being for traditional void methods and the latter being for methods with T return type.

The reason for this is that a void method cannot be awaited (since it doesn't return a Task) and will in effect be a fire-and-forget kind of thing: it will start executing your asynchronous code on a separate thread and continue doing business as normal. However once the main thread reaches its end, the application will exit regardless of whether or not your asynchronous code has finished as well. This obviously leads to nasty bugs.

You won't notice this in this case because you're using a GUI which means there will always be a main thread active (as long as the application runs).

However in case you ever want to re-use this code for a console application or just in a class library where you don't know the client, I would suggest making it async Task just for good measure.

The only exception to this are asynchronous event handlers since they have to adhere to the convention that event handlers return void. This also explains why events are "dangerous" to use in asynchronous code.


Batch renames file's extension in a given directory with Python

Questions

  Is the code easy to read and comprehend?

Import both join and splitext on the same line, and it'll be perfect.

  Is the code Pythonic?

Yes... But is it good?

It's doesn't follow *nix too much. And sys.exit is just wrong.
When using sys.exit you pass an error status, not a message.
The status should be a number from 0-127, where 0 is successful.
And all the other numbers are an error of sorts.

Also you can set up your terminal to change colour or add words if you get an error response. So when sys.exit(1) is called my prompt goes from green to red.

  Does the code have any BUGS?

Yes:

>>> '.txt_file.txt'.replace('.txt', '.spam')
'.spam_file.spam'

  Should i have used argparse instead of sys.argv

I'd say no, as this is a very small script.
Otherwise, I'd say yes.
If you need flags and such you should use argparse, even if the program is very small. So if you think about adding a --verbose flag, you should.

Code review

As noted above, your usage for sys.exit is wrong.

To amend this, I would change your sys.exit to a standard raise.
And then catch it, print the message, and exit with status 1.

class InputError(Exception):pass

def main():
    ...
    except ValueError:
        raise InputError("Usage: {} directory old-ext new-ext".format(__file__))
    ...

if __name__ == '__main__':
    try:
        main()
    except InputError as e:
        print(str(e))
        sys.exit(1)

To amend the bug, I would use a completely different approach.
A more *nix and Python approach.

*nix encourages regex's, and Python has str.format, but you can use the both of them!
They are both micro-languages but regex's are for pattern matching where Python's format is for output formatting.
I would argue having two dedicated micro-languages, is far better than anything we manually program.

import sys
import re
import os
from os.path import join

class InputError(Exception):pass

def main():
    try:
        work_dir, regex, format_ = sys.argv[1:]
    except ValueError:
        raise InputError("Usage: {} directory regex format".format(__file__))

    regex = re.compile(regex)

    for filename in os.listdir(work_dir):
        if regex.match(filename) is not None:
            newfile = format_.format(*regex.findall(filename)[0])
            os.rename(join(work_dir, filename), join(work_dir, newfile))
            print('Replaced {} with {}'.format(filename, newfile))

if __name__ == '__main__':
    try:
        main()
    except InputError as e:
        print(str(e))
        sys.exit(1)

This is as complex as your previous code. However you can now do things like:

$ mkdir temp
$ touch temp/txt.boo
$ python change.py temp "(.*)\.(txt|boo)" ".{1}_file.{0}"
Replaced txt.boo with .boo_file.txt
$ ls temp
.boo_file.txt
$ python change.py temp "(.*)\.(txt|boo)" ".{1}_file.{0}"
Replaced .boo_file.txt with .txt_file..boo_file
$ ls temp
.txt_file..boo_file
$ python change.py temp
Usage: change.py directory regex format
err$

As I was asked

  Wouldn't the fnmatch module be better suited for matching a pattern in a filename then a regular expression.

I thought I should make a pro's and con's for each method:

Regex

Pros

Well know micro-language
Allows an extremely large amount of customisation to the query
Easy to implement

Cons

Larger input

glob / fnmatch

Pros

Simple input
Easy to implement

Cons

No capture groups
Good luck with substitution '{0[:-4]}.boo'.format('hello.txt')
Some inputs are impossible to have reliable output. *file*

glob based regex

So as the main fallback is that you can't have capture-groups in glob,
you can add them.
E.g:

re.compile(fnmatch.translate().replace(r'\(', '(').replace(r'\)', ')'))

Pros

Easy for people who don't know regex
Smaller input, but not as small is glob

Cons

Hard to implement well, without becoming regex where .* is substituted with *.

inp = '\(*\).txt' # Matches r'\\(.*\\)\.txt'.
fnmatch.translate(inp).replace(r'\(', '(').replace(r'\)', ')'))

However if we were to use re.sub.

inp = '(*).txt' # Matches r'(.*).txtZ'
re.sub(r'\\(.)', lambda m: m.group(1), fnmatch.translate(inp))

inp = r'(*)\.txt' # Might as well be regex.
re.sub(r'\\(.)', lambda m: m.group(1), fnmatch.translate(inp + '\\'))

And then there is the edge-case for '[a-z]*'.
As the docs say:

  For a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'.

But that make '[a-z][*]' turn into '[a-z][*]' not '[a-z]*'.

Conclusion

I chose re as more people know it.
You can extract information out of it with ease.
And is super easy to implement.

If you wanted to use glob & regex, you might as well use regex.

And glob is kinda broken:

>>> '{0[:-4]}.boo'.format('hello.txt')
TypeError: string indices must be integers
>>> '{0[-4]}.boo'.format('hello.txt')
TypeError: string indices must be integers


You could also make a baseactivity for all the other activity that are going to use the adView

    public class BaseActivity extends Activity {

    private DfpAdView adView;
    RelativeLayout rl;
    //some other stuff

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.baseactivity_layout)
        rl = (RelativeLayout) findViewById(R.id.adLayout);
        adView = new DfpAdView(this, AdSize.BANNER, adId);
        rl.addView(adView);
        adView.loadAd(new AdRequest());
    }
}

And and make your MainActivity (or all the other activities that are using the adview)

public class MainActivity extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState){

    }
}


Finding locations with a distance between 1 and 5000

Shorter, and while min/max was tricky, IMO, this is easier to understand:

def self.location(distance=100,location)
    distance = 100 unless distance.is_a?(Integer)
    distance = 1 if distance < 1
    distance = 5000 if distance > 5000

    if location
        within(distance, :origin => location)
    else
        find(:all)
    end
end


Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used.
See Effective Java, Second Edition, Item 45: Minimize the scope of local variables. (Google for "minimize the scope of local variables", it's on Google Books too.))

The m_ prefix is unnecessary and uncommon in the Java world. See Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions

The sendMail method should validate its input parameters. Does it make sense if the form, to etc. is null or empty string? If not, check it and throw a NullPointerException or an IllegalArgumentException. (Effective Java, Second Edition, Item 38: Check parameters for validity)


Check if two strings are anagrams - HackerEarth

How do I make this code as small (shorter code) as possible?

You could change this:

if(strcmp(str1,str2)==0)
    printf("YES\n");
else
    printf("NO\n");

Like this, using the ternary operator and puts:

puts(strcmp(str1, str2) ? "NO" : "YES");

Technically,
you could also get rid of much of the whitespace and concatenate all instructions on a single line with semicolons.
But that's probably not what you really want.

If your aim is simplicity, then I think this is about as simple and short as it gets.

For readability, it would be better to add spaces around operators, for example like this:

    if (str[j] > str[j+1])
    {
        swap = str[j];
        str[j] = str[j+1];
        str[j+1] = swap;
    }

Some minor final remarks:

bubble sort is a slow sorting algorithm, but with words of max 100 letters, it's probably good enough
uppercase and lowercase letters will be treated differently, but since the treatment of letter case is unspecified, that might be fine too


Securely upload multiple image files with PHP

If you are talking about a "secure" version then please state what you mean with it. What are you protecting against and which security requirements do you have extracted?
if (is_post_request() && is_request_same_domain() && isset($_POST['add-list-submit'])) {

This only indicates what it is doing. But it is doing too much on a line. If this is some particular check then please implement it in a well named function.

Convert the $_FILES array to a cleaner version

What does that even mean, a "cleaner version"?
function rearrange_files_array($file)

So it is apparently a rearranged array, but why? Please document your functions if it is not clear what they are doing. Furthermore, here even the "how" is missing: how is the array rearranged?
$errors['form'] = 'Please upload the images.';

Is this something that a user could do? I just select the images. If they don't get loaded into variables then I cannot fix that myself.
$errors['form'] = 'Only PNG and JPG file formats are allowed.';
...
$errors['form'] = 'Max file size is 2.5 MB.';

You have run into a common problem: putting all possible information in the error message while keeping the parameters generic. Please fix the error message so that the extensions and max file size are dynamic. Currently you would have to adjust both the function and the content of the error message separately to achieve one thing.
You did let the extensions be the 2nd parameter of the has_valid_file_extension method. That's a good thing and you should perform the same for checking the file size. It will also bring the error and value of the file size closer together.
It seems that you fall through the if statements when error checking; I'd expect the script to perform some kind of action, right? Currently only an error is set, but the script seems to continue.
$imageTypes = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO];

That's strange, I thought only JPEG and PNG were allowed. This is probably a more generic method. But even in that case: check the file extension first before running this method. You don't want to be checking some exotic file type only to find out that it is not allowed anyway; always bring down the number of options / states of a program as soon as possible.
You may also wan to check that the extension is correct for the given image type, I don't see that happening.
As an aside: Obviously the method getimagesize is named terribly badly as it returns all kinds of information, but that's something to blame on PHP, not your script.
return false; // Invalid Image Type

This wipes out the actual error message, which means it will be impossible to inform the user correctly. You'd better return result which contains an error string or use a similar construct. I applaud you for at least including a comment, but if you have to type such comments then the code itself is often not verbose enough.
return false; // One Bit Image

Huh? No, that seems to be the bit depth. So it would be  B/W or rather monochrome image.
else {
    return true;
}

Just return true is enough here, the application has nowhere to go after all.

All in all, it's not a bad attempt to me, but a few repairs and a lot of polishing seems in order.


Optimize calculation for the amount of time between when a value changes in Pandas

Cool problem, thanks for sharing.  Here is my take on the implementation. I will discuss each section in turn.

1. Use diff to directly get the state changes

diff() returns a vector with the difference between subsequent elements.  Thus when the state does not change it is equal to zero.

# find when the state changes
run_change = df['Run'].diff()

2. Use diff to directly get time delta between steps

# get the step lengths
step_length = df['Datetime'].diff()

3. Loop and build delta since previous change

Since we need to keep state from previous rows I could not formulate a vector way to do this, and had to resort to a loop.  But in the loop we do not use any indices, instead we iterate directly on the data structure.  zip() is used to take matching index elements of the two series at the same time.

# loop and get the change since last state change
since_change = []
current_delta = 0
for is_change, delta in zip(run_change, step_length):
    current_delta = 0 if is_change != 0 else \
        current_delta + delta.total_seconds() / 60.0
    since_change.append(current_delta)

4. Insert the intermediate data into the data frame

This is just for illustration.  Likely more efficient to use concat, than three separate dataframe constructions.

# add this data to the data frame
df['Run_Change'] = run_change
df['Step_Length'] = step_length
df['Time_Since_Change'] = pd.Series(since_change).values

Whole Code Listing:

import pandas as pd

# load example data
df = pd.DataFrame(data=[['2015-01-01 00:00', 1],
                        ['2015-01-01 00:02', 1],
                        ['2015-01-01 00:04', 1],
                        ['2015-01-01 00:06', 0],
                        ['2015-01-01 00:08', 0],
                        ['2015-01-01 00:10', 1],
                        ['2015-01-01 00:12', 0],
                        ['2015-01-01 00:15', 1],
                        ['2015-01-01 00:17', 1],
                        ['2015-01-01 00:19', 1],
                        ['2015-01-01 00:23', 0],
                        ['2015-01-01 00:25', 0],
                        ['2015-01-01 00:30', 0],
                        ['2015-01-01 00:32', 0],
                        ['2015-01-01 00:34', 0]],
                  columns=['Datetime', 'Run'])

# convert to datetime object
df.Datetime = pd.to_datetime(df['Datetime'])

# find when the state changes
run_change = df['Run'].diff()

# get the step lengths
step_length = df['Datetime'].diff()

# loop and get the change since last state change
since_change = []
current_delta = 0
for is_change, delta in zip(run_change, step_length):
    current_delta = 0 if is_change != 0 else \
        current_delta + delta.total_seconds() / 60.0
    since_change.append(current_delta)

# add this data to the data frame
df['Run_Change'] = run_change
df['Step_Length'] = step_length
df['Time_Since_Change'] = pd.Series(since_change).values


Idiomatic catching of unchecked exceptions in ExecutorService.submit

Exception handling in Java has certain best practices. But not all situations are covered equally.

In this case, what you have, is a combination of logging, handling, and shutdown handling.

In this case, your handling appears to be sane. The centralization of this logging/shutdown is convenient because it essentially extracts the same functionality from multiple places in to a single place.

There are two issues that I can see:

Logging in Java often is tied to the class that the log message is called from. For example, the Logger is created with a name of the class as a constructor/key.

This means that the logging of the exception may/will be logged with the name of the ErrorHandler class rather than the class that threw the exception.

Depending on your circumstances, this may be a problem.
Logic flow in situations like this are often complicated by the return types of the class. For example, your code may look like:

public int myMethod() {
    try {
        // .... do something ....
        return 1;
    } catch (LWJGLException ex) {
        exceptionHandler.onException(ex);
    }
}

but, that code will not compile because you need to return an int value after handling the exception.

You know that there will never be an exit from the onException, because it shuts down. The compiler does not know that, so the compiler makes the wrong assessment of the exit path of the method.

I recommend you change the signature of the onException class, to have a return type of RuntimeException. With that, you can have:

   } catch (LWJGLException ex) {
       throw exceptionHandler.onException(ex);
   }

That will keep the compiler happy too.


Overview
The trouble here is ownership. Who owns the tail?
In C++ ownership is a very important topic and defines who is responsible for who should destroy an object. The problem with C like pointers is there are no explicit ownership semantics. So as part of the documentation you need to define who the owner (and people read documentation is the problem here) is otherwise things go wrong and the wrong person will delete the object or it will never get deleted.
This is why in modern C++ it is very uncommon to see C-pointers. Because there is no ownership defined. You can use smart pointers to explicitly define the owner of a pointer or you can use references to show that you are retaining ownership.
Note: Inside a class it's OK to use a pointer as you control everything inside a class. The problems happen when you leak a pointer through a public interface.
You don't show how you expect your class to be used, but given the interface it is easy to use it with pointers and leak object all over the place. Given the current interface I would expect the following to be standard usage:
 ImmutableList<int>* data = new List<int>(1, new List<int>(2, new List<int>(3, new Nil<int>())));

 // Do stuff.

 delete data;

This leads to all but the first element from being leaked (because the destructor does not delete the chain).
Now you can't just add a delete into the destructor as you can retrieve the tail and place it another object.
ImmutableList<int>* data1 = new List<int>(1, new Nil<int>());
ImmutableList<int>* data2 = new List<int>(2, data1->tail());

In this situation simply deleting the tail is not going to work as both data1 and data1 share the same tail. So you need some form of shared ownership semantics. Now you can do this yourself but if you try and implement your own ownership semantics then you need to define the copy and move operators for your class.
// Copy Operators
List& List::List(List const&);
List& List::operator=(List const&);

// Move Operators
List& List::List(List&&);
List& List::operator=(List&&);

This becomes exceedingly not trivial when you have shared objects. So really you need to use std::shared_ptr.
Code Review
If you have a base class with virtual methods then you your destructor should also be virtual:
template <class T>
class ImmutableList {
    public:
       // Destructor should be declared virtual
       ~ImmutableList() {std::cout << "base class destructor";}
       ...
}

This is because you are likely to use delete on a base class pointer that points at a derived type. If the destructor is not virtual you call the wrong destructor.
Your code is not const correct.
virtual bool is_empty() = 0;
virtual T head() = 0;
virtual ImmutableList<T> * tail() = 0;

All the above methods are const (as your class is Immutable). So you can change the object just query it.
virtual bool              is_empty() const = 0;
virtual T                 head()     const = 0;
virtual ImmutableList<T>* tail()     const = 0;
virtual int               length()   const = 0;
                                  // ^^^^^

You return the head by value. This causes a copy of the object. Now for int and other simple types this is not a problem. But for complex types (like vector) a copy may be much more expensive.
So normally you return by reference. Not because the class in Immutable you should return a const reference.
virtual const& T head()                 const = 0;
    //  ^^^^^^

Now you return a reference to the object (allowing it to be queried). If you actually want a copy you can assign it to a variable and it will be copied.
T val = data1->head();


Aspect-oriented vs explicit style in Python

Pythonic, readable and convenient

are all subjective and open to debate, even though "Pythonic" is less so than the others. That said, a simplified version may be illustrative. Comparing

@foo
@bar
def baz(value: T) -> T:
    return value

to

def baz(value: T) -> FooT:
    return foo(bar(value))

there are two issues with the former:

The final return type is now hidden in foo.
It is easy to confuse the layering - is baz(value) equivalent to foo(bar(baz(value))) or bar(foo(baz(value))) (or even baz(foo(bar(value))) in case of a novice)? Nested decorators come up so rarely that I would have to look at the documentation to be absolutely sure whether they were in the right sequence.

There seems to be two situations where multi-level decorators would be fine:

If they pass through the return value unchanged. A logger would be a typical example.
If the decorators are commutative, that is, their order doesn't matter for the outcome.


Insert into two tables during user registration using PHP

You should return early to reduce nesting and make it more obvious when what values are returned:

if (!$stmt = $mysqli->prepare("INSERT INTO users (username, email, regtime, emailverified, type) values (?,?,?,?,?);")) {
    echo "uh oh";
}
[...]

if($stmt->bind_param('sssii', $username, $email, $dateStr, $emailverified, $type) !== true){
    // you actually didn't have an else for this
}
[etc]

You should also replace your echoes with exceptions with proper error messages.

Misc

your indentation is off, and you should use a minimum of 4 spaces.
rc is not a good variable name, and you shouldn't reuse variables for different things.
you should also extract this into two functions: insertUser($username, $email, ...) and insertUserCredentials($username, $hash).