Pick sequences of numbers to maximize the points

Some general points

The code looks good, and the steps you take to calculate the result are sound. I would like to mention a few general points for reviewing the code, then move on to some tips that could improve the code.

Include usings

This helps others when reviewing the code.

using System.Collections.Generic;
using System.Linq;

Include the results when you run the program

This also helps reviewing, but more importantly: it helps you
testing.  Pressing "Run" and seeing what the results are is quicker
than attaching the debugger and needing a break point to check.

class Value
{
    // ...
    public override string ToString() { return $"({idx}, {num})"; }
}

static void Main(string[] args)
{
    CountInitValues();
    Solve(values, new List<Value>(), 0, T);
    System.Console.Out.WriteLine ("The result is: {0}", string.Join(", ", result.Select(i => i.ToString())));
}

Names

Use descriptive names for fields and variables with large scopes

Example: N, S and T are clear if you have the problem description
at hand, but not when you are looking at them in the code itself.
You could change them to numbers, maxMoves and numbersToTake,
so that their meaning is clear at one glance.

Write smaller functions

This helps readability, and especially in the case of Solve(), this could make it more clear what the code is doing. An example:

Split CountInitValues()

static void CountInitValues()
{
    for (int i = 0; i < N - T + 1; i++)
    {
        Value ee = new Value(i, CountValuesFrom(i));
        values.Add(ee);
    }
}

static int CountValuesFrom(int startIndex)
{
    int newValue = 0;
    for (int j = 0; j < T; j++)
    {
        newValue += numbers[startIndex + j];
    }
}

Bug

You use T for the number of steps, instead of S

This gives no different result in the example, because after 2
steps, you can't take another set of 3 values any more.  But in
different sets, this will give false results.

Solve(values, new List<Value>(), 0, T);

should be

Solve(values, new List<Value>(), 0, S);

An Object Oriented issue

Solver can be a separate class with non-static fields

If you extract a class Solver, and use non-static fields, you can
create more of them in a testing method (or in Main()), give them
different values to calculate results, and test those results.

class Solver
{
    int N;
    int S;
    int T;
    int[] numbers;

    List<Value> values = new List<Value>();
    int maxPoint = -1;
    List<Value> result;

    public Solver(int N, int S, int T, int[] numbers)
    {
        this.N = N;
        this.S = S;
        this.T = T;
        this.numbers = numbers;
    }

    public List<Value> Run()
    {
        CountInitValues();
        Solve(values, new List<Value>(), 0, S);
        return result;
    }

    void Solve(List<Value> remaining, List<Value> numSoFar, int pointSoFar, int StepsRemain)
    {
        // ...
    }

    void CountInitValues()
    {
        // ...
    }
}

You can call the test like this, then:

class Program
{
    const int N = 8;
    static int S = 2;
    static int T = 3;
    static int[] numbers = new int[N] { 1, 6, 8, 7, 6, 2, 1, 8 };

    static void Main(string[] args)
    {
        var result = new Solver(N, S, T, numbers).Run();
        System.Console.Out.WriteLine ("The result is: {0}", string.Join(", ", result.Select(i => i.ToString())));
    }
}

But also like this:

class Program
{
    const int N = 8;
    static int S = 2;
    static int T = 3;
    static int[] numbers = new int[N] { 1, 6, 8, 7, 6, 2, 1, 8 };

    static void Main(string[] args)
    {
        var result = new Solver(N, S, T, numbers).Run();
        System.Console.Out.WriteLine ("The result for S = 2, T = 3 is: {0}", string.Join(", ", result.Select(i => i.ToString())));
        result = new Solver(N, 3, 2, numbers).Run();
        System.Console.Out.WriteLine ("The result for S = 3, T = 2 is: {0}", string.Join(", ", result.Select(i => i.ToString())));
    }
}

Optimizing the algorithm

It does not matter in which order you take groups

If you pick numbers from indices (2, 3, 4), and then from indices
(6, 7, 8), you will get the same result as when you first pick (6,
7, 8) and then (2, 3, 4).  Also, when picking (1, 2, 3) then (4, 5,
6), you already have the same number of points as when picking (2,
3, 4) and then (1, 5, 6).

Knowing this, you can skip tests that try to take numbers from the
left of where you took numbers:

void Solve(/*...*/)
{
    List<Value> newRemaining = new List<Value>();
    newNum.Add(remaining[i]);
    newRemaining.AddRange(remaining.Take(i - T));
    newRemaining.AddRange(remaining.Skip(i + T));
}

can now be

void Solve(/*...*/)
{
    List<Value> newRemaining = new List<Value>();
    newNum.Add(remaining[i]);
    newRemaining.AddRange(remaining.Skip(i + T));
}


Function TirNoPer360(Cash, Dates As Range, rate As Double)

The function is implicitly Public, implicitly returns a Variant, and implicitly receives all its parameters ByRef; Cash is implicitly a Variant, and the name isn't making it obvious that...

If Opt(Cash, Dates, rate)

...

Function Opt(Caja, Fecha As Range, tasa As Double)
    '...
    For i = 1 To Caja.Rows.Count

...that Cash (and Caja) really needs to be a Range object, otherwise things can go all kinds of wrong.

Make these things explicit, pass parameters ByVal, and keep the same identifiers when concepts are the same:

Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double) As Double

Private Function Opt(ByVal Cash As Range, ByVal Dates As Range, ByVal rate As Double) As Double

Now it's much clearer that...

TirNoPer360 is the public UDF, and Opt is a private implementation detail of it.
Cash in TirNoPer360 is the same thing as what you had as Caja in Opt.
The function(s) return a Double

This block needs immediate attention:

If Opt(Cash, Dates, rate) > 0 And Opt(Cash, Dates, rate) > tolerance Then
    rate = rate + 0.0000001
ElseIf Opt(Cash, Dates, rate) < 0 And Opt(Cash, Dates, rate) < tolerance * -1 Then
    rate = rate - 0.0000001
Else
    rate = rate
End If

The entire Else block is no-op and should be removed. rate is already equal to rate, but the biggest inefficiency here is the fact that, in the worst case, Opt is invoked 4 times, and it's a very expensive function call. Pull it into a local variable (as was already suggested) and call it once:

Dim optResult As Double
optResult = Opt(Cash, Dates, rate)

And now the conditionals become:

If optResult > 0 And optResult > tolerance Then
    rate = rate + 0.0000001
ElseIf optResult < 0 And optResult < tolerance * -1 Then
    rate = rate - 0.0000001
End If

The tolerance looks like it should be an optional parameter, with a default value of 0.00001. You could amend the function's signature like this:

Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double, Optional ByVal tolerance As Double = 0.00001) As Double

Variable Iteration is not declared. I like that it's a fully spelled-out identifier and not just i, but given the variable has no use other than counting the number of iterations... so i wouldn't hurt at all. Just declare it - the fact that the code is allowed to run without this variable being declared indicates that Option Explicit is not specified at the top of the module, and that's a very dangerous thing, because any typo will merrily compile and run.. and produce the wrong results... and typos can be hard to spot. Spare yourself the trouble, and always put Option Explicit at the top of every module you ever write any code in.

  I need more than 100 tries in order to get a good rate

Your function needs to define a concept of what a "good rate" is, and bail out (Exit Function, or Exit For) when it gets one. Currently, the function performs 100 iterations every time, regardless of whether the 2nd or 99th iteration yielded a "good rate".

    TirNoPer360 = rate
Next Iteration

You're re-assigning the function's return value at every iteration. That's a redundant step, just assign it once, after the loop:

Next Iteration
TirNoPer360 = rate

Now, about that Opt function...

For i = 1 To Caja.Rows.Count
    sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))
Next i

i should be declared as a Long, not an Integer. I don't know how many rows this function is iterating, but Caja being a Range means it's absolutely possible that there are more than 32,767 (the maximum value an Integer can take).

The function would be more efficient if you were iterating a single-dimensional Variant array rather than a Range.

Consider declaring Caja and Fecha parameters ByVal...As Variant, and passing them from TirNo360 like so:

Public Function TirNoPer360(ByVl Cash As Range, ByVal Dates As Range, ByVal rate As Double, Optional ByVal tolerance As Double = 0.00001) As Double

    Dim cashValues As Variant
    cashValues = Application.WorksheetFunction.Transpose(Cash.Value)

    Dim dateValues As Variant
    dateValues = Application.WorksheetFunction.Transpose(Dates.Value)

    Dim optResult As Double
    optResult = Opt(cashValues, dateValues, rate)

Now instead of this:

For i = 1 To Caja.Rows.Count
    sum = sum + Caja(i) / ((1 + tasa) ^ (Application.WorksheetFunction.Days360(Initial, Fecha(i)) / 360))
Next i

You'll have this (assuming the Caja parameter is now named cashValues):

Dim firstDate As Date
firstDate = dateValues(1)

For i = LBound(cashValues) To UBound(cashValues)
    sum = sum + cashValues(i) / ((1 + rate) ^ (Application.WorksheetFunction.Days360(firstDate, dateValues(i)) / 360))
Next

Now the only thing left to address, is the function names: I've no idea what TirNoPer360 actually stands for, and Opt is very cryptic. Give your functions meaningful names that ideally start with a verb, like, FindOptimalRate or something.


Get only intended input from user through the console

I see some things that may help you improve your program.

Use const references where practical

The code currently declares its first function like so:

void gValid_Input(std::string& var, std::string question);

However the passed question is not and should not be altered by this code, so better would be to pass a const std::string& question or std::string_view question if you have a C++17 compiler.

Use return values to return values

Each of the functions is defined as returning void but each is actually returning a single value which is the response.  So for the first function, including the advise listed above, one could instead make the signature of the first function this:

std::string gValid_Input(const std::string& question);

Fix the bug

When the user inputs the end of file marker (Ctrl+D in Linux), the prompt just repeats endlessly in a loop.

Consolidate the code

All four of the functions could be represented with a single templated function:

