Count number of even and odd numbers from input

Do not use system("pause"). Read
this
Stop using using namespace std. Read
this
You have an unneccessary amount of variables. You don't need to have
a variable to hold the remainder for each number.
Just have a function that determines whether the input number is odd
or even. I think you might have to rethink the logic of your
program.

//Your function should do the following:
//MAX is a const int. In your case it is 5
    for(int i=0; i<MAX; i++){
        if(numbers[i] % 2 == 0)
            evenNumbers++;
        else
            oddNumbers++;

        sum += numbers[i];
    }

Here is how I would have done it:

#include <iostream>
#include <vector>
#include <iterator>

using std::cin;
using std::cout;
using std::endl;
using std::vector;

int main(){

    int value = 0;
    int oddNumbers(0), evenNumbers(0), sum(0);

    std::istream_iterator<int> begin(cin);
    std::istream_iterator<int> end;

    //while(cin >> value)
    //  numbers.push_back(value);

    //Instead of a while loop, I use input stream iterators.
    vector<int> numbers;
    std::back_insert_iterator<std::vector<int>> iter (numbers);

    std::copy(begin,end,iter);

    //Range based for-loop (C++11)
    for(auto i : numbers){
        if(i % 2 == 0){
            evenNumbers++;
        }else {
            oddNumbers++;
        }

        sum += i;

    }

    cout << "# of odd numbers: " << oddNumbers << "\n";
    cout << "# of even numbers: " << evenNumbers << "\n";
    cout << "Sum of all numbers: " << sum << endl;

}


Wrapping postback functions to call custom code at execution

Interesting question,

I think the biggest thing is that callee is going the way of the Dodo bird.

JsHint does not like your code because you are using for( .. in .. ) without filtering properties, which is fine since you create the object with Object Notation, and I assume you did not modify the Object prototype. You are also creating functions/closures in a loop. Are you sure you need those closures there?

Other than well commented, and easy to follow, something that I would not mind using in one of my projects.


Sort a list of pairs representing an acyclic, partial automorphism

Code style

Use constants for variables that do not change. Eg const sortedArray = [];

Don't include the type in the name, Eg const sortedArray = []; can be Eg const sorted = [];

