This might be a good candidate to use SQL::Abstract in, as per DBIx::Class.

sub insert {
    # insert takes ( $table, \%fieldmap )
    my $sql = SQL::Abstract->new();
    my ( $query, @binds ) = $sql->insert( @_ );
    $dbh->prepare($query)->execute(@binds);
    return $dbh->last_insert_id(undef, undef, undef, undef);
}

This gives you a few easy features that may come in handy in the future
if you change your database, like:

easily change quoting character for tables/fields
guard against injection abuse in user-specified key names, because your code currently assumes all keys will be safe. But this will not necessarily be true, and is a vulnerability target even under taint


Am I violating any sound coding principles with this approach?

As you've discovered complex DALs are ugly to build because they are just an uninteresting hard to maintain bunch of plumbing :(

Fortunately some smart guys have built generics DALs that you can leverage to do almost all the operations like projecting and filtering you want.

When possible they will be processed on the server side which can be a huge gain in performance because you don't have to pass enormous quantity of data around, just the result you want to further process or display to the user.

Have a look at NHibernate which offers the kind of stuff you're building plus many more.

In my opinion he is the best on the market but there is some interesting challengers like Entity framework from the fourth version.

And before asking yourself if you're violating any good practices, principle or dogma, rather ask if it could cause any issue in term of code quality (readability, maintainability, robustness...).

We other geeks are too focused on what is best rather than on what should be done now, it personally took me (a lot of) years, and some experience in front office development, to realize that ... but I'm not completely cured. ;)


Simple Java ArrayList stores and shows not repeated elements entered by user

Personally, I'd refrain from putting the bulk of your logic into the main method. I'd refactor the code out into other methods and just call them from the main method.

Also, I wouldn't consider 'while(true)' to be good programming practise with some exceptions. If I were you I'd get the ArrayList size and use a loop that runs up to that. This also removes the need for that if-break statement you have at the bottom of the while loop.

I would also note that the question outlined in the comments says to use an array, not an ArrayList which may or may not be important but given the student/interview style of the question it may need to be a normal array as specified...strictly speaking an ArrayList is an object that behaves 'like' and array.

In regards to comments although they are thorough I'd advise against writing comments on the same line as statements (unless they are very short) as it is inconvenient for anyone reviewing your code to have to scroll left and right just to read the comments.

Variable names could be a touch better too but this only really applies in a professional context where other people are going to be looking at your work (same as comments I suppose). Rather that use 'number' as variable name use something a bit more descriptive like 'usersNumber' or something like that...all goes towards easier understanding and readability. I should also note that this applies to method names too (eg. gimmeValue doesn't really make much sense).

However with all that being said, keep it up! Programming is all about refinement and practise and no doubt you'll be an excellent, clean coder in no time!


I'd recommend having a look at Python's "official" Style Guide aka PEP 8, which is widely accepted in the community as a guideline on how Python code should be formatted.

But you can also learn a lot from looking at other peoples code, e.g. here on Code Review. E.g. it's very common to have imports at the top of the file, followed by constants, class and function definitions, with "script" code most often found at the very end. The script code is often surrounded by if __name__ == "__main__":, which is a way to tell the interpreter to only run this piece of code in case the file is executed as a script (and not when you try to import a function from it).

Directly applying this to your code might leave you with an awkward feeling, because some global variables are used inside the functions before they are "physically" defined in the script. You've probably heard this from other people already: try to avoid global variables whenever possible. This is one of the reasons. In general, global variables make it harder so see what goes into a function and how the function affects the "state"/variables of your program without looking at the source code. If all inputs are passed as parameters and the new/altered values are actually returned from the function, you don't need to know what exactly happens inside to understand what's going on.

You work around this be passing all the necessary variables as parameters when calling a function.

If that brings up another strange feeling, like say, a function accepts parameters that seem to have nothing to do with what it name would let one expect, then you have identified another common error: violations of the single responsibility principle. A few ideas how that might look like in your script

Have a main() function where all the script code lives. This function calls other functions as necessary and provides input to them via parameters.
Have randomize_picture accept all the necessary inputs as parameter and return which image was selected, raise an appropriate exception whenever this is not possible instead of printing to console.
Pass the source image and all the other relevant information to post_image(...).
Alternatively, assemble the target filename also in main so you'll just have to pass two parameters to post_image(...).

import os
from os import listdir, rename
from random import choice
from datetime import datetime

def post_picture(original_picture, pictures_posted_dir, kind, post_time):
    """Here I move the picture to the 'posted' folder"""
    rename(original_picture, pictures_posted_dir + kind + post_time + ".png")

def randomize_picture(pictures_to_post, pictures_dir):
    """Here a random picture is selected(if there are any)"""
    if not pictures_to_post:
        raise ValueError('No Pictures Left')

    random_kind = choice(pictures_to_post)
    random_kind_dir = pictures_dir + random_kind + "/"
    random_picture = choice(listdir(random_kind_dir))
    random_picture_dir = random_kind_dir + random_picture

    return random_picture_dir, random_kind

def main():
    # The main directory in which I'll store the pictures
    pictures_dir = "C:/Users/firmi/Desktop/Pictures/"

    # The directory in which posted pictures go to
    pictures_posted_dir = os.path.join(pictures_dir, "Posted/")

    # The folders inside the main directory
    picture_folders = listdir(pictures_dir)

    # List of folders with pictures that have not been posted
    pictures_to_post = [kind for kind in picture_folders if not kind.startswith('Posted') and len(listdir(pictures_dir + kind)) > 0]

    # Current date of the post
    post_time = datetime.now().strftime("_(%d-%m-%Y)")

    random_picture_dir, random_kind = randomize_picture(pictures_to_post, pictures_dir)

    post_picture(random_picture_dir, pictures_posted_dir, random_kind, post_time)

A few notes on what else has changed:

import _datetime --> impor datetime. Variables, functions and modules starting with a leading _ are not supposed to be used in code outside of that file or module. It's a Python convention to tell others, that you consider it an implementation detail which is subject to change. So don't use it.
the function documentation was changed from # comments to proper docstrings. docstrings are found by Python's built-in help(...) function as well as by most IDEs and are THE way to go for function, class, and module documentation.
whenever working with paths it's best to use either os.path.join (Python 2/3) or the pathlib module. Both of them make working with paths much more convenient, e.g. because they know which separator to use for which platform (Linux: /, Windows: \).
Look Ma! No global variables ;-)


I see a couple of ways to speed this up.

Observe that at least one factor is even, and exactly one factor is a multiple of 3, so these numbers are all divisible by 6. Assuming random input, testing for that at the beginning will find the answer in one inexpensive operation in 5 out of 6 cases:

if (userInput % 6) {
    printf("User input is not a triangular number\n");
    return 0;
}

As for the rest of it, if we set n = x + 1, we get

$$T(n-1)=(n-1)(n)(n+1)=n^3-n$$

Thus, we can solve in O(1) time, though the cube root is a somewhat expensive operation:

#include <math.h>    /* Link with -lm in gcc */

int n;

n = (int) (ceil(cbrt(userInput)) + 0.1);
if (n * (n-1) * (n+1) == userInput)
    printf("User input is a triangular number\n");
else
    printf("User input is not a triangular number\n");

We add 0.1 after the ceil because the double value might be something like 6.9999999999759, which would round to the wrong number when converted to int. The (int) cast suppresses a compiler warning about conversion from double to int.


Improving GUI update call from a worker thread in winforms

You could create a helper method like the following:

void ChangeUI(Action action)
{
  if (InvokeRequired)
  {
     Invoke(action);
  }
  else
  {
     action();
  }
}

Now you can use it from any place where you need to modify the UI of that form and let the method check if it actually needs to call Invoke or simply execute the delegate.

ChangeUI(() => gamepadStatusLabel.Text = "Connected");


Cleaning and extracting meaningful text from tweets

Copying my answer from SO:

You can use pandas vectorized string methods to do your processing and it also removes the for loop for more efficient pandas operations, this should give you some speed.

# column you are working on
df_ = tweets_df[1]

stopword_set = set(stopwords.words("english"))

# convert to lower case and split
df_ = df_.str.lower().split()

# remove stopwords
df_ = df_.apply(lambda x: [item for item in x if item not in stopword_set])

# keep only words
regex_pat = re.compile(r'[^a-zA-Z\s]', flags=re.IGNORECASE)
df_ = df_.str.replace(regex_pat, '')

# join the cleaned words in a list
df_.str.join("")

Also I've changed your regex to [^a-zA-Z\s] so that it does not match the space character.


It might be better to render the control as an unordered list.  This is more semantically correct and normal practice for menu-type controls (which tabs are, if you think about it).


Euler Problem 7 (finding the 10001st prime) in Powershell

I'd start with

removing redundancy
measuring the time automatically
output to screen slows down, comment it out

depending on the speed of the computer used I get results of ~74..120 seconds.
Compared with 0.450 secs here with matlalb there IS potential to get better ;-)

## Q:\Test\2018\11\08\CR_207250.ps1

$StartTime = get-date
$PrimeNo = 10001

$incNum1 = 0
$highestNum = 0
$k = 1

while($k -lt $PrimeNo){
    $incNum2 = 2
    $divisNum = 2 * $incNum2 - 1
    $incNum1++
    $nextNum = 2 * $incNum1 + 1

    $upTo = [Math]::Ceiling(($nextNum / 2))
    $break = $false
    while($divisNum -lt $upTo){
        $modRes = $nextNum % $divisNum

        if($modRes -eq 0){
            $break = $true
            break
        }
        $incNum2++
        $divisNum = 2 * $incNum2 - 1
    }
    if(!$break){
        $highestNum = $nextNum
#        "{0}:{1}" -f $k,$nextNum
        $k++
    }
}

"## PrimeNo: {0} is {1} calculated in {2} seconds" -f $PrimeNo,$highestNum,
    ((Get-Date)-$StartTime).TotalSeconds

## PrimeNo: 10001 is 104743 calculated in 73,6911884 seconds
## PrimeNo: 10001 is 104743 calculated in 118,3481173 seconds


You create the SqlConnection only once, in the type constructor of ConnectionStringManager. Then you wrap its usage in a using block which is good practice but will dispose the object when it leaves the scope, so any subsequent usage will result in an ObjectDisposedException.

