Implementing factory design pattern with generics

Several considerations:

Base Factory class does all the work, so I would simply merge it into the generic method.
Your singleton instance is stored in a public field. This means any part of your program can easily replace it. You should make it readonly, or (even better) expose it through a readonly property.
If you are not abstracting the factory (i.e. exposing the Instance property as an interface), it means there is no way to use any other factory in your program. This has two possible consequences:

you can either skip accessing Instance every time and use a plain static method (Factory<T>.Instance.DoStuff(...) becomes Factory<T>.DoStuff(...), which is slightly shorter)
or, you can decide that you want to hide the implementation of the factory behind an interface (IFactory<T>, for example), in which case a concrete factory will be stored in an instance of a separate class, which would completely change the call to something like DAL.GetFactory<T>().DoStuff(...) (DoStuff becomes an instance method). This leaves allows greater flexibility, since you can pass an IFactory<T> to a part of code which doesn't need to know about your static DAL classes. But it would require additional redesign.

If you add a new generic parameter to the RegisterProductType method, you can use the where clause to limit the type to derived types at compile time. Getting a compile error is much better than getting a run-time one.
Are you sure that you need to pass the constructor parameters to the GetProduct method? This part might be slightly unusual (although there might be cases where you would want to instantiate your classes by passing a parameter). What it there is a specific derived type which accepts different parameters than other types? Activator.CreateInstance indicates that you are forcing all your callers to know which constructor your method will use.

First four points (simplified) would result in something like:

public class Factory<T>
{
    private Factory() { }

    static readonly Dictionary<int, Type> _dict = new Dictionary<int, Type>();

    public static T Create(int id, params object[] args)
    {
        Type type = null;
        if (_dict.TryGetValue(id, out type))
            return (T)Activator.CreateInstance(type, args);

        throw new ArgumentException("No type registered for this id");
    }

    public static void Register<Tderived>(int id) where Tderived : T
    {
        var type = typeof(Tderived);

        if (type.IsInterface || type.IsAbstract)
            throw new ArgumentException("...");

        _dict.Add(id, type);
    }
}

Usage:

Factory<IAnimal>.Register<Dog>(1);
Factory<IAnimal>.Register<Cat>(2);

// this is the "suspicious" part.
// some instances may require different parameters?
Factory<IAnimal>.Create(2, "Garfield");

Fifth point is worth considering. If you change your factory to this:

public class Factory<T>
{
    private Factory() { }

    static readonly Dictionary<int, Func<T>> _dict
         = new Dictionary<int, Func<T>>();

    public static T Create(int id)
    {
        Func<T> constructor = null;
        if (_dict.TryGetValue(id, out constructor))
            return constructor();

        throw new ArgumentException("No type registered for this id");
    }

    public static void Register(int id, Func<T> ctor)
    {
        _dict.Add(id, ctor);
    }
}

Then you can use it like this:

Factory<IAnimal>.Register(1, () => new Dog("Fido"));
Factory<IAnimal>.Register(2, () => new Cat("Garfield", something_else));

// no need to pass parameters now:
IAnimal animal = Factory<IAnimal>.Create(1);

This delegates all construction logic to init time which allows complex scenarios for different object types. You can, for example, make it return a singleton on each call to Create:

// each call to Factory<IAnimal>.Create(3) should return the same monkey
Factory<IAnimal>.Register(3, () => Monkey.Instance);


Making a directory structure for a web project

I think it would be nice, if you could define the directory structure once and then let the program create it. Something like this:

import os

folders = ["css", "resources/img", "resources/js"]

name = input("Enter the name of your project here: ")
for folder in folders:
    os.makedirs(os.path.join(name, os.path.normpath(folder)))
os.chdir(name)
...
# file opening like Peilonrayz suggested

This uses a list and os.path.join, which allows joining filenames with the platform specific file name separator (\ for Windows, / for UNIX), os.path.normpath to convert the / in the path to \ in case you are on Windows and it also uses a for-loop, if you have not seen them, yet.


The typical insertion sort is O(n) for already sorted input, and "almost O(n)" for "almost sorted" input. Which is somewhat common in real world data. Your way you don't have that, you're \$\Theta(n^2)\$. Someone not familiar with how lists work internally might think your code is O(n) for reverse-sorted input, but since del lst[i] takes O(n - i) and lst.insert(j, val) takes O(n - j), that's not the case.
As Ted points out, better don't both modify and return. Choose one or the other. Just like Python's own sorting functions do: list.sort only modifies, and sorted only returns (well, it necessarily "modifies" a given iterator by consuming it).
"Insertion a list"... huh? insertion seems like an incomplete name for insertion sort. You can't really tell from the function signature what it does (and there's no doc string, either).
I'd go with enumerate, then you have val already, which is nicer and faster.

Improved version sticking with search-from-left but incorporating the other points:
def insertion_sort(lst):
    for i, val in enumerate(lst):
        for j in range(i):
            if val < lst[j]:
                del lst[i]
                lst.insert(j, val)
                break

A benchmark sorting 10000 random numbers:
2.17 seconds  insertion
1.69 seconds  insertion_sort

2.15 seconds  insertion
1.66 seconds  insertion_sort

2.17 seconds  insertion
1.69 seconds  insertion_sort

Benchmark code:
from timeit import timeit
from random import random

def insertion(lst):
    for i in range(1, len(lst)):
        for j in range(i):
            if lst[i] < lst[j]:
                val = lst[i]
                del lst[i]
                lst.insert(j, val)
                break
    # return lst

def insertion_sort(lst):
    for i, val in enumerate(lst):
        for j in range(i):
            if val < lst[j]:
                del lst[i]
                lst.insert(j, val)
                break

for _ in range(3):
    lst = [random() for _ in range(10000)]
    for func in insertion, insertion_sort:
        copy = lst * 1
        t = timeit(lambda: func(copy), number=1)
        assert copy == sorted(lst)
        print('%.2f seconds ' % t, func.__name__)
    print()

Try it online!


C++ shared pointer wrapper for lazy initialization

A really useful idea - well worth creating.
Missing #include <memory>.  With that fixed, I get almost clean compilation:
255367.cpp:9:5: warning: ‘LazySharedPtr<int, int>::init’ should be initialized in the member initialization list [-Weffc++]

I agree, we should use the initialisation list for init:
LazySharedPtr(Args ... args)
    : init{[args = std::make_tuple(std::forward<Args>(args) ...)]() mutable
           {
               return std::apply([](auto&& ... args) {
                                     return std::make_shared<T>(std::forward<Args>(args) ...);
                                 }, std::move(args));
           }},
      ptr{}
{}

I don't see why we have the inner lambda.  There's no good reason not to pass std::make_shared() directly to std::apply(), like this:
LazySharedPtr(Args ... args)
    : init{[args = std::make_tuple(std::forward<Args>(args) ...)]() mutable
           {
               return std::apply(std::make_shared<T, Args...>, std::move(args));
           }},
      ptr{}
{}

I think the class could be easier to use.  There's no need for the argument types to be part of the class itself, as they are erased by std::function.  So make the class template have only T as argument.  Otherwise we need separate code paths for our smart pointers if they are created differently.  Much better to separate the type that is essential to the LazySharedPtr from those which are accidental:
template <class T>
class LazySharedPtr {
public:
    template <typename ... Args>
    LazySharedPtr(Args ... args);
}

There's some functionality missing that I would expect from a drop-in replacement for std::shared_ptr:

operator*
get()
reset()

I'd also expect a LazySharedPtr to be assignable to std::shared_ptr (invoking the creator function in the process).  That could reduce the need for these functions (especially reset(), which might not make sense here).
On the other hand, I don't think that LazySharedPtr is intended as a base class for inheritance, so shouldn't need a virtual destructor.  And we don't need IsInited(), given we already have operator bool.
Do have a think about what it means to copy a lazy-pointer object.  As it stands, copying a materialized instance yields another shared pointer to the same T object, but copying an unmaterialized instance will result in different T objects in the original and the copy.  I wonder if this could make it difficult to use correctly; we might want to make this a move-only type, and require casting to std::shared_ptr in order to copy (thus materialising the object).
For efficiency, InitAndGet() shouldn't copy the shared pointer, but return a reference.  I'm not fond of the naming - C++ convention uses snake_case for function names.
There's a lot of unnecessary this-> cluttering the code.

Modified code
#include <cstddef>
#include <functional>
#include <memory>
#include <tuple>
#include <utility>

template <class T>
class LazySharedPtr {
public:
    template <typename... Args>
    LazySharedPtr(Args... args)
        : ptr{},
          init{[args = std::make_tuple(std::move<Args>(args)...)]() mutable
               { return std::apply(std::make_shared<T, Args...>, std::move(args)); }}
    {}

    // compiler-defaulted copy/move construct and assign, and destructor

    auto operator->() const
    { return object().get(); }

    auto operator*() const
    { return *object(); }

    auto operator[](std::ptrdiff_t idx)
    { return object()[idx]; }

    explicit operator bool() const noexcept
    { return ptr; }

    explicit operator std::shared_ptr<T>() const
    { return object(); }

private:
    mutable std::shared_ptr<T> ptr;
    std::function<std::shared_ptr<T>()> init;

    auto& object() const
    {
        if (!ptr) { ptr = init(); }
        return ptr;
    }
};

int main()
{
    LazySharedPtr<int> a{0};
    auto b = std::shared_ptr<int>{a};
    return *b;
}


Consume rest endpoint removing payload's unwanted properties and falsy values

field: v for field, v in kwargs.items() if v and field in cls.fields

Feel free to break that into a multi-line comprehension.

Note that the in has linear cost w.r.t. len(cls.fields).

    """Valid fields' iterable. Override this as you need."""
    pass