The default parameter in this case seams inappropriate as it is likely that "JFK" is not an origin in all calls to this function. If no origin is given one could assume that the first item in trips contains the origin.  function sortByLinked(trips, origin = trips[0].from) { which will throw an error if trips is empty so the function should not be called with an empty trips array if you don't pass the from parameter.
However in this example best to leave the default as undefined if not passed as that will return an empty array which is more fitting the input parameters.

The name sort is inappropriate as in JS it implies that the array be sorted in place, that all items be sorted (may not be possible).

You have declared i two times. As a var you should put the declaration at the top of the function and not in the for loop.

Rather than use Array.filter you can use Array.find. It will find the first instance.

Using for...of rather than for(;;) reduces the code complexity.

No point continuing the search inside the for loops when you have found a match. Use the break token to stop a loop early

Put a space between if and (

Don't forget to add the ; where appropriate. It is missing from the call sortByLinked(trips)

You call the origin origin and from this can get confusing. Keep the naming unambiguous. As the trip items use from then that would be the better name for the second input argument.

Using the above points to modify your code we get
function tripFrom(trips, from) {
  const sorted = [];
  const first = trips.find(trip => trip.from === from);
  sorted.push(first);

  for (const trip of trips) {
    if (first.to === trip.from) {
      sorted.push(trip);
      break;
    }
  }
  for (const trip of trips) {
    if (sorted[sorted.length - 1].to === trip.from) {
      sorted.push(trips);
      break;
    }
  }
  return sorted;
}

sortByLinked(trips, "JFK");

This is still not a good solution. Its not at all DRY (don't repeat yourself) and is hard coded to a single use case.
Improving the function.
It can all be done within a single loop and work for any length array.
To create the function we must add some constraints on the array trips and what to do when we encounter any problems.

That the array trips contains objects that each have the property from and to that are correctly formatted static strings. The resulting array is erroneous or indeterminate if not so.
That the array does not contain circular trips shorter than the array length.
That a complete trip length is no longer than the array, or when a matching trip.to can not be found. The returned array can be 0 to trips.length in size.
Locations are case sensitive.
If there is more than one matching trip.from it is assumed that the first match in trips is the correct one. (It would be interesting to extract the longest possible trip from? or the shortest trip that returns to the origin?)

Example
function tripFrom(trips, from) {
    const result = [];
    while (result.length < trips.length) {
        const trip = trips.find(trip => trip.from === from);
        if (!trip) { break }
        from = trip.to;
        result.push(trip);
    }
    return result;
}
tripFrom(trips, "JFK");

Or if it is known that the trip is the same length as the input array.
function tripFrom(trips, from) {
    const res = [];
    while (res.length < trips.length) {
        from = (res[res.length] = trips.find(trip => trip.from === from)).to;
    }
    return res;
}
tripFrom(trips, "JFK");

It is unclear if you want the array sorted in place. If that is a requirement then the above version can be modified to do that by simply copying the results array res to the trips array. You can empty an array by setting its length to zero. The spread ... operator in this case spreads the array items over the functions arguments trips.push(...res) thus pushing all the items to the array.
function tripFrom(trips, from) {
    const res = [];
    while (res.length < trips.length) {
        from = (res[res.length] = trips.find(trip => trip.from === from)).to;
    }
    trips.length = 0;
    trips.push(...res);
    return trips;
}
tripFrom(trips, "JFK");


Determine whether a magazine contains the words needed for a ransom note

You're making it enormously complicated. This is a job for Counter:
from collections import Counter

def checkMagazine(magazine, note):
    print('No' if Counter(note) - Counter(magazine) else 'Yes')


class Encap{

I find all your class names confusing.  You seem to be describing the code, not what it does.  Maybe something like

class Greeter {

would be more understandable.

    private String name;
    public void setName(String newValue){
        name = "Hello, "+newValue+"!";
    }

The name variable isn't a name, but a greeting.  Why not call it that?

Also, newValue isn't very descriptive.  That actually is a name, so

    private String greeting;

    public void setGreeting(String name) {
        greeting = "Hello, " + name + "!";
    }

Now I can easily see that setGreeting takes a name as an input.

Some people might argue that setGreeting should only set the greeting, not determine what it is.  You could either create a constructor to handle this with an immutable variable, or you could change the name to changeGreeting.  Or you can ignore that convention, but you may get negative feedback.

abstract class Abstraction {

This could be

abstract class Sequence {

    private int[] sequence;

    Sequence(int length) {
        sequence = new int[length];
    }

    int getLength() {
        return sequence.length;
    }

    abstract void generate();
}

This seems a clearer set of names.

You also may want to look into how to use constructors

    int fibCount, flag=0, y;

It's generally preferable to have one variable per declaration, particularly if you are initializing as well.

    int fibCount;
    int flag = 0;
    int y;

Now you can easily see that only flag is initialized.

Why declare y?  You never use it.

Why make fibCount and flag object fields?  You only use them in one method.  They could be local variables instead.

    String names[] = new String [] {"Anna","Joe","Carl"};

This doesn't seem to have anything to do with the rest of this.  Why declare that variable in this class?

    Scanner x = new Scanner(System.in);

Why name your Scanner x?  Is it a secret that it is a scanner?  More common names would be scan or scanner.  You could also name it something like input or stdin.

I'd move the input and output out of the class and into main.  Then you can make scanner a local variable as well.

class abs2 extends Abstraction{

Again, this would be clearer as

class FibonacciSequence extends Sequence {

Now I know what I expect to find here.

        for (String name : abs.names) {
            if(abs.inputName.equals(name)){
                encap.setName(abs.inputName);
                System.out.println(""+encap.getName());
                abs.flag = 1;
            }
        }
        if(abs.flag!=1){
            System.out.println("Name doesn't exist..");
        }
        else{
            abs.abscompute();
        }

This would be easier to read as a method call:

        if (validName(inputName)) {
            greeting.setGreeting(inputName);
            sequence.generate();
        }
        else {
            System.out.println("Name doesn't exist..");
        }

Then instead of

                abs.flag = 1;
            }
        }

You could say

                return true;
            }
        }

        return false;

There are other places with similar feedback, but perhaps you should take a try at it yourself.


php Laravel - given a certain argument, call different function

I don't personally see a problem with the way its currently structured as there aren't that many options, but you could do it a couple of other ways;

Option 1

Array function name mapping (hacky name I just came up with), you could do the following;

$functionMap = [
    "daily" => "addDay",
    "weekly" => "addWeek",
    "monthly" => "addMonth",
    "yearly" => "addYear"
];

if(!isset($functionMap[$pattern_type])){
    throw new \Exception("Can't find patern type $pattern_type", 1);
}

$startDate->$functionMap[$pattern_type]();

This might be seen as a sin by the PHP community but it works none the less

Option 2

You could use a switch which probably isn't a sin by the community.

switch ($pattern_type) {
    case "daily":
        // Do the daily task
        break;
    case "weekly":
        // Do the weekly task
        break;
    case "monthly":
        // Do the monthly task
        break;
    case "yearly":
        // Do the yearly task
        break;
    default:
        throw new \Exception("Can't find pattern type $pattern_type", 1);
}

Conclusion

I would add some exception / error that can be picked up if a non matched  pattern_type is passed.

I would also convert the "magic strings" E.G "daily" to constants in case you need to re-use, change or update them in the future!

In terms of line count;

your way 10 lines of code
option 1  11 lines of code
option 2  15 lines of code

The switch & if statements may have some advantages when doing code analysis aswel where the expected required input values can be picked up.


If you extract the logic that builds the output string to its own method buildFizzBuzz,
you'll get something testable:

public static String buildFizzBuzz(int fizz, int buzz, int limit) {
    StringBuilder sb = new StringBuilder();
    // ...
    return sb.toString();
}

public static void printFizzBuzz(String line) {
    int fizz = Integer.parseInt(line.split(" ")[0]);
    int buzz = Integer.parseInt(line.split(" ")[1]);
    int limit = Integer.parseInt(line.split(" ")[2]);

    System.out.println(buildFizzBuzz(fizz, buzz, limit));
}

And you can add some unit tests, for example:

@Test
public void test_3_5_20() {
    assertEquals("1 2 F 4 B F 7 8 F B 11 F 13 14 FB 16 17 F 19 B", buildFizzBuzz(3, 5, 20));
}

@Test
public void test_2_7_15() {
    assertEquals("1 F 3 F 5 F B F 9 F 11 F 13 FB 15", buildFizzBuzz(2, 7, 15));
}

Having these unit test, which pass at the moment,
now we can refactor a bit safely, knowing that if anything breaks, the tests will break.

It's not great to have a check on the limit twice in the loop,
in the loop condition and also in the loop body.
It would be better to eliminate the condition from the body,
always appending ' ', and cutting off the space at the end.

It's not great to have a check on i % fizz twice.
It would be better to use a boolean to track if fizz or buzz were already appended.

Putting these two points together, the implementation becomes:

public static String buildFizzBuzz(int fizz, int buzz, int limit) {
    StringBuilder sb = new StringBuilder();

    for (int i = 1; i <= limit; i++) {
        boolean shouldAppendNum = true;
        if (i % fizz == 0) {
            sb.append("F");
            shouldAppendNum = false;
        }
        if (i % buzz == 0) {
            sb.append("B");
            shouldAppendNum = false;
        }
        if (shouldAppendNum) {
            sb.append(i);
        }
        sb.append(" ");
    }
    sb.setLength(sb.length() - 1);
    return sb.toString();
}


Checking whether a string is a valid number

NumberUtils.isNumber from Apache Commons Lang does that.


Option Explicit

Option explicit. Always.

Strong typing

VBA facilitates strong typing. This should be used because it stops VBA guessing at types which improves performance and reduces the chance of coding errors. Especially as some types/objects have default values that are not well documented!

This is a function, so what does it return? At the moment, it returns a Variant which might be OK, but your code does not reflect this requirement.

Public Function discrete(r1 As Range, r2 As Range) As String

If you want it to be Variant, then be explicit and state that!

Also, another gotcha is the way variables are declared. The following lines are not doing what you think they are doing:

Dim arr1, arr2 As Variant
Dim min, max As Double

In these lines, both the first variables are not declared and thus they default to Variant. Again, if you want a variable to be a Variant, then be explicit (like you tried to be in the first line above). What you really wanted was:

Dim arr1 As Variant, arr2 As Variant
Dim min As Double, max As Double

By the way, kudos for declaring variables near where you are using them.

Proper qualification

Always put proper qualification on your objects. Excel uses defaults for things that are not properly qualified - the active sheets and cells may not be what you want! Especially in a UDF and you could have multiple workbooks open!

Range(r2(1), r2(1).End(xlDown))

should be

wb.ws.Range(r2(1), r2(1).End(xlDown)) ' wb and ws is something you define here - more notes below.

Default value for discrete

You only set the value for discrete in a conditional (If) statement in a loop. What if it never fires? What would you like the user to see?

A simple option is to set a default value at the beginning - the most obvious is an error message. For this to work, the UDF should return a variant:

Public Function discrete(r1 As Range, r2 As Range) As Variamt
    discrete = CVErr(xlErrValue) '<-- pick an error value to suit yourself

Now that we have set that up - what are some other ways this can fail?

user picks ranges that re not one column wide?
user picks two ranges that are a different size?

Now you can test for this early and then exit the function - the default value will be an error and the user will have an indicator of this.

Altering the parameters

This is bad:

Function discrete(r1 As Range, r2 As Range)
    […]
    Set r1 = Range(r1(1), r1(1).End(xlDown))

A big no-no. You should always consider the parameters on a UDF as immutable. If you want to reset the ranges, then use a temporary variable within the Function scope (e.g. Dim tempRange1 as Range).

However, you are double-guessing the user. What if they did not want to go to the end of the page? What if they had other stuff under the table?

By doing this manipulation, you are increasing the chances that the value arrays will be mismatched. arr1(found,1) may no longer have an equivalent arr2(found,1)!

Working with arrays

Yes, always practice working with arrays where you can. Even replace the Application.Sum call. You can never tell when your user is going to set up a 1000-value discrete array!

Some suggestions

Use only a single range in the UDF call (Public Function
discrete(twoColTable As Range) As Variant. This reduces the
opportunity for user error. You array will be two columns
arr(found,1) will correspond with arr(found,2)
Check your user input immediately for size and values to make sure
you are getting what you think you should. If column count does not
equal 2, or your second column is not ascending numbers then exit
with an error.
Traverse the array from beginning until you find a value that is
greater then your n. The value you want will be the one before you hit that value (i.e. go back one array index). Alternatively, traverse the array from the end until you find a value that is not greater than your n. This way, you do not need max or min.


Order and visibility tracking algorithm (e.g. scope visibility)

I came up with a cleaner looking solution:

bool isVisibleTo(Node * accessor) {
    Node * node = accessor;
    while (node) {
        if (node == this) return true;
        if (node->_parent) {
            uint i = node->_parent->_children.indexOf(node);
            while (i) if (node->_parent->_children.at(--i) == this) return true;
        } node = node->_parent;
    } return false;
}

But it will be inevitably slower in a scenario with lots of children. While the first "messy" solution uses the relative tree indices and only traverses the object tree from child to parent, this cleaner solution goes through all children nodes before going to the parent. I will have to do some profiling with a bigger tree to verify if that is the case.

EDIT: I take it back, despite what appeared as an obvious performance penalty this method is actually about 4 times faster consistently. I tested with a whooping 10 million nodes


Advice 1

PEP 8 has some (minor) complains: the names of functions and their arguments should be funky_functions instead of funkyFunctions, and funky_argument instead of funkyArgument.

Advice 2

In Python, you can say

def funky1():
    for i in range(10):
        yield i

def funky2():
    arr = []
    for i in range(10):
        arr.append(i)
    return arr

So you may come up with:

def intersection(array_one, array_two):
    array_one_index = 0
    array_two_index = 0
    size_of_array_one = len(array_one)
    size_of_array_two = len(array_two)
    while array_one_index < size_of_array_one and array_two_index < size_of_array_two:
        if array_one[array_one_index] < array_two[array_two_index]:
            array_one_index += 1
        elif array_one[array_one_index] > array_two[array_two_index]:
            array_two_index += 1
        else:
            yield array_one[array_one_index]
            array_one_index += 1
            array_two_index += 1

Advice 3

Your union does not omit duplicates. You can deal with them in a following manner:

def union(array_one, array_two):
    array_one_index = 0
    array_two_index = 0
    size_of_array_one = len(array_one)
    size_of_array_two = len(array_two)
    while array_one_index < size_of_array_one and array_two_index < size_of_array_two:
        if array_one_index > 0 and array_one[array_one_index - 1] == array_one[array_one_index]:
            array_one_index += 1
            continue
        if array_two_index > 0 and array_two[array_two_index - 1] == array_two[array_two_index]:
            array_two_index += 1
            continue
        if array_one[array_one_index] < array_two[array_two_index]:
            yield array_one[array_one_index]
            array_one_index += 1
        elif array_one[array_one_index] > array_two[array_two_index]:
            yield array_two[array_two_index]
            array_two_index += 1
        else:
            yield array_one[array_one_index]
            array_one_index += 1
            array_two_index += 1

    while array_two_index < size_of_array_two:
        if array_two_index > 0 and array_two[array_two_index - 1] == array_two[array_two_index]:
            array_two_index += 1
            continue
        yield array_two[array_two_index]
        array_two_index += 1

    while array_one_index < size_of_array_one:
        if array_one_index > 0 and array_one[array_one_index - 1] == array_one[array_one_index]:
            array_one_index += 1
            continue
        yield array_one[array_one_index]
        array_one_index += 1

Advice 4

Note also that you don't need

if arrayOneIndex == sizeOfArrayOne:

in union; only one of the "leftover" loop will iterate at least once.

Hope that helps.


How random is this password-generating algorithm?

Copy&pasting code multiple times does not make it more secure. If we clean up your mutate_seed method, we'd end up with this:

def mutate_seed(self):
    for x in range(self.seed):
        number_or_letter = r.randint(0, 1)
        if number_or_letter:
            self.mutated_seed.append(r.randint(0, 9))
        else:
            lower_or_higher = r.randint(0, 1)
            if lower_or_higher:
                self.mutated_seed.append(r.choice(self.alphabet_lower))
            else:
                self.mutated_seed.append(r.choice(self.alphabet_upper))

Quick Notes on the changes:

I don't request random values which I don't end up using. Throwing away values from the random number generator does not make those numbers that you use more secure.
I don't use single-letter variable names or abbreviations like con or mut that obscure the meaning.
random.choice is so simple and nice – consider using it.
This solution features far less duplicate code. Did you calculate r.ranint(1, 6) as an analogy for six-sided dice?

Now the code is cleaned up so that we can do some more substantial reviewing.

There is no use in separating between numbers, lowercase letters, and uppercase letters. They all should be in the same character pool so that each character has the same probability of occuring at each position in the password. With your current methods, a digit is much more likely to occur than any given letter, simply because there are less digits than letters.

So we should have something like

lower = [chr(x) for x in range(ord('a'), ord('z') + 1)] # I can't be bothered to type
upper = [chr(x) for x in range(ord('A'), ord('Z') + 1)] #   out all letters manually
digits = [str(x) for x in range(0, 9)]
character_pool = lower + upper + digits
...
password = [random.choice(character_pool) for _ in range(0, length)]

The interface of your class is horrible. We have to create an instance, then call the mutate_seed method, then access an instance variable, then must join that array to a string until we can finally display it. Consider packing all of this functionality into a single, convenient function instead:

def make_password(length, *collections_of_characters):
    # join all character collections into a single set
    characters = set()
    for collection in collections_of_characters:
        characters.update(str(c) for c in collection)
    characters = list(characters)

    password = [random.choice(characters) for _ in range(0, length)]
    return "".join(password)

Then using this is as simple as

password = make_password(10,
                         "0123456789",
                         "abcdefghijklmnopqrstuvwxyz",
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print(password)

If you need a certain set of characters more often, put those into a list:

alphanumeric_chars = ["0123456789",
                      "abcdefghijklmnopqrstuvwxyz",
                      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
password = make_password(10, *alphanumeric_chars)
print(password)

or create a wrapper function:

def make_alphanumeric_password(length):
    return make_password(length,
                         "0123456789",
                         "abcdefghijklmnopqrstuvwxyz",
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print(make_alphanumeric_password(10))

Not all abstractions map cleanly to classes.

Your code uses the word “seed” quite often. A seed is the initial state of a random number generator. When set to the same seed each time, the random number generator will produce the same sequence of numbers. In your class, “seed” seems to mean “length” instead. Use clear, obvious names for your variables rather than using technical lingo if you aren't sure what it means – although a quick trip to Wikipedia would have cleared that up.

You issue a few Windows-only system commands such as cls. Unless this is central to the working of your application, don't manipulate the console, such as setting the color or clearing the screen. Users can do this themselves if they want to. Removing these commands also makes your code usable on other operating systems like OS X or Linux.

You are using the random library as a random number generator. The numbers produced by this library aren't really random, they are just pseudo-random. This is usually not an issue as long as a really random seed is chosen, but because the number sequence is derived algorithmically, it should not be used for really really important stuff. Most passwords are only important and not really really important, so this should be fine ;-) but it's good to remember that real randomness is something different.

That is one aspect where the security of your program is not optimal, but good enough. Writing the password to a file is however absolutely irresponsible. When the password is only displayed on the command line, we can assume that it will only be immediately visible until the screen is cleared or other content has caused it to scroll out of sight. It will be held in memory for a while longer, but at least a rebooting of the system will remove any trace of this.
A plain text file however is much more persistent (it stays there after a reboot). It is also much easier for other users to access that password. Don't store secrets at all, or if you have to store them, secure them properly.

You should consider writing your Python code so that it is usable both as a module, and a script. For this, we first write all definitions that should be usable as a module, and at the end add an if __name__ == '__main__' section, which will only be executed if the file was invoked as a script. Now we can both do:

# in some other program:
import make_password as mp
random_hex = mp.make_password(10, "0123456789abcdef")

or

python make_password.py

to use the functionality of your code. Designing for code reuse is a generally good idea.


Using the Python call stack to remember your state is very convenient and often results in shorter code, but it has a disadvantage:

>>> collatz(5**38)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr24195.py", line 3, in collatz
    d[n] = collatz(n * 3 + 1 if n & 1 else n/2) + 1
  [... many lines omitted ...]
  File "cr24195.py", line 3, in collatz
    d[n] = collatz(n * 3 + 1 if n & 1 else n/2) + 1
RuntimeError: maximum recursion depth exceeded

You need to remember all the numbers you've visited along the way to your cache hit somehow. In your recursive implementation you remember them on the call stack. In an iterative implementation one would have to remember this stack of numbers in a list, perhaps like this:

def collatz2(n, d = {1: 1}):
    """Return one more than the number of steps that it takes to reach 1
    starting from `n` by following the Collatz procedure.

    """
    stack = []
    while n not in d:
        stack.append(n)
        n = n * 3 + 1 if n & 1 else n // 2
    c = d[n]
    while stack:
        c += 1
        d[stack.pop()] = c
    return c

This is a bit verbose, and it's slower than your recursive version:

>>> from timeit import timeit
>>> timeit(lambda:map(collatz, xrange(1, 10**6)), number=1)
2.7360708713531494
>>> timeit(lambda:map(collatz2, xrange(1, 10**6)), number=1)
3.7696099281311035

But it's more robust:

>>> collatz2(5**38)
1002


Determine if two arrays are a rotated version of each other

Bug

I ran your code with the following arrays and your function thought that the two arrays were rotated versions of each other but they were not:

public static void main(String [] args)
{
    int [] a = { 0, 1, 2, 3, 0 };
    int [] b = { 0, 1, 1, 2, 3 };
    System.out.println(isRotatedVersion(a, b));
}

Output:

  true

Achieving a correct \$O(n)\$ solution

Determining if an array is a rotated version of another array is equivalent to searching for the first array within the second array concatenated with itself.  For example, given:

a = { 0, 0, 1, 2, 0 }
b = { 0, 0, 0, 1, 2 }

You can search for pattern a within this array, which is b doubled:

{ 0, 0, 0, 1, 2, 0, 0, 0, 1, 2 }

To do this in \$O(n)\$ time, you just need to implement a linear time string searching algorithm.  I would suggest using the Knuth Morris Pratt algorithm, which is easy to understand and implement.


T-SQL query Choose name of clients, concluded more than one loan agreement in 2010

I believe your code will work based on what you provided.  However, I would recommend a couple of changes.

T1 does not need to be part of the result set as you do not retrieve anything from it.  Since it is only used to filter, I've moved it to an exists clause.
Avoid expressions on the data field when comparing to a static or known value.  It takes a bit more typing, but can provide performance benefits in your code.

SELECT  c.cl_full_name AS "ФИО Клиента",
        d2.dl_code AS "Номер договора",
        CAST(d2.dl_valutation_date AS DATE) AS "Дата выдачи"
FROM  deal AS d2
  INNER JOIN client AS c ON c.cl_id = d2.dl_client_id
WHERE EXISTS ( SELECT 1
       FROM deal AS d
       WHERE d.dl_valutation_date >= '20100101'
         AND d.dl_valutation_date < '20110101'
         AND c.cl_id = d.dl_client_id
       GROUP BY d.dl_client_id
       HAVING COUNT(*) > 1)
ORDER BY c.cl_full_name,
 d2.dl_valutation_date ;

UPDATE to respond to comment

Leveraging good performance practices builds a foundation that makes good performance possible.  If there is another part of your query that has a greater impact to performance, the first recommendation may or may not affect performance by itself.  However, it can help to reveal other performance bottlenecks.


You don't need to write ...ifNecessary if you just describe the property you want to have in the return value, and then you just know that after calling it, it has that property. You want the return amount to be clamped so it is less than or equal to the maximum amount. It doesn't matter that it might not change it, but it DOES matter to the business logic that it has been applied (i.e. checked). The actual name isn't that important in this case because I think I'd drop it anyway, as per below.
First, I just rewrote your code to use a member variable instead of being static, and without all the intermediate variables:
public class TaxReturn {

    private static final float MAXIMUM_RETURN_AMOUNT= 1000f;

    private final float income;

    public TaxReturn(float income) {
        this.income = income;
    }

    public float returnAmount() {
        return clampReturnAmount(base() + addition());
    }

    private float base() {
        return income * 0.5f; // More complex calculation here
    }

    private float addition() {
        return base() * 0.3f; // More complex calculation here
    }

    private static float clampReturnAmount(float returnAmount) {
        return returnAmount > MAXIMUM_RETURN_AMOUNT ? MAXIMUM_RETURN_AMOUNT
                : returnAmount;
    }

}

But this clampReturnAmount function is just Math.min by a different name. Using Math.min to enforce a limit is common enough to be well understood why we're calling it, especially if we're naming the second argument something like argument MAXIMUM_RETURN_AMOUNT. So just:
public class TaxReturn {

    private static final float MAXIMUM_RETURN_AMOUNT = 1000f;

    private final float income;

    public TaxReturn(float income) {
        this.income = income;
    }

    public float returnAmount() {
        return Math.min(base() + addition(), MAXIMUM_RETURN_AMOUNT);
    }

    private float base() {
        return income * 0.5f; // More complex calculation here
    }

    private float addition() {
        return base() * 0.3f; // More complex calculation here
    }

}


Verify a subnet mask for validity in Python

As recommended in PEP 8, the official style guide, function names should be lower_case_with_underscores unless you have a good reason for making an exception.

Functions like this are perfect places to write doctests, to explain how the function should behave while providing unit tests at the same time.

The IsIPv4Address() function is easy to implement.  I would take advantage of the all() function with a generator expression and a double-ended inequality.

def is_ipv4_address(dotquad):
    """
    Validate an IPv4 address in dotted-quad notation.

    >>> is_ipv4_address("1.2.3.4")
    True
    >>> is_ipv4_address("127.0.0.1/8")
    False
    >>> is_ipv4_address("1.2.3.4.5")
    False
    >>> is_ipv4_address("1.2.3")
    False
    >>> is_ipv4_address("1.2.3.256")
    False
    >>> is_ipv4_address("1.2.3.-4")
    False
    >>> is_ipv4_address("fe80::")
    False
    """
    octets = dotquad.split(".")
    return len(octets) == 4 and \
           all(o.isdigit() and 0 <= int(o) < 256 for o in octets)

The netmask verifier is trickier to write well.  You have chosen to use bin() to stringify the 32-bit number.  I'd avoid using strings for something that can be done arithmetically, since string manipulation is relatively inefficient.

Furthermore, I'd suggest that instead of writing just a validation function, you may as well write a function to tell you the length of the netmask, since it's nearly the same amount of work, but you can get more useful information that way.

def ipv4_mask_len(dotquad):
    """
    Finds the number of bits set in the netmask.

    >>> ipv4_mask_len("255.255.255.0")
    24
    >>> ipv4_mask_len("0.0.0.0")
    0
    >>> ipv4_mask_len("255.255.255.255")
    32
    >>> ipv4_mask_len("127.0.0.0")
    Traceback (most recent call last):
      ...
    ValueError: Invalid netmask: 127.0.0.0
    """
    if not is_ipv4_address(dotquad):
        raise ValueError("Invalid netmask: {0}".format(dotquad))
    a, b, c, d = (int(octet) for octet in dotquad.split("."))
    mask = a << 24 | b << 16 | c << 8 | d

    if mask == 0:
        return 0

    # Count the number of consecutive 0 bits at the right.
    # https://wiki.python.org/moin/BitManipulation#lowestSet.28.29
    m = mask & -mask
    right0bits = -1
    while m:
        m >>= 1
        right0bits += 1

    # Verify that all the bits to the left are 1's
    if mask | ((1 << right0bits) - 1) != 0xffffffff:
        raise ValueError("Invalid netmask: {0}".format(dotquad))
    return 32 - right0bits


I see you already solved your own questions from before your latest edit. Just two very minor things that can be improved: you can omit repeating the type name Init in two places:
template <std::ranges::input_range R, typename Init = std::ranges::range_value_t<R>>
constexpr auto accumulate(R&& rng, Init init = {})
{
    return std::reduce(std::ranges::begin(rng), std::ranges::end(rng), std::move(init));
}

And you don't need to use std::views::common in main().


Your code runs into a lot of problems because it chooses a weird value for Nil, and because it fails to check for that value. What is the correct result for head(lst())? "N", Nil, or a type error?

Because "Nil" === "Nil" holds (value type), but [] === [] does not (reference type), I suggest you use the empty array to represent Nil (this is also closer to Lisp semantics). The advantage of this is that your cons can then contain any value in the tail position – the string "Nil" was previously forbidden.

Another good possibility would be to use a false value, this would even remove the need for isEmpty! I will assume var Nil = undefined for the rest of this answer, even though now undefined and Nil cannot be distinguished.

As already mentioned, you fail to check for Nil, therefore your code can be considered incorrect. E.g. head could be:

function head(xs) {
  if (!xs) return Nil;
  return xs[0];
}

or even

function head(xs) {
  if (!xs || !(xs instanceof Array)) {
    throw "Expected pair";
  }
  return xs[0];
}

Other functions that build on these primitives are in turn correct, although the new value for Nil simplifies the code a bit, e.g.

function length(xs) {
    if (!xs) return 0;
    return 1 + length(tail(xs));
}

Notice that I removed the unnecessary else, but this is a matter of personal style.

You may want to specify what exactly the output of take(3, Nil) and similar functions should be. It seems you are assuming that all indices will always be inside the correct bounds. Better be explicit about that. In this case, valid interpretations of var n = 3; take(n, Nil) would be to:

Use the n as an upper limit, and return the empty list/Nil.
Use n as a strict limit, and fill up the surplus cons with Nil in the head.
Throw an error that the index is out of bounds.

The first solution is most DWIM, it would seem to me.

Your piece function does not document if the from and to bounds are inclusive or exclusive. Because you will drop(from, xs), the from index is not included in the output. The to is exclusive as well. This counterintuitive behaviour is not made clear in the documentation!

Your removeOne is even weirder by using one-based indexing instead of zero-based indexing, like piece does.

Interestingly, you don't have an indexing function, e.g. at(1, lst(0, 1, 2)) === 1.

Summary

Your code looks fine, but you haven't carefully considered (or tested) the actual behaviour of your functions. When writing complex code, a few well-chosen test cases can help detect errors early.


String compression using repeated character counts

Your solution here is wrong, it produces incorrect results when it compresses chars that are in two different places in the string:

For the input: aaaaabbbbbcdrfaaaaaaccccc your program produces:

a11b5c6d1r1f1

when it should produce:

a5b5c1d1r1f1a6c5

Because the a and c repeat in two different places, you include them all in the first count.

Since this is homework, writing out the full solution would be counter-productive, but, if you have:

StringBuilder sb = new StringBuilder();

and two variables to contain the previous char and the previous char count, you could just go through each character in the string, if it's the same as the previous char, you increment the count. If it's different, you add the previous char and it's count to the StringBuilder, and reset the previous and count to 1.

Then, when your loop is done, if the StringBuilder is smaller than the input, return the StringBuilder version.

This type of compression is called 'run length encoding' by the way.


Moving MP3 files from one directory to another using regex

Constants like '/home/rich/Downloads/' could be made into variables, for example:

src_dir = '/home/rich/Downloads/'
dest_dir = '/home/rich/Music/Songs/'

This would make it clear what they mean, and would avoid duplication if you need to use a constant more than once.
There are three problem in the regular expression.

First, the parentheses are unnecessary — they capture whatever they match for future use, but there's no future use here.

Second, the dot has a special meaning in regular expressions — it matches any character. If you want to match a literal dot, then you need to escape it.

Third, the regular expression is not anchored and that means it can match anywhere in the string. For example, it will match the filename "not.actually.an.mp3.wav".

The regular expression should be r"\.mp3$".
There's no need for a regular expression at all, you could just call os.path.splitext to get the extension:

for f in files:
    _, ext = os.path.splitext(f)
    if ext == '.mp3':
        shutil.move(f, dest_dir)

In fact there's no need to do that, because you could use glob.glob instead:

for f in glob.glob(os.path.join(src_dir, '*.mp3')):
    shutil.move(f, dest_dir)

It seems like overkill to use Python for this, because it would be a one-liner in shell:

mv ~/Downloads/*.mp3 ~/Music/Songs/


for SCRIPT in $DIR/post-receive.d/*

You might want to limit that to only *.sh pattern, just for clarity.

Personally I'm a fan of the one-line-style, but that's personal preference:

for ITEM in SET; do
if [ CONDITION ]; then

And yes, input from stdin is at the moment ignored completely by your script. Reading from stdin can be done via the read command, like this.

#!/bin/sh

# This whill be our input variable
input=""

# Read the first line without adding
# a new line to the start.
read input

# Start reading from stdin
while read line; do
    # Concate the input into our variable
    input=$input"\n"$line
done

# Echo it...what else?
echo $input

After doing that you can pipe the variable into the scripts like this:

echo $INPUT | "$SCRIPT"

One word of warning: I'm not sure if this is BASH only or cross-shell compatible.


Improving performance while sorting a JavaScript Object

Disclaimer: I don't know anything about javascript

If you have a construct like

if (condition){
   return someValue;
} else {
   return someOtherValue;
}

the else can be omited, because if the first condition is true the else is never reached.

So your code could be refactored to

filtered.sort(function (a, b) {
  if (!b.sortdist) { return -1; }
  if (!a.sortdist || a.sortdist > b.sortdist) { return 1; }
  return -1;
});

which doesn't improve the performance, but I don't see anything to make your code faster.


Create a calendar application to check the scheduling conflicts of meetings

A couple of things that would be good to point out:

It appears that your code only checks the clash between the start and end time. If the start time is always bigger than the end time, in theory it should never clash.

for(int i=0;i<start.length;i++){
    int startMeeting = parser(start[i]);
    int endMeeting = parser(end[i]);
    boolean result = timeClashChecker(startMeeting,endMeeting);
    if(result == false){ //clash check
        return false;
    }
}

might be replaced with:

for(int i=0;i<start.length;i++){
    int startMeeting = parser(start[i]);
    int endMeeting = parser(end[i]);
    for(int e = 0; e < end.length; e++){
        if(e == i) continue;
        int meetingEnd = parser(end[e]);
        if(meetingEnd > startMeeting && meetingEnd < endMeeting) return true;
    }

    for(int s = 0; s < start.length; s++){
        if(s == i) continue;
        int meetingStart = parser(start[s]);
        if(meetingStart > startMeeting && meetingStart < endMeeting) return true;
    }

}

This way the end of each meeting is checked with each starting time. If there is a clash with any of them, it should detect it. It also checks if each starting time of another is also between a meeting.

If you make the change above, your timeClashChecker method is unnecessary.
Some of the method names are not entirely helpful.parser could become parseTime, and scheduler could be changed to doesClash, especially seeing it doesn't do any of the scheduling itself.


Short Ruby program that opens a random video file from a directory

I'll try to help you on how you could improve your code here.
Keep in mind that I have no idea what is your current level in programming in general. You state that you started learning ruby, but you don't tell us about other languages.

Random number generator

This method is fine, but what you want is to avoid having to comment every line. Comments are usually needed when the code is not clear. We'll try to make its meaning more obvious.

Let's try first to find better names here. It can seem like a little detail, but it is pretty important if you want to be able to read it in the future.

Names are very hard to find, you want names that give the meaning of what you are doing, and not how you are doing it.

For instance first_num is not as good as season, or season_number, because it gives less information.

This is true for functions names too. The result of your random_number_generator is a string that you will use as a file name. Based on the function's name, you would expect to get an object that generates numbers.

Let's rename it to random_file_name for instance.

This would make us write this function

def random_file_name
  season = rand(2..9)
  episode = rand(1..25)
  "#{two_chars(season)}#{two_chars(episode)}"
end

Did I mention it would be good to extract the logic of turning a number into a 2 characters string?

Let's create this two_chars function

def two_chars(number)
  number.to_s.rjust(2, '0')
end

Calling two_chars(1) will take 1, convert it to a string with to_s and fill the string with 0s until the string's size is 2. This way we won't need this test second_num < 10.

Episode Picker

In this function you are looping through all files in your folder; there is a more efficient way of doing it.

Plus you are calling random_num_generator several times in the same loop, and it will generate different filenames. This is probably not what you want: it could not find any file, or find several different files.

What you want is something looking like

def pick_episode
  file = file_with_name(random_file_name)
  puts "You are watching Season: #{filename[0..1]} Episode: #{filename[2..3]}!"

  system %{open "/GitHub/videos/#{file}"}
end

I changed the function's name to pick_episode since that what it does.
What we do is find a random file, display that we are watching it, and open it.

Since you ask what is in this file_with_name function, here is how you could write it

def file_with_name(filename)
  files = Dir["/GitHub/videos/#{filename}.{mkv,mp4,avi}"]
  raise "No file named #{filename}" if files.empty?
  raise "Several files: #{files}" if files.size > 1

  files.first
end

Instead of looping through all files in the folder, we try to find a file that starts with the right name, and that has an extension amongst mkv, mp4 and avi.

Then if no file is found, we raise an error.
If several files share the same prefix, we raise an error.

In the case we found exactly one file, we return its name.

If you find good names for your variables and functions, and you try to break your code in smaller pieces (functions), you will be able to look at it in 2 months and understand it clearly.

You could even go further and use some classes to have be even more explicit with the season and the episode numbers: for now, we compute them, turn them into a string, and extract them from a string later on when displaying it. But I think it would be a bit out of scope here. Tell me if you want me to go further this path.

Well, that is it. Asking questions here is a good way to improve your coding skills, the rest is just practice!


Indentation

Please please please please automatically indent your code. You're doing all readers (and yourself) a disservice by not following indentation conventions and enforcing them through your IDE.

Abstraction

This code can be much cleaner by simply extracting responsibilities into methods, especially those that encapsulate setup. Let's get the code into a final state as follows:

public String sendEmail(String[] to, String from, String subject, String msg) throws MessagingException {
    String status = "099";
    final Session session = buildMailSession(from, password);
    final MimeMessage message = buildMailMessage(session, from, to, subject, msg);
    final Transport transport;
    try {
        transport = session.getTransport();
        transport.connect();
        Transport.send(message);
        status = "000";
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } finally {
        if (transport != null) {
            transport.close();
        }
    }
    return status;
}

This is signifcantly easier to comprehend and understand. It even makes clear, what status is. You should very much consider extracting those into named constants.

This is a good moment to also talk about documentation.

When extracting methods, that is a huge opportunity to include some "free" documentation through the method name. In case that is not sufficient, one should employ *javadoc" to clarify what the method does exactly:

/**
 * Sends an email to all the recipients in <tt>to</tt>
 *
 * @return {@link #SUCCESS_STATUS} if sending was successful,
 *     {@link FAIL_STATUS} otherwise
 */
public String sendEmail(..);

Signature changes

Instead of returning magic Strings, it would be much cleaner to return an enum value like so:

public SendResult sendEmail(...) {
    SendResult status = SendResult.SEND_FAIL;
    // ...
         status = SendResult.SEND_SUCCESS;
    // ...
    return status;
}

Now if we use the fact that I introduced a finally block, which is executed regardless of how the corresponding try-block is left we can simplify this to:

public SendResult sendEmail(...) {
    // ...
        Transport.send(message);
        return SendResult.SEND_SUCCESS;
    } catch (..) {
    // ..
    return SendResult.SEND_FAIL;
}

In addition to that you should consider changing the signature to the following:

public SendResult sendEmail(String msg, String subject, String from, String... to)

This makes use of "varargs" to allow invoking it as follows:

emailService.sendEmail(message, subject, from, "recipient@example.com", "recipient2@example.com");

Whether that's more useful... How would I know?


Finding if sequential numbers for total exists

Your code incorrectly returns false if I give it [23, 5, 4, 7, 2, 11, 1] and a target value of 20. The answer should still be 7 + 2 + 11, but it doesn't find it.

That's because the reduce operation always runs to the end of the array, so it is unable to pick out a matching sub-sequence in the middle of a larger sequence. It can only find it, if it's at the end. I.e. it does this:

5 + 4 + 7 + 2 + 11 + 1 => 30
4 + 7 + 2 + 11 + 1     => 25
7 + 2 + 11 + 1         => 21
2 + 11 + 1             => 13 # could just give up here, really
11 + 1                 => 12
1                      => 1

=> false

However 2 + 7 + 11 would've been a valid answer.

Your example input just happens to be crafted so that you get correct results; the matching sub-sequences are always anchored to the end of an array. They're never in the middle of it.

Furthermore, by chunking using i < max you remove values that are equal to the target sum. I.e. trying [1, 3, 7, 5, 23, 2] with a target of 7 will fail, even though there is a sequence - a sequence of 1 value - that matches.

This is however easily fixed by changing the block to use i <= max.

Overall, I'd propose something like this:

def sub_sequence_equal_to?(total, values)
  sequences = values.chunk { |n| n <= total || nil }.map(&:last)

  sequences.each do |sequence|
    sequence.reduce(0) do |sum, n|
      sum += n
      sum -= sequence.shift while sum > total
      return true if sum == total
      sum
    end
  end

  false
end

It'll gradually build a sum, but also subtract the earliest values if said sum has grown too large.

So given [23, 5, 4, 7, 2, 11, 1] and a target value of 20 it'll do something like:

5                  => 5
5 + 4              => 9
5 + 4 + 7          => 16
5 + 4 + 7 + 2      => 18
5 + 4 + 7 + 2 + 11 => 29
    4 + 7 + 2 + 11 => 24
        7 + 2 + 11 => 20

=> true

It's not quite \$O(n)\$, and perhaps there's a smarter way (it'd be nice to get rid of that separate chunk step for instance). Still, it's more efficient (and works better) than the original.


Fetching objects and adding a calculated field in Doctrine 2

If you wanna just show them, just use

count($blog->getComments()) or blog.comments|length in template, or something similar.


Best way to refactor this loop of animations with delay?

Anything that you're using as a constant should be marked as such.

double const delayInSeconds = 0.2f;

Now then, we know in Objective-C, we have NSArray and its mutable cousin, and they can only hold objects.  But also remember, Objective-C is a superset of C.  We can use a C-Style array.

int const POPTIME_COUNT = 8;

dispatch_time_t poptime[POPTIME_COUNT];

And then fill this an array with a loop...

for (int i = 0; i < POPTIME_COUNT; ++i) {
    double totalDelay = delayInSeconds + ((i + 1) * 0.1 * NSEC_PER_SEC)
    poptime[i] = dispatch_time(DISPATCH_TIME_NOW, totalDelay);
}

Firing off the animations is done just as easily in a loop:

for (int i = 0; i < NUM_ANIMATIONS; ++i) {
    dispatch_after(poptime[i], dispatch_get_main_queue()), ^(void){
        [self animateWithCoreAnimaGenerallyWithIndex:i];
    }];
}

Where NUM_ANIMATIONS is the number of animations you need to fire off (it's different in each branch).


Extending react hook useState for use in event handlers

I must admit that my experience with typescript and react.js is quite limited so my review will be limited to basic syntax points. This code seems straight-forward. It makes good use of arrow functions and destruction assignment. There are just a couple suggestions I will make below.

if (typeof e?.stopPropagation === 'function') e.stopPropagation();

It is best to include brackets around the block, even if it is all on one line:

if (typeof e?.stopPropagation === 'function') { e.stopPropagation(); }

Some believe such blocks should never be on one line. If you are going to do it on one line, you could use short-circuiting:

typeof e?.stopPropagation === 'function' && e.stopPropagation();

This block can be simplified somewhat:

if (typeof value === 'boolean') {
    // @ts-ignore
    return [value, setter, booleanAgg(value, setter, makeSetter)]
} else if (typeof value === 'string') {
    // @ts-ignore
    return [value, setter, stringAgg(value, setter)];
} else if (typeof value === 'number') {
    // @ts-ignore
    return [value, setter, numberAgg(value, setter)];
} else {
    throw new Error('Only boolean, string and number is supported');
}

The else keywords can be avoided because preceding blocks have return statements.'

if (typeof value === 'boolean') {
    // @ts-ignore
    return [value, setter, booleanAgg(value, setter, makeSetter)]
}
if (typeof value === 'string') {
    // @ts-ignore
    return [value, setter, stringAgg(value, setter)];
}
if (typeof value === 'number') {
    // @ts-ignore
    return [value, setter, numberAgg(value, setter)];
}
throw new Error('Only boolean, string and number is supported');


Bug

if self.return_date.isoweekday() is 1 or 7:

Is always true because 7 is true, adding parenthesis will help you understand:

 if  ( self.return_date.isoweekday() is 1 ) or 7:

To get proper behaviour use:

 if self.return_date.isoweekday() in (1, 7):

Repetition

self.return_date = self.return_date + timedelta(2)
return self.return_date - timedelta(2)

And:

self.return_date = self.return_date + timedelta(1)
return self.return_date - timedelta(2)

Use a if/ternary for the first timedelta arguments and flatten these lines.

No class

You have a single function with a single argument, simplify and avoid a class. (You can re-use your function without a class, just put it in a separate module and import it.)


When describing quicksort partitioning, your v is typically called the "pivot".  The code would be clearer if you named the variable according to that convention.

You always choose a[lo] as the pivot.  However, that produces pathological performance when the input array is already sorted.

I would prefer to see

while(a[i] < v):
      i += 1
      if (i == hi): break

… written as

while i < hi and a[i] < pivot:
    i += 1

Array index bounds usually work better when specified as inclusive-exclusive ranges, such that sort(a, lo, hi) means "sort a where lo ≤ index < hi".  This is a common convention — you can see it in Python's range() and slicings.  Also, Java's Arrays.sort(a, fromIndex, toIndex) works with inclusive-exclusive ranges.

Some nice properties of inclusive-exclusive ranges are:

hi - lo gives you the number of elements in the range.
When creating a range for the entire array a, hi is just len(a).  You save a "-1".
When splitting [lo, hi) into two consecutive ranges, it becomes [lo, mid) and [mid, hi).  You save a "-1".
In Python, you can conveniently write for i in range(lo, hi) for the most common type of iteration. (Admittedly, iterating backwards is uglier, but it's less common.)


First item I see is:

private static object _lockDependenciesManagement;

...should be:

private static readonly object _lockDependenciesManagement;

I don't see any reason this should/would change.

With the possibility of having Retrievers overwritten while being used, you should return a copy of the collection instead:

//    fields that could be altered while in use if made public
static IEnumerable<IEntryRetriever> _retrievers { get; private set; }
static IEnumerable<IEntryDepositor> _depositors { get; private set; }

public static IEnumerable<IEntryRetriever> Retrievers
{
    get
    {
        //    return copy of _retrievers
        lock (_lockDependenciesManagement)
        { return _retrievers.ToList(); }
    }
}

Your consumers can now manipulate work from it's own copy of the _retrievers collection. Handle _depositors in the same manner ...I think these steps will make the collections safer to use.


Simple python script to shorten URLs in specified text files

Overall, LGTM.

Suggestions:

try ... except would look better than os.path.isfile(). Even if isfile returns True, you still may encounter an exception trying to open it (say, insufficient privileges), so you should be ready to handle exceptions anyway. Besides, using isfile may lead to a race (not likely in this code), if a file is removed right between testing and opening it.
The script spends most of the time in shorten_url, which in turn mostly waits for network IO. I'd recommend to give each invocation a thread.
Original files are destroyed. I'd prefer to keep originals intact, or at least provide an option for that. Also an ability to read urls from standard input is usually desirable.


Conditionally replacing a placeholder in a form

There is not "you choose this" rule in this context. But to be able to decide, you should take few elements in consideration:

Are you working on an existing code (which is not yours)? If so, it would be better to follow the philosophy of the existing code, or ask the project leader in case of doubt.
If this is a new project, then you could opt for the third option which was first proposed on PEP 0308 because, in general, typing less makes you less error prone.


Print routes on the stairway when only 1 or 2 steps are possible

In general, recursion is a complicated technique. It is often hard to understand the state of the system at any point in time because you have to add a dimension to your thinking.

I consider it to be bad practice to have a recursive process where the recursion is unnecessarily split across multiple methods. In your case, you have a 2-method split in your recursion.

calcAllRoutes calls processSteps
   processSteps calls calcAllRoutes
      calcAllRoutes calls processSteps
         processSteps calls calcAllRoutes
            ...

Sometimes this is not avoidable... but, in this case, it is unnecessary. By splitting the logic in to two methods, it becomes harder to 'grok' the recursion.

Additionally, your previous questions where you have had similar sorts of work, you have always 'defaulted' to using java.util.* collections instead of using simpler mechanisms like arrays of primitives. Arrays are much faster, and smaller, and tend to lead to better structured code. This is because the array is essentially a stack, and popping the stack is as easy as changing it's size.... you do not have to do as much manipulation of the stack head.

Finally, this problem is one which should have a more general solution. You have hard-coded this solution to only work with 1-step and 2-step 'strides'. The problem is actually simpler if you make the stride options a general thing....

Consider this alternative code... it:

has a single recursive method.
the recursive method has the standard layout:

check recursion-ending-conditions
initiate further recursion

it can use any number of positive-valued strides to get to the destination
it is just a single recursive method.
it uses an array of primitive ints to accumulate the current combination

So, this code is, in my opinion, preferable:

public class Stairway {

    /**
     * Calculate all possible ways to ascend `steps` stairs, using the different-sized strides provided.
     * @param strides the different number of steps that can be taken.
     * @param steps the number of steps to ascend.
     * @return a list of all step combinations.
     */
    public static final List<int[]> stairClimbingRoutes(int[] strides, int steps) {

        // create the combination stack.
        // Longest possible combination is 1 step each time.
        int[] combination = new int[steps];
        int comblength = 0;

        List<int[]> results = new ArrayList<>();

        recurseRoute(steps, strides, combination, comblength, results);
        return results;
    }

    private static void recurseRoute(final int remaining, final int[] strides,
            final int[] combination, final int comblength, final List<int[]> results) {
        if (remaining < 0) {
            // this combination takes us too far.
            return;
        }
        if (remaining == 0) {
            // this combination is just right.
            results.add(Arrays.copyOf(combination, comblength));
            return;
        }
        // need to go further.
        for (int s : strides) {
            combination[comblength] = s;
            recurseRoute(remaining - s, strides, combination, comblength + 1, results);
        }

    }

    public static void main(String[] args) {

        for (int[] combination : stairClimbingRoutes(new int[] {1, 2}, 10)) {
            int check = 0;
            for (int s : combination) {
                check += s;
            }
            System.out.println("Actual " + check + " using " + Arrays.toString(combination));
        }

    }

}


The main thing I would say here is that you have 2 nigh identical functions apart from the balance being passed to them. Instead of checking_account and savings_account being different functions, make a single account_interaction function that takes an argument which you can then pass to the choden function.

def account_interaction(account):
    print "You have $%i available" % (account)
    print """
    What would you like to do:
    [W]ithdrawl
    [D]eposit
    [T]ransfer funds
    """
    choice = raw_input("> ")
    if choice == "W":
        withdraw_funds(account)
    elif choice == "D":
        deposit_funds(account)
    elif choice == "T":
        transfer_funds(account)
    else:
        print "Invalid input.."

Ideally account would be a class, or at least a dictionary that contains multiple relevant values (ie. type, amount, account holder), either of these makes it easier to pass them around functions like this.


Overall

Resolve all standard library entities with std::. Never put using namespace declarations in a header file, where most of his belongs.

Class Edge

You use initializer lists in some places (Graph), not in others. Be consistent. I advise using them always where they're needed, and not at all where they're not.  Also, there is no need for a destructor in this class unless you're expecting polymorphism and need virtual-dtor for a vtable. Finally, make your getters const

class Edge {
private:
  int vertex1;
  int vertex2;
  int cost;
  int time;

public:
  Edge(int v1, int v2, int cost, int time)
    : vertex1(v1), vertex2(v2), cost(cost), time(time)
  {
  }

  int getVertex1() const { return vertex1; }
  // etc...
};

Class Graph

There are outright compilation bugs in this class. There is no such entity as Edges, yet you have a vector of them. Further, properly named it should be edges are a vector of Edge. Also, the initializer list in this class is pointless, as is the destructor and, as-written, the constructor. Finally, you may (or may not) want to pass your incoming edge as a const-ref (lots of opinions on that, I know).

class Graph {
private:
  vector<Edge> edges; //edges in graph

public:
  int getTotalCost();
  int getTotalTime();
  void addEdge(const Edge& e);

  Graph getMST();   // get Minimum Spanning Tree
};

Class Vertex

As previously mentioned, use initializer lists and full std:: namespace resolution. Like Graph, this uses Edges as a typename, but no such type exists. Again, we use const qualifiers on all getters, here also returning the name by const-ref rather than value-copy. Finally, no chance of ever setting visited to true unless you provide a setter for it, nor accessing or modifying the edges vector without providing some means to do so.

class Vertex
{
private:
    std::string name;
    int number;
    bool visited;
    std::vector<Edge> connEdges;  // vector of all edges connected to this vertex

public:
    Vertex(const std::string& name, int number)
        : name(name), number(number), visited(false)
    {
    }

    // edge accessors
    void addEdge(const Edge& edge) { connEdges.push_back(edge); }
    const std::vector<Edge>& getEdges() const { return edges; }

    // properties
    const std::string& getName() const { return name; }
    int getNum() const { return number; }
    bool wasVisited() const { return visited; }
    void setVisited(bool val = true) { visited = val; }

    Graph getShortestPath();
};

main()

This function is simply loaded with errors. Among them:

edge  is not a pointer type, so that assignment won't event compile.
p_edge is derferenced though it is never initialized, so that will likely outright-fault due to undefined behavior
ifile is never opened before use, so nothing will be read there.
it leaks memory, but only because of an error previously mentioned above. Were that coded correctly this would be a non-issue.


Authentication system - AngularJS & Ionic Framework

First thing that strikes me is the inconsistency of naming.
Why using different styles 'apiAddress', 'EVENTS' for constants?

Your .service does not need to return this, see here.

I would use something like signData instead of signForm as Form has another meaning.

As a personal preference I like to write my .factory as

.factory('AuthService', function (...) {

   // any initialization and private method go here
     ...

   return {

      // public methods
      login: function (...) {...},
         ...

   }
});

This keeps my code DRYer and I don't need to worry misprinting authService or forgetting to return it (your factory does need a return!)

You don't handle errors (but you knew this already ;-)

Your .controller has way too many dependencies and responsibilities. The best practice is to keep your controllers "thin" with the sole responsibility to glue your data with its scope. Changing routes (states) looks like one job too much. Say you want to keep another sing-up form elsewhere with its own controller - will you really want to copy over all the logic?

This is good for prototyping but is generally to be avoided in production:

console.log("Failed");

Also this way of using promise is not recommended - notice that your second (error) function will not catch any errors inside the first (success) function. A better way is:

AuthService.signup(signForm)
  .then(function (data) {

     // handle your success here

  })
  .error(function (error) {

     // handle your error here

  });

Now you will catch all errors.

Finally, I find your Session too small and AuthService too big with too many dependencies. It plays a role of a "Manager" that has many responsibilities. You can't always avoid it but you want to keep Manager's jobs at high level and as simple as possible. Imagine a stupid manager that knows nothing other than how to give basic commands :)

.factory('AuthService', function (...) {
   return {
      login: function (credentials) {
         Server
           .login(credentials)
           .then(function (user) {

              // we return the result promise that can be picked by next function
              return UserService.create(user);
           })
           .error(function (error) {
             ...
           })
      }
   }
})


Word ladder implemented using stack and queue

Some small improvements:

Do not use std::endl because it always forces a flush in addition to a new line, which can degrade output performance.
Prefer operator[] over at[] wherever possible. For example, in oneDiff you use dictWord.at(i) instead of dictWord[i]. The reason this is detrimental is that at() performs a bounds check (and possibly throws an exception if the bounds are violated) while operator[] does not. Since i only ever takes values smaller than stackWord.size(), you do not need at().
Prefer std::size_t for iteration variables. int may be to small to hold all indices for very large strings.
Don't use ... < something.somemethod() in a loop head, because something.somemethod() may be executed every iteration. If you know that it value does not change throughout, store its value before the loop into a variable.
oneDiff can be optimized. Since you only return whether or not the difference between characters is one or less, you can return false as soon as you have found more than one mismatch.
Although you do not give the definition of dictionary, it can be assumed that it is of type std::list<std::string> because of the iterator you are using. I would recommend replacing it with a std::vector if you are not doing a lot of insertion and deletion at random positions, because std::vector profits from cache coherency.


Don't do using namespace std;.
Use an appropriate type for the range. The number of test-cases can never be negative, so we should use an unsigned integer. It looks like the player capabilities are similarly unsigned.
for (int i = 1; i <= testCases; i++) In C++, it's more usual to use != for the end condition, and use the pre-increment operator (since we don't a temporary value). It's usually safer to use a zero-based index, and simply add one for printing if we need to convert to one-based: for (int i = 0; i != testCases; ++i).
int attack {}, defense {}, physical {};. Declare variables (especially POD variables) as close to the point of use as possible to minimize their scope and avoid reusing them for multiple things. These should be declared in each of the innermost loops.
reserve is not a constant value, so this is not valid C++: int reservePlayers [reserve];, even if some compilers allow it. We should use a std::vector instead. (This particular array also appears to be unused!)
for (int i = 0; i < totalOriginalPlayer; i++) The loop condition variable shadows the i variable of the outer loop. This is likely to cause confusion. It would be better to pick a meaningful name for the loop variables, e.g. outfielderIndex.
It might be neater to separate the logic of the program from reading the input. Then we could reuse the input reading code for both sets of players.

std::vector<std::uint32_t> outfielders = ReadPlayerData(numOutfielders);
std::vector<std::uint32_t> reserves = ReadPlayerData(numReserves);
std::uint32_t total = // ...
std::uint32_t worstOutfielder = // ...
std::uint32_t bestReserve = // ...

// ... do output

We can use the standard library to do the necessary math. Specifically std::accumulate, std::min_element and std::max_element.


JavaScript function to categorize data by their "styles" attribute, and store the key-"unicode" pair

First off, some code review items;

Don't skip on semicolons
You are not changing a number of variables, consider const over let in those cases
The names of your styles match the names of your variables, you could use this

Given that, I would consider something like this

function processMetadata(metadata) {
    let out = {regular: {}, solid: {}, brands: {}};
    for (const icon in metadata) {
        const styles = metadata[icon].styles;
        const codePoint = metadata[icon].unicode;
        for(const style in out){
            if (styles.includes(style)) {
                out[style][icon] = codePoint;
            }
        }
    }
    return out;
}


Access to a pimpl's members from another pimpl

As you said, if you need something in a pimpl class from another class, then something is wrong. If you can't abstract away the differences, then you can't hide the differences and shouldn't use this idiom.

Don't you think it would be simpler to put Play() in CSound? Each version (Linux/Windows) would have its own pimpl and there would be no need to try to find an abstraction or to try to access private data. Otherwise it gets a bit messy, since your Linux/Windows implementations of CSoundInstances will need to accept only the correct implementation: I don't know how easy it is to do this at compile time.


Return sizeof a struct containing members ordered like given template parameters

Looks reasonable to me.

I don't understand why you keep sum.first and sum.second as separate values; IIUC, sum.first is "the size of the struct so far, minus its last element", and sum.second is "the size of the last element". It seems like you could just keep "the size of the struct so far" as a single value. That is, isn't your code equivalent to the following?

template<typename... T>
constexpr std::size_t sizeof_struct()
{
    using meta_t = std::pair<std::size_t, std::size_t>;
    auto alignto = [](auto x, auto a) { return (x + a - 1) / a * a; };
    size_t sum{0};
    std::size_t max_align{0};
    std::array<meta_t, sizeof...(T)> arr{{ {alignof(T), sizeof(T)}... }};
    for (auto&& it : arr) {
        sum = alignto(sum, it.first) + it.second;
        max_align = std::max(it.first, max_align);
    }
    return sum ? alignto(sum, max_align) : 1;
}

Or if not, why not?

In the above version I also "corrected" your brace placement on the std::array initializer; I think it's more idiomatic (and in this case specifically, more readable) to bundle together the outer pair of braces {{ {x}... }} as opposed to staggering them out as { {{x}...} }.

Also for (x : y) is more idiomatic than for (x: y), and you had a trailing redundant semicolon on the for-loop's body.

If you're looking for template type parameters that break the above code, try sizeof_struct<char&>. Your code returns 1, but obviously it should return sizeof(char*). You can solve that easily, though.

And of course you have no guarantee that the compiler's struct layout algorithm is equivalent to the one you've written. It almost certainly is (modulo base classes, vptrs, bitfields, and most importantly the fact that the compiler can reorder public and private data members)... but technically you have no portable way to know that.


Count the number of unique elements in a sorted array

Just a few minor suggestions:

If you invert the condition on the length, then you can reduce the level of nesting, which is slightly easier to read
An array will never have a negative length. It's pure paranoia to check for array.length <= 0, I suggest to replace with array.length == 0
The spacing is not perfect. Use an IDE to reformat the code
This maybe a matter of taste, but I would rename countUnique to simply count, and the method from numUnique to countUnique

Putting it together:

public static int countUnique(int[] array) {
    if (array.length == 0) {
        return 0;
    }
    int count = 1;
    for (int i = 0; i < array.length - 1; i++) {
        if (array[i] != array[i + 1]) {
            count++;
        }
    }
    return count;
}


Sorting function that also works with containers having only forward iterators

The loop

for(size_t i = 0; i < n/2; ++i)
    ++mid;

may and should be replaced with std::advance(mid, n/2)

To answer your question on better ways of finding the midpoint, I don't think it is worthy: it complicates the logic, while the amount of calculation remains the same.
A condition if(*first1 < *first2) breaks the stability of merge sort. This way, if two elements compared equal, the one from the second list would output first. Very standard mistake. To fix, either compare for <=, or change the order:

if (*first2 < *first1) {
    *out = *first2;
    ++first2;
} else {
    *out = *first1;
    ++first1;


Cross-platform MySQL database backup using mysqldump

Is the code cross-OS-friendly?

Sure it is working, but IMHO one should never use exec() especially in costumer software with user supplied data to it. I'am gueesing you have to logged in to a admin account but still it's a huge security risk. But if you insist on using it, you should at a minimum check that the user supplied path is a vaild path and do a md5 hash of mysqldump.

I would just use a php native solution like mysqldump-php instead of using exec().

Is it a balanced way of doing this?

You have solved the problem in a simple way, so thats good. The only thing i can see as a hurdle is if you have costumers that isn't that tech savvy. it could be hard for them to find the correct path and/or knowing if mysqldump is installed.

could you flesh out this question further, i dont understand what you are asking? (cant comment yet)


Extension method splitting string on each capital letter

With regex it's virtually a one-liner:

var words =
    Regex.Matches("SmallFireBall", @"([A-Z][a-z]+)")
    .Cast<Match>()
    .Select(m => m.Value);

var withSpaces = string.Join(" ", words);

Regex.Matches - searches an input string for all occurrences of a regular expression and returns all the matches. MSDN
[A-Z][a-z]+ - matches strings that begin with a capital letter and are followed by one or more lowercase letters

Output:

  Small Fire Ball

Let's review your code anyway and optimize it a little bit. Even without regex it still can be very short.

Use a StringBuilder for building string dynamically
You can use a foreach loop for strings too

public static string SplitOnCapitalLetters2(this string inputString)
{
    var result = new StringBuilder();

    foreach (var ch in inputString)
    {
        if (char.IsUpper(ch) && result.Length > 0)
        {
            result.Append(' ');
        }
        result.Append(ch);
    }
    return result.ToString();
}

The 3rd alternative would be only LINQ:

public static string SplitOnCapitalLetters3(this string inputString)
{
    // starts with an empty string and accumulates the new string into 'result'
    // 'next' is the next character
    return inputString.Aggregate(string.Empty, (result, next) =>
    {
        if (char.IsUpper(next) && result.Length > 0)
        {
            result += ' ';
        }
        return result + next;
    });
}


Why is your parameter variantValue a string? Why not an IEnumerable<string> or an ICollection<string> or something like that?

Why is variants an array? If it had been an ICollection<string> it would have had a Count property that was far less costly than .Count(). Don't use the (extension) method .Count(), use the Length property. Also: why is it called variants when it really contains names?

Why do you do this inside that loop: variants[i] = variants[i].Trim();? Why not do this when you do variantValue.Split(',').Where(x => !String.IsNullOrEmpty(x)).ToArray();

The whole logic seems really contrived to me: storing the contents of a table in a dictionary, just to check whether you need to add a value to the DB and to retrieve the IDs? Why not make it much more simple:

Query the DB for the entries where the name corresponds with the ones you've received as a parameter (a WHERE IN query).
Remove the results from the list of names.
Loop through the filtered names, create a Variant for each and only execute db.SaveChanges(); after you've added ALL items.
After you've executed db.SaveChanges(); all those newly created variants will have an ID which you can retrieve.

By the way, don't do ContainsKey if you need the value associated with said key, instead use TryGetValue.

I suppose that you need variantIds for that //Some not relevant to question code here, and that bothers me a bit. GetVariantId for instance does far more than the method name says it does, and thus I suspect UpdateVariants contains more logic that really shouldn't be there according to the Single Responsibility Principle.


Nowadays we have great tools at our disposal, one of them is The Closure Compiler from Google, which is a tool for making JavaScript download and run faster.  It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

So, the web version of Closure Compiler gave me the following recommendations for your snippet:

Example,
this.incumbent = Number.POSITIVE_INFINITY;
this.maxCost = Number.POSITIVE_INFINITY;
becomes this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;
Other obvious speed enhancements that can be automated with minification:

Use parameters as a variable instead of another var:
var minSize = this.pricesBB(0, 0, 0, 0);
Reuse var's when they are longer in user in a function instead of declaring new ones
Shorten variable names (parsing speed issue)
var price = this.prices [i];
var size = price.size; becomes var price = this.prices[i], g = price.size;

The full result of the Closure Compiler for your piece Javascript:

function Prices(c) {
  this.prices = c;
  this.prices.sort(PriceCompare);
  this.minimise = PricesMinimise;
  this.pricesBB = PricesBB
}
function PricesMinimise(c) {
  this.minSize = c;
  this.maxCost = this.incumbent = Number.POSITIVE_INFINITY;
  c = this.pricesBB(0, 0, 0, 0);
  c.xs.reverse();
  return c
}
function PricesBB(c, i, h, f) {
  var e = this.prices[c], g = e.size;
  e = e.cost;
  var a = (this.minSize - i) / g, d = Math.ceil(a), b;
  if(g == Number.POSITIVE_INFINITY) {
    d = 1;
    g = 0;
    b = e
  }else {
    b = h + e * d;
    a = h + e * a;
    f = Math.max(f, a);
    if(a >= this.incumbent) {
      return null
    }
  }
  this.maxCost = Math.min(this.maxCost, b);
  a = {xs:[d], cost:b};
  if(b < this.incumbent) {
    this.incumbent = b
  }
  if(b == f) {
    return a
  }
  if(c < this.prices.length - 1) {
    for(d--;d >= 0;d--) {
      b = this.pricesBB(c + 1, i + g * d, h + e * d, f);
      if(b != null) {
        b.xs.push(d);
        a = b;
        if(a.cost == f) {
          return a
        }
      }
    }
  }
  return a.cost == this.incumbent ? a : null
}
;


Filtering a list of names based on certain conditions

I would make this two different functions, one for filtering all names of length n and one for all names starting with some letter. I made them into generator comprehensions, so they are more memory efficient on their own (even though here I cast them to lists, as soon as I want to use them).

Then there is a function which is similar to your function, except that it is configurable. By default it just yields the original list. If additional n's or c's are passed, it applies these criteria.

Finally there is a print function, which has your concrete realization of n = 4, 3 and c = "K", "Z".

def n_chars(names, n):
    return (name for name in names if len(name) == n)

def starts_with(names, c):
    return (name for name in names if name.lower().startswith(c))

def print_sublists(names):
    print(names)
    print(list(n_chars(names, 4))
    print(list(n_chars(names, 3))
    print(list(starts_with(names, "k"))
    print(list(starts_with(names, "z"))

if __name__ == '__main__':
    names1 = ["Jane", "Jake", "Bradley", "Bill", "Betty", "Kara", "Kris", "Jil"]
    names2 = ["George", "Kate", "Karen", "Kurt", "Greg", "Gary"]
    for names in names1, names2:
        print_sublists(names)


Count how many times a value is greater than or equal to the median of previous D elements

You are almost correct.

I believe you are interpreting the performance as \$O(n²*logn)\$ because you are looping over (most of) the items in the input array (length = n) and you are using a sort to compute your median.

However, sorted's performance is actually determined by the size of the window parameter, D, which is a constant, and its log is a constant, too! So your performance is technically \$O(n*DlogD)\$, which is \$O(n × C)\$ which is \$O(n)\$.

But you can do better!

Assume for a moment that you have the window sorted. You now receive a sequence of pairs (a, z) where value a is to be removed from the window and value z inserted. Once this is done, you will need to recompute the median.

Also, you have two cases: one where the window size D is an odd number and thus the median is one of the values in the window; and the other case where the window size is an even number and the median must be computed as the mean of the central values.

I think that if you separate your code into two functions at the top level - one for even windows, one for odd windows, you can write code that updates the sorted window without having to invoke the sorted function each time through. Thus, instead of D log D you can perform one removal and one insert in a single pass, having time proportional to D.

You'll still pass over nearly all the items in the list, so your time will still be \$O(n)\$, but it won't be times quite so large a constant.

Edit for @hjpotter92:

You are traversing an unsorted sequence of numbers, using a sliding window:

 D = 4
 [a, b, c, d,] e, f, g, h
 a, [b, c, d, e,] f, g, h
 a, b, [c, d, e, f,] g, h

Each time you advance, your window adds one number (I called it z) on the right side, and loses one number (I called it a) from the left side. So instead of pretending that each window is a whole new bunch of numbers that have to be put into order, using sort, you can write your code to remove one number, insert one number, and then recompute the median.

In some cases (D is odd), the median is just window[D//2]. In other cases (D is even), the median is (window[D//2-1] + window[D//2]) / 2. This is because of how the median is computed. You can see OP doing this computation in the original code. However, there's no reason to keep checking D for odd/even, since it never changes in the function. Instead, it's better to split the function at the top level, and proceed from there:

def func(sequence, d):
    if d % 2 == 0:  # D is even
        # code for scanning with even window size
    else:  # D is odd
        # code for scanning with odd window size

Edit 2: Comprehensive performance test

I made some changes to your code to test various performance enhancements. Here is one set of results run on my 2011 MacBook Pro (numbers are seconds, lower is better):

$ python -V
Python 3.5.4

$ python test.py

With n=10 inputs, d=4
    replsort             0.925
    replsort2            1.063
    linsert              1.549
    insbisect            1.102
    noparity             0.965
    orig                 1.129

With n=1000 inputs, d=4
    replsort             3.945
    replsort2            4.268
    linsert              5.210
    insbisect            4.280
    noparity             4.431
    orig                 5.324

With n=1000 inputs, d=50
    replsort             7.384
    replsort2            7.156
    linsert              8.763
    insbisect            4.736
    noparity             10.172
    orig                 10.854

With n=1000 inputs, d=500
    replsort             10.447
    replsort2            10.590
    linsert              8.184
    insbisect            6.641
    noparity             50.901
    orig                 49.458

The orig function is your code. The noparity function is your code with the parity check hoisted to the top. The replsort functions maintain the window by replacing the a value with the z value (as discussed above) and then sorting the window. The linsert and insbisect functions work by doing a linear scan of the window, or by calling bisect.insort_left, respectively, to get the z value in place.

Important: your example is bad. You've got a short list of input numbers, with a small window size. That means the "fixed costs" will tend to dominate your performance.

What does that mean? It means that things like calling the function, initializing count = 0, setting up and tearing down the for loop, and executing the return statement will make a difference.

It also means that the difference between \$O(n)\$ and \$O(log\ n)\$ and \$O(n\ log\ n)\$ don't seem to matter.

But when I switched to generating 1000 random numbers, instead of 10 fixed numbers, things changed! Notice the linsert function goes from being 50% slower, to being something like 25% slower when n=1000. Also, notice that all the other functions beat noparity. I believe this is because noparity always recomputes the entire slice before sorting it. That computation got added in 990 more times (for d=4) and it started to be a drag on the performance.

Finally, I started increasing the window size. This is where the magic really happens, because this affects the performance of the sort, the bisect, the window search and removes. Essentially, this is the number that really determines the differences in performance. For a small window size, again the upfront costs of calling sorted or remove or bisect are dominating. But when the window size goes up, suddenly the differences in algorithmic efficiency start to matter.

And look what happens with d=500. First, realize that setting d=500 means the code only does half the work! Because the input of 1000 minus a 500 window size leaves 500 checks to run, rather than 996 (d=4) or 950 (d=50). But when that change is made, suddenly linsert (which is \$O(d)\$) and insbisect (which is \$O(log\ d)\$) outperform everybody. Because "setup costs" and "written in C" no longer cover up \$O(d\ log\ d)\$!

# test.py
import bisect

def orig(expenditure, d):
    """ Worst-case: O( n^2 * logn ) """
    num_of_trans = len(expenditure) - 1
    count = 0
    for i in range(d, num_of_trans):
        prev_trans = sorted(expenditure[i - d:i])
        if d % 2 == 0:
            left_i = (d - 1) // 2
            right_i = left_i + 1
            median = prev_trans[left_i] + prev_trans[right_i]
        else:
            median = prev_trans[d - 1]
        if expenditure[i] >= median:
            count += 1

    return count

def noparity(expenditure, d):
    """Hoist parity check out of loop"""

    num_of_trans = len(expenditure) - 1
    count = 0
    left_i = (d - 1) // 2
    right_i = left_i + 1

    if d % 2 == 0:
        for i in range(d, num_of_trans):
            prev_trans = sorted(expenditure[i - d:i])
            median_x2 = prev_trans[left_i] + prev_trans[right_i]
            if expenditure[i] >= median_x2:
                count += 1
    else:
        for i in range(d, num_of_trans):
            prev_trans = sorted(expenditure[i - d:i])
            median_x2 = prev_trans[d // 2] * 2
            if expenditure[i] >= median_x2:
                count += 1

    return count

def linsert(expenditure, d):
    """Hoisted median, using linear insertion instead of sort"""

    count = 0
    len_exp = len(expenditure)
    window = sorted(expenditure[:d])
    winremove = window.remove
    winsert = window.insert
    winappend = window.append

    if d % 2 == 0:
        m1 = d // 2
        m0 = m1 - 1
        ai = 0
        for zi in range(d, len_exp):
            median_x2 = window[m0] + window[m1]
            a, z = expenditure[ai], expenditure[zi]
            ai += 1

            if z >= median_x2:
                count += 1

            winremove(a)
            for i in range(d-1):    # d-1 because .remove
                if window[i] <= z:
                    winsert(i, z)
                    break
            else:
                winappend(z)

    else:
        raise NotImplementedError("I haven't written this code.")

    return count

def insbisect(expenditure, d):
    """Hoisted median, using bisect for insertion."""

    count = 0
    len_exp = len(expenditure)
    window = sorted(expenditure[:d])
    winremove = window.remove

    if d % 2 == 0:
        m1 = d // 2
        m0 = m1 - 1
        ai = 0
        for zi in range(d, len_exp):
            median_x2 = window[m0] + window[m1]
            a, z = expenditure[ai], expenditure[zi]
            ai += 1

            if z >= median_x2:
                count += 1

            winremove(a)
            bisect.insort_left(window, z)

    else:
        raise NotImplementedError("I haven't written this code.")

    return count

def replsort(expenditure, d):
    """Hoisted median, using replacement via index, then sort."""

    count = 0

    window = sorted(expenditure[:d])
    windex = window.index
    winsort = window.sort

    if d % 2 == 0:
        m1 = d // 2
        m0 = m1 - 1

        for a, z in zip(expenditure, expenditure[d:]):
            median_x2 = window[m0] + window[m1]
            if z >= median_x2:
                count += 1

            # Note: do not write `window =` anywhere, or you invalidate
            # windex and winsort.
            window[windex(a)] = z
            winsort()
    else:
        raise NotImplementedError("I haven't written this code.")

    return count

def replsort2(expenditure, d):
    """Hoisted median, using replacement via index, then sort."""

    count = 0

    len_exp = len(expenditure)
    window = sorted(expenditure[:d])
    windex = window.index
    winsort = window.sort

    if d % 2 == 0:

        m1 = d // 2
        m0 = m1 - 1
        ai = 0

        for zi in range(d, len_exp):
            median_x2 = window[m0] + window[m1]
            a, z = expenditure[ai], expenditure[zi]
            ai += 1

            if z >= median_x2:
                count += 1

            # Note: do not write `window =` anywhere, or you invalidate
            # windex and winsort.
            window[windex(a)] = z
            winsort()
    else:
        raise NotImplementedError("I haven't written this code.")

    return count

if __name__ == "__main__":
    from timeit import timeit
    from random import randrange as rr

    results =[line.strip().split() for line in """
replsort   9.730
replsort2  11.538
linsert    17.954
insbisect  10.970
noparity   10.574
orig 11.801
""".splitlines() if line.strip()]

    print("\nWith n=10 inputs, d=4")
    for funcname, time_for_me in results:
        print("    {:20s} {:5.3f}".format(funcname,
            timeit('{}([2,3,4,2,3,6,8,4,5], 4)'.format(funcname),
                setup='from __main__ import {}'.format(funcname),
                number=100000)))

    print("\nWith n=1000 inputs, d=4")

    for funcname, time_for_me in results:
        print("    {:20s} {:5.3f}".format(funcname,
            timeit('{}([rr(1, 16) for _ in range(1000)], 4)'.format(funcname),
                setup='from __main__ import rr, {}'.format(funcname),
                number=1000)))

    print("\nWith n=1000 inputs, d=50")

    for funcname, time_for_me in results:
        print("    {:20s} {:5.3f}".format(funcname,
            timeit('{}([rr(1, 16) for _ in range(1000)], 50)'.format(funcname),
                setup='from __main__ import rr, {}'.format(funcname),
                number=1000)))