1. Comments on your code

For most of your functions, you've written a comment describing what it does. It's usual in Python to put this in a docstring, so that a user can get at it from the interactive interpreter using the help function.
The function rotate relies on a global variable draw. This makes it hard to reuse and test. (And you couldn't use it in a multi-threaded program.)
The function rotate carries out multiple tasks: it rotates the bitmap; translates it; draws the result to an Image object; and saves it to a file. It would make the code easier to use and more general if you separated these functions.
The comments suggest that you have not understood how to use NumPy. For example, you write that your function lin_interp is "Faster than numpy.interp()". Which no doubt it is for the case of a single point. But when properly vectorized, NumPy will beat pure Python.

For a very simple example, consider a pure-Python implementation of the dot product operation:

def dot(v, w):
    return sum(x * y for x, y in zip(v, w))

Let's compare the speed with numpy.dot. The pure-Python version is substantially faster for very small arrays:

>>> import numpy as np
>>> from timeit import timeit
>>> timeit(lambda:dot([1, 2], [3, 4]))
2.1183970817364752
>>> timeit(lambda:np.dot([1, 2], [3, 4]))
11.150392828974873

but the NumPy version is hundreds of times faster for large arrays:

>>> v = np.arange(1000)
>>> w = np.arange(1000)
>>> timeit(lambda:dot(v, w), number=1000)
1.4182810601778328
>>> timeit(lambda:np.dot(v, w), number=1000)
0.0053491611033678055

So in order to get a performance benefit out of NumPy, you have to vectorize your algorithm so that each step of the algorithm operates on many elements simultaneously.
Here's another example. In this extract you iterate over a grid of coordinates (x, y) and rotate each coordinate by −r radians about the point (cx, cy):

for x in xrange(xoffset,nw):
    for y in xrange(yoffset,nh):
        ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))

Let's put that in a function for timing purposes:

def rotate1(a, theta, ox, oy):
    """Rotate array of 2-dimensional coordinates by theta radians about
    the point (ox, oy).

    """
    for x, y in a:
        affine_t(x-ox, y-oy, *mrotate(theta, ox, oy))

To be as generous as possible with the timing results, I haven't even attempted to store or return a result. Let's try that out on an array of a million coordinates:

>>> grid = np.meshgrid(np.arange(1000), np.arange(1000))
>>> coords = np.vstack(grid).reshape(2, -1).T
>>> timeit(lambda:rotate1(coords, np.pi / 4, 500, 500), number=1)
94.44321689195931

Here's how the same operation looks when vectorized:

def rotate2(x, y, theta, ox, oy):
    """Rotate arrays of coordinates x and y by theta radians about the
    point (ox, oy).

    """
    s, c = np.sin(theta), np.cos(theta)
    x, y = x - ox, y - oy
    return x * c - y * s + ox, x * s + y * c + oy

Instead of looping over the coordinates and applying all the stages of the  transformation to one coordinate at a time, we apply each stage of the transformation to all the coordinates simultaneously.

>>> timeit(lambda:rotate2(grid[0], grid[1], np.pi / 4, 500, 500), number=1)
0.06842728098854423

So although your comment says that affine_t is "A lot faster than numpy", in fact, when properly vectorized, NumPy runs more than 1300 times faster.

2. Revised code

If I was doing this for real, then obviously I'd use scipy.misc.imrotate or skimage.transform.rotate or whatever. But considered only as an exercise, here's how I'd program this (in the nearest neighbour case, which is quite enough for one answer).

import numpy as np

def rotate_coords(x, y, theta, ox, oy):
    """Rotate arrays of coordinates x and y by theta radians about the
    point (ox, oy).

    """
    s, c = np.sin(theta), np.cos(theta)
    x, y = np.asarray(x) - ox, np.asarray(y) - oy
    return x * c - y * s + ox, x * s + y * c + oy

def rotate_image(src, theta, ox, oy, fill=255):
    """Rotate the image src by theta radians about (ox, oy).
    Pixels in the result that don't correspond to pixels in src are
    replaced by the value fill.

    """
    # Images have origin at the top left, so negate the angle.
    theta = -theta

    # Dimensions of source image. Note that scipy.misc.imread loads
    # images in row-major order, so src.shape gives (height, width).
    sh, sw = src.shape

    # Rotated positions of the corners of the source image.
    cx, cy = rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy)

    # Determine dimensions of destination image.
    dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy))

    # Coordinates of pixels in destination image.
    dx, dy = np.meshgrid(np.arange(dw), np.arange(dh))

    # Corresponding coordinates in source image. Since we are
    # transforming dest-to-src here, the rotation is negated.
    sx, sy = rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy)

    # Select nearest neighbour.
    sx, sy = sx.round().astype(int), sy.round().astype(int)

    # Mask for valid coordinates.
    mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh)

    # Create destination image.
    dest = np.empty(shape=(dh, dw), dtype=src.dtype)

    # Copy valid coordinates from source image.
    dest[dy[mask], dx[mask]] = src[sy[mask], sx[mask]]

    # Fill invalid coordinates.
    dest[dy[~mask], dx[~mask]] = fill

    return dest

Here's fabio.jpg, a 200×200 image (courtesy of Oasisisgood at en.wikipedia, licensed under CC-BY-SA):

and here are some rotated versions:

>>> from scipy.misc import imread, imsave
>>> img = imread('fabio.jpg')
>>> for angle in (45, 75, 90, 120):
...     imsave('fabio-{}.jpg'.format(angle),
...            rotate_image(img, angle * np.pi / 180, 100, 100))

The rotation of this 200×200 image takes about 1/60 of a second:

>>> timeit(lambda:rotate_image(img, np.pi / 4, 100, 100), number=1)
0.01648401003330946

(scipy.misc.imrotate is about 4 times faster than this when using interp='nearest'.)


How can I extract these similar codes into only one method?

Simple, with a bit of overhead, calling a run()

    testInstance("IT", () -> IvoryTower.getInstance());
    testInstance("TSDCL", () -> ThreadSafeDoubleCheckLocking.getInstance());
    testInstance("IODH", () -> InitializationOnDemandHolder.getInstance());
}

private void testInstance(String title, Runnable r) {
    long startTime = getCurrentTime();
    for (int i =  0; i < MAX_ITE; i++) {
        r.run();
    }
    long endTime = getCurrentTime();
    System.out.println(title + ": " + (endTime - startTime));
}

Possibly with testInstance as lambda too if you do not want a second method.

OR

Runnable[] rs = {
    () -> IvoryTower.getInstance(),
    () -> ThreadSafeDoubleCheckLocking.getInstance(),
    () -> InitializationOnDemandHolder.getInstance()
};
for (r : rs) {
    ...
    r.run();
    ...
}


Reverse the word order in string, without reversing the words

Your algorithm is supremely inefficient. Moving a word to the front moves all the other characters to the back, resulting in a quadratic algorithm. In addition to that, you repeatedly recalculate the length of the null terminated string.

As an aside, the standard library provides std::rotate() for moving part of a sequence from the end to the beginning, no need to write your own.

There is an alternative in-place algorithm which swaps every character at most twice, and traverses three times. Thus it is trivially proven linear:

Reverse every word in isolation. Remember the end if needed.
Reverse everything.

The standard library features std::reverse() for implementing this.


Overriding static method with different static variable in java

From time to time one sees this wish. I never needed it, but the way is to have one global repository in the base class:
public abstract class Animal {
    private static final Map<Class<? extends Animal>, List<Animal>> all =
            new HashMap<>();

    protected Animal() {
        List<Animal> species = all.computeIfAbsent(getClass(),
                type -> new ArrayList<>());
        species.add(this);
    }

    public static Stream<T extends Animal> all(Class<T> type) {
        return all.computeIfAbsent(getClass(),
               type -> new ArrayList<>()).stream().map(type::cast);
    }

Instead of storing the Animal child instance one could use a WeakReference<Animal> to let animals disappear when not used.
A call to Animal.all(Dog.class) needs no Animal instance.


Python program to check if a set of points is at land or at sea

Style

Your docstring at the top of the seq function should be moved underneath the function signature, like this:

def seq(start, end, step):
    """Function to iterate with decimal step size"""
    ...

The variable map, should be written like this, to improve clarity and readability:

map = Basemap(
    projection="merc",
    resolution = 'h',
    area_thresh = 0.001,
    llcrnrlon=bottomlong,
    llcrnrlat=bottomlat,
    urcrnrlon=toplong,
    urcrnrlat=toplat
)

All these variables:

bottomlat = 70.390829
toplat = 70.855549
bottomlong = 27.692793
toplong =  28.728254
gridsize = 0.001

Should be renamed so they appropriately display the fact that they are constants.

BOTTOM_LAT = 70.390829
TOP_LAT = 70.855549
BOTTOM_LONG = 27.692793
TOP_LONG =  28.728254
GRID_SIZE = 0.001

This comment:

"""Divide global area into grid cells"""

Should be changed into an inline comment:

# Divide global area into grid cells

For more help with style, visit PEP8, Python's official style guide.

Error handling in seq

You shouldn't be using assert to check if a variable meets certain constraints unless you're doing testing. The proper way would be to do something like this:

if step != 0:
    sample_count = abs(end - start) / step
    return itertools.islice(itertools.count(start, step), sample_count)
raise ValueError("Step must not be equal to zero.")


Advice 1

You can save some indentation space:

if (size > 1) {
    ... // Lots of code.
}

to

if (size < 2) {
    return;
}
... // Lots of code here.

Advice 2

You can do the partitioning in-place; there is no need for asking for more memory. The pseudocode in Wikipedia is rather detailed, uses no auxiliary memory (except for the recursion stack, of course) and is easy to follow.


Given 2 numbers a and b find the smallest number greater than b by interchanging the digits of a and if not possible print -1

main()

When I started your program the first time, I didn't know what to do, because your program didn't tell me. Before scanning a user input, I would tell the user to input something:

Scanner sc = new Scanner(System.in);
System.out.println("Please enter number a:");
char[] a = sc.next().toCharArray();
System.out.println("Please enter number b:");
int b = sc.nextInt();

For number a, I would also use an int instead of a char[]. Then I would convert it to a char[], but not in the main-function:

System.out.println("Please enter number a:");
int a = sc.nextInt();
System.out.println("Please enter number b:");
int b = sc.nextInt();

Another problem now is that your program doesn't validate the user input. The user could enter a letter instead of a number and your program would just break. This problem can be solved like this:

System.out.println("Please enter number a:");
int a;
while(true) {
    try {
        a = sc.nextInt();
        break;
    }
    catch(InputMismatchException e) {
         System.out.println("That's not a number!");
         sc.nextLine();
    }
}
System.out.println("Please enter number b:");
int b;
while(true) {
    try {
        b = sc.nextInt();
        break;
    }
    catch(InputMismatchException e) {
        System.out.println("That's not a number!");
        sc.nextLine();
    }
}

f()

Create a method static void f(int numberA, int b) that creates the char-array and the boolean[] vis and then calls the method static void f(char[] a, String s, int r, boolean[] vis, int b). That way you don't have to do work in the main-method that doesn't belong to the main-method:

static void f(int numberA, int b) {
        char[] a = ("" + numberA).toCharArray();
        boolean[] vis = new boolean[a.length];

        f(a, "", a.length, vis, b);
        System.out.println(ans == Integer.MAX_VALUE ? -1 : ans);

}

I don't like most of your variable names. You should (almost) always use names that tell the person who reads your code, what the variable does.

Your algorithm looks solid. Well done.

All in all it looks like this:

import java.util.Scanner;
import java.util.InputMismatchException;

class ChangeDigits {
    static int ans = Integer.MAX_VALUE;

