Change-making problem with specific constraints

1. Review

The function coinChange carries out three tasks: (i) read the input; (ii) solve the problem; (iii) print the solution. This makes it hard to test, because it's hard to run the code on different problem instances (you have to feed it the problem in text form on standard input), and becaue it's hard to automatically check the output (you have to capture the standard output).

It would be easier to test the code if task (ii) were refactored into a separate function. I'd write something like this:

class NoSolution(Exception):
    pass

def coin_change(amount, coins):
    """Given a target amount and a sorted list of coins denominations,
    determine how to make change for amount with the minimum number of
    coins, subject to the restrictions that every denomination is used
    and the number of coins of a small denomination must be greater
    than the number of coins of a large denomination. Return a list
    giving the number of coins of each denomination, or raise
    NoSolution if making change is impossible under the constraints.

    """
    # ... see below ...

def main():
    """Read coin change problem from standard input and write solution to
    standard output, or NA if there is no solution.

    """
    amount, coins = int(input()), list(sorted(map(int, input().split())))
    try:
        result = coin_change(amount, coins)
    except NoSolution:
        print('NA')
    else:
        print(sum(result))
        print(*result)

and now it's easy to test the code, for example from the interactive interpreter:

>>> coin_change(20, [1, 2, 5])
[4, 3, 2]

sorted already returns a list, so there is no need to pass the result to list.
str.split splits on whitespace by default, so there is no need to pass sep=' ' in this case.
Note in the code above that I handle an exceptional result by raising an exception (instead of returning some exceptional value). This is more robust because it is easy to forget to check the result of a function, causing exceptional cases to be silently mishandled.
These lines are unnecessary:

min_package = [x for x in range(len(coins), 0, -1)]
min_sum = sum(map(lambda x, y:x * y, min_package , coins))

if amount < min_sum:
    print('NA')
    return

That's because there is already logic for detecting unsolvable problem instances later in the function. There's no point in doing this twice: duplicate code has twice the opportunties for bugs.
The line:

dp, dp[0] = [amount + 1] * (amount + 1), 0

