Here are some comments and an example rewrite of your code.

Indentation and line breaks are not idiomatic to OCaml, it's good practice in any language.

A more intuitive type for is_prime would be to have only one argument, so let's encapsulate is_prime_rec:

let is_prime =
  let rec is_prime_rec number start =
    if start * start > number then true (* OCaml provides a type `bool`, distinct from `int`, so it's better to return `true` instead of `1`. *)
    else if number mod start = 0 then false
    else is_prime_rec number (start+1) in
  fun n -> is_prime_rec n 2;;

which yields val is_prime : int -> bool = <fun>.

You know the number of iterations in the loop, so better use for rather than while.
This also avoid manually incrementing i.

let sum = ref 0 in
for i = 2 to 2_000_000 do (* detail: OCaml parses `2_000_000` as `2000000`, which is more readable. *)
  if is_prime i then (* no need for parentheses around the if clause *)
    begin
      sum:= !sum + i;
      Printf.printf "%d is prime, it is prime number %d\n" i !sum;
    end
done;;

I can't help but add an algorithmic remark: consider using a sieve.


Repeatedly incrementing array elements using OpenCL

Sorry, but this is a general review and will not answer your specific question. While this is a simple test program, it is good to develop some habits in writing C or C++ programs.

Complexity
One of the good habits to keep in mind is the Single Responsibility Principle which states

  "every module, class, or function should have responsibility over a
  single part of the functionality provided by the software, ...".

The Single Responsibility Principle is the first pillar in SOLID programming. SOLID programming is a set of principles that generally improve object oriented programming.

The code is too complex to be in one function, main() could be divided into may functions that would make it easier to read and debug. Generally main() should do the following when necessary:
 - call a function to process command line arguments.
 - call functions to set up for any processing
 - call one function to do the processing, this function may call
   many other functions
 - call functions to clean up after processing

In this program there doesn't seem to be any command line arguments so that function isn't necessary. Some possible functions called by main():
 - Set Up Platforms
 - Set Up Devices
 - Set Up Program
 - Set Up Queues
 - Execute Program
Any or all of these functions can return bool or int to indicate success or failure

Use System Defined Constants to Make Code More Readable
Rather than using return(1); or return(0) in main there are constants defined in cstdlib or stdlib.h that indicate success or failure of a program, these are EXIT_SUCCESS and EXIT_FAILURE. Since they are system defined they are more portable than zero or one. They also make the code self documenting:

    return(EXIT_SUCCESS);

    return(EXIT_FAILURE);

Avoid the Use of the Exit Function in C++ and C
The code is good in that it only calls std::exit() from main(), however, it is generally a bad idea to call std::exit() especially from functions that are not main(). When calling exit from a function other than main no cleanup code will be called and if the program is a program that shouldn't terminate such as an operating system there can be dire side effects. Even calling exit from main may not clean up after processing as explained in this stackoverflow.com question. The accepted practice is to call return from main.


Some thoughts:

I find your method naming to be really confusing. To me, if I called methods named .day(), .month(), year(), etc. I would be expecting methods named in this manner to behave more like a getter than a setter.

For example, this usage seems very confusing:

new HumanDate().day(-1).day()

Consider naming like modifyDay(), modifyMonth(), etc.

You have unnecessary else conditions.

For example:

if (numOfDays === undefined) {
    return date.getDate();
}
else {
    date.setDate(date.getDate() + numOfDays);
    return this;
}

Could more clearly be written as:

if (numOfDays === undefined) {
    return date.getDate();
}

date.setDate(date.getDate() + numOfDays);
return this;

Here there is no need for else since if returns.

The dayOfWeek() method looks odd.  Why convert Sunday to Monday in all cases?
toJSDate() seems like an odd name for a function. The word "to" tends to connote cases where some casting or data transformation might take place.  Here you are just returning the underlying date Object. Maybe just getDateObj() or something more descriptive of what is happening. Of course, the caller can always just access the .date property of the object to get the same result.
I think some of the logic you are applying to try force you week to start on a certain day, might best be something you want to specify in configuration on instantiation, or via more appropriate specificity around methods that deal with work week constructs. Just totally re-mapping the days returned by underlying Date object seems to sort of hide this away from the caller.
I think that perhaps you might need to look at the time component here as well.  To me, if I am trying to get the beginning of a week or month, I would be expecting to get 00:00:00 as the time component. On the other hand, if maybe the methods were named something like modifyToBeginningOfMonth() perhaps the current behavior would be more expected.
Consider passing the Date object dependency in the constructor.  Right now you limit this class to only working with Date object for current timestamp.  If you took a Date object as parameter, you could set this Date object on your HumanDate object as is currently done, but allow the caller to fully utilize the capabilities of Date to set the timestamp to whatever they want to start with.  This also makes the dependency of this class really clear.
You might give consideration to defining this class more as an extension of the underlying Date class.  That way you can eliminate needing to wrap underlying date properties and methods.


IService or defining IProductService, ICustomerService

It makes perfect sense to define such generic interface as long as there is a generic consumer that can do some useful work with any of the implementations.
And I suppose there is in this case.
If I were to guess, I'd say the tutorial did not include generics just because that is a feature that might not be familiar to the audience that the tutorial was pointing at.
As @Hayden already mentioned, IService<T> is not a very useful name. Let me call it IEntityListProvider<T> instead.
I can imagine the common consumer could be a single route controller.
Let me first a define a simple routing framework to provide some context:
// IRequest and IResponse are models of HTTP request resp. response
interface IRequestHandler
{
  public Task<IResponse> HandleAsync(IRequest request);
}

interface IRouterBuilder
{
  // register a GET route handler
  public void Get(string path, IRequestHandler handler);

  // build the router instance
  public IRequestHandler Build();
}

now we can implement the generic consumer like this:
class EntityListRouteHandler<T> : IRequestHandler
{
  private IEntityListProvider<T> Provider;

  // add constructor to take the dependency

  Task<IResponse> HandleAsync(IRequest request)
  {
    // get the list from provider
    // and convert the list to a response in a way
    // that's going to be the same for all entities
  }
}

and somewhere in router factory you would do somethig like this:
RouterBuilder.Get('/categories', new EntityListRouteHandler<Category>(categoriesProvider));
RouterBuilder.Get('/products', new EntityListRouteHandler<Product>(productProvider));
RouterBuilder.Get('/customers', new EntityListRouteHandler<Customer>(customersProvider));

Now I would like to expand on @Hayden's answer.
Ad 1) he mentions that if a PasswordService were to exist, it would probably not need a ListAsync method. Well, that's true, but it's misleading because it is irrelevant. Such a service would simply not implement the IEntityListProvider<T> interface.
Ad 2) if some service needs some more methods, then I would ask mayself is there someone who needs those methods at the same time? If yes just create a new interface extending the base one. If not, just define a new separate interface. Whether the concrete class implements two interfaces or you simply provide two different classes to implement each of the two interfaces is up to you. But a separate class for each interface feels like it better follows SRP.
I would add one more note regarding pagination. It is not very wise to provide the lists of entities without any limit. The momory consumption of such program is then out of control unless there is some logic that prevents too many entities to exist in the first place. Your ListAsync method should have arguments for pagination and possibly filtering and sorting as those are very common things to do with list resources. The type of these arguments may as well be generic arguments of the interface. I.e. Task<IEnumerable<T>> IEntityListProvider<T, F, S, P>::ListAsync(F filter, S sort, P page) or so...


Algorithm

The beginning of the mathematical analysis is very nice and well explained. Maybe it would be nice to have it in your code as a comment.

Also, please note that if what you really care about is the number of lockers open (or closed), it is just a matter of computing a square root.

Separation of concerns

The biggest issue in your code is that you have a function doing everything : handling user input, string formatting, updating globals... This makes your code hard to follow and hard to test. A better way to do it would be to have smaller units (functions or sometimes classes and modules) with a single responsability.

By doing so, you could get rid of the globals and write the code like this :

# 100 Locker Problem

def get_open_lockers(num_lockers):
    open_list = []
    num = 1
    while num**2 < num_lockers:
        open_list.append(num**2)
        num += 1
    return open_list

def format_output(nb_lockers, open_list):
    endings = ["st", "nd", "rd", "th"]
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    return_str = "The "
    for index in range(0, len(open_list)):
        if index == (len(open_list) - 1):
            if str(open_list[index])[-1:] == "1":
                return_str += ("and " + str(open_list[index]) + endings[0])
            elif str(open_list[index])[-1:] == "2":
                return_str += ("and " + str(open_list[index]) + endings[1])
            elif str(open_list[index])[-1:] == "3":
                return_str += ("and " + str(open_list[index]) + endings[2])
            else:
                return_str += ("and " + str(open_list[index]) + endings[3])
        else:
            if str(open_list[index])[-1:] == "1":
                return_str += (str(open_list[index]) + endings[0] + ", ")
            elif str(open_list[index])[-1:] == "2":
                return_str += (str(open_list[index]) + endings[1] + ", ")
            elif str(open_list[index])[-1:] == "3":
                return_str += (str(open_list[index]) + endings[2] + ", ")
            else:
                return_str += (str(open_list[index]) + endings[3] + ", ")
    return_str += " locker(s) will be open."
    print return_str
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

while True:
    try:
        nb_lockers = int(raw_input("How many lockers will there be: "))
    except ValueError:
        print "Please insert an integer"
    else:
        open_list = get_open_lockers(nb_lockers)
        format_output(nb_lockers, open_list)

Look like a native

Almost everytime you do range(len(list)), you are not doing things the right way. I highly recommend Ned Batchelder's excellent talk called "Loop like a native".

In your case, the code becomes (l stands for locker which is probably not the best name):

def format_output(nb_lockers, open_list):
    endings = ["st", "nd", "rd", "th"]
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    return_str = "The "
    for i, l in enumerate(open_list):
        if i == (len(open_list) - 1):
            if str(l)[-1:] == "1":
                return_str += ("and " + str(l) + endings[0])
            elif str(l)[-1:] == "2":
                return_str += ("and " + str(l) + endings[1])
            elif str(l)[-1:] == "3":
                return_str += ("and " + str(l) + endings[2])
            else:
                return_str += ("and " + str(l) + endings[3])
        else:
            if str(l)[-1:] == "1":
                return_str += (str(l) + endings[0] + ", ")
            elif str(l)[-1:] == "2":
                return_str += (str(l) + endings[1] + ", ")
            elif str(l)[-1:] == "3":
                return_str += (str(l) + endings[2] + ", ")
            else:
                return_str += (str(open_list[i]) + endings[3] + ", ")
    return_str += " locker(s) will be open."
    print return_str
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

Extra Operations (functions calls and slicing)

You keep converting l to str. Maybe you could it once and for all.

Similarly, you keep accessing string[-1:] : it would be nice to do it only once. By the way, the usual way to get the last elements of the list is just [-1] (no need for colon).

def format_output(nb_lockers, open_list):
    endings = ["st", "nd", "rd", "th"]
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    return_str = "The "
    for i, l in enumerate(open_list):
        s = str(l)
        last_dig = s[-1]
        if i == (len(open_list) - 1):
            if last_dig == "1":
                return_str += ("and " + s + endings[0])
            elif last_dig == "2":
                return_str += ("and " + s + endings[1])
            elif last_dig == "3":
                return_str += ("and " + s + endings[2])
            else:
                return_str += ("and " + s + endings[3])
        else:
            if last_dig == "1":
                return_str += (s + endings[0] + ", ")
            elif last_dig == "2":
                return_str += (s + endings[1] + ", ")
            elif last_dig == "3":
                return_str += (s + endings[2] + ", ")
            else:
                return_str += (s + endings[3] + ", ")
    return_str += " locker(s) will be open."
    print return_str
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

Don't repeat yourself

Your have similar logic in the then and else blocks in format_output. This could be factorised out. Also, it would be a good idea to take this chance to extract it out in a function on its own.

def int_to_ordinal(n):
    endings = ["st", "nd", "rd", "th"]
    s = str(n)
    last_dig = s[-1]
    if last_dig == "1":
        return s + endings[0]
    elif last_dig == "2":
        return s + endings[1]
    elif last_dig == "3":
        return s + endings[2]
    else:
        return s + endings[3]

def format_output(nb_lockers, open_list):
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    return_str = "The "
    for i, l in enumerate(open_list):
        if i == (len(open_list) - 1):
            return_str += ("and " + int_to_ordinal(l))
        else:
            return_str += (int_to_ordinal(l) + ", ")
    return_str += " locker(s) will be open."
    print return_str
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

Tiny bug

I've just discovered one bug as I was trying to go further. I imagine it was in the original code but I might be wrong. It happens when there is only one lock open (the first), the formatting gives : "The and 1st locker(s) will be open." which looks a bit weird.

PEP8 and join

There is a style guide for Python code called PEP 8 : it is worth reading (and worth following as much as possible). Your code seems to follow the PEP 8 style for most parts but there is a part you'd be interested in:

  For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

Even though I can safely assume that your code performance is not that important, the join builtin, on top of making your code faster, can make it clearer. You could write something like:

def format_output(nb_lockers, open_list):
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    print "The " + ", ".join(int_to_ordinal(l) for l in open_list) + " locker(s) will be open."
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

(I removed the part with the "And" because it seemed buggy anyway).

If main

In Python, it is recommended to put the part of your code that actually does something (instead of merely defining something) behind an if __name__ == "__main__": so that you can easily run your code as a main program but also import it to be able to reuse the functions/classes you've defined.

if __name__ == "__main__":
    while True:
        try:
            nb_lockers = int(raw_input("How many lockers will there be: "))
        except ValueError:
            print "Please insert an integer"
        else:
            open_list = get_open_lockers(nb_lockers)
            format_output(nb_lockers, open_list)

Optimisation in get_open_lockers

In get_open_locks, you can easily compute the number of iterations you'll need. Also, you could use a list comprehension to avoid calling append many times.

import math

def get_open_lockers(num_lockers):
    if num_lockers <= 0:
        return []
    sqrt = int(math.sqrt(num_lockers-1))
    return [i*i for i in range(1, sqrt+1)]

(It is easy to write tests to ensure that the function returns the same resultats before and after)

Final version of the code

My final code looks like (it can still probably be improved):

import math

def get_open_lockers(num_lockers):
    if num_lockers <= 0:
        return []
    sqrt = int(math.sqrt(num_lockers-1))
    return [i*i for i in range(1, sqrt+1)]

def int_to_ordinal(n):
    endings = ["st", "nd", "rd", "th"]
    s = str(n)
    last_dig = s[-1]
    if last_dig == "1":
        return s + endings[0]
    elif last_dig == "2":
        return s + endings[1]
    elif last_dig == "3":
        return s + endings[2]
    else:
        return s + endings[3]

def format_output(nb_lockers, open_list):
    counter_open = len(open_list)
    counter_close = nb_lockers - counter_open
    print "The " + ", ".join(int_to_ordinal(l) for l in open_list) + " locker(s) will be open."
    print "Open Lockers: " + str(counter_open)
    print "Closed Locker: " + str(counter_close)
    print "----------------------------"

if __name__ == "__main__":
    while True:
        try:
            nb_lockers = int(raw_input("How many lockers will there be: "))
        except ValueError:
            print "Please insert an integer"
        else:
            open_list = get_open_lockers(nb_lockers)
            format_output(nb_lockers, open_list)


Code to classify elements on np.array on lists

You have essentially one chunk of code that's duplicated three times:
list_N = []
a,b,c = 0,0,0
for j in indexes_N[0]:
    if testy_L2[j] == 0.0:
        a += 1
    if testy_L2[j] == 1.0:
        b += 1
    if testy_L2[j] == 2.0:
        c += 1
list_N.append(a)
list_N.append(b)
list_N.append(c)

This could be easily wrapped in a function:
def process_the_stuff(indexes):
    acc = []
    a,b,c = 0,0,0
    for j in indexes[0]:
        if testy_L2[j] == 0.0:
            a += 1
        if testy_L2[j] == 1.0:
            b += 1
        if testy_L2[j] == 2.0:
            c += 1
    acc.append(a)
    acc.append(b)
    acc.append(c)
    return acc

Then just:
list_0 = process_the_stuff(indexes_0)
list_1 = process_the_stuff(indexes_1)
list_2 = process_the_stuff(indexes_2)

I'd clean up some other stuff though:

I'm not a fan of assigning multiple variables on a line in the vast majority of cases. I think a, b, and c should be initially assigned on separate lines.
The three append calls at the bottom could be cleaned up a bit by using extend, or just simply returning a tuple/list directly.
All three if checks are necessarily exclusive of each other (since testy_L2[j] can't be equal to 0, 1, and 2 at the same time). Those should be elifs instead so that once one is true, the others aren't checked.

After fixing these things, you'd be left with:
def process_the_stuff(indexes):
    a = 0
    b = 0
    c = 0
    for j in indexes[0]:
        if testy_L2[j] == 0.0:
            a += 1
        elif testy_L2[j] == 1.0:
            b += 1
        elif testy_L2[j] == 2.0:
            c += 1
    return [a, b, c]  # May make more sense to return a tuple instead unless you need a list

list_0 = process_the_stuff(indexes_0)
list_1 = process_the_stuff(indexes_1)
list_2 = process_the_stuff(indexes_2)

Minor, but "indexes" should be "indices" for the plural of "index".


Simple wrapper to use IEnumerable as a producer in a producer-consumer pattern

I think the implementation is too leaky - it should not expose how the blocking internals are achieved since if if decide do change this you might have to change a whole lot of application code which violates the open-closed-principle (the O part of SOLID). This can be easily fixed by making the class IEnumerable<T> and using GetConsumingEnumerable of the BlockingCollection.
I think the more idiomatic way to start a new task is to use Task.Factory.StartNew.
I would rename it into BlockingEnumerable since that what it is.
Since you're talking about long running operations you may want to add a method of canceling the task.
It might be useful to add a capacity for the intermediate blocking collection as well to provide better control of how much data is cached.

Slightly refactored code:

class BlockingEnumerable<T> : IEnumerable<T>
{
    private readonly BlockingCollection<T> _ProducerCollection;

    public BlockingEnumerable(IEnumerable<T> source)
    {
        _ProducerCollection = new BlockingCollection<T>();
        AddItemsToBlockingCollection(source);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _ProducerCollection.GetConsumingEnumerable().GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    private void AddItemsToBlockingCollection(IEnumerable<T> source)
    {
        Task.Factory.StartNew(() =>
        {
            foreach (var item in source)
            {
                _ProducerCollection.Add(item);
            }
            _ProducerCollection.CompleteAdding();
        });
    }
}


Adjusting integer based on multiple elements in int array

At the risk of being 'clever':

int Blue = 0;
int[] Adjustments = new int[24];
// ... populate Adjustments

for (int blueIndex=0; blueIndex<8; blueIndex++)
{
   if (Adjustments[blueIndex] == 255)
   {
      Blue |= (1 << (7 - blueIndex));
   }
}

Since in effect you're setting bits anyway I think using bitwise operations is idiomatic here.


Determine if Array has an Increasing Sequence

Your code has a bug because it will accept decreasing sequences as true as well, for example, increasingSequence([4,3,2,1]); will be true.

Having said that, you could do the tests a whole lot simpler by using a search:

  const increasingSequence = (arr) => !arr.some((val, idx) => val != arr[0] + idx);

How does that work? Well, each element in the array is expected to be the value of the first item, plus the index address of the current item, so, if the first value is 4 then the 3rd value will be expected to be 6 (4 + 2).

The above code simply looks for any value that does not meet those expectations.

If there is a value that does not meet the expectations, the some returns true, so we negate that, and return false.

Since the some(...) method is a short-circuiting function so it will terminate when the first mismatch is encountered (just like your logic).

Also, note that the short-circuit does not impact the time-complexity of the function, it is still \$O(N)\$ because the performance will scale linearly in relation to the number of elements.

You can see this running on Ideone.


Calculates the number of hours and days left, where the total number of hours is 486

ReuseableClass

Each class is (ok, might be) reusable so naming it like this does not have much value. It calculates something... name it simply IntershipCalculator.

And... it's not really reusable either because you write to the console there. You should write to the console somewhere else and let the methods just calculate the results.

NumberOne

This looks to me like a class but it's a method. You should name it appropriatly ie ReadNumberOne.

        //gets input from user
        int accumHours = AccumulatedHours(dayHours, input);
        int remainingHours = RemainingHours(totalHours, accumHours);
        RemainingDays(remainingHours, dayHours);

The comment is misleading. You are not getting here anything from the user but writing results.

Console.WriteLine("1. Enter No. of Days \n2. Use current day");

Why not like so?

Console.WriteLine("1. Enter No. of Days");
Console.WriteLine("2. Use current day");


Let's talk very generally about AVAudioPlayer.

There are a few relevant methods to discuss here:

play
pause
stop
prepareToPlay

Strictly speaking, prepareToPlay is optional, but if we call play without the player being prepared to play, there will potentially be some latency between calling play and audio actually beginning to play.  If the player wasn't already prepared, the first thing that play will do is prepare it.

From the documentation on prepareToPlay:

  Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.

And perhaps, the important part to read here is that calling stop will undo the set up.  This is repeated in the documentation on stop:

  Calling this method, or allowing a sound to finish playing, undoes the setup performed upon calling the play or prepareToPlay methods.

So, in your specific case, where we have a view controller that does nothing but play "bach.mp3", we should consider never actually calling stop except perhaps in viewWillDisappear.  Calling stop will simply release resources that have to be re-obtained before the track can be played again.  And if we continue reading the documentation for stop, we can see that the behavior of not resetting the currentTime to zero is well documented and to be expected:

  The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off.

So basically, if you're not actually done with that player, stop does the same as pause, but just requires a lot more work.

Realistically, if we want to present to the user behavior which stops the current audio from playing, and will resume the audio from the beginning of the track when play is pressed again (and we have no expectation of starting another track without some other action happening to trigger that), then we should be using pause and then resetting the currentTime to 0.

The only difference between our stop and pause buttons in this specific case should be that stop resets the current time to zero, but both buttons simply pause the player.


That is a huge docstring, it's longer than the code itself. You should read Python's PEP about how to write good docstrings.

For a start a docstring shouldn't contain examples, you can put that as a  regular comment in the script if you want. And you don't need to be so detailed and explicit about the type and optional nature of your parameters. I would take some information out of your parameters and returns sections and just fold it back into your opening section. Docstrings should be relatively concise and mostly add context and explanation.

A user can easily see the default parameters get_interfaces(external=False, ip=False), which reveals that they're optional and booleans. All you need to explain is what setting them will affect.


multiple if statements "forced" by database query result & external api response

If you don't want to repeat yourself (DRY) then consider using multiple methods, and set properties ($this->collection) and/or pass parameters, as necessary. If you are finding yourself nesting if statements inside a method, it is a good indication that you should be using multiple methods.

For example, for your method, it looks like you could cut the database check into their own method.

If you have a return, then there is no need for an else statement :-)

if($a){
  return;
}
// no need for else

There is no point in setting a variable $json and echo it, just echo it as you did most of the time, but not all.

It looks as though you could break the rest response into it's own method for example with the if count > 0 return true or false to determine the action.

private function method($results){
    if (count(($results)) > 0) {
        echo Zend_Json::encode($result);
        return true;
    }
    return false;
}

Check out this video "Your code sucks, let's fix it - By Rafael Dohms" to help with understanding the above.
https://www.youtube.com/watch?v=GtB5DAfOWMQ

I hope this is helpful!


Using sed to its fullest

sed is surprisingly powerful tool. For example:

finddir=$(sed -n -E /"${sfile}_finddir"'/s/[^"]*\"([^"]*).*/\1/p' "${sdir}/config.cfg")
[ -z ${finddir} ] && finddir=${d_finddir}

achieves the desired effect without any egrep.

Explanation: The last line ([ -z ]) tests whether finddir has zero length (meaning that sed didn't find the line in interest) and if so (&&) assigns it a default value.

Editing the config file

I am not sure I understand the decision to edit the config file via the script. It is much more natural (at least within the context provided) to edit it manually.


Revealing module pattern modified for more class-like behavior

Review

This is a code review so I will point out some style problems first

Function expressions V statements

There are several ways to ways you can declare a named function.

As a statement.  function functionName() { }
As an expression. const functionName = function() { };  Note the semicolon

The most important difference between the two is that function statements are hoisted and available in all part of the scope they are declared in. Function expressions are not, even if you declare them as a var (which is hoisted) it remains undefined until it is assigned a value.

Function declared as statements are thus the safest form of function declaration and should be preferred over expression declarations.

testA(); // no error and calls testA
testB(); // throws an error ReferenceError: testB is not defined
testC(); // throws and error TypeError: testC is not a function

function testA(){};
const testB = function(){};
var testC = function(){};

const, var and let

When declaring variables use the appropriate type. const is the preferred type, unless you need to modify the value then use var. If you wish to use let in preference to var that is up to you, but be warned that let is not hoisted.

Avoid reserved words.

There is a set of words that are reserved and represent existing, or possible future tokens. Two of these are public, and private you should avoid using reserved words.

There are also many context specific words that you should try to avoid unless you are sure you are not overwriting an existing global property. For example parent, though you safely use it, I do not know if that is just luck or  knowledge that parent is a global scope object AKA window.parent and you are in function scope thus not overwriting the global.

Anti pattern

I consider this as an anti pattern

var Extended = function({extraText = 'no extra text given'} = {}) {
   var parent = Module(arguments[0]);

I am not sure if you are aware that if you call

 Extended(); // without an argument

Then arguments[0] is undefined, and arguments.length === 0 but the destructured argument named extraText has the value "no extra text given"

If you did this in purpose may I suggest that you use an alternative...

const Extended = function(info = {}) {
    const parent = Module(info);
    info = {extraText : "no extra text given", ...info};

...as it is much clearer what the intent is.

Use quotes not apostrophes

To avoid confusion with template string declarations delimited by Back Quote try to avoid using Apostrophes (AKA single quite)

Don't duplicate variables

The object Module creates the object private and assign the property text the value of the argument text. This is just a duplication as the only place you use text is in the function it is available as the argument

Design

You are on the correct path to using JavaScript to create private (protected) and public states. Though there is no need to create the private objects as you can use the function scope to hold the private state, including functions

Simple example of a object with both public and private states, using getters and setters to protect type (count as a Number), and access to private state from private and public scopes (eg function 'show')

function MyObj(text = "Nothing to see here."){

     if (typeof text !== "string") {  text = "Wrong type." }

     // private variables
     var count = 0;  // Type safe from outside

     // private functions declared here or in the API below
     function show(){
         console.log(text);
         count += 1;
     }

     // public API also accessible from private scope
     const API = {
         get count() { return count  },
         set count(c) {  // only set if a number to keep type safe state
             if (!isNaN(c)) { count = Number(c) }
         }
         show,  // public access to private function

        // OR add the function here
         show() {
            console.log(text);  // still have private access
            count += 1;
         }
     }

     // internal access
     setTimeout(show, 1000); // via private function

     // or via public API
     setTimeout(API.show, 2000);

     return API;
}

You can nest these objects creating additional levels of state security. You can also create several public objects that share a single private state,

A rewrite

As your code does nothing with its private states there was not much to go by. The Design section above would be more appropriate for what you may be after.

The following does the same as your code with considerably less noise.

function Module({text = 'no text given'} = {}) {
    function logText() { console.log(text) };  // private function
    return { logText };
}

function Extended(info = {}) {
    info = {extraText : "no extra text given", ...info};
    function alertText() { alert(info.extraText) }
    return { ...Module(info), alertText };
}


Laravel scopes are not a way to create static methods, they should be used to add parts to a database query. They should always return a query builder.
Aim to make your scopes as small as possible so you can then combine them together to make more complex queries.
It doesn't matter if you use the Request passed in to the controller or the request() helper, use whichever you prefer.
If you aren't going to reuse the getSelect2() method you don't need to add it to the model, just do the query in the controller. If you do need to repeat the query elsewhere you can make a new class that can build the options ($formatted_tags).
class Customer extends Model
{
    // ...

    public function scopeNameLike($query, $name): void
    {
        $query->orderBy('name','asc')->where("name", "like", "%{$name}%");
    }

    // ...
}

class Controller
{
    public function selectJson(Request $request)
    {
        return Customer::nameLike($request->q)
            ->when($request->city_id, function ($query, $value) {
                $query->where('city_id', $value);
            })
            ->limit(5)
            ->get(['name', 'id'])
            ->map(function ($item) {
                return ['id' => $item->id, 'text' => $item->name];
            });
    }
}

Is return something in scope really bad practice? What about the normal method in the model? I have so many tables/models that I need to format to select2 format. Am I need to format it in every controller? – Muhammad Dyas Yaskur

I was mistaken that scopes shouldn't return a value, as per the Laravel documentation they should return a query builder instance. It would be bad practice to return any other value from a scope.
If you need many of these types of queries for different models you can create a helper class that can then be reused.
class Select2
{
    public static function customer(Request $request)
    {
        // Query moved from controller
    }
}

class Controller
{
    public function selectJson(Request $request)
    {
        return Select2::customer($request);
    }
}


Exposing includes to client over webservice for database queries

I don't think you should add a method for setting includes on the query object. That means your consumers have to know which properties need to be included and which ones don't.

I think you should be explicit about it on the query. One approach could be to simply add a property:

// Slightly odd use of "WithPosts" to make it more comparable.
public class GetCustomerQuery : IQuery<Customer>
{
    public string CustomerId { get; private set; }

    public bool IncludePosts { get; private set; }

    public GetCustomerQuery(string customerId)
    {
        CustomerId = customerId;
    }

    public GetCustomerQuery WithPosts()
    {
        return new GetCustomerQuery(CustomerId) { IncludePosts = true};
    }
}

You could also leverage some inheritance:

public class GetCustomerWithPostsQuery : GetCustomerQuery
{
    public GetCustomerWithPostsQuery(string customerId) : base(customerId)
    {
    }
}

public class GetCustomerQuery : IQuery<Customer>
{
    public string CustomerId { get; private set; }

    public GetCustomerQuery(string customerId)
    {
        CustomerId = customerId;
    }

    public GetCustomerWithPostsQuery WithPosts()
    {
        return new GetCustomerWithPostsQuery(CustomerId);
    }
}

Either way:

var customerQueryWithoutPosts = new CustomerQuery("Dennis");
var customerQueryIncludingPosts = new CustomerQuery("Dennis").WithPosts();
// ... profit?

You can then either check the query's IncludePosts property OR have a different handler for the specialised GetCustomerWithPostsQuery query object.


Your approach is.... accurate, but inefficient. I believe you already know that. You can search here on Code Review for alternate algorithms (I believe the most efficient algorithm is described in this answer by David Zhang (I see ILoveCoding has answered something similar).

But, I would like to address an obvious inefficiency here:

public static boolean isSmallestMultiple(int i) {
    return i % 2 == 0 &&
        i % 3 == 0 &&
        i % 4 == 0 &&
        i % 5 == 0 &&
        i % 6 == 0 &&
        i % 7 == 0 &&
        i % 8 == 0 &&
        i % 9 == 0 &&
        i % 10 == 0 &&
        i % 11 == 0 &&
        i % 12 == 0 &&
        i % 13 == 0 &&
        i % 14 == 0 &&
        i % 15 == 0 &&
        i % 16 == 0 &&
        i % 17 == 0 &&
        i % 18 == 0 &&
        i % 19 == 0 &&
        i % 20 == 0;
}

Right, you know that 4 is a multiple of 2.... so, why do you do:

`i % 2 == 0`

when you're also going to do:

`i % 4 == 0`

Similarly, why do 4 when you do 8, and 16?

If you do 16, then you've already also checked 8, 4, and 2.

At a minimum, if you're going to hard-code the values, at least hard-code the largest factors.... No need hard coding a value that has a larger multiple too in the tests:

public static boolean isSmallestMultiple(int i) {
    return
        i % 11 == 0 &&
        i % 12 == 0 &&
        i % 13 == 0 &&
        i % 14 == 0 &&
        i % 15 == 0 &&
        i % 16 == 0 &&
        i % 17 == 0 &&
        i % 18 == 0 &&
        i % 19 == 0 &&
        i % 20 == 0;
}


K&R C book, Exercise 1-21: Replace tabs with spaces

Constants

#define TAB_SIZE 4

This is the old way of doing things.  Modernly C uses the same syntax as C++:

const int TAB_SIZE = 4;

While both will still function, this has the added benefit of offering type safety.  The #define is just a search and replace used by the preprocessor.  I.e. it replaces TAB_SIZE with the character 4 in an intermediate copy of the file.  The const variable will be managed by the compiler.

Update assignments

                character_count = character_count + whitespace_count;

This is more idiomatically written

                character_count += whitespace_count;

That form is exactly the same as the longer form.  It evaluates the left-hand side of the assignment, adds it to the right-hand side, and stores the result in the left-hand side.  But it is shorter and more easily recognizable.

Simplifying logic

However, I wouldn't do either of these.  Instead, on each iteration of the loop, just increment character_count.  Then you never have to add character_count and whitespace_count.  This will work in your program because you never use character_count separately from whitespace_count.  So make this change and replace character_count + whitespace_count with just character_count.

Yoda conditions

        if (c == ' ') {

This is often written as

        if (' ' == c) {

The reason is that if you accidentally leave off an equals sign ' ' = c will generate a compiler error.  Meanwhile, c = ' ' will silently do the wrong thing.  It wouldn't be so bad here, as it will be immediately obvious in the display.  But in a different kind of program, assigning to c might make a much more subtle bug.

Correct naming

            //we encountered a non-whitespace char. Print all 'saved' whitespaces.

This is incorrect.  A whitespace is any character that can produce indent.  It specifically includes tabs (and new lines).  But what you check is non-space characters.  This is easy enough to fix, just remove "white" both times here and rename whitespace_count to space_count.

Consistent naming style

You have the camelCased numberOfCharsToReachTabStop and snake_cased character_count and whitespace_count.  Please pick one kind of casing per identifier type and stick to it.  If local variables are snake_cased, then number_of_chars_to_reach_tab_stop.  Or change them all to camelCase.  I personally prefer snake_case, which is easier for non-native English speakers, as it doesn't rely on an ability to differentiate between capital and lowercase letters.  But the most important thing is to be consistent so that people can see snake_case and realize that it is a local variable or one of the other things that use snake_case.

TAB_SIZE is a constant, so it is appropriate to use a different casing style (e.g. ALL_CAPS) for it.

Bugs

As already noted, you don't print spaces at the end of a line.  But there is a more serious bug.  You treat tabs as single characters in the character count.  You should not.  Instead, tabs are TAB_SIZE characters.  Don't forget to adjust for the tab stop.  I.e. if you are currently one character past the tab stop, you'd only add three characters for the tab.  So if you adopt my previous suggestion of incrementing character_count on every iteration, you need something like

if ('\t' == c) {
    /* update character_count appropriately */
} else {
    character_count++;
}

I'll leave the actual update to you, as that's the exercise that you're exploring.


Usage of the ternary "?:" operator with functions listening to click events

Let's do some fixing. First, this is how you pass optional (non-boolean) parameters in JS (the Good Waytm):

addFooListeners = function (panelType, handlers) {
    handlers        = handlers        || {};
    handlers.show   = handlers.show   || showFoo;
    handlers.hide   = handlers.hide   || hideFoo;
    handlers.commit = handlers.commit || commitFoo;

The above can be rewritten in a neater way using jQuery (not sure what the name of YUI equivalent to extend is):

handlers = $.extend({
    show  : showFoo,
    hide  : hideFoo,
    commit: commitFoo
}, handlers || {})

Now, using eval for this code is criminal. Say the object ns refers to is module, then you can do this instead of eval:

YAHOO.util.Event.addListener("show" + panelType, "click", handlers.show, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("hide" + panelType, "click", handlers.hide, module["panel_" + panelType], true);
YAHOO.util.Event.addListener("commit" + panelType, "click", handlers.commit, module["panel_" + panelType], true);

Now, as you can see, you are assigning a lot of events in a similar fashion. Did you think of defining an addPanelListener function within your function?

function addPanelListener (event, panelType, handler) {
    YAHOO.util.Event.addListener(event + panelType, "click", handler, module["panel_" + panelType], true);
}

addPanelListener("show"  , panelType, handlers.show);
addPanelListener("hide"  , panelType, handlers.hide);
addPanelListener("commit", panelType, handlers.commit):

Hope it helps.


Some few thoughts without testing or anything else:

Cache the value of the cell in a local variable.
Replace for-loops if possible with foreach-loops.
The call of boxList[x].Name.ToString() is unnecessary, it is already a String.
break after setting the visibility to avoid unnecessary checks.

foreach(DataGridViewRow row in dgv.Rows)
{
    String cellValue = row.Cells[1].Value.ToString();
    foreach(CheckBox boxItem in boxList)
    {
        if(cellValue == boxItem.Name)
        {
            row.Visible = false;
            break;
        }
    }
}

On another sidenote, please use meaningful variable names, even in such stupid iterating loops.


_port.Encoding.GetBytes(_port.ReadExisting())

If you want to work with byte[], then your data should never appear as string, even temporarily, because some byte sequences are likely going to be invalid in your encoding.

I believe you should be able to use the byte[] overload of Read() for this. (Though switching to byte[] and async methods of the BaseStream is probably a better choice in the long run.)

Your class is schizophrenic about whether it wants to use string or byte[] (the observables use byte[], Write() uses string). You should figure out which choice makes more sense and stick to it.

What is the purpose of DataTx? I think that being able to read what you have written is not commonly needed.

I realize that Tx and Rx are abbreviations used in networking, but I find them confusing. Are you sure users of this library will immediately understand them? If not, you should rename the properties.

Boolean
String

It's common to write those types in their keyword form: bool, string.

~ComPort() {
    Dispose(false);
}

You don't have any unmanaged resources, so Dispose(false) basically doesn't do anything. But this means there is no reason for this class to have a finalizer.

The Dispose Pattern makes sense when you're writing a class that is going to be inherited. But since your class is sealed (nice, most people don't bother with that), I think there is also no reason to have the Dispose(bool) overload, just a single Dispose() method will be enough.


I have not coded in Java for a few years so it might be good to get another opinion, though some points did stand out while reading your code.

It seems odd to me that you would use an ArrayList with a fixed size, personally I would just use an array for the buffer.
when you dequeue, you do not overwrite the value until you enqueue over the top of it. This might not seem like an issue (and if you only queue primative types like int, its not) but if you use reference types and the queue cycles slowly then it means you hold a reference to the object for longer than needed and it cannot be collected.
I'm a bit worried about catching the InterruptedException inside a while(true) loops without breaking out of the loop. The most common reason I have seen for one thread to interrupt another is when the interrupting thread wants to give the interrupted thread the opportunity to terminate gratefully, but this will prevent that option. I thought about what can be returned in such a case and eventually decided it might be best to let this exception flow through and be handled by the caller.


I second @Dannnno arguments except for the fact that you don't need to split the work into tinier functions.

In fact I'd say quite the opposite as using more function let you turn them into generators for a more efficient memory usage.

You should also make yourself familiar with the str.format syntax which is the new way to go over the % formatting syntax.

My proposal is:

from collections import Counter
from itertools import chain

def word_map(filename, stop_words_file):
    with open(stop_words_file) as f:
        stop_words = set(f.read().split())

    with open(filename) as f:
        for line in f:
            words = (filter(str.isalnum, w).lower() for w in line.split())
            yield (w for w in words if w and w not in stop_words)

def top_words(filename, stopfile, count):
    words = chain.from_iterable(word_map(filename, stopfile))
    return Counter(words).most_common(count)

if __name__ == '__main__':
    for word, count in top_words('story.txt', 'stopwords.txt', 5):
        print '{} : {:>10}'.format(word, count)


Calculating the number of rounds required to complete a tournament

Well, I feel like an idiot but I finally figured out why it seemed like there should be an obvious solution - one hour after posting, and three after starting to think about it. If I'm not allowed to post the answer myself, please let me know and I'll remove it.

function totalRounds($participants)
{
    return strlen(decbin($participants - 1));
}

The logic goes as follows: each bit in a string representation of the number of participants as a binary can be seen as a doubling of the number of participants, as long as the total number is a power of 2.

Then, by the same logic, each bit (except for the left-most one) can be seen as the reverse - a halving of the number of participants. And this is exactly what we want: each round, half of the players should be eliminated.

If we need to assign byes, that basically means we need to do one more round than that - so we can just use the string length straight away. But if we don't, then we need to disregard the left-most bit.

So if we start by subtracting one from the number of participants, that means that e.g. 8 participants = 1000 in binary turns into 7 = 111, which requires three rounds. For 9-15 participants, the string length would not change, so it's still correct. And for 16, the same logic applies as did to 8 - and so on.


Project Euler 11: Largest product in a grid

We take take advantage of these features of numpy to reduce the code quite a bit:

array reshaping
array row, column and diagonal slices
np.prod to compute the product of all elements in an array
flipping the array to get anti-diagonals

Reshaping

Reshaping allows you to (for instance) reorganize a 1-dimensional array into a 2-dimenstional array. Just the dimension metadata is changed so the operation is very efficient:

a = np.array([1,2,3,4,5,6]).reshape(3,2)
print a

[[1 2]
 [3 4]
 [5 6]]

Slicing

Here are example of how to take row, column and diagonal slices of arrays:

import numpy as np

a = np.array( [[11,12,13,14,15,16],
               [21,22,23,24,25,26],
               [31,32,33,34,35,36],
               [41,42,43,44,45,46]
              ] )

print "row",     a[1][3:5]         # horizontal slice, row 1, columns 3..5
print "column:", a[:,4]            # column 4
print "diag:",   np.diagonal(a, 2) # 2nd diagonal

Note that row and column indices start from 0. In the case of diagonals, 0 is the main diagonal, with positive diagonals to the right and negative diagonals to the left of the main.

Products

And here is how to use np.prod:

a = np.array([5,6,7,8])
print np.prod(a)             # prints 1680

Anti-diagonals

We can get anti-diagonals by first flipping the matrix along one of its dimensions:

a = np.array([1,2,3,4,5,6,7,8]).reshape(2,4)
b = a[::-1,]
print b

b has the same shape as a and the diagonals of b are the anti-diagonals of a.

Solution

Putting it all together:

def euler11():
  data = """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
"""
  a = np.array([ int(x) for x in data.split() ]).reshape(20,20)
  # print a
  b = a[::-1,]

  maxprod = 0
  for i in xrange(20):
    for j in xrange(20):
      r = np.prod( a[i][j:j+4] )
      c = np.prod( a[:,j][i:i+4] )
      k = min(i,j)
      d1 = np.prod( np.diagonal(a, j-i)[ k:k+4 ] )
      d2 = np.prod( np.diagonal(b, j-i)[ k:k+4 ] )
      maxprod = max([maxprod,r,c,d1,d2])
  print maxprod

Note here is i,j represents the upper left corner of either the row, column or diagonal we are taking the product of. That's why both range from 0 to 16 We just run both i and j from 0 through 19. We examine a few extra products (some with less than 4 terms), but since we are looking for the maximum it doesn't matter.


All of your arguments accept *args but don't use it. If someone calls your functions like sin(some_angle), it's going to return None which is confusing. You can simply leave it out, **kwargs still works.

This is more a situation that calls for keyword-only arguments, because each function only has a small fixed number of possible arguments. This leads to better errors if, say, you misspell one of the argument names in a call. If you want to use keyword-only arguments without *args, you can add a single *, before the arguments, like this:
def sin(*, degrees=None, opposite=None, hypotenuse=None):
    if degrees:
       return math.sin(math.radians(degrees))
    elif opposite and hypotenuse:
       return opposite / hypotenuse

Testing for possible arguments should be done with if x is not None instead of if x: getting sin(degrees=0) is totally valid but will return None if you test for degrees instead of degrees is not None!

You're sort of overloading each function based on arguments passed. This makes the functions error-prone to use and possibly confusing. You can call sin(degrees=60, opposite=1, hypotenuse=1) and your program won't complain. You can call sin() and get None.
A possible solution would be to split the first four functions out like this:
def sin_from_degrees(degrees)
def sin_from_edges(*, opposite, hypotenuse)
def cos_from_degrees(degrees)
def cos_from_edges(*, adjacent, hypotenuse)
def tan_from_degrees(degrees)
def tan_from_edges(*, opposite, adjacent)
def opposite_from_sin(*, sin, hypotenuse)
def opposite_from_tan(*, tan, adjacent)
def adjacent_from_cos(*, cos, hypotenuse)
def adjacent_from_tan(*, tan, opposite)
def hypotenuse_from_sin(*, sin, opposite)
def hypotenuse_from_cos(*, cos, adjacent)

Note how none of the arguments are optional any more, and if you try to use a function the wrong way, Python will give you a nice error message explaining exactly what went wrong. I also made degrees a regular argument, because I felt that sin_from_degrees(degrees=degrees) would be a bit redundant and there's no confusion about which argument means what if there's only one, although I can understand wanting the API to be more consistent.

Your last two function is interesting in that it is overloaded to an extent, but not as easy to extricate as the other functions. I would use a namedtuple instead of a dictionary, and definitely signal if pythagorean is called with the wrong arguments.
from typing import NamedTuple

class Triangle(NamedTuple):
    adjacent: float
    opposite: float
    hypotenuse: float

def pythagorean(*, adjacent=None, opposite=None, hypotenuse=None):
    if hypotenuse is not None and opposite is not None and adjacent is None:
        adjacent = math.sqrt(hypotenuse * hypotenuse - opposite * opposite)
    elif adjacent is not None and opposite is not None and hypotenuse is None:
        hypotenuse = math.sqrt(adjacent * adjacent + opposite * opposite)
    elif hypotenuse is not None and adjacent is not None and opposite is None:
        opposite = math.sqrt(hypotenuse * hypotenuse - adjacent * adjacent)
    else:
        raise TypeError("pythogorean() expects exactly two arguments from 'adjacent', 'opposite', and 'hypotenuse'")
    return Triangle(adjacent, opposite, hypotenuse)

There is still a bit of duplication (if a is not None and b is not None and c is None: c = math.sqrt(a * a ± b * b) occurs three times) but I'm not sure at the moment how to cleanly refactor that, especially due to the sign change when calculating the hypotenuse. You could make it a bit shorter by using comparator chaining (a is not None is not b) but honestly I think that would be hurt readability and maintainability more than it would help.

Maybe I've gone a bit overboard with suggesting changing things you didn't ask about, but I hope that at least answers your questions!


Efficiency of Recursive Checkers Legal Move Generator

A couple of little things that caught my eye:

You could simplify this

dist = 1
while True:
    jx, jy = px + dist * dx, py + dist * dy
    dist += 1

to this:

jx, jy = px, py
while True:
    jx += dx
    jy += dy

You don't need this range check

if not (0 <= jx < 8 and 0 <= jy < 8):
    break
if board[jy, jx] != EMPTY:

because, assuming board is a dict indexed by tuple, you can just catch KeyError when out of bounds:

try:
    if board[jy, jx] != EMPTY:
        ...
except KeyError:
    break

Instead of

((piece & WHITE) and (board[jy, jx] & BLACK) or
 (piece & BLACK) and (board[jy, jx] & WHITE))

you could use board[jy, jx] & opponent if you determine the opponent's color in the beginning of the function:

opponent = BLACK if piece & WHITE else WHITE


In Java: convert an array of floats to bytes and vice versa

Welcome again to Code Review, not my field but from a not so clear documentation it seems that you can rewrite your bytesToFloats method using the FloatBuffer class like below, using the asFloatBuffer method from ByteBuffer class:
ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
FloatBuffer fb = buffer.asFloatBuffer();

After you have to back the FloatBuffer buffer allocating a new float array like below:
float[] floats = new float[bytes.length / BYTES_PER_FLOAT];
fb.get(floats);

Then your method can be rewritten like below:
protected static float[] bytesToFloats(byte[] bytes) {

    if (bytes.length % BYTES_PER_FLOAT != 0) {
        throw new RuntimeException("Illegal length");
    }

    ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
    FloatBuffer fb = buffer.asFloatBuffer();
    float[] floats = new float[bytes.length / BYTES_PER_FLOAT];

    fb.get(floats);

    return floats;

}

In alternative to the bytes.length / BYTES_PER_FLOAT the fb.limit() method seems returning the same result, moreover it is bound directly to the FloatBuffer fb used.


Levenshtein Distance with Haskell Vectors and Memoization

Readability improves a lot with import Data.Vector ((!)) and replacing V.! with !.

generate looks better; performance-wise I do not expect a difference (with optimization).

lev    = V.generate (l1 + 1) levi

If you like point-free notation, you can short-cut levi, with intermediate manual steps:

  lev    = V.generate (l1 + 1) levi
  levi i = V.generate (l2 + 1) (levij i)

2

  lev    = V.generate (l1 + 1) (\i ->
           V.generate (l2 + 1) (levij i))

3

  lev    = V.generate (l1 + 1) (\i -> V.generate (l2 + 1) (levij i))

4

  lev    = V.generate (l1 + 1) (V.generate (l2 + 1) . levij)

Your code looks good. You might try it with Array next, to two-dimensional Index. The google results for haskell levenshtein Array are only marginally better than your Vector approach.


Determining the existence of string Intersections

Some simple suggestions for refactoring on your current code (without going into the implementation)

Use Set over HashSet

Your original question says "Compute this in linear time using a HashSet.", but that usually doesn't mean you need to use HashSet as the return type. Set<String> result = new HashSet<>() works better in the sense that callers of your method will not need to know the underlying implementation. Also, you'll be free to change it to LinkedHashSet without changing the method signature.

Variable names

Two points here.

i is usually used in for loops, so do consider using a better name in the method signature, e.g. permutateString(String str, int length).

Your count isn't actually counting anything, but to keep track of the last exclusive index for substring-ing (I think I just made a new word up!).  For people who don't use String.substring() often, that line of code will instead read like you are creating sub-strings of increasing lengths.

Looping

for (int j = 0; j < str.length(); j++ ) {
    if (count > str.length()) { break; }
    ...
}

This can be better expressed as:

for (int j = 0; j <= str.length() - length; j++ ) {
    result.add(str.substring(j, j + length));
}

Illustration:

1234567890
123
 234
  345
   456
    567
     678
      789
       890

So, to extract 3-character sub-strings from a 10-character string, we need to loop from i = 0 to i = 7, or i <= string.length() - length for the latter.
Unit testing

As mentioned elsewhere, please consider using unit testing frameworks like JUnit or TestNG. :)


Dont call functions in loop conditions.

Calling count as condition of a for is a common mistake. It has the same behaviour but it is slower because the count function has to be called repeatedly although it returns the same value all the time. Unless the count changes during iterations, prefetch the count before the loop.

Iterate only where body is same

In your for you always check if the element is the last one, to do something else in that case. You better exclude it from the for, and handle the last element separately.

Unpack is not necesary

I wasnt really sure until I benched it, but just accessing individual characters of the strings with the [] operator and using the ord function to get the numeric value of bytes seems quite faster.

Not sure your algorithm is correct

As I've shown in me2 implementation, you are actualy adding just the first charracter of each word and subracting last character of each word twice.
It means that none of the characters except first and last in each word is contributing to the resulting sum. Therefore item Item1 is the same as Ixxx1. (Try for $input2 in the code below and see for yourself).

<?php

function op(array $array)
{
    $sum = 0;

    foreach( $array as $item ) {
        $bytes = unpack( 'C*', $item );

        for( $i = 1; $i <= count( $bytes ); $i++ ) {
            if( isset( $bytes[$i+1] ) ) {
                $sum += $bytes[$i] - $bytes[$i+1];
            } else {
                $sum -= $bytes[$i];
            }
        }
    }

    return $sum;
}

function op2(array $array)
{
    $sum = 0;

    foreach( $array as $item ) {
        $bytes = unpack( 'C*', $item );

        $length = count( $bytes );
        for( $i = 1; $i < $length ; $i++ ) {
            $sum += $bytes[$i] - $bytes[$i+1];
        }
        if ($length > 0) {
            $sum -= $bytes[$length];
        }

    }

    return $sum;
}

function me(array $array)
{
    $sum = 0;

    foreach( $array as $item ) {
        $length_1 = strlen($item) - 1;
        for ($i = 0; $i < $length_1; ++$i) {
            $sum += ord($item[$i]) - ord($item[$i + 1]);
        }
        if ($length_1 >= 0) {
            $sum -= ord($item[$length_1]);
        }

    }

    return $sum;
}

function me2(array $array)
{
    $sum = 0;

    foreach( $array as $item ) {
        $length = strlen($item);
        if ($length == 1) {
            $sum -= ord($item[0]);
        } elseif ($length > 1) {
            $sum += ord($item[0]) - 2 * ord($item[$length-1]);
        }
    }

    return $sum;
}

function bench(callable $callback, array $input, int $reps = 10000)
{
    $total = 0;
    for ($i = 0; $i < $reps; ++$i) {
        $start = \microtime(true);
        $callback($input);
        $total +=  \microtime(true) - $start;
    }
    return $total / $reps;

}

$input1 = ['Item1', 'Item2', 'Item3', 'X', ''];
$input2 = ['Ixxx1', 'Ixxx2', 'Ixxx3', 'X', ''];

$outOp = op($input1);
$outOp2 = op2($input1);
$outMe = me($input1);
$outMe2 = me2($input1);

echo 'OP: ' . bench('op', $input1);
echo \PHP_EOL;
echo $outOp;
echo \PHP_EOL;

echo 'OP improved: ' . bench('op2', $input1);
echo \PHP_EOL;
echo $outOp2;
echo \PHP_EOL;

echo 'No unpack: ' . bench('me', $input1);
echo \PHP_EOL;
echo $outMe;
echo \PHP_EOL;

echo 'Me2: ' . bench('me2', $input1);
echo \PHP_EOL;
echo $outMe2;
echo \PHP_EOL;

OP: 3.5921573638916E-6
-169
OP improved: 3.3084869384766E-6
-169
No unpack: 1.4432907104492E-6
-169
Me2: 5.5739879608154E-7
-169


Closing SQL connection for async operations

No that isn't right. If your query throws an error you won't be closing the connection. Swallowing exceptions like that (even though you're logging it) is generally bad as well. How does the user know anything has gone wrong?

If you can, just use async and await with a using:

public async Task DeleteDataAsync(...)
{
     using (var connection = GetConnection())
     using (var cmd = /* ... */)
     {
         // ... trimmed
         await cmd.ExecuteNonQueryAsync();
     }
}

If you can't do that (I don't know why you couldn't) then you could do this:

cmd.ExecuteNonQueryAsync().ContinueWith(_ => connection.Close());

But you should be waiting for that task to finish.

Your naming is non standard: methods should be PascalCase.

async void is generally bad - there's no way for the caller to wait until the work is finished. You shouldn't use async void methods (except for event handlers).

Async methods should have the suffix Async and return a Task or Task<T>.

Don't use Task.Factory.StartNew unless you want to specify advanced options; use Task.Run. However, don't use Task.Run for fake asynchrony - you'll just slow things down.


Use clock's native resolution everywhere
If you cast time points and durations to something with a different resolution than that of clock, you risk losing precision. So for all internal state of your classes, I would definitely store everything as clock::duration and clock::time_point types. You might consider keeping the template parameter to ensure the return types of public member functions have the requested time resolution, but that just makes it easy for the caller to make the same mistake.
To give an example of where it can go wrong, suppose I write:
StopWatch<std::chrono::seconds> watch;
watch.go(); // done at 11:59:59.999
...
watch.stop(); // done at 12:00:00.000
auto elapsed = watch.elapsed_time();

With your implementation, elapsed will be equal to one second, even though only one millisecond passed.
If the issue is just convenience so the caller doesn't have to call std::chrono::duration_cast<>() themselves, I would remove the template parameter from the class, and make the member function elapsed_time() a template instead, like so:
template <typename duration = clock::duration>
duration elapsed_time() const noexcept
{
    ...
}

current_time() should not be constexpr
If you mark a function constexpr, you promise that this function can be evaluated at compile-time. But that does not make sense here.
Consider not storing lap results in LapWatch
Having struct Lap and a function to mark when a lap happened is good. However, by making lap() store the results in a member variable, you now gave LapWatch the responsibility to store laps. That might sometimes be exactly what you want, but maybe the caller wants to do something completely different. Maybe the previous laps don't need to be stored, or they need to be stored in a different way. I would make lap() return a Lap instead, and have the caller decide whether it wants to add those to some container. So:
Lap lap() {
    Lap current;
    ...
    return current;
}

And then the caller can write:
LapWatch<> watch;
std:vector<Lap> laps;
laps.push_back(watch.lap());

Use std::move() instead of static_cast<Lap&&>()
If you really want to move an object, use std::move(), it is shorter and less error-prone.
Note that neither the cast nor std::move() will do anything in this case, since neither Lap nor std::chrono::duration has a move constructor, but it doesn't hurt either.


Encrypted text - C# SHA256, implementation

My concern is that the passphrase is 4 sets of "diceware" words (like here: https://diceware.dmuth.org/) and therefore could be brute forced.

The diceware password is about 51 bits in strength, so it should indeed be run through a password based key derivation function, especially if you use it to encrypt messages - because encryption can be broken offline (i.e. on the computer of an attacker).

Would adding more to the passphrase, such as as hash of DateTime.UtcNow.ToString("yyyyMMdd") or GetHashString(random-string) for example add any additional security or is it just theatre and the "diceware" passphrase is practicably unbreakable?

No, the passphrase is not big enough to be unbreakable. Adding more information could help, but only if it is not available to an attacker, which is very questionable for a date / time.

private const int Keysize = 256;

This is good because we generally use key sizes in bits (and "size" is better than "length" in my opinion).
private const int DerivationIterations = 1000;

This is not a good idea at all. First of all, you should use about a million as iteration count at the moment. It would also be a big boon if you could upgrade it to a higher count later on. The amount of operations that an attacker has to perform is the same as the number of iterations, and an attacker may use a very fast implementation. Currently it adds about log_2(1000) =~ 10 bits of security.
public static byte[] GetHash(string inputString)

Especially if this is a public method (why?) then the hash function and encoding performed on the input string should be documented. It is not clear why the input needs to be a string in the first place though.
public static string GetHashString(string inputString)

Same for the output encoding of course.
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
    sb.Append(b.ToString("X2"));

Reprogramming a hex encoder doesn't make sense, and why not use a generic hex encoding function? In the end you want to have something like: hex(hash(utf8(text))) in your code...
var saltStringBytes = Generate256BitsOfRandomEntropy();

No, that's 256 bits of randomness you generate, the entropy is gathered by the operating system in the end. Why not just call it a salt? A StringByte is not a structure I've ever heard of.
 using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))

This badly named class of Microsoft implements PBKDF2, which is defined in the Password Based Encryption standard. So what about var pbkdf2 =  because the returned object certainly is not a password.
Note that PBKDF2 is inefficient if you ask more than the configured hash output size. That defaults to SHA-1. If you'd use SHA-512 instead then you could retrieve a key, and IV and a check value all from a 512 bit / 64 byte output (32 bytes for the key, 16 bytes for the IV and check value each, for instance).
var engine = new RijndaelEngine(256);

Why would you use Bouncy Castle, a software only provider for bog-standard AES functionality? Do you hate the AES-NI instruction set?
var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);

I'm not sure, but I'm pretty confident that ivStringBytes is already the correct size, so the offset and length should not be needed.
var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)];

Comparison to what? You have encrypted a message, right? If you just want to check if a password is correct then just use the password hash (PBKDF2).


CSS mask clipping and overlay SVG to achieve a two effect

I would suggest using an inline svg to create these shapes. This will provide more browser support than using the CSS mask property (canIuse).

Both sides are created with paths and filled with the images using the pattern element :

DEMO

* {margin: 0;padding: 0;}
body {
  background: url('http://lorempixel.com/output/nature-q-g-800-600-5.jpg');
  background-size: cover;
}
svg {
  display: block;
  width: 95vw; height: 47.5vw;
  margin: 2.5vw;
}
<svg viewbox="0 0 100 50">
  <defs>
    <pattern id="img" patternUnits="userSpaceOnUse" x="0" y="0" width="100" height="50">
      <image xlink:href="http://lorempixel.com/output/abstract-h-c-490-500-4.jpg" x="0" y="0" width="49.5" height="50" />
      <image xlink:href="http://lorempixel.com/output/abstract-h-c-490-500-8.jpg" x="50.5" y="0" width="49.5" height="50" />
    </pattern>
  </defs>
  <path d="M0 0 H49.5 V15 A10.02 10.02 0 0 0 49.5 35 V50 H0z" fill="url(#img)" fill-opacity="0.8" />
  <path d="M50.5 0 H100 V50 H51 V35 A10.03 10.03 0 0 0 50.5 15z" fill="url(#img)" fill-opacity="0.8" />
</svg>


All your fields are private and final, which is the first step to being immutable. This is good.

The Date class is not immutable, so, for example, you have a problem with the method:

public Date getDateOfBirth() {
    return dateOfBirth;
}

because, someone could do:

employee.getDateOfBirth().setYear(1900);

and suddenly your employee has aged... a lot.

What the oracle documentation is saying, is that, if you have mutable content, you should return a copy of that data. This is often called a 'defensive copy':

public Date getDateOfBirth() {
    return new Date(dateOfBirth.getTime());
}

Update: additionally, your method should be final so that no subclasses can change the behaviour of getDateOfBirth() (same is true for getName()). If the method is not final, then a subclass could possibly override the method, and do it in a way which make the name/dateOfBirth mutable.

Note, that the constructor for Date, in this instance, takes a long value. This leads on to a suggestion that the immutable class should store a long instead of a Date. The long is immutable anyway, if final.

public class Person {

    private final String name;
    private final long dateOfBirth;

    .....

    public Date getDateOfBirth() {
        return new Date(dateOfBirth);
    }

}

Apart from that, the immutability looks fine. Good, even.

The package name you have chosen though... is lacking: objects.objects. You could not name your package something better?


Help to Refactor PHP Flip Image Code to smallest size as possible

You could use call_user_func to check the extension only once. Something like this (I haven't got the time even to read the code now)

function flip_image($filepath)
{
if(file_exists($filepath)):

    //Array ( [dirname] => images
    //        [basename] => pig.png
    //        [extension] => png
    //        [filename] => pig
    //        [filesize] => 72 )
    $file = $this->get_file_info($filepath); // Returns above array

    // Is it allowed in our extensions array
    if(in_array($file['extension'], $this->allowed_exts)):
         // Reference our Image for the correct extension
        $outfile = $file['dirname'] . "/" . $file['filename'] . "_flipped" . "." . $file['extension'];
        switch ($file['extension']) {
            case 'png':
                return flip_image_in($filepath, $outfile, 'imagecreatefrompng', 'imagepng');
            case 'gif':
                return flip_image_in($filepath, $outfile, 'imagecreatefromgif', 'imagegif');
            default: // Has to be JPG, or JPEG
                return flip_image_in($filepath, $outfile, 'imagecreatefromjpeg', 'imagejpeg');
        }
    else:
        echo 'Incorrect File Type, Not an Image, .png .gif, jpeg. jpeg Only.';
        return false;
    endif;
else:
    echo 'No Such file found, Check the file path';
    return false;
endif;

}

function flip_image_in($inpath, $outfile, $create_function, $write_function)
{
        $img = call_user_func($create_function, $inpath);

        // Now we have our image...
        // Image Width & Height
        $size_x = imagesx($img);
        $size_y = imagesy($img);

        // Create Temp Image
        $temp = imagecreatetruecolor($size_x, $size_y);

        // Define a colour as transparant, allocate the colour, resample it
        imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
        imagealphablending($temp, false);
        imagesavealpha($temp, true);

        $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
        if ($x) {
            $img = $temp;
        }
        else {
            die('Unable to flip image');
        }

        call_user_func($write_function, $img, $outfile);
        imagedestroy($img);
        return $outfile;
}


Find the in-order successor of a given node in a binary search tree

For idiomatic Python:

You should not put spaces between the brackets and the values in function calls.
You should use snake_case for variables.

You've said you have concerns over finding the parent node that is the ancestor. Lets say we have the tree:

   A
 B
C D

Since that all left nodes are smaller than the current value in binary trees we know that \$B < A\$, \$C < B\$ and \$D < A\$. We also know that the right nodes are larger than the current node, and so \$B < D\$. And so we know \$C < B < D < A\$.

From this we can see that logically if node.parent.left == node is the same as if node.parent.value > target.

The benefit to the former is you don't have to create target.

Your implementation is awkward, successor should always be called duplicating the input.

successor(node, node.value)

If you don't then you'll have problems. Say \$A = 1\$, and \$\text{node} = D\$. The successor to \$D\$ is \$A\$, however successor(node, 1) will incorrectly return \$B\$.

To fix this just define target_value in successor.

def successor(node):
    if node.right:
        node = node.right
        while node.left:
            node = node.left
    else:
        target_value = node.value
        while node:
            node = node.parent
            if node.value > target_value:
                break
    return node

If you follow what you've seen online you can reduce the amount of lines of code:

def successor(node):
    if node.right:
        node = node.right
        while node.left:
            node = node.left
    else:
        while node != node.parent.left:
            node = node.parent
        node = node.parent
    return node

It should be noted that if there is no successor in the tree all implementations will raise an AttributeError.

This is rather confusing, and so you may want to change it to a different error.

def successor(node):
    try:
        if node.right:
            node = node.right
            while node.left:
                node = node.left
        else:
            while node != node.parent.left:
                node = node.parent
            node = node.parent
        return node
    except AttributeError:
        raise ValueError('No successor exists.') from None


A wrapper for user authentication using cURL in PHP

Let me be frank: this code is just a Frankenstein sewn from different unrelated parts. Basically here are two main problems:

sending HTTP requests is a distinct task and should be performed by another wrapper
splitting the main functionality between two methods just makes no sense. I do understand that you probably wanted to make use of constructor, but that's not how it is done

The HTTP request class
Basically there must be a class that does HTTP requests with methods to set particular settings, such as

setAuth(new BearerAuth($token))
setContentType()
setUrl()
etc

The error checking
Also, in this class, it is important to check for errors. Right now your code returns whatever is sent by the other party. But it is not necessarily would be JSON of a particular format. It could be HTML, JSON that contains some different data, an empty string, etc.

First of all the code must check for the curl_error. In case there is, it must throw an Exception
Then it must try to decode JSON. If it fails it must throw an Exception
Then it must check if the decoded data contains expected information. If it doesn't,  it must throw an Exception
only then it must return the data

The actual class
And then there could be a class to interact with a particular API, something like this
class Nucleolus
{
    protected $transport;
    protected $host;

    public function __construct(string $host, string $token)
    {
        $this->transport = new HTTPTransport;
        $this->transport->setAuth(new BearerAuth($token));
        $this->transport->setContentType('application/json');
    }

    public function authenticate(string $username, string $password, string $serverUrl = null)
    {
        $this->transport->setUrl($this->host."/authen/user");
        $result = $this->transport->post([
            'url' => $serverUrl ? $serverUrl : $_SERVER['SERVER_NAME'],
            'username' => $username,
            'password' => $password,
        ]);
        $data = JSON::decode($result);
        if ($data === true)
            return true;
        } else {
            throw new NucleolusException("Incorrect data from auth: $result");
        }
    }
}

Destructor is not really needed as PHP will destruct everything itself.


Operator-based switch for a database query filter

There are a few ways to approach this base on how much you want to minimize the code.

Define the predicates as actual functions and pass them in by name.

case Operator.Equal:
    tmpResult = tmpResult.Where(NumericEqual);
    break;

Use a temporary variable for the argument to Where()

Func<T, Boolean> predicate;
switch (enumOperator)
{
    case Operator.Equal:
        predicate = a => a.NUMERIC_VALUE == value;
        break;
    case Operator.Less:
        predicate = a => a.NUMERIC_VALUE < value;
        break;
    // ...
}
tmpResult = tmpResult.Where(predicate);

This could also be done with a function that encapsulates the switch and hiding it from the main function.

Or, if you feel like the switch statement is causing too much boilerplate, you could make a Dictionary<Operator, Func<T, Boolean>> and insert a function pointer for each operator. Then the code that uses it becomes:

tmpResult = tmpResult.Where(operatorMap[enumOperator]);

It is a trade off. The shorter code requires the use of more memory. Handling the case where enumOperator does not have match (which is not currently being done) would also have to change.

For the case where you will have lots of different properties that all need similar operations, you can have a function that creates the predicate.

Func<T, Boolean> MakePredicateEqual(Func<T, X> getField, X value)
{
    return a => getField(a) == value;
}

However, as things become more generic, more things need to be passed in as arguments and plumbing things together gets more complicated. It needs to be determined when the diminishing returns make it not worth it.


Before streamlining the code, it almost always pays off to streamline the math. The h you calculate is the dot product of two vectors, X[i] and Y[i] = cache[0] - w[i]*X[i], so we can rewrite it as

h = X[i].cache[0] - w[i]*X[i].X[i]

When you go on to calculate w_mean, you are actually negating h and then dividing it by a number that turns out to be X[i].X[i], so you can calculate w_mean as

w_mean = w[i] - X[i].cache[0] / X[i].X[i]

Setting aside the np.isnan and np.isinf checks you are doing, you then update cache[0] with a value where w[i] cancels out, and you are basically doing:

cache[0] -= X[i] * (X[i].cache[0] / X[i].X[i])

Putting it all together into a single function, I got this very compact code:

from numpy.lib.stride_tricks import as_strided

def draw_w_bis(X, w, cache):
    X = X.tocsr()
    x_rows_sqr = np.add.reduceat(X.data*X.data, X.indptr[:-1])
    rows, cols = X.shape
    row_start_stop = as_strided(X.indptr, shape=(rows, 2),
                                strides=2*X.indptr.strides)
    for row, (start, stop) in enumerate(row_start_stop):
        data = X.data[start:stop]
        cols = X.indices[start:stop]
        delta = np.dot(data, cache[0, cols]) / x_rows_sqr[row]
        w[row] -= delta
        cache[0, cols] -= delta * data

If you are not comfortable with calling as_strided you could replace the definition of row_start_stop with:

row_start_stop = np.column_stack((X.indptr[:-1], X.indptr[1:]))

On my system your test code runs the 1000 iterations over an order of magnitude faster (6 sec vs. 0.4 sec) which seems to be what you were after. There still is a for loop in there, so if you are going to run this on large arrays, it is still going to be slow, and you may want to consider using things like Cython.


function(cb,limit,pattern) {
    limit = typeof(limit) === "undefined" ? 1 : limit;
    //do stuff
}

Calling a function with less arguments than declared will just fill them with undefined. You can then check if that is the value, if so fill in your default ones.
The I have above will have the same affect as yours, there are always three variables (even in your code, Javascript variables are function scope, all of the var declarations are pulled to the top.).
The variables:
cb - unchanged
limit - set to 1 if not supplied
pattern - unchanged (undefined if not supplied)

EDIT:
I just saw your comment on reordering
you can do the following

  function foo(cb,limit,pattern) {
        if(limit instanceof RegExp) {
            pattern = limit;
            limit = 1;
        }
        else {
            limit = typeof(limit) === "undefined" ? 1 : limit;
        }
        //do stuff
    }


Your code is both short and good, so there's not much to say.

Header organization

It's a good idea to keep your headers organized. Keeping them alphabetically ordered allows you to spot accidental duplicates.

main() signature

You don't need to put void in the parentheses. It's very much a C-ism, and is not necessary in C++. Empty parentheses also means the function takes no arguments.

const variables and constants

acceleration is a constant, and should be marked constexpr to indicate it is a compile-time constant. Please note that constexpr is only available in C++11 or later. If you have to use an earlier version, you can replace it with static const for largely the same effect. feetFallen should be marked const, since you only read from it after it is initialized.

Marking variables const and constants constexpr limits the number of moving parts in your application, making it easier to reason about and keep correct.

Unnecessary comment

Your comment about initialization is not necessary. The fact that you initialize variables the same time they are declared is obvious from reading the code.

Invalid user input

time will contain the value 0 if your user inputs non-numeric input. If you want to constrain the user to numeric-only input, you can loop until the user enters only a valid number. Inspired by this StackOverflow answer, your solution could look like this:

while(!(std::cin >> time)){
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "Invalid input.  Please enter a number: ";
}


Lazy generators

Most often in Python you do not want to build an actual list and return it.

If I want to sum the divisors of a number, and there are many, I will waste a lot of space if I put them in a list first.

Also, not creating a list is even shorter, you just give out the elements one by one from the function:

def factorize(n):
    for item in primes_list:
        if item > n:
            break
        else:
            while n > 1:
                if n % item == 0:
                    n //= item
                    yield item
                else:
                    break

Reduce nesting

You got some serious nesting going on, each level of nesting is a level of complexity so getting it a bit down is positive. Luckily if we break we do not need an else: the code after will not be executed anyway:

def factorize(n):
    for item in primes_list:
        if item > n:
            break

        while n > 1:
            if n % item != 0:
                break
            n //= item
            yield item

Still two nested loops, but the situation is becoming more manageable.

Now let me re-factor the while loop away:

def how_many_times_divides(n, div):
    """
    >>> list(how_many_times_divides(40, 2))
    [2, 2, 2]
    """
    while n > 1:
        if n % div != 0:
            break
        n //= div
        yield div

And now factorize is starting to look nice and small:

def factorize(n):
    """
    >>> list(factorize(480))
    [2, 2, 2, 2, 2, 3, 5]
    """
    for item in primes_list:
        if item > n:
            break
        yield from how_many_times_divides(n, item)

Doctests

You may have noted that I added some examples of usage in the doc-strings of this functions. They are actually automatically runnable with doctests and I highly recommend them when writing numerical code.

Avoid unnecessary assignments & mutation

It is just simpler to return the expression:

combination_product = list(functools.reduce(operator.mul, i)
                           for i in unique_combinations)
combination_product.sort()

return combination_product

Becomes:

return sorted(functools.reduce(operator.mul, i)
                 for i in unique_combinations)

Note that I omitted list as it was not really needed.