Instead, create a new connection in the GetOpenConnection method (maybe rename it to CreateConnection or similar in order to reflect the fact that there's work being done).


Bitcoin wallet address and private key generator

IMPORTANT!!!
Not a Python tip, but rather a MUST when it comes to sensitive information (quote from @nzall's comment):

Those private keys should NEVER, EVER be posted in a location even
as remotely public as a code review site. More, replacing them
is not enough. For all purposes, you should now view the original keys as compromised and must NEVER EVER EVER use them again for
bitcoin storage. Doing so runs high risk of losing the bitcoins stored
in them

I just made this tip a bit more seeable for everybody.

Another three small observations, in addition to what @Graipher said.
In Python you can "chain" comparison operations which just means they are "and"ed together.
if random_int >= 1 and random_int < curve_order:
    return random_int

In your case, it'd be like this:
if 1 <= random_int < curve_order:
    return random_int

Read more about it here

More, I'd recommend you use .format() when it comes to printing:
print("Private Key: " + private_key_hex)
print("Public Key: " + public_key_hex)
print("Private Key (WIF Format): " + private_key_wif_hex)

Could be:
print("Private Key: {}".format(private_key_hex))
print("Public Key: {}".format(public_key_hex))
print("Private Key (WIF Format): {}".format(private_key_wif_hex))

You should also have two blank lines between your functions (instead of a single one)
This:
# ...
from binascii import hexlify, unhexlify

def random_secret_exponent(curve_order):
    while True:
        random_hex = hexlify(dev_random_entropy(32))
        random_int = int(random_hex, 16)
        if random_int >= 1 and random_int < curve_order:
            return random_int

def generate_private_key():
    curve = ecdsa.curves.SECP256k1
    se = random_secret_exponent(curve.order)
    from_secret_exponent = ecdsa.keys.SigningKey.from_secret_exponent
    return hexlify(from_secret_exponent(se, curve, hashlib.sha256).to_string())

# ...

Should be:
# ...
from binascii import hexlify, unhexlify

def random_secret_exponent(curve_order):
    while True:
        random_hex = hexlify(dev_random_entropy(32))
        random_int = int(random_hex, 16)
        if random_int >= 1 and random_int < curve_order:
            return random_int

def generate_private_key():
    curve = ecdsa.curves.SECP256k1
    se = random_secret_exponent(curve.order)
    from_secret_exponent = ecdsa.keys.SigningKey.from_secret_exponent
    return hexlify(from_secret_exponent(se, curve, hashlib.sha256).to_string())

# ...

For more details / suggestions / improvements regarding your code layout, you could take a look at PEP8, Python's official style guide.


SQL Server 2012: How do I eliminate multiple statements in this code to a more efficient, single statement?

This could be simplified. You don't have to create a temporary table to get your unique day count. You can use the COUNT function on the StartDate column directly.

Try this:

SELECT
    TotalLoadCount / NULLIF(TotalDayCount, 0) AvgLoadCountByDay
FROM
(
SELECT
    COUNT(DISTINCT  CAST(StartDate as date)) TotalDayCount
    ,SUM(LoadCount) TotalLoadCount
FROM
    dbo.Tracker
) x

Obviously, you can write it directly like this as well:

SELECT
    SUM(LoadCount) / NULLIF(COUNT(DISTINCT  CAST(StartDate AS date)), 0) AvgLoadCountByDay
FROM
    dbo.Tracker

If my understanding of your problem is correct, this query should give you the same result. Let me know if it doesn't.

I personally prefer the first version with derived table as it helps with the readability of the query. You are not paying any additional cost because SQL Server will generate the same execution plan for both the queries.


Sphere Online Judge, Problem 2: Prime Number Generator

I'll make general statements not addressing (or not limited to) performance.

Your overall design is not very Object-Oriented. Usage of static/global variables is discouraged for a reason, it is very hard to follow the flow the program. Consider rewriting it with proper classes/encapsulation.

You could extract reading into one function, which then returns the list of pairs which another function can work on. Some pseudo code:

main()
    List pairs
    if args provided
        pairs = pairsFromFile(args[0])
    else
        pairs = pairsFromStdIn()

    foreach pair in pairs
        processpair(pair)

Your usage of one-line ifs is partly confusing, consider to expand those to at least two lines for readability:

if(test)
    return true;

You're declaring and actively throwing exceptions which never get caught, that means that your application will exit with a thrown exception, that's a bad thing. Applications should handle exceptions at least in the main loop and exit gracefully.

Consider writing directly to the output-stream instead of buffering everything in a StringBuilder. While it might hurt performance if you're doing a lot of writing, it will remove some of the complexity.

System.out.println("IOException encounterd!");

Exceptions and errors should traditionally go to System.err.

You're using System.exit() at some places, it might be more desirable to let the main loop handle the application flow instead of "exiting" from any or some functions. I also now realize that you're using some sort of template to handle exceptions (write to out, print stacktrace, exit(-1)), please don't just slap an "error-handling-template" on it and be done with it. Handle exceptions in a context-sensitive way.

isPrime() does use a temporary variable isPrime when returning at the appropriate places would be more then enough.

private static boolean isPrime(int num) {
  if (num < 2)
    return false;
  else if (num > 3) {
    // Loop here
        if (num % (6 * factorNdx + 1) == 0 || num % (6 * factorNdx - 1) == 0) {
          return false;
        }
  }

  if (isPrime) primes.add(num);
  return true;
}


One observation is that you are converting the splitted[1] to float inside the inner loop - redoing the same exact thing multiple times - do it once before the loop:

splitted = float(read.split(" ", 1)[1])  # convert to float here
for k in range(i + 1, num_lines + 1):
    read1 = linecache.getline('just_nodes.txt', k).rstrip('\n')
    splitted1 = float(read1.split(" ", 1)[1])

    alpha_temp = abs(splitted - splitted1)

Note the other thing I've done - splitting by an explicit space and doing it strictly once - please check if it actually has a positive impact on performance.

You may also not strip the newlines from the end of the lines, float() can handle it:

In [1]: float("1.00\n")
Out[1]: 1.0


Python program that takes input and runs queries on a mySQL database on it

A comment on this bit:

customerNumbers = '('
for prime in primeCustomers:
    customerNumbers += str(prime.id)
    customerNumbers += ', '

# Remove the trailing comma and space and add ending parenthesis
customerNumbers = customerNumbers[:-2]
customerNumbers += ')'

can be written as:

customerNumbers = '(' + ', '.join(str(x) for x in primeCustomers.id) + ')'

My final comment has to do with the use of fetchone() instead of fetchall(). Is there a reason you do it like that? Instead of having the while statements which you have to evaluate in every loop you can just fetch all results and process them in a less "expensive" for loop like that:

rows = cur.fetchall()
for row in rows:
    #do stuff with the results of every row.


Notes:

Before refactoring, let's identify what makes this code feel "messy". IMO there are two problems: the in-place method << and the inline statement unless. As usual, I'll try to make the case for functional programming (as opposed to imperative programming, not opposed to OOP). I guess you are not familiar with FP in Ruby but somehow you felt something was wrong. A quick intro: when you update variables in-place, the = symbol loses a lot of its glamour :-) In maths x = "hello" means that, in this scope, x is always equal to 'hello'. Period. In imperative programming it means "for now x is equal to 'hello', but I reserve the right to change it whenever I feel like it, in this scope or any other. Good luck debugging!". I don't know about you, but I prefer = to mean the first one :-) Yes, even for a such simple and short code.
I don't understand: m.format, where is m? is it mny?
ebeach?. What is ebeach??
m.format[-3, 3]. Do you want the last 3 chars of a string? In Rails: m.last(3).
@visitor: Using an instance variable in a helper is a no-no. Pass it as an argument.

So let's rewrite the snippet in functional style. There are at least two ways, 1) use different variable names for the different values and concat the strings, or 2) use an array+compact+join. The first:

def format_price(money_value, visitor)
  money = get_price_string(money_value).to_money
  symbol = content_tag(:span, visitor.currency.symbol.html_safe, class: 'pounds')
  value = money.format(no_cents: true, symbol: '')
  currency = ebeach? ? "" : content_tag(:span, money.format.last(3), class: 'pence')
  symbol + value + currency
end

Note how pure functions in FP follow a simple pattern: create intermediate variables (if needed, to make the method more readable and declarative) and use them in the last expression of the method. Don't "do things", declare "what things are".

Second approach:

def format_price(money_value, visitor)
  money = get_price_string(money_value).to_money
  [
    content_tag(:span, visitor.currency.symbol.html_safe, class: 'pounds'),
    money.format(no_cents: true, symbol: ''),
    *(content_tag(:span, money.format.last(3), class: 'pence') if condition?),
  ].join
end

Of course an alternative approach would have been to create a partial view instead of rendering from a helper.


Sorting a list and another list inside each item

There are others concerns with your code, without going into the sort:

Getter returning mutable data

getCompetitors() returns directly the internal list stored by your factory object. This is generally not a good idea: it means a client of Factory can modify its internal structure, which defeats the OOP principle. It would be preferable instead to have a method sortCompetitors(), that would sort the list, without leaking it:

private List<Competitor> competitors;

public void sortCompetitors() {
    Collections.sort(competitors);
}

and remove completely the method getCompetitors().

Comparator, Comparable

class Factory implements Comparator<Factory>

will be problematic in the future. It seems what you want would be to use Comparable instead, but even this isn't a good idea in this case. There is a difference between the two: a class is Comparable when it can compare itself to another class of the same type, which is what you are doing here: one Factory is comparing itself to another object. On the other hand, a Comparator is a class that is comparing 2 objects of the same type (it does not compare this with another object).

Therefore:

It is wrong to have your class implement Comparator: it means the class is doing too much: it knows itself and it is also responsible for comparing any 2 factories (See also on Stack Overflow). More often than not, there are several ways to compare 2 objects given a context: sort by name or sort by price...
It is also probably wrong to have your class implements Comparable, but for a different reason. As said before, Comparable is used to compare this with another object of the same type. But this interface is closely related to equals and hashCode: any class that is Comparable should provide a consistent equals method (It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))). In your case, it would imply that two factories are equal when their price is equal, which is probably not what you want.