is kind of tricksy (the reader would need to be very sure of Python's order-of-evaluation rules to know that dp[0] is evaluated after dp is assigned), and so it would be simpler to write something like:

dp = [amount + 1] * (amount + 1)
dp[0] = 0

or alternatively,

dp = [0] + [amount + 1] * amount

The only role of amount + 1 in this line is to be greater than every possible number of coins. I think it would be clearer to use a value like float('inf') here.
This loop:

for i in range(len(dp)):

would be better written like this:

for i in range(1, amount + 1):

This is because there's no point in considering making change for 0, so we might as well start at 1, and because amount + 1 makes it clear that we consider all values up to amount, without having to remember how many elements there are in the list dp.
In Python we prefer not to use tuple assignment just to save on lines of code (only when we really do have a tuple to assign). This kind of code is hard to follow:

dp[i], package[j], packages[i] = dp[last] + 1, package[j] + 1, package

because you have to count carefully to see which expression on the right is assigned to which expression on the left. I think it's clearer to write:

dp[i] = dp[last] + 1
package[j] += 1
packages[i] = package

Notice that I can use the += operator here, which wasn't possible in the tuple assignment version of the code.
Making a deep copy of packages[last] is unecessary: this is a list of integers, and so a shallow copy would work.
There's no need to import the copy module just to take a shallow copy of a list. It's simpler to use the built-in function list.
The code takes a copy of packages[last] before testing whether coin could be used. But this is a waste if coin in fact cannot be used. It would be better to take the copy after the test, like this:

package = packages[last]
if dp[i] > dp[last] + 1 and (j == 0 or package[j - 1] > package[j] + 1):
    dp[i] = dp[last] + 1
    new_package = list(package)
    new_package[j] += 1
    packages[i] = new_package

The meaning of the name dp is not clear to me. The value dp[i] is the smallest number of coins found so far that makes change for i under the restrictions of the problem. Even knowing this, I can't work out what "dp" stands for! I would use a name like min_coins together with a comment explaining the meaning.

Update: does "dp" stand for "dynamic programming"??
The meaning of the name package is also not clear. The value packages[i][j] is the number of coins of the j'th denomination in the best solution found so far that makes change for i under the restrictions of the problem. So I'd use a name like solutions together with a comment.
Instead of:

    if coin <= i:
        # ...
    else:
        break

I would write:

    if coin > i:
        break
    # ...

which saves a level of indentation. In general, it's a good idea to dispose of exceptional cases first.
At the end of the function, the code uses packages[-1] to get the solution for amount. It would be clearer to write packages[amount]. Then the reader wouldn't have to remember how many elements there are in the list packages.
In the line:

if dp[-1] > amount or packages[-1][-1] < 1:

the first part of the condition (dp[-1] > amount) is unnecessary; the second part of the condition suffices.

2. Revised code

def coin_change(amount, coins):
    """Given a target amount and a sorted list of coins denominations,
    determine how to make change for amount with the minimum number of
    coins, subject to the restrictions that every denomination is used
    and the number of coins of a small denomination must be greater
    than the number of coins of a large denomination. Return a list
    giving the number of coins of each denomination, or raise
    NoSolution if making change is impossible under the constraints.

    """
    # min_coins[i] is smallest number of coins found making change for i.
    min_coins = [0] + [float('inf')] * amount

    # solutions[i][j] is the number of coins of the j'th denomination in
    # the best solution found making change for i.
    solutions = [[0] * len(coins)] * (amount + 1)

    for i in range(1, amount + 1):
        for j, coin in enumerate(coins):
            if coin > i:
                break
            last = i - coin
            solution = solutions[last]
            if (min_coins[i] > min_coins[last] + 1
                and (j == 0 or solution[j - 1] > solution[j] + 1)):
                min_coins[i] = min_coins[last] + 1
                new_solution = list(solution)
                new_solution[j] += 1
                solutions[i] = new_solution

    if solutions[amount][-1] == 0:
        raise NoSolution()
    else:
        return solutions[amount]

3. Improved algorithm

The data structure packages ends up containing len(coins) * (amount + 1) values. But this is a waste of memory and computation, because you ought to be able to describe each solution by giving only the denomination of the highest coin used in that solution. Then you could subtract that coin and look up the remainder to get the next coin, and so on.

But if you try to implement this then you'll struggle, because in the revised data structure you can't apply the restriction that every denomination is used and the number of coins of a small denomination must be greater than the number of coins of a large denomination.

However, there's a way to transform the problem so that it turns into an ordinary (unrestricted) change-making problem. The idea is that if you're given the problem instance:

  make change for 20 using fewest coins with values 1, 2, 5 (with the restriction)

then you transform it into:

  make change for 8 using fewest coins with values 1, 3, 8 (without the restriction)

which has the solution 0, 0, 1 which transforms into the solution 4, 3, 2 in the original problem.

No doubt you're asking, what is this transformation and how does it work? There are two steps in the transformation:

Any solution has to contain at least one of the highest denomination of coin (because all denominations have to be included), at least two of the second highest denomination (because the number of coins of a small denomination must be greater than the number of coins of a large denomination), at least three of the third highest denomination, and so on. So we can start by subtracting all these coins from the amount, and then drop the restriction that all denominations have to be included.

In the example above, we know that the solution has to include at least 3×1, 2×2 and 1×5, so we start by subtracting 12 from the amount, getting 8.
Now, whenever we add a coin of some denomination to the solution we're building up, we have to add coins of all smaller denominations too, to maintain the restriction that number of coins of a small denomination must be greater than the number of coins of a large denomination. So if we add a coin of denomination 2, then we have to add a coin of denomination 1 too. And if we add a 5, we have to add 2 and 1 too.

But if a 2 always has to be accompanied by a 1, this is almost the same as having a coin of denomination 3. And if 5 always has to be accompanied by a 2 and a 1, this is almost the same as having a coin of denomination 8. So we can transform the problem into one where the coins have values 1, 3, and 8, and then drop the restriction that number of coins of a small denomination must be greater than the number of coins of a large denomination.

I wrote "almost the same" above because there is a difference in how we have to count the number of coins in order to ensure we meet the "minimum number of coins" condition. See the line marked "(A)" in the code below.

In the transformed problem we can represent the solutions more compactly as discussed above, and then reconstruct the full solution coin by coin at the end. Here's an implementation.

from itertools import accumulate

def coin_change(amount, coins):
    """Given a target amount and a sorted list of coins denominations,
    determine how to make change for amount with the minimum number of
    coins, subject to the restrictions that every denomination is used
    and the number of coins of a small denomination must be greater
    than the number of coins of a large denomination. Return a list
    giving the number of coins of each denomination, or raise
    NoSolution if making change is impossible under the constraints.

    """
    # Transform problem into (almost) standard change-making problem.
    coins = list(accumulate(coins))                    # see (2) above
    amount -= sum(coins)                               # see (1) above
    if amount < 0:
        raise NoSolution()

    # min_coins[i] is smallest number of coins found making change for i.
    min_coins = [0] + [float('inf')] * amount

    # solutions[i] is the index of the highest coin in the best
    # solution found making change for i, or -1 if no solution has
    # been found.
    solutions = [-1] * (amount + 1)

    # Solve the transformed problem
    for i in range(1, amount + 1):
        for j, coin in enumerate(coins):
            if coin > i:
                break
            last = i - coin
            new_coins = min_coins[last] + j + 1        # (A)
            if min_coins[i] > new_coins:
                min_coins[i] = new_coins
                solutions[i] = j

    # Reconstruct solution in the transformed problem.
    result = [0] * len(coins)
    while True:
        j = solutions[amount]
        if j == -1:
            break
        result[j] += 1
        amount -= coins[j]
    if amount != 0:
        raise NoSolution()

    # Transform solution back again.
    return list(accumulate(r + 1 for r in reversed(result)))[::-1]


Not sure about your full implementation, but from what I see, you could do a fluent API
something like :

public class PhysicsProcess
{
    private readonly float _delta;
    private readonly Vector2 _velocity;

    public PhysicsProcess(Vector2 velocity)
    {
        _velocity = velocity;
    }

    public PhysicsProcess Run()
    {
        // Run logic which would be saved on the global variable
        return this;
    }

    public PhysicsProcess Jump() { ... }

    public PhysicsProcess Dash() { ... }

    public PhysicsProcess Friction() { ... }

    public PhysicsProcess Gravity() { ... }

    public void Apply()
    {
        // Your final logic which would take all arguments, and do the process you need.
    }

}

then your usage would be something like :

var process = new PhysicsProcess(velocity)
.Run()
.Jump()
.Dash()
.Friction()
.Gravity()
.Apply();

You can then extend or customize each process as fits your needs. You can also make PhysicsProcess as nested class and call it from a method from the parent class. There are many approaches and customization can be done with fluent APIs, just choose the approach that you see it would be more reasonable to the existing logic (technically, and business-wise).

UPDATE

As I mentioned, fluent API is an easy interface to use and customize. For that, you can also make it an extension like this :

public static class Vector2Extensions
{
    public static PhysicsProcess Apply(this Vector2 velocity)
    {
        return new PhysicsProcess(velocity);
    }
}

now you can for instance add new method to your fluent API class say Save() for instance, which would return Vector2, then you could do something like this :

moveVelocity.Apply()
    .Run()
    .Jump()
    .Dash()
    .Friction()
    .Gravity()
    .Save();

When you use this approach, it would make it more maintainable and easy to extend.

I hope this would make it more useful answer.


Computing bezier curves of degree n with recursive functions

Recursion

[Edit]
In bezier(), the 2 recursive calls to bezier() is inefficient as it exponential grows with O(2n) and only O(n2) operations are needed.   I suspect  better efficiency (linear) can be had  with a pre-computed weighing of the d[] terms below.

The concern about seg faulting due to excessive recursion would be mitigated with the above improvement.

I also change function bbezier() to code.

long double bezier_alt1(long double t, const uint64_t *points, size_t n) {
  assert(n);
  long double omt = 1.0 - t;
  long double d[n];  // Save in between calculations.

  for (size_t i = 0; i < n; i++) {
    d[i] = omt * points[i] + t * points[i + 1];
  }
  while (n > 1) {
    n--;
    for (size_t i = 0; i < n; i++) {
      d[i] = omt * d[i] + t * d[i + 1];
    }
  }
  return d[0];
}

[Edit2]

A linear  solution O(n) is possible with O(1) additional memory.

long double bezier_alt2(long double t, const uint64_t *points, size_t n) {
  assert(n);
  long double omt = 1.0 - t;
  long double power_t = 1.0;
  long double power_omt = powl(omt,n);
  long double omt_div = omt != 0.0 ? 1.0/omt : 0.0;

  long double sum = 0.0;
  unsigned long term_n = 1;
  unsigned long term_d = 1;
  for (size_t i = 0; i < n; i++) {
    long double y = power_omt*power_t*points[i]*term_n/term_d;
    sum += y;
    power_t *= t;
    power_omt *= omt_div;
    term_n *= (n-i);
    term_d *= (i+1);
  }
  power_omt = 1.0;
  long double y = power_omt*power_t*points[n]*term_n/term_d;
  sum += y;
  return sum;
}

Additional linear simplifications possible - perhaps another day.

Minor stuff

Use const

A const in the referenced data allows for some optimizations, wider application and better conveys code's intent.

// long double bezier(long double t, uint64_t *points, uint64_t n){
long double bezier(long double t, const uint64_t *points, uint64_t n){

Excessive wide type

With uint64_t n, there is no reasonable expectation that such an iteration will finish for large n.

Fortunately, n indicates the size of the array.  For array indexing and sizing, using size_t.  It is the right size - not too narrow, nor too wide a type.

// long double bezier(long double t, uint64_t *points, uint64_t n){
long double bezier(long double t, uint64_t *points, size_t n){

For this application, certainly unsigned would always suffice.

static

Good use of static in static long double bbezier() to keep that function local.

Missing "bezier.h"

I'd expect a bezier() declaration in a .h file and implementation in the .c file instead of extern "C" long double bezier(long double, uint64_t *, uint64_t); in main.c

// extern "C" long double bezier(long double, uint64_t *, uint64_t);
#include "bezier.h".

n range check

Perhaps in a debug build, test n.

long double bezier(long double t, const uint64_t *points, uint64_t n){
  assert( n > 0);    // Low bound
  assert( n < 1000); // Maybe a sane upper limit too


Finding a Bash script's Runfiles as generated by Bazel

The following snippet provides a cross-platform implementation

That looks correct, but the script requires Bash 4, and I don't see any validation of that.

Actually, the only Bash 4 feature is the -v VAR operator of [[,
used as [[ ! -v VAR ]].
I would replace that with [[ ! "$VAR" ]],
even if it's not exactly the same thing,
but probably good enough.

Do you really need the [[ ! -v EXEC_NAME ]] check?
I don't see a point in a caller overriding this,
so I would drop the condition.

From the snippet it's not clear why this variable is exported with the export keyword.
I would review this point, and if there is no reason to export it,
then drop the export.

It seems to me the script is intended to be executed,
as opposed to being sourced.
In this case, you could use $0 as the name of the executable,
no need for the tedious ${BASH_SOURCE[0]}.

According to help test:

-a FILE        True if file exists.
...
-e FILE        True if file exists.

Although using -a is correct, I prefer -e, because it's easy to associate with the word "exists".
I had to look up help test to verify what is -a.

Instead of printf "...\n" it's simpler to write echo "...",
the \n is automatically added,
and the posted snippet doesn't use any interesting feature of printf.

Instead of:

EXEC_PATH="${BASH_SOURCE[0]}"
...
export EXEC_PATH

I would write:

export EXEC_PATH="${BASH_SOURCE[0]}"


C code to parse out certain characters in a string

outputString doesn't have enough room to accomodate the results. It can hold just one byte. It is just unlucky coincidence that the code does not segfault. In any case, undefined behaviour.

If the intention is just to print the result out, you don't need outputString at all. Just printf the tokens as you compute them.
strcat must scan the entire outputString to figure out where it ends. The overall time complexity of the repeated strcats becomes roughly quadratic. I recommend to maintain a pointer to the end of outputString, and strcpy the token.


Quoting

You should double-quote variables that may contain spaces when used as command arguments. For example here:

addToPath $element false NEW_PATH

You will get strange results if $element contains spaces. Double-quote it, and also in the conditional inside the function:

if [ ! -d "$1" ]; then

One statement per line

It's easiest to read code from top to bottom,
without having to carefully read from left to write too. For this reason it would be better to split the conditionals you crammed on a single line.

Simple solutions are better

The optional third parameter of the function is quite clever, appending to a specified variable instead of the default, at the expense of some added complexity. Instead of all that, you could simply reset PATH after setting path_array and before calling the function. That way you could get rid of the third parameter of the function and its added complexity.

Note also that your function does not add duplicates. So instead of removing duplicates at the end, it will be better to remove duplicates at the beginning, as that will process fewer path elements.

case with two cases

When a switch-construct is used with only two cases,
it's usually easier to read converted to an if-else.


Pass more arguments to functions

primes is global, but passing it as an argument to primeSum is trivial:

def primeSum(n, primes):

and then:

primeSum(int(input()), primes)

This makes the reasoning about and testing the function easier.

Do not modify random global variables

out.extend([p,q]) where out is a global variable. Don't. It makes the code impossible to use in different situations and therefore wastes your programming effort.

Do not print from a computation function

primeSum should find a prime sum. Printing the couples nicely is the job for another function. Again a computer friendly return format improves re-usability.

Remove dead code

You write:

limit=math.floor(n/2)

But limit is never been used, so delete that line.

Also p=2 can be eliminated as it does nothing.

Meaningful names

Avoid single-letter names, be descriptive. Good names can really make the difference between un-readable and readable code. And remember to use snake_case in Python.

Final version

Putting all my advice together gives this nice prime_sum function:

def prime_sums(number, primes):
    """
    Checks how a number may be written as a sum of two primes.

    >>> list(prime_sums(100, sorted(set(sieve(100)))))
    [(3, 97), (11, 89), (17, 83), (29, 71), (41, 59), (47, 53)]
    """
    for prime in primes:
        difference = number - prime
        if(prime > difference):
            break
        if(difference in primes):
            yield (prime, difference)


Handle edge cases

If the given numbers array is empty then the first loop will do nothing, but

computedNumbers.append(numbers[count - 1] * numbers[0])

aborts with a runtime exception. The correct result in this case would be to set computedNumbers to an empty array as well.

Better loops

This

var i = 0
while i < count - 1 {
    // ...
    i = i + 1
}

is shorter and better done as

for i in 0 ..< count - 1 {
    // ...
}

The advantages are

The scope of i  is limited to the loop.
i is a constant.
The range of i is clearly seen right at the start of the loop.

In this particular case we iterate of adjacent array elements, which is conveniently by by zip()ping the array with a shifted view of itself:

var computedNumbers = zip(numbers, numbers.dropFirst()).map(*)
computedNumbers.append(numbers[count - 1] * numbers[0])

If we append the first element to the shifted view then the complete operation reduces to

let computedNumbers = zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)

Note that this handles also the case of an empty array gracefully.

Use constants if possible

The numbers array is never mutated, therefore it should be declared as a constant with let:

let numbers = [3, 1, 4, 2]

Using a constant

makes it clear to the reader that this value is never mutated,
helps to avoid unintentional mutation,
possibly allows better compiler optimization.

Make it a function

If we put the functionality in a separate function then

it becomes reusable,
test cases can be added more easily,
we can give it a meaningful name,
we can add documentation.

In our case the function would simply be

/// Compute an array where each element in the numbers array is multipled by
/// the next following element. The last element is multiplied by the first element.
/// - Parameter numbers: An array of integers.
func circularAdjacentProducts(of numbers: [Int]) -> [Int] {
    return zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)
}

and would then be used as

let numbers = [3, 1, 4, 2]
let computedNumbers = circularAdjacentProducts(of: numbers)
print(computedNumbers)

Make it generic on the element type

The same operation could be done with an array of floating point values (Float or Double), or with other integer types (e.g. Int16) as long as the multiplication does not overflow. Therefore we can generalize it to array of type [T] where T conforms to a protocol which required a multiplication operation.

A possible choice is the Numeric protocol which is adopted by all floating point and integer types:

func circularAdjacentProducts<T: Numeric>(of numbers: [T]) -> [T] {
    return zip(numbers, [numbers.dropFirst(), numbers.prefix(1)].joined()).map(*)
}

Example:

let floats = [3.3, 1.1, 4, 2.2]
let computedFloats = circularAdjacentProducts(of: floats)
print(computedFloats) // [3.63, 4.4, 8.8, 7.26]

Make it generic on the collection type

The next possible generalization is to apply this operation not only to arrays, but to arbitrary collections:

extension Collection where Element: Numeric {
    func circularAdjacentProducts() -> [Element] {
        return zip(self, [dropFirst(), prefix(1)].joined()).map(*)
    }
}

Example with an ArraySlice:

let numbers = Array(1...10).dropFirst(3)
print(numbers) // [4, 5, 6, 7, 8, 9, 10]
let computedFloats = numbers.circularAdjacentProducts()
print(computedFloats) // [20, 30, 42, 56, 72, 90, 40]


1. Review

There are no docstrings. What do any of these functions do? How do I call them? What do they return?
Just because leetcode.com insists on a Solution class, doesn't mean that all functions need to be members of that class. Write plain functions and avoid the unnecessary use of self.
I like the implementation of make_defaultdict, but this doesn't just make a defaultdict, it makes an empty prefix tree (trie), so a name like make_empty_prefix_tree would be better. (I prefer the name "prefix tree" because it's clear what it is from the name, whereas the name "trie" is a bit mysterious.)
Distinguishing the end of the prefix_tree by a special key like 'end' ought not to be necessary in this application (constructing word squares) because all of the words are the same length.
When you need to iterate over the keys and values of dictionary simultaneously, use dict.items. For example, this line:

q = [(search_str + k, sub_trie[k]) for k in sub_trie.keys()]

becomes

q = [(search_str + k, v) for k, v in sub_trie.items()]

avoiding the lookup of sub_trie[k].

2. Performance

In order to understand what the code is doing, it is handy to trace its execution on an example. This can be done using the Python debugger, for example we might print the value of square on each call to make_square, like this:

>>> pdb.run("Solution().wordSquares('tide idea dear yarn tidy'.split())")
> <string>(1)<module>()
(Pdb) break Solution.make_square
Breakpoint 1 at cr176612.py:38
(Pdb) commands 1
(com) silent
(com) p ' '.join(square)
(com) continue
(Pdb) continue
'tide'
'tide idea'
'tide idea dear'
'idea'
'idea dear'
'dear'
'yarn'
'tidy'
'tidy idea'
'tidy idea dear'
'tidy idea dear yarn'

(You could get a similar result by editing the code to add a print at the start of make_square but it is a good idea to practice using the debugger on easy examples like this, so that when you have a tough bug to investigate you are proficient with it.)

Looking at the output carefully you can see the problem: after choosing tide for the first row, the search continued by choosing idea for the second row. But this should have been ruled out because then the fourth column would have to start ea and nothing in the dictionary will fit there.

So work is wasted following search paths that could have been rejected earlier if all constraints had been applied. The problem is that only one constraint is applied at a time — on the \$i\$th loop in make_square we use search_trie to apply the constraint for the \$i\$th column only, failing to apply the constraints from columns \$j > i\$.

3. Organizing the work

It takes some thought to figure out how to organize the work so that all constraints are applied at the earliest possible stage. This is the kind of algorithm where it makes sense to work out the details on paper for a simple example, before starting to write code.

Suppose our dictionary consists of all, led, and lee, making the following prefix tree:

The algorithm is going to need the idea of "current position in the prefix tree". I'm going to draw this with a red triangle. For example, if l and e have been matched, then the current position looks like this:

In this position, d and e are the possible matches for the next letter.

Now, in a 3×3 word square there are nine squares to be filled:

In the real problem the result is required to be symmetric, so that choice 2 is the same as choice 4 and so on, but it will be clearer, I think, to solve the general problem first and then figure out how to take advantage of symmetry later.

When we come to make a choice for a square there are two constraints we have to satisfy, a horizontal constraint for the row and a vertical constraint for the column. The constraints correspond to positions in the prefix tree. For choice number 1, the constraints in both directions correspond to the root of the prefix tree, like this:

The vertical constraint says that we can choose a or l, and so does the horizontal constraint. Let's suppose that we choose a. Then we can update the position in the prefix tree to make constraints for the next cells, like this:

Now we can consider the constraints bearing on choice number 2, bringing in a fresh vertical constraint:

Here, the vertical constraint says that we can choose a or l, and the horizontal constraint says that we can only choose l, so this is our only way to satisfy both constraints. Once again we can propagate the constraints:

The process continues through the choices in order, until all constraints have been applied and a solution has been found (or until a dead end has been reached where the constraints cannot be satisfied, in which case we have to backtrack). If a solution is found, the data structures will look something like this:

4. Data structures

Given the approach outlined in §3 above, how can we represent the state of the search in a data structure? Well, we will need choices (the black squares in the diagram below) which we will consider in order. For each choice we have constraints bearing on that choice (the blue diamonds connected to the choice by blue lines), and there are rules specifying how to propagate the constraints after a choice has been made (the red arrows which join two blue diamonds by passing through a black square).

We can represent constraints by objects with a node attribute:

class Constraint:
    node = None     # Node in the prefix tree, or None if not initialized.

(These need to be objects rather than, say, named tuples, because the node gets modified when a constraint is propagated.)

We can represent choices as objects with lists of constraints and propagation rules:

class Choice:
    def __init__(self, constraints, rules):
        """Create a choice.

        Arguments:
        constraints: List of Constraint objects.
        rules: List of propagation rules as pairs (Constraint, Constraint).

        """
        self.constraints = constraints
        self.rules = rules

    def options(self):
        "Return set of available options, assuming initialized constraints."
        # Intersect all the keys of the constraint dictionaries.
        constraints = iter(self.constraints)
        options = next(constraints).node.keys()
        for c in constraints:
            options &= c.node.keys()
        return options

    def propagate(self, choice):
        "Propagate a choice from source to destination constraints."
        for source, dest in self.rules:
            dest.node = source.node[choice]

Now finding all assignments that meet the constraints is a straightforward depth-first search, and a convenient way to implement this in Python is to use the stack of iterators pattern, like this:

def assignments(choices):
    """Generate satisfying assignments to a sequence of choices."""
    n = len(choices)
    assignment = [None]
    stack = [iter(choices[0].options())]

    # Cache methods in local variables to avoid lookups in the loop
    assignment_append = assignment.append
    assignment_pop = assignment.pop
    stack_append = stack.append
    stack_pop = stack.pop

    while stack:
        for option in stack[-1]:
            i = len(assignment)
            if i < n:
                assignment_append(option)
                choices[i - 1].propagate(option)
                stack_append(iter(choices[i].options()))
                break
            yield tuple(assignment[1:]) + (option,)
        else:
            assignment_pop()
            stack_pop()

Notice that this generates the assignments one by one instead of collecting them all and returning a list. Generating results is more flexible than returning a list: for example, if you only want one assignment then you can use next(assignments(choices)), or if you want to see whether there is a unique assignment or not then you can use islice(assignments(choices), 2), without having to wait for the search to run all the way to completion.

It's a bit fiddly to build the data structure, but we can do it like this:

from itertools import product

def word_squares(words):
    """Generate word squares from a sequence of words."""
    n = len(words[0])
    assert all(len(word) == n for word in words)
    prefix_tree = make_prefix_tree(words)

    # Horizontal and vertical constraints for each choice.
    N = range(n)
    horiz, vert = [[[Constraint() for _ in N] for _ in N] for _ in range(2)]
    for k in N:
        horiz[k][0].node = vert[0][k].node = prefix_tree

    # Create choices.
    choices = []
    for i, j in product(range(n), repeat=2):
        h, v = horiz[i][j], vert[i][j]
        rules = []
        if j < n - 1:
            rules.append((h, horiz[i][j + 1]))
        if i < n - 1:
            rules.append((v, vert[i + 1][j]))
        choices.append(Choice([h, v], rules))

    # Find assignments and reformat them.
    for assignment in assignments(choices):
        yield [''.join(word) for word in zip(*[iter(assignment)] * n)]

5. Adding symmetry

Now it ought to be clear how to implement symmetry. We drop the squares that we don't need to fill, and reroute the constraint propagation like this:

It's still fiddly to build the choices structure, but it can be done like this:

from itertools import combinations_with_replacement

def symmetric_word_squares(words):
    """Generate symmetric word squares from a sequence of words."""
    n = len(words[0])
    assert all(len(word) == n for word in words)
    prefix_tree = make_prefix_tree(words)

    # Horizontal and vertical constraints for each choice (some we
    # won't use, but it's simpler like this).
    N = range(n)
    horiz, vert = [[[Constraint() for _ in N] for _ in N] for _ in range(2)]
    for k in N:
        horiz[k][0].node = vert[0][k].node = prefix_tree

    # Create choices.
    choices = []
    for i, j in combinations_with_replacement(N, 2):
        h, v = horiz[i][j], vert[i][j]
        rules = []
        if i == j:
            constraints = [v]
            if j < n - 1:
                rules.append((v, horiz[i][j + 1]))
        else:
            constraints = [h, v]
            if i != j < n - 1:
                rules.append((h, horiz[i][j + 1]))
            if j != i < n - 1:
                rules.append((v, vert[i + 1][j]))
        choices.append(Choice(constraints, rules))

    # Find assignments.
    grid = [[None] * n for _ in N]
    for assignment in assignments(choices):
        for a, (i, j) in zip(assignment, combinations_with_replacement(N, 2)):
            grid[i][j] = grid[j][i] = a
        yield [''.join(word) for word in grid]

Note the use of itertools.combinations_with_replacement here — this is useful when you would otherwise need two nested loops to loop over all \$0 \le i \le j < n\$:

    for i in range(N):
        for j in range(i, N):

Here combinations_with_replacement combines the two loops into one, saving a level of indentation.

6. Timing comparisons

I got kind of carried away there with data structures and algorithms, so I'm not sure if the revised code will really be any faster. Let's try an example, using all the 4-letter words in my system dictionary, which can make 4.3 million symmetric word squares:

>>> words = [w for w in map(str.strip, open('/usr/share/dict/words'))
...          if len(w) == 4 and w == w.lower()]
>>> len(words)
4347
>>> sum(1 for _ in symmetric_word_squares(words))
4264868
>>> timeit(lambda:sum(1 for _ in symmetric_word_squares(words)), number=1)
49.30328282299888
>>> timeit(lambda:Solution().wordSquares(words), number=1)
66.61988531300449

So the revised code takes about 75% as long as the original.


One major thing:
Queue consists of node which consist of data. Here, your data is Customer.
Data should not be coupled with the Queue i.e. think this way.

   typedef struct Node{
         Node* next; // navigation pointer.
         Customer customer; // data
   }Node;

Considering the current implementation, here are a few points to go with:

Initialize misses to initialize customer_cnt = 0;.
Where are you allocating the Queue instance. Instead, have getQueueNode which allocates memory for the node and initialise that as well. Allocation at one place helps for e.g: easy debugging when malloc returns null due to insufficient memory.
Extract common code outside the if-else block in enqueue().
Put related code at once i.e. in dequeue operations for head_customer could be consecutive.


Fetch Reattempt and Hold Date count in efficient way

You can create one query and select all elements. For example:

select sum(case when DATE(reattemptdate) = CURDATE() THEN 1 ELSE 0 END) as reattemptdate,
       sum(case when DATE(holddate) = CURDATE() THEN 1 ELSE 0 END) as holddate,
       sum(case when DATE(reattemptdate) = DATE(NOW() - INTERVAL 1 DAY) THEN 1 ELSE 0 END) as prev_reattemptdate,
       sum(case when DATE(holddate) = DATE(NOW() - INTERVAL 1 DAY) THEN 1 ELSE 0 END) as prev_holddate
from orders;

php:

$results = $db_handle->runSelectQuery($sql);
$reattemptdate =$results[0]['reattemptdate'];
$holddate =$results[0]['holddate'];
$prevReattemptdate =$results[0]['prev_reattemptdate'];
$prevHolddate =$results[0]['prev_holddate'];
// display counters
echo $reattemptdate;
echo $holddate;
echo $prevReattemptdate;
echo $prevHolddate;


Web service getting value using LINQ from queue table in SQL database

LINQ is a good choice. You're querying something, so it lends itself to the task.

That being said, the exception handling is atrocious. Making your return values null, some command's value from the database or some big honkin' exception text is abusing the string data type. I'd remove the try..catch altogether and let your client app handle the exception if it knows what to do. In the best case, your catch could log the error somewhere then re-throw.


Honestly, the code seems a bit long for what it does. I'm not suggesting anything crazy like code golf, but is there maybe some way to unify (byte_position, bit_position) so a single call advances one bit at a time? I'm looking for a simple invariant that you maintain across calls. The read* functions appear to be on the verbose side.

You have at least four kinds of values: byte_val, bit_val, byte_pos, bit_pos. I encourage clear consistent naming around those. In particular the comments about leaving "result" on the stack are more vague than I'd like to see.


Find the fastest run of each year from a list of running results

First solution using .forEach, for...in and .sort

Here what I did to achieve this:

First sort your array of objects, i.e convert:

data = [ {...}, {...}, {...}, {...}, {...}, {...} ]

into an object sorted by year:

sortedY = { 2017: [{...}, {...}, {...}], 2018: [{...}, {...}, {...}] }

You can achieve such result by using a forEach loop:

const sortedY = {};
data.forEach(e => {
    const year = e.date.split('-')[0];
    sortedY[year] = sortedY[year] || [];
    sortedY[year].push(e);
});

Then we will need to sort each object [{...}, {...}, {...}] per year by duration. sorted is not an array. We can't use map unfortunately: use a for...in loop instead. However to sort each key/value (<=> year/array of results for this year) we can use one of Array's methods: sort, the sorting criteria is the following:

(a,b) => a.duration > b.duration

Where a and b are two different races from the same year.

So with:

sortedY[year].sort((a,b) => a.duration > b.duration)

You get an array of sorted races for the year year.

The last thing to do is saving the first of the sorted array (the first is the one with the shortest duration, so select it with [0] and add it to result:

result[year] = sortedY[year].sort((a,b) => a.duration > b.duration)[0]

The final code is:

const sortedY = {};
data.forEach(e => {
    const year = e.date.split('-')[0];
    sortedY[year] = sortedY[year] || [];
    sortedY[year].push(e);
});

const result = {};
for(year in sortedY) {
   result[year] = sortedY[year].sort((a,b) => a.duration > b.duration)[0];
}

console.log(result);
<script>
const data = [ { id: 1, date: '2017-01-01 00:00:00', duration: 195 }, { id: 2, date: '2017-01-10 00:00:00', duration: 270 }, { id: 3, date: '2017-03-12 00:00:00', duration: 220 }, { id: 4, date: '2018-01-10 00:00:00', duration: 218 }, { id: 5, date: '2018-02-23 00:00:00', duration: 220 }, { id: 6, date: '2018-05-18 00:00:00', duration: 215 } ]
</script>

Second solution using only .forEach

I realised there was a quicker way of doing this: we don't need to loop over the array data twice! One loop will suffice. Indeed, we'll fill result as we navigate through data only replacing a yearly race if a race is shorter in duration.

So a race will be added to result[year] only if:

!result[year] || (result[year] && e.duration < result[year].duration)

is true, i.e. if either:

there is no race registered for the year year
there is one but its duration is longer than the one that we're checking

So the code is shorter, simpler and I bet it will be quicker: its complexity is \$O(n)\$. The previous code was cool but not so much efficient. I was looping twice the data: first time for the sorting, second on the sorted array. Not even mentioning that I was using sort...

let result = {};
data.forEach(e => {
  const year = e.date.split('-')[0];
  if( !result[year] || (result[year] && e.duration < result[year].duration) ) {
    result[year] = e;
  }
})

console.log(result);
<script>
const data = [ { id: 1, date: '2017-01-01 00:00:00', duration: 195 }, { id: 2, date: '2017-01-10 00:00:00', duration: 270 }, { id: 3, date: '2017-03-12 00:00:00', duration: 220 }, { id: 4, date: '2018-01-10 00:00:00', duration: 218 }, { id: 5, date: '2018-02-23 00:00:00', duration: 220 }, { id: 6, date: '2018-05-18 00:00:00', duration: 215 } ]
</script>


Welcome to Kotlin! Consider this.

// Define constructor this way
class UserSettings(context: Context) {
    // Prefixes for fields are rather uncommon in the Kotlin world.
    // You could remove the type declaration here - Kotlin will infer it for you
    private val prefs: SharedPreferences = context
        .getSharedPreferences("UserSettings", Context.MODE_PRIVATE)

    var deviceId: String
        get() = prefs.getString(KEY_DEVICE_ID, null) ?: UUID.randomUUID().toString().also {
            // `also` block will execute only in case we return a new UUID.
            deviceId = it
        }
        set(it) {
            prefs
                .edit()
                .putString(KEY_DEVICE_ID, it)
                .apply()
        }

    companion object {
        // Depends on a taste / convention your team uses.
        // I like keeping my key constants within the companion object.
        private const val KEY_DEVICE_ID = "deviceId"
    }
}

For simplifying it even more, consider using Android KTX - it has some handy SharedPreferences extensions, described here: https://developer.android.com/kotlin/ktx


Day finder program, inputs date, outputs day of the week

Declaring a new DayFinderLaunch inside DayFinder is bad (and wrong): DayFinder must find the day and nothing more (another error here: DayFinderLaunch calls DayFinder that calls DayFinderLaunch that calls DayFinder (and so on...)

compute is the main method of DayFinder, I'd rename it to findDay, getDayOfWeek or similar. You're calling it from a validation method, wrong!

Moreover, this method MUST NOT print to the console the result. A better approch is return the name of the day so the developer can choose how to manage it (Console log? File log? Message Box?)

The date validation should be done inside getDayOfWeek(). If validation fails, an exception should be throw: DayFinder MUST NOT ask for user input again, it's not its job!

...
final String dayOfWeek = getDayOfWeek(2017, 5, 30);

System.out.println("Day: " + dayOfWeek);
...
fileWriter.writeLine("Day: " + dayOfWeek);
...

public String getDayOfWeek(final int year, final int month, final int day) {
    if (!isDateValid(year, month, day)) {
        throw new InvalidDateException(String.format("Date %d/%d/%d is not valid", year, month, day));
    }

    String dayOfWeek;

    ...

    return dayOfWeek;
}

I don't understand what mArr, cArr, yc, mc etc. are, you should use significative names.
mArr, cArr and mDays could be extracted from methods and declared as constants in DayFinder
dArr could become a Day enum.

Example:

public enum Day {
    SUNDAY("Sunday")
    MONDAY("Monday"),
    ...
    ...
    SATURDAY("Saturday");

    private final String name;

    private Day(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

so you can retrieve the day name using the following:

String dayOfWeek = Day.values()[index].getName(); // index must be valid of course!

isLeap should be moved in a DateUtils class:

public final class DateUtils {
    public static boolean isLeap(int year) {
        return ((y % 4 == 0) && (y % 100 != 0))
            || ((y % 100 == 0) && (y % 400 == 0));
    }
}

I didn't check if your algorithm is correct.


First of all, main should be declared int main.

Second, I would advise passing the cnt (which I have called iteration_number) as a parameter as well. Also, you should avoid using a global (b). If you define a helper function, that won't change the signature of your function:

int add_helper(int value, int max, int iteration_number)
{
    if (iteration_number >= max) return value;

    return add_helper(value + 1, max, iteration_number + 1);
}

int add(int a, int b)
{
    add_helper(a, b, 0);
}

Note that I have refactored your b to be a parameter, which I have called max. The function can be used like this:

int main(void)
{
    int start = 9; // Your a
    int count = 6; // Your b

    int sum = succ(start, count);
}

(If you are using C89 instead of C99 or C11, there should be a return 0; at the end of main()).

However, the "good" way to define addition recursively is by increasing one number and decreasing the other:

int add(int a, int b)
{
    if (b == 0) return a;

    return add(a + 1, b - 1);
}

Modifying the function to work with negative numbers is left as an exercise to the reader.

(Note: Normally you want to subtract from the lowest number and add to the largest. I left that out to keep the example compact.)

  I also want to understand how stacking happens in this case for variables cnt and x.

By "stacking", I assume you mean how the variables are pushed onto the stack as the function is called. Your cnt has static linkage, and is not pushed onto the stack at all. In my example, value, max and iteration_number will be pushed onto the stack for each call. (Exactly how is, as far as I know, implementation defined and depends on the calling convention in use.) In other words, assuming no optimization, the arguments will take iteration_number * sizeof(int) bytes on the stack.

If you want to keep track of the values, simply print them in the recursive function like this:

int succ_helper(int value, int max, int iteration_number)
{
    if (iteration_number >= max) return value;

    printf("%d: %d - %d\n", iteration_number, value, max);

    return succ_helper(value + 1, max, iteration_number + 1);
}

  Can anyone suggest optimization or better code for this?

int sum = 9 + 6;

:-)


Is this a sufficient way to prevent script injections and other bad stuff in strings

That one is quite simple (for me at least) since there is a very general answer :)

NO

There is no way you can ever really safely "repair" user input.

  "Please provide a list of everything you shouldn't to with a hammer"

is way harder than

  "list all appropriate uses of a hammer".

You might forget one or two but no harm done there if you go back and add them.

It might sound harsh but something will always byte you and if it's only EVAL(UNHEX(ASD23426363)) or something like that. (Sql example even so you did say it not sql but whatever).

Of course you might want to do things like strip out tags out of input for html context anyways so that a hole in your other code is not as easily exploited and less damage will be done but i shouldn't be your only defense.

Someone that said Filter Input, Escape Output way better than i could. Terry Chay

In short: Whatever you are doing there, find the appropriate escaping function and use it.

Shell context ? escapeshellarg

Html context ? htmlspecialchars

Database context ? Use prepared statements and never worry about sql injection again

Little edit:
I know what i said and the blog post contradict a little but thats fine with me. 'In practice' will always differ from general advice and sometimes you want to do everything you can ;)


Don't use volatile in the below line

    private volatile MyQueueNode<T> _headNode, _tailNode;

Link https://www.infoworld.com/article/3229360/application-development/how-to-use-the-volatile-keyword-in-c.html


Am I multiplying two matrices together correctly?

No. Let's first look at it as two dimensional arrays, so we know what we're talking about:

int i[4][4];
int j[4][4];
int k[4][4];

for (int x = 0; x < 4; x++) { // row number of output
    for (int y = 0; y < 4; y++) { // column number of output
        k[x][y] = 0;
        for (int z = 0; z < 4; z++) { // four elements are added for this output
            k[x][y] += i[x][z] * j[z][y];
        }
    }
}

Important difference!!! We start at 0 for the indices!

Now I'll convert it to int[16]s for you assuming that i[1] is the second element of the first row:

int i[16];
int j[16];
int k[16];

for (int x = 0; x < 4; x++) { // row number of output
    for (int y = 0; y < 4; y++) { // column number of output
        k[4*x+y] = 0;
        for (int z = 0; z < 4; z++) { // four elements are added for this output
            k[4*x+y] += i[4*x+z] * j[4*z+y];
        }
    }
}

This is equivalent to your code except for the fact that you start at 1 instead of zero.


C++17 enum macro with to_string operator

I’m really not a fan of this idea, on a lot of levels. First of all, it’s extremely limited; it only works for the most basic enum definitions. As soon as you add initializers or attributes, chaos ensues. Second, it’s just absurdly overcomplicated for what should be trivial code. The fact that you’re having problems with code gen should be a warning sign. There is no way I could justify the debugging effort if I tried to use this and something went sideways.
In my opinion, manually rolling out a to_string() function for an enum isn’t that much extra work. Certainly not enough to justify the level of complexity of this macro. And if your primary concern is compile time (really? that’s the most important thing? how many enums do you have, and how big are they that this is even measurable, let alone the most crucial issue?), then a manually rolled function will compile MUCH faster than the code in that macro. Yeah, sure, you have to repeat yourself a little bit… but not that much. Certainly not enough to justify a state machine parser for a string (that also only works in the simplest cases).
But okay, let me set aside my qualms about the overall idea, and focus on the code itself.
#define EnumWithUnderlying(Name, NTy, ... )\
enum class Name : NTy {__VA_ARGS__, End };\

You don’t include any comments or documentation to explain the logic of the macro, so I don’t know if this extra End enumerator is a feature or a bug. In other words, I don’t know if there is a reason someone might want End added to their enumerators, or if you just added it to make your code work.
Assuming it’s just there to make things work… the only purpose I can make out for it is that you use it to figure out the size of your enumerator arrays, such as in:
using ArrIdxTy = std::array<BeginLen, NTy(Name::End)+1>;

This “works” only so long as none of the enumerators have any initializers (that don’t happen to equal what their default values would be), but aside from being brittle, it’s also unnecessary. If all you need is the count of initializers, then all you need is something as simple as:
template <typename... Args>
constexpr auto count_args(Args&&...) noexcept
{
    return sizeof...(Args);
}

using ArrIdxTy = std::array<BeginLen, count_args(__VA_ARGS__) + 1>;

If End serves some other purpose, then fine, there’s no need to remove it… but in that case you still might want to get the number of enumerators using a count function like the one above. That way your macro won’t break if any enumerators have initialzers. (Well, it won’t break in that particular way, anyway.)
namespace std {\
    std::string_view to_string(enum Name enumIn) noexcept {\

There are a very limited number of cases where you are allowed to add stuff to std—really just a few templates that you are allowed to specialize in fairly restricted ways. Adding a completely new function? Definitely not allowed. No, not even if it’s an overload of an existing function.
To make matters worse, the function lies. When I call to_string()… I expect to get a string. Not a view to a string.
I figure that your goal is to be able to write std::to_string(enum_value)… but that goal is misguided. When I see std::some_func() that I’ve never seen before, the very first thing I do is go straight to my favourite standard library reference (cppreference) and read the docs. But I won’t find this function there, now will I?
You might respond: “But it does the same thing std::to_string() does for all the types it is defined for!” Does it, though? If I do auto x = Move::UP; std::cout << std::to_string(x);, it will print “UP”. But if I do auto x = SOME_INT_CONSTANT; std::to_string(x); it will not print “SOME_INT_CONSTANT”. std::to_string(int) prints the (locale-flavoured) value of an int… not its name… yet your enumerator-specific std::to_string() functions print the name. Not the same thing, now is it?
You might respond: “But what it does is so obvious!” Is it, though? I mean, ignoring that it actually doesn’t do what it claims to (it returns a std::string_view, not a std::string), converting an enumerator value to a string doesn’t necessarily mean returning the enumerator’s name. It might actually make more sense to return the enumerator’s numeric value as a string in some cases.
So in summary:

std::to_string() is the wrong name for this function; and
even if it weren’t, you can’t use it.

So what’s the right name? Well, why not just to_string() in the same namespace as the enum? (Well, better would be to_string_view(), but one thing at a time.) ADL would find the function when you need it, so you’d only have to call to_string(enum_value)… which is actually shorter than std::to_string(enum_value).
(It might also make sense to define a to_string() function in terms of a to_string_view() function. That’s actually how I usually do it.)
Now to get into the meat of the code… what this does (as I understand it) is take the variadic macro arguments, translate the bunch of them into a single string, then use a state machine to parse out the enumerator names into an array. As I mentioned above, your parser is too simplistic—it can’t handle initializers or attributes—but let’s ignore that issue for now.
The biggest problem with your strategy is the assumption that all the enumerators in an enumeration have their default “natural” values. If they don’t, you probably have UB, because your enumerator values won’t be valid indexes into the array.
A less critical issue is that if you really only want to support trivial enumerations (that is, no initializers), that’s fine… but in that case, this seems wildly over-complicated. All you need to do to find the Nth enumerator is find the (N−1)th comma and the Nth comma, take everything between them, then trim the whitespace. Special case the first and last enumerators (or don’t! add a leading and trailing comma to the string to simplify the algorithm!), and you’re done.
If you intend to support general enumerations, then this design just won’t work: you can’t simply cast the enumerator to a number and use that as an index. You need a map. No, not a std::map; that would be overkill. std::array<std::tuple<Name, std::string_view>> would suffice. To actually implement this, all you’d need is some kind of preprocessor for-each—either roll your own or use one from a library—then you could just do something like this:
// Takes an arbitrary enumerator string with arbitrary whitespace:
//     *   "foo"
//     *   "foo = N"
//     *   "foo [[attribute]]"
//     *   "foo [[attribute]] = N"
// and extracts just the enumerator ("foo").
constexpr auto extract_enumerator(std::string_view) -> std::string_view;

#define ENUM_STR_MAP_ITEM(enumerator) std::tuple{enumerator, extract_enumerator(#enumerator)},

constexpr auto enumerator_string_map = std::array{
    FOREACH(ENUM_STR_MAP_ITEM, __VA_ARGS__)
};

And to_string_view() could use that map.
struct BeginLen {\
    std::size_t begin;\
    std::size_t len;\
};\

So, your strategy is to parse the string into an array of BeginLen objects, then transform that into an array of std::string_view. But… why? A std::string_view is literally just a “begin” and a “len” already. The entire last quarter of your function is literally just a transform that does std::string_view{begin, len} for each BeginLen. Why not parse the enumerator strings directly into std::string_views and skip that last bit?
std::size_t jbegin = 0;\
std::size_t jend = 0;\

Why do you need two indexes to keep track of which enumerator you’re currently parsing? (I mean, I assume that’s what those variables are for, in lieu of any comments or even clear names.) Couldn’t you drop jend, remove the jbegin++;, and replace jend with jbegin in the In case?
Summary
You have a number of critical bugs and conformance issues:

You are not allowed to add new functions to namespace std. (An overload of an existing function is still a new function.)
Your method for determining the number of enumerators is broken. (It only works for trivial enums, and it adds a new enumerator, which is not ideal (unless there’s another reason for it?).)
Your method for mapping enumerators to their strings is broken. (You assume a trivial enum, where you can cast the enumerator value to an index.)
Your method for parsing enumerator strings will only work properly for trivial enums. (For non-trivial enums it will return weird results, but technically (so far as I can tell) won’t actually trigger UB.)

I know your primary performance concern is the compile time, but just in case you do care about run time performance… this code is extremely inefficient for what it actually does. It sounds like you don’t care; you figure it will all be constexpred away. Well, maybe, maybe not. There doesn’t seem to be any real reason not to make it more efficient in either case.
Style-wise, my biggest complaint would have to be the complete lack of any commenting or documentation. I know commenting a macro isn’t the easiest thing to do. But it’s still worth it; especially for a macro as complicated as this.
It also doesn’t help that most of your identifiers are terrible. jbegin? What’s “j”? ArrStrTy? Whut? A struct that contains only the members begin and len being called BeginLen? That’s really not helpful at all. A function called to_string() that doesn’t actually convert to a string?
The other thing that raises my hackles is that your macros are mixed-case. That’s just BEGGING for trouble. (Even more alarming is that you use mixed-case macros WHILE ALSO USING MIXED-CASE IDENTIFIERS!!! There’s a point where you’ve loaded a gun, pointed it at your foot, taken the safety off, and started feathering the trigger, and if you end up blowing your foot off, no one can possibly take you seriously for being surprised.)
(I’d also raise complaints about the header file being named “enum.h”. “.h” is for C header files. For C++ header files, you should use “.hpp”, “.hxx”, “.hh”, or something similar.)
Overall design-wise… I might be convinced of the utility of a make-an-enum-with-a-built-in-to_string macro. But not if that macro is as complex as this. A macro should make my code easier… if a macro makes things harder (to understand, to debug), then it’s not worth it. If you could make this macro much, MUCH simpler (I have to figure out an ad hoc state machine just to get enumerator strings?!), then it might be worthwhile.


Python function to determine whether a given BST is valid

Stick with None

One of the things you do is effectively convert Nones into -inf and +inf. But that's not necessary. Stick with None, and then you can ignore those comparisons. I would additionally explicitly default the arguments:

def is_valid(root, min=None, max=None):
    if not root:
        return True
    if min is not None and root.value <= min:
        return False
    if max is not None and root.value >= max:
        return False
    return is_valid(root.left, min, root.value) and is_valid(root.right, root.value, max)

I also removed the print - since you don't really want random output as you go through your function.

Besides that, looks good to me. The last line is a bit long, so I might wrap it in parentheses just so I can do:

    return (is_valid(root.left, min, root.value) and
            is_valid(root.right, root.value, max))

Try to keep your lines below 80 characters.

An alternate implementation, just throwing it out as an idea for thinking about the problem completely differently is this. A BST is valid if it's in-order traversal is actually ordered. An in-order traversal would be:

def traverse_in_order(root):
    if root:
        yield from traverse_in_order(root.left)
        yield root.value
        yield from traverse_in_order(root.right)

In Python2.7, replace yield from X with for x in X: yield x. Basically, we're turning our tree into an iterable. Then, we can just pairwise iterate over this with some itertools recipes:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

And just check that every pair is in strictly increasing order:

def is_valid(root):
    return all(i < j for i,j in pairwise(traverse_in_order(root)))

Not saying this is better than your original approach, but it's certainly different.


Fetching all the project's items for a specific project id

It seems likely that the subquery in the SELECT is causing a row-by-row lookup.  Try moving into a LEFT JOIN to get the set-based performance we're looking for:

SELECT
    msprojectitems.idJobItem,
    msprojectitems.project_id,
    msprojectitems.hashcode,
    msprojectitems.itemID,
    msprojectitems.itemName,
    msprojectitems.itemNum,
    msprojectitems.itemWeight AS totalWeight,
    msprojectitems.itemUnit,
    msprojectitems.deleted,
    msprojectitems.LastUpdated,
    msprojectitems.itemWeight_assigned AS assignedWeight,
    IFNULL(cte_quantity_delivered.quantity_delivered,0) AS quantity_delivered
FROM
    msprojectitems
LEFT JOIN
    (
        SELECT
            msjobitems.itemID,
            Sum(
                IFNULL(
                    msjobitems.itemWeight_loaded,
                    msjobitems.itemWeight
                )
            ) AS quantity_delivered
        FROM
            msjobcustomer
        INNER JOIN msjobcusttoitems ON msjobcustomer.idJobCustomer = msjobcusttoitems.idJobCustomer
        INNER JOIN msjobitems ON msjobcusttoitems.idJobItem = msjobitems.idJobItem
        WHERE
            msjobcustomer.project_id = 10
        AND msjobcustomer.jobstatus = 1
        GROUP BY
            msjobitems.itemID
    ) cte_quantity_delivered ON cte_quantity_delivered.itemID = msprojectitems.itemID
WHERE
    msprojectitems.project_id = 10
ORDER BY
    msprojectitems.itemID ASC


Note: Not an answer, an extended comment.

There's no way your code can work the way you intend it to.

Your leader board doesn't work when the user isn't already in the leader board.

The second line will IndexError in these cases:

index_row_list = [leaderboard.index(row) for row in leaderboard if username in row]
index_row = int(index_row_list[0])

You can never score more than 3 points on the leader board.

while not guessed_wrong_twice:
    result = start_quiz()
    guessed_wrong_twice = result[1]
score = result[0]

You can never enter a correct song.

if guess.lower == song_chosen[0]:

Looks innocent enough, but it's never true. Unless song_chosen[0] is str.lower. In which case it's always true.

>>> 'abc'.lower == 'abc'
False

Now 1 & 2 are pretty minor, so if your code only contained them I'd just answer. But 3 means it's impossible for your code to work.

Given that start_quiz was the last function I reviewed I have a half written review for you. Please fix the above problems for it.


Loading attributes of cars and orders from JSON

This is the typical problem the relational community (relational databases) answers with OR-Mappings. As we do not have a relational datastructure more an object structure the mapping impedance is less but it remains.

But as we have to do a mapping it is not the question IF but the question WHERE the mapping is neccessary. Finally you have ALWAYS a big switch-case-statement. It may not be obvious and maybe it is not done all by yourself but there is no way around. You cannot escape the mapping but you can get help with it.

A pragmatic way would be to use the "org.json" API, Here is the Maven dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>1.5-20090211</version>
</dependency>

With this library your mapping will be a little be easier. You can parse the json string:

JSONObject carInfoAsJsonObject = new JSONObject(jsonString);

Then you can wrapp this JSONObject into your own object and have the getters returning their values directly from the JSONObject:

class OrderObject {
    public String getCar_width() {
        return carInfoAsJsonObject.getString("CAR_WIDTH");
    }
}

Here you do not have a switch-case have you? Of course you have. But it is hidden in the structure we chose and not formulated with the JAVA language element "switch-case".

Another way is to let a library make the mapping decision. A good library is "Jackson". Here is the Maven dependency:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

The Jackson way is "mapping by name"-convention. Your keys must be named like the attributes of your JAVA Object that should follow the bean convention.

The central clas is the ObjectMapper you have to instantiate:

ObjectMapper mapper = new ObjectMapper();

Then you may have the OrderObject attribute names synchronized:

class OrderObject {
    private String CAR_WIDTH;
    // getter and setter
}

After that you can instantiate an object of the type OrderObject:

OrderObject orderObject = objectMapper.readValue(carInfoAsJsonString, OrderObject.class);


Three edittext boxes: suggestions to clean up code

Replace "43560*144" by a constant.
Store new Double(sS), new Double(srS), new Double(pop) in variables
before if (checkifempty(boxes) <2). It'll improve speed and clarify
the code.
Correct indentation in the onCreate method


Points of improvement:

The animation moves a bit faster than a traditional logo animation would.
When the window is too small, the brand and the boxes overlap.

There's an extraneous bracket at the end of your CSS file:

@keyframes scaling {
  0%, 100% {transform: scale(1)}
  50% {transform: scale(.5)}
}

}
^ <- Here

If you're not against one line CSS rules, you could convert the following:

.turnOffAnimation {
  animation-name: none;
}
.intro {
  text-align: center;
}


Unit test Web API controller that uses a static helper class which uses app config setting

You're doing it wrong.

You can't do Dependency Injection and have static class dependencies scattered throughout your code: when you do Dependency Injection, you need to go all the way or not at all, else you gain the complexity and lose the benefits.

Proper DI goes like this:

Register: Set up your IoC container and register dependencies.
Resolve: Resolve the entire application's dependency graph - this is ONE method call.
Release: Dispose any disposables, clean up and tear down.

Your solution doesn't follow the Resolve step correctly, since you're calling .Resolve to fetch a single specific type, only to call that specific Init method on your static class: in all likelihood you're eventually going to need to do this in more than one place, and that's only because you stopped injecting dependencies at one point.

Any code that uses this HeaderHelper static class has a hidden dependency that isn't being injected, which means every single piece of code that uses HeaderHelper is tightly coupled with one specific implementation of that class.

Consider the below hypothetical MyClass; its constructor implicitly documents the type's dependencies (here ISomeDependency), but DoSomething has a dependency that isn't injected from the outside:

private readonly ISomeDependency _dependency;

public MyClass(ISomeDependency dependency)
{
    _dependency = dependency; // explicit dependency, constructor-injected
}

private void DoSomething()
{
    var foo = HeaderHelper.Foo; // HeaderHelper is a hidden dependency
    _dependency.DoSomething(foo);
}

There are several ways to fix this, but which is best for your case largely depends on context you haven't provided in your question (we know nothing of HeaderHelper other than it has a vague useless name that doesn't mean anything - you should really avoid "Helper" in class names).

1. Constructor Injection

You could do exactly like you did with the static ConfigurationManager class, and wrap it with an interface:

public interface IHeaderHelper // todo: rename!!!
{
    // members
}

That Init method seems rather artificial, and wouldn't be needed if the class' constructor took an IConfigurationReader dependency.

public class HeaderHelper : IHeaderHelper // notice: NOT static
{
    private readonly IConfigurationReader _configReader;

    public HeaderHelper(IConfigurationReader configReader)
    {
        _configReader = configReader;
    }

    // members
}

And then every class that needs to use a HeaderHelper should intake an IHeaderHelper constructor argument, and replace the implicit dependencies to the static class with explicit dependencies to that interface, so instead of this:

HeaderHelper.Foobar();

You would have that:

_headerHelper.Foobar();

Where _headerHelper is a private readonly IHeaderHelper instance field.

2. Ambient Context

Constructor injection is nice, but sometimes there are cross-cutting dependencies that are needed pretty much everywhere - it's fairly possible that configuration is one of such dependencies. Wrapping it with an interface and constructor-injecting it will work, but then you'll end up with lots of classes that intake this dependency, and when that feels like constructor-bloating, you might want to explore other possibilities.

Mark Seemann's blog describes an interesting pattern to address this problem: the Ambient Context.

This DI pattern would change this:

var foo = HeaderHelper.Foo();

Into this:

var foo = HeaderSettingsContext.Current.Foo();

The Ambient Context is still an implicit dependency though, and Constructor Injection should be preferred most of the time. But by storing the current context in thread-local storage, your tests can easily manipulate the current context, and alter what Foo() does in your application (e.g. hit the file system and read some XML value vs return a mocked-up value).

This article by Adras Nemes describes more DI patterns (the article is based on Mark Seemann's work).


As people have already pointed out you have to actually rotate the array.To do that  a really cool way would be using the mod(%) operator so even if the Rotation_Number variable that you are using is greater than the array length your code will run fine.

Declare a new array

   int arrRotated[] = new int[Array_Size];

and to store and print the array

    for (int i = 0; i <= Array_Size - 1; i++) {
        arrRotated[i] = arr[(i+Rotation_Number)%arr.length];
        System.out.print(arrRotated[i]);
    }


Everything can be controlled by a changing limit.

The (2 * limit - 1) results in either 1 for limit 1 or -1 for limit 0 controlling whether you are increasing or decreasing.

color.a * sign >= limit if limit = 1 and color.a > 1 or limit = 0 and color.a < 0

and maxAlpha - limit is either 1 if limit is 0 or 0 if limit is 1

Remove

private float minAlpha = 0.0f;

private bool alphaIncreasing = false;

Add

private float limit = 0.0f;

New Update code.

void Update()
{
    var color = image.color;
    float alphaChange = Time.deltaTime / time / 2.0f;
    var sign = 2 * limit - 1;
    color.a += sign * alphaChange;
    if (color.a * sign >= limit)
    {
        color.a = limit;
        limit = maxAlpha - limit;
    }
    image.color = color;
}


The class template provided provides the necessary public interface, anything else should be private rather than public. Therefore the variable int curr_shot_id and the variable std::unordered_map<int, std::vector<pair<int, int>>> id_map; should be declared after private:.
The variable curr_shot_id should be initialized by the constructor SnapshotArray(int length).
    SnapshotArray(int length)
    : curr_shot_id{0}
    { }

It's not clear that you need a binary search of the map since a map is a direct access memory structure which means that the key will be hashed and that provides a direct reference to the object stored.


Can I use mapWriterT instead of mapM/mapM_ (Haskell)?

mapWriterT is for transforming one WriterT into another. Its type is painfully generic, but allows you to transform pretty much everything about a WriterT.

mapWriterT :: (m (a, w) -> n (b, w')) -> WriterT w m a -> WriterT w' n b

So if you start with a WriterT w m a, and you want to end up with WriterT w' n b (in other words, you can transform all 3 type parameters), then you have to provide a function of the form
m (a, w) -> n (b, w').

Contrast this with mapM_ :: (a -> m b) -> [a] -> m (). The purpose of this mapping is to take a list and perform monadic operations parameterized by the list's contents in sequential order.

While there may be a way to write your function in terms of mapWriterT, it is a completely different kind of mapping than mapM_, so your request to " replace mapM_ with mapWriterT" doesn't really make much sense to me. Nevertheless, let's give it a spin.

newtype MatchedFiles = MatchedFiles { unwrapFiles :: [FilePath] } deriving Monoid
newtype SubDirs = SubDirs { unwrapDirs :: [FilePath] }

filesInDir :: String -> FilePath -> WriterT MatchedFiles IO SubDirs
filesInDir s f = do
  d <- liftIO $ listDir f
  let found = MatchedFiles $ filter (=~ s) (files d)
      subdirs = SubDirs $ subdirs d
  tell found
  return subdirs

OK, so here we've got a non-recursive WriterT that will simply tell the files that match the string at the given directory, and returns the subdirectories in that directory. I've used newtypes to help me not get the "found files" and "subdirectories" mixed up.

Now, what is the transformation we want to perform on this?

searchWriterT :: String -> FilePath -> WriterT MatchedFiles IO ()
searchWriterT s f = mapWriterT mapper (filesInDir s f)
  where
    mapper :: IO (SubDirs, MatchedFiles) -> IO ((), MatchedFiles)
    mapper action = undefined

Assuming we want to write searchWriterT in terms of mapWriterT and filesInDir, I just followed the types and this is what we've got. Now, the question is, how to write mapper?

mapper action = do
  (SubDirs subdirs, files) <- action
  if null subdirs
    then return ((), files)
    else undefined

Clearly, if there are no "subdirs", then we are done, and we simply regurgitate the files. But what if there are subdirs? Well, you've already figured out what to do: use mapM_ on the subdirs!

else runWriterT $ tell files >> mapM_ (searchWriterT s) subdirs

In fact, mapM_ will take care of the null case for us: it won't do anything in the event of an empty list.

mapper action = do
  (SubDirs subdirs, files) <- action
  runWriterT $ tell files >> mapM_ (searchWriterT s) subdirs

Conclusion: mapWriterT felt kind of awkward for this problem, especially since inside the mapper we turned right around and used runWriterT. We didn't even get rid of mapM_, because mapM_ embodies exactly what needs to be done for this problem.

searchWriterT s f = filesInDir s f >>= mapM_ (searchWriterT s) . unwrapDirs


City Construction Solution times out for large input

It was a tough one but I managed to solve it and pass all the test cases. Below are main points.

Build a full directed graph first

Save the queries because there can be up to 100,000 of them and it's more efficient to build a full graph first and then run all the queries on it.

Find all strongly connected components

Find all strongly connected components in the graph and then build a reachability map based on them. It has a lower space complexity since each strong component can be represented by a single node and so we don't need to have a reachability set for each node but only for its representative.

Use DFS for finding reachability sets

Modify a DFS so that after running it each connected component contains representatives (so-called low-link nodes) from other connected components that are reachable. But then, if a low link node is reachable so is any node from its connected component.

Use memory efficiently for storing strong components

Create an array of (n + 1) integer values, where n - the number of nodes in the graph. Index identifies a node in the graph and a value - all connected components (low link node) reachable from it. Value can have up to n + 1 binary digits (if all nodes are reachable from the current one).

Increase recursion limit

As the number of nodes can reach 50000 so the recursion call stack must be set to this value.

Solution Code

from collections import defaultdict, deque
import sys

sys.setrecursionlimit(50001)

n, m = map(int, input().split())
adjacentNodes = defaultdict(set)
for _ in range(m):
    u, v = map(int, input().split())
    adjacentNodes[u].add(v)

q = int(input())
# read all queries first
queries = []
for i in range(q):
    c, x, d = map(int, input().split())
    if c == 1:
        n += 1
        y = n
        if d == 0:
            adjacentNodes[x].add(y)
        else:
            adjacentNodes[y].add(x)
    else:
        y = d
        queries.append((x, y))

# each node with number i corresponds to 2^i
nodeDpPosition = {i: (1 << i) for i in range(n + 1)}
# Implementation using the Tarjan algorithm
# https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
def findAllConnectedComponents(edges):
    connectedComponents = [0 for _ in range(n + 1)]
    index = {'value' : 0}
    # map node to its connected component low link node
    connectedComponentLink = {}

    nodeStack = deque()
    indices = [-1] * (n + 1)
    lowLinks = [0] * (n + 1)
    onStack = [False] * (n + 1)

    def connectedComponent(node):
        indices[node] = index['value']
        lowLinks[node] = index['value']
        index['value'] += 1
        nodeStack.append(node)
        onStack[node] = True

        for adjacentNode in edges[node]:
            if indices[adjacentNode] < 0:
                connectedComponent(adjacentNode)
                lowLinks[node] = min(lowLinks[node], lowLinks[adjacentNode])
            elif onStack[adjacentNode]:
                # we have reached the previously visited node or come back in the call stack
                lowLinks[node] = min(lowLinks[node], indices[adjacentNode])

        if lowLinks[node] == indices[node]:
            while nodeStack:
                current = nodeStack.pop()
                connectedComponentLink[current] = node
                onStack[current] = False
                connectedComponents[node] |= nodeDpPosition[current]

                if current == node:
                    break

    for i in range(1, n + 1):
        if indices[i] < 0:
            connectedComponent(i)

    return (connectedComponents, connectedComponentLink)

connectedComponents, connectedComponentLink = findAllConnectedComponents(adjacentNodes)

def advancedDfs(node):
    lowLinkNode = connectedComponentLink[node]

    neighbours = adjacentNodes.get(node)
    if neighbours is not None:
        for neighbour in neighbours:
            lowLinkNeighbourNode = connectedComponentLink[neighbour]
            if (connectedComponents[lowLinkNode] & nodeDpPosition[lowLinkNeighbourNode]) == 0:
                connectedComponents[lowLinkNode] |= nodeDpPosition[lowLinkNeighbourNode]
                advancedDfs(lowLinkNeighbourNode)

            connectedComponents[lowLinkNode] |= connectedComponents[lowLinkNeighbourNode]

for i in range(1, n + 1):
    advancedDfs(i)

for query in queries:
     x, y = query
     lowLinkXNode = connectedComponentLink[x]
     lowLinkYNode = connectedComponentLink[y]
     if connectedComponents[lowLinkXNode] & nodeDpPosition[lowLinkYNode]:
         print ("Yes")
     else:
         print ("No")


How to pass pre-generated values to an anonymous function to speed up a fit?

A named function is declared like this:

function out = function_name(in)

If it is written in a file of the same name, and the file is on the MATLAB path, then it is accessible from the base workspace and any function you call. If it is written as a local function (an additional function in a file defining a different function) then it is only accessible to the other functions in that file. If it is in a sub-directory called private, then it is only accessible to the functions defined in the parent directory.

An anonymous function is defined as like this:

function_handle = @(p) p

Here, function_handle is a variable that contains the anonymous function. In other languages this is called a lambda. This lambda can capture variables from its environment:

data = 1:10;
function_handle = @(p) p.*data

function_handle now contains a copy of data. Changing data or clearing it after creating the anonymous function won't affect the copy of data inside it.

The interesting thing for you here is that a named function can also capture data. This is true only for nested functions (which we didn't mention above). The difference between a nested function and a local function is one measly end statement, it's easy to miss it. This is a local function:

function out = main(in)
% code ...
function r = local(p)
% code ...

This is identical to:

function out = main(in)
% code ...
end
function r = local(p)
% code ...
end

The end statements ending a function are optional.

This is a nested function:

function out = main(in)
% code ...
   function r = nested(p)
   % code ...
   end
end

Here the end statements are mandatory. nested is inside main. nested also has access to variables declared in main. For example, nested can use in.

main can also create a function handle of nested and return it. This function handle then will point at the nested function, and capture its environment. Much like an anonymous function:

function out = main(in)
   data = integral(in,0,1);
   out = @r;
   function r = nested(p)
      r = p .* data;
   end
end

Now, calling main returns a handle to the function nested, which has captured data computed in main. You can use this to create a function handle that you can pass to fit. nested would be your zeusEquation, and main would simply package it with the precomputed integral.

Code review

There are a few things to note about your code:

You compute sin(psi0) and 1-cos(psi0) repeatedly inside your loop. psi0 is a constant within this loop, and consequently you should compute these values once outside of the loop.
You compute integral(sinIntegral,0,u(a6,a5,x(i))) twice for each x(i). This being an expensive function, you should compute it only once and re-use the result.
for i = 1:max(size(x)) is long-hand for for i = 1:length(x). This only works correctly in your loop if x is a vector. In this case, you can use numel(x) instead of length(x). numel is faster.

These three points above lead to:

sinpsi0 = sin(psi0);
cospsi0_1 = 1-cos(psi0);
for i = 1:numel(x)
   if u(a6,a5,x(i))~=0
      int = integral(sinIntegral,0,u(a6,a5,x(i)));
      y(i) = a3 + a4.*(x(i)-a5)  ...
                + (1-int) .* (a1.*sign(x(i)-a5).*sinpsi0 ...
                              - (1-a2).*int.*cospsi0);
   else
      y(i) = a3 + a4.*(x(i)-a5);
   end
end

integral must be called with scalar limits, but other components can be computed vectorised. It would be possible to compute only the integral within the loop, and the rest without a loop.

This leads to:

int = zeros(size(x));
for i = find(u(a6,a5,x)~=0)
   int(i) = integral(sinIntegral,0,u(a6,a5,x(i)));
end
y = a3 + a4.*(x-a5)  ...
       + (1-int) .* (a1.*sign(x-a5).*sin(psi0) ...
                     - (1-a2).*int.*(1-cos(psi0)));

This should be faster, but I haven't tested it. (I assume a1 and the like are all scalars?)
You define your functionzeusEquation using varargin, then proceed to unpack the varargin cell array with the assumption that all your input arguments are there. This is correct in your situation of course, but you might as well do:

function y = zeusEquation(psi0,a1,a2,a3,a4,a5,a6,x)

In this way, if zeusEquation is called with fewer (or more!) arguments, you'll get a sensical error message, rather than an "index out of bounds" error.


A/B testing using chi-square to calculate the significance in an elegant way

When you have a finite number of members in a group A and B. Instead of split into groups, hstack the DataFrame like this:

pd.concat(
    [
        df[df.index % 2 == 0].add_prefix('a_').reset_index(),
        df[df.index % 2 == 1].add_prefix('b_').reset_index()
    ], axis=1
)

    a_grp   a_tot   a_lgn   a_read  index   b_grp   b_tot   b_lgn   b_read
0   0   a1  6300    360 30  1   ca1 2300    60  7
1   2   b1  26300   148 6   3   cb1 10501   15  3
2   4   c1  74600   36  2   5   cc1 26000   6   1

Now you can replace the for-loop with 'a_' and 'b_' and df.apply() like

df.apply(apply_chi2)

def apply_chi2(df_ab):
  if df_ab['a_'+convert] > df_ab['a_'+'nonconvert']:
     return ...
  obs = df_ab.a
  return _, p, _, _=chi2_contingency(obs)


Showing items and categories after clicking on a subcategory

Naming

Assuming you or Mr.Maintainer will have to fix a bug in this code in 3 months, will you still know what any of these variables

avm
stackIbro2
stackIbro
articlesH

should do or represent ?

You should give your objects/variables meaningful names so that you or Mr.Maintainer will see at the first glance what to expect.

Indentation

                    StackLayout articlesH = new StackLayout()
                    {Orientation = StackOrientation.Horizontal};

here it can be missed at first glance that these 2 lines belong together. You should indent them like

                    StackLayout articlesH = new StackLayout()
                        {Orientation = StackOrientation.Horizontal};

btn_subcategory.Clicked eventhandler

Grouping together the related code, will increase readability.
the Array array is not really needed at all, you can remove it
commented code is dead code, hence it should be removed.
changing the for loop to a for each loop will add readability
EventArgs are name e and it is sender instead of senderr
don't use hungarian notation (at least like you have done). If the type changes but you forget to change the name also you get weird code like: Label btn_Quantity

btn_subcategory.Clicked += (object sender, EventArgs e) =>
{
    this.IsPresented= false;
    stackIbro2.Children.Clear();
    stackIbro.Children.Clear();

    foreach (Article article in Subcategory.Articles)
    {
        StackLayout articlesH = new StackLayout()
            {Orientation = StackOrientation.Horizontal};

        Button button = new Button()
            {
                Text = article.Name,
                HorizontalOptions = LayoutOptions.StartAndExpand
            }

        Label label = new Label()
            {
                Text = article.Quantity.ToString(),
                HorizontalOptions = LayoutOptions.End
            }

        articlesH.Children.Add(button;
        articlesH.Children.Add(label);
        stackIbro2.Children.Add(articlesH);
    }
};


I'm sure there will be elements of your application that are of much more concern, performance-wise, than this, but it could certainly be a little more clear, or maybe a little less superfluous...

Evaluation of and work within conditions is only required if q > 0
You really want to use AndAlso to apply short-circuiting in the first condition
q > MaxQtyDisplay is redundant since this condition wouldn't hit otherwise (forgetting negative quantities but we address that by addressing my first point)
Else is likewise not required.
Only get the value of MaxQtyDisplay from the settings context once (negligible in terms of performance really, since settings are loaded from file into memory on request)
Naming variables with single character identifiers doesn't optimise anything

So, for example, you can correct these as such:

Private Function CalculateQtyDisplay(ByVal x As Double, ByVal y As Double) As Double
    Dim result = 0.0
    Dim desiredQuantity As Double = x - y
    Dim maxQuantity = My.Settings.MaxQtyDisplay
    If (desiredQuantity > 0) Then
        If (desiredQuantity <= maxQuantity) Then
            result = maxQuantity
        Else
            result = desiredQuantity
        End If
    End If
    Return result
End Function

Any other modifications to this code are simply going to be aesthetic and preferential really, as far as I can see. For instance you could do away with maintaining result, this goes against what I recommend in another answer but it clearly boils down to context):

Dim desiredQuantity As Double = x - y
Dim maxQuantity = My.Settings.MaxQtyDisplay
If (desiredQuantity > 0) Then
    If (desiredQuantity <= maxQuantity) Then
        Return maxQuantity
    End If
    Return desiredQuantity
End If
Return 0

A modification that comes to mind which could potentially impact performance, if anything might, is to use the IIf function available to VB.NET (both TruePart and FalsePart of this call are evaluated, though I highly doubt you'll ever have any noticeable degradation with this method anyway, even if you used this method):

Dim quantity As Double = x - y
Dim maxQtyDisplay = 1800 'My.Settings.MaxQtyDisplay
If (quantity > 0) Then
    Return IIf(quantity <= maxQtyDisplay, quantity, maxQtyDisplay)
End If
Return 0


Usage of interfaces

HashMap<String, Integer> dictionary = ...

Try to use interfaces on the lefthand side as a best practice: Map, List,  ... as it will make you independent of hashmap, linkedhashmap,...

also try not to use vector unless really necessary (https://stackoverflow.com/questions/2986296/what-are-the-differences-between-arraylist-and-vector)

Naming

HashMap<String, Integer> dictionary = new HashMap<String, Integer>();
...
Dictionary reader = new Dictionary(dictionary);

There is a class dictionary, a map with the same name and when initalizing an instance of Dictionary, then it is called "reader". This is confusing

reader.fileScanner(text)

This method name does not really indicate an action. reader.scanFile(text) would be better.

Reusing dictionary data

you could make the counting of the words a method of the dictionary where you build a new map with only a count for the words encountered in the new text file(s) and return that map.

Comments

avoid comments like

// Assigns the value of the parameter to the field of the same name

as they describe what you do in the code, which you can see by reading the code. When putting a comment then at least tell why some piece of code is implemented as such (specific issue, specific algorithm, ...)

Error handling

e.printstacktrace is by preference replaced by a logging framework (log4j2, logback, slf4j as façade, ...)
Perhaps you can make the method throw ioException and make the calling code handle this?


Wrapping individual values in single-value streams and concatenating the streams is very inefficient.  You'd be better off using IntStream.Builder to build your IntStream, like this:

public static IntStream properDivisors(int num) {
    IntStream.Builder builder = IntStream.builder();
    for (int i=2; i<=num/2; i++) {
        if (num%i == 0) {
            builder.accept(i);
        }
    }
    return builder.build();
}

Better yet, since you're experimenting with Streams, convert your for loop to an IntStream using IntStream.range(), like this:

public static IntStream properDivisors(int num) {
    return IntStream.range(2, num/2 + 1).filter(i -> num % i == 0);
}


2vs2 Poker Hand One Pair Winner Algorithm

I'm not really any good at algorithms as such so my main suggestion would be to remove duplicate code.  That is primarily in the creation of your pPairHigh and oPairHigh blocks of code.

I admit they do share a common loop which in my implementation means this will be occurring twice.  If this is an issue in performance it could be broken out so the pairs are created like you have done in a single loop.  But I would still call a method to do the actual creation.  However I'm working on the assumption performance is not really an issue, here is my suggestions.

// Please not I made a guess around your method name here
private int ComparePairs() {
    PlayingCard[] myHand = getPokerHand(this.hand);
    PlayingCard[] otherPlayersHand = getPokerHand(otherHand);

    return compareMyHandAgainstOthers(myHand, otherPlayersHands)
 }

 private int compareMyHandAgainstOthers(PlayingCard[] myHand, PlayingCard[] otherHand) {
    if(pPairHigh[0].compareTo(oPairHigh[0]) == 0) {
        if(pPairHigh[1].compareTo(oPairHigh[1]) < 0)
           return -1;
        else if(pPairHigh[1].compareTo(oPairHigh[1]) > 0)
           return 1;
        else
           return 0;
    }

    if(pPairHigh[0].compareTo(oPairHigh[0]) < 0)
       return -1;
    else
       return 1;
 }

 private PlayingCard[] getPokerHand(Array hand) {

   PlayingCard[] pair = new PlayingCard[2];
   for(int i = 0; i < POKER_HAND_SIZE - 1 ; i++) {
        if(this.hand[i].compareTo(this.hand[i+1]) == 0) {
            pair[0] = this.hand[i];

            if(i == 3)
               pair[1] = this.hand[i - 1];
            else
               pair[1] = this.hand[POKER_HAND_SIZE - 1];

        }
    }

    // throw exception here as no possible pair found???
     return pair;
 }

Please note there may be java specific code as I haven't programmed in Java for a while.


I have implemented something like that in one of my projects, the trick is to use CRTP to pass the Child type to the parent.

This is a simplified code :

#include "collisions.h"
#define SHAPES Box, Sphere, Mesh
class Box;
class Sphere;
class Mesh;

class Geometry;

// Collidable defines all the pure virtual functions.
template <typename... Shapes>
struct Collidable;

template <>
struct Collidable<> {
    virtual bool collide(const Geometry* obj) const = 0 ;
};

template <typename Shape, typename... Others>
struct Collidable<Shape, Others...> : Collidable<Others...> {
    using Collidable<Others...>::collide;
    virtual bool collide(const Shape* obj) const = 0;
};

// Geometry inherits from Collidable and is our common base class.
class Geometry : public Collidable<SHAPES> {
    public:
        Geometry();
        virtual ~Geometry();
        glm::vec3 getPosition() const;

    private:
        glm::vec3 m_pos;
};

// Dispatcher inherits from Geometry and implements one dispatch function
// for all the given type and the Geometry one.
template <class T, typename... Shapes>
struct Dispatcher;

template <class T>
struct Dispatcher<T> : public Geometry {
    bool collide(const Geometry* obj) const final override {
        return obj->collide(static_cast<const T*>(this));
    }
};

template <class T, typename Shape, typename... Others>
struct Dispatcher<T, Shape, Others...> : public Dispatcher<T, Others...> {
    using Dispatcher<T, Others...>::collide;
    bool collide(const Shape* obj) const final override {
        return Collisions::collide(obj, static_cast<const T*>(this));
    }
};

// Shape<T> is our generic dispatch class.
template <class T>
class Shape : public Dispatcher<T, SHAPES> {};

With all shapes defined like:

class Sphere : public Shape<Sphere> {...};

Of course, all the corresponding Collisions::collide(*,*) must be declared.
I am not very familiar with template meta-programming, so I couldn't find a clean solution to replace the #define SHAPES Box, Sphere, Mesh and the classes declarations at the beginning of the file.

Furthermore, I don't know if a good compiler can optimize virtual calls using de-virtualization (that's why I tried to add final keyword).


"Longest Substring Without Repeating Characters" in Python

Nice solution, please find a few thoughts below:

Do you need to wrap it in class for leetcode? It's unnecessary otherwise.
Function names use snake_case and not camelCase, check PEP8 for more details. Hence it would be length_of_longest_substring.
Do not use dict as a variable name, it is already built-in to construct dictionaries.
I think a for-loop would be preferable over a while-loop in this case, it's more straightforward, less clunky, and easier to understand.
You update curr_length, but never actually use it to determine your max_length.
The docstring should come right after the class Solution and before the first function, and no line should be longer than 79 characters. Moreover, you seem to not have pasted the entire docstrings, it just ends mid-sentence.