    static void changeDigits(int numberA, int numberB) {
        char[] change = ("" + numberA).toCharArray();
        boolean[] pickedElements = new boolean[change.length];
        int remaining = change.length;
        changeDigits(change, "", remaining, pickedElements, numberB);
        System.out.println("Solution: " + (ans == Integer.MAX_VALUE ? -1 : ans));

    }

    static void changeDigits(char[] change, String substring, int remaining, boolean[] pickedElements, int numberB) {
        if (remaining == 0) {
            int substrNumber = Integer.parseInt(substring);
            if (substrNumber > numberB && substrNumber < ans)
                ans = Math.min(substrNumber, ans);
            return;
        }

        for (int i = 0; i < change.length; i++) {
            if (!pickedElements[i]) {
                substring += change[i];
                pickedElements[i] = true;
                changeDigits(change, substring, remaining - 1, pickedElements, numberB);
                substring = substring.substring(0, substring.length() - 1);
                pickedElements[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter number a:");
        int numberA;
        while(true) {
            try {
                numberA = sc.nextInt();
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("That's not a number!");
                sc.nextLine();
            }
        }

        System.out.println("Please enter number b:");
        int numberB;
        while(true) {
            try {
                numberB = sc.nextInt();
                break;
            }
            catch(InputMismatchException e) {
                System.out.println("That's not a number!");
                sc.nextLine();
            }
        }

        changeDigits(numberA, numberB);
    }
}


According to the Code Conventions for the Java Programming Language, 9. Naming Conventions, I'd call the class EpubReader. The name should be a noun, and try to avoid abbreviations which makes the code harder to read.
Couldn't the readEpub method be private? Why has it default access?
The readEpub does not use the epubInputStream parameter. Why is it read sample.epub? It looks like a test code. Furthermore, this class seems really incomplete. onCreate creates a new Eread instance then calls its readEpub method. The readEpub creates (again!) a new Eread instance (epubReader) then calls its readEpub method. It's an endless loop.
onCreate is an instance method, so you could call readEpub without creating a new Eread instance:

Book book = readEpub(epubInputStream);


The following are a few suggestions on how I'd write the SQL.

define your date parameters as variables
create a CTE of table expressions to simplify parts of your query

Source Control
If you don't already have a database project, create one in Visual Studio. Then check it in to source control. Microsoft Azure DevOps Services is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.
Formatting
I use the following tools for SSMS and Visual Studio, ApexSQL Refactor and Poor Man's T-Sql Formatter. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.

Also check out the book Clean Code. It will change the way you think about naming conventions.

Revised SQL
Without table definitions and sample records I was unable to test this, but it should give you a good start.
DECLARE @ValidFrom  AS DATETIME = '01-Jan-2019';
DECLARE @ValidTo    AS DATETIME = '31-Dec-2019 23:59:59';

WITH
agreements_list
AS
(
   SELECT
        [agr].[Name]
      , [agr].[Link]
   FROM
      [dbo].[Agreements]
   WHERE
      1=1
      AND [TenantId] = 1
      AND [ValidFrom] >= @ValidFrom
      AND [ValidTo] <= @ValidTo
)
,
companies_list
AS
(
   SELECT
        [PartyName] = comp.[Name]
      , [CountryName] = cnt.[Name]
   FROM
      [dbo].[Companies] AS comp
      LEFT JOIN [dbo].[Countries] AS cnt ON comp.[CountryId] = cnt.[BusinessId] AND comp.[TenantId] = cnt.[TenantId]
   WHERE
      1=1
      AND comp.[ValidFrom] >= @ValidFrom
      AND comp.[ValidTo] <= @ValidTo
)
SELECT
     [agr].[Name]
   , [agr].[Link]
   , [Party 1] = [comp1].[PartyName]
   , [Party 1 Country] = [comp1].[CountryName]
   , [Party 2] = [comp2].[PartyName]
   , [Party 2 Country] = [comp2].[CountryName]
FROM
   agreements_list AS [agr]
   LEFT JOIN companies_list AS [comp1] ON [agr].[Party1CompanyId] = [comp1].[BusinessId] AND [agr].[TenantId] = [comp1].[TenantId]
   LEFT JOIN companies_list AS [comp2] ON [agr].[Party2CompanyId] = [comp2].[BusinessId] AND [agr].[TenantId] = [comp2].[TenantId]


Methods to create C# dictionaries, with static keys/values, in fluent notation

This sounds like a good idea but I don't think it is, at least not with the current method names that I agree with @denis are very confusing.

The name KeysToValue should actually be AddValueWithKeys because this is the order of parameters and it better suggests that the first parameter is a value and not a key. KeysToValue sounds like a query that gets something or converts keys to values etc.

I also find the extension should extend the dictionary and not some arbitrary IEnumerable<KeyValuePair<TKey, TValue>> because if it will throw a duplicate key exception, it will be hard to find where it happened and it's of more use if extending a dictionary. If it however extends the IEnumerable then the name should be Concat.

The improved version could look like this:

public static Dictionary<TKey, TValue> AddValueWithKeys<TKey, TValue>(
    this Dictionary<TKey, TValue> dictionary,
    TValue value,
    params TKey[] keys)
{
    foreach (var key in keys) dictionary.Add(key, value);
    return dictionary;
}

and is much easier to use as it now requries only a single extension

public static readonly IReadOnlyDictionary<string, string> GroupsForVehicles =
    new Dictionary<string, string>()
        .AddValueWithKeys(RoadVehicles, "Car", "Truck", "Tractor", "Motorcycle");


Check if a string ends with a given suffix, without using .endswith()

You could use substr and pass it a negative number. Doing so is the equivalent of str.substring(str.length - X). That means you just have to pass -target.length.

function confirmEnding(str, target) {
  return str.substr(-target.length) === target;
}

function test(str, target, expected) {
  let testName = `"${str}" ${expected ? 'ends' : 'does not end'} with "${target}"`;
  if (confirmEnding(str, target) === expected) {
    console.log(`PASS: ${testName}`);
  } else {
    console.log(`FAIL: ${testName}`);
  }
}

test("Bastian", "n", true);
test("Connor", "n", false);
test("Walking on water and developing software from a specification are easy if both are frozen", "specification", false);
test("He has to give me a new name", "name", true);
test("Open sesame", "same", true);
test("Open sesame", "pen", false);
test("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain", false);


HackerRank Sherlock and Squares: count perfect squares in an interval

using namespace std;

Why is “using namespace std;” considered bad practice?

Personally, I find code more readable if it says what namespace is being used.  E.g. std::sqrt.

  unsigned test_cases, low_range, high_range, count = 0;

Three of these variables are only used inside the loop, so you can simplify by just saying

  unsigned test_cases;

As a general rule, you should declare variables at the smallest scope where they are needed.

  while(test_cases != 0)
  {
    cin >> low_range >> high_range;

Some people prefer for loops for this kind of situation.

  for (; test_cases > 0; --test_cases)
  {
     uint32_t count = 0;
     uint32_t low_range, high_range;
     std::cin >> low_range >> high_range;

Also added declarations inside the loop for variables that are only used inside the loop.  Note how this also takes care of resetting the count on each iteration.  This saves clearing the count after it's no longer used, which your original code does.

Note that unsigned is not guaranteed to be a 32-bit integer, although it almost always will be.  Using uint32_t guarantees 32 bits and is found in #include <stdint.h>.

    for(unsigned i = low_range; i <= high_range; ++i)
    {
      if(sqrt(i) == floor(sqrt(i)))
        count += 1;
    }

First, why not say

      {
        count++
      }

That's simpler than count += 1;.

  I am unsure of how I can simplify my code for this HackerRank activity:

But you are experiencing a timeout.  You don't need to make it simpler.  You need to make it faster.

Rather than calculating the square root on every iteration, calculate them only once.

    // +1 because both ends are inclusive
    // floor to keep within the high end (inclusive)
    // ceil to keep within the low end (inclusive)
    int32_t count = (unsigned)std::floor(std::sqrt(high_range)) - (unsigned)std::ceil(std::sqrt(low_range)) + 1;
    if (count < 0)
    {
      count = 0;
    }
    sherlock_squares.push((uint32_t)count);

I was originally going to do a for loop where I only calculated the squares, but I realized that I didn't have to do so.  This will get the right answer consistently.  It counts the number of integers from the square root of A to the square root of B.  That will correspond to the number of squares between A and B, since we're only counting the squares of integers.

  for(unsigned i = 0; i < sherlock_squares.size() - 1; ++i)
    cout << sherlock_squares.at(i) << endl;
  cout << sherlock_squares.at(sherlock_squares.size() - 1);

Rather than subtracting 1 from the end, add 1 to the beginning.  That saves math operations.

  std::cout << sherlock_squares.at(0);
  for (unsigned i = 1; i < sherlock_squares.size(); ++i)
  {
    std::cout << '\n' << sherlock_squares.at(i);
  }

Switching from std::endl to '\n' is faster, as std::endl triggers a flush, which you don't need here.  Probably not the performance bottleneck in this case, but it can be in some cases.

Always using the block form of control structures is more reliable and simplifies source control if you add statements in the future.

But I actually think that what the challenge wanted was

  for (auto sherlock_square : sherlock_squares)
  {
    std::cout << sherlock_square << '\n';
  }

with new lines after every line rather than only between them.

It may even have wanted you to interleave input and output.  But that's uncertain.


As a first attempt in F# you have passed the test, but the overall impression is a little messy, while the algorithm seems to (almost) work as expected.

If calling it with an empty argument list - from this:

match args with
        | [] -> lower @ upper @ numbers

in buildChars, I would expect it to produce a 16 chars password from the default settings. But it fails here:

let bytes : byte array = Array.zeroCreate <| if strContainsOnlyNumber(argv.[0]) then Convert.ToInt32 argv.[0] else 16

with an IndexOutOfRangeException

   let rec contains item list : bool =
        match list with
        | [] -> false
        | head::tail -> (head = item) || contains item tail

This is not used, so delete it. If you need a contains function, the List-module has a predefined such ready to use.

Especially buildChars seems overly messy and complicated, and it is not very efficient that the char lists (numbers, lower, etc) are redefined for each recursion. Instead of having buildChars as a rec function you could have an inner recursive function to the matching and then define the char lists out side of that:
let buildChars chars (args: string list) : char list =
    let numbers = ['0'..'9']
    let lower = ['a'..'z']
    let upper = ['A'..'Z']
    let special = ['!' .. '/'] @ ['@']
    let rec listBuilder chars args =
        match args with
        | [] -> lower @ upper @ numbers
        // ... etc.

    listBuilder chars args

Besides that, I think I would think of another design, if I find my self repeating the almost same code like in this function. List.fold may be a solutions in this case.
Another issue with the function is that if the argument list contains more of the same argument (for instance "-l", "-l") it will be included more than once making the result somewhat biased. Maybe consider to reduce the argument list to a distinct set - unless you want the behavior.

You could consider to print help/information, if the argv has a "-?" entry.

In F#, lists are very convenient because of its operators that makes the code more readable, but in this particular algorithm, I think I would stick to use arrays for everything, because you address the list entries by index, which is not efficient for lists, because chars.[index] is an O(index) operation where the same operation is O(1) for arrays, further List.length is a O(n) operation - adding more inefficiency to the equation.

let rec buildString  (bytes: byte list) (chars: char list) (builder: StringBuilder) : string =
    match bytes with
    | [] -> builder.ToString()
    | head::tail -> buildString tail chars <| builder.Append chars.[(int) head % chars.Length]

This function is not tail recursive and therefore builds up the stack. For a password generator it will probably never be an issue, but there is a hypothetical risk for a stack overflow. Fortunately you can easily make it tail recursive and more efficient, because builder.Append returns the builder itself. So changing the last line to
| head::tail -> buildString tail chars (builder.Append chars.[(int) head % chars.Length])

makes the function tail recursive.

Below is my version with some inline explanation:
let passwordGenerator (argv: string []) =

    // The @ - operator for lists is temporarily redefined to work with arrays
    // in order to make the code more readable
    let inline (@) left right = Array.append left right

    // From the first argument or a possible empty argument list the
    // custom size and if the default settings should be used is determined
    let useDefaults, size =
        match argv.Length with
        | 0 -> true, 16
        | _ ->
            match (Int32.TryParse(argv.[0])) with
            | true, n -> (argv.Length = 1), n
            | false, _ -> false, 16

    // The usable characters are determined from the arguments
    let chars =
        let lower = [| 'a'..'z' |]
        let upper = [| 'A'..'Z' |]
        let numbers = [| '0'..'9' |]
        let special = [| '!' .. '/' |] @ [| '@' |]

        if useDefaults then
            lower @ upper @ numbers
        else
            // This will avoid duplicate chars
            let predicate arg short long (chs: char[]) all =
                (arg = short || arg = long) && not (all |> Array.contains (chs.[0]))

            let folder all arg =
                match arg with
                | a when predicate a "-l" "--lower" lower all -> all @ lower
                | a when predicate a "-u" "--upper" upper all -> all @ upper
                | a when predicate a "-n" "--numerics" numbers all -> all @ numbers
                | a when predicate a "-s" "--special" special all -> all @ special
                | _ -> all

            argv |> Array.fold folder [||]

    // Provides the random bytes
    let bytes =
        use rng = new RNGCryptoServiceProvider()
        let bytes = Array.zeroCreate size
        rng.GetBytes(bytes)
        bytes

    // Generates the password
    let password =
        bytes
        |> Array.map (fun b -> chars.[int b % chars.Length])
        |> fun chs -> new String(chs)

    printfn "%s" password


Solving this Python implementation for Stock Gains

As a variable name, i has a connotation of being an index, rather than a value, of a list.  I would expect it to be used in contexts more like for i, value in enumerate(values).

Making the slice input_list[1:] would involve duplicating most of the list. I would use an iterator to avoid doing that, and also to simplify the handling of the special case.

With a few improvements in naming…

def max_gain(input_list):
    prices = iter(input_list)
    best_buy = next(prices, 0)
    profit = 0
    for price in prices:
        profit = max(profit, price - best_buy)
        best_buy = min(best_buy, price)
    return profit


Using common code inside a Higher Order Component

There's no reason to use a HOC for this, it can be done more simply and clearly with a component:

class List extends React.Component {
  state = { data: this.props.initialData, element: "" };

  add = item => {
    this.setState(prev => ({ data: prev.data.concat(item) }));
  };

  remove = keyToRemove => {
    this.setState(prev => ({
      data: prev.data.filter(({ key }) => keyToRemove !== key)
    }));
  };

  render() {
    const { data, element } = this.state;
    const { placeholder, listName } = this.props;

    return (
      <>

{listName}:

        {data.map(({ name, key }) => (

{name}

            <button onClick={() => this.remove(key)}>remove</button>

        ))}
        <input
          placeholder={placeholder}
          onChange={e => this.setState({ element: e.target.value })}
        />
        <button
          onClick={() => this.add({ name: element, key: data.length + 1 })}
        >
          insert
        </button>
      </>
    );
  }
}

const Users = () => (
  <List
    initialData={[
      { name: "a", key: 1 },
      { name: "b", key: 2 }
    ]}
    listName="Users"
    placeholder="insert user"
  />
);
const Comments = () => (
  <List initialData={[]} listName="Comments" placeholder="insert comment" />
);
const AnotherList = () => <Users />;

function App() {
  return (

      <Users />
      <Comments />
      <AnotherList />

  );
}

ReactDOM.render(<App />, document.getElementById("app"));

HOCs are generally better for cross-cutting concerns, or behavior (not presentation) which you want to add to any component. for example logging:

const withLogging = Component => props => {
  console.log('Props:', props);
  return <Component {...props} />;
}

const List = ({ name, data }) => ...
const ListWithLogging = withLogging(List); // <-- This will log all props


In this loop…

    for(int i = 0; i<trials; i++) {
        xVal(darts);
        yVal(darts);
        hits(darts);
        System.out.println(piCalc(darts));
    }

You are throwing away the values returned from xVal(darts), yVal(darts), and hits(darts), making these calls completely superfluous.  All they are doing is wasting entropy from the random number generator.  The only thing that matters is piCalc(darts) (which calls hits(), which in turn calls xVal() and yVal()).

The code for xVal() is exactly identical to yVal().  You don't need to write the same function twice.


and welcome to C programming! Also, to Code Review.
Style
There are a couple of "style" issues with your code. The most obvious one is that your indentation is not consistent. I don't know if that's due to pasting it into the browser, or if it appears that way in your code. But computescore needs to be cleaned up.
Next is an issue of "comprehensibility". You have this array:
// Points assigned to each letter of the alphabet
int points[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

Quick, how many points for 'S'?
This array might possibly be correct, but it's not comprehensible and it's not modifiable. It would be much better to provide some other mechanism to initialize the array, or initialize some other structure, such that the next guy to maintain the code has a chance of seeing bugs and/or being able to make changes.
For example:

You might create an enum, with point values for each letter, then initialize the array using the enum labels:
enum {
    A_POINTS = 1,
    B_POINTS = 3,
    C_POINTS = 3,
    :
};

int points[] = {
    A_POINTS,
    B_POINTS,
    C_POINTS,
    :
};

You might create a clever designated initializer macro that makes things more clear:
#define TILE(CH) [CH - 'a']

int points[] = {
    TILE('a') = 1,
    TILE('b') = 3,
    TILE('c') = 3,
    :
};

You might consider building a string and parsing it at runtime, like:
const char * points =
     "A = 1; B = 3; C = 3; ...;"
     "N = ..."
     ;

Be aware: the point of this is purely to make it easy to understand the mapping between letters and points. Ideally, you want to make it easy enough to understand that someone could look at the code and catch a mistake before you compiled it and went to testing.
Magic
Your scoring function searches through a list of characters in order to obtain the index of a particular character. Never do that! You know the index, it's just hidden behind a thin layer of mathematics.
In ASCII, the upper and lowercase letters (also, digits) are runs of encoding values assigned in consecutive, increasing order. Once you know where the start of the run is, you can get to any other character by simple addition. Likewise, you can reverse that trick using simple subtraction:
    score_index = ch - 'a';
    score += points[score_index];


Lambda .Where() expression to return selected/flagged objects

If you control the MenuItemDefinition class, why not just add a feature tag to it?

public class MenuItemDefinition
{
    public string MethodName { get; set; }
    public string Feature { get; set; }
}

// each instance
new MenuItemDefinition { MethodName = "NewWidget", Feature = "Widgets" }

// GetMenuItems():
return GetAllMenuItems().Where(m => FeatureIsEnabled(m.Feature));

If not, you could put them in a dictionary:

var items = new Dictionary<string, MenuItemDefinition[]> {
    { "Widgets", new[] {
        new MenuItemDefinition { MethodName = "NewWidget" },
        new MenuItemDefinition { MethodName = "DeleteWidget" }
    },
    { "Default", new[] {
        // ....
    }
}

return items.Where(pair => FeatureIsEnabled(pair.Key)).SelectMany(pair => pair.Value);

Or better yet, build the initial list based upon content in a dictionary. That way you don't run the risk of having typos in the switch or the initial setup:

var dict = new Dictionary<string, string[]>
{
    { "Widgets", new[] { "NewWidget", "DeleteWidget" },
    { "Default", new[] { "..." }
    ...
}

var menuItems = dict
    .Where(p => FeatureIsEnabled(p.Key))
    .SelectMany(p => p.Value)
    .Select(mn => new MenuItemDefinition { MethodName = mn });

// GetMenuItems()
return menuItems; // :)


Why does binding have parameters? The closure isn't passing any.
As far as I know, 75% of browsers (including IE9+) actually support addEventListener. If you check for attachEvent first, you are wasting that 75% assurance. Instead, check for addEventListener first and 75% of the time, your code is evaluating just one condition.
For better readability, use common conventions when naming. Element references can be shortened to el, events are usually ev (because e sometimes refer to error objects), and event handlers are usually called handler or callback.
Although you might say that you are not going to support older/other browsers, that does not mean you should recklessly code.

In your code, if you used attachEvent was not supported, you use addEventListener. But what if the browser hasn't got addEventListener either? The binding will crash trying to use it since addEventListener a last resort that is, in this case, not supported.

So I added a third case which makes NS.addEL be a function that does nothing if both methods are not available.

And so:

NS.addEL = (function binding(){

  if(window.addEventListener){
    return function addEventListener(el, ev, handler){
      el.addEventListener(ev, handler);
    }
  }

  if(window.attachEvent) {
    return function attachEvent(el, ev, handler){
      el.attachEvent('on' + ev, handler);
    }
  }

  return function(){/*not supported for some reason*/}

}());

Another approach to this is the following code. It's shorter, but performs checks everytime the function is called. If the browser supports neither, then nothing is actually executed:

NS.addEL = function addEL(el,ev,handler){
  if(window.addEventListener) {
    el.addEventListener(ev,handler);
  } else if(window.attachEvent){
    el.attachEvent('on' + ev,handler);
  }
});


ReactJS component to classify a list of books

You may start to make your code slightly less verbose (and with all the required semicolons):

const result = {
    currentlyReading: [],
    read: [],
    wantToRead: []
};

this.state.books.forEach(item => {
    if (...) {
        item.setShelf = "Currently Reading";
        result.currentlyReading.push(item);
    }
});

return result;

Then you might simplify comparison using regular expressions:

if (item.shelf.match(/^currently\s?reading$/i)) { ... }

Now you can see that you are MUTATING THE STATE without using setState(). That's an Incredibly Bad Thing™. You do not give enough context to provide a specific suggestion then I'll mention few:

1) Do not mutate existing objects, create new ones:

if (item.shelf.match(/^currently\s?reading$/i) {
    result.currentlyReading.push({ ...item, setShelf: "Currently Reading" });
}

2) Perform this translation in componentDidUpdate() when you populate the books state property.

3) If you're using Redux then perform this translation in your Reducer (or Selector, if you're using them).

Re-think your design. Why do you need to duplicate an information you already have? What do you need these lists (with slightly changed values) for if they're already there in state.books? Let's imagine an hypothetical render() method:

render() {
    const { books } = this.state;

    return (
        <React.Fragment>
            <Shelf title="Currently reading" books={books} filter="^currently\\s?reading$" />
            <Shelf title="Read" books={books} filter="^read$" />
            <Shelf title="Want to read" books={books} filter="^want\\s?to\\s?read$" />
        </React.Fragment>
    );
}

Your separate lists are now obsolete. If you do not care about localization then regex for filter attribute might even be calculated directly (inside Shelf component!) with something like:

const filter = new RegExp(`^${this.props.title.replace(" ", "\\s?")}$`, "i");

Even if I am not doing this in my example please note that regular expression text MUST be escaped (before calling .replace()): Escape string for use in Javascript regex.

Now that you have a separate component...you may consider to move selection again outside and use memoization, simplified example (pseudo-code for memoization, pick the package you prefer):

render() {
    const { books } = this.state;

    const read = memoize((list, filter) => list.filter(book => book.shelf.match(filter)));

    return (
        <React.Fragment>
            <Shelf title="Currently reading" books={read(books, /^read$/i)} />
        </React.Fragment>
    );
}

Note that I'm NOT using the setShelf property any more in favor of Shelf.title property.


Separate grow and shrink functions are not necessary. Instead you can have a single function that prints, recurses and prints again the same value when the recursion returns.

For example like this:

def inverse_cascade(n, digits=1):
    n = str(n)
    print(n[:digits])
    if digits < len(n):
        inverse_cascade(n, digits+1)
        print(n[:digits])


Implementing bounds-checking with exceptions based on an existing bitset container

It doesn't really matter which direction you do the checking in - it's a matter of personal preference. Both are valid, semantically identical, and will almost certainly perform identically.

One thing you can do to avoid having to rewrite all of this stuff is to have a single function that does bounds-checking:

size_t boundsChecked(size_t coord) const {
    // whichever order of this you prefer
    if (coord >= _length) {
        throw std::out_of_range(...);
    }
    return coord;
}

And then defer to that function everywhere you want to add bounds checking:

bool operator[](size_t coord) const
{
    return data[boundsChecked(coord)];
}


Overall this seems fine: a classing linked list implementation in C.
A couple of things can be simplified or improved here and there.

Instead of testing head == NULL twice:

if (head == NULL && ind > 0) return head;
if (head == NULL && ind == 0) return new_SLLNode(val);

It would be better to eliminate this duplication and do it only once:

if (head == NULL) {
    if (ind > 0) return NULL;
    if (ind == 0) return new_SLLNode(val);
}

Notice that I also changed return head to return NULL.
I know that head is NULL there,
but it's more explicit this way.

I have a feeling that after the while loop that iterates until ind to insert an element, when you do this:

if (curr == NULL) return head;

Possibly you really meant this instead:

if (curr == NULL) return curr;
// or
if (curr == NULL) return NULL;

I could be wrong, but perhaps not using explicit NULLs somehow led to mistakes like this. (I assume it was a mistake to return head when trying to insert beyond end + 1 of the linked list, which indicates a likely bug in the caller.)

  Is the spacing excessive?

No, I think it's just right.

  Are 1-line control flow statements okay?

They are ok. But keep in mind that if/for/while statements without a { ... } block can lead to nasty bugs, like in this famous example.
Some static analysis tools flag a warning for such statements.


Tic Tac Toe using Cartesian coordinate system

It is a convention in Python to use the _ variable as the 'throw away variable'.
In your case you can replace column with it.
Rather than using a for loop with list.append you can use a list comprehension.

data = []
for i in range(4):
    data.append(i)

data = [i for i in range(4)]

When you build an array with all of the items having the same immutable value you can make an array with just one value and multiply the array.

foo = [None for _ in range(4)]

foo = [None] * 4

You should not rely on globals to hold state. There are two solutions:

Pass and return the values from the functions.
Use a class to encapsulate state.

Strings % method for formatting is somewhat archaic and buggy. It should be noted that str.format or f-strings are a better alternate with more features.

values = (1, 2)

'%s %s' % values

'{0[0]} {0[1]}'.format(values)
'{} {}'.format(*values)

f'{values[0]} {values[1]}'

It is best practice to use an if __name__ == '__main__' guard to prevent your code from running if imported by accident.
Python uses 0 based indexing. I have had no problems with it once adjusted. However if you do you'd be better off not using Python.

Lua, Julia and R are all languages that use 1-based indexing.

def new_board():
    return [['_'] * 3 for _ in range(3)]

def print_board(board):
    print(
        '  {} | {} | {}  '.format(*board[0])
        + '----+---+----'
        + '  {} | {} | {}  '.format(*board[1])
        + '----+---+----'
        + '  {} | {} | {}  '.format(*board[2])
    )

if __name__ == '__main__':
    board = new_board()
    print(board)
    print_board(board)


Your checkOccurrence(s) is just a clumsy way to write s.find(countMap(_) > 1).

You can significantly simplify the solution by taking advantage of .distinct.

def firstUnique(s: String): Option[Char] =
  s.zipAll(s.distinct, '\u0000', '\u0000')
   .collectFirst({ case ab if ab._1 != ab._2 => ab._1 })


Extension method that writes to a stream

Your questions imply that you might not be quite aware of how streams or references work in C#.

You pass in a reference to a Stream
You create a StreamWriter which writes to that Stream
This will automatically make changes visible to anyone holding a reference to the same Stream.

Therefor there is no need to try and return the Stream in any way from the method to make the changes visible to the caller - you just need to write to it. This is at least how I interpret your questions.

However there is a catch in your implementation: disposing the StreamWriter will automatically close the underlying Stream which I find hugely annoying at times.  Only since .NET 4.5 there is a constructor for StreamWriter which allows you to leave the Stream open. So right now your extension method will close the Stream which I guess is not the intention. Your only option to avoid that is to use .NET 4.5 or do not wrap the StreamWriter in a using statement.


Overall this code looks decent. Just a few concerns:

For this kind of complex set of steps, it is always a good idea to add comments which will help the reader to understand the code
You can use the diamond operator here:

Queue<Integer> q = new LinkedList<>();

I might be opinionated, but I prefer the name val (or even v) rather than valq.

for (int i = 0; i < size; i++) {
    int val = q.poll();
    s.push(val);
    q.offer(val);
}


Simple example to get started with a browser based game

Instead of using ball_pos as an array with two elements to contain the x and y coordinate values of the ball,
it would be more natural to use a an object like this:

ball = {
    x: canvas.width() / 2,
    y: canvas.height() / 2
}

Instead of writing keys[37] and explaining with a comment // left what the number means,
it would be better to put that in a well-named variables, for example:

var KEY_LEFT = 37;

Then you can rewrite the conditions like this:

if (keys[KEY_LEFT]) {
    ball.x -= vel;
}
if (keys[KEY_UP]) {
    ball.y -= vel;
}

Putting it together:

var canvas, context, ball, vel, keys = {};

var BALL_RADIUS = 20;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;

function init() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball = { x: canvas.width / 2, y: canvas.height / 2 };
    vel = 4;
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'red';
    context.lineWidth = 2;
    context.fillStyle = 'white';
    context.beginPath();
    context.arc(ball.x, ball.y, BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function keydown(evt) {
    'use strict';
    // mozilla based browsers return which and others keyCode
    var keyCode = evt.which || evt.keyCode;
    keys[keyCode] = true;
    // alert(keyCode)
    // 33 up right
    // 34 down right
    // 35 down right
    // 36 up left
    if (keys[KEY_LEFT]) {
        ball.x -= vel;
    }
    if (keys[KEY_UP]) {
        ball.y -= vel;
    }
    if (keys[KEY_RIGHT]) {
        ball.x += vel;
    }
    if (keys[KEY_DOWN]) {
        ball.y += vel;
    }
}

function keyup(evt) {
    'use strict';
    var keyCode = evt.which || evt.keyCode;
    delete keys[keyCode];
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

// register event handlers
window.onkeydown = keydown;
window.onkeyup = keyup;

init();
animate();
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <canvas id="c" width="600" height="400"></canvas>
</body>
</html>


myDecimal is an absolutely unhelpful name overall.  I don't see any need to give int64_t a typedef here, but even if there is one, then it should still use a better name.
Empty void parameters are not needed in C++:

OrderBook(void);
~OrderBook(void);

You also don't need these defaults as the compiler will provide them for you.  They would only be necessary if you need to overload them and will still need default versions.
It's a little less-readable not having whitespace after commas:

BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)

Not only that, but you already add this whitespace in other places.  Keep it consistent.

BOOST_MULTI_INDEX_MEMBER(OrderBookItem, myDecimal, price)

You use different styles of curly braces.  C++ doesn't restrict you to a particular one, so choose one you prefer and stick with it.
Although this line has been commented out, are you still using C++11?

// auto curLevel = buyContainer.get<name>(price);

If so, then you can replace OrderBookContainer::iterator with auto:

auto it = buyContainer.insert(price_).first;

auto it = sellContainer.insert(price_).first;


I would use function recursion in place of a jQuery queue.
The central piece is the displayNextHiddenMessagesIn function. As the name implies, it grabs the next hidden message and displays it.  After the message is displayed, it calls this function again... looping until all messages are visible.
To me, this seems much more readable and easier to maintain. Also, it would be trivial to have a another message parent and reuse this same code (i.e. error messages and information messages).
(function($) {

    function createMessageFor(parent, contents) {
        var $parent = $(parent);

        for(var content in contents) {
            var $message = newMessage(contents[content]);

            $parent.prepend($message);
        }

        function newMessage(text) {
            return $("<div />").text(text).hide();
        };
    }

    var displayNextHiddenMessagesIn = function(parent) {
        var $parent = $(parent);

        $parent.find('div:hidden:last').slideDown(function() {
            displayNextHiddenMessagesIn($parent);
        });
    };

    $("#input1").click(function()
    {
        createMessageFor('.parent', [1,2,3]);
        displayNextHiddenMessagesIn('.parent');
    });

})(jQuery);

see it in action: http://jsfiddle.net/natedavisolds/TP66b/6/
Update
Here's what it looks like as a plugin:
(function($) {
    $.fn.fanDownHiddens = function() {
        return this.each(function() {
            var $parent = $(this);

            $parent.find('div:hidden:last').slideDown(function() {
                $parent.fanDownHiddens();
            });
        });
    }
})(jQuery);

And then the onload with the test data.
(function($) {

    $(function() {
        $("#input1").click(function() {
           setupTestMessages('.parent');
           $('.parent').fanDownHiddens();
        });
    });

     function setupTestMessages(parent) {
        var $parent = $(parent),
            testData = [1,2,3];

        for(var content in testData) {
            var $message = newMessage(testData[content]);

            $parent.prepend($message);
        }

        function newMessage(text) {
            return $("<div />").text(text).hide();
        };
    }
})(jQuery);

Here's the plugin working: http://jsfiddle.net/natedavisolds/TP66b/12/


This is a valid C code which implements the above:

void ImageToColumns(float* mO, float* mI, int numRows, int numCols, int blockRadius)
{
    int blockSize, blockNumElements, colImageColIdx, colImageRowIdx;
    int ii, jj, kk, ll;

    blockSize           = (2 * blockRadius) + 1;
    blockNumElements    = blockSize * blockSize;
    colImageRowIdx      = -1;

    for (ii = blockRadius; ii < (numRows - blockRadius); ii++)
    {
        for (jj = blockRadius; jj < (numCols - blockRadius); jj++)
        {
            colImageRowIdx = colImageRowIdx + 1;
            colImageColIdx = -1;

            for (kk = -blockRadius; kk <= blockRadius; kk++)
            {
                for (ll = -blockRadius; ll <= blockRadius; ll++)
                {
                    colImageColIdx = colImageColIdx + 1;
                    mO[(colImageRowIdx * blockNumElements) + colImageColIdx] = mI[((ii + kk) * numCols) + jj + ll];
                }

            }
        }
    }

}

Clearly this a memory bounded algorithm.


1. Encapsulate

Writing code at the top level of a module makes it hard to test the code and hard to measure its performance. It's best to encapsulate code in a function. Accordingly, I'd write:

def survivor(n):
    """Return the survivor of a circular firing squad of n people."""
    persons = list(range(1, n + 1))
    while len(persons) > 1:
        for index, _ in enumerate(persons):
            del persons[(index + 1) % len(persons)]
    return persons[0]

(The variable person is not used in the body of the for loop; it's convential to write _ for such variables, and that's what I've done here.)

2. The meaning of efficiency

Is this code "efficient" as the question asks? Normally in computing we use "efficient" to mean algorithmic efficiency: that is, the rate at which the resources used by the program grow as a function of the input, usually expressed in big-O notation.

The question says, "Python is not efficient", but according to the usual view of efficiency, the programming language does not matter: efficiency is a property of the algorithm, not of the language it's implemented in.

3. It's accidentally quadratic

What's the runtime of the survivor function, expressed as a function of \$ n \$? Well, looking at the time complexity page on the Python Wiki, we can see that the del operation on a list takes \$ O(n) \$ where \$ n \$ is the length of the list, and this is executed once for each person who is killed, resulting in an overall runtime of \$ O(n^2) \$.

It's possible to check this experimentally:

>>> t = 1
>>> for i in range(8, 17):
...     t, u = timeit(lambda:survivor(2**i), number=1), t
...     print('{:6d} {:.6f} {:.2f}'.format(2**i, t, t / u))
...
   256 0.000138 0.00
   512 0.000318 2.31
  1024 0.000560 1.76
  2048 0.001363 2.43
  4096 0.006631 4.87
  8192 0.030330 4.57
 16384 0.132857 4.38
 32768 0.534205 4.02
 65536 2.134860 4.00

You can see that for each doubling of n, the runtime increases by roughly four times, which is what we expect for an \$ O(n^2) \$ algorithm.

4. Making it linear

How can we speed this up? Well, we could avoid the expensive del operation by making a list of the survivors, instead of deleting the deceased. Consider a single trip around the circular firing squad. If there are an even number of people remaining, then the people with indexes 0, 2, 4, and so on, survive. But if there are an odd number of people remaining, then the last survivor shoots the person with index 0, so the survivors are the people with indexes 2, 4, and so on. Putting this into code form:

def survivor2(n):
    """Return the survivor of a circular firing squad of n people."""
    persons = list(range(1, n + 1))
    while len(persons) > 1:
        if len(persons) % 2 == 0:
            persons = persons[::2]
        else:
            persons = persons[2::2]
    return persons[0]

(You could shorten this, if you liked, using an expression like persons[(len(persons) % 2) * 2::2], but I don't think the small reduction in code length is worth the loss of clarity.)

Let's check that this is correct, by comparing the results with the original implementation:

>>> all(survivor(i) == survivor2(i) for i in range(1, 1000))
True

Notice how useful it is for testing that we have the code organized into functions.

Now, what's the runtime of survivor2? Again, looking at the time complexity page on the Python Wiki, we can see that the "get slice" operation takes time \$ O(k) \$ where \$ k \$ is the number of items in the slice. In this case each slice is half the length of persons, so the runtime is $$ O\left({n \over 2}\right) + O\left({n \over 4}\right) + O\left({n \over 8}\right) + \dots $$ which is \$ O(n) \$. Again, we can check that experimentally:

>>> t = 1
>>> for i in range(8, 25):
...     t, u = timeit(lambda:survivor2(2**i), number=1), t
...     print('{:8d} {:8.6f} {:.2f}'.format(2**i, t, t / u))
...
     256 0.000034 0.00
     512 0.000048 1.40
    1024 0.000087 1.79
    2048 0.000142 1.63
    4096 0.000300 2.12
    8192 0.000573 1.91
   16384 0.001227 2.14
   32768 0.002628 2.14
   65536 0.006003 2.28
  131072 0.017954 2.99
  262144 0.043873 2.44
  524288 0.094669 2.16
 1048576 0.180889 1.91
 2097152 0.364302 2.01
 4194304 0.743028 2.04
 8388608 1.497255 2.02
16777216 3.094121 2.07

Now, for each doubling of n, the runtime increases by roughly two times, which is what we expect for an \$ O(n) \$ algorithm.

5. Making it polylogarithmic

Can we do even better than this? Let's look at who the survivors actually are after each trip around the firing squad:

from pprint import pprint

def survivors(n):
    """Print survivors after each round of circular firing squad with n people."""
    persons = list(range(1, n + 1))
    while len(persons) > 1:
        if len(persons) % 2 == 0:
            persons = persons[::2]
        else:
            persons = persons[2::2]
        pprint(persons, compact=True)

>>> survivors(100)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41,
 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81,
 83, 85, 87, 89, 91, 93, 95, 97, 99]
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77,
 81, 85, 89, 93, 97]
[9, 17, 25, 33, 41, 49, 57, 65, 73, 81, 89, 97]
[9, 25, 41, 57, 73, 89]
[9, 41, 73]
[73]

After each round, the gap between the survivors doubles. So after one round, the survivors are every 2nd person; after two rounds, every 4th person, after three rounds, every 8th person, and so on. When there are an even number of people, the first person remains the first survivor in the next round. But when there are an odd number of people, the third person becomes the first survivor in the next round.

So to solve this problem, we don't need to remember all the survivors, we only need to remember the first survivor, the gap between survivors, and the total number of survivors. Like this:

def survivor3(n):
    """Return the survivor of a circular firing squad of n people."""
    first = 1
    gap = 1
    while n > 1:
        gap *= 2
        n, odd = divmod(n, 2)
        if odd:
            first += gap
    return first

Once again, we should check that this is correct:

>>> all(survivor(i) == survivor3(i) for i in range(1, 1000))
True

How fast is this? Here, each time round the loop we just have some arithmetic operations on numbers of size no more than \$ n \$, taking \$ O(\log n) \$, and each time around the loop we divide the number of survivors by two, so the loop executes \$ O(\log n) \$ times, for an overall runtime of \$ O((\log n)^2) \$.

>>> t = 0
>>> for i in range(8, 60, 4):
...     t, u = timeit(lambda:survivor3(2**i), number=1), t
...     print('{:20d} {:8.6f} {:.6f}'.format(2**i, t, t - u))
...
                 256 0.000014 0.000014
                4096 0.000012 -0.000001
               65536 0.000013 0.000001
             1048576 0.000015 0.000002
            16777216 0.000016 0.000002
           268435456 0.000018 0.000002
          4294967296 0.000022 0.000003
         68719476736 0.000030 0.000008
       1099511627776 0.000026 -0.000003
      17592186044416 0.000027 0.000001
     281474976710656 0.000031 0.000003
    4503599627370496 0.000032 0.000001
   72057594037927936 0.000035 0.000003

You can see that for each increase of n by a factor of 16, the runtime increases by a roughly constant amount, which is what we expect for a polylogarithmic algorithm.

Notice that the graph shows the runtime scaling roughly proportionally to \$ \log n \$ and not to \$ (\log n)^2 \$. That's because the values of \$ n \$ are small (less than \$ 2^{64} \$) and so in this range the arithmetic operations are effectively \$ O(1) \$. We'd have to use much larger values of \$ n \$ to show the asymptotic behaviour.

6. Further reading

This problem is (a simple case of) the well-known Josephus problem.


I think this could be greatly simplified, as you are currently iterating through the input data many more times than is necessary.

There are a number of possible approaches you could take to optimize this.  One option might be to simplify this down to one call to Array.sort() to apply multi-level sorting, followed by iterating the array to reset order values.

// sort data
data.sort(
    (a, b) => {
        if (a.source < b.source) return -1;
        if (a.source > b.source) return 1;
        if (a.order < b.order) return -1;
        if (a.order > b.order) return 1;
        return 0;
    }
);

// iterate data, applying new order value
var currentGroup = null;
var counter = 0;
for (var i = 0, len = data.length; i < len; i++) {
    if (currentGroup !== data[i].source) {
        counter = 0;
        currentGroup = data[i].source;
    } else {
        counter++;
    }
    data[i].order = counter;
}

The sort here would be \$O(n log(n))\$ on average or \$O(n^2)\$ worst case (based on underlying quicksort implementation for sort()).  And the mapping on new count values would execute in \$O(n)\$.  So, you would have \$O(n^2 + n)\$ worst case complexity.

Memory utilization is also probably close to optimal for this approach, as you are modifying data in place for both the sort and the re-writing of order values.

If you wanted to consider alternate output data structures such as the following, where you use index position in array as "order" rather than having to apply an order value on the item, you might be able to improve performance.

{
    "source1": [
        {"id": "somevalue"},
        {"id": "someothervalue"},
        ...
    ],
    "source2": [
        ...
    ],
    ...
}

Some partially-implemented code for this approach might look like:

var output = {};
for(var i = 0, len = data.length; i < len; i++) {
    var el = data[i];
    var group = el.source;
    var insert = { 'id': el.id };
    if(group in output) {
        // perform sorted insert into array at group
        sortedInsert(output[group], insert);
    } else {
        output[group] = [ insert ];
    }
}

Note I say "partially" implemented based on my not having implemented the mechanism for sorted insert into group array.  You can certainly search online for an optimized approach for performing a sorted insert into an array which might use insertion sort, quicksort, heapsort, or some combination of those depending on expected array sizes.

This approach has you iterating the input data array only a single time, but with each pass you would be performing an increasingly complex insert which could range from \$O(1)\$ to \$O(n log(n))\$ (if appropriate sorting logic is used).

This could lead to worst case \$O(n^2 log(n))\$ operation. This my sound bad but consider that if you had X groups in your data set each of roughly similar size such that typical group size m = n / X that average case could actually could improve significantly:

\$O(n * m log(m)) \rightarrow O(n * (\frac{n}{X}) log (\frac{n}{x}))\$

For "worst case" example list of 1000 items in single group:

\$O(1000 * 1000 * log(1000)) \rightarrow O(3000000)\$

vs. better example of 1000 items in 10 equal groups:

\$O(1000 * 100 * log(100)) \rightarrow O(200000)\$

vs. first example of sort + mapping, again with 1000 items (number of groups doesn't matter):

\$O(1000^2 + 1000) \rightarrow O(1001000)\$

With the second approach, if you needed to, you could then "flatten" the data structure to get to your desired output, an operation that would cost an additional \$O(n)\$. If would be \$O(201000)\$ if we extended the 1000 items in 10 equal groups example.

You can see that the value of n that you expect for your use cases and how items are distributed amongst groups may become important to understanding which approach might be optimal for your application.

This leads to the most important point of this whole post, which is that if you are truly trying to optimize performance, you may need to potentially attempt several different implementations and then actually test them against your expected typical and "worst case" data sets to understand what sort of performance you might actually expect from this piece of code.


Designing a public API for a JavaScript module

It seems to me that it'd be simpler to always use JSON, rather than limit yourself to strings and arrays, specifically.

E.g.

function retrieve(key) {
  var json = localStorage.getItem(key);
  try {
    return JSON.parse(json).value;
  } catch(e) {
    return json; // either null or a non-comforming value
  }
}

function store(key, value) {
  var json = JSON.stringify({ value: value });
  localStorage.setItem(key, json);
}

This will let you store and retrieve any JSON-serializable value including strings and arrays. You can wrap/namespace it however you like.


I like your approach:

First you've defined an interface on accepting side of application. So you can fix requirements to parts responsible for storage.
Realisation is not tied to interface. Today you may use PostgreSQL, later you may add some sharding on application side, or even migrate to another DB. Keeping db-related logic in one place helps you do it in future.
Next you can cover it with tests to ensure logics won't get broken in future impovements.


Multiple isset block going from more specific to more generic

Long time reader, first time poster, welcoming of critique.

You could create an array populated with each variant of the property you're looking for:

    $is_set = array (
        $carData->{$owner}->{$brand}->{$part},
        $carData->{$owner}->{$brand}->allparts,
        $carData->{$owner}->allbrands->allparts,
        $carData->allowners->allbrands->allparts
    );

And then check each value in the array using a foreach loop which ends when the condition isset evaluates to true. The first property to evaluate to true is then returned which in turn breaks you out of the function (credit to Brett for the insight).

    foreach ($is_set as $this_set) {
        if isset($this_set) {
            return $this_set;
        }
    }

Putting it all together would look like:

function getCarPartColor($carData, $owner, $brand, $part) {

    $is_set = array (
        $carData->{$owner}->{$brand}->{$part},
        $carData->{$owner}->{$brand}->allparts,
        $carData->{$owner}->allbrands->allparts,
        $carData->allowners->allbrands->allparts
    );

    foreach ($is_set as $this_set) {
        if isset($this_set) {
            return $this_set;
        }
    }
}


Simulation study in R with two variables and 10000 iterations

Possible Bug

If I understand what you are trying to do correctly, the lines...

DVcontrol <- rnorm(iter, mean=0, sd=1)
DVexperiment <- rnorm(iter, mean=ES, sd=1)

...should probably be

DVcontrol <- rnorm(SS, mean=0, sd=1)
DVexperiment <- rnorm(SS, mean=ES, sd=1)

This was noted in the comments by @flodel.

Identifying slow steps

The best way to figure out what lines of the code are slowest is to use a line profiling tool.  I like profvis.  In general, the slow steps in R are element-wise assignment to vectors/matrices/data.frames, and unvectorized functions.  In your case,

p.rep[i] <- t.test(DVdiff, alternative="greater")$p.value
d.rep[i] <- mean(DVdiff) / sd(DVdiff)

are likely to be slow. And the t.test() function in R is unvectorized as also a bottleneck.

Possible solutions

Vectorization of assignments

I'm a big fan of the tidyverse system of packages.  For this case, the tidyr, purrr, and dplyr system of packages allows a very nice functional implementation of your problem.  However, they won't automatically vectorize functions like t.test().

Vectorization of t.test()

Googling around, it appears there are a few vectorized implementations of t.test().  One I found easy to use is from the genefilter package, colttest().  And although it isn't as much of a bottleneck, I also used a vectorized computation of d by using the colSds() and colMeans() functions from matrixStats.

Putting it together

Below I implement some of what your original code does.  I didn't worry about the particular flavor of t-test that you were using (i.e. alternative = "greater"), and I didn't implement computing the correlation between p.values.

require(tidyverse)
require(purrr)
require(genefilter)
require(matrixStats)

N_ITER <- 10000
effect_size_range <- seq(0, 2, 0.5)
sample_size_range <- seq(10, 1000, 100)
test_or_repeat <- c('test', 'rep')

input <-
    expand.grid(effect_size_range, sample_size_range, test_or_repeat)
names(input) <- c('ES', 'SS', 'test_or_rep')

output <-
    input %>%
    group_by(ES, SS) %>%
    mutate(ctrl = map(SS, ~rnorm(.x * N_ITER)),
           expt = map2(SS, ES, ~rnorm(.x * N_ITER, mean=.y)),
           diff = map2(expt, ctrl, ~ .x - .y),
           diff.matrix = map(diff, ~matrix(., nrow=N_ITER)),
           p = map(diff.matrix,  ~colttests(., gl(1, nrow(.)))$p.value),
           d = map(diff.matrix, ~colMeans(.)/colSds(.)),
           mean.p = map(p, ~mean(.)),
           mean.d = map(d, ~mean(.))
          ) %>%
    select(ES, SS, test_or_rep, mean.p, mean.d) %>%
    unite(p_and_d, mean.p, mean.d, sep='___') %>%
    spread(test_or_rep, p_and_d) %>%
    separate(test, c('p.test', 'd.test'), sep='___') %>%
    separate(rep, c('p.rep', 'd.rep'), sep='___')

This run, which covers about 1/5th of the effect sizes and 1/10th of the sample sizes you are interested in, takes about 5 minutes to run on my laptop.  Since it uses N_ITER = 10000, I think scaling up to your full system size would take about 50 times this number, or about 4 hours.  The bottlenecks here are still the t-tests, but also simply calling rnorm, a sign that we got rid of the assignment-by-element bottlenecks and reduced the t-test bottlneck at least somewhat.


Add a number to a number to be prime number in python

To be cheeky, the ultimate optimization is "don't use Python for numerics", and the next-best optimization is "use a library rather than writing this yourself".
It's worth having a read through https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python
Also consider calling into https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime .
Otherwise:
Roots
I do not trust Python to do the right thing here:
b**(0.5)

Just call isqrt instead, which will be more likely to get an optimized implementation. This is confirmed here: https://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx
Variable names
You need to get out of the habit of single-letter variable names. I have no idea what b means other than inferring based on context.
Time measurement
Use timeit. Your current implementation only has a single iteration for each of the input values and is thus extremely vulnerable to CPU thread-switching noise, etc.


What do you think?

For learning RAII/resource management, it's a good idea to write your own smart pointer class. For production code, use std::shared_ptr, std::unique_ptr, or boost smart pointers (if you have to).

Here are some notes on the code itself:

The code only compiles if you add:

Code:

#define destructor ~

Don't do that! It simply increases the WTFPLOC ("what the fuck!"s per lines of code) ratio of your code and even if it seems like a nice idea now, you will (most probably) not consider it a good idea one year from now, looking at the code.

MemWrp should:

store the data in a strongly-typed pointer (that means, make it a template by pointer type); Otherwise, when you delete it will not invoke the right destructor type unless you use a cast.
be a private part of the Ref class; It's an implementation detail; you should not need to create instances of it outside of Ref implementation, and you should not pollute the global namespace with the class name.
Use a better name; While using shortened words for names (i.e. MemWrp instead of MemoryWrapped/MemoryWrapper/MemoryWrap etc), this is only a good idea if the shortened words are traditionally used for replacement (e.g. "ptr" for "pointer" is fine, "Mem" for "memory" is fine, "Wrp" can be expanded into about five words easily and leads to confusion).
protect it's managed resource (why is MemWrp::content public?)

Ref class should:

be renamed to _Something_Ptr or Ptr_Something_ ("Ref" traditionally represents a reference which has/should have reference semantics). See std::ref and std::cref for comparison. Examples: Shared_Ptr, CountedPtr, ManagedPtr, SmartPtr, etc. Just don't call it Ref.
Not allow construction from a pointer converted to int.

The interface of the class suggests that this code is perfectly legal:

class Qxb; // implementation is irrelevant
Ref<Qxb> ref(101); // good luck dereferencing this pointer

Ref class should (continued):

Not need C-style (or any other style) casts; They are not only unnecessary, they are a symptom of bad implementation or design.
Disallow construction of a Ref instance from a MemWrp instance, especially since the MemWrp class is not strongly-typed on the stored content.
not implement equality comparison with ints. Your class doesn't store ints, it should not have a value equal to them. This will (probably) lead to problems in client code.


Optimal way to filter DataFrame by many arguments, without usage of multiple ifs and for loops

Comparisons to None should always be done with is or is not. This is because None is a singleton object and this will give you the right behavior even if you override some objects __eq__ method or similar. This is mentioned in Python's official style-guide, PEP8. It also recommends no spaces around = for keyword arguments and using lower_case for variables and functions.

As to your actual question, what you really want to do is apply some function (fitting and plotting) to either the whole dataset or grouped by one or more categorical values.
The latter is what pandas.DataFrame.groupby is for.

kmf = KaplanMeierFitter()

def plot_fit(df, fig, name='Survival function'):
    results = kmf.fit(df['TIME'], df['EVENT'])
    trace_df = results.survival_function_.copy()  # Is this copy really needed?
    fig.add_trace(go.Scatter(
        x=trace_df.index,
        y=trace_df.iloc[:,0],
        mode='lines',
        name=name
    ))

def do_fit(df, by=None):
    fig = go.Figure()
    if by is None:
        plot_fit(df, fig)
    else:
        for group, df2 in df.groupby(by):
            name = ...  # Somehow determine label from group
            plot_fit(df2, fig, name)
    fig.update_layout(showlegend=True)
    return fig

This function can be called either as do_fit(df), do_fit(df, "PROTOCOL") or do_fit(df, ["PROTOCOL", "MUTATION"]). The group variable is a tuple telling you which protocol and/or mutation it is, extracting a correct label from this is left as an exercise. I also omitted getting the dataframe with your getter function and other preparations. These should probably be done in the function calling this function.

It could be argued that this should be divided up even further and the fitting should be separated from the plotting.


Java application for finding permutations efficiently

First of all, please write a single function instead of expanding what is essentially the same code three times!

long factorialN = n;
for (int ForN = n; ForN <= n && ForN > 1; ForN--) {
    factorialN = factorialN * ForN;
}
factorialN = factorialN / n;

Also, if your for-loop counter will start at N and only decrement, you do not need to check in every iteration whether it is less than or equal to N; it is guaranteed to be. You only need to check if it is greater than 1. But that incurs no performance penalty, since the Java compiler is clever enough to disregard your superfluous check.

Now, if you want a faster factorial implementation, you can use a recursive one, like the one described in this page. It is in C#, but you should have no problem converting it to Java. The only thing is, you need to gain knowledge of what recursion really is before trying to pass this as a piece of code you understand.

Or, you could use something far more advanced, like the asymptotic prime factorization algorithm described on this page, though you will have a very hard time convincing your teacher that you, an 8th grader, have the slightest clue as to how this algorithm works, and why, so better stay away from it!


Singleton

There is a definite argument that a Singleton is an anti-pattern.  I won't go into it too much, but just to make it not link-only:

Singletons are hard to unit test, as of course you can only have one.
It's hard to reuse a Singleton if you suddenly find yourself needing two.  E.g. if you have a similar API, you have to copy the whole Singleton even though most of the code is the same.

What should you do instead?  Alternatives to Singleton.

In particular, consider a pattern like

CredentialsHolder apiCredentials = CredentialsHolder.getInstance("api_credentials.txt");

Behind the scenes, this might do a lookup in an instance table.  If found, use it.  If not found, create it.

So

           if (instance == null)
               instance = new CredentialsHolder();

becomes

           CredentialsHolder instance = credentials.get(apiFileName);
           if (instance == null) {
               instance = connectToApi(apiFileName);
               credentials.put(apiFileName, instance);
           }

Configure outside the code

This also moves the login information out of your code and into configuration.  This is often helpful in that you want to share your code but not your configuration.  That is to say, your login information is private, but you are posting your code publicly.  What if you forgot to obscure the info?

Curly brackets

I personally prefer the block form of control structures even when there is only a single statement.  If you do use the single statement form, consider putting it on the same line, e.g.

           if (instance == null) instance = new CredentialsHolder();

But of course, that won't work in my revised code, which has a two statement block.

The counter-argument is that it's not actually necessary in your original code.  But neither is it harmful in your original code.  I find a simple bright line rule of always using them better than trying to evaluate each situation.  This is especially true as the coding situation often changes quickly and in surprising ways.  Using the {} will always work.

Paragraphing

                Map headers = new HashMap();
                headers.put("userName", API_USER_NAME);
                headers.put("password", API_PASSWORD);
                Map criteria = new HashMap();
                criteria.put("headers", headers);
                criteria.put("url", API_BASE_URL_V1 + API_LOGIN_TOKEN_PATH);
                Map response = new ExternalAPICaller().httpGet(criteria);
                Map responseHeaders = ((Map) response.get("headers"));
                System.out.println(responseHeaders);
                loginToken = (String) (responseHeaders.get("Token"));
                try {
                    loginTokenExpiry = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a").parse((String) (responseHeaders.get("TokenExpiry")));
                } catch (ParseException e) {
                    e.printStackTrace();
                    loginTokenExpiry = null;
                }

That's a wall of code, which makes it harder to read.  Consider

                Map<String, String> headers = new HashMap<>();
                headers.put("userName", API_USER_NAME);
                headers.put("password", API_PASSWORD);

                Map<String, Map<String, String>> criteria = new HashMap<>();
                criteria.put("headers", headers);
                criteria.put("url", API_BASE_URL_V1 + API_LOGIN_TOKEN_PATH);

                Map<String, Map<String, String> response = new ExternalAPICaller().httpGet(criteria);
                Map<String, String> responseHeaders = response.get("headers");
                System.out.println(responseHeaders);

                loginToken = responseHeaders.get("Token");
                try {
                    loginTokenExpiry = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a").parse(responseHeaders.get("TokenExpiry"));
                } catch (ParseException e) {
                    e.printStackTrace();
                    loginTokenExpiry = null;
                }

Now it's much easier to see what code goes with what, because the blank lines (vertical whitespace) separate the blocks of code.

You also might consider moving the try/catch block into a separate method.  Then you could say something like

                loginTokenExpiry = parseTokenExpiry(responseHeaders.get("TokenExpiry"));

Don't use raw types

I changed all the raw types to parameterized types.  It's possible that that only works for the ones that you create, like headers and criteria, but I changed all of them.  Change the latter ones back if ExternalAPICaller won't work with them.  And then tell these External people to fix their API.

This eliminates the need to cast the results of get and avoids a compiler warning in some configurations.


Efficient pathfinding without heuristics?

Complete and Incomplete Algorithms

Search algorithms can be classed into two categories: complete and incomplete.

A complete algorithm will always succeed in finding what your searching for. And not surprisingly an incomplete algorithm may not always find your target node.

For arbitrary connected graphs, without any a priori knowledge of the graph topology a complete algorithm may be forced to visit all nodes. But may find your sought for node before visiting all nodes. A* is a complete best-first method with a heuristic to try to avoid searching unlikely parts of the graph unless absolutely necessary.

So unfortunately you can not guarantee that you will never visit all nodes whatever algorithm you choose. But you can reduce the likelihood of that happening.

Without pre-processing

If you cannot consider pre-processing your graph then you're stuck with a myriad of on-line algorithms such as depth-first, breadth-first, A* and greedy-best-first. Out of the bunch I'd bet on A* in most cases if the heuristic is even half good and the graphs are non-trivial.

If you expect all routes to be short, a breadth-first algorithm with cycle detection and duplicate node removal may outperform A* with a poor heuristic. I wouldn't bet on it though, you need to evaluate.

With pre-processing

In your case I'd see if I could pre-process the graph, even if you need to repeatedly re-do the pre-processing when the graph changes as long as you do sufficiently many searches between pre-processing it would be worth it.

You should look up Floyd-Warshall (or some derivative) and calculate the pairwise cost/distance/jumps between all nodes and use this table as a heuristic for your A*. This heuristic will not only be admissible, it will be exact and your A* search will complete in no-time.

Unless you of course modify the algorithm to store all pairwise routes as they are detected in a matrix of vectors, then you have O(1) run time at the cost of memory.


Four-function and exponentiation console calculator

I'll mention some additional points that haven't been mentioned yet, but this does look like it can still be cleaned out quite a bit.

You could define those functions above main() so that prototypes won't be needed.  Otherwise, put them above main(), as already mentioned in another answer.
These:

#include<iostream>
#include<cmath>
#include<cstdlib>

would look nicer with spaces:

#include <iostream>
#include <cmath>
#include <cstdlib>

Regarding spacing, you have some inconsistent spacing around the cases.  Try not to neglect this as it could make your code more awkward to read for others.
type, x, and y are all declared outside of the loop, but are only used inside of the loop.  In order to help keep track of them, declare them right where they're first used.  Doing this with every variable can help with maintaining cleaner code, especially with larger programs.
This is not doing what you expect:

while (x != 0, x--)

The comma operator returns the result of the last expression, which is the x--. The other expressions are evaluated (from left to right) but the results of the expression are ignored.  Thus, the result of x != 0 is evaluated with no side affects and the result dropped. This makes the expression equivalent to while (x--).
You don't check for division by 0, so your program can break if this operation is done.  You may throw an exception for that and handle it, so that you can get a different input.  Just make sure this division doesn't happen.
You don't need return 0 at the end of main().  The compiler will do this return for you after reaching this point.


Comparator based on Double values in Java

Your question does not show how you call/use the Comparators you have defined. Despite that, there are a number of issues I see with your code, and feel I should point out....

When you have data that is sorted, the data tends to last around for a while, and sorted-data is often a very important assumption for complex processing (i.e. if the data was not sorted correctly the computations will fail).

Whenever you have sorted data, and Comparable data, the data should almost always be immutable (cannot possibly change). If the data can change after the sort happens, then the sorted data is no longer sorted.

So, your Point class should probably be an immutable class. At the moment, it has a number of problems with that:

The member fields should be final.
There should be 'getters' for the fields, and the fields themselves should be private (not public like you have).

Your class should look more like:

public static final class Point{
    private final int id;
    private final double x;
    private final double y;

    Point(int id, double x, double y){
        this.id = id;
        this.x = x;
        this.y = y;
    }

    public int getID() {
        return id;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    .....

ahhh, I see skiwi just answered a bunch... I'll cover some other stuff from here on....

Reiterating his comments:

the equals and hashCode method he suggests are very important (I was about to add that too).

Right, when you have value-based items like this, it is often convenient to make the Point have a 'natural' ordering. This means that the Point class should implement Comparable<Point>, and then implement the compareTo(Point other) method.

Having two comparators is a problem, you only want one, that does both coordinates.

Consider a compareTo() method like:

public static class Point implements Comparable<Point> {

    ....

    public int compareTo(final Point other) {

        if (other == null) {
            // non null always comes after null
            return 1;
        }

        final int xcomp = Double.compare(this.x, other.x);

        return xcomp == 0 ? Double.compare(this.y, other.y) : xcomp;
    }

This will be one comparator that does both axes.

Then, you can use this Point as a natural sort order, and use it as a key in a TreeMap, and or things like Arrays.sort(pointarray), etc.

Note, I reused the comparison function Double.compare() to do the heavy lifting of the compare.


Before even thinking about performance, concision, etc., run JSLint or similar over these methods and fix the indentation, other whitespace, and bugs. As it is the lack of consistency and poor indentation makes it hard to read and hides things like a missing comma which is leading to implicit semicolon insertion:

        var randomIndex = Math.floor(Math.random() * len),
        pivot = arr.splice(randomIndex, 1),
        lesserHalf = arr.filter(el =>el <= pivot)
        biggerHalf = arr.filter((el)=> el > pivot)

These four lines also look buggy because pivot is an array and yet it's being compared to an element with <= and >.

        var randomIndex = Math.floor(Math.random() * len),
            pivot = arr.splice(randomIndex, 1)[0],
            lesserHalf = arr.filter(el => el <= pivot),
            biggerHalf = arr.filter(el => el > pivot);

is more consistent, more obviously correct, and fixes at least one bug.

Example 3 also looks buggy.

const quickSort = ([x = [], ...xs]) => {
  if (x.length === 0) return [];

How will this sort ["", "a", "b"]? Answer: it will return [].


Script that parses the Chase.com page for my recent payments

Single responibility principle

You method violates the SRP because it does to many things.

it parses HtmlElements for 3 different types
it validates the resulting List<T>
updates the UI

If you need comments like

//Parse for date
//Parse for description
//...

then it is a clear sign that these parts should be extracted to separate methods.

A much cleaner way would be

private const string dateRegexPattern = @"^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d$"
private List<string> ParseForPurchaseDates(HtmlDocument document)
{
    var purchaseDates = new List<string>();

    var links = document.GetElementsByTagName("span");

    foreach (HtmlElement link in links)
    {
        if (link.InnerText == null) { continue; }

        string inner = link.InnerText.Trim();
        if (inner == "Pending" || Regex.IsMatch(inner,dateRegexPattern ))
        {
            purchaseDates.Add(inner);
        }

    }
    return purchaseDates;
}

if you do this for the other parsings too, your click eventhandler could look like

private void stepBtn_Click(object sender, EventArgs e)
{
    List<string> date = ParseForPurchaseDates(wb.Document);
    List<string> desc = ParseForPurchaseDescriptions(wb.Document);
    List<double> amt = ParseForPurchaseAmounts(wb.Document);

    if (ListCountIsValid(date, desc, amt))
    {
        // update the UI
        return;
    }

    MessageBox.Show("The three arrays do not have the same length.\n\nDate: " + date.Count + "\nAmt: " + amt.Count + "\nDesc: " + desc.Count, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

private bool ListCountIsValid(List<string> purchaseDates, List<string> purchaseDescriptions, List<double> purchaseAmounts)
{
    return purchaseDates.Count == purchaseAmounts.Count
        && purchaseDescriptions.Count == purchaseAmounts.Count;
}

For the parsing of the amount I would like to suggest to add a second parameter which should be optional to replace the hardcoded value 1000.

private List<double> ParseForPurchaseAmounts(HtmlDocument document, double maxAmount = 1000d)
{
    //....
}

Naming

Naming is a very important part of programming. Using abbreviations instead of the complete word will reduce readability and makes it hard to maintain. So give Bob the maintainer a chance to do his/her job easy and fast by using proper names.

amt should be e.g amounts or purchaseAmounts ...


handle more possibilities

Anything touching the file system can fail.

mkdir You could have permission problems or something else.  Do mkdir foo || exit 3.  Feel free to replace the exit with your own function for error handling.
cd is the same deal as mkdir
check for the existance of your directory before lsing it: if [[ -d $PlaceLogs ]]

Also, do any bz2 exist after the sftp?  You should check before bunzip'ing them.

You can safely ignore all of these things too, but since you specifically asked about error handling it seemed good to point them out.  If this is a critical piece of software then I would build a way for these failures to raise alerts with your DevOps team.

shellcheck.net

Run all of your scripts through http://www.shellcheck.net/ until you get in better habits.

use double square brackets

Double square brackets are better than single square brackets.  They have less surprises.  The primary one is that if you have an empty variable you can do

if [[ $FOO == "" ]]

where single brackets require a placeholder so none of the arguments disappear if missing:

if [ x$FOO == "x" ]

Without the xs the $FOO would disappear as a shell argument when empty.


PeopleObjects is an odd name for a couple reasons:

Both words are plural, even though each instance only represents a single person.
Having "object" in the name is a little redundant. It's implied that the class is representing an  object.

I'd just call the class Person.

And you didn't give PeopleObjects a constructor. You're constructing an instance of the class ahead of time, then asking for input and calling the setters. What if you forgot to set the birthday or name? They would be left as null and potentially cause problems later. If properties are required (which both name and birthday would presumably be), have them supplied by a constructor:

public Person(String name, String birthDay) {
    this.name = name;
    this.birthDay = birthDay;
}

. . .

List<Person> people = new ArrayList<Person>();

Scanner input = new Scanner(System.in);

System.out.println("Enter any number other than 1 to start program."+"\n");

while (input.nextInt() != 1){
        // This is needed since nextInt doesn't consume the newline
        input.nextLine();

        System.out.println("\n###What is the name of the person?###\n");
        String name = input.nextLine();

        System.out.println("\n###What is their birthday?###\n");
        String birthday = input.nextLine();

        Person person = new Person(name, birthday);

        people.add(person);

        System.out.println("\nDo you want to quit and see list? Enter 1 for yes and 0 for no\n");
}

I changed a few things about that loop:

As mentioned above, the person isn't constructed until the necessary data is already obtained, and the data is passed directly to the constructor.
userChoice was never used. It was just storing the users entry, but that choice was only ever used in the condition. If you really wanted it for debugging purposes, it may be appropriate, but I didn't think that it was necessary here.
I renamed the list of people to simply people. This was replacing your PeopleObjects people = new PeopleObjects(); line. Again, calling a single person people is confusing. I also changed the type of people to List, from ArrayList. Always use the broadest type possible. In this case, you don't need any operations specific to ArrayList; you're only using List methods. To see why this is important, give this a read over. Note the example used in the question.

Your other loop at the bottom is sub-optimal as well. First, you're constantly writing people.get(i). For an ArrayList, get is very fast, but those calls are causing unneeded bloat. Create an intermediate variable person in the loop to neaten things up:

for(int i = 0; i < people.size(); i++) {
    Person person = people.get(i);
    String name = person.getName();

    if(name.equals("Joe")) {
        System.out.println("Happy Birthday Joe! You are special! Your birthday is on "
                           + person.getBirthDay() + " \n");

    } else if(i % 2 == 0) {
        System.out.println("Happy Birthday to " + name + ".\n");

    } else {
        System.out.println("Happy Birthday to " + name + " too!!!\n");
    }
}

I ended up creating a name variable as well since the name of the person was needed in multiple places.

You also had inconsistent spacing that I corrected. Some places had everything all smooshed together, and then other places (like with ==) had spacing. I added spaces around all the operators, then broke up one of the longer lines. I also added empty lines after each println call so the cases were a little more distinct.

Unless you need the i % 2 == 0 check to give a special message to every arbitrary second person, this loop could be slightly simplified by using an enhanced for-loop that doesn't rely on indices:

// Read as "for each person in people"
for(Person person : people) {
    String name = person.getName();

    if(name.equals("Joe")) {
        System.out.println("Happy Birthday Joe! You are special! Your birthday is on "
                           + person.getBirthDay() + " \n");

    } else {
        System.out.println("Happy Birthday to " + name + " too!!!\n");
    }
}


Command-line implementation of Mastermind

Simple things you can improve:

12 is a magic number in your code, you can move it to a constant.
I think TURNS.times do |turn| ... is better than the while loop because you don't have to keep track of the counter.
When you're passing a simple space (" ") to the method split you can just call split instead, without passing any argument.
When the block has multiple lines it is a good practice to use do and end instead of brackets.
I think you can use the select method and assign the result directly to the correct_colors variable.
I think it would be better to call Game.new.start_game instead of Game.new, for me, it isn't intuitive that the game will begin just by instantiating the Game class.
You can make some methods private because you are not calling them on the instance.


"Impossible" check

Per task description, k >= 2 and n >= 3. But nevertheless you're performing this "impossible" check:

if (n < 3 || k < 2) return 0;

Redundant check

I don't understand why you're checking cases n == 3 separately. You could remove these 2 checks and have this case handled in your for loop quite easily as below (please note that the values of i, countOne and countOther have changed):

long countOne = 0, countOther = 1, temp;
for (int i = 3; i < n; i++) {
    temp = countOther * (k - 1) % MOD;
    countOther = (countOne % MOD + countOther * (k - 2) % MOD) % MOD;
    countOne = temp;
}

Variable naming

countOne or countOther are not a good way to call your variables - their names don't convey their purpose. I'll leave it up to you to come up with better names.

Excessive modulo operation

You don't have to perform a modulo operation more times than is needed. Given you task constraints, your can perform a modulo operation twice per iteration as below:

temp = countOther * (k - 1) % MOD;
countOther = (countOne + countOther * (k - 2)) % MOD;
countOne = temp;

Reduce scope of temp

As @Barmar correctly pointed out, your temp variable should be local to the for loop. It's not needed anywhere out of it.

Simplify return statements

You don't have to calculate countOne or countOther once you leave the for loop. You can do it all there, just fix your loop condition from i < n to i <= n and swap countOne with countOther in your return statements.

for (int i = 3; i <= n; i++) {
    long temp = countOther * (k - 1) % MOD;
    countOther = (countOne + countOther * (k - 2)) % MOD;
    countOne = temp;
}

if (x == 1) {
    return countOne;
}

return countOther;

Final Code

public static long countArray(int n, int k, int x) {

    long countOne = 0, countOther = 1;
    for (int i = 3; i <= n; i++) {
        long temp = countOther * (k - 1) % MOD;
        countOther = (countOne + countOther * (k - 2)) % MOD;
        countOne = temp;
    }

    return x == 1 ? countOne : countOther;
}