The solution here is not to make your class implements Comparator and define a custom comparator class, like

class FactoryPriceComparator implements Comparator<Factory>

Using built-in methods

Your compare methods are currently doing:

@Override
public int compare(Factory o1, Factory o2) {
    if (o1.getPrice() < o2.getPrice())
        return -1;
    if (o1.getPrice() > o2.getPrice())
        return 1;
    return 0;
}

This can be written more concisely with the built-in Double.compare (since Java 7), which also properly handles NaN, -0.0 and 0.0, contrary to your current code:

public int compare(Factory o1, Factory o2) {
    return Double.compare(o1.getPrice(), o2.getPrice());
}

Your whole comparator would then become:

public class FactoryPriceComparator implements Comparator<Factory> {
    @Override
    public int compare(Factory o1, Factory o2) {
        return Double.compare(o1.getPrice(), o2.getPrice());
    }
}

Note that you would have the same implementation for the Comparator<Competitor>.

Java 8 API

If you're using Java 8, you can even get rid of the above FactoryPriceComparator and use the built-in Comparator.comparingDouble(keyExtractor), which creates a comparator comparing the double values returned by the key extractor. In this case, the key extractor could be the method reference Factory::getPrice (resp. Competitor::getPrice). So you could simply have:

Collections.sort(factoriesList, Comparator.comparingDouble(Factory::getPrice));

or even

factoriesList.sort(Comparator.comparingDouble(Factory::getPrice));

Finally:

  What I am doing require to sort collection of factories and loop through all factories and sort collection of their competitors

This is actually the proper way of doing it: when you sort a Factory, you cannot sort the inner competitors at the same time, because different objects are being compared.


Finding similar items in two arrays with multithreading in C++

The cost of starting up a thread is generally considered expensive. For your example of only 10 items, you won't ever see it because the application quits before you notice it started. Generally for something like this, you'd want to start up a thread to process some large portion of the array rather than one thread per element of the array. At 10 elements, it's no big deal. But once you have thousands of elements, you don't want thousands of threads running. In fact, many operating systems will limit the number of threads you can start. According to @user673679, you can get the number of concurrent threads by calling std::thread::hardware_concurrency.

I recommend limiting the number of threads to something like the number of available CPU cores on the machine. Then split the input arrays into that many parts and have each thread work on one part of the array. So if you have 8 cores, split the work into 8 parts and have each thread work on 1/8th of the array.

I ran your code with Thread Sanitizer and it's telling me you have a data race. Here's what it says:

WARNING: ThreadSanitizer: data race (pid=7975)
  Read of size 8 at 0x7ffeefbff2f0 by thread T4:
    #0 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0::operator()() const main.cpp:34 (CPlusPlusTester:x86_64+0x100006b4a)
    #1 decltype(std::__1::forward<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(fp)()) std::__1::__invoke<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) type_traits:4339 (CPlusPlusTester:x86_64+0x100006a00)
    #2 void std::__1::__thread_execute<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>&, std::__1::__tuple_indices<>) thread:342 (CPlusPlusTester:x86_64+0x100006868)
    #3 void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0> >(void*) thread:352 (CPlusPlusTester:x86_64+0x1000059f9)

  Previous write of size 8 at 0x7ffeefbff2f0 by main thread:
    #0 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char) main.cpp:32 (CPlusPlusTester:x86_64+0x1000018e2)
    #1 main main.cpp:47 (CPlusPlusTester:x86_64+0x100001fa1)

  Location is stack of main thread.

  Thread T4 (tid=669186, running) created by main thread at:
    #0 pthread_create <null>:2673600 (libclang_rt.tsan_osx_dynamic.dylib:x86_64h+0x2a17d)
    #1 std::__1::__libcpp_thread_create(_opaque_pthread_t**, void* (*)(void*), void*) __threading_support:328 (CPlusPlusTester:x86_64+0x10000593e)
    #2 std::__1::thread::thread<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0, void>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) thread:368 (CPlusPlusTester:x86_64+0x1000055e7)
    #3 std::__1::thread::thread<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0, void>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) thread:360 (CPlusPlusTester:x86_64+0x100001ad8)
    #4 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char) main.cpp:33 (CPlusPlusTester:x86_64+0x10000189f)
    #5 main main.cpp:47 (CPlusPlusTester:x86_64+0x100001fa1)

SUMMARY: ThreadSanitizer: data race main.cpp:34 in process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0::operator()() const

Line 34 is the call to process_element(). @pschill pointed out:

  The lambda captures all variables by reference, including i. So if the thread starts a little bit too late, the for loop already incremented i and the call to process_element recieves the wrong value. A solution would be changing the lambda capture from [&] to [&, i], so that i is captured by value.

You ask:

  Is this just an artifact of the fact that process_element is very simple and takes almost no time at all, or will the output in general be ordered according to the order in which I run the threads?

I think it's just because there's so little work being done that the threads end up executing in order. One is probably done before the next is even started.


Creating simulated items sold at a store into a hash

The SimStore class doesn't seem to do much except create a hash and create an item. These seem like separate concerns

You really could use an Item class with a static method for stubbing out an Item.

First, let's start with an "Item" class:

class Item
  attr_accessor :price, :name, :sku, :quantity

  def initialize(name, sku, price, quantity)
    self.name = name
    self.sku = sku
    self.price = price
    self.quantity = quantity
  end

  def self.stub
    price = Random.new.rand(1.00 ... 75.00).round(2)
    name = 1.times.map { RandomWord.nouns.next }
    sku = Random.new.rand(1000 ... 1000000)
    quantity = Random.new.rand(10 ... 100)

    self.new name, sku, price, quantity
  end

  def to_h
    { name: name, price: price, sku: sku, quantity: quantity }
  end
end

It has a price, name and sku that is a getter and setter. A static, or class level method called Item.stub generates a fake item based on the code you are using. Lastly, it has a to_hash method for converting the Item into a Hash.

Now we can take one step back and think about your SimStore, which at this point doesn't simulate anything so we can rename it to Store:

class Store
  def items
    @items ||= []
  end

  def self.stub(number_of_items)
    store = self.new

    number_of_items.times do |i|
      store.items << Item.stub
    end

    store
  end

  def to_h
    items.map { |item| item.to_hash }
  end

  def sku_hash
    # For Ruby < 2.1
    array = items.map { |item| [item.sku, item.quantity] }
    Hash[array]

    # For Ruby >= 2.1
    items.map { |item| [item.sku, item.quantity] }.to_h
  end
end

It has an array of Items and a to_hash method that converts the entire store into a Hash. Additionally, it also has a class method called stub, which accepts the number of items that should be stubbed out.

You wanted to convert the items into a Hash of SKUs for the keys, and quantities for the values, so explicitly creating a sku_hash method seems to be more appropriate.

And to use it:

store = Store.stub 15
store_hash = store.to_hash # => [{name: '...', sku: 123, price: 23.99}, ...]
sku_hash = stsore.sku_hash # => { 'sku1' => 2, 'sku2' => 55 }

By separating the Item from the Store and adding class methods to stub items and entire stores, you get two classes that can actually be used in a real context, but also can be used just for playing around.


This is what I've come up with, which is nicer than the if/else if statement I was originally using.

$("#show").on("click", function() {
  renewElement($(".animated"));
  var $animated = $(".animated");
  var shown = $animated.hasClass('on');
  $animated.toggleClass('on', !shown).toggleClass('off', shown);
});

function renewElement(e) {
  var newElement = e.clone(true);
  e.remove();
  $(".container").append(newElement);
}
.controls {
  text-align: center;
}

button {
  display: inline-block;
}

.textbox {
  width: 280px;
  margin: 0 auto;
  background: tomato;
  padding: 10px;
}

.animated {
  max-height: 0;
  overflow: hidden;
  animation-name: none;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}
.triangle {
  content: " ";
  width: 0;
  height: 0;
  border: 10px solid;
  border-color: transparent transparent tomato transparent;
  position: relative;
  left: 50%;
  top: -9px;
  margin-left: -7px;
}

.on {
  animation-name: slideOpen;
  animation-direction: normal;
}

.off {
  animation-name: slideOpen;
  animation-direction: reverse;
}

@keyframes slideOpen {
  0% {
    max-height: 0px;
    padding: 0px;
  }
  100% {
    max-height: 150px;
  }
}

  <button id="show">Show div</button>

text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text

As you can see, I've kept the renewElement() function. After reading this article it seems that there isn't much you can do.


Deserialize an email header into key-value pairs

There are a couple of things that I find odd about this code. This is the first thing that jumps out at me.

Dim startIndex As Integer = Nothing
Dim item As Match = Nothing
Dim key As String = Nothing

I see no purpose in initializing variable to Nothing. Simply declaring them would be cleaner in my opinion.

Dim startIndex As Integer
Dim item as Match
Dim key As String

I also find your For loop a bit strange. Is there a reason you're stepping backwards? If there is, I don't see it and you should comment on why in the code.

For index As Integer = (matches.Count - 1) To 0 Step -1

Personally, I would rewrite this to loop forward like this.

For index As Integer = 0 To matches.Count - 1
    '...
Next index

You could also use a comment here.

Const pattern As String = "(\n|^)[a-z|A-Z|-]*:\s"

Regular Expression patterns are rarely obvious. Tell Mr. Maintainer in English what you're matching on.


Between dates : from highest -> current -> lowest

There's not really much to review here since it's such a short snippet, but a few things:

I tend to avoid manipulating dates as strings.  With just a year-month format it's actually fine since there's no odd rules. It's generally a lot safer to use DateTime though (or even strtotime/date). The problem with dates and times are that they are not simple units. There are complex, ever-changing 'business rules' (of sorts) that surround dates and times and cause huge headaches.

As said though, you're fine with year-date format since there's no gotcha's.

Just for consistency sake though, I would work with a standardized date format and use a date-time specific API.

For example:

$start = new DateTime(date('Y-m')); //First of this month
$end = new DateTime('2013-03'); //March 1st
$oneDay = new DateInterval('P1D');
$dates = array();
for (; $end >= $start; $end->sub($oneDay)) {
    $dates[] = $end->format('Y-m');
}