template <typename T>
T gValid_Input(const std::string& prompt, bool (*isValid)(const T&) = [](const T&){ return true; }) {
    T var;
    while (std::cout << prompt && !((std::cin >> var) && isValid(var))) {
        if (std::cin) {
            std::string line;
            std::getline(std::cin, line);
            std::cout << var << line << " is not a valid answer\n";
        } else {
            std::cin.clear();
            std::string line;
            std::getline(std::cin, line);
            std::cout << line << " is not a valid answer\n";
        }
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return var;
}

Here's are some example of its use:

#include <complex>
#include <array>

int main() {
    auto answer{gValid_Input<std::string>("What is your name? ")};
    std::cout << "Your answer: \"" << answer << "\"\n";
    auto age{gValid_Input<int>("What is your age? ")};
    std::cout << "Your answer: \"" << age << "\"\n";
    auto cpx{gValid_Input<std::complex<double>>("What is your favorite complex number? ")};
    std::cout << "Your answer: \"" << cpx << "\"\n";
    auto weekday{gValid_Input<std::string>("What is your favorite day of the week? ",
        [](const std::string &day){ const std::array<std::string, 7> weekdays{
            "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
            };
            return std::find(weekdays.begin(), weekdays.end(), day) != std::end(weekdays);
        }
    )};
    std::cout << "Your answer: \"" << weekday << "\"\n";
    auto fun{gValid_Input<char>("Are you having fun? ",
        [](const char &ch){ return ch=='y' || ch=='n'; }
    )};
    std::cout << "Your answer: \"" << fun << "\"\n";
}

I'm using a lambda function as the validator, but it could also be any function with the appropriate signature.

Reconsider the interface

It would be nice to be able to use streams other than std::cin and std::cout.  I'd recommend passing the input and output streams as parameters.


Following @mpapec suggestion, your code becomes (in pseudocode):

@columns = transpose(map (split " ", readlines("filename")))
print join (" ", map { sum(@$_)/@$_ } (columns), $/;

Where readlines reads a file into an array of lines.

To find the transpose function you will have to follow the link @mpapec gave you.

Your code is now down to just two lines and uses functional programming, that seems to be encouraged in Perl, so it looks better to me.


Simplifying constructing native SQL query with nested if-else's

Let's look for some patterns in your code:

First of all, we notice that you have three parameters with similar names. condition, condition2 and condition3. These names indicates a code smell, that we should use an array or list instead.

Taking one step at a time, we see this code is repeated multiple times:

if (StringUtils.isNotEmpty(condition.toString())) {
    query.append(ApplicationConstants.AND+"(");
    query.append("( " + condition + " )");

if (StringUtils.isNotEmpty(condition2.toString())) {
    query.append(ApplicationConstants.AND);
    query.append("( " + condition2 + " )");

if (StringUtils.isNotEmpty(condition3.toString())) {
    query.append(ApplicationConstants.AND);
    query.append("( " + condition3 + " )");

if (StringUtils.isNotEmpty(condition3.toString())) {
    query.append(ApplicationConstants.AND);
    query.append("( " + condition3 + " )");

if (StringUtils.isNotEmpty(condition2.toString())) {
    query.append(ApplicationConstants.AND+"(");
    query.append("( " + condition2 + " )");

if (StringUtils.isNotEmpty(condition3.toString())) {
    query.append(ApplicationConstants.AND);
    query.append("( " + condition3 + " )");

if (StringUtils.isNotEmpty(condition3.toString())) {
    query.append(ApplicationConstants.AND+"(");
    query.append("( " + condition3 + " )");

This indicates that we can extract a method. (We can also notice that the "(" should be added for the first true if-statement, this is important but we will ignore this for now and get back to this later).

private boolean addParameter(StringBuilder query, StringBuilder condition) {
    if (StringUtils.isNotEmpty(condition.toString())) {
        query.append(ApplicationConstants.AND);
        query.append("( " + condition + " )");
        return true;
    }
    return false;
}

private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,
    StringBuilder condition3) {
if (addParameter(condition)) {
    if (addParameter(condition2)) {
        if (addParameter(condition3)) {
            // we don't actually care about the result here
        }
    } else {
        if (addParameter(condition3)) {
            // not here either
        }
    }
    query.append(" )");
} else {
    if (addParameter(condition2)) {
        if (addParameter(condition3)) {
            // again, don't care about result
        }
        query.append(" )");
    } else {
        if (addParameter(condition3)) {
            // yeah ok, here we actually care...
            query.append(" )");
        }
    }
}

Now it's pretty clear that query.append(" )"); should always be done last, so that can be moved out and then we can avoid some if statements.

private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,
    StringBuilder condition3) {
if (addParameter(condition)) {
    if (addParameter(condition2)) {
        addParameter(condition3);
    } else {
        addParameter(condition3);
    }
} else {
    if (addParameter(condition2)) {
        addParameter(condition3);
    } else {
        addParameter(condition3);
    }
}
query.append(" )");

And now we're doing the same in both some if's and else's, so that can be simplified:

private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,
    StringBuilder condition3) {
if (addParameter(condition)) {
    addParameter(condition2);
    addParameter(condition3);
} else {
    addParameter(condition2);
    addParameter(condition3);
}
query.append(" )");

Once again we're doing the same thing:

private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,
    StringBuilder condition3) {
addParameter(condition);
addParameter(condition2);
addParameter(condition3);
query.append(" )");

So we're essentially doing the same thing three times. This is where a loop would be handy.

private void appendConditions(StringBuilder query, StringBuilder... conditions) {
    for (StringBuilder condition : conditions) {
        addParameter(condition);
    }
    query.append(" )");

And now of course, we don't really need that separate addParameter method.

private void appendConditions(StringBuilder query, StringBuilder... conditions) {
    for (StringBuilder condition : conditions) {
        if (StringUtils.isNotEmpty(condition.toString())) {
            query.append(ApplicationConstants.AND);
            query.append("( " + condition + " )");
        }
    }
    query.append(" )");

Now, let's get back to the parenthesis: +"(" is added in the first true if-statement in your original code. So this, in connection with the closing " )" can be handled by for example keeping a boolean to check for if an if-statement has been true so far.

private void appendConditions(StringBuilder query, StringBuilder... conditions) {
    boolean conditionUsed = false;
    for (StringBuilder condition : conditions) {
        if (StringUtils.isNotEmpty(condition.toString())) {
            query.append(ApplicationConstants.AND);
            if (!conditionUsed) {
                conditionUsed = true;
                query.append(" (");
            }
            query.append("( " + condition + " )");
        }
    }
    if (conditionUsed) {
        query.append(" )");
    }

But when reflecting more about what it is that you do, we see that you have a collection of StringBuilders, you check each if it is not empty, then you join them together with ApplicationConstants.AND.

    String specialConditions = Arrays.stream(conditions)
        .map(StringBuilder::toString)
        .filter(StringUtils::isNotEmpty)
        .collect(Collectors.joining(ApplicationConstants.AND));
    if (StringUtils.isNotEmpty(specialConditions)) {
        query.append(" (");
        query.append(specialConditions);
        query.append(" )");
    }

Voilà!


Your code seems to be working properly so there is not much to say on this.

The only changes I would perform would be to make things easier to understand through different little steps.

Multiplication could return a result

At the moment, your multiplication procedure stores the result in the first argument. First issue is that it cannot be generalised to product of non-square matrices. The second issue is that it can make things a bit hard to understand when looking at the code using your function (getNthfibo in your case). It is a fairly easy change to perform :

private static int[][] multMatrix(int[][] m, int [][] n) {
    int a = m[0][0] * n[0][0] +  m[0][1] * n[1][0];
    int b = m[0][0] * n[0][1] +  m[0][1] * n[1][1];
    int c = m[1][0] * n[0][0] +  m[1][1] * n[0][1];
    int d = m[1][0] * n[0][1] +  m[1][1] * n[1][1];
    int[][] ret = {
        {a, b},
        {c, d}};
    return ret;
}

and in your main function:

result = multMatrix(result, fiboM);` and `fiboM = multMatrix(fiboM, fiboM);

The signature of the multMatrix method lets us think that is works for any matrices.

Actually, it only works for 2*2 matrices. This should be documented and checked at runtime (because it doesn't seem to be possible to do so at compilation time).
Making Mathematics a bit more obvious

Values can be reformatted in such a way that the mathematics behind are easier to understand. Also, a little bit of comment can help.

    int[][] result = {
        {1, 0},
        {0, 1}};

    /*         n
     * [ 1 1 ]     [ F(n+1) F(n)   ]
     * [ 1 0 ]   = [ F(n)   F(n-1) ]
     */
    int[][] fiboM = {
        {1, 1},
        {1, 0}};


Haskell - Caching third party API token across requests

I think the type of apidefTokenRef unnecessarily exposes internal details. Perhaps it would better to parameterize APIDefaults with a monad and hide the code that gets the token behind a monadic action, like this:

data APIDefaults m = APIDefaults
  { apidefManager :: Manager
  , apidefPool :: ConnectionPool
  , apidefTokenAction :: m APIToken
  }

I'm also making it return the APIToken type instead of Text. It's good to have a more precise type for it than Text, let's not fall prey to primitive obsession!

Now APIEnv seems a bit redundant. Instead of reading the token from APIEnv, functions in need of it can simply execute the token action each time. Or perhaps we could define a function like

sequenceToken :: Monad m => APIDefaults m -> m (APIDefaults Identity)
sequenceToken r = do
    token <- apidefTokenAction r
    pure (r { apidefTokenAction = Identity token })

But how to define the token action itself? Here I will indulge in a bit of over-abstraction and define this typeclass:

class Perishable p where
    lifetime :: p -> NominalDiffTime

for values which have a certain lifetime during which they are valid. Of course, APIToken will have an instance.

What type should the function which creates the token action have? It will be something like

makeRefresher :: Perishable p => IO p -> IO (IO p)

(Working in IO for simplicity, the real function would likely work in MonadUnliftIO.)

The argument is an action that obtains the perishable value. But why the outer IO in the result? because makeRefresher will have to set up some reference—like an MVar—that will be used across successive invocations of the resulting action:

makeRefresher obtain = do
    ref <- newMVar _initialValueHole
    return $ _actualTokenActionHole

What should be on the MVar? Perhaps a Maybe (UTCTime, p). It would be Nothing initially to signify that no perishable value has been obtained yet, and later it would become Just (someTime,somePerishable). We have the time of creation and the expected lifetime of the Perishable, so we can decide whether to return the current value or invoke obtain again.

Instead of Maybe, I would perhaps use my own type, for clarity:

data PerishableState p = NoPerishableYet
                       | PerishableObtainedAt UTCTime p

Also, I would try to manipulate the MVar with functions like modifyMVar_ to avoid deadlocks if there's an exception while obtaining the token.

One potential disadvantage of this solution is that the token "state" becomes harder to inspect because it's hidden behind an opaque action. Perhaps some logging effect should be added.


Finding all possible combination of alphabets of length 5

Let me take a stab at this.

from itertools import product
def permuteKey():

    def pp(chunks):
        return map(''.join, chunks)

    k=pp(product('abcdefghijklmnopqrstuvwxyz', repeat=2))
    key=[]
    for i in range(len(k)):
        temp=k[i]
        temp2=[]
        for j in range(len(temp)):
            temp1=temp[j]
            temp2.append(ord(temp1)-97)
        key.append(temp2)
        print key

permuteKey()

Let's start by taking a look at the inner loop:

    temp=k[i]
    temp2=[]
    for j in range(len(temp)):
        temp1=temp[j]
        temp2.append(ord(temp1)-97)

First of all, you're only referring to temp[j] once, and never use j any further. The quick solution would be to iterato over temp instead:

    temp=k[i]
    temp2=[]
    for temp1 in temp:
        temp2.append(ord(temp1)-97)

But now we easily see that temp2 can be written as a list comprehension:

    temp=k[i]
    temp2=[ord(temp1) - 97 for temp1 in temp]

The temp = k[i] can also be removed, leaving

    temp2=[ord(temp1) - 97 for temp1 in k[i]]

Now we end up with

from itertools import product
def permuteKey():

    def pp(chunks):
        return map(''.join, chunks)

    k=pp(product('abcdefghijklmnopqrstuvwxyz', repeat=2))
    key=[]
    for i in range(len(k)):
        temp2=[ord(temp1) - 97 for temp1 in k[i]]
        key.append(temp2)
        print key

permuteKey()

Again, we can apply the trick that k[i] is only used once:

from itertools import product
def permuteKey():

    def pp(chunks):
        return map(''.join, chunks)

    k=pp(product('abcdefghijklmnopqrstuvwxyz', repeat=2))
    key=[]
    for val in k:
        temp2=[ord(temp1) - 97 for temp1 in val]
        key.append(temp2)
        print key

permuteKey()

Another thing I notice, is that you never use the value of one of the items itself, but always ord(c) - 97. Why not just replace abcd...xyz with range(26), and remove the ord(...) - 97 part?

from itertools import product
def permuteKey():

    def pp(chunks):
        return map(''.join, chunks)

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        temp2=[temp1 for temp1 in val]
        key.append(temp2)
        print key

permuteKey()

But now we don't need pp anymore.

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        temp2=[temp1 for temp1 in val]
        key.append(temp2)
        print key

permuteKey()

Also, the definition of temp2 is now equal to val.

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        temp1 = list(val)  # `val` is a tuple, but your code expects a list.
        key.append(temp1)
        print key

permuteKey()

Does it really matter that you want lists instead of tuples? I think not.

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        key.append(val)
        print key

permuteKey()

Now, I have to wonder: why are we actually printing key at every step? I think you might have made a typo, so I'm going to assume you meant the following: (If not, skip the review from here).

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        key.append(val)
    print key

permuteKey()

Now, it's bad practise to print inside a function. Better would it be to return the value.

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    key=[]
    for val in k:
        key.append(val)
    return key

print permuteKey()

Now, notice the similarity between k and key. key = list(k).

from itertools import product
def permuteKey():

    k=product(range(26), repeat=2)
    return list(k)

print permuteKey()

But, now you have an intermediate value, you do not need it, and you can remove it.

from itertools import product
def permuteKey():
    return list(product(range(26, repeat=2)))

print permuteKey()

Now, I don't know how often you need permuteKey. If only once, you can write

from itertools import product
print list(product(range(26), repeat=2))


Simulates flipping a coin repeatedly and continues until however many consecutive heads are tossed

Loop

  Also i assume assigning -1 to i was an appropriate move as well because after a loop cycle it will iterate (i++) causing i to become 1 if I had not, resulting in one less loop.

Well, that works, but I think it would be more clear to explicitly increment i on heads, and reset it otherwise:

for (int consecutiveHeads = 0; consecutiveHeads < CONSECUTIVE_HEADS_THRESHOLD;) {
  ...
  if (coinSide.equals("Heads")) {
    consecutiveHeads++;
  } else {
    consecutiveHeads = 0;
  }
}

That could be a while loop as well, depending on your tastes.

Comments

/* Create an instance variable for the random number generator */

This is not really necessary. It's clearly an instance variable, and the names and types show that it is a RNG.

/* Private constant */

Again, this isn't really necessary. private final already shows that is is a private constant. Even if you these comments are more intended for organization, a common approach would be to group these variables in blocks at the top of the class, with implicit meaning.

They don't take away from anything, they're just not really necessary.

/* Returns true 50% of the time */
private String flipCoin() {

This is not accurate. It will never return true. It returns strings.

Matching strings

Matching against strings is somewhat fragile. If this was a larger codebase, you would probably implement an enum for the coin sides, although it's overkill for this example. Altogether, a slightly more genericized version might look something like this:

public class ConsecutiveHeads extends ConsoleProgram {

  // These traditionally go up top, not at the bottom of the class.
  private final RandomGenerator rgen = RandomGenerator.getInstance();
  private static final int DEFAULT_CONSECUTIVE_HEADS_THRESHOLD = 3;

  public void run() {
    run(DEFAULT_CONSECUTIVE_HEADS_THRESHOLD);
  }

  // Theshold is parameterized
  public void run(final int consecutiveHeadsThreshold) {
    int flips = 0;
    for (int consecutiveHeads = 0; consecutiveHeads < consecutiveHeadsThreshold;) {
      CoinSide toss = flipCoin();
      flips++;
      println(toss.getName());

      if (CoinSide.HEADS.equals(toss)) {
        consecutiveHeads++;
      } else {
        consecutiveHeads = 0;
      }
    }
    System.out.printf("It took %d flips to get %d consecutive heads.", flips, consecutiveHeadsThreshold);
  }

  private CoinSide flipCoin() {
    return CoinSide.from(rgen.nextBoolean());
  }

  // Alternatively, in the limited scope of this example, you could
  // just define `true` to be heads and then not bother defining tails
  // at all.
  enum CoinSide {
    HEADS("Heads"), TAILS("Tails");

    private final String name;
    CoinSide(String name) { this.name = name; }
    public String getName() { return name; }

    public static CoinSide from(bool value) { return value ? HEADS : TAILS; }
  }
}


I think instead of writing the macro MISC_XCHG and using only once, I would just write the swap directly in place.
The use of upper-case for the single-letter locals is unconventional, and looks odd.
I haven't measured performance, but it seems that sorting already-ordered (or nearly-ordered) input is likely to suffer as a consequence of always picking the first element as pivot.  A popular strategy is to pick the median of the first, last and central elements.  It doesn't matter that these are not necessarily distinct when we get to the very smallest partitions.
I do like the code that chooses the smaller partition for the recursive step, and uses iteration on the larger partition.
I don't understand why L is a uintptr_t - I would have thought size_t the obvious choice, the same as standard qsort().
The cast of cmp from  bool(*)(t const*, t const*) to (bool(*)(void const*, void const*) leads to Undefined Behaviour when it's called as the wrong type.  The correct way to provide a type-specific comparator is to convert the arguments:
#define DEFINE_QSORT_COMPARATOR(s,t,cmp) \
  static bool qsort_compare_##s(void const *a, void const *b) \
  { t const *x = a; t const *y = b; return cmp(*x, *y); }


Just for dealing with ready alone I use jQuery -- it does the cross-browser heavy lifting, is well-tested and maintained. Minified, it's only 32K, and included from a CDN, you get fast delivery that may already be cached in your user's browser.

And there is a lot more code than what you have above to deal with all of the browsers being ready.

There's some good coverage in Paul Irish's 10 Things I learned from the jQuery source screen-case .ready coverage starts around 21:20. There's also some links to jQuery sources.


Connections

You don't close your sockets and connections. The best way to ensure you close them is with a context manager (with-statement)

You can also reuse the socket you make, and connect it to other ports. This would make a SocketConnection:

class SocketConnection:
    def init(self, ip, port=None):
        self.socket = None
        self.ip = ip

    def __enter__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def __exit__(self, type, value, traceback):
        self.socket.close()
        self.socket = None

    def portscan(self, port):
        if self.socket is None:
            raise ConnectionError('No socket open')
        try:
            return not self.socket.connect_ex((self.ip, port))
        finally:
            self.socket.detach()

This can be used like this:

def scan_ports(ip, port_range):
    """yields the open ports in `port_range` (port_range is half-open) """
    with SocketConnection(ip) as connection:
        for port in range(*ports):
            if connection.portscan(port):
                yield port

Validate input

You don't validate the input of your client. To do this, you can do something like this:

def validate_ip(ip):
    return True # needs implementation
def get_ip():
    while True:
        ip = input("Target IP: ")
        if validate_ip(ip):
            return ip

You can do ctrl+C to get out of this while True loop

and then the main() function:

def main():
    logging.basicConfig(filename="errlog.log", format="%(asctime)s : %(message)s")
    logging.info("Start")
    message = """
    Hello user and welcome to Network Port Scanner!
    Please insert a IP address that you want to scan for open and closed ports.
    The range of ports scanned is 1-65535.
    """
    print(message)
    ip = get_ip()
    open_ports = list(scan_ports(ip, (1, 65536)))

    print(
        f"""open ports: ({len(open_ports)})
        {open_ports}""")

Caveat: I don't know a lot about socket programming. I just used the python documentation, so there might be socket-related bugs


Second for loop
Your second loop will only iterate once, because string is only 1 character long:
string = l[i]

I think you meant to slice here.
Incrementing an int
You can use the += operator to increment an integer:
x = 0

for i in range(3):
    x += 1

str.startswith
For the most part, you can use str.startswith to check if the suffix starts with the prefix (other than the case where prefix is ''):
prefix, suffix = 'a', 'abc'

suffix.startswith(prefix)
True

This is a bit more idiomatic than slicing from position i or j to compare with a prefix
Creating your prefix and suffix
When generating your prefix and suffix, slice once, and you can keep your code down to one loop:
for i in range(len(l)):
    # Generate your prefix and suffix here
    prefix, suffix = l[:i], l[i:]

    # rest of code

Instead of a counter, use an if statement
For actually tabulating your results, you can use an if statement, paired with the str.startswith logic to cut down on your second loop.
Furthermore, it appears from the example that if the prefix is an empty string, you append the length of the suffix. This can go in the if str.startswith bit because 'anystr'.startswith('') will return True:
results = []

# Start your loop
for i in range(len(mystring)):
    # Create your prefix and suffix based on slice point
    prefix, suffix = mystring[:i], mystring[i:]

    # check str.startswith here
    if suffix.startswith(prefix):
        # You can use a ternary if block in the append to cover the
        # empty string case
        results.append(len(prefix) if prefix else len(suffix))
    else:
        results.append(0)

The ternary operator will result in either the left side if the predicate is truthy, otherwise the right side
x = 'a' if True else 'b'

x
'a'

x = 'a' if False else 'b'
x
'b'

x = 'a' if '' else 'b'

x
'b'

Empty strings are falsey.
Style
Naming Conventions
Method names should be snake_case:
def some_method_name():
    # do things

Spacing
There should be a space between a name, the equals sign, and a value:
# instead of this
some_value=3

# do this
some_value = 3

The exception to this is with keyword arguments in a function
def f(key='value'):
    return None

# No extra spaces here
f(key=1)

Be careful about name shadowing
string is the name of a module, so watch out for cases where you might acidentally name a variable something that you may import (or users of your code might import). Not a huge deal in this case, but certainly something to watch out for. Note that this accounts mostly for common modules and functions, both built-in and 3rd party like string, pandas, math, sum, etc.


Rearrange string to an anagram of the string - get new position, old position values

You can simplify the logic by setting each character you find in target to NULL. I also like to use a "while" loop as shown below.

function _get_new_positions(source, target) {
    var transform = [], i, j, found, want;
// convert both strings to arrays - uppercase so we can find the destination without worrying about cases
    source = source.toUpperCase().split('');
    target = target.toUpperCase().split('');
    for(i=0; i<source.length; i++) {
        j = 0;
        found = false;
        want  = source[i];
        while((j < target.length) && !(found = (target[j] == want))){j++}
        if (! found) {
            console.log("Cannot find character: " + want + " at [i]: " + i);
        } else {
            console.log("Found character: " + want + " at [i,j]: " + i + j);
            target[j] = ''; //blank out the character for future searches
            transform.push([i,j])
        }
    }
    return transform;
}


You report errors if any of the files fails to open, but continue execution anyway.  If either of them fails to open, you should also return EXIT_FAILURE.  In addition, you should be writing the errors to cerr instead of cout.

On those same output lines, you're indenting by just one space, but you indent by four spaces everywhere else.  You should try to keep the spacing consistent.
Don't cram lines like this:

oufile<<"Case #"<<x<<": "<<all<<std::endl;

Add more whitespace between operators for readability:

oufile << "Case #" << x << ": " << all << std::endl;

Be sure to do this everywhere, not just with this line.
You don't need to close files yourself, unless you're needing to check for errors.  Since you're not, you can just remove these function calls.
Since count_wrd is incremented with each call to hold.push_back(), you can just use hold.size() in place of count_wrd.  You could also rename this vector to words.
This doesn't need to be two separate lines:

rvrs += hold[i];
rvrs += " ";

It can just be one:

rvrs += hold[i] + " ";


You are effectively picking your first hex digit from "123456789ABCDEF" (no zero) and the subsequent digits from "0123456789ABCDEF".  Hence it might be better to adjust the first random pick:

// This assumes that str_len is at least 1.
*str = *(digits + (1 + rand() % 15));  // Pick first char in range 1..15
str++;

// For loop starts at 1 as str[0] already picked.
for (int i = 1; i < str_len; i++) {
    *str = *(digits + (rand() % 16));  // Following chars in range 0..15
    str++;
}

That eliminates the tmp_char variable and the while loop, which makes the code a lot cleaner, to my eye anyway.


First of all, you should declare all of these in it's own scope, not in the global scope. That way, other code (or your own code) won't collide with naming. A simple IIFE would do:

(function(){
  //All code in here
}());

Your code assumes that it will run on modern browsers. But what if your user doesn't use one or can't use one (cough, enterprise, cough)? You code should check if these new APIs like FileReader and Blob exists. Modernizr is a handy library for this.
Likewise, you should also prepare for inconsistent APIs on browsers. addEventListener doesn't exist in older IE browsers. I suggest you use a library like jQuery for this as well as for other operations to normalize the results. It's easier, and you won't be repeating code.
Use libraries to simplify the job. True, libraries can add a bit of baggage to your code, but it shouldn't be an excuse not to use them. jQuery is just 40KB. In contrast, images and backgrounds in websites reach 1MB. How's that for size?
Scale. This code assumes you will only have one editor. What if you wanted more than just one in the near future? What if the app increases to 100k lines of code? Would you dig deep to change element id's and variable names for a second editor?

Or would prefer calling a function, and a set of configs in a few lines of code and create a second one? Something like:

$('#some-element,#another-element').myVeryCoolTextEditor({
  emoji : true,
  someCoolConfig : true,
});

I suggest you take a look at jQuery Boilerplate to easily structure plugins and plugin states.
Reusablility. A jQuery plugin is not the answer to everything, but I'm just suggesting it for a clean and structured code (Check the comments in the source). You can even go without it, as long as you keep your code reusable and "plugin-like". Think "Drop this script and a one-liner and it just works!"


* or []
There isn't really a definitive time when you should and shouldn't use pointers or arrays  (at least not that I know of). However, I generally only use arrays for:

Large buffers. For example, if you were reading a file.
A definitive size array of a simple type, such as an int or a char.
A group of constants all sharing the same type (your commands array, for example).

The two things are very similar. However, pointers are more idiomatic and C and I find are actually a lot easier to use.

Here is a great example of using pointers or arrays:

for (c = 0; string[c] != '\0'; ++c)
    string[c] = tolower(string[c]);

If instead of receiving an array through an argument you received a char *, you could do this:
for(; *string != '\0'; string++) {
    *string = tolower(*string);
}

This completely eliminates the need for c, and is a lot cleaner. Here, in the above snippet, we are taking the pointer string and increment through it each iteration.
Note that you still might be able to use an array in the arguments, it would just look a lot cleaner if you wrote it like this:
char *string

instead. I think it would still work either way (I did not test it), which is one of those gray areas between arrays and pointers.

const vs #define
Your #defines as the top should not be #defines:
const int MAX_TEXT_LENGTH = 100
const int MAX_DESC_LENGTH = 100
const int MAX_KEYWORDS_LENGTH = 100
const int NUM_COMMANDS = 8
const int NUM_RESULTS = 3

This is better practice than using #defines as those do not specify a direct type for the value; the pre-processor simply substitutes that number as a string into your code and it is up to the compiler to determine a type.

sprintf

    strcpy(current, commands[c].text);
    strcat(current, commands[c].description);
    strcat(current, commands[c].keywords);

Three separate function calls to concatenate three strings? That's not very efficient; and it's quite ugly. It would be better to use sprintf:
sprintf(current, "%s%s%s", commands[c].text, commands[c].description, commands[c].keywords);

Actually, this looks like a toString method for a command struct. Time for a refactor!
void buffer_tostring(char *buf, struct command);

Simply move that code (with slight adjustments) into a method like the one above; it is good to split your code into as many different (and logical) methods as you can so that everything follows the single responsibility principle, overall making your code more maintainable.
You could also do the same thing for your results struct regarding here:

    strcpy(results[c].text, commands[c].text);
    strcpy(results[c].description, commands[c].description);


HackerRank New Year Chaos: arriving at a given list using neighbor swaps

Good attempt, but unfortunately the nested loop brings the time complexity to O(n2). Keep in mind that .find performs a linear search on the vector, inspecting up to the entire array to find an element. We can arrive at a O(n) solution by exploiting the fact that no more than 2 swaps can be performed by any given element, which is a red flag in the problem statement that your solution ignores. In other words, we can transform the linear operation inside the array to constant time.

Here's the approach I used:

Start at the back of the array and move forward. For each element q[i] not in its original location, check only q[i-1] and q[i-2] to see if it moved to one of those locations. If the element is in q[i-1], then it must have used only one bribe. If at q[i-2], it must have taken two bribes to get there. Either way, perform an un-swap to return it to its original location. If it's not at either element, the array is "Too chaotic".

Let's try this algorithm on the input examples:

Example 1

initial state:
[2, 1, 5, 3, 4]

[2, 1, 5, 3, 4]
             ^-- This element should be a 5. Let's look for 5 at index 3 or 2.
[2, 1, 5, 3, 4]
       ^-------- Found 5 at index 2. It must have swapped twice; set `bribes = 2`.
[2, 1, 3, 4, 5]
             ^-- Put 5 where it belongs by undoing the swaps it made.

[2, 1, 3, 4, 5]
          ^-- Moving to the next element, we see 4 is OK.

[2, 1, 3, 4, 5]
       ^-- Moving to the next element, we see 3 is OK.

[2, 1, 3, 4, 5]
    ^-- Moving to the next element, this element should be 2.
[2, 1, 3, 4, 5]
 ^----- Found 2. It must have swapped once; set `bribes = 3`.
[1, 2, 3, 4, 5]
    ^-- Put 2 where it belongs by undoing the swap it made.

Outcome: 3 bribes in total must have happened.

Example 2

initial state:
[2, 5, 1, 3, 4]

[2, 5, 1, 3, 4]
             ^-- This element should be 5. Let's find 5.
[2, 5, 1, 3, 4]
          ^----- This element, q[i-1], is not 5.
[2, 5, 1, 3, 4]
       ^-------- This element, q[i-2], is not 5, either.

Outcome: Too chaotic! 5 must have used more than 2
         bribes to get any further than index 2.


Parse the phone balance from the operator site

It is not perfect example, but your code might be like this:

function __construct()
{
//...
    $this->cookieUrl = 'https://-------------/ps/scc/login.php';
    $this->sessionUrl = 'https://-------------/ps/scc/php/check.php';
    $this->balanceUrl = 'https://-------------/SCWWW/ACCOUNT_INFO';
//...
}

function loginToService()
{
    $response = $this->_sendPostRequest($this->cookieUrl, '', null, 1);
    preg_match_all("/PHPSESSID.*;/isU",
                $response, $matches, PREG_PATTERN_ORDER);
    $this->phpsessid = $matches[0][0];
    if (!this->phpsessid) {
        throw new Exception ('Could not retrieve PHP session id');
    }
}

function getServiceSessionId()
{
    $vars = array(
        'LOGIN' => $this->login,
        'PASSWORD' => $this->password,
    );
    $response = $this->_sendPostRequest($this->sessionUrl, implode('&', $vars), $this->phpsessid);
    preg_match_all("/<SESSION_ID>.*<\/SESSION_ID>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
    $this->sessionId = strip_tags($matches[0][0]);
    if (!$this->sessionId) {
        throw new Exception ('Could not retrieve Service session id');
    }
}

function getBalanceMessage()
{
    $vars = "SESSION_ID={$sessionId}";
    $response = $this->_sendPostRequest($balanceUrl, $vars);
    preg_match_all("/
.*<\/div>/isU",
            $response, $matches, PREG_PATTERN_ORDER);
    if (count($matches[0]) == 0) {
        preg_match_all("/
.*<\/div>/isU",
                $response, $matches, PREG_PATTERN_ORDER);
    }
    retrun strip_tags($matches[0][0]);
}

/* begin */
try {
    $this->loginToService();
    $this->getServiceSessionId();
} catch Exception $e {
    return $e->getMessage();
}
$this->balance = $this->getBalanceMessage();;
$this->updated = date(Settings_Constants::DATETIME_DATABASE_FORMAT);
$this->save();
$this->balance; //What the hell is this?
/* end */


leetcode 987. Vertical Order Traversal of a Binary Tree

Your code seems to have the right general structure, but is doing some extra work.

Comments would help people (including you in the future) understand what your code does and why (e.g the comment below explaining why -y is used).

Also, the problem says that nodes at the same x-coord are listed in order of their y-coord (top-to-bottom) and then by value, but you don't seem to keep track of the y-coord.

from collections import defaultdict

class Solution:
    def verticalOrder(self, root: TreeNode) -> List[List]:
        # the stack keeps track of nodes that are waiting to be
        # processed, along with their x and y coordinates
        stack = [(root, 0, 0)]

        # the key is x-coordinate of a tree node, the value is a list of (-y, node_value) tuples.
        # We use -y so so that when the list is sorted later, the tuples are sorted top-to-bottom
        # and then by node_value
        node_map = defaultdict(list)

        # while there are nodes left to be processed, get the next one and add it to the node_map
        while stack:
            node, x, y = stack.pop()
            node_map[x].append((-y, node.val))

            # add the node's children to the stack for processing
            if node.left:
                stack.append((node.left, x - 1, y - 1))

            if node.right:
                stack.append((node.right, x + 1, y - 1))

        result = []

        # process groups of nodes in order from smallest to largest x-coordinate
        for x_coord in sorted(node_map.keys()):

            # sort the tuples by y-coordinate and then value
            values_at_this_x = [node_value for _,node_value in sorted(node_map[x_coord])]

            result.append(values_at_this_x)

        return result


Save to a MySQL database a temporary row with all information about a receipt

With this code:

string items = "";
 for (int i = 0; i < _ProductsGrid.Rows.Count; i++)
 {
     items += _ProductsGrid.Rows[i].Cells[1].Value.ToString();
     items += ",";
 }

items = items.Remove(items.Length - 1, 1);

You're concatenating a list of values into a string. Let me first say a word about that try/catch. Exceptions are exceptional conditions, if you can avoid an exception then you should:

if (items.Length > 1)
    items = items.Remove(items.Length - 1, 1);

However you do not need it, both items and Qnt can be created with like this (assuming _ProductsGrid is a DataGrid but same logic applies in any case):

var rows = _ProductsGrid.Rows.Cast<DataRow>();
string items String.Join(";",
    rows.Select(x => Convert.ToString(x.Cells[1].Value)));

Now let's see you SQL. You're building SQL commands into strings, it makes your code hard to debug, open to SQL injection attacks and fragile because invalid and unexpected user inputs will crash the application. Use SQL parameters:

string query = "SELECT * FROM TempSave WHERE Localization=@Localization";

Now you have to build the command:

using (var cmd = new MySqlCommand(query, connection))
{
    cmd.Parameters.AddWithValue("@Localization", _Save.Localization);

    // ...
}

And you have the reader:

using (var reader = cmd.ExecuteReader())
{
    // ...
}

Note that using parameters also the string concatenation will go away (because you can dynamically create named parameters as @param1, @param2 and so on).

You do not need to call MySqlConnection.Close() if (correctly!) you're already wrapped the object inside a using statement.

Please follow usual C# naming guidelines, they will make your code easier to read for everyone (for example local variables should be camelCase). Stick to one convention and follow it (to have items and Qnt is confusing, why they have different casing?)

Also try to use meaningful names for your variables. Code should be a fluent sentence to read like a book.

Catch exceptions. Things may go wrong and you do not want to crash entire application.

Validate user input. What if user didn't enter anything in one of your input boxes?

Split code into separate methods, it helps because to understand whole logic you need to read just few lines, not the entire code. Think (names are weird because I do not know your domain but you must do better):

if (CheackTemDataAlreadyExists())
    DeleteCheackTemData();

InsertCheackTemData();

Note that  you should avoid code duplication (INSERT was repeated twice).

Do not hard-code constants (like connection string). Ideally it should be in your configuration file but, at least, move it to a private const string field.


MyTruck and MyCar do not need their own initialize, the behaviour looks the same as the one in MyVehicle.

if self.on == false may be replaced with if !self.on or predicates

def on?
  on
end
def off?
  !on
end

see http://ruby-for-beginners.rubymonstas.org/objects/predicates.html .

Using self.class.mileage(self.gallons, distance.to_i) allows to overwrite class method mileage.

self.speed == 0 may be replaced with self.speed.zero? because
0, 1 and the likes are Integer objects and respond to zero?, although this is opinionated, i.e. not every object respond to zero?.


Python unittest.mock.patch.object context manager

First, note that this is all untested, but the ideas should hold up. I tried to abstract a lot of the logic by distilling the Mock object creation to a dictionary containing the data, but it turned into a bit of a mess. To start with, consider the following structure for your Mock object data:

async def coro(a):
    return a

mock_object_data = {
    'validator': {
        'subattrs': [
            {'validate':
                {'return_value': True}
            }
        ]
    },
    'model': {
        'subattrs': [
            {'create_instance':
                {'side_effect': coro}
            }
        ]
    },
    'normalizer': {
        'subattrs': [
            {'normalized':
                'side_effect': lambda a: a
            }
        ]
    }
}

This contains the name of each Mock object, any keyword arguments that are necessary, and any attributes that also need to be created (as Mock objects themselves). These can be created from this structure using the following functions:

def _generate_mock_object(attr_dict):
    if 'subattrs' in attr_dict:
        subattrs = attr_dict.pop('subattrs')
    else:
        subattrs = []

    mock_object = Mock(**attr_dict)

    for subattr_dict in subattrs:
        for subname, kwargs in subattr_dict.items():
            setattr(mock_object, subname, _generate_mock_object(kwargs))

    return mock_object

def generate_mock_objects(object_data):
    return {n: _generate_mock_object(d) for n, d in object_data.items()}

This allows for a arbitrary number of Mock objects to be created. However, this runs into some problems when we want to use the context manager since it is not natural to have an arbitrary number of required contexts. This can be achieved using a recursive function. Here, we will supply a sequence of callables that are to be opened with the with statement, and a callback function and arguments to be executed once all of the contexts are opened.

def recursive_context_manager(callable_seq, callback, *args, **kwargs):
    if not callable_seq:
        return callback(*args, **kwargs)
    else:
        current, *rest = callable_seq
        with current():
            return recursive_context_manager(rest, callback, *args, **kwargs)

Finally, we want to create a decorator which will do the following things: (a) create all of the Mock objects, (b) generate and enter the required contexts, and (c) execute the supplied function.

def bind_mock_object_data(data):
    def decorator(f):
        factory = lambda name, obj: lambda: patch.object(CreateMixin, name, new=obj)
        mock_callables = [factory(n, o) for n, o in generate_mock_objects(data).items()]
        def wrapper(*args, **kwargs):
            return recursive_context_manager(mock_callables, f, *args, **kwargs)
        return wrapper

After all of this overhead, your final test code comes out nice and clean.

@unittest_run_loop
@bind_mock_object_data(mock_object_data)
async def test_post_response(self):
    response = await self.client.post('/', data='{"body": "ok"}')
    text = await response.text()
    self.assertTrue(text == '{"body": "ok"}' or text == '{\n    "body": "ok"\n}')


My explorations on GCD and performance

Aside: you might find My blog post interesting, where I found bottlenecks in GCD including branch prediction, lack of instruction parallelism, and the DIV instruction.  Even things like Modulo is significantly slower for signed types compared to unsigned types of the same size!  Since the values being used are all positive, that is another speedup.

For some operations, the opcode is faster for 32-bit than 64-bit; so switching to a smaller version once the numbers get small enough will speed it up.

I found that an algorithm written for computers in 1961 that does no division runs slower than the modern expression when coded naively, but once the bottlenecks in that are found and eliminated, it runs much faster.  The CPU can burn through lots of primitive instructions so the increased length is not significant; it’s the traffic jams inside the CPU that kill the performance.

Your code review

Don’t write using namespace std;.

You can, however, in a CPP file (not H file) or inside a function put individual using std::string; etc.  (See SF.7.)

You should break up the monolithic main into smaller functions.  It is clear that first you read the input, then you do the actual work.

Write the function that does the real work isolated from any real I/O.  It takes parameters and returns values.  You can call that from test cases that means you don’t have to type the input yourself every time!  And you can have a function to read the input in the manner needed, for the final deliverable.

Meanwhile, the functions you write to load arrays from a file like that can be reused for the next problem.  You can be sure it has no code tangled up with the old program — it is just for getting input.

Your code seems complex since GCD itself is just a few lines.  Is that what countGcd is?  The name is odd if it returns GCD, not the count of something.  No, that’s just one step as there is no while loop.  Point is, I have no idea from the names and complete lack of comments just what this code does or how it works.

    for ( size_t j = 0; j < arr.size(); ++j ) {

It appears that this could be a range-based for loop.  I see you refer to arr.at( j ) eight times!  And you are wondering about performance?

for (auto current : array) {

and then I think the long line is the actual GCD calculation because of its name:

    auto GCD= compute_GCD (current, elem);

put that in a separate (readable) function.  It will also make it easy to change the implementation of the GCD algorithm itself without messing with the rest of the program!

        if ( gcd > max_gcd ) {

            max_sum = elem + arr.at( j );
            max_gcd = gcd;
        } else if ( gcd == max_gcd ) {
            size_t sum = elem + arr.at( j );
            if ( sum > max_sum )
                max_sum = sum;
        }

You want to accumulate the maximum incrementally.  It’s probably not worth using an stl algorithm for that since you are giving it the input incrementally rather than having a prepared list.  It can, however, but split into a separate function or accumulator class.

The complex part here is the tie-breaking.  Understand that the description is simply that of a compound key!  Think of sorting names:  if the last name matches, then sort by the first.

Now std::pair already does this for comparison operators.  So make a pair{GCD,sum} of the current trial, and have the max variable of the same type.  Now you just need a straightforward remember the largest accumulator.

using respair = std::pair<size_t, size_t>;

static respair best { };

void check_for_best (const respair& x)
{
    best = std::max (best,x);
}

basically, it reduces to one line.

max.second will be the max sum.


Avoid using the same type to store the results of plain digests and HMACs
You can't (or at least should never be able to) compare a HMAC to a plain digest. So would be good if the type system could catch that potential mistake. Instead of having a DigestStore<Hash> class that is used both for plain digests and HMACs, I would just have Digest<Hash> and HMAC<Hash> each store their own result directly.
Allow adding data to the HMAC in multiple steps
As mentioned in the review for part 1, it is not uncommon to have to add multiple, discontiguous pieces of data to be added to the HMAC, so have a member function add() that can update the HMAC. This would mean splitting the creation of the HMAC in three parts:

The key material is prepared as part of the constructor
The message is added to the hash, either in one go or using multiple function calls
The final value is calculated

I would structure the class like so:
template<typename Hash>
class HMAC {
    Digest<Hash> outer_digest;
    Digest<Hash> inner_digest;

public:
    HMAC(std::string_view key) {
        // Add key XOR opad to outer_digest
        // Add key XOR ipad to inner_digest
    }

    // Convenience constructor to do a one-shot HMAC creation
    HMAC(std::string_view key, std::string_view message): HMAC(key) {
        add(message);
        finish();
    }

    void add(std::string_view message) {
        // Add message to inner_digest
    }

    void finish() {
        // Finish inner_digest, add it to outer_digest
        // Finish outer_digest
    }

    // Something to get the bits out
    const auto &get() {
        return outer_digest.get();
    }
};

You might also want to add some way to prevent finish() from being called more than once.
Avoid unsafe operations
Your own words:

I just hate reading these badly written C++ (which is why I started this hack) projects that are crappy wrappers around C rather than using good type safety and nice clean C++ interfaces and techniques.

You want good type safety, but I also think you want good safety in general. Creating unsafe functions goes against that goal. If you store the results of a hash in a Digest object, and have a way to get a const reference to the data it stores, then you don't need a hashUnsafe() function.


It might be a personal preference, but I find indenting the entire procedure body massively helps making a module easier to read - the only thing that's left in column 1 is module-level declarations, procedure signatures, and line labels. Conversely, not indenting the entire procedure body makes it harder to tell which procedure starts/ends where in a module.

Sub SaveFile(fName As String)

The procedure is implicitly Public, which makes it hard to tell whether it's meant to be used in the same module, or if it's meant to be called by code outside the module. If it's meant to be used in the same module, make it Private. If not, make it explicitly Public.

The fName parameter is implicitly passed ByRef, which means if SaveFile reassigns the parameter, the new value will be visible at the call site. If that's intentional, an explicit ByRef modifier should be there. Given the parameter isn't reassigned in the body of the procedure, it should be passed ByVal.

It's not clear how the procedure is used, but it seems cancelSave is declared outside the procedure. If it's in the same module, it should be Private. If it's in another module, then it's Public and you have a global variable... and in all likelihood (assuming SaveFile is called from some BeforeSave event handler) it could be avoided by making the procedure a Function that returns a Boolean:

Public Function SaveFile(ByVal fName As String) As Boolean

I strongly doubt you actually need a global variable for this.

The procedure feels wrong, because error-handling logic is intertwined with the actual procedure logic; these On Error and GoTo statements obscure the intent of the code.

Typically, error-handling is done in a dedicated subroutine, and no GoTo statement is needed - you want to run some logic in a loop until the user cancels out; it's much clearer if you use one of VBA's many loop structures instead of implementing that GoTo-loop.

Let's take a moment to consider this alternative implementation:

Public Function SaveFile(Optional ByVal initialPath As String = vbNullString) As Boolean
    On Error GoTo CleanFail
    Dim cancelSaveHandler As Boolean

    Dim completed As Boolean
    While Not completed

        Dim result As Variant
        result = Application.GetSaveAsFileName(InitialFileName:=initialPath, FileFilter:="Excel Files (*.xlsx), *.xlsx")

        If VarType(result) = vbBoolean Then
            'cancelling GetSaveAsFileName dialog returns False:
            cancelSaveHandler = True
            completed = Not result
        'ElseIf Dir(result) = vbNullString Then
        '    'selected file doesn't exist, try saving:
        '    ActiveWorkbook.SaveAs FileName:=result, FileFormat:=xlWorkbook, ConflictResolution:=xlLocalSessionChanges
        Else
            ActiveWorkbook.SaveAs result
        End If

    Wend

    SaveFile = cancelSaveHandler
    Exit Function

CleanFail:
    completed = (MsgBox("An unexpected error has occurred while saving. Try again?", vbYesNo + vbExclamation) = vbNo)
    Resume Next
End Function

Notice:

The parameter is Optional, because it's not really required; it's also named in a way that doesn't suggest that that's the name we're saving the file with.
The loop is explicit; there's no GoTo jump.
The error-handling logic is completely separated from the procedure's actual logic.
Error handling doesn't leave unexpected errors dangling unhandled, and only ever runs when a runtime error happens.
No implicit conversion from Variant/String or Variant/Boolean when evaluating whether the GetSaveAsFileName dialog was cancelled.
No more double-negative when checking if the file exists.
Checking if the file exists is redundant if we're going to save either way; xlWorkbook is the default format anyway, and what's wrong with prompting for conflict resultion (the default behavior) if/when applicable?
User knows what's happening and why, at all times.
We're returning a value to the caller instead of assigning a global variable: there are no side-effects to global state.

In an ideal world, there would also be a VB_Description attribute, to describe what the function does:

Attribute SaveFile.VB_Description = "Prompts user for a non-existing file name and saves the active workbook. Returns True if 'BeforeSave' handler should be cancelled."

You can set this procedure attribute via the Object Browser, by browsing to the function, right-clicking, selecting "Properties" in the context menu, and entering a value in the "Description" box. That description will then be visible in the Object Browser:

Ideally all public members should have a description.


BASH Script to Configure Monitors on Linux via xRandR

for a problem like this, it helps to break down the possible states and map out what you want to do for each, and then construct a data model that lets you minimize duplication.

Here is my approach to your problem:

hardcoded array of monitors by order of preference, allowing wildcards
hardcoded assoc. array of screen resolutions for each preference
hardcoded assoc. array of options templates for each possible configuration
construct array of actual available monitor names from (1) and xrandr output
construct array of resolutions from (2) and (4)
get options template from (3) and (4)
fill template using (4) and (5)

__

#!/usr/bin/env bash

# each PRIORITY entry must have matching entry in MODE; $displays will be sorted in priority order
declare -ar PRIORITY=( "DP-1*" HDMI-2 eDP-1 )
declare -Ar MODE=(
        [eDP-1]=1920x1080
        [DP-1*]=2560x1440
        [HDMI-2]=1680x1050
    )

# options corresponding to each possible config.  sorted in PRIORITY order.
# left hand side is matched against space-separated list of actual monitor labels from xrandr
# template values like <D2> are zero-based
declare -Ar OPTS=(
            [DP-1* HDMI-2 eDP-1]='--output <D2> --off --output <D0> --mode <M0> --pos 1680x0 --right-of <D2> --output <D1> --mode <M1> --pos 0x0 --left-of <D0>'
            [HDMI-2 eDP-1]='--output <D1> --off --output <D0> --mode <M0> --pos 0x0'
            [eDP-1*]='--output <D0> --primary --mode <M0> --rotate normal --pos 0x0'
        )

declare -ar ALL_CONNECTED=( $( { xrandr -q || exit 1; } | awk '$2 == "connected" {print $1}' ) )

[[ ${#ALL_CONNECTED[@]} = 0 ]] && {
    echo no monitors connected
    exit 1
}

declare -a displays=()
declare -a modes=()

# populate displays and modes in preference order from ALL_CONNECTED
for (( i=0; i<${#PRIORITY[@]}; i++ )); do
    for (( j=0; j<${#ALL_CONNECTED[@]}; j++ )); do
        if [[ ${ALL_CONNECTED[$j]} == ${PRIORITY[$i]} ]]; then
            displays+=( ${ALL_CONNECTED[$j]} )
            modes+=( ${MODE[${PRIORITY[$i]}]} )
            break
        fi
    done
done

echo "
ALL_CONNECTED: ${ALL_CONNECTED[@]}
displays: ${displays[@]}
modes: ${modes[@]}
"

for i in "${!OPTS[@]}"; do
    if [[ "${displays[@]}" == $i ]]; then
        opts=${OPTS[$i]}
        opts=${opts//<M/\$\{modes\[}
    opts=${opts//<D/\$\{displays\[}
        opts=${opts//>/\]\}}
        set -x
        xrandr $( eval echo $opts )
        exit $?
    fi
done
echo "no OPT setting found for connected display combination of ${ALL_CONNECTED[@]} [ ${displays[@]} ]"
exit 1


Animation for collapsing/expanding a navigation bar

Here are some quite general pointers on your code. If you put up a fiddle with everything working, I might be able to play around and re-write this for you. But anyways, I've included my comments directly into the code to provide some context:

$(function() {//Is this what wraps your entire code, or just this part of it?
    var newHash      = "",
        $NavmainContent = $("#contentNavigationWrapper"),
        $mainContent = $(".contentWrapper"),
        $first       = $('#currentSection'),
        $second      = $('#project-tools'),
        $third       = $('#project-pagetools'),
        $fourth      = $('#cp'),
        $pageWrap    = $("#page-wrap"),
        baseHeight   = 0,
        $el; //You define "el" but don't use it anywhere.

    $pageWrap.height($pageWrap.height()); //Da fuck? I don't get this lol. You set the height of the element to its own height?
    baseHeight = $pageWrap.height() - $NavmainContent.height(); //I would just include a pageWrapHeight variable since you use often.

    $("nav").delegate("a", "click", function() { //.delegate is deprecated since 1.7, use .on() instead: $("nav").on("click", "a", callback(){});
        _link = $(this).attr("href");
        history.pushState(null, null, _link);
        loadContent(_link);
        return false; //Here you can just e.preventDefault(); instead. Don't forget to pass the "e" for event into the callback.
    });

    function loadContent(href){

        $mainContent
            .find("#guts")
            .fadeOut(1000, function() {
                $mainContent.hide().load(href + " #guts", function() {
                    $mainContent.fadeIn(1000);
                });
            });

        $NavmainContent
            .find('#inner-cn')
            .find("#project-pagetools,#project-tools,#cp,#currentSection")
            .animate({
                'width': '0'
            },800);

            //The method ".load()" calls the method ".ajax()", passing in the stuff you put there.
            //Why not save a few function calls and just use the .ajax() method directly?

            //Instead of using this timeout, you should check out ajax a little more.
            //You'll find that it has a nice little thing called Deffered already built into the ajax method.
            //Also jQuery has a queue which you can manipulate the order of stuff that happens etc., animation in particular.
        setTimeout(function(){
            $first.load(href + " #currentSection span");
            $second.load(href + " #project-tools li");
            $third.load(href + " #project-pagetools li");
            $fourth.load(href + " #cp span");
        },900);

        //Same thing here.
        //You could do this all with a deffered promise.
        //Also worth checking out is Pub/Sub
        //Basically when set up, you can publish, "Hey I'm done doing this stuff" to another part of your JS that is "subscribed" to that,
        //and continue with your other stuff only when that gets published.
        setTimeout(function(){

            var l = $("#project-tools li").length; //I don't personally like using single character variable names.
            //That can be a nightmare to come back to in the future if you have to make changes or include new functionality.
            //But then again that's just me. Don't shoot yourself over that.

            l = 100 / l ;
            l = l + '%';
            $("#project-tools li").css({
                'width': l
            });

            $NavmainContent
                .find("#project-pagetools,#project-tools")
                .animate({
                    'width': '15%'
                },800);

            $NavmainContent
                .find("#currentSection")
                .animate({
                    'width': '10%'
                },800);

            $NavmainContent
                .find("#cp")
                .animate({
                    'width': '55%'
                },800);
        },1100);
    }
});


Header only c++ singleton pattern implementation

I have a problem with this because

template<class Type>
struct SingleTon
{
    static std::unique_ptr<Type> instance;

This is still a static storage duration object. This means its initialization can happen after a call to Type& get(). So you have to solve this problem first.

So the instance variable needs to be wrapped in a function to make sure initialization of instance is guaranteed. If you are going to do that you may as well not dynamically create the object.

How about this:

template<class Type>
struct SingleTon
{
    private:
        static Type& instance()
        {
            // Use static function scope variable to
            // correctly define lifespan of object.
            static Type instance;
            return instance;
        }
    public:
        static Type& get()
        {
            // Note the constructor of std::once_flag
            // is a constexpr and is thus done at compile time
            // thus it is immune to multithread construction
            // issues as nothing is done at runtime.
            static std::once_flag flag;

            // Make sure all threads apart from one wait
            // until the first call to instance has completed.
            // This guarantees that the object is fully constructed
            // by a single thread.
            std::call_once(flag, [] { instance(); });

            // Now all threads can go get the instance.
            // as it has been constructed.
            return instance();
        }
};

The Elephant in the room (Linker)

Now that we solved this issue. There is a larger elephant in the room to solve. (which is also true for the original code).

Since this is a template class with its whole definition in the header file there will be several versions of this function spread around the code (one in each compilation unit). It becomes the job of the linker to remove all but one copy. If you have a simple application that just uses object files this does not seem to be an issue.

BUT I have come across linkers that were unable to do this when the object were compiled into separate dynamically loaded libraries. Thus in effect your singleton becomes a singleton per runtime library that uses it. This is why you don't find Singelton libraries defined like this with a template class as the harness.


Construct and send an HTTP get request from scratch and print all the received data to the screen

Review

  Is the code pythonic?

The code looks quite clean to me, but it never gets pythonic enough ;)

Some PEP-8 issues:

Don't mix single and double quotes;1
Leave two blank lines between the constants and the first function / class definition.2

Don't use repr(): repr() is meant to get a printable (human readable)
version of an object. In this case, you don't even need to modify the chunks in any way, because they are already of the correct type (str).
You should consider a longer connection timeout. I find a second to be acceptable, but this of course depends on your use case.
There's usually no reason to set socket.SO_REUSEADDR. Regardless, doing so only has an effect if you bind the socket to an address after having done so.
socket.socket.send() does not guarantee that all of what you passed it was sent, instead, it returns the number of bytes sent. You may want to put that part in a loop to assure all data was sent. Or consider socket.socket.sendall().
If you choose to explicitly call socket.socket.shutdown(), make sure you get the argument right. 1 corresponds to socket.SHUT_WR, but you need to prevent reading and writing. Use module constants! socket.SHUT_RDWR is the answer.
I see you added a docstring for receive_all(). That's a nice start, but the docstring is a little generic. A more elaborate description of the arguments and return type and value would be helpful. The same goes for get(). If this were a library, get() would be part of the API, so documenting it should be a priority.

Make sure the documentation is accurate. 'Gather all the data from a request' makes it sound like the socket already made a request and the function merely modifies the response in some way and then returns it. That may give people the false impression that the function has no side effects, but it does!
Let's say you extend this piece of code, and add more helper functions. If one of them raises an exception, the socket is never closed, and you leave the server hanging. Luckily, Python sockets provide context manager capabilities out of the box. That means we can make sure resources are cleaned up:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.settimeout(timeout)
    ...
return data

Turns out this has only been a feature since Python 3.2. One of the many reasons to switch to Python 3. Are you being forced to work with Python 2? A try / finally is probably the closest we can get:

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    ...
finally:
    sock.shutdown(socket.SHUT_RDWR)
    sock.close()

  Does the receive_all function make the code any cleaner or should that functionally be apart of the get function?

It's a good idea to extract functionality and put it in its own function, so yes, it does make the code cleaner. Should you be a big fan of OOP, a custom socket class extending from socket.socket, with a receive_all() method, would be the solution.

My take on it

import socket
import urlparse

CONNECTION_TIMEOUT = 0.30
CHUNK_SIZE = 1024
CRLF = "\r\n\r\n"

socket.setdefaulttimeout(CONNECTION_TIMEOUT)

def receive_all(sock, chunk_size=CHUNK_SIZE):
    """Receive all data from a socket, until EOF is reached.

    Arguments:
      - sock (socket.socket): The socket to receive from. This socket must
        be in a valid state, where it can receive data.
      - chunk_size (int) = 1024: The size of the chunks to receive, in
        bytes. Commonly a multiple of 2 (1024, 2048, 4096). When in doubt,
        do not change.

    Return:
      - (str) All the data received.
    """
    chunks = []
    while True:
        chunk = sock.recv(chunk_size)
        if chunk:
            chunks.append(chunk)
        else:
            break
    return "".join(chunks)

def get(url, timeout=CONNECTION_TIMEOUT, chunk_size=CHUNK_SIZE):
    """Get the HTTP response from a webserver.

    Arguments:
      - url (str): A URL (optionally with a scheme attached).
      - timeout (int / float) = 0.3: The number of seconds to wait before
        timing out. May also be less than 1; a timeout of 0.5 corresponds to
        half a second.
      - chunk_size (int) = 1024: The size of the chunks to receive, in bytes.
        Commonly a multiple of 2 (1024, 2048, 4096). When in doubt, do not
        change.

    Return:
      - (str): The HTTP response.
    """
    url = urlparse.urlparse(url)
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((url.netloc, url.port or 80))
        sock.sendall("GET {0} HTTP/1.0 {1}".format(url.path or "/", CRLF))
        data = receive_all(sock)
    finally:
        sock.shutdown(socket.SHUT_RDWR)
        sock.close()
    return data

if __name__ == "__main__":
    print(get("http://www.google.com/robots.txt", chunk_size=65535))

References

1 PEP-8: String Quotes

2 PEP-8: Blank Lines


Find all combinations of numbers of a set that add up to a given target - avoid for loops

you need the function
public static List<Integer> get_next_highest(List<Integer> combinations, List<Integer> numbers) {
    for(int i=0; i < combinations.size(); i++) {
        if(combinations[i]<numbers.size()-1) {
            combinations[i]++;
            return combinations;
        }
        else combinations[i] = 0;
    }
    return null;
}

here, to simplify I've made combinations have indices (otherwise can't just do combinations[i]++, would need to find the next highest number in numbers)...
for eg. if numbers=[25 30 60 80] and combinations=[0 0 2 1]
this corresponds to the wheel positions [25 25 60 30]
if you pass the value of combinations [3 3 3 3] the function will return a null so make sure to do a check and stop when it does.
This will loop you through all possible combinations if you start at [0 0 0 0]
Specifically in the order [0 0 0 0] [1 0 0 0 ] [2 0 0 0] [3 0 0 0] [0 1 0 0] [1 1 0 0] ... [3 3 3 3]
should be fairly easy to sum up numbers[combinations[i]]
since you specified no for loops here's the recursive version
public static List<Integer> get_next_highest(List<Integer> combinations, List<Integer> numbers, int i=1) {
    if(i==combinations.size()) return null;
    if(combinations[i]<numbers.size()) {
            combinations[i]++;
            return combinations;
    }
    else {
        combinations[i] = 0;
        return get_next_highest(combinations, numbers, i+1);
    }
}

it does the same thing
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestClass {

    public static void main(String[] args) {

        List<List<Integer>> solutions = new ArrayList<>();
        List<Integer> combinations = new ArrayList<Integer>();

        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(3);
        numbers.add(15);
        numbers.add(17);
        numbers.add(35);
        numbers.add(40);
        numbers.add(25);
        numbers.add(5);
        numbers.add(13);

        int target = 75;
        int num_wheels = 3;

        for (int i = 0; i < num_wheels; i++) combinations.add(0);

        for (; combinations != null; combinations=get_next_highest(combinations, numbers)) {
            int sum = 0;
            for(Integer x : combinations) sum += numbers[x];
            if (sum == target) {
                 temp = new ArrayList<>();
                 for(Integer x : combinations) temp.add(numbers[x]);
                 Collections.sort(temp);
                 if (!solutions.contains(temp)) solutions.add(temp);
             }
        }

        for (List<Integer> solution: solutions) {
            System.out.println(solution);
        }

    }
}


What you have implemented is just a change event for the session value, but as you are using a delegate instead of event only one control at a time can register for the event.

Use an event instead of a delegate, and you have a regular change event for session variables.


C++11
Pre C++20 you have to use the type traits based approach, which is essentially what you have done. I dont think this is a bad solution, but probably the way to go if you need to.
C++20 solution (if integral min and max are ok also for C++11 )
In C++ 20 this all becomes easier as it finally allows for class and float non-type template arguments.
template<typename T, T min, T max>
struct RGB {
    T r,g,b;
}

works for T = int, T = char, T = float and so on.
This is the most straightforward solution I could think of that does not need any helper classes. If you only need min and max this is probably good.
If you could live with integer min and max then this also works pre C++20. Simply use int for the min and max template arguments.
The drawback is that in every function that accepts an RGB you need three  template parameters (T, min and max), which could create a lot of noise in the code and make it less readable.
In case you need more than two config parameters
In case min and max is not a sufficient description of the number range, you could add addtional template parameters. However I would not advise this but make the parameters now a class.
In C++20 this is very straightforward again, as you can also use class values as template parameters. This is a bit more clear than the previous type based traits approach (which is also the one you are using).
template <class T>
struct RGBconfig<T> {
   T min, max;
}

template<typename T, RGBconfig<T> config>
struct RGB {
    T r,g,b;
}

use as
constexpr RGBconfig<float> float1020 = {10, 20}

using RGBfloat1020 = RGB<float, float1020>

alternatively one could do
using RGBfloat1020 = RGB<float, RGBconfig<float> {10,20} >

Reduce to one template parameter => include type in RGBconfig
Perhaps it is even possible to reduce it down to one template argument
template <class T>
struct RGBconfig<T> {
   using type = T;
   T min, max;
}

template<auto config>
struct RGB {
    typename decltype(config)::type    r,g,b;
}

then use as
constexpr RGBconfig<float> float1020 = {10, 20};
using RGBfloat1020 = RGB<float1020>;

or
using RGBfloat1020 = RGB<RGBconfig<float> {10,20} >;


Cancel Long Running Query using Cancellation Token AND SqlCommand.Cancel()

It both cancels the Task as well as cancels the query in SQL Server. I can check the status of the query in SQL Server with select * from sys.query_store_runtime_stats to verify that the query was in fact aborted. This is important as I need to make sure it's not just canceled in the app but in the database as well.

Baaaack up a few steps. Your strategy to rely on proof of query completion by looking in a secondary table seems strange to me. If your long-running query were an update, insert etc., you would want to consider

Running your query in a transaction that does not have any kind of auto-commit enabled
Only committing at the end, once you're sure that there will be no desire for cancellation
If cancellation occurs before the commit, then you can be sure that the query was cancelled with no effect on the database

But that's not required, because your long-running query is only a select. Is there a specific reason that you don't trust Cancel to do what it's designed to do? Doing the query_store_runtime_stats check manually as a part of development testing is fine, as long as you aren't baking it in programmatically.


3-level deep if-else tree for constructing a neural network

Here are some ways you can tidy up this code:

Add some comments. It’s quite hard for me to tell whether this code is correct, or whether I‘ve introduced a bug by refactoring, because I don’t know what this code is supposed to do.
Get rid of the unnecessary pass statements. The pass statement literally does nothing except provide a placeholder for unwritten code. If you delete them all, you’ll save a lot of lines and be able to fit more code on screen.
Under the extended branch, the code is almost the same except we remove the first and last character of self.output_tv. If we defer that until the end, we can have one set of branches as follows:

if (self.prm('stagger_schedule') == 'extended'):
    if self.prm('do_backward_pass'):
        self.output_tv = T.concatenate([forward, backward, input_tv], axis=1)
    else:
        self.output_tv = T.concatenate([forward, input_tv], axis=1)

    if self.prm('chop_bilstm'):
        self.output_tv = self.output_tv[1:-1]

22 lines cut down to 7, and this is only 2 levels deep.
The code in the external branch can be similarly consolidated: you do the same effect in both subbranches, but with slightly truncated forward and backward variables. Here’s an alternative version:

elif self.prm('stagger_schedule') == 'external':
    if self.prm('chop_bilstm'):
        forward = forward[1:-1]
        backward = backward[2:]

    if self.prm('do_backward_pass'):
        self.output_tv = T.concatenate([forward, backward, axis=1)
    else:
        self.output_tv = forward

20 lines cut down to 8, and this is only 2 levels deep.

You could consider wrapping each branch into its own method, and calling into that. For example, something like:

if (self.prm('stagger_schedule') == 'extended'):
    self._set_output_tv_extended(forward, backward, input_tv)
elif self.prm('stagger_schedule') == 'external':
    self._set_output_tv_external(forward, backward, input_tv)
elif self.prm('stagger_schedule') == 'extended_multiplicative':
    self._set_output_tv_extended_multiplicative(forward, backward, input_tv)
elif self.prm('stagger_schedule') == 'external_multiplicative':
    self._set_output_tv_external_multiplicative(forward, backward, input_tv)
else:
    raise NotImplementedError()

That saves you an immediate level of nesting and pushes the specific logic of each branch out of this method.


Your getline function looks more like a variant of fgets than getline.
If size == 0, size - 1 == SIZE_MAX, a very large number.
Your getline reads up to size bytes from the stream even though it only places only up to size - 1 into the buffer. It simply drops the last byte silently. You should switch the order of the loop condition:

while (count < size && (c = (char)getc(stream)) != '\n') { ... }

Your getline also writes to memory outside the range defined by its parameters if size is 0, when it writes the terminating null byte.
If getc(stream) == EOF, which is an error condition, your getline function will keep trying to read from the stream, always "reading" EOF, placing (char) EOF (usually '\xff') into the buffer until the end of the buffer is reached.

You can try this by pointing stdin at an empty file.
Use a for loop instead of a while loop, if you're using an iteration counter. It'll be much clearer, what is incremented where and how.

This is how I would rewrite your function considering the above points:

ssize_t fgets(FILE *stream, char *buf, size_t size)
{
  if (size == 0)
    return 0;

  size_t count;
  int c = 0;
  for (count = 0; c != '\n' && count < size - 1; count++)
  {
    c = getc(stream);

    if (c == EOF) {
      if (count == 0)
        return -1;
      break;
    }

    buf[count] = (char) c;
  }

  buf[count] = '\0';
  return (ssize_t) count;
}


Calculate True Positive, False Positive, True Negative and False negative and colourize output

Don't use manual iteration. It's slow and tedious. Use broadcasting instead.

For instance, you can create a true positives mask like this:

true_positive_mask = np.logical_and(prediction > 127, truth_image > 127)

After that, you can use this mask to index the output image:

output_image[true_positive_mask] = green # or whatever color you want

and to compute the total number of true positives:

true_positives = np.sum(true_positive_mask)

You can use the same idea to compute other values or for input binarization.


Handling create, update, and destroy for sync

If this should be executed on all properties of sync in general, i'd go with a for..in loop.

for(var prop in sync){
  if(sync.hasOwnProperty(prop) && typeof sync[prop] !== 'undefined'){
    var i=0, l = sync[prop].length;
    for (i; i < l; i+=1) {
        sync[prop][i].modified.id_partenaire=false;
    };
  }
}

Otherwise, if there are more properties and this should only be applied to these 3, Esailija's answer works better.


Dynamic homepage with PHP - making things too complicated?

Let's go for a step-by-step cleanup.

1) Get rid of repetition by using a variable to store your html code common to the different branches.

2) Remove useless levels of indentation to make things easier to follow.

The inside of the while loop is now :

        $currentRow=$currentRow+1;
        $id = $row["id"];
        $product_name = $row["product_name"];
        $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));
        $link = '

';
        if($currentRow==1 || $currentRow==4) {
            $dynamicListLeft .= $link;
        } else if($currentRow==2 || $currentRow==5) {
            $dynamicListMiddle .= $link;
        } else if($currentRow==3 || $currentRow==6){
            $dynamicListRight .= $link';
        }

(I could move the definition of link out of the loop but I guess in your real situation, the content depends on $row).

3) You can try to store your content in an array instead of using different variables. It removes a bit of logic and makes things easier to update if you want 2 or 4 columns in the future. It also removes some code duplication :

$cols=array('','','');
$nbCol=count($cols);
$currentRow=0;
while($row=mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_name = $row["product_name"];
        $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));
        $link = '

';
        $cols[$currentRow%$nbCol] .= $link;
        $currentRow=$currentRow+1;
}
for ($col as $i => $content)
{
   $dynamicList .= '
' . $content . '
';
}

4) So far, the comments were about the php code and not the HTML output it produces. My last comment is more of a question but wouldn't there be a way to have your HTML defined in such a way that you don't need such a complicated logic. Basically, at the moment, the whole point is that your HTML code contains reference to your item in this order : 1,4,2,5,3,6. Things would be easier if you could have them in the natural order (1,2,3,4,5,6) in your HTML code and then update your HTML to display them in such a such a way.
My HTML skills are way too limited to answer this question...


A function that checks for duplicate elements in an array

function has_duplicates(arr) {

In JS, function names are usually in camelCase. So this should be hasDuplicates.

for (var key in arr) {

Don't use for-in with arrays. for-in loops will run through properties, including prototype properties. Use a regular for loop with counters. A forEach would also work, but you can't bail out in the middle of the array.

So far, iirc, a loop and hash is favorable in this scenario since it's just O(n) and you can bail out in the middle of the operation.

Another way to do it is the following. The concept is that when a value appears twice, indexOf and lastIndexOf will not be the same, thus adding the entry to the array created by filter.

function hasDuplicates(arr){
  return !!arr.filter(fuction(value){
    return arr.indexOf(value) !== arr.lastIndexOf(value);
  }).length;
}

Another way to do it is by using ES6's Set. The concept is that sets only hold unique values. When you try to add a duplicate, it won't be added to the set. If there is a mismatch in the array length and set size, you jumped over a duplicate somewhere, thus revealing the existence of the duplicate.

function hasDuplicates(arr){
  var set = new Set();
  arr.forEach(function(value){ set.add(value); });
  return set.size !== arr.length;
}

Going with @PeterCordes's suggestion, you can use Set and check on each iteration the size mismatch. We can assume false until a mismatch happens.

function hasDuplicates(arr){
  var set = new Set();
  for(var i = 0; i < arr.length; i++){
    set.add(arr[i]);
    if(set.size !== i + 1) return true;
  }
  return false;
}


I haven't tested this due to time constraints, and lack of knowledge of the data, but from my understanding of the problem, this should work.

I have taken the linq join queries, two for the insert, two for the delete and created two IEnumerable.Where clauses, one for insert, one for delete.  The two sets of criteria are combined in an OR statement within the .Where statement.

The one thing I wasn't sure on is if the original list needed to be returned.  That wasn't clear in the original code.  If it does need to be returned, that's an easy change to implement.

EDIT: Changed to do work per Kyles suggestion in comments.

public IEnumerable<AssetBlob> Synchronize(IEnumerable<AssetBlob> assets, string id)
{
    var assetsList = assets.ToList();

    //Get list of devices already checked in lineitemsmap
    IEnumerable<LineItemsMap> lineItems = auditRepo.GetLineItemsMap(id).DeviceResults;

    var items =
        assetsList.Where(
            existingAsset =>
                // ExisingItems that need updating
                // Any returns true if any of the items in a list meet the criteria
                lineItems.Any(lineItem => lineItem.BlobId == existingAsset.Id && existingAsset.Imported > lineItem.Created) ||
                // New items that need inserting.
                // All returns true if all of the items in a list meet the criteria
                // therefore All == !Any
                lineItems.All(lineItem => lineItem.BlobId == existingAsset.Id)).ToList();

    var deleted =
        lineItems.Where(lineItem =>
                        assetsList.Any(existingAsset => existingAsset.Imported > lineItem.Created) ||
                        assetsList.All(existingAsset => existingAsset.Id != lineItem.BlobId)).ToList();

    // If there is a foreach in RemoveLineItemMaps you can probably remove this check.
    // Just cleans up the code a little, and the foreach will take care of this check.
    if (deleted.Any())
    {
        auditRepo.RemoveLineItemMaps(deleted);
    }

    return items;
}


Is this a correct way to write a convenience constructor?

Personally I would prefer the second option because it makes it easier/less weird for subclasses to use and override alloc-init.

As a side node I would point to some reasons to reconsider user properties in your constructors.

Should I refer to self.property in the init method with ARC?
Friday Q&A 2009-11-27: Using Accessors in Init and Dealloc
Don’t Message self in Objective-C init (or dealloc)