Consider specifying that it shall be a set rather than just an iterable. (Also, I suppose return None would more clearly show that by default we don't return an iterable. Or consider doing an explicit raise.)


Default value mechanism in Lua using metatables

If you comment out secondSubTable from actualTable in the testPropertyShadowing test and run it you get an error because you cannot index a number value.

The problem is that you are assuming that the replacement value will be index-able but not all values are. Tables, strings and custom userdata can be indexed but functions, numbers, and nil (by default at least) cannot be.

You might want to consider checking for the default being a table (testing for userdata requires trying it in a pcall I believe and is probably not worth it). Alternatively, you could leave it alone and let people use anything they can index and keep both parts if they use something else.


checks validity of credit card in python (cs50 pset6)

Your program would benefit from breaking up logic into functions. This also eliminates the global variables involved.
if i%2 == (-2+len(number))%2

This line is strange and not immediately obvious what it's doing. A reversed iteration would be easier to understand.
import re

def luhn_digit(digit,double):
    if double:
        doubled = digit*2
        return doubled-9 if doubled>9 else doubled
    else:
        return digit

def is_valid_luhn(card):
    check_digit = int(card[-1])
    luhn_sum = sum([
        luhn_digit(int(digit),i%2==0)
        for i,digit in enumerate(reversed(card[:-1]))
    ])
    total = check_digit+luhn_sum
    return total%10==0

def is_valid_card(card):
    return (
        len(card) in (13,15,16) and
        is_valid_luhn(card)
    )

def get_card_type(card):
    if not is_valid_card(card):
        return "INVALID"
    if re.search("^3(4|7)", card):
        return "AMEX"
    if card[0] == str(4):
        return "VISA"
    if re.search("^5(1|2|3|4|5)", card):
        return "MASTERCARD"
    return "INVALID"

print(get_card_type(input("NUMBER: ")))


There are several ways to approach this.

The classic object oriented way is to make Payload be a simple interface class

class IPayload {
    virtual ~IPayload() = default;
    virtual std::string   toStr() = 0;
    virtual PropertyValue fromStr(const std::string &) = 0;
    virtual PropertyValue get() = 0;
    virtual void          set(PropertyValue) = 0;
};

And just create for each property its own instance of an implementation of the interface - depending on what kind of property one uses. This can be helpful when you need variety updating mechanisms to work simultaneously. Say, one Payload that stores the field only in memory, one that stores into both in memory and in a file, and one that forwards it to GUI - or a combination of these. This can be also helpful when you require specialized treatment for some properties - like time input property - that upon receiving std::string input it processes it according to some time conversion, i.e., read double and then converts it to seconds depending on the time unit specification, e.g., "5min" converts to 300 (seconds). The only issue is that you ought to instantiate a treatment for each property - which can be a hassle and make the class unsuitable for some trivial basic usages.

I don't see any circumstances when the std::function approach would better - unless one has to runtime change setters or something - which is kinda odd honestly.

Also you can try going in the opposite direction and detach the storage class from the "customized actions". Say, make a simple multipurpose ini file parser wrapping std::unordered_map<std::string,std::string> - or use an existing one like boost::ptree that can read and write xml and json in addition. While in the GUI simply call the right functions when user sets the fields. Whether it is viable / not viable / preferred option depends a lot on your development platform for the GUI as well as other nuances.

You can in fact combine the two methods. Use the boost::ptree for storing / parsing and for internal usage whilst class PropertySet make responsible for the GUI handling and just instantiate one from each other upon loading / saving / updating.


Create a list of all strings within hamming distance of a reference string with a given alphabet

Your strategy here is to keep a working set and repeatedly expand it by adding strings within Hamming distance 1 of elements in the set. This involves a lot of duplicated work, because the same candidate strings are going to be generated many times over (and then thrown away because they are already members of the working set).

I find that I get a substantial speedup just by generating each string exactly once.

from itertools import chain, combinations, product

def hamming_circle(s, n, alphabet):
    """Generate strings over alphabet whose Hamming distance from s is
    exactly n.

    >>> sorted(hamming_circle('abc', 0, 'abc'))
    ['abc']
    >>> sorted(hamming_circle('abc', 1, 'abc'))
    ['aac', 'aba', 'abb', 'acc', 'bbc', 'cbc']
    >>> sorted(hamming_circle('aaa', 2, 'ab'))
    ['abb', 'bab', 'bba']

    """
    for positions in combinations(range(len(s)), n):
        for replacements in product(range(len(alphabet) - 1), repeat=n):
            cousin = list(s)
            for p, r in zip(positions, replacements):
                if cousin[p] == alphabet[r]:
                    cousin[p] = alphabet[-1]
                else:
                    cousin[p] = alphabet[r]
            yield ''.join(cousin)

def hamming_ball(s, n, alphabet):
    """Generate strings over alphabet whose Hamming distance from s is
    less than or equal to n.

    >>> sorted(hamming_ball('abc', 0, 'abc'))
    ['abc']
    >>> sorted(hamming_ball('abc', 1, 'abc'))
    ['aac', 'aba', 'abb', 'abc', 'acc', 'bbc', 'cbc']
    >>> sorted(hamming_ball('aaa', 2, 'ab'))
    ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba']

    """
    return chain.from_iterable(hamming_circle(s, i, alphabet)
                               for i in range(n + 1))

In pure Python, this runs about 4 times as fast as the code in the original post.


Deleting email using mailcore with imapSession

I don't know anything about mailcore2, nor have you provided any Time Profiler information to help narrow down what takes so long to complete the action (is it just a slow network, or is it something in your code?  Anyone's guess), so I can't really address the slowness issue.  I also don't have a clue which methods are yours versus what you simply get from mailcore2, but with that said...

NSLog() statements should almost always be wrapped in #if DEBUG and #endif statements.

Moreover, regardless of whether or not the deletion is successfully, we need to let the user know one way or the other, and NSLog() isn't going to cut it.

I'm not sure how the second code snippet ties to the first, but all of our methods could use better names.

deleteOnServer(indexSet:) - delete what?  on which server?  What does index set represent?

createNewIMAPSessionWith - the words New and With can both be removed from this method.  Although, what would probably be best is simply creating a factory method:

extension MCOIMAPSession {
    class func session(userName: String, hostname: String, oauth2Token: String) -> MCOIMAPSession {
        // all the code you're already doing
    }
}

And then we call it simply like this:

let imapSession = MCOIMAPSession.session(userName:"username", hostname:"hostname", oauth2Token:"token")

localCopyMessageOperation!.start