$dates is then an array in the format you want.  This code is quite ugly, but unfortunately I've never been able to figure out a way to manipulate dates in PHP that isn't ugly.

Here's a strtotime/date based version:

$start = strtotime(date('Y-m'));
$end = strtotime('2013-03');
$dates = array();
while ($end >= $start) {
    $dates[] = date('Y-m', $end);
    $end = strtotime(date('Y-m-d', $end) . ' +1 day');
}

Rather than the strtotime call, you could just use 864000 seconds. I'd have to think for a few minutes to make sure that won't have any DST mistakes though. Once again, a situation where I like to keep date operations as abstracted away as possible. 864000 is a lie since not all days have 24 hours (at least not in places that observe DST).

If I were to go with a string approach, your do_lower function is basically what I'd use.  It's named rather poorly though since it has no mention of what it's 'lowering' or what 'lowering' even means. Also, I would probably use a strict comparison against 01.

The problem with a purely string based approach is that it's not very reusable. Your function has a very specific input format and a very specific output format. Anything else and it breaks.

If you pass around DateTime's instead, dates are no longer represented as a string. They're represented as a type that is much more appropriate for such a complicated system. They're represented as a type that is aware that they are a date.


You don't have to inject express into each modules.

requiring express in each file will return the same instance. http://nodejs.org/docs/latest/api/modules.html#modules_caching

Also, ask yourself who should be the one registering the router into the app. The app it self or the router ? For code reuse and clean separation you should let the app handle it. Let's say you have an authentication router used with the path '/auth'. You may want to reuse it in another app with a path like '/authentication'

Here's how I would do it.

server.js

//================== ROUTES ======================================
...

var api = require('./routes/api');
var router = require('./routes/web');

app.use('/api', api);
app.use('/', router);

...

apiroutes:

//================================== routes for API ====================================

var express = require('express');

module.exports = (function() {
    'use strict';
    var api = express.Router();

    api.get('/somget', function(req, res) {
        res.send('some json');
    });

    return api;
})();

pages routes (both main template and partials):

//================================== routes for index and partials================================

var express = require('express');

module.exports = (function() {
    'use strict';
    var router = express.Router();

    router.get('/', function(req, res) {
        res.render('index');
    });

    router.get('/partials/:name', function (req, res) {
        var name = req.params.name;
        res.render('partials/' + name);
    });

    return router;
})();


Get all combination of a nested object with arbitrary levels

Your code is clean and works fine.
The only little point I've noticed is that you didn't follow this rule:

instead of (for instance) for (var i = 0; i <obj.length; i++)
you should write for (var i = 0, n = obj.length; i < n; i++), so the obj.length is evaluated only once rather than for each iteration

That's said, it may be possible that it doesn't matter any longer in modern browsers, due to optimizers.

Beyond that, I was interested by your challenge to find "a better/more elegant solution".

Then I found one that uses reduced code, and probably works faster:

var data = {
  "title": {
     "original": "Hitchhiker",
     "more": ["HGTTG"],
     "link": null
  },
  "date": ["20150101", "20160101"]
}

function nestedObjectToArray(obj, prefix) {
  prefix = prefix ? prefix : '';
  var result = [], isArray = Array.isArray(obj), value, nextPrefix;
  obj = typeof obj == 'object' ? obj : JSON.parse('{"' + obj + '": null}');
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      value = obj[key];
      nextPrefix = prefix + (isArray ? '' : (key + '-'));
      result = result.concat(
        value === null ? (prefix + key) : nestedObjectToArray(value, nextPrefix)
      );
    }
  }
  return result;
}

console.log(nestedObjectToArray(data));

The main points of interest are:

The function gets a second argument prefix which is recursively transmitted, growing as depth increases: this allows to always add the complete prefix at each level, instead of having to re-process the complete result returned to prepend each item with the key of the ancestor level.
There is a unique loop to process arrays and objects: since the only difference is the absence/presence of a key, the test (is array ?) is made at this precise point, inside the generation for the current item:
nextPrefix = prefix + (isArray ? '' : (key + '-'));.
More over, also a final "leaf" is not processed separately, like:
if (typeof(obj) != "object") {return [obj];} in your version;
instead, the leaf is transformed into an object:
obj = typeof obj == 'object' ? obj : JSON.parse('{"' + obj + '": null}');
so it can be processed in the loop, where it falls into the (already planned by design, following your initial needs) case of null value: the trick is that the value became a key.


Node.js package that retrieves data from an API, formats it and sends it out via email to a distribution list

When you have a lot of asynchronous requests to make, and you want to wait for all to finish, the proper method to use is to first promisify the requests (if they don't return a Promise already), and then to use Promise.all, which returns a Promise which resolves once all promises in the passed array have resolved.
Unfortunately, icingaServer looks to be callback-based, and you have to multiple methods from it. Luckily, there's a package called promisify that makes turning these callback APIs into Promises much easier.
You can reduce the nesting level by one by changing
clients.forEach((clientMap) => {
    Object.entries(clientMap).forEach(([client, hostnameWildcard]) => {

into a use of flatMap instead: clients.flatMap(Object.entries)
DRY You have two very similar callbacks in getServiceFiltered and getHostFiltered. All that differs is the function invoked and the parameter passed, so it'd be better to make another function to which you can pass the parts that change.
Parallel processing Rather than two calls which are made in serial, consider making them both at once, in parallel, if the API supports it - this'll let your script finish quicker.
Filtered array length While you can do arr.filter(callback).length, you might consider using reduce instead, since you don't care about the resulting array, you just care about the number of matching elements.
Unquoted keys In JS, there's no need to quote object keys unless the keys contain characters that are invalid for idenfifiers. Most prefer not to use quotes so as to keep the code free of unnecessary noise.
Refactored:
const { promisify } = require('util');
const icingaServer = new icingaApi(icingaConfig.url, icingaConfig.port, icingaConfig.username, icingaConfig.password);
const getServiceFiltered = promisify(icingaServer.getServiceFiltered).bind(icingaServer);
const getHostFiltered = promisify(icingaServer.getHostFiltered).bind(icingaServer);

const processClient = async ([client, hostnameWildcard]) => {
    const getClientData = async (method, filterKey) => {
        const result = await method({
            filter: 'match(host_name, host.name)',
            filter_vars: {
                [filterKey]: hostnameWildcard
            }
        });
        return {
            warnings: result.reduce((count, o) => count + (o.attrs.state === warning), 0),
            errors: result.reduce((count, o) => count + (o.attrs.state === warning), 0),
            totalCount: result.length,
        };
    };
    const [serviceData, hostData] = await Promise.all([
        getClientData(getServiceFiltered, 'service_name'),
        getClientData(getHostFiltered, 'host_name'),
    ]);
    return {
        name: `${client} (${hostData.totalCount}/${serviceData.totalCount})`,
        errors: serviceData.errors + hostData.errors,
        warnings: serviceData.warnings + hostData.warnings,
    };
};

Promise.all(
    clients.flatMap(Object.entries).map(processClient)
)
    .then(sendEmail)
    .catch((error) => {
        // handle errors
    });

where sendEmail now takes a parameter of the data to send.
Also note that // handle errors shouldn't just log an error if it occurs - ideally, you'd have a system in which such an error results in a developer being able to look at a dashboard or something to see at a glance what's failed recently, to see when an issue arises that needs looking into (for example, if the API changes and all requests start failing).


String length calculation implementation in Assembly (NASM)

I have a number of comments that I hope you find helpful.

Code comments

First, your code is generally well commented and I had little difficulty in understanding what the code was doing or why.  That's a good thing.  A few minor points, though.  First, your comment for the overall function says

; input register: EAX - the string

however, it's probably useful to point out that EAX is actually a pointer to the string and isn't intended to contain a whole string.

Also, comments should tell something not obvious about the code.  So this:

        jmp     _NextBlock; repeat loop

is arguably OK, but this:

        inc eax ;increment EAX

is not really helpful.  Instead you should say why the code is incrementing EAX rather than simply repeating what the instruction does.

Structure

Overall, the structure was OK, but the line

        jmp _NextBlock ; go to _NextChar

near the top of the function is not needed, since _NextBlock is the next instruction anyway.  The same is true of the jmp just before _FinalizeFinalBlock.  Generally speaking, you should strive to eliminate unconditional jumps.  So for example, your code includes this:

    _FinalizeFinalBlock:
        cmp     byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.
        jz      _Exit ;if this byte is null, proceed to _Exit
        ; if not...
        inc eax ;increment EAX
        jmp     _FinalizeFinalBlock ;repeat loop

    _Exit:

But you could easily restructure that to eliminate the unconditional jmp like this:

        dec eax ;
    _FinalizeFinalBlock:
        inc eax ;increment EAX
        cmp     byte[eax], NULL_TERMINATOR ;Compare the characters of the final block to the null byte.
        jnz     _FinalizeFinalBlock ; keep going until final block is NULL

    _Exit:

Algorithm

The most significant problem I see with the code is the algorithm that relies on strings having multiple trailing NUL bytes.  This may be true for code that calls this function, but it's not generally true of C strings which typically end with only a single NUL character.

Instruction set use

The repnz scasb instruction is probably going to be a lot more efficient that the loop you've constructed.  I'd recommend reading about it and then incorporating that into your code.

Register use

The ebx register is destroyed and not saved by the function.  This may be fine for your purposes, but it should be documented in comments at the top of the function.

Also, the code doesn't actually alter ebp so there isn't any point to pushing it onto the stack and popping it off at the end of the routine. (Maybe you meant ebx?)

Update:

On my machine (quad core running 3.2GHz under 64-bit Linux) I found this version to be slightly (15%) faster than the corresponding repnz scasb version:

strlen2:
    mov edx, [esp + 4]
    xor eax,eax ; count = 0
    jmp overit
looptop:
    inc edx
    inc eax
overit:
    cmp byte[edx],0
    jnz looptop
    ret


Simple proof-of-work (based on HashCash)

public HashCash() throws NoSuchAlgorithmException {

SHA-256 is a requirement for any Java SE environment. Instead of throwing you should be catching and converting to a RuntimeException (or IllegalStateException) with this particular exception as cause.
public long generateHashCash(final String seed, final int targetLevel) {
...
private final int getSecurityLevel(final String value) {

If you're going to design for performance you should not be using String types. The seed should be a byte array from the start. And you could use e.g. ByteBuffer to write an integer to an existing array that already starts with the seed.
Note that SHA-256 is a Merkle-Damgard hash function that handles input block-by-block. That means that if you start off with a large enough seed (512 bits or larger) you might as well pre-hash it. Of course this means mucking about within the hash implementation.
if(b != 0)
    break;
level++;

Generally the level calculation is performed on bits or even values (where the hash value, when seen as a unsigned number, is below a certain value).
As for performance: you can stop comparing whenever you encounter a number that doesn't have the right level. It won't matter much when compared the time required to perform SHA-256 in all probability, but it is still wasteful.
I don't expect getSecurityLevel to perform the actual hash calculation. A getter is generally not expected to perform any work at all.
The PHP code doesn't seem to reflect the structure of the Java application. If you have one getSecurityLevel method I would expect the same in the verification application, whichever language is used.

Otherwise, yes, it is a very simple proof of work. I'd rather require a few hashes instead of one, to average out the amount of work performed. With just one hash there will be a lot of luck involved, and the actual work will therefore vary rather wildly.
In the unlikely case that you've invented yet another popular PoW: I'd use 128 bits rather than a 64 bit long. It's pretty easy to make a counter that operates on bytes directly, so you would not even have to convert to the binary values required for the hashing.


Method to close a lot of closeable objects

A ResultSet is closed automatically when the Statement that created it is closed.
A Statement is closed automatically when the Connection that created it is closed.

If you want to close everything, just close the Connection.


Get missing letters - TopCoder challenge

Since the size of the alphabet is fixed, you don't need a set, a boolean array will be enough:

Initialize a boolean array, with size of the alphabet, all values false
For each letter in the input string, set the flag to true for index letter - 'A'
After the entire input string is processed, iterate over the boolean array, if the value is false for an index, then append the character index + 'A' to the list of missing letters

The time complexity of this alternative algorithm is \$O(n)\$ where \$n\$ is the size of the input string, space complexity is \$O(1)\$, for the size of the alphabet.


Knuth–Morris–Pratt string search algorithm

This code does not work. In some cases it fails to find the pattern:

>>> KMP_search('ab', 'aab')
[]

In other cases it raises an exception:

>>> KMP_search('ab', 'ba')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr190837.py", line 39, in KMP_search
    if pattern[j] == lst[i + j]:
IndexError: string index out of range

How could you have found these problems? Well, by testing the code thoroughly. One way to do this is to use random test case generation. The idea behind randomized testing is that it can test a much larger range of inputs than you could ever enter by hand, and it can test parts of the space of inputs that would not be reached by systematic test case generation.

So one idea for a random test case would be to generate a random string of length k:

haystack = ''.join(random.choices('abc', k=k))

(Here I'm using random.choices which was new in Python 3.6. If you're on an earlier version of Python, you could use a loop like random.choice('abc') for _ in range(k).)

Then pick a random substring:

start, stop = sorted(random.sample(range(k + 1), 2))
needle = haystack[start:stop]

Run KMP_search(needle, haystack) and check that the results are correct, for example by comparing with Python's built-in str.find.

This can all be packaged together into a unit test using the unittest module:

import random
import unittest

class TestKMPSearch(unittest.TestCase):
    "Unit tests for KMP_search."

    def test_positive(self):
        for k in range(1, 100):
            # Generate a random test case with k characters.
            haystack = ''.join(random.choices('abc', k=k))
            start, stop = sorted(random.sample(range(k + 1), 2))
            needle = haystack[start:stop]

            # Use Python's built-in str.find to compute the expected result.
            expected = []
            index = -1
            while True:
                index = haystack.find(needle, index + 1)
                if index == -1:
                    break
                expected.append(index)

            # Compare with the actual result.
            found = KMP_search(needle, haystack)
            self.assertEqual(found, expected,
                             "KMP_search({!r}, {!r})".format(needle, haystack))

(I called the method test_positive because the test cases are positive in the sense that the needle is found in the haystack. For really thorough testing you ought to generate some negative test cases too, ones in which the needle is not found. But this is enough to find some errors.)

Now if you run the unit tests you'll (most likely) get a failure like this:

$ python -munittest cr190837.py
F
======================================================================
FAIL: test_positive (cr190837.TestKMPSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr190837.py", line 79, in test_positive
    "KMP_search({!r}, {!r})".format(needle, haystack))
AssertionError: Lists differ: [] != [3]

Second list contains 1 additional elements.
First extra element 0:
3

- []
+ [3]
?  +
 : KMP_search('bac', 'ccbbac')

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)


public static IObservable<DateTime> Create(TimeSpan interval, IDateTime dateTime)
{
    return
        Observable
            .Interval(TimeSpan.FromSeconds(1))
            .Select(_ => dateTime.Now());
}

You forgot to plug interval parameter. And, I would consider renaming it resolution.

I wouldn't trust the values from selecting DatetTime::Now or DateTime::UtcNow:

// try running this for a while
var scheduler = Scheduler.Create(TimeSpan.FromSeconds(1), new LocalDateTime());
scheduler.Schedule("0/1 * * * * * *", schedule =>
{
    Console.WriteLine($"ACTION: {schedule}: {schedule:ss.fff}");
});

ACTION: 2018-04-13 6:28:29 PM: 29.987
ACTION: 2018-04-13 6:28:30 PM: 30.987
ACTION: 2018-04-13 6:28:32 PM: 32.001
ACTION: 2018-04-13 6:28:33 PM: 33.001

Depending on CronExpression::Contains implementation, the scheduler could be skipping task when DateTime.Now.Millisecond gets near 0 or 999.

I've attempted to solve that by adding index * interval to a snapshot of time, however this solution suffered a problem: The delay is cumulative, so the schedule's time will slowly deviate(fall behind) from the real time:

// dont use this
public static IObservable<DateTime> Create2(TimeSpan interval, IDateTime dateTime)
{
    var snapshot = dateTime.Now();
    var offset = interval.Ticks - snapshot.Ticks % interval.Ticks;

    return Observable.Interval(interval)
        .Delay(TimeSpan.FromTicks(offset))
        .Select(x => snapshot.AddTicks(interval.Ticks * (x + 1) + offset));
}

An better solution would be to provide a range of time, and check if expression fall between the range:

public static IDisposable Schedule2(this IObservable<DateTime> schedules, string cronExpressionString, Action<DateTime> action)
{
    var cronExpression = Regex.Match(cronExpressionString, @"^0/(?<s>\d+)");
    return
        schedules
            .Scan(default(TimeRange), (previous, x) => new TimeRange(previous?.End, x))
            .Where(cronExpression.Contains)
            .Subscribe(action);
}

public class TimeRange
{
    public DateTime? Start { get; }
    public DateTime End { get; }

    public TimeRange(DateTime? start, DateTime end)
    {
        this.Start = start;
        this.End = end;
    }
}


Finding the common prefix in a list of strings

There are some inconsistencies in your code style: sometimes you do put a space before an opening curly bracket, sometimes you don't. It is a good practice to adhere to one style(in this case, it is conventional to have a whitespace there). It is also conventional to surround all binary operators with whitespaces to make the code more readable. For instance, for(int x = 0; x < list.length; x++) looks better than for(int x=0; x<list.length; x++).
In terms of time complexity, you algorithm is optimal(it is linear in the size of input). However, if it is supposed to work with long strings, I'd use iteration instead of recursion(it gets a StackOverflowError when the strings get really big). Here is my iterative solution:

public static String getLongestCommonPrefix(String[] strings) {
    int commonPrefixLength = 0;
    while (allCharactersAreSame(strings, commonPrefixLength)) {
        commonPrefixLength++;
    }
    return strings[0].substring(0, commonPrefixLength);
}

private static boolean allCharactersAreSame(String[] strings, int pos) {
    String first = strings[0];
    for (String curString : strings) {
        if (curString.length() <= pos
                || curString.charAt(pos) != first.charAt(pos)) {
            return false;
        }
    }
    return true;
}

In general, each class should have single responsibility(that it, you might create two separate classes here: one for computing the longest prefix and the other one for checking and parsing command-line arguments).  But I think it is fine to have one class here(the entire class is pretty small) as long as the format of arguments is not going to change in the future.


You should remove the many trailing spaces.

You can replace slicing with unpacking and the double-brackets can be removed:

def getJavaName(column):
   first, *rest = column.split('_')
   return first + ''.join(word.capitalize() for word in rest)

Python uses snake_case, even if your DB columns don't, so you should be calling this get_java_name - although personally it's still better named snake_to_camel_case and the column parameter should be renamed to, say, name.


Better way to assert correct return values in Groovy

You can use with to do things inline without declaring another variable:

List list = [
  [first: "foo", last: "bar"],
  [first: "baz", last: "qux"],
  [first: "baz", last: "bar"]
]

List findDuplicateElements(myObjects) {
   myObjects
   .groupBy { it.last }
   .findAll { it.value.size() > 1 }
   .collect { it.value }
   .flatten()
   .with {
     assert it.size() != null
     it
   }
}

assert findDuplicateElements(list).size() == 2


VBA Excel substitute function for multiple conditions at once

You do not want to read and write the cell multiple times. You only do a read and a write. You also need to check if the cell has a string. There is no point in running the replace on numbers or errors. Something like:
Dim v As Variant
Dim i As Long
Dim oldLen As Long

For Each cell In rng
    v = cell.Value2
    If VarType(v) = vbString Then
        oldLen = Len(v)
        For i = 25 To 23 Step -1
            v = WorksheetFunction.Substitute(v, " ", "  ", i)
        Next i
        If Len(v) <> oldLen Then cell.Value2 = v
    End If
Next

Or, if you want to be efficient then you read the range into array and replace the whole thing in one go:
Dim rngArea As Range
Dim arr() As Variant
Dim i As Long
Dim j As Long
Dim lastRow As Long
Dim hasChanged As Boolean
Dim v As Variant
Dim oldLen As Long

For Each rngArea In rng.Areas
    'Read range into array of values
    If rngArea.Count > 1 Then
        arr = rngArea.Value2
    Else
        ReDim arr(1 To 1, 1 To 1)
        arr(1, 1) = rngArea.Value2
    End If

    i = 1
    j = 1
    lastRow = UBound(arr, 1)
    hasChanged = False
    For Each v In arr 'Traverse the 2D array column-wise
        If VarType(v) = vbString Then
            oldLen = Len(v)
            For i = 25 To 23 Step -1
                v = WorksheetFunction.Substitute(v, " ", "  ", i)
            Next i
            If Len(v) <> oldLen Then
                arr(i, j) = v
                hasChanged = True
            End If
        End If
        i = i + 1
        If i > lastRow Then
            i = 1
            j = j + 1
        End If
    Next v
    If hasChanged Then
        rngArea.Value2 = arr
    End If
Next rngArea


Java implementation of the Factory Method pattern

This pattern can be difficult to understand outside of an application with many modes of operation. There are two advantages to using the factory patterns: you can swap in different implementations, and you can vary the construction parameters without changing client code.

Where do these advantages shine? Testing! In the case of a game, randomness is a good example. When playing the game for real, you want your monsters to vary their behavior randomly. But when testing, you need to be able to choose from their possible behaviors. The real factory will initialize each monster with a real random number generator, but tests must be able to specify the behavior choices.

Take this example monster action:

public void chooseCombatAction() {
    if (isAfraid()) {
        return Action.RUN;
    }
    else {
        return Action.ATTACK;
    }
}

private boolean isAfraid() {
    return random.nextInt(10) > 7;
}

To test chooseCombatAction, you need to provide a mock random number generator. But if the constructor creates it, you can't. Instead, have the factory provide it, and create an implementation that takes one with pre-configured values. Now you can give that factory to the root game object that uses the factory to create monsters.

  Style Note: Drop implied modifiers--such as public and abstract on interface members--wherever possible. Every modifier adds context that must be groked.


Using Dynamic to create and then flatten an arbitrarily-nested array

There's never any reason to use dynamic here at all.  You never use any of its features.  You could literally copy-paste all instances of it with object and the code would function identically.

Now, that's not a particularly good design for storing data like this.  If you actually want to store a tree of data you're better off with a more traditional tree setup.  Create a Node type, and let those nodes have both values and child nodes, which can themselves have child nodes, and so on.  You can then traverse that tree structure.  That makes it much clearer what's going on, rather than just seeing an object that you happen to just know is a tree structure where it contains either a sequence of other objects, or a value, and where each object in the sequence may itself be a sequence or a value.  It also means that when you create operations that work with these trees they can accept instances of those types, so people don't do weird things like pass in a string to your method here, only to have it crash, instead of just failing to compile.

As for the actual Flatten method, personally I'd prefer a non-recursive implementation.  Most significantly because the stack in C# just isn't that big, and it's not really all that uncommon to have tree structures that are deeper than the stack can support, resulting in you getting stack overflow exceptions.  It's a little bit easier code to write the recursive version for many people, but you're constraining yourself to only working with shallow trees by using it.

I'd also suggest making the Flatten method an iterator block.  There's no sense computing the entire value right from the start, when the underlying algorithm itself is inherently computing one value at the time.  Using an iterator block lets the consumer use each value as you compute it, and removes the need for you to do the work of computing values that may not be needed, and also prevents the entire result set from needing to be in memory all at once, assuming the resulting values can be processed one at a time (a common enough situation).


Outputting the Manufacturer ID of a processor using CPUID with inline ASM

Use uint32_t

You have to be careful with shift operations on signed integers. In particular, right shifts on signed integers have implementation-defined behaviour, so it is hard to write portable code for it. It might work out in this case, but it is better to treat the values as unsigned integers here.

Bit shifting

While you have written a correct function to print the individual bytes of a 32-bit integer, it is a bit overkill. You can write it like so:

void print_register(uint32_t value) {
    printf("%c%c%c%c",
           (int)value,
           (int)(value >> 8),
           (int)(value >> 16),
           (int)(value >> 24));
}

This uses the fact that when printing a character, the value will already by truncated to 8 bits as if you would have written value & 0xFF, (value >> 8) & 0xFF, and so on. The cast to int might be necessary because the %c conversion expects an int, but int32_t might have a different size than an int on some platforms (for example, on an Arduino with an AVR CPU, int will be 16 bits).


Using counter for both for loops seems awkward.

for(int i = 0; i < n1; i++) {
    result[i] = a1[i];
}
for(int i = 0; i < n2; i++) {
    result[n1 + i] = a2[i];
}

This way, the for loop looks just like people expect it to look. Your implementation requires extra thought. There is still a single arithmetic operation for indexing in the second loop, so reusing counter is not saving you anything.

One line if statements can be missed by someone reading your code. Plus you need to remember to add curly brackets if you want to add a second line.

concatArrays(int[] a1, int a2) does not concatenate arrays. Function names that lie about what they do are bad.


I can't agree with tinstaafl's idea of creating a new array for every input number that starts with a 9. It's not needed in roughly 10% of the possible inputs.

I do however agree that using a for loop is better in this case. Anyone even mildly familiar with for loops can instantly recognise you're looping over each of the digits from right to left which isn't as clear in your while loop.

Instead of breaking the for loop and doing the special case testing afterwards you could also return early instead. With a little bit of rearanging this also simplifies the loop itself slightly.

The final for loop to set the result to all 0's is not needed. Creating a new int[] array will already set them all to 0 for you.

Putting this all together gives us the following implementation:

static int[] plusOne(int[] digits){
    for(int i = digits.length-1; i>=0; i--){
        if(digits[i]<9){
            digits[i]++;
            return digits;
        }
        digits[i]=0; //carry handled by next iteration in for loop
    }
    //didn't return yet so digits were all 9's
    int[] result = new int[digits.length+1];
    result[0] = 1;
    return result;
}


Concatenating 2 array variable names to create a new variable name

I have to agree with bumperbox here - why create separate variables instead of using an array to store them all, as follows:

$day = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$B = array('P1B', 'P2B', 'P3B', 'P4B', 'P5B', 'P6B');
$arr = array();

for ($l = 0; $l < count($day); ++$l) {
    for ($k = 0; $k < count($B); ++$k) {
        $days = $day[$l];
        $week = $B[$k];
        $arr[$days . $week] = $_POST["'" . $days.$week . "'"];
    };
};

Which would generate:

Array
(
    [MonP1B] =>
    [MonP2B] =>
    [MonP3B] =>
    ...
    [FriP4B] =>
    [FriP5B] =>
    [FriP6B] =>
)

And which you can access via $arr['FriP5B'] for example.

Now, as to how you can improve your code, see this:

$days_of_the_week = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$number_of_days = count($days_of_the_week);
$rooms = array('P1B', 'P2B', 'P3B', 'P4B', 'P5B', 'P6B');
$number_of_rooms = count($rooms);
$booked_day_room = array();

for ($day = 0; $day < $number_of_days; ++$day) {
    for ($room = 0; $room < $number_of_rooms; ++$room) {
        $days_room = $days_of_the_week[$day] . $rooms[$room];
        $booked_day_room[$days_room] = isset($_POST[$days_room]) ?: $_POST[$days_room];
    };
};

print_r($booked_day_room);

What we did:

Used descriptive variable names
Cached the count() function calls
Stored everything in 1 array, so we don't have to chase 100 different variables

Why are we using an array over multiple variables? Multiple variables might be a bit faster, and they might use more or less the same memory, however from a code readability standpoint, you want one array as it is easier to keep track of in the code.


It works but is my use of promises good or an anti-pattern?

Promises work great when using $http.

  Should I be using the success and error methods provided by $http in place of then and catch?

According to the documentation:

  Returns a promise object with the standard then method and two http specific methods: success and error. The then method takes two arguments a success and an error callback which will be called with a response object. The success and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method.

So you should use .then(successHandler, errorHandler) or .success(successHandler) and .error(errorHandler), but .catch(errorHandler) will not work with $http! According to the docs anyway...

function solveChallenge(url, challenge) is confusing to me, is this function really solving the challenge or is it checking the solution against a server? Consider renaming to checkSolution(url, challenge)

function getChallenge(url) is also confusing, it gets the challenge, solves it, and returns an answer from a server to see if the solution was correct. Should it be renamed to getAndSolveChallenge(url)?

function sumArray(items) could be rewritten as:

function sumArray(items) {
  return items.reduce(function(previousValue, currentItem) {
     return previousValue + currentItem;
  }, 0);
}

but there is nothing wrong with your sumArray function as is.


int out = rand.nextInt(max - min) + min;
while (!isPrime(out)) {
    out = rand.nextInt(max - min) + min;
}
return out;

This duplicate code can be replaced with a do/while loop. The rule of thumb is, if you always need to perform an action at least once, do while!

int out;
do {
    out = rand.nextInt(max - min) + min;
} while(!isPrime(out));
return out;


.bind should've been used here instead of .apply

on: function(msg, callback) {
    socket.on(msg, $rootScope.$apply.bind($rootScope, callback.bind.apply(socket, arguments)));
},

But seeing how complicated the shortened "one-liner" becomes, expanded form was probably better:

on: function(msg, callback) {
    socket.on(msg, function(data){
        $rootScope.$apply(function(){
            callback(data);
        });
    });
},


Here are a few suggestions on how to simplify and format your code.
Break directly from the loop
In your loop construct there really is no point in keeping track of exit.  In addition exit is used by Python, and it is better to not reuse these things becuase it can be confusing.  Instead something like:
while True:
    if input(msg).lower() == 'exit':
        break

In addition this shows how you really only need one input statement.  Instead the message for input can be set as needed.
Avoid extra parens
In all three of these cases you have an extra set of outer parens.
if (enter=="exit"):
while(enter=="" or not exit):
enter=(input("Press Enter to Roll Again! \n").lower())

Use descriptive variable names
As an example you have a variable named count, that I think would be more descriptive as roll_number.  Additionally dice_number might be more descriptive as dice_value.
Use the programming language to its fullest.
Python has a bunch of nifty operators that can make code cleaner.
count = count + 1

Can be written as:
count += 1

which makes it more explicit that the variable is being incremented, and not just assigned.
PEP8
You should consider formatting your code in accordance with pep8.  This is important when sharing code, as the consistent style makes it much easier for other programmers to read your code.  There are various tools available to assist in making the code pep8 compliant.  I use the PyCharm IDE which will show pep8 violations right in the editor.
One PEP8 note that I will highlight is to not use what are relatively obvious comments.  With clean code and descriptive variable names the code will often be as descriptive as the comments.
Reconstructed code:
""" This Program is Dice Simulator that produce an Output from 1-6
everytime the User presses Enter. In order to close the Program,
the User has to type "Exit" into the console.
"""

import random

print(" Hi! Welcome to Dicey!")
print("""

   .-------.    _______
  /   o   /|   /\\      \\
 /_______/o|  /o \\  o   \\
 | o     | | /   o\\______\\
 |   o   |o/ \\o   /o     /
 |     o |/   \\ o/  o   /
 '-------'     \\/____o_/

  """)

roll_number = 0
msg = "Press Enter to Roll (or) Type 'Exit' to Close.\n\n"
while True:
    if input(msg).lower() == 'exit':
        break

    roll_number += 1
    dice_value = random.randint(1, 6)
    print(f"{roll_number}> You got a {dice_value}\n")

    msg = "Press Enter to Roll Again! \n"


How can use array to imitate repeated individual instances?

Do you mean like this:

def searchDir = ["z:/pathA/pathB","z:/pathA/pathQ"]
searchDir.each { d ->
    new File( d ).eachFile {
        if (it.isFile()) {
            outfile.append( "$it.name\n" )
        }
    }
}


Perl 6 oneliner to sum up all numbers in a text file

The warning comes from the fact that the third and fourth capture groups are inside an optional part of the regex.  Therefore, $f[4] might not be defined.

Rather than concatenating the parts of a decomposed number, I suggest taking all of $f[0] and replacing any comma with a period.

my $sum = 0;

my regex float {
                 <[+-]>?          # opt. sign
                 \d+              # whole part
                 [ <[.,]> \d+ ]?  # opt. fractional part
                                      #comma is vaild separator
               }

for slurp.match( / \* <float> /, :g ) {
    $sum += +$_<float>.subst( /','/ , '.' , :g );
}

say $sum;


Your script consumes a lot of CPU due to the while loops. Using just the input function in a loop should be good enough for your purpose. I can't see the need for threading in a script that is quite basic for the moment.

These:

global cont
global text

don't belong in your class.
A class is normally supposed to be self-contained and shouldn't have to rely on global variables defined elsewhere. They should go inside the class body.
On the other hand you can pass parameters to your class instantiation method or to some class functions.

By the way text is not a good choice of variable since many objects have a text property and be careful with reserved keywords.

Exception handling is lacking. Any quality script should have at least basic exception handling (ten lines of code could do).

Validation of user input is also lacking.
If I type anything after help I have a KeyError exception and your script crashes too easily. The dictionary selection is rather clumsy but see below for suggestions.

Structure: I am wondering why you split the code in two classes ?
InputThread could have been embedded in CLI as a subclass or simply implemented as a function. But they are not independent from each other.

Style: after:

if __name__ in '__main__':

the norm is to call main(), so it is customary to have a main method.

You don't call a class like that:

x = CLI().loop()

Instead:

x = CLI()

with optional parameters inside the parentheses, or you run the code in multiple steps eg:

# instantiation
x = CLI()
# or:
x = CLI(prompt="Prompt message goes here")
x.start()
x.stop()

Because you can perfectly instantiate a class without immediately running it.

Naming conventions: variable names (a, text) are not always well-chosen and meaningful.

Misc: your script does not recognize commands in uppercase. I would always convert the commands to lowercase and use strip to trim them (here the split command takes care of that).

Overall impression: I think that this is a way of reinventing the wheel. There are modules that already exist for interactive cli programs, for example PyInquirer. There is also clint and quite a few others (I have not tested and compared all of them).
So I think I would build on the more mature solutions available, unless the problem you are trying to solve cannot be addressed adequately by the solutions that already exist.

An alternative would be to use feature-rich argparse. Because it can be used not only for command line options but in functions too (I haven't done that yet though but it's worth investigating). To give you an idea have a look at this post on SO: How to pass parameters to python function using argparse?. Also have a look at the Sub-commands section for more elaborate scenarios. As you can see this module is very powerful and very often underutilized.

It seems to me that it could have fulfilled all your desired functionality, with increased flexibility since the commands could be passed in a different order, as long as the grouping of dependent parameters is respected.


Lots of Continues in an Inner Loop and Dictionary of Actions

If you do this often, you could write an extension method for object that takes a function, which is executed only when the input is not null. You could then use it in a fluent manner to navigate multiple times:

public static class Navigator
{
    public static TOutput Navigate<TInput, TOutput>(
        this TInput input, Func<TInput, TOutput> navigationFunction)
        where TOutput : class
    {
        if (input == null)
            return null;

        return navigationFunction(input);
    }
}

Usage:

var destinationPage =
    (annotationMaster.Resolve(Atom.GetItem(annotationMaster.Atom, 0)) as DictAtom)
        .Navigate(annotItem => annotItem["D"] as ArrayAtom)
        .Navigate(destination => destination[0] as RefAtom);

if (destinationPage == null)
    continue;

Notice that I also removed the braces. This is a matter of personal opinion (and sometimes company policy), but I think that they're not always necessary, especially when the body of the condition is this simple.


PHP function to access a database and return json

This:

$tables = array(
    "day"        => "p_day",
    "month"      => "p_month"
    ... etc. .....
);

$table = $tables[$user_table];

if(!$table) {
    die(json_encode(array("error" => "bad table name")));
}

will throw a notice if $user_table is not a valid array key, something you should have already tested. Rewrite as:

$tables = array(
    "day"        => "p_day",
    "month"      => "p_month"
    ... etc. .....
);

if(!array_key_exists($user_table, $tables)) {
    die(json_encode(array("error" => "bad table name")));
}

$table = $tables[$user_table];

I really hate it when functions die(), and in your case there's no point in that. You could simply do:

if(!$table) {
    return json_encode(array("error" => "bad table name"));
}

since the function is expected to return a json formatted string. If you really want to die() you should do that where you call the function and the returned string is an error. Or you could just return false when an error occurs and the raw array when everything works, and when calling the function do something like:

$result = json_encode(getReport("some_table"));

That way getReport() will be useful even when you don't need json encoded output. But that's up to you and how you actually use it.

As @LokiAstari mentions mysql_* functions are deprecated and should be avoided. I would skip mysqli_* functions too and use PDO which will give you the extra bonus of switching to another database engine if you ever need to and it has a nice OO interface.

For everything else, I'm with @LokiAstari.


CRC function duplication – differ only in pointer vs iterator signature

The obvious way is to replace the type that changes with a templated type, like this:

template<typename T>
static inline crc_t crc_update(crc_t          crc,
                               T              data,
                               long long      data_len)
{
    while (data_len--)
    {
        crc = (crc_table[(crc ^ *data) & 0xff] ^ (crc >> 8));
        ++data;
    }
    return crc;
}

Or in words: put template<typename T> in front of the function, and replace all char const * with T.

There are some details about inserting typename in some cases to help the compiler, but those do not apply in this case.

To prevent incorrect usage, one might add some checks to ensure that only 8 bit types can be used. However, that is advanced stuff and not required to answer your question.


There is one bad problem in the code that can be answered by the basis of the pattern presented here:

// Inherit from validator
var VatCheck = Validator;

This does not inherit anything, instead it causes VatCheck name to point to the exact same object (constructor function) as the Validator. Thus all you are doing is overwriting Validator.prototype.isValid (changing the base implementation), and aliasing the base implementation by different names.

If you repeat this pattern again, the end result is that all validators have their isValid check method do the action of the last validator type that you define.

Instead you need to do VatCheck.prototype = new Validator() but then you need to also redo the constructor.


The 99th percentile is due to the linear nature of your approach. The goal of this exercise is to figure out a logarithmic one.

I don't want to spell out the algorithm entirely. Just a hint to get you started. Take a middle element of nums1. Find its lower bound in nums2; call it i2. In the sorted array the selected element would be at the position nums1.length/2 + i2. I hope the hint is a good enough.

pivot doesn't look like a good name to me. totalLength, perhaps?

The complicated logic inside the loop also hurts the performance. Consider looping until you reach the midpoint:

    while (i1 + i2 < pivot)

and do the final median finding afterwards.


Just some points:

Naming:

What does mstv mean? I assumed that ms in mstv stands for minimal spanning, but what is tv then? Television?

Try clearing that up with a more "reasonable" name.
Bad Practices:

This is definitely prone to bugs:

    for (int j = 0; j < gSize; j++)
        if (mstv[j])
            for (int k = 0; k < gSize; k++)
                if (!mstv[k] && weights[j][k] < minWeight)
                {
                    endVertex = k;
                    startVertex = j;
                    minWeight = weights[j][k];
                 }

Even though there might be no bugs in the code above, accidental mistakes do occur more if you lack braces.

Instead, add the braces, which makes the code both more readable and less error-prone:

for (int j = 0; j < gSize; j++) {
    if (mstv[j]) {
        for (int k = 0; k < gSize; k++) {
            if (!mstv[k] && weights[j][k] < minWeight) {
                endVertex = k;
                startVertex = j;
                minWeight = weights[j][k];
            }
        }
    }
}

(Note that this is using my coding habits; you may move the braces where you are comfortable with)


Function that helps with reaching nested objects

Very similar to an earlier answer I did with regards to deep value extraction. Here's the code:

function createResolver(keypath){
  return new Function('root', `
    try { return root.${keypath}; }
    catch(e){ return undefined; }
 `);
}

// Return foo.bar.baz
var obj1 = { foo: { bar: { baz: 'bam!!!' }}};
var resolver1 = createResolver('foo.bar.baz');
var value1 = resolver1(obj1);

One difference between this one and your approach is that your approach seems to evaluate on every call. This can be slow as you are having the browser evaluate the string JavaScript on every call. A constructed function on the other hand can be cached. This means you can construct the function once, store the constructed function, and call it over and over again without having to re-evaluate the string every time.

// keypath-resolver store
var resolvers = {}

function createResolver(keypath){
  return new Function('root', `
    try { return root.${keypath}; }
    catch(e){ return undefined; }
 `);
}

// Create a resolver for foo.bar.baz. We only have JS evaluate the string here.
resolvers['foo.bar.baz'] = createResolver('foo.bar.baz');

var obj1 = { foo: { bar: { baz: 'bam!!!' }}};
var obj2 = { foo: { bar: { baz: 'pow!!!' }}};

// We just call the function. No evaluation!
resolvers['foo.bar.baz'](obj1);
resolvers['foo.bar.baz'](obj2);

Although these two approaches seem to act the same, one issue with eval is that it evaluates the string in the scope it is called. This means it can leak variables or override code that's visible in the current scope, just like you did with result. A generated function on the other hand does not. It does not form a closure of the scope it was created from, and the immediate outer scope is the global scope. This makes it relatively safer than eval.

Your reliance of console.log is also something to ponder on. If it's an error, is it not better to actually throw than just log the error? Also, if the keypath isn't fully resolved, this means the value isn't present which makes it technically undefined. Consider returning undefined instead of logging an error if you want errors to be handled.


Removing repetitive code in ASP.NET MVC Controller actions?

I like the direction Scott started but would recommend to take it another layer down so that the GenerateSignature method does not have to do discovery with the thing object (Do I have an Id or do I have string X/Y/Z or do I only have Key/Signature, etc).

public class MySignatureCreateRead
{
    public string Key { get; set; }
    public string Signature { get; set; }
}

public class MySignatureUpdateDelete : MySignatureCreateRead
{
    public int Id { get; set; }
}

public class MySignatureAction : MySignatureCreateRead
{
    public string X { get; set; }
    public string Y { get; set; }
    public string Z { get; set; }
}

Which puts the ActionResults like:

public ActionResult List(MySignatureCreateRead signature) { GetSignature(signature); /* etc */ }
public ActionResult Add(MySignatureCreateRead signature) { GetSignature(signature); /* etc */ }
public ActionResult Update(MySignatureUpdateDelete signature) { GetSignature(signature); /* etc */ }
public ActionResult Delete(MySignatureUpdateDelete signature) { GetSignature(signature); /* etc */ }
public ActionResult Action1(MySignatureAction signature) { GetSignature(signature); /* etc */ }

This also gives you objects to strongly bind views to.


To address your "main need" first: Your algorithm starts with a
single-element array, and then repeatedly calls primeFact() to
compute a new array, until the array is "constant". That can
be done more clearly as

var initial = [992]
var temp = [Int]()
repeat {
    temp = initial
    initial = primeFact(tree: temp)
} while initial != temp
print(initial)

However, your algorithms seems to be highly inefficient, for
the following reasons:

Since the trial division starts with the lowest possible divisors,
each found divisor is necessarily a prime number. But the
next call to primeFact() will again try to find divisors of that
number.
All calls to primeFact() will try all numbers starting from 2
as divisors for all elements in the "tree". For example, if the
current list is [2, 2, <someOddNumber>] then each call will
again try to divide <someOddNumber> by 2.
A lot of intermediate arrays are created.
Possible large arrays must be compared in order to determine if
the factorization is done.

Additional remarks:

Put spaces around operators, e.g. element % divisor for
better readability.
Use either [Int] or Array<Int> for array notation (I prefer
the first), but don't mix it.
Calling the parameter tree is confusing because you treat
it as an array, not as a tree.

A more efficient approach is to divide the given number by 2, 3, 4, ...
As soon as a factor is found, the number is divided by this factor.
Using the fact that composite number \$ n > 1 \$
must have a prime factor \$ p \$ for which  \$ p \le \sqrt n \$,
this leads to the following function:

func primeFactors(_ n: Int) -> [Int] {
    var n = n
    var factors: [Int] = []

    var divisor = 2
    while divisor * divisor <= n {
        while n % divisor == 0 {
            factors.append(divisor)
            n /= divisor
        }
        divisor += divisor == 2 ? 1 : 2
    }
    if n > 1 {
        factors.append(n)
    }

    return factors
}

As another small optization, only 2 and all odd numbers are used
as trial divisors.

Performance comparison:

For \$ N = 1000000000000 = 2^{12} \cdot 5^{12} \$:
Your tree factorization: 1ms. Direct factorization: 0.005 ms.
For \$ N = 1000000000001 = 73 \cdot 137 \cdot 99990001 \$:
Your tree factorization: 1,100ms. Direct factorization: 0.1 ms.

The tests were done on a 1.2 GHz Intel Core m5 MacBook, with the
code compiled in Release mode.


Place try/catch in business logic or user interface

It can be interesting to convey more information about the error to the end user, but it doesn't mean the UI layer has to be the only one to handle the exception.

You can both log the error into your database from the business layer and relay it to the UI layer if you rethrow the exception:

try {
    // Insert user and return userId...
} catch (Exception ex) {
    // Log error to database...
    throw;  // Relay error to UI layer.
}


Should a PDO object be passed to classes and procedural functions as a parameter?

Let's start with the review, and then talk about correctness of the approach.

Pass things by parameters - What do you do if your credentials change? Don't you want to reuse the function? Pass the credentials as parameters to the createPDO function, or better yet, the DSN directly:

function createPDO($dsn, $user, $password)

Add good practice defaults to PDO instance - Use $pdo->setAttribute() to set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and PDO::ATTR_EMULATE_PREPARES to false.
Don't handle exceptions in your function - You are creating hidden dependencies (You now depend on errorHandler to exist somewhere in your application). Also, you don't know what you want to do if you fail creating the PDO instance. In this app you may want to kill the script, in another you may want to fall back to the filesystem. It's not your function's job to know!
Typehint what you can - Your $stmt variable is a PDOStatement object. You should hint it in the function's signature. Your $array is an array.

function makeQuery(PDOStatement $stmt, array $params)

Approach wise, you should ask yourself, What in my application needs a PDO object?

If the rest of your application is procedural, there's no point in even what little abstraction you tried to give here. However, if you do have some sort of other object which uses the PDO connection, then using lazy loading is a good practice to follow:

$pdoProvider = function() {
    //Do all PDO instantiation logic here
};
$mapperFactory = new MapperFactory($pdoProvider);

By passing in a function instead of the actual object, you can delay the creation of the object until it's first needed (which may not even happen, saving you the connection!)

In the MapperFactory:

class MapperFactory {
    private $provider;
    private $pdoInstance;
    public function __construct(callable $provider) {
        $this->provider = $provider;
    }
    public function create($mapper) {
        if ($this->pdoInstance !instanceof PDO) {
            $this->pdoInstance = call_user_func($this->provider); //Call the provider, get the PDO instance
        }
        //By this point, $this->pdoInstance has a PDO instance for sure.
    }
}

For more information, See this answer on Stack Overflow.


One thing that I do not like very much is that the code calls
  doesDirectoryExist twice.

You can return the result of the doesDirectoryExist from getSubitems and pass it to copyItem, obviating the duplicate call.

  Especially, I would like to make it as succinct and as idiomatic as
  possible.

You can use low precedence <$> instead of fmap to remove some parentheses.

Also "." and ".." should be returned once from getDirectoryContents, so you can replace the

(filter (`notElem` [".", ".."]))

with (\\ [".", ".."]).

Slight Behavior Difference between copyTree and copyTree'

Behavior of copyTree' is slightly different from copyTree, in that it will accept files as well as directories as parameter s. This is due to the fact that getSubitems' includes the input parameter (path, root of the subtree) in the descendants list it returns. You can get back the previous behavior by ignoring the first value returning from the getSubitems' in copyTree'. But I left the change in copyTree' as is for a behavior more consistent with cp -R of POSIX.

Modified Code

import Data.Functor ((<$>))
import Data.List ((\\))

getSubitems' :: FilePath -> IO [(Bool, FilePath)]
getSubitems' path = getSubitemsRec ""
  where
    getChildren path =  (\\ [".", ".."]) <$> getDirectoryContents path

    getSubitemsRec relPath = do
        let absPath = path </> relPath
        isDir <- doesDirectoryExist absPath
        children <- if isDir then getChildren absPath else return []
        let relChildren = [relPath </> p | p <- children]
        ((isDir, relPath) :) . concat <$> mapM getSubitemsRec relChildren

copyItem' baseSourcePath baseTargetPath (isDir, relativePath) = do
    let sourcePath = baseSourcePath </> relativePath
    let targetPath = baseTargetPath </> relativePath

    putStrLn $ "Copying " ++ sourcePath ++ " to " ++ targetPath
    if isDir
      then createDirectoryIfMissing False targetPath
      else copyFile sourcePath targetPath

copyTree' s t = do
    createDirectoryIfMissing True t
    subItems <- getSubitems' s
    mapM_ (copyItem' s t) subItems


Combine lists of objects with no duplicates

Formulate your SQL query such that you get exactly the combined results you want. Don't use Groovy to do work that the database should be doing for you.  It will be faster and easier.


Considering there is almost no code to review, this will be purely stylistic. Remember that criticism is a sign of love.

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>

The comment isn't needed, we all know what a codebehind is for. Comments should explain the why, not the what.
You should (almost) never have public fields. If they are actually needed outside of the current object's scope then you should make them properties, otherwise private.
Are they consciously static? This will mess up your program if you execute it multiple times simultaneously. A static modifier on a field is something you probably won't need very often and should be avoided unless needed.
You're hardcoding the user's path. It would be more userfriendly to let them pick this through a FolderBrowserDialog.
C#'s naming conventions dictate that methods are UpperCamelCase, not lowerCamelCase.
You've already imported System.Drawing, remove all the explicit namespace naming in your code.
currentImage is only used inside the first part of your if block so you should declare it there. Always restrict the visibility of variables to the most-restrictive scope possible. You'll notice you won't even need the temporary variable and might as well use CaptureScreen().Save(saveAddress).
if(recording == false) can be less verbosely written as if(!recording).
Don't use this unless you need it to distinguish between members of different scopes.
Use resource files to store your buttons their text so you can easily re-use messages and add additional languages. It also allows you to centrally manage all messages.
CaptureScreen() indicates a long-running operation with perhaps events raised to return information. That's not the case here. I suggest naming it GetScreenCapture().
Some people prefer using var to - again - be less verbose.