This is a pretty big no-no, in my opinion.  If the method we're calling to get localCopyMessageOperation returns an optional, then we should use real optional chaining, not forced unwrapping.  It's as simple as changing the exclamation point to a question mark and it prevents an "found nil when unwrapping" (or whatever it's called) exception.


Method that filters a list parameters based on different fields

Your code has lots of duplication. You can make it more readable:

private bool FilterLicenseList(object item)
{
    var license = item as LicenseEntry;
    return FilterString(Filter.Firm, license.Firm)
        && FilterString(Filter.RegistrationCode, license.RegistrationCode)
        && FilterString(Filter.LicenseCode, license.LicenseCode)
        && FilterString(Filter.Branch, license.Branch)
        && FilterBoolean(Filter.Active, license.Active);
}

All you need to do now is to implement the two helper methods FilterString and FilterBoolean.

I know that even the rewritten code is visually redundant since the field name appears twice in each line of code, but removing this would be more difficult. Compared to the original code I find the rewritten code much more readable, and there is no chance that in one of the lines an exclamation mark is missing, which would be pretty easy to overlook.


Class member method based multithreading [C++]

I think you have an OK approach, however it's hard to tell if it's going to work for you because at the moment you seem to be at concept phase.  As you develop the application, you may find that having different methods for different thread loops may mean your class is responsible for too much.  I tend to prefer to have a class for each thread I create, which has a main thread function.  An example of which would be the WorkerThread in this question I posted.

Nested scopes in functions

As far as your coding style goes, I'm not super keen on the way you're using braces to create scoping for your mutex uses:

{
    std::lock_guard<std::mutex> lck(mtx);
    value1 = 0; value2 = 0; value3 = 0;
}

I'd be inclined to create a function with a name if I felt like I needed to have the extra scoping and put the body into it.  Your run method also re-initializes the values even these have been set in the constructor, it's unclear if this is on purpose or not.

Global Mutex

You've got std::mutex mtx; as a global.  If you're only going to be using it from within your AThreadedClass, it would be better as a static class member.  I'd also update its name to reflect what it is it's used to lock.

Atomic Vs Volatile

Whilst atomic is the safe option for running, I'm not sure you really need it to be atomic.  You never update its value outside of the mtx lock.  I would expect that marking it as volatile should be enough to prevent the compiler from optimizing out the checks in the while loops.


Converting enum values to strings in C++

Question 1: functionxxx_as_string() is used below. How else could it be more elegantly named?

How about:

std::ostream& operator<<(std::ostream& str, thing const& data);

  Question 2: Is the static char* array method adopted below the only solution? Best solution? Any suggestions?

You will need a static char array (or equivalent (like a switch)) somewhere as there is no built in way to convert enum values (which are integers) to a string.


Criticize my first attempt at using the itertools module

import itertools as iter

I dislike abbrevations like this. Itertools is widely used within the python community, and it only hinders code readability by using iter instead of itertools

def swaps_gen(s):
    '''This generator yields all the possible outcome of applying one swap
    to the input string'''
    X_positions = [i[0] for i in enumerate(s) if i[1] == "X"]
    O_positions = [i[0] for i in enumerate(s) if i[1] == "O"]

PEP 8 recommends lowercase_with_underscores for local variable names. Your comprehensions would be more clearly written as

X_positions = [index for index, value in enumerate(s) if value == 'X']

Because you do it twice, I'd consider writing a function

    for x in X_positions:
        tmp_x = X_positions[:]
        tmp_o = O_positions[:]

I despise uses of tmp in variable names. All variables are temporary.

        tmp_x.remove(x)
        tmp_o.append(x)

That's going to be expensive. The remove has to move the whole list back to make it fit.

        for o in O_positions:
            ttmp_x = tmp_x[:]
            ttmp_o = tmp_o[:]

Especially egregious is using tmp again with an extra t.

            ttmp_o.remove(o)
            ttmp_x.append(o)

            s = []

I wouldn't reuse s from before

            for i in ttmp_x: s.insert(i, "X")
            for i in ttmp_o: s.insert(i, "O")

Inserts may be expensive. It won't be so bad here because your inserts will be in mostly sorted order. But the one unsorted element in each list will cost you somewhat.

            yield "".join(s)

Your whole approach here is a bit awkward. I'd suggest something like

for x_index in x_positions:
    for y_index in y_positions:
         swapped_list = list(s) # copy string into list, so I can modify it
         swapped_list[x_index], swapped_list[y_index] = swapped_list[y_index],swapped_list[x_index] # swap elements
         yield ''.join(swapped_list) # back to list

Shorter and probably more efficient.

def flatten(l):
    '''flatten one level. [[a], [b, c]] --> [a, b, c]'''
    return iter.chain.from_iterable(l)

def max_x_after_swap(s, n):
    '''repeat the generate swap_gen n times.
    I used a set() to avoid duplicates.
    Then returns the highest number of consecutive "X"s it finds.'''

PEP 257 recommends using """ not ''' for docstrings. Also, the closing ''' should be on a line by itself

    outcomes = [s]

I'd make this a set, just for consistency with the next line

    while n > 0:

Why a while loop instead of a for loop?

        outcomes = set(flatten([list(swaps_gen(x)) for x in outcomes]))

I'd use outcomes = set(flatten(map(swaps_gen, outcomes))) There is no reason to use list here, as the generator will flatten just fine.

        n -= 1
    return max(map(nbr_of_consecutive_x, outcomes))

def nbr_of_consecutive_x(s):

I dislike abbreviation like nbr, I'd call this count_of_consecutive_x

    '''return the number of consecutive "X" '''
    return max([len(list(v)) for k, v in iter.groupby(s) if k == "X"])

You don't need the [], because max will take a generator expression just fine

def main():
    input = "XXOXOXOXO"
    swaps_nbr = 2
    print(max_x_after_swap(input, swaps_nbr))

main()


Intersection of subset between two lists of dicts

Although a list comprehension is generally an efficient way to go about things, in this case it means you check every obj0 against every obj1, even if you've already found a match. To avoid that:

out = []
for obj0 in ld0:
    for obj1 in ld1:
        if obj_equal_on(obj0, obj1, keys):
            out.append(obj0)
            break
return out

Beyond that, you could consider using a custom immutable class rather than dictionaries, implementing __eq__ and __hash__ and using sets rather than lists to efficiently determine the intersection.


Optimizing a dynamic programming solution for "Oil Well"

It is not possible to make this solution fast enough. The number of states in your dynamic programming is O(2^numberOfVertices)(the number of subsets of a set with numberOfVertices elements), which is 2^2500 in the worst case under given constraints. So a more efficient algorithm is required.


You could try for a more functional expression that matches problem description more closely:

 Stream.from(1).filter(!set.contains(_)).head

[Caveat: I'm not a scala programmer, I have no idea how idiomatic this is]


Could this template function be improved?

The use of template parameters here is just fine. You can call the second one UnaryPredicate if that makes you happier, but in the end, C++ currently lacks the ability to specify further requirements on template arguments. (That's what concepts are for.)

So you really need to specify the detailed requirements in prose in the documentation, e.g.

  ContainerType must fulfill the Container requirement, and its value_type must be Copyable. Predicate must be an UnaryPredicate taking value_type as its argument.

What you could possibly improve is making this more efficient in C++11 when the argument is a temporary.


Add an entry to every element in a nested data structure

You could maybe make your solution a bit neater by using a lambda in place of one of your partials.  assoc might be a little clearer in purpose than a conj as well:

(def sample-board-solved
  (map (partial map #(assoc % :explored true))
       sample-board))

Using map like this will return things in sequences rather than vectors like the input data.  If it's particularly important that you get vectors out you can always use mapv


SQL query on percentage share of different groups in total

CTEs

A CTE is an optimization fence. You'll want to try to avoid it and at the least convert it into a subquery.

Casting

Do an explicit cast instead of an implicit cast:

0.00 + COUNT(*)

becomes

count(*)::real

Between

Rather than writing

  loan_loan.created_at > '2019-08-15' and
  loan_loan.created_at < '2019-09-05'

write

  loan_loan.created_at between '2019-08-15' and '2019-09-05'

Joining

More broadly: are you sure this is doing the right thing? You aren't selecting type from your CTE to join to your upper query's loan_loan.type. Given the lack of this join, I fail to see how your total column will be reliably matched to your upper rows.


Finding the most common section from the visible cells in a collection view

Re 1: You can take advantage of reduce(into:_:) which was introduced in Swift 4 precisely for this purpose:

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

See also SE-0171 Reduce with inout:

Motivation
The current version of reduce needs to make copies of the result type for each element in the sequence. The proposed version can eliminate the need to make copies (when the inout is optimized away).

In your case:
 let counted = visible.reduce(into: [Int: Int]()) { (result, path) in
    result[path.section, default: 0] += 1
}

The compiler can also infer the type of the initial accumulator automatically if the closure consists only of a single statement:
let counted = visible.reduce(into: [:]) { (result, path) in
    result[path.section, default: 0] += 1
}

Re 2: A dictionary is a collection of key/value pairs, therefore it can be sorted directly, without mapping each key to a tuple first:
let section = counted.sorted(by: { $0.value > $1.value }).first?.key

Even better, use max(by:) to find the dictionary entry with the maximal value:
let section = counted.max(by: { $0.value < $1.value })?.key

This is shorter and eliminates the intermediate arrays and the dictionary lookup. It is more efficient than sorting an array because only a single traversal of the collection is done. And even if the forced unwrapping is safe in your case, it is nice not to have it.

One could also make this a generic method for sequences
extension Sequence {
    func mostFrequent<T: Hashable>(by map: (Element) -> T) -> T? {
        let counted = reduce(into: [:]) { (result, elem) in
            result[map(elem), default: 0] += 1
        }
        return counted.max(by: { $0.value < $1.value })?.key
    }
}

which is then used as
let section = collectionView.indexPathsForVisibleItems.mostFrequent(by: { $0.section })


I have very minimal flow experience, but the action definition looks right. You may also be able to define a state type for this reducer.

It's pretty generic right now, so I'm not sure I would push it much more. Maybe it should be called fetchReducerFactory, just to keep the terminology consistent.

The tests look good. By "reliable", you probably mean "good." They are readable and look to provide good coverage for the code and branches.

You may want to test that the default state is correct.
You may want to test that unknown actions do nothing to the state.

NOTE: The following comment is pretty minor, but wanted to bring it up. The way the code is structured, the tests make sense. But there are implicit cases that work because of the code structure. Let me explain:

You expect FETCH_TEST_SUCCESS to do 3 things: (1) clear the isLoading flag (2) set data to the payload, and (3) set error to null. These three behaviors are wrapped together in one test. And, the only data that is actually changed by the reducer in this test is the data property; isLoading and error are not changed. So, for this test, you could make sure all values are changed by passing in a different state:

expect(
       factory({ data: null, isLoading: true, error: 3 },
               { type: "FETCH_TEST_SUCCESS", payload: "success" })
       ).toEqual({
         data: "success",
         isLoading: false,
         error: null
  });

This will guard against code changes later where someone refactors. Or, you could just have three small tests, each that test single property mutations. Again, small potatoes.


today

First of all, I'm super confused as to why you're doing

today = datetime.date.today()
today = today.strftime("%m/%d/%Y")
today = datetime.datetime.strptime(today, "%m/%d/%Y")

It seems like you'd be fine if you just did

today = datetime.datetime.today()

Additionally, constants (such as today) are traditionally named in ALL_CAPS.

days_between

It is very counter-intuitive to me that this only takes a single argument.  I think writing it this way

def days_between(d1, d2):
    return (d2 - d1).days

def days_from_today(date):
    return days_between(date, today)

makes much more sense.

find_dt

I don't like everything that is going on here.  First of all, I would argue that it shouldn't be the job of find_dt to convert an input string to a datetime object - the caller should be responsible for that.

Next, you're doing two distinct things.  One is displaying the day of the week for the given date, and the other is displaying information about that day being a US holiday.  These should probably be distinct.

def day_of_week(date):
    date_string = date.strftime("%A")

    from_today = days_from_today(date)
    if from_today == 0:
        info_string = "Today IS {}"
    elif from_today <= 1:
        info_string = "It will be a {}"
    else:
        info_string = "It was a {}"
    print(info_string.format(date_string))

A few notes about this.  I didn't call days_from-today every time - that's pretty wasteful.  Additionally, because each one does basically the same thing, instead of repeating the print I create the appropriate string and then just print into that at the end.

Next, holidays.

def holiday_status(date):
    us_holidays = holidays.UnitedStates()
    us_h = us_holidays.get(date)

    from_today = days_from_today(date)

    if us_h is None:
        if from_today == 0:
            print("Today is not a holiday")
        elif from_today <= 1:
            print("It won't be a holiday")
        else:
            print("It wasn't a holiday")
    else:
        if from_today == 0:
            info_string = "Today is {}"
        elif from_today <= 1:
            info_string = "It'll be {}"
        else:
            info_string = "It was {}"
        print(info_string.format(us_h))

Notice that I used some similar strategies as with day_of_week.  I also broke up your if statements a little more - while some people think nesting is bad, I think in this case it makes it much more clear what the conditions are.

__main__

You should have a block like this

if __name__ == '__main__':
    main()

at the bottom of your file.  Then it is import safe.

Locale

While right now you assume the US, it is conceivable that your users may be from other locales.  You probably want something like this (the specifics of this depend on your Python version, but this is a rough approximation)

LOCALE_ENUM = enum("US UK FR JP ...")
LOCALES = {
    LOCALE_ENUM.US: holidays.UnitedStates(),
    LOCALE_ENUM.UK: holidays.UnitedKingdom(),
    ...
}

and then to define both find_dt and holiday_status to take a LOCALE_ENUM instance and use it to determine what locale's holidays they should use.


Conditionally set attributes in MongoDB based on form fields

I'm not 100% sure there is a particularly elegant way to write this. If the code did not have a different body for each if statement, one could rewrite it like this

FORM_VALUES = {
    "priority": accident.priority,
    "status": accident.status,
    "duration": accident.duration,
    "service_status": accident.service_status
}

for key in FORM_VALUES:
    if request.form.get(key) and int(request.form[key]) != FORM_VALUES[key]:
        # As you use different functions for setting the values, this isn't possible
        request.set_value(key, request.form[key])

However, that is not the case, so don't get your hopes up. Regardless, there are still improvements to be made:

You're not checking that the header values are valid integers. I'd recommend either checking they are by using string.isdigit() or otherwise wrapping your calls to int() in a try except block.
You can use 'reason' in request.form instead of request.form.get('reason'); they have the same meaning in the places you've used them, but the first is easier to read.
It might be good if you used an enumeration for the values to Accident.status. As it is, checking that accident.status == 1 doesn't tell me anything; using a meaningful identifier might solve this. You can do this quite simply, by just assigning values to each identifier: PENDING, IN_PROGRESS, FINISHED = STATUSES. I've used some random names, and assumed that there are 3 possible statuses, change this to be accurate. Then in your function, instead of if accident.status == 1, we can have if accident.status == PENDING, which is a lot easier to understand without needing to know the meaning of each value of status.
In general, you should try and be consistent with the ordering of your arguments: your set_reason takes first a reason, then a user argument, while all of your other methods take the user argument first. The set_service_status doesn't take a user argument at all, which is fairly impressive, considering it uses a user variable in the function.

Overall not bad code. I don't agree with your comments on how @property would be inappropriate there, but it's far from the end of the world. In general, I'd try and be more careful to validate user input, but it may be that you do not need to worry about that.


That's a very lengthly piece of code. To delete a Node, it's not about doing something confusing; it's about changing links around. Imaging this list:

1, 2, 3, 4, 5

In this case, 1 links to 2, which links to 3, and so on. So what if you want to remove 3, for example? Well, change the links so that 2 links to 4!

How? Well...

Rewrite the method so that it returns a boolean depending on if the delete was a success:

public boolean delete(int data) {

Handle special case head and empty list:

    SinglyLinkedNode nodeBeforeDelete = this.head;
    if (nodeBeforeDelete == null) { // List in empty
        return false;
    } else if (nodeBeforeDelete.getData() == data) {
        this.head = this.head.getNext();
        return true;
    }

Loop until you find the data:

    while (true) {
        SinglyLinkedNode next = nodeBeforeDelete.getNext()
        if (next == null) { // No data found in list
            return false;
        } else if (next.getData() == data) {
            break;
        }
        nodeBeforeDelete = next;
    }

Relink the nodes:

    SinglyLinkedNode next = nodeBeforeDelete.getNext();
    nodeBeforeDelete.setNext(next.getNext());
    next.setNext(null);

End the method:

    return true;
}

Result:

    public boolean delete(int data) {
        SinglyLinkedNode nodeBeforeDelete = this.head;
        if (nodeBeforeDelete == null) { // List in empty
            return false;
        } else if (nodeBeforeDelete.getData() == data) {
            this.head = this.head.getNext();
            return true;
        }
        while (true) {
            SinglyLinkedNode next = nodeBeforeDelete.getNext()
            if (next == null) { // No data found in list
                return false;
            } else if (next.getData() == data) {
                break;
            }
            nodeBeforeDelete = next;
        }
        SinglyLinkedNode next = nodeBeforeDelete.getNext();
        nodeBeforeDelete.setNext(next.getNext());
        next.setNext(null);
        return true;
    }


Optimised solution for implementing a queue with two stacks

Lets assume the following test case: First you push a million elements into the queue. Than you perform alternating a pop and a push. The pop will move all of the million elements of the first stack to the second one and the push will move all of them back to the first time. Every alternating push and pop call has a time complexity of O(size of queue). This is not very efficient and you get time problems really soon. And that is why you get the "Terminated due to timeout 2s" error on Hackerrank.

So copying the elements like crazy is definitely not the way to go. How can you improve it?

Here's a hint: The main error that you do is, that you assume that one of the stacks should be empty at all time. This doesn't have to be the case. Only copy if you really have to.

If you are still stuck, check out the solution:

  stack_newest_on_top keeps the newest elements on top.
So if you push one element into the queue, just push it onto this stack. Don't worry about the about stack_oldest_on_top.
void push(int x) {
   stack_newest_on_top.push(x);
}
 If you pop/front an element, do the same thing. Just use the top element from stack_oldest_on_top. Only if stack_oldest_on_top is empty. You need to move all the elements from stack_newest_on_top to stack_oldest_on_top.
void pop() {
    if (stack_oldest_on_top.empty()) {
        while (!stack_newest_on_top.empty()) {
            stack_oldest_on_top.push(stack_newest_on_top.top());
            stack_newest_on_top.pop();
        }
    }
    stack_oldest_on_top.pop();
}
 Notice, in the worst case a pop has still O(size of queue) time complexity. But it is called very rarely. In fact every element moves from the first stack only once to the second stack. This gives you an amortised time complexity of O(1).


Looping through multiple regex efficiently

Start writing in python3.x ;)

End of Life for python2.x will happen pretty soon 1
One regex to rule them all

Instead of looping over a the list to create a regex,

you could use the | char which will work as an or so it can handle multiple outputs

REGEX_FILTER = re.conmpile('lo|wlp2s0')
If you only need the parameters, a simple namedtuple will suffice

You could create a namedtuple that will get rid of the empty looking class
IMHO setting the variables outside of the init is bad style

I would get the different variables needed before, and only then create the NetworkInterface object.

Note I will not review getting the interface type, since I am nowhere near a linux atm

Code

from collections import namedtuple
import re

import netifaces

FILTER_REGEX = re.compile(r'lo|wlp2s0')
NetworkInterface = namedtuple('NetworkInterface', ['iface', 'mac', 'type'])

def get_mac(iface):
    addresses = netifaces.ifaddresses(iface)
    return addresses[netifaces.AF_LINK][0].get("addr")

def get_type(iface):
    """Just return TP for testing"""
    return "TP"

def find_network_interfaces():
    for iface in netifaces.interfaces():
        if FILTER_REGEX.search(iface):
            continue
        yield NetworkInterface(iface, get_mac(iface), get_type(iface))

if __name__ == '__main__':
    for nwi in find_network_interfaces():
        print(nwi.iface)
        print(nwi.mac)
        print(nwi.type)


is_dir function for FTP/FTPS connections

In case someone is interested, here's a follow up to MarcDefiant's comment about using ftp_rawlist(). It's fast if you're already using it for getting the file list as well. Here's a snippet from the filebrowser.php in my GitHub filebrowser project. It's certainly not on the same level as Flysystem but I enjoyed working on it :).

public function isDir($path,$contents=NULL){
    $name = getPathName($path);
    if($contents === NULL){
        $path = getItemPath($path);
        $contents = $this->scandir($path);
    }
    foreach($contents as $content => $data){
        if($content == $name){
            if($data['type'] == 'directory'){
                return TRUE;
            }
            return FALSE;
        }
    }
    return FALSE;
}

public function scandir($path=NULL){
    if($path === NULL){
        $path = $this->Path;
    }
    if(!$path){
        $path = ".";
    }
    if(is_array($children = @ftp_rawlist($this->conn_id, $path))){
        $items = array();

        foreach($children as $name => $child){
            if(!$name){
                continue;
            }
            $chunks = preg_split("/\s+/", $child);
            list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
            $item['type'] = $chunks[0]{0} === 'd' ? 'directory' : 'file';
            array_splice($chunks, 0, 8);
            $items[implode(" ", $chunks)] = $item;
        }

        return $items;
    }
    return FALSE;
}

function getPathName($path){
    return substr($path,strrpos("/".$path,"/"));
}


Readable implementation of Trie in Python

naming

Your naming is not consistent. sometimes you use letter, sometimes w for the same thing. I generally avoid 1-letter variable names, but if you use them, be consistent

dict.setdefault

using dict.setdefault, you can simplify your Trie.add method significantly

def add(self, word):
    curr = self.root
    for letter in word:
        curr = curr.children.setdefault(letter, TrieNode())
    curr.end_of_word = True

Then you can also change the TrieNode.children to an ordinary dict.

string representation

For debugging, it can be handy to have a string representation of a Node

def __repr__(self):
    return f'TrieNode(end_of_word={self.end_of_word}, children={tuple(self.children)})'

getting a node

Currently, there is no way in your Trie to get a node. Having this method would simplify the rest of the implementation

def __getitem__(self, word):
    curr = self.root
    for letter in word:
        curr = curr.children[letter]
    return curr

def get(self, word):
    return self[word]

If you changed the type of TrieNode.children to a dict instead of a defaultdict, this will raise a KeyError. If you left it at defaultdict, this will return an empty TrieNode: 'TrieNode(end_of_word=False, children=())', check for it, and raise the KeyError yourself

would simplify the rest of the implementation

def __getitem__(self, word):
    curr = self.root
    for letter in word:
        curr = curr.children[letter]
    if not (curr.children or curr.end_of_word):
        raise KeyError(f'{word} not in Trie')
    return curr

trie['foo']

TrieNode(end_of_word=True, children=('b', 'f'))

Search

With the method to get a Node, Search becomes as trivial as

def search(self, word):
    try:
        return self[word].end_of_word
    except KeyError:
        return False

words starting with prefix

This name can be shortened to starts_with.

Here, I would move the iteration to find the 'child-words' to the TrieNode, and recursively descend down the nodes

def child_words(self, prefix=''):
    if self.end_of_word:
        yield prefix
    for letter, node in self.children.items():
        word = prefix + letter
        yield from node.child_words(word)

Trie.starts_with becomes simply:

def starts_with(self, prefix):
    try:
        node = self[prefix]
    except KeyError:
        raise KeyError(f"Prefix `{prefix}` not in Trie")
    return node.child_words(prefix)

which returns the generator yielding words

list(trie.starts_with('foo))

['foo', 'foob', 'foobar', 'foof']

If you want to, you can even add in a inclusive boolean flag

def child_words(self, prefix='', inclusive=True):
    if inclusive and self.end_of_word:
        yield prefix
    for letter, node in self.children.items():
        word = prefix + letter
        yield from node.child_words(word, inclusive=True)

full code

class TrieNode:
    def __init__(self):
        self.children = dict()
        self.end_of_word = False

    def __repr__(self):
        return f'TrieNode(end_of_word={self.end_of_word},' \
               f' children={tuple(self.children)})'

    def child_words(self, prefix='', inclusive=True):
        if inclusive and self.end_of_word:
            yield prefix
        for letter, node in self.children.items():
            word = prefix + letter
            yield from node.child_words(word, inclusive=True)

class Trie_Maarten:

    def __init__(self):
        self.root = TrieNode()

    def add(self, word):
        curr = self.root
        for letter in word:
            curr = curr.children.setdefault(letter, TrieNode())
        curr.end_of_word = True

    def __getitem__(self, word):
        curr = self.root
        for letter in word:
            curr = curr.children[letter]
        return curr

    def get(self, word):
        return self[word]

    def search(self, word):
        try:
            return self[word].end_of_word
        except KeyError:
            return False

    def starts_with(self, prefix, inclusive=True):
        try:
            node = self[prefix]
        except KeyError:
            raise KeyError(f"Prefix `{prefix}` not in Trie")
        return node.child_words(prefix, inclusive)


Generally speaking, it is really well done, for several reasons: std::tuple often takes advantage of the empty base class optimization, which means that since you feed it lambdas, your class will often weigh almost nothing, and everything is correctly forwarded. The only things I see that could be improved are the following ones:

You could const-qualify apply and operator().
size should be static constexpr instead of static const to make it even clearer that it is a compile-time constant.
You should be consistent when qualifying std::size_t: either use the prefix std:: or leave it, but stay consistent.

As you can see, these are really minor improvements. I also have some other remarks, but those will be opinions more than actual advice:

int2type kind of already exists in the standard and is named std::integral_constant. However, I will concede that it takes another template parameter for the type and that it might be too verbose for your needs.
I had some trouble understanding how your recursion worked because it was in ascending order. For some reason, I am more used to descending order. I would have overloaded apply for int2type<0> and not for int2type<size-1> and performed a descending recursion. That would have allowed me to write:

template<typename ... Ts>
auto operator()(Ts&& ... ts)
{
    return apply(int2type<sizeof ... (Fs) - 1>(), std::forward<Ts>(ts)...);
}

And then, size wouldn't have had to be a member of the class anymore. But I have to admit that this is an opinion and not a guideline. Your code is good enough that I see almost nothing that could be improved :)


Unit testing legacy code with static classes

I happen to like your fix for making it testable, but would reverse the implementation order between the static method and the explicit interface method. This will allow you to slowly change existing code first to use the Singleton instead of the static and then finally use an injectable pattern:

public interface IHelperClass
{
    bool ReturnSomething();
}

public sealed class HelperClass : IHelperClass
{
    private static readonly IHelperClass instance = new HelperClass();

    private HelperClass()
    {
    }

    public static IHelperClass Instance
    {
        get
        {
            return instance;
        }
    }

    [Obsolete("Use the Instance singleton's implementation instead of this static method.")]
    public static bool ReturnSomething()
    {
        return Instance.ReturnSomething(); // Simply calls the Singleton's instance of the method.
    }

    bool IHelperClass.ReturnSomething()
    {
        return true; // The original static ReturnSomething logic now goes here.
    }
}


Random changes in a list of binary numbers

You could replace
        for position in range(l):
            if random.random() < mu:
                intList[number] = intList[number] ^ (1 << position)

with
        for bit in bits:
            if random() < mu:
                intList[number] ^= bit

after preparing bits = [1 << position for position in range(l)] before the show and importing the random function.
Don't know whether that helps when using numba, and you didn't provide benchmark code.


Disable reboot on control-alt-delete for RedHat/CentOS 5/6/7

That's a four calls to cat /etc/redhat-release.  A case statement could help reduce the clutter:

case "`cat /etc/redhat-release`" in
  *"release 5."*)
    cp /etc/inittab /etc/inittab.install
    sed -i 's/ca::ctrlaltdel/#ca::ctrlaltdel/' /etc/inittab
    init q
    ;;
  *"release 6."*)
    echo 'exec false' > /etc/init/control-alt-delete.conf
    ;;
  *"release 7."*)
    systemctl mask ctrl-alt-del.target
    systemctl daemon-release
    ;;
  *)
    cat /etc/redhat-release 2>&1 | mailx -s "ctrl-alt-delete disable failure" some.user@example.com
    ;;
esac


The cleanest way to solve this would probably be to check the argument before calling the super constructor. This allows the code to fail fast and prevents it from opening the file, rendering the close() call unnecessary:
public class TxtInputStream extends FileInputStream {
    public TextInputStream(String fileName) {
        // super call must be first statement so have to call validation method
        // as argument to super call
        super(checkFileName(fileName));
    }

    private static String checkFileName(String fileName) {
        if (!fileName.endsWith(".txt")) {
            throw new UnsupportedFileNameException();
        }
        return fileName;
    }
}

However, this is a pretty bad example for wrappers since the TxtInputStream does not add any functionality at all.
If you want to see some good examples have at look at which JDK classes implement InputStream:

BufferedInputStream: Buffers data, this can be useful when you are only consuming small amounts of data at a time, but reading such small amounts of data would be inefficient, e.g. for a network connection. Instead it reads larger chunks from the wrapped InputStream and when you then consume data it first serves it from the buffer.
CipherInputStream: Decrypts the data
InflaterInputStream: Uncompresses data

So assuming you read encrypted, compressed data over the network you could have:
InputStream networkInputStream = ...
BufferedInputStream bufferedInputStream = new BufferedInputStream(networkInputStream);
CipherInputStream cipherInputStream = new CipherInputStream(bufferedInputStream, cipher);
InflaterInputStream inflaterInputStream = new InflaterInputStream(cipherInputStream);

Then you can simply use inflaterInputStream like any other InputStream and do not even have to worry about all the previous processing steps which are taking place.


Verifying if one list contains a string from another list

The current code works but it is very awkward, as rolfl pointed out. I would add that you should never compare booleans with true or false, like what you're doing in:

} else if(k == models.size() - 1 && flag == false) {
    return false;
}

Instead, have

} else if (k == models.size() - 1 && !flag) {
    return false;
}

You can actually accomplish this task in a single, clear and easy line using the Stream API:

public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
    return titleOfVehicles.stream().allMatch(t -> models.stream().anyMatch(t::contains));
}

This does exactly what is written: it returns whether all elements in the given titles contains any of the given models.

Both allMatch and anyMatch are short-circuiting operations, so it will behave exactly like your current code.


Remove item from a list, which (of the 2) methods is better?

The two methods are functionally identical.
The first method is faster to execute.
The first method is clearer for someone who doesn't know the code.

Unless there's an "else" you need (that is, logic to execute if the item can't be found), I can't think of a reason to prefer the second approach.

First approach wins.


Setting fields, with default values, before saving a row

The problem with your code is that you keep repeating the same code over and over again.

If Not IsDBNull(dgvproformas.Item("columnName", e.RowIndex).Value) Then
  columnVar = dgvproformas.Item("columnName", e.RowIndex).Value
End If

What you need is function that does the same thing, so that you have code that looks more like this:

columnVar= fn(dgvproformas, "columnName", e.RowIndex)

Except we want to keep type safety so, a bit more like:

columnVar = fn(Of Integer)(dgvproformas, "columnName", e.RowIndex)

Personally, I like extension methods for something like this, and would create an extension method for it.  I would almost certainly name it GetValueOrDefault.

I believe you can eliminate the rowindex if you get the row, so combining the two...

Dim row = dgvproformas.Rows(e.RowIndex)
columnVar = row.GetValueOrDefault(Of Integer)("columnName")

Finally, I like meaningful names and dislike magic strings, so I like Nameof...

Dim row = dgvproformas.Rows(e.RowIndex)
columnName = row.GetValueOrDefault(Of Integer)(NameOf(columnName))


numList is not used (this is "ok" as numList[i] == i). There is value == mid or value == end several times. But this just means you are comparing a value to be found with an index. The correct way would be value == numList[mid].

Consider using a function that does the binsearch for you.

You may or may not use recursion. There is a nice way to do binsearch without recursion.

I have also incorporated some naming conventions of python. If you are interested try programs like pylint. I have also added a bit nicer string formatting and some other python features you can live without but can come handy.

"""Binary search."""
from random import randint

def bin_search(sorted_list, to_find):
    """Searches the sorted_list for a to_find.
    If the to_find is found return (True, index)
    Otherwise return (False, 0)
    """
    beg = 0
    end = len(sorted_list) - 1
    while beg <= end:
        mid = (end + beg) // 2  # integer division
        if sorted_list[mid] == to_find:
            return (True, mid)
        if sorted_list[mid] < to_find:
            (beg, end) = (mid + 1, end)
        else:  # sorted_list[mid] > to_find
            (beg, end) = (beg, mid - 1)
    return (False, 0)

# Create a sorted list of random numbers
MY_LIST = sorted(randint(0, 100) for _ in range(20))
print(MY_LIST)

while True:
    try:
        TO_FIND = int(input('Enter value you want to find: '))
        (FOUND, INDEX) = bin_search(sorted_list=MY_LIST, to_find=TO_FIND)
        if FOUND:
            print(f'Found {TO_FIND} at index: {INDEX}!')
        else:
            print(f'Value {TO_FIND} not found!')
    except ValueError:
        print('Invalid number to find')
```


Looking at your code, this jumps out at me:

    D = {}

    for x in range(n):

        if complement in D.values():

The D variable here is a dictionary. It is designed for \$O(1)\$ lookup of a key. But you are looping over n items, performing a test (complement in D.values()) that is \$O(m)\$ itself, since D.values() is an iterable and the in test will be a linear search.

I suspect you can get a lot of performance back if you figure out how to not do that: it looks like you are treating D as a list, since you are using x as the key and nums[x] as the value.

I'll point out to you that unlike lists, tuples are immutable and therefore can be hashed, which makes them valid as dict keys. So you can use a dict of tuples. Or a set of tuples.


Print how many times a sequence of characters appears in a string

Missed detection of EOF: getchar() returns an int with values in the range of unsigned char and the negative value of EOF.  Saving that result in a char loses distinctiveness should getchar() return EOF due to stdin becoming closed or input error.

//char ch;
//while ((ch = getchar()) != '#')
int ch;
while ((ch = getchar()) != '#' && ch != EOF)

Why uint16_t?  The input stream can be excessively long, and certainly more than 65,535.  Suggest a wider type.  (Good that code uses an unsigned integer.)

// uint16_t count = 0;
unsigned long long  = 0;

Code could do this with 2 variables rather than 3.

int ch;
previous = EOF;

while ((ch = getchar()) != '#' && ch != EOF) {
  if (previous == `e` && ch == `i') {
    count++;
  }
  previous = ch;
}

Recommend {}

// if (last_ch == 'e' && cur_ch == 'i')
//     count++;
if (last_ch == 'e' && cur_ch == 'i') {
    count++;
}

Grammar: Code goes though work to print are vs. is yet does not make correct with ei's vs. ei.


PHP subset of 2 arrays containing objects - compared only by 1 attribute

As far as these things go, I think your performance is going to be close to ideal.  There is maybe a little room for improvement, namely:

I'm pretty sure all you need is array_udiff.  My suspicion (and some quick tests) suggest that this:

$subset = array_diff( $array_2, array_intersect( $array_1, $array_2 ) );

Is exactly equivalent to this:

$subset = array_diff( $array_2, $array_1 );

(some details excluded for brevity) So save yourself an expensive function call.  My only other suggestion would be a more "global" change that may or may not be helpful.  In your example it looks like you don't care about the keys.  In that case, use them.  When you build your array of objects use order_hash( $obj ) as the key.  They you can do array_diff on the array_keys, without having to worry about compare_objects method, i.e.:

$array1 = [
    order_hash( $o1 ) => $o1,
    order_hash( $o2 ) => $o2,
];

$array2 = [
    ... same thing ...
]

$keys_to_check = array_diff( array_keys( $array2, $array1 ) );
foreach ( $keys_to_check as $key )
    do_something( $array2[$key] );

It is a different way of organizing your data structures, and it takes a little more awareness about how your objects are stored.  However, if these arrays of objects are being passed back and forth frequently, and if you are frequently doing these kinds of comparisons, it can save you a lot of time (I think) because you only have to do your hash calculation once per object, instead of doing it once per object per intersect.

I frequently organize my structures this way (and do lots of diffs on them), and I find it easier to follow.  Basically, the thinking changes from:

Use this function to compare these arrays and see which ones are different

to

Check the keys of this array to see which ones are different

Personally I prefer the latter.


I assume you'll have no more than 10 names/hours/percents, but you could use an std::vector in place of these arrays.  This will allow you any number of inputs without fear of exceeding the allotted 10.  If you don't need this for your assignment, then you can stick with what you have.
If you're allowed to use more of the STL, I'd recommend std::accumulate for summing up the values in a container.

For instance, your first loop in Percentage():

for (int i = 0; i < students; i++)
{
    total += hours[i];
}

can be done with this function as such (with the array):

// the 10 corresponds to the array size
// the 0 is the starting value of the accumulator

int total = std::accumulate(hours, hours+10, 0);

If you choose to use std::vector (or other STL container):

// functions cbegin() and cend() return const iterators

int total = std::accumulate(hours.cbegin(), hours.cend(), 0);

I'd slightly tweak the percentage calculation for clarity:

percent[i] = (double(hours[i]) / total) * 100;

Prefer to cast the C++ way:

// C way
double(hours[i])

// C++ way
static_cast<double>(hours[i])

It seems a little weird having Highest() display something.  You could instead return most, thereby making the function of type std::string.  That way, you can display this name from main() or wherever else.

You don't need the first two arguments.  They are passed in from main(), but also not modified by any previous functions.  I'd remove those two and just use local variables.

highest should be of type double since it's being assigned to a percent element.  Otherwise, you may receive a "possible loss of data" warning.  This is especially important for when the two values are being compared in the loop.

You could then have this:

// get the name
std::string most = Highest(percents, names, students);

// display it
std::cout << most << " worked the most hours." << std::endl;

std::string Highest(double* percent, string* names, int students)
{
    double highest = percent[0];
    std::string most;

    for (int i = 0; i < students; i++)
    {
        if (highest < percent[i])
        {
            highest = percent[i];
            most = names[i];
        }
    }

    return most;
}


Naming

I think you're naming convention is OK, it seems consistent which is the most important thing.  Some of your names could be a bit more specific:

std::function< void(SOCKET) > callback

callback doesn't tell me what the callback is for.  new_connection_callback might be more appropriate.

Shutdown

There's no obvious way to shutdown your server.  You just allow the object to be destroyed and hope for the best.  I'd usually add a shutdown to a class like this so that the listen thread can be shutdown cleanly.  The accept thread itself has a loop while (client == SOCKET_ERROR) which is a condition that is always true.  You may as well be saying while(1).

Startup

Since the class has no concept of state it doesn't know whether or not it's running.  This means you can't check if it's running when startup is called, so you get a strange error 'can't bind to socket' if you try to start the server on two different ports.  Usually you'd encounter this error if the port was already in use.  However, since the server port is an instance variable you get it because the SOCKET itself is already in use.

Constructor errors

This is a critical error:

if (WSAStartup(MAKEWORD(2, 2), &wsa) == SOCKET_ERROR)

If you can't get a socket, your application is in trouble.  Don't just write to the log, throw an exception so that the caller is aware that there has been a problem and they can stop processing.

Callbacks

It's often useful to pass an additional piece of data into a callback method (for example a pointer to an instance of a collection to add the new socket to).  With that in mind, I'd consider adding an extra parameter (usually a void*) to the callback.  You also might want to consider typedefing the callback to make it easier to update in one place (if you decide to in the future).

Something like:

typedef std::function<void(SOCKET)> accept_callback;

makes the function signatures more descriptive and concise:

tcp_listener(accept_callback callback);


Correctness
I assume this is a toy problem and you don't need to worry about overflow/underflow? If you do, you should be using longs to do all your math, and either returning a long or casting back to an int before you return it.
Performance
You don't need to keep an array of all the left sums. You can get away with just two ints, one containing the sum of numbers on the left and the other containing the sum of numbers on the right. In your second loop, look at the ith element. Add it to the leftSum and subtract it from the rightSum. Use that to do your math.
General
This also cleans up the math you're doing. totalSum - 2 * leftSums[i] is not at all intuitive. Using Math.abs is nice. Using Math.min() would be even nicer.
Java variables start with lowercase letters. int[] A doesn't conform to that standard. Also, abbreviations should be avoided in variable names. minDiff would be better as minimumDifference, and diff would be better as difference.
If I were to code this, it would look something like:
public final class Summer {

    public int solve(final int[] values) {

        long leftSum = 0;
        long rightSum = 0;
        for (int i = 0; i < values.length; i++) {
            rightSum += values[i];
        }

        long minDifference = Integer.MAX_VALUE;
        for (int i = 0; i < values.length; i++) {
            leftSum += values[i];
            rightSum -= values[i];
            final long difference = Math.abs(leftSum - rightSum);
            minDifference = Math.min(minDifference, difference);
        }

        return (int) minDifference;
    }
}


I don't quite exactly understand the logic, but you could extract out at least one method which removes lots of code duplication. I've inverted some conditions (which improves code readability) and placed some comments into the code too.

function processValue(&$form, $value, $i, &$form_sub) {
    if (!is_array($value)) {
        return;
    }

    // TODO: rename test to $keys or something more meaningful
    $test = array_keys($value);
    if (!is_array($test)) {
        // TODO: is it possible? according to the documentation
        // array_keys() always returns array
        return;
    }
    foreach ($test as $z) {
        if (strpos($z, '#') === 0) {
            continue;
        }
        if (!isset($form['field_afl_dienst_adressen']['und'][$i][$z])) {
            continue;
        }
        $form_sub[$i][$z]['#prefix'] = "
";
        $form_sub[$i][$z]['#suffix'] = "
";
    }
}

$address_afl = $form['field_afl_dienst_adressen']['und'];
$i = 0;
foreach($address_afl as $value) {
    processValue($form, $value, $i, $form['field_afl_dienst_adressen']['und']);
    $i++;
}

$address_bev = $form['field_bevoegde_adressen']['und'];
$i = 0;
foreach($address_bev as $value) {
    processValue($form, $value, $i, $form['field_bevoegde_adressen']);
    $i++;
}

A possible bug: both foreach has the following condition with the same $form index:

if (isset($form['field_afl_dienst_adressen']['und'][$i][$z])) ...

Maybe you want to change the second one to

if (isset($form['field_bevoegde_adressen']['und'][$i][$z])) ...

It would make possible some other refactorings (fewer parameters etc.), as Victor T. suggested.


Extension method replacing elements from an IEnumerable collection

Why didn't Microsoft include this in the .NET framework?

Probably because it can be realized in one line with Select:

source.Select(x => x.Equals(oldValue) ? newValue : x)

or with 2 lines as extension method if the function is needed frequently.

public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
    => source.Select(x => x.Equals(oldValue) ? newValue : x)

That's the nice thing of enumerable methods. There are just some discrete methods available, but those can be parameterized / combined to realize the most use cases. I really like the compactness and elegance of the LINQ API :).


An ES6 array of numbers - Double last number, delete the first number


A few notes about the original code.

If the ocean mostly empty it's actually a sparse matrix. If you are allowed to use more arrays or another primitive data structures check the Spare matrix Wikipedia article about it, it contains other, maybe more effective storage structures.
The second switch case contains the same logic three times. You could extract it out to a method to remove duplication:

private static int encode(int[] runType, int[] runLength, int currentType, int index) {
    if (runType[index] == currentType) {
        runLength[index]++;
    } else {
        index++;
        if (index == runType.length) {
            runType = doubleTheSize(runType);
            runLength = doubleTheSize(runLength);
        }
        runType[index] = currentType;
        runLength[index]++;
    }
    return index;
}

And use it in the switch:

switch (sea.cellContents(row, col)) {
case Ocean.EMPTY: {
    final int currentType = Ocean.EMPTY;
    index = encode(runType, runLength, currentType, index);
    break;
}
case Ocean.SHARK: {
    int currentType = Ocean.SHARK;
    index = encode(runType, runLength, currentType, index);
    break;
}
case Ocean.FISH: {
    int currentType = Ocean.FISH;
    index = encode(runType, runLength, currentType, index);
    break;
}

After that it's easier to notice that the whole switch-case could be eliminated since the body of every case statement is very similar to each other and depends on only the sea.cellContents(row, col) value.

final int currentType = sea.cellContents(row, col);
index = encode(runType, runLength, currentType, index);

int[] runLength = new int[10]; // corresponding index cell stores its number of occurence of that respective runType.

I'd put the comment before the line it comments:

// corresponding index cell stores its number of occurrence of that respective runType.
int[] runLength = new int[10];

It's easier to work with because it requires less horizontal scrolling.
A comment says the following:

// i&j are width & height of a 2d array read from commandline

Then you can use width and height as variable names for better readabilty (you don't have to remember what i or j mean nor check the comment for it) and could get rid of the comment.
The temp variable in doubleTheSize could be called doubledArray or newArray, arg is oldArray or originalArray. It would express the purpose of them.
Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could show blocks.

    }// end outer for loop
}// end main()

“// …” comments at end of code block after } - good or bad?


Detecting arrays with enough entries in common

This testing routine runs three to four times faster on the test data:

function testing($dataArray,$source,$limit)
{
  $matchesFound = 0;
  foreach ($dataArray as $data)
  {
    $counter = 0;
    foreach ($data as $number)
    {
      if (!in_array($number,$source)) $counter++;
      if ($counter == 2) break;
    }
    if ($counter == 1) $matchesFound++;
    if ($matchesFound >= $limit) return implode("-", $source);
  }
  return "x";
}

A big assumption is that $dataArray only contains arrays of 6 numbers and you will always look for 5 matching numbers.

The improvement is that I stop looping as soon as I know whether there is a match or not. You simply loop over all the data. So the real speed improvement depends heavily on the data. My guess is that it can perform even better on the complete data set.

More can probably be gained if your question was more informative.


Overall, your code is pretty readable and understandable.

There is an unneeded type on tokens; it can just be Vec<_>.
There's no need to collect to a vector at all! The current code takes an iterator, stores it in a vector, then converts it back into an iterator. Instead, just use the first iterator.
It's unusual to use from_str directly. Usually, you call parse on the string.

That's the basic style stuff, looking up a level...

There's a lot of repeated code for the 5 binary operators. I'd suggest refactoring these out:

struct Stack(Vec<f64>);

impl Stack {
    fn new() -> Stack { Stack(Vec::new()) }

    fn pop(&mut self) -> Option<f64> {
        self.0.pop()
    }

    fn parse(&mut self, token: &str) {
        self.0.push(token.parse().unwrap());
    }

    fn binary<F>(&mut self, f: F)
        where F: Fn(f64, f64) -> f64
    {
        let b = self.0.pop().unwrap();
        let a = self.0.pop().unwrap();
        self.0.push(f(a, b));
    }
}

fn rpn(expression: &str) -> f64 {
    let mut stack = Stack::new();

    for token in expression.split_whitespace() {
        match token {
            "+" => stack.binary(|a, b| a + b),
            "-" => stack.binary(|a, b| a - b),
            "*" => stack.binary(|a, b| a * b),
            "/" => stack.binary(|a, b| a / b),
            "^" => stack.binary(|a, b| a.powf(b)),
            _ => stack.parse(token),
        }
    }

    stack.pop().unwrap()
}

fn main() {
    let expression = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
    println!("{}", rpn(expression));
}

There's also a lot of unwrap calls. This is fine for quick code that you don't expect to have non-programmers using, but often it's a good idea to try and see how error reporting can work:

use std::{error, fmt, num};

#[derive(Debug)]
enum Error {
    InvalidNumber(num::ParseFloatError),
    EmptyStack,
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::InvalidNumber(..) => "Not a valid number",
            Error::EmptyStack => "No numbers on the stack",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::InvalidNumber(ref e) => Some(e),
            Error::EmptyStack => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", error::Error::description(self))
    }
}

impl From<num::ParseFloatError> for Error {
    fn from(e: num::ParseFloatError) -> Error { Error::InvalidNumber(e) }
}

struct Stack(Vec<f64>);

impl Stack {
    fn new() -> Stack { Stack(Vec::new()) }

    fn pop(&mut self) -> Option<f64> {
        self.0.pop()
    }

    fn parse(&mut self, token: &str) -> Result<(), Error> {
        self.0.push(try!(token.parse()));
        Ok(())
    }

    fn binary<F>(&mut self, f: F) -> Result<(), Error>
        where F: Fn(f64, f64) -> f64
    {
        let b = try!(self.0.pop().ok_or(Error::EmptyStack));
        let a = try!(self.0.pop().ok_or(Error::EmptyStack));
        self.0.push(f(a, b));
        Ok(())
    }
}

fn rpn(expression: &str) -> Result<f64, Error> {
    let mut stack = Stack::new();

    for token in expression.split_whitespace() {
        let r = match token {
            "+" => stack.binary(|a, b| a + b),
            "-" => stack.binary(|a, b| a - b),
            "*" => stack.binary(|a, b| a * b),
            "/" => stack.binary(|a, b| a / b),
            "^" => stack.binary(|a, b| a.powf(b)),
            _ => stack.parse(token),
        };
        try!(r);
    }

    stack.pop().ok_or(Error::EmptyStack)
}

fn main() {
    let expression = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
    println!("{:?}", rpn(expression));
}

Rust has a built-in testing framework, so I'd encourage you to use it. It's easy enough to throw in some tests instead of visually comparing the output of main. I've wrapped the tests in a bit of ceremony here to ensure they aren't compiled during a production build:

// Add `PartialEq` to the `derive` on `Error` to allow comparison

#[cfg(test)]
mod test {
    use super::rpn;

    #[test]
    fn golden_master() {
        assert_eq!(Ok(3.0001220703125), rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
    }
}

  I had attempted to write the commutative operations without assigning the operands to variables

Yes, this is a current limitation of the borrow checker. The entire expression is borrow checked at once, and it sees that stack.push requires a mutable borrow and stack.pop requires an immutable borrow. Since you can't have any other borrows during a mutable borrow, you get the error. It isn't currently smart enough to understand that the immutable borrow ends before the mutable borrow begins.

There is work in progress to loosen up these checks, but separate variables is the current solution.

For the alternate code:

There's no need for an explicit type on parse. The fact that it needs to be a f64 can be inferred.
Use an if let expression instead of if_ok. This avoids the need to unwrap and better communicates intent.
Having a no-op fallthrough case in the match is too loose for my tastes. I'd panic there to indicate that something unexpected happened. That way if I tried to use something like ** for exponentiation it isn't silently ignored.

fn rpn(expression: &str) -> f64 {
    let mut stack: Vec<f64> = Vec::new();
    for token in expression.split_whitespace() {
        if let Ok(value) = token.parse() {
            stack.push(value);
            continue;
        }

        let b = stack.pop().unwrap();
        let a = stack.pop().unwrap();
        match token {
            "+" => stack.push(a + b),
            "-" => stack.push(a - b),
            "*" => stack.push(a * b),
            "/" => stack.push(a / b),
            "^" => stack.push(a.powf(b)),
            other => panic!("Unknown symbol `{}`", other),
        }
    }
    stack.pop().unwrap()
}


I am thinking of removing timeoutStyle and timeout from the Cache constructor and providing default values that can be changed via public properties. How do you like that?

Does it make sense to change these properties in the middle of using the cache? Is it a desirable feature? If yes, go ahead. If not, and you just want to provide default values to make it easier to construct the class, then add a default constructor that calls the existing one.

I don't know enough C# to comment on the rest, I hope you'll get good reviews!


Reminds me of the days where <marquee> was the easiest way to add this kind of animation.

In terms of markup, your markup makes sense. However, I suggest you also move the title inside the markup instead of being in the JS.

With regards to your problem with timers, browsers usually slow down timers when the tab is inactive. This is to conserve battery life. As far as I know, setInterval, setTimeout and requestAnimationFrame are all affected.

Another problem I see is you animate in intervals. You don't let the animation finish before animating the next item. What you should do here is put your animation in a function, and when it finishes, it calls itself recursively from the complete callback. That way, you know it finishes before pulling in the next item.

Now if you don't mind CSS3, you can simply use transition or the more advanced animation property coupled with @keyframes block.

Now here's my take on your problem. The main difference here is I animate the entire list. That way, I only need to deal with 1 item when animating. There is a padding on each item to show a gap between items.

var list = $('.news ul');
var totalWidth = 0;
var items = $('.news li').each(function(){
  totalWidth += $(this).outerWidth();
});

function scrub() {
  // Note that we added a wrapper. That's so the entire list scrubs in,
  // and you don't have to deal with it individually.
  list.animate({
    // We animate the left all the way past negative so text travels from
    // right to left and we read left to right.
    left: -totalWidth
  }, {
    easing: 'linear',
    // We adjust speed here. Here it is 20ms per pixel.
    duration: totalWidth * 20,
    complete: function(){
      // When the animation is done, we just move the element back to its
      // starting position, which is off-screen to the right.
      $(this).css({ left: '100%' });
      // Run scrub again.
      scrub();
    }
  });
}
// Start the scrub
scrub();
.news {
  border-radius: 7px;
  background-color: lightgray;
  padding: 8px;
  font-size: 12px;
  overflow: hidden;
}
.news header {
  float: left;
  color: red;
}
.news .wrapper {
  overflow: hidden;
}
.news ul {
  left: 100%;
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
  white-space: nowrap;
}
.news li {
  padding-right: 50%;
  min-width: 100%;
  display: inline-block;
}

  Headlines

Foo!Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ac ligula nec tortor facilisis pharetra a ut arcu. Ut lacus libero, finibus sit amet risus id, rutrum malesuada odio.

Bar!Aliquam luctus dapibus eros id eleifend. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ac tellus sem. Integer laoreet sem in ex tincidunt fringilla.


Algorithm
The algorithm works well enough. You have captured the essence of the problem in your code, and reading your code it is apparent what it does, and why.
This is a good thing. It is not very often that the intent of the code is so easy to discern.
The draw-back of your algorithm is that it is not going to be able to support the more esoteric operations like parenthesis e.g. ( 123 - 45 ) ^ 2 .... That sort of support will require a preprocessing step.
Keeping the equation as a string is convenient for some things, but i would have preferred to see the process broken down in to components, for example, a parse step could break the input down to List<String> eqnParts = parse(eqn). at the same time, it could be trimming the white-space. Then, you just need to scan the List<String> and find 3 items separated by the highest precedence operator, and swap all three with the resulting value.
Code Style
You should read through the Code Style Guidelines for Java.
This code, for example, has a number of faults:

        for( i = left.length() - 1; i >= 0; i--)
            if(!isPONumber(left.charAt(i)))
                break;
        for( j = 0; j < right.length(); j++)
            if(!isPONumber(right.charAt(j)))
                break;

It should rather look something like:
        for (int i = left.length() - 1; i >= 0; i--) {
            if(!isPONumber(left.charAt(i))) {
                break;
            }
        }
        for (int j = 0; j < right.length(); j++) {
            if(!isPONumber(right.charAt(j))) {
                break;
            }
        }

Notes:

declare int i and int j inside the loop.
space after the keyword for.
braces even for '1-liner' conditional statements.

Double.parseDouble
Double.parseDouble() throws the unchecked exception NumberFormatException.
The exception thrown does not give great deals of information about why the number is not valid.
I always recommend wrapping Double.parseDouble (and Integer.parseInteger(), etc.) in a try-catch that reports what value was parsed, as well as the exception that was thrown. Otherwise debugging is a pain.
I often have a helper function like:
public static final double parseDouble(String value) {
    try {
        return Double.parseDouble(value);
    } catch (NumberFormatException nfe) {
        throw new IllegalArgumentException("Unable to Double.parseDouble(" + value + ")", nfe);
    }
}


Why bother renaming a to b?

This function would be more useful as a generator, because you will be interested in finding the next number in the sequence.  That is, you should yield rather than return the result.

You wrote str(b) three times.  Once would be better, but that would still be once too many, if you care about performance.  Keep in mind that stringifying a number involves allocating an object, some buffer space, some arithmetic, and translation to ASCII behind the scenes.  A function to compute the reversed integer yourself, even if it involves writing more code, should be faster.


Function to search for weekends left in month

You could use something like this :

function hasWeekendDaysLeft() {
  var today = new Date();
  var lastDayInMonth = new Date(today.getYear(), today.getMonth() + 1, 0).getDate();
  var numToday = today.getDate();

  return lastDayInMonth - numToday > 6 - today.getDay();
}


Using Euler-Maruyama method to solve Ornstein-Uhlenbeck equation (SDE)

Make constants constexpr
You can tell C++ that some of your variables are constast by marking them const. If the constants can be computed at compile time, you can even mark them constexpr. Doing this helps the compiler generated more optimal code and will result in an error if you accidentily do try to modify a constant. So:
constexpr int num_sims = 5;
constexpr double t_init = 3.0;
...

Mark variables and functions static where appropriate
If a variable or function is not used by any other source files, you should mark them static. This again might help the compiler produce more efficient code, and can prevent conflicts with other variables and functions with identical names in other source files in your project. It looks like everything except main() can be made static.
Optimize random number generation
You are using the right functions to create normal distributed random numbers, but the way you have written it, it will instantiate a new distribution, random device and generator for each call to dW(). You only need to create them once. To do this, move everything except the return statement out of the function (and make them static):
static normal_distribution<double> distribution(dt, sqrt(dt));
static random_device rd;
static default_random_engine generator(rd());

static double dW(double dt) {
    return distribution(generator);
}

Use N consistently
You created a constant for the number of datapoints you are generating. Once you have done that, use it consistently everywhere. Don't start mixing N, ts.size() and other ways to calculate the size of the array, since this might result in slight differences that will cause problems. For example, floating point values have a limited precision, and because of that the following for-loop might actually run more or less than N iterations:
for (double t = t_init; t < t_end + dt; t += dt) {

Use N consistently:
for (int i = 0; i < N; ++i) {
    ts.push_back(t_init + i * dt);
}

...

for (int h = 0; h < num_sims; ++h) {
    for (int i = 1; i < N; ++i) {
        ...

Alternatively, you could also use ts.size() everywhere, as long as you are consistent. In that case, the line to change is:
vector<double> ys(ts.size());

Note that ys doesn't need to be one larger than ts, and you don't need to initialize it with zeroes, as you will overwrite all values anyway.
Use ++ to increment counters
It's customary in C and C++ to use the ++ and -- operators to increment and decrement counters. And since it can give a slight performance benefit in some cases, prefer to use the prefix version to the postfix version if there is no difference to the result. So:
for (int i = ...; ...; ++i)

Avoid using std::endl
You should avoid using std::endl and use '\n' instead. The former is equivalent to the latter, but it will also force a flush of the output, which is often unnecessary and might slow down your application.
Do you need std::vectors at all?
You are storing the time and y-coordinates of the datapoints in the vectors ts and ys, but you never read them back. The only thing you use is the value of y of the previous timestep, but this could easily be held in a single variable:
int main() {
    for (int h = 0; h < num_sims; ++h) {
        double y = y_init;

        for (int i = 0; i < N; ++i) {
            double t = i * dt;
            y += mu(y, t) * dt + c_sigma * dW(dt);
            cout << h << '\t' << y << '\n';
        }
    }
}

Avoid unnecessary complexity

I feel like I should be using the boost packages on some level, and also maybe structures.

This problem absolutely doesn't need Boost packages nor structs. Follow the KISS principle.


Optimize Clock Update Code To Prevent Bottleneck Resulting In Time Lost

The thing to understand with setInterval() and other timer-based functions in general is that they do not guarantee precise timing.  You request an interval of 60000ms, and your mistake is assuming that what you get is in fact an interval of exactly 60000ms.

The main trick is to measure the actual amount of elapsed time between intervals, rather than assuming that each interval occurs exactly 60000ms after the previous one.  Do that and you should see better results.

Note that there may also be secondary effects caused by the execution time of your code itself.  To get around that, instead of adding deltas on each invocation you could track the initial starting timestamp at which your script starts running, and then just always compute the total amount of time that has elapsed between that starting timestamp and now, and add that amount to the starting timestamp when displaying the time.  That should give you very accurate output, and it solves the problem of the imprecise timer as well.

Here's a similar JavaScript timer that I coded awhile back that you can use as a reference.


In my opinion, the Concat part is what's throwing it off. There is a lesser utilized Select overload that provides access to the index, which could be used like so (ignoring the DataPoint part to make a minimal example):

double[] points = new double[] { 3, 5, 6, 10.5 };

points.Select ((p, i) => p - (i == 0 ? 0 : points[i - 1]));


In n circle size removing k th person every time until 1 remains

1. Review

If all the code is at the top level of the module, and reads from standard input, it is hard to test it or measure its performance. It's better to organize the code into functions so that they can be easily tested.
The values in the problem have the names \$N\$ and \$K\$ but in the code they have the names a and b. This makes it hard to check the code against the problem. It would be better to be consistent.
The code initializes the list c by repeatedly calling its append method:

c = []
for i in range(a, 0, -1):
    c.append(i)

Instead, just call list:

c = list(range(a, 0, -1))

The variable d is not used and could be omitted.
Instead of testing len(c) != 0, just test c.
The loop index i is not used; it's conventional to name an unused variable _.
Instead of:

f = c.pop()
c.insert(0, f)

you could save a line and write:

c.insert(0, c.pop())

2. Revised code

def josephus(n, k):
    """Yield the order in which people are removed from the circle in the
    Josephus problem starting with n people and removing every k'th
    person.

    """
    c = list(range(n, 0, -1))
    while c:
        for _ in range(1, k):
            c.insert(0, c.pop())
        yield c.pop()

def main():
    n, k = map(int, raw_input().split())
    print(' '.join(josephus()))

3. Performance analysis

The while c: loop executes \$N\$ times, each for loop executes \$K-1\$ times, and inserting an item at the start of a list takes time proportional to the length of the list (see the time complexity page on the Python wiki). So the overall runtime is \$Θ(N^2K)\$.

4. Performance improvement

We can avoid one of the factors of \$N\$ in the runtime by using a collections.deque instead of a list and calling the rotate method:

from collections import deque

def josephus(n, k):
    """Yield the order in which people are removed from the circle in the
    Josephus problem starting with n people and removing every k'th
    person.

    """
    c = deque(range(n, 0, -1))
    while c:
        c.rotate(k - 1)
        yield c.pop()

This brings the runtime down to \$Θ(NK)\$ which might be acceptable, but since you didn't give us the link, I can't check whether that's the case.


SQL query with dynamic unpivot+pivot for cross product

There is a more general way to do it, but it involves a dynamic query..... which is messy, and may not be better than what you have. Any time you involve a pivot, you are going in to the 'ugly' territory.

First though, some other comments:

you do not include the Rawdata CTE with your question, and it has some small issues I can see in SEDE
You select your data out as formatted strings, and you should only do the formatting as the last step, if possible.

Other than that, I found your query relatively easy to read, and since I understand the SEDE dataset quite well, I could follow the logic nicely.

Basically, your query is good, and I would 'accept it' in a review.

Ugly things of note though are:

max(Progress) is doing character-based max on a single-value set
the order by does a convert-to-float of a character value

I would like those things to be commented on, but, since the data volumes for those operations are small, I think it is OK, given the circumstances.

Out of interest, I processed your query using a more general syntax, that avoids the unpivot, and makes the pivot dynamic. As you will see, it is just as ugly, if not worse.

it does not do the order-by
it does not format the values as string at all.

See it for yourself

Note the multiple temp tables, and the variables for the pivot, and the query. Ugly, but it may give you some ideas.


It would be better to try and use built in functions for iterating over arrays. It appears that you are trying to generate and store all possible mountains. This would not be necessary. This would be my approach.

var longestMountain = function(arr) {
  //get nodes that may be the peaks of mountains
  var candidates = arr.map(function(currentValue, index) {
    if (index == 0 || index === arr.length - 1) {
      return false;
    } else {
      return arr[index - 1] < currentValue && arr[index + 1] > currentValue;
    }
  });

  //for each index, calculate the height of the slope where arr[i - 1] < arr[i]
  var increasingMountainCounts = arr.map(function(currentValue, index) {
    if (index == 0 || arr[index - 1] >= currentValue) {
      return 0;
    } else {
      return arr[index - 1] + 1;
    }
  });

  //for each index, calculate the height of the slope where arr[i - 1] > arr[i]
  var decreasingMountainCounts = arr.reverse().map(function(currentValue, index) {
    if (index == 0 || arr[index - 1] >= currentValue) {
      return 0;
    } else {
      return arr[index - 1] + 1;
    }
  });

  //for each candidate peak, get the height of the mountain with that peak
  var maxMountainHeight = 0;

  candidates.forEach(function(currentValue, index) {
    if (currentValue !== true) {} else {
      maxMountainHeight = Math.max(maxMountainHeight, increasingMountainCounts[index - 1] + decreasingMountainCounts[index + 1] + 1);
    }
  });

  return maxMountainHeight;

};

An alternative approach which uses more javascript array iterators but in my opinion makes the code a bit less readable.

var longestMountain = function(arr) {
  var candidates = arr.map(function(currentValue, index) {
    if (index == 0 || index === arr.length - 1) {
      return false;
    } else {
      return arr[index - 1] < currentValue && arr[index + 1] > currentValue;
    }
  });

  var increasingMountainCounts = arr.map(function(currentValue, index) {
    if (index == 0 || arr[index - 1] >= currentValue) {
      return 0;
    } else {
      return arr[index - 1] + 1;
    }
  });

  var decreasingMountainCounts = arr.reverse().map(function(currentValue, index) {
    if (index == 0 || arr[index - 1] >= currentValue) {
      return 0;
    } else {
      return arr[index - 1] + 1;
    }
  });

  var maxMountainHeightAccumulator = (maxMountainHeight, currentValue, index) => {
    if (currentValue !== true) {
      return maxMountainHeight;
    } else {
      return Math.max(maxMountainHeight, increasingMountainCounts[index - 1] + decreasingMountainCounts[index + 1] + 1);
    }
  };

  return candidates.reduce(maxMountainHeightAccumulator, 0);

};

In terms of improving performance, this reminds me of the problem of finding the (contigious) subsequence with the maximum sum/product. That solution would probably require completely rewriting your code.