Do-While loop in Python, with limit on the amount of 'do's

Python has a language feature just for that: else clauses on loops.

  Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

def post_safe(url, params):
    max_tries = 3
    messages = []

    for _ in range(max_tries):
        try:
            response = requests.post(url, data=params)
            return True
        except Exception as e:
            messages.append(e)
            time.sleep(1)

    else:
        print(datetime.now().strftime('%Y-%m-%d %H:%M'))
        print("requests() failed %d times:" % (max_tries))
        for m in messages:
            print(m)
        return False

I'd also make the following changes:

The else clause on the try block is unnecessary; it can be replaced with a break within the try block just after calling .post().  But in the end, you'll just end up returning True, so why not get out of there right away with return True?  (For that matter, the else block that I just suggested is also unnecessary, as the else could be removed and its contents outdented by one level.)
It seems easier to print each line separately than to build a multi-line string to print all at once.  You might want to consider logging instead.


Code to ask for user string, then display the output

More elegant way to check if a string is empty
Read here

if not s_string:
    sys.exit()

You don't need a sys.exit(), just let the program exit on its own.

if s_string:
    print(s_string)

# the program will exit here anyway.

sys.exit() has some side-effects like killing the python interpreter, which might have some undesirable effects. Read here

You don't even need to check if the string is empty

print(s_string) # If string is empty, will print nothing except for a newline.

Name s_string just s or string.

It doesn't detract from the readability of the code, and makes it more pretty and easier to type(and read)

Most people tend to prefer double quotes " for string literals Read Here


I don't recommend the use of a FROM clause with UPDATE, as it is non-standard SQL.  Neither Oracle nor MySQL supports UPDATE … FROM ….  PostgreSQL does support FROM, but the documentation states that it is a PostgreSQL extension.  Even worse, it interprets the FROM clause differently from Microsoft SQL Server!  (PostgreSQL treats the Item i in the FROM clause as a self-join with the Item table in the main clause of the UPDATE; SQL Server treats it as an alias of the same table.)

I suggest using a Common Table Expression to reduce the redundancy.  CTEs with UPDATE are still non-standard, but at least PostgreSQL and SQL Server interpret the query in the same way.

WITH ItemsForEstimate AS (
    SELECT ItemID
        FROM Item
            INNER JOIN BidItem
                ON BidItem.BidItemID = Item.BidItemID
            INNER JOIN [Group]
                ON [Group].GroupID = BidItem.GroupID
        WHERE EstimateID = @EstimateID
)
UPDATE Item SET AttachementID = NULL
    WHERE
        ItemID IN (SELECT ItemID FROM ItemsForEstimate)
        AND AttachementID NOT IN (SELECT ItemID FROM ItemsForEstimate);

Since GROUP is an SQL keyword, it should be quoted as an identifier.  (I'm surprised that your query worked at all.)

AttachementID should be spelled AttachmentID.


Removing duplicates from a linked list without a buffer

Problem statement

The problem is underdefined. In a real-life interview I'd ask immediately, do we care about the stability? If yes, your solution is good. If no, sort the list first.
Complexity

\$O(n^2)\$ and \$O(n\log n)\$ are quite different beasts. This algorithm is \$O(n^2)\$ obviously. If sorting is allowed, there is a \$O(n \log n)\$ solution.
getters and setters

Python doesn't have a concept of public and private. At the end of the day everything is public. getData, getNext and setNext do not serve any purpose but generating entropy.

Even in the language which encourages such approach it only makes sense when there is an invariant to maintain. Unrestricted getter and setter are as good as a public member.


This code is confusing and inefficient:

for token in map(str, molecule):

It treats molecule as some kind of iterable object, and applies the str function to each element the iteration returns, an assigns each result successively to token.  In this case, molecule is a string, which is already a sequence of iterable characters, and a single character is itself a string, so this map function is taking individual character strings and calling str() on those character strings to return the same character strings.

The statement could be written much simpler:

for token in molecule:

These statements are testing for only 2 of the three grouping brackets:

    elif token == '(' or token == '[':
        ...
    elif token == ')' or token == ']':
        ...

The correct statements would read:

    elif token == '(' or token == '[' or token == '{':
        ...
    elif token == ')' or token == ']' or token == '}':
        ...

however, this is rather verbose.  You can use the in operator to check if a character appears anywhere in a string, so these test could be written more compactly as:

    elif token in '([{':
        ...
    elif token in ')]}':
        ...

isdigit() is not the best function to use to verify a string can be parsed as an integer.  It includes superscript and subscript digits, and other characters which will cause an exception when passed into int(...):

>>> "³₂".isdigit()
True

Instead, use isdecimal().

As mention by scnerd in their answer, it is hard to parse strings character by character.  You are detecting a lower case letter, adding it to the last token you found, and replacing the last token.  You would need to do the same thing when you find a digit, and only when the current series of digits end perform the replication of the last radical, but this results in numerous special cases, which again make the parsing hard.

It is better to break the molecule into low level tokens, not individual characters, and process complete tokens.  As mention by scnerd, the regular expression engine can help.  They diverted into attempt to match parenthesis in the regular expression parsing, which complicates things far too much.  Here is a simpler approach:

import re

def tokenize_molecule(molecule):
    return re.findall('[A-Z][a-z]?|\d+|.', molecule)

molecules = ['H2O', 'Mg(OH)2', 'K4[ON(SO3)2]2', 'C12H22O11']

for molecule in molecules:
    print(molecule)
    print("\t", tokenize_molecule(molecule))

which outputs:

H2O
     ['H', '2', 'O']
Mg(OH)2
     ['Mg', '(', 'O', 'H', ')', '2']
K4[ON(SO3)2]2
     ['K', '4', '[', 'O', 'N', '(', 'S', 'O', '3', ')', '2', ']', '2']
C12H22O11
     ['C', '12', 'H', '22', 'O', '11']

Here, the regex has 3 parts: [A-Z][a-z]? which matches an element, \d+, which matches one or more digits, and . which matches any character.  These are joined together with the | alternative operator; if the current character does not begin an element name, or a digit group, it is returned as a single character ... which is one of the bracket characters in a properly formed molecule.

Using this initial parsing will make the parsing the molecule much easier:

def parse_molecule(molecule):

    # ...

    for token in re.findall('[A-Z][a-z]?|\d+|.', molecule):

        if token.isalpha():
            # ...
        elif token.isdecimal():
            count = int(token)
            # ...
        elif token in '([{':
            # ...
        elif token in ')]}':
            # ...
        else:
            raise ValueError('Unrecognized character in molecule')

    # ...


The compiler warns you

The gcc compiler doubles as a code analysis tool. Running on your code it found the following potential problems:

year.c:4:1: warning: return type defaults to ‘int’
 valid(int day, int month, int year)
 ^
year.c: In function ‘main’:
year.c:26:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d", &day);
     ^
year.c:27:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d", &month);
     ^
year.c:28:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d", &year);
     ^

The last 3 warnings are no big deal in a toy like this, but the first is important: you forgot saying that the functions returns an int, greatly confusing the future reader of your code as he may not know by heart that unspecified return type defaults to int.

The (not)-boolean return antipattern

    if(day < 1 ||  day > st[month-1] || month < 1 || month > 12 || year < 0)
        return 0;
    else
    return 1;

Means that if day < 1 ||  day > st[month-1] || month < 1 || month > 12 || year < 0 is true you return 0 (false) otherwise (if it is false) you return true.

expression_value = true -> return_value = false
expression_value = false -> return_value = true

Just return the negation: !

return ! (day < 1 ||  day > st[month-1] || month < 1 || month > 12 || year < 0);

The same in general applies when there is no negation, booleans shall be returned direclty, not after an if - else

Use a negative check to reduce nesting

If a pre-condition is not met, just abort early:

if(! valid(day, month, year)) {
    puts("\nInvalid date\n");
    return 1; // non-zero return code signals error.
}

puts

printf has a lot of power, when dealing with simple strings puts is preferred (see the example above).


Inserting a Node in a singly linked list

public Node(){
      this.next = null;
      this.data = 0;
}

As used, your no-arg constructor can be reduced to Node() {} The default instance values for objects and integers is null and 0 respectively; this is redundant.

In your insert method you refer to item yet it has no reference anywhere, I'm guessing that's supposed to be data but that's conjecture. The same goes for wherever first comes from. I'm guessing the actual linkedList class keeps reference to it, but again without the context this is purely speculation.

I would suggest you ponder why linkedlists are used. When you think of the answer you might realize you want to keep a reference to tail and prev as well.


Using std::future to manipulate objects in C++11

There are two things that concern me in the code you offer:

The Thing instances pointed to by tA, tB, tC are leaked. In this case it looks like it would be trivial to address this by stack allocating them, and passing their address to the async calls: Thing tA; async( ... , &tA);
The cross thread synchronization dependencies are not explicitly addressed. Instead it's all implicit by the way the code is written. Any mistake in the code to lead to data races. For example if in creating tB2 it called the wrong get() or pass the wrong Thing*, not only would it be the wrong value, but it might race.

I spent some time trying to figure out if proposed functionality such as Resumable Functions (pdf) would allow this to be nicer, and while I expect resumable functions would help in more general code, in your code I think a bigger problem is the factoring. Namely, since nothing uses the middle state, the code passed to the future should encompass both operations.

auto tLambdaBoth = [](const string& iStr, Thing* oThing) -> Thing* {
    auto pthing = tLambda(iStr, oThing);
    return tLambda(pthing->getValue(), oThing);
}

And writing this showed me a new angle on my second misgiving. The original code mixed uses of the original pointer and the pointer returned by tLambda. We know that they currently are the same pointer, but assuming that could restrict your options later. In tLambdaBoth I'd rather see return tLambda(pthing->getValue(), pthing); so why not the same in the original code?

So we can address both points together by avoiding new, and then never reusing the original object; instead it always uses the pointer that's returned from the future:

Thing tA, tB, tC;

// launch futures
std::vector<std::future<Thing*>> fut1;
fut1.emplace_back(async(launch::async, tLambda, "This is a test...A", &tA));
fut1.emplace_back(async(launch::async, tLambda, "This is a test...B", &tB));
fut1.emplace_back(async(launch::async, tLambda, "This is a test...C", &tC));

// launch second set; using values clearly no longer in flight
std::vector<std::future<Thing*>> fut2;
for (auto& fut : fut1)
{
    auto pthing = fut.get();
    fut2.emplace_back(async(launch::async, tLambda, pthing->getValue(), pthing));
}

// report results
for (auto& fut : fut2)
{
    cout << fut.get()->getValue() << endl;
}

While I definitely like this a lot better, I'm not sure I understand your use case well enough to say whether this addresses it. Perhaps you should digest what I'm saying here, and then clarify your use case if this did not address what you were trying to determine about the validity of your approach.


Improving the performance depends on where exactly the bottleneck is - with a database it's typically either IO or CPU. A simple way to see if IO is the main problem is to load the entire database into memory and then selecting from it. However once you have loaded the database into memory you might just want to consider loading your data on demand when you need to display it rather than pulling it into a DataTable.

Once you have the database in-memory you could also try a Parallel.ForEach to load the data from all tables in parallel. Of course you can try this without loading the data into in-memory. I'm not sure how well this works with a physical file but it's worth a shot.

A few additional remarks:

Nitpick: It's a database and not a data base hence your variable names should read Database and not DataBase.
The general C# naming convention for method parameters and local variables is camelCase - Percentage and ProgCtl both violate this.
Don't abbreviate variable and parameter names needlessly, e.g. ProgCtl could be easily progressController - much more readable.
For more complex string formatting I'd prefer string.Format over concatenating manually:

ProgCtrl.SetMessage(string.Format("Loading Data\nCurrent Table ({0} of {1}): {2} ...",
                                   currentTable, tables.Rows.Count, tablename));

Makes the structure of the resulting string much clearer.
SQLiteConnection, SQLiteDataAdapter and SQLiteCommand are all  IDisposable and should be wrapped into using statements to make sure they get cleaned up properly.
DatabasePath and DatabaseName should be const.
Use Path.Combine to combine paths:

string dbpath = Path.Combine(DataBasePath, DataBaseName + ".sqlite");


Efficient visualization of large number of particles using openGL

Basic optimizations

There are a number of possible optimizations you could apply to your problem. Particle simulation real-time rendering is a well researched topic and I think you will be able to find a lot of material on the subject. In particular, look into game development-related research. Games make heavy use of real-time particles. The GPU Pro series might be a good place to start.

The first basic optimization to unlock would be to port your code to modern, shader-based OpenGL (starting from GL version 3 and above). Note that I use the term port. It will be a major change from the legacy OpenGL used in your example, but it is the only way you can take full advantage of the current graphics hardware on the market.

Start by changing your rendering code to use Vertex Buffers. This by itself will make things more efficient by reducing CPU/GPU traffic and the number of API calls. A full explanation on Vertex Buffers would be beyond the scope of this answer, plus it is a common introductory subject on modern OpenGL, so you can find dozens of tutorials out there.

Once you have your Vertex Buffers and shaders set up, you might consider reviewing the way you are drawing the particles. Rendering a full sphere for each particle is very inefficient. They are far too small to require a large number of vertices, in general. All real-time applications and games "fake" particles by drawing a textured quadrilateral per particle that always faces the viewer/camera. When you add alpha blending to the texture, results look quite convincing, even with the simplest of approaches. You can find some samples at my website.

After you have made these major conversions, remember to look into view-dependent culling. It is likely that for any given view of your scene, some or even most particles will not be visible. It is usually more efficient to spend some time testing for the potentially visible geometry and them culling the non-visible parts than to just submit everything to the GPU at every frame. The simplest form of viewport culling is the frustum culling.

Going further

Once you have looked into the above, it might still not be enough for the throughput you need. It will then be the time to start looking into Instanced Rendering and Transform Feedback. Using Compute Shaders might also help accelerating things if you can perform some of the simulation in the GPU as well as the rendering.

I hope these pointers can give you some perspective and a rough roadmap to follow. To know more about each of the topics, I suggest searching the StackOverflow and GameDev.SE sites, as well as good ol Google.


Use Java LinkedList class

Almost always prefer built-in data structures to hand-rolled. For instance, your insertion routine takes O(n) time while LinkedList::addLast takes O(1) times.

Also, use an ArrayList instead of an array to hold the lists due to problems with generic arrays in Java.

Write a Graph class

A class offers a great opportunity to re-organize your code. It makes it easy to separate initialization and adding edges.

Correctness issues

Validate the input to addEdge. Throw an exception if either to or from is not in the appropriate range.

Style issues

indent and capitalize properly
write fewer comments: only when something need explaining
write shorter comments: use sentence fragments

import java.util.ArrayList;
import java.util.LinkedList;

public class Graph {
    private ArrayList<LinkedList<Integer>> adjacencyList;

    public Graph(int numberNodes) {
        adjacencyList = new ArrayList<LinkedList<Integer>>(numberNodes);
        for (int i = 0; i < numberNodes; i++) {
            adjacencyList.add(new LinkedList<Integer>());
        }
    }

    private boolean isValidNode(int index) {
        return index >= 0 && index < adjacencyList.size();
    }

    public void addEdge(int to, int from) {
        if (!isValidNode(to) || !isValidNode(from)) {
            throw new IndexOutOfBoundsException();
        }

        adjacencyList.get(from).addLast(to);
    }
}

import java.util.Scanner;

public class GraphRunner {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        Graph g = new Graph(5);

        for(int from=0; from < 5; from++) {
            int n=sc.nextInt();
            for(int j=0; j < n; j++) {
                int to=sc.nextInt();
                g.addEdge(to, from);
            }
        }
    }
}


Minimum number of coins problem using dynamic programming - follow up

I advised you that it is called main and not everything, and you did a good job of moving code out of main.  Now main looks a lot closer to what I'd expect to see.

But, we still have functions that are doing too much.  Plus, we've made a bad problem worse.  We've replaced doing everything in the main function with global variables.  And we don't want to do that.

One indication that we have functions that are doing too much is that our functions don't have very great names and there's not a good name to give to them.

For example, void input().  It's not very clear what exactly this function does (from name alone), and we can't really give it a more clear name without it being miles long (and filled with ands... "and" and "or" in function names is generally a code smell).  From the name alone, we'd guess that this function gets input from the user.  But what does it do with that input?  Who knows?  Because this returns void and it doesn't take anything by reference to return either.

So let me repeat the method from earlier more clearly (this you can and should copy-and-paste this exactly and use it):

int getUserInput(const char * prompt) {
    int input;
    printf(prompt);
    scanf("%d", input);
    return input;
}

Do not mistake this.  You're repeatedly getting integer input from the user.  This is a clear indication that you should have a function for doing this.  If you don't have this in your next post, you're doing something very wrong.

The section in which we gather inputs from the user should look basically exactly like this:

int denominationCount = getUserInput("How many different denominations? ");
for (int i = 0; i < denominationCount; ++i) {
    denominations[i] = getUserInput("Enter the next denomination: ");
}
int makingChangeFor = getUserInput("How much are we making change for? ");

And now you've got all the values for which to do the calculation.  You can feed them to the function that does the calculation and get an output from that.  And you don't need the global variables.

Until all of your functions that are accessing the global variables are both taking and returning arguments, you shouldn't be comfortable using the global variables (as a rough guideline).  Global variables are almost always unnecessary.  Global variables are the path to rats nests, madness, and lunacy.


PHP dynamic insert - mysql. Is there a better way than this?

Array based approach

Instead of appending a number to the field, use an array based approach:

<form action="" method="POST">
    Product 1<br
    Product Id <input type="text" name="products[0][id]">

    Product Type <input type="text" name="products[0][type]">

    Product 2

    Product Id <input type="text" name="products[1][id]">

    Product Type <input type="text" name="products[1][type]">
</form>

Now if you were to submit this to PHP and do print_r($_POST['products']);, you would get something like the following:

array(
    0 => array(
        'id' => '...',
        'type' => '...',
    ),
    1 => array(
        'id' => '...',
        'type' => '...',
    )
)

This allows you to do the logic for the insertion once, and then use a loop to do all of the fields.

The (pseudo) code would be like:

$products = (isset($_POST['products']) && is_array($_POST['products'])) ? $_POST['products'] : array();

//Note that I've assumed the id column is an int, and the type column is a string.
//In real schema, I would expect type to also be an int, but I want to illustrate proper escaping.
//(There is more on this in a later section)
$query = "INSERT INTO products (id, type) VALUES (%d, '%s')";

foreach ($products as $product) {
    //Ensure that $product contains a valid entry, and if it does not, store errors somewhere
    if (valid entry) {
        $res = mysql_query(sprintf($query, (int) $product['id'], mysql_real_escape_string($product['type'])));
        if (!$res) {
            //Log an error about the query failing
        }
    }
}

SQL Injection

Put all the validation on the client side you want, but at the end of the day, it's bypassable.  In fact, a user doesn't even have to use a browser, much less use JavaScript.  A user can send your server anything he wants.  After all, at the end of the day, HTTP is a text based protocol.

Also, properly escaping isn't just about security.  It's also about correctness.

$string = "The other day, someone said, "Hello my name is Fred!""; //Syntax error!

Not escaping SQL is the same concept as this.  This isn't a security issue; it's just wrong.  Escaping SQL is the same concept as doing:

$string = "The other day, someone said, \"Hello my name is Fred!\"";

The escaping is necessary so that the SQL server can parse the query correctly in the same way that escaping in PHP is necessary so that the PHP engine can parse the script correctly.

The reason that SQL injection is a security concern is user input.  If you don't properly escape, users can change your code.

It's hard to make a brief PHP-injection example, but hopefully the concept is there.  An attempt at an example:

eval("\$x = 5 + {$_POST['input']};");

That's all good and fine as long as $_POST['input'] === "5"; or some other kind of innocent value.  However, consider if $_POST['input'] === "5; evilFunction()".  Suddenly the eval is:

eval("\$x = 5 + 5; evilFunction();");

This is the broad concept of SQL injection.  (Various articles on the internet will explain it much better than me though :p.)

(eval should very rarely [arguably, never] actually be used -- this is just to illustrate a point)

Anyway, the solution is very simple.  Anything that is going to be a string needs to be run through mysql_real_escape_string before being interpolated into a query.  Likewise, anything that is not a string should be handled as the proper type:

$query = "INSERT INTO tbl (stringField, intField) VALUES ('%s', '%d')";
$qry = sprintf($query,
        mysql_real_escape_string($someString), //make sure the string field is properly escaped
        (int) $someInt //make sure the int field is an int
       );

PDO

I would advise everyone to move away from the old mysql extension.  The mysql_* functions are a very thin wrapper around the C API, and though there is not anything particularly wrong with them, PDO is just better.

In particular, PDO:

Offers a cleaner API
Offers better error handling (the ability to have failed queries throw exceptions is wonderful)
Handles transactions SQL-dialect agnostically (for the most part)
Different RDBMS can be changed out relatively easily (switching from mysql_* to Postresql is extremely painful.  Switching from PDO with MySQL to PDO with Postresql isn't pleasant, but is care is taken to stay as dialect-agnostic as possible, it's reasonably easy)
Prepared statements

Prepared statements deserve their own sublist:

100% safe from SQL injection (if used correctly, of course)
Better performance for batched queries
Various other minor things

Prepared statements work vaguely like:
* Create a parameterized statement
* Let the SQL server handle putting the variables into place

The second point is the important one.  Since the server is putting the paramters into place, it's impossbile for something to be misinterpretted.

An example will be a lot more useful:

//create the connection
$db = new PDO("mysql:host=localhost;dbname=database_name", "username", "password");
//I like for failed queries to throw exceptions.
//If you're not comfortable with exception handling, you would want to omit the following line.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$products = (isset($_POST['products']) && is_array($_POST['products'])) ? $_POST['products'] : array();

//Create the prepared statement -- in a way this is like having SQL create a temporary function
$insertStmt = $db->prepare("INSERT INTO products (id, type) VALUES (:id, :type)");

foreach ($products as $product) {
    //Ensure that $product contains a valid entry, and if it does not, store errors somewhere
    if (valid entry) {
        //Execute the statement -- this is similar to calling the temporary function
        //Note that a new array is created in case $product contains an extra key.  For example,
        //if there were a $product['extra'] field, then using $insertStmt->execute($product) would
        //cause an error since there would be an extra paramater that MySQL would not know what
        //to do with.
        $insertStmt->execute(array(
            'id' => $product['id'],
            'type' => $product['type']
        ));
    }
}

Don't assume user input is there

Never assume anything from the client side.  What I mean in this particular instance is to never assume a key exists in $_POST, $_GET, $_COOKIE, etcetra.

Just because isset($_POST['productid2']) is true does not mean that the type2 key for $_POST is set.  This goes back to the note earlier about people being able to send your client whatever they want.

I could make your script issue all kinds of index undefined and mysql_query() errors if I wanted by making a form like the following:

<form action="http://yoursite.tld/somepage.php" method="POST">
    <input type="text" name="productid2" value="let there be errors!">
    <input type="submit">
</form>

My approach is to be paranoid on user provided values.  Something intersting to note is that $_GET/$_POST/$_COOKIE/$_REQUEST values will always be either a string or an array (unless somewhere in your script you have something like: $_POST['int'] = 5;).  This means that if you're not expecting an array, you should make sure you're getting a string.

$type = (isset($_POST['type']) && is_string($_POST['type'])) ? $_POST['type'] : null;
if ($type === null) {
    echo 'Please provide a type';
} else {
    //do some other validations on $type
}

If you want to be a bit more flexible, you could use is_scalar instead of is_string.

The broad idea is that you never want to access an array by key $k unless you are certain that array_key_exists($k, $arr) is true.  When $arr is something user provided, you can never be certain of that unless you explicitly check it.


Python factory class with dynamic imports

If a factory pattern is indeed called for - much of the time it is not - there is an easier way that needs neither importlib nor explicit registration calls.
If you follow something like this layout:
mypackage/
mypackage/__init__.py
mypackage/tracker_factory.py
mypackage/trackers/__init__.py
mypackage/trackers/type_a.py
mypackage/trackers/type_b.py
...

then in mypackage/trackers/__init__.py:
from .type_a import TypeA
from .type_b import TypeB
...

then your factory can import mypackage.trackers as all_trackers, do a dir(all_trackers), and every subtype that you care about will be listed. Instead of a dynamic import plus runtime registration calls, this uses traditional imports and will look up the individual type using getattr() on the module object. The class and module names are automatically able to differ though it would not be a good idea to do so. The subtype modules would still be able to import, as you put it, "unusual dependencies".
If you are concerned about the performance impact of initializing modules that you may not end up using, I think this concern is unwarranted - though of course you haven't shown any code as evidence one way or the other. A properly-written Python module should be fast and safe to load, and should only incur execution expenses when something is called.


Since the and operation is associative, one could write:

(and (and (symbol? a) (symbol? b)) (eq? a b))

as:

(and (symbol? a) (symbol? b) (eq? a b))

Similarly:

(and (and (and (not (null? a))
               (list? a))
          (and (not (null? b))
               (list? b)))
     (and (equal? (car a) (car b))
          (equal? (cdr a) (cdr b))))

is equivalent to:

(and (not (null? a))
     (not (null? b))
     (list? a)
     (list? b)
     (equal? (car a) (car b))
     (equal? (cdr a) (cdr b)))

One could extend the definition of equal? to work with both lists and pairs simply by changing the test list? to pair?.  This also obviates the need to test for non-nullity within the same and clause.

Using the above guidelines, one may write a shorter definition thus:

(define (equal? a b)
  (or (and (symbol? a) (symbol? b) (eq? a b))
      (and (null? a) (null? b))
      (and (pair? a)
           (pair? b)
           (equal? (car a) (car b))
           (equal? (cdr a) (cdr b)))))

Conceptually, one may think of null, symbol, and pair as types.  To test for equality of two objects, one needs to check that their types are the same and then test for equality in that type.

Thus, to test for equality, if we see that objects are symbols, test for eq?; if we see that objects are null, no further test is necessary so they're equal; if we see that objects are pairs, test for equality of car and cdr.

This insight allows one to extend the definition of equal? to other types (hash tables, vectors, etc.) if one should choose to do so in the future.


I don't think there's much to review here! Since your options are hard coded, there's not a lot of wiggle room. There are a couple things you can add if you're feeling up to it.

Docstrings: These allow documentation to see what your code is doing, marked with """

Constants: Variables that are constants should be uppercase LIKE_THIS


Write a function that adds two numbers stored in a linked list and returns the sum

Strictly speaking, the code does not solve the problem. As an interviewer I'd expect a clearly defined

    List add(List l1, List l2)

method.

At the very least, rename Run to add, and do not CreateNumbers in it, but pass them as parameters.
Since it is guaranteed that every node contains a digit, the sum may never exceed 19. This means, among other things, that there is no need for decimal. Everything can be done with primitive types, e.g.

    alpha = sum > 10;
    sum -= alpha * 10;

As a side note, the entity you call alpha is traditionally called carry.
The do {} while() approach seems to create more problems than it solves. An immediate manifestation is duplication of n1 != null tests. Consider

    while (n1 != null && n2 != null) {
        // addition logic here
        n1 = n1.Next;
        n2 = n2.Next;
    }

and promote the carry along the remainder of the longer list in a separate loop.
Consider creating a dummy head for a resulting list. It is a standard trick to avoid a special case of prev == null, e.g.

    Figure dummy = new Figure;
    Figure tail = dummy;

    while (....) {
        ....
        tail.next = new Figure(sum);
        tail = tail.next;
    }
    ....
    return dummy.next;


Efficiency

In response to

// do I need to create this everytime for each call?
HttpClient httpclient = HttpClientBuilder.create().build();

Then no. The construction doesn't take any parameter, so it's independent from the loop and you can initialize only once before the loop. And although the javadoc for those methods is empty, by the looks of .create().build() I'd say that it's not a cheap instantiation.

Simplification

You can save some lines by using IOUtils to read the content from the response, as explained in this answer.

Readability

Your function is a bit too long. You can probably divide it into smaller functions. I would start extracting the try/catch block into a readResponse() method.

Miscellaneous

This

HttpStatus.OK.value()

is from Spring. There's nothing wrong with it, but since you're using an Apache library, why don't you use HttpStatus from the Apache library?


Safely setting object properties with dot notation strings in JavaScript

obj = typeof obj === 'object' ? obj : {};

When obj argument points to something other than object you will create one. Like in set("foo", "a.b.c", "Yay!"). I guess you want to return it at function end or it will be lost.

Other notes:

/^\+?(0|[1-9]\d*)$/ allows + in integer key inputs
you may use isNaN(+nextKey) instead of regular expression, but beware float or signed numbers
finalStep is a bit misleading name. You may use key = keys[keys.length - 1] instead.


Iterative "counting change" implementation in mit-scheme

In SICP the authors note:

  Count-change generates a tree-recursive process with redundancies similar to those in our first implementation of fib. (It will take quite a while for that 292 to be computed.)
  On the other hand, it is not obvious how to design a better algorithm for computing the result, and we leave this problem as a challenge.

And while your solution is more efficient than the solution they provide it still has a lot of redundancies. If you're will to sacrifice some readability you could use a bottom-up algorithm to eliminate these redundancies.

For example:

(define (add-if predicate x addition)
  (if predicate (+ x addition) x))

(define (inc-if predicate x)
  (add-if predicate x 1))

(define (zero-if predicate x)
  (if predicate 0 x))

(define (count-change amount)
  (define (cc-iter value ways-to-change new-ways nickel-ways dime-ways quarter-ways nickels dimes quarters)
    (define (current-coins num-nickels num-dimes num-quarters)
      (and (= nickels num-nickels)
           (= dimes num-dimes)
           (= quarters num-quarters)))
    (if (> value amount)
        ways-to-change
        (cc-iter (+ value 5)
                 (+ ways-to-change new-ways)
                 (+ new-ways (if (= nickels quarters) dime-ways nickel-ways))
                 (add-if (current-coins 0 1 1) nickel-ways quarter-ways)
                 (add-if (current-coins 0 1 0) dime-ways quarter-ways)
                 (inc-if (current-coins 0 1 0) quarter-ways)
                 (zero-if (or (= nickels 1) (= dimes 2)) 1)
                 (zero-if (= dimes 2) (inc-if (= nickels 1) dimes))
                 (zero-if (current-coins 0 2 1) (inc-if (= dimes 2) quarters)))))
  (cc-iter 0 0 1 1 0 1 0 0 0))


React app that receives data via an AJAX requests, display the data and makes it searchable

Looks pretty idomatic :) the one major thing you might want to do is make use of propTypes to more explicitly define your Component API's. PropTypes help set expections for what values should/can be.

For instance in SearchBar your doSearch() method looks like

this.props.change(e.target.value.toLowerCase());

There is an implicit assumption that onChange is never going to be null, and that it's a function. You can codify that (and guard against dumb mistakes) by adding

propTypes: {
  onChange: React.PropTypes.func.isRequired
}

alternatively you can leave off: isRequired and provide a default value for onChange (perhaps a noop function).

In PollList

this line is odd (you also do this in _onChange of View):

this.props.data.map(function(value) {
   var head = value.uuid;
   var body = value.question_text;
   arr.push(
<Panel header={head} key={head}>{body}</Panel>
);
});

.map() already returns a new array so there is no need to push into the arr either just return the child elements or use a forEach()


BookController.php

I don't see anything to change, the only thing which i could do different is the return line from

 return $this->render('MatiitBookBundle:Book:new.html.twig', ['form' => $form->createView()]);

i would write something like this to make it more clear

return $this->render(
    'MatiitBookBundle:Book:new.html.twig',
    [
        'form' => $form -> createView()
    ]
);

So if one day you need to add another line you will just add a , and the code will still look good.

new.html.twig

Why var $file? Why this $? It remember me something which is related to jQuery... Do you really need this? I would just do var file or choose a more specific name. (no idea right now, file could be ok but what is book_file? a input type="file"?)

Book.php

You use documentation only to specify the type of the fields? You could start with add the documentation of the fields and document all methods (or at least public/protected methods)

I'm wrong or here the indentation is a bit messed up? Could be just a copy/paste bug, anyway from protected $category; it wil look like you start write an inner class. (same for the end of the file)

Fix it if it's in your code.

What is length? I'm not English so maybe i'm wrong but i don't think length is a great name for a Book class (without documentation it's more hard to understand what is it).

It's the book pages? What about totalPages? It's the length (size) of the file in bytes? What about fileSize?

BookType.php

class BookType extends AbstractType

Why not call your class AbstractType as AbstractBookType?

AbstractType could sound as something which is related to variables type, not your class.

I know you use namespaces but i think it's important to make the name of something very clear.

Here you could add documentation too.

BookCover.php

It looks so similar to Book.php

Some methods are similar, maybe Book should have an instance of BookCover inside instead of recreate the methods from zero?

I need more info about it.

protected function getUploadRootDir()
{
   // the absolute directory path where uploaded
   // documents should be saved
   return __DIR__.'/../../../../../web/'.$this->getUploadDir();
}

I'm not a PHP expert, but what if one day you change the location? You should remember to edit this method inside BookCover and inside Book too! Can't you make it in a static field for the two classes?

And you should maintain the /../../../../../ to point in the new location!

Anyway my review is more about style than other.


Binary tree max sum level - better design?

My initial criticism is that your method doesn't have javadoc comments that state clearly and unambiguously what the method is supposed to do.

Why am I saying that?

Well, mainly because your Question has exactly the same problem!  You say:

  I have written some code for finding a level in a binary tree, having a maximum number of elements.

This is bad description of what you are (apparently) trying to do:

The word "level" usually refers to the distance of a node from (say) the root of a tree.  But you apparently mean the "height" of the entire tree.
The phrase "having a maximum number of elements" is unclear.  What are you talking about?  How does this affect the problem?  (I don't see a maximum number of elements parameter ... or any reference to this in your code.)

So why does this matter?

Because I (the reader) should not have to read through your code to try to figure out the problem you are trying to solve.  Especially if your implementation is non-obvious ... which it is ... and possibly contains mistakes that might lead me to think it is solving a different problem than you are actually trying to solve.


Better way to create directories using File

Well, for the purpose of codereview:

There is a mkdirs() methods instead of the mkdir() method
You can use the new File(String, String) constructor to avoid taking care of slashes
If you have Java7, you can (and probably should) use Path. Especially, because there is a way to construct Paths with unlimited arguments, not only 2 as for File:

Path dir = Paths.get(rootPath, "media", userBean.getUsername(), arg1);
Files.createDirectories(dir);

You should check the return codes and errors. Could be helpful.


Optimizing the function in R by replacing for loop

I have tried this, but I don't know, how much (and even if) faster it is. Anyway, you used a lot of redundant code (creating variables M, h_unbiased, delta_t etc.).

filter2 <- function(x, m, delt) {
  series <- x
  tau_crit <- 3 # critical period (hours)
  theta_crit <-  2*pi*delt/tau_crit # critical frequency
  # get the lanczos coefficients
  h <- sapply(-m:m, FUN=function(x)ifelse(x == 0,theta_crit*delta_t/pi,
    (sin(x*theta_crit*delt)/(pi*x)) * (sin(x*pi/m)/(x*pi/m))))
  # need to adjust the weights so that they add up to 1
  h <- h/sum(h)
  # step through each time for which we'd like to create a filtered value
  y2 <- sapply((1+m):(length(series)-m), function(t){
    sum(unlist(sapply(-m:m, FUN=function(x)(series[t+x]*h[m+x+1]))))
  })
  # return
  return(y2)
}


What docblock definition on this function will satisfy PHPLint?

Ok, did not noticed that, then:

@param int[int][string] $items

foreach($items as $k => $e){...}

here $k is int, $e is int[string].

In the general case, if

@param T[I1][I2][I3] $items

then

foreach($items as $k => $e){...}

yields $k of type I1 and $e of type T[I2][I3].


I've tried cleaning it up a bit here, removed instances of setting a variable once and using it directly below where it was set (yes, improves readability, but still).

require_once 'Bcrypt.php';

class Mysql {
    private $conn;
    private $host    = 'host';
    private $dbName  = 'dbname';
    private $charset = 'UTF-8';
    private $checkUserQuery = 'SELECT * FROM Conference WHERE Username = :un';

    function __construct() {
        $this->conn =  new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset)
                       or die('There was a problem connecting to the database.');
    }

    function verifyUsernameAndPass($un, $pwd) {
        $stmt = $this->conn->prepare($this->checkUserQuery);

        $stmt->bindParam(':un', $un);
        #$stmt->bindParam(':pwd', $pwd);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $stmt->close(); # Moved up, so closes before we return/exit function

        # You're setting $hash here, and using it directly below.
        # See new code below
        //$hash = $row[0]['Password'];
        //$is_correct = Bcrypt::check($pwd, $hash);

        //if ($is_correct) {
        if( Bcrypt::check($pwd, $row[0]['Password']) ){
            # User exist

            # You're setting $firstName once, and using it directly below it.
            # See new code below
            //$firstName = $row[0]['First Name'];
            //$_SESSION['FirstName'] = $firstName;

            $_SESSION['FirstName'] = $row[0]['First Name'];

            return true;
        } else {
            # User does not exist
            return false;
        }
    }
}

And here's the same code, without my comments:

require_once 'Bcrypt.php';

class Mysql {
    private $conn;
    private $host    = 'host';
    private $dbName  = 'dbname';
    private $charset = 'UTF-8';
    private $checkUserQuery = 'SELECT * FROM Conference WHERE Username = :un';

    function __construct() {
        $this->conn =  new PDO('mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset)
                       or die('There was a problem connecting to the database.');
    }

    function verifyUsernameAndPass($un, $pwd) {
        $stmt = $this->conn->prepare($this->$checkUserQuery);

        $stmt->bindParam(':un', $un);
        $stmt->execute();
        $row = $stmt->fetchAll();
        $stmt->close();

        if( Bcrypt::check($pwd, $row[0]['Password']) ){ # User exists
            $_SESSION['FirstName'] = $row[0]['First Name'];
            return true;
        } else { # User does not exist
            return false;
        }
    }
}


Finding the closest string match for each string in two dataframe columns

Comparing 30,000 strings against 30,000 other strings is 900 million comparisons.  It's going to take a while.

Run the Python profiler on a small data set to see where it is spending the most time.  So you can focus your efforts.

difflib

The documentation for SequenceMatcher says it caches information about the second sequence.  So that to compare one string against a bunch of other strings, use .set_seq2() to set the one string, and the use .set_seq() to check it against each of the other strings.

It also says that calculating ratio() is expensive to compute so you might want to use 'quick_ratio()orreal_quick_ratio()` first.

def wuzzyfuzzy(df1, df2):
    myList = []
    total = len(df1)

    s = SequenceMatcher(isjunk=None, autojunk=False)

    for idx1, df1_str in enumerate(df1.col1):
        s.set_seq2(df1_str)

        my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%')
        sys.stdout.write('\r' + str(my_str))
        sys.stdout.flush()

        best_str2 = ''
        best_ratio = 0

        for idx2, df2_str in enumerate(df2.col1):
            s.set_seq2(df2_str)

            if s.real_quick_ratio() > best_ratio and s.quick_ratio() > best_ratio:
                r = s.ratio()

                if r > best_ratio:
                    best_match = df2_str
                    best_ratio = r

        myList.append([df1_str, best_match, best_ratio])

    return myList

You could also consider difflib.get_close_matches(string, possibilities, n, cutoff).  It compares string against a list possibilities and returns a list of upto n that match better than cutoff.

def wuzzyfuzzy(df1, df2):
    myList = []

    possibilities = list(df2.col1)

    s = SequenceMatcher(isjunk=None, autojunk=False)

    for idx1, df1_str in enumerate(df1.col1):
        my_str = ('Progress : ' + str(round((idx1/total)*100,3))+'%')
        sys.stdout.write('\r' + str(my_str))
        sys.stdout.flush()

        # get 1 best match that has a ratio of at least 0.7
        best_match = get_close_matches(df1_str1, possibilities, 1, 0.7)

        s.set_seq(df1_str, best_match)
        myList.append([df1_str, best_match, s.ratio()])

        return myList


Your algorithm is correct and will be very efficient. Note that it assumes that the array of float values is sorted ascendingly. To make sure of that, you could explicitely sort the array before entering the while loop, or document that the method must take a pre-sorted array.

The comments I have are concerning the presentation of the code itself:

Consider adding white-spaces before and after each parentheses and curly braces. For example

while(currentChild<lastChild){

could be read easier with

while (currentChild < lastChild) {

where extra spaces have been added.
You have added a lot of vertical spaces. Adding a line break with an empty line can indeed help readability but having 2 empty lines is too much: this is what you have after your while loop and between the two if statements. Consider having only a single empty line where you think it adds to clarity.
Be consistent with your usage of white-spaces. Statements like

startingPoint=currentChild ;

are a bit weird. There is a space before the semi-colon and no spaces around the = operator.

An IDE can usually reformat your code automatically. For example, taking directly your code into Eclipse and reformatting it by selecting it and hitting Ctrl+Shift+F let me to

static int getGroups(float[] children) {

    int lastChild = children.length;
    int currentChild = 1;
    int startingPoint = 0;
    int groups = 0;

    while (currentChild < lastChild) {

        if (children[currentChild] - children[startingPoint] > 1) {
            startingPoint = currentChild;
            groups++;
        }

        if (currentChild == lastChild - 1) {
            groups++;
        }
        currentChild++;
    }

    return groups;
}

Also, I noticed that you used wildcard import statement:

import java.io.*;
import java.util.*;

This is generally not a good practice. You want to import the specific classes with which you are interacting. In this case, it is actually not a lot, you just one import statement:

import java.util.Scanner;

There is no need for any class under java.io.


You may be aware that there are simpler answers to this problem, such as:

function toRoman(n) {
    var r = '',
        decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
        roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
    for (var i = 0; i < decimals.length; i++) {
        while (n >= decimals[i]) {
            r += roman[i];
            n -= decimals[i];
        }
    }
    return r;
}

Bearing this in mind it might be useful to explain what exactly you are trying to achieve with your refactoring? E.g. is it to practice using more complicated language patterns?


Simple c++ triple class to mimic pair for use with uniform initialization

While the code you have appears to work as you expect, your stated reason for using it doesn't make sense to me, because one could use std::tuple with uniform initialization as well.

Use std::tuple

With only a relatively minor change to your print routine, the main you have could be used just as easily with std::tuple:

void print(const std::vector<std::tuple<int, const std::string, const std::string>> &vals) {
   for(auto &tup : vals) {
        std::cout << "First:  " << std::get<0>(tup) << std::endl
                  << "Second: " << std::get<1>(tup) << std::endl
                  << "Third:  " << std::get<2>(tup) << std::endl;
        std::cout << "------------------" << std::endl;
   }
}

Answer 1

The reason those typedefs are there is that they're required by the standard.  That way, it's easy to be able to create other variables of the same type as, say, the second argument, without having to jump through a lot of hoops.  In other words, it's a convenience for the user of the template rather than for the author of the template.

Answer 2

I wouldn't bother with static asserts.  If you did want to restrict the kinds of things that can be stored, it's probably better to use std::enable_if.

Answer 3

I'm not sure, but I suspect that the other types U1 and U2 are required for convertable but non-identical classes that might be used to construct the triple (as you've surmised).

Answer 4

Only one alarm -- why aren't you using std::tuple?  :)

Try it live.


The general push/pop logic of the stack looks fine. The memory management however is somewhat flawed:

Missing Destructor

From the perspective of the unique ptr, the stack doesn't contain Nodes, but uninitialized memory (effectively a char array). So at destruction of the stack object, it won't call the destructor of the individual nodes, which in turn won't call the destructor of value.

In order to correct that, one could write a destructor for stack that traverses the nodes and manually calls the destructor on them.

Assignment into uninitialized variables

node->value = std::forward<U>(data);

Upon construction, no actual nodes are created, but only properly aligned memory is reserved, on which you later call the assignment operator. I believe (although I'm not sure) this is OK if T is a POD, but if not, then (move) assigning values to them is definitively not allowed, because custom move assignment operators usually assume that this points to a valid, initialized object.

So in general, I see two possibilities:

You default construct all nodes upon construction of the stack and destruct them when stack is destructed, in which case std::aligned_storage is unnecessary. One can just use an array of nodes and pass it to the unique_ptr. In this case you also don't need a destructor for stack. Obviously that only works with default constructable T's and makes only sense, if T doesn't hold any resources after it has been moved from.
You actually create and delete objects upon calls to push and pop, in which case you have to use placement new (new(&node->value)T(std::forward<U>(data));) and manually call the destructor node->value.~T() (not delete &node->value)

Padding
I just want to point out that aside from the false sharing between head and free_nodes, which is avoided via padding, any thread calling push or pop will access both variables anyway and afterwards you still have false sharing between the actual nodes.

Performance
This code contains a lot of micro optimizations, which might or might not be worth the effort if the code gets reused in different contexts (its definitively  not worth for handling a worker pool). However, I'd suggest, to write at least few small benchmarks to ensure that those optimizations are in fact improving and not hurting performance.

Also I want to repeat my warning from the comments that for some reason, VS2013 (and also 2015RT) seems to be unable to implement std::atomic<head_t> in a lock-free manner, in which case the whole structure is probably much slower than a normal stack with a mutex.


Big issue: you can create your own replace function as something like a recursive array iterator. It should be quite easy, but there might be some performance drawbacks if used on long strings, but the code above is not the case. Also you probably better off drop the regexp, unless search() function is allowed.
As of css there are reset stylesheets/boilerplates to start with and there are also preprocessors like sass or less, to help you create a more structured stylesheet.
Cross browser compatibility is always depending on your target audience, but generally speaking it's enough if you support the last 2 version of all major browsers and try to keep it at least "minimally functional" for the rest if possible.


SQL Sub-query with running total optimization

Assuming that #PurchaseOrderProducts is a realistic depiction of your real table but with less data (and that your real table is also a heap), then I get this plan.

This is a pretty reasonable plan, where I wouldn't necessarily expect it to be that bad.

There are a few things we could do to make this better, including:

Batch-mode for rowstore is enabled (via hacks) in SQL Server 2016 if you include a CCI in your query, even if it isn't used. This can likely make the window function better. This gets me a batch-mode operator for everything but the table scan, and cleans up a lot of the aggregation.
Creating an appropriate index that your window function can use will help as well by removing the sort (the index maintains a sorted order). A clustered index on the Id column moves all of the cost onto the index scan. A non-clustered index on Id that INCLUDEs Quantity and Product (order didn't matter in my testing) does the same. You'll have to INCLUDE any columns you want in the output, however - otherwise it will just table scan, or if you force it to use the index it'll key lookup. That won't be great for performance.

If we look at all of these side-by-side, we notice that the non-clustered without an INCLUDE is the worst by far, and the rest all look about the same.

You may notice that the batch-mode query is also using the non-clustered index; getting all of the plans side-by-side without indices is a pain. If you use the batch-mode hack without any indices then it will still have to sort the data, but it can do that in batch mode which will provide a nice performance bump. This is also good if you rely on the table being a heap elsewhere (e.g. parallel inserts, minimal logging, etc).

You may also notice that the plans using the clustered index vs non-clustered index have no apparent difference (besides the index they use). This is because all of the columns in the table are selected in both queries, and all indices include all columns. You can get substantial performance and memory savings if you only need a subset of columns and have a good non-clustered index; this might be helpful for your real data if the temp table isn't representative.

Query samples:

Batch mode w/ rowstore table

DROP TABLE IF EXISTS #FakeCciForRowstoreBatchMode;
CREATE TABLE #FakeCciForRowstoreBatchMode
(
  __zzDontUseMe bit NULL,
  INDEX CCI CLUSTERED COLUMNSTORE
);

DROP TABLE IF EXISTS #PurchaseOrderProducts;
CREATE TABLE #PurchaseOrderProducts
(
  Id       int,
  Product  varchar(10),
  Quantity int
);

INSERT INTO #PurchaseOrderProducts
VALUES
( 1, 'Item A', 5 ),
( 2, 'Item B', 1 ),
( 3, 'Item C', 8 ),
( 4, 'Item D', 2 ),
( 5, 'Item E', 1 );

SELECT P.Id,
       P.Product,
       P.RunningQty,
       P.Quantity
  FROM ( SELECT Id,
                Product,
                Quantity,
                SUM( Quantity ) OVER ( ORDER BY Id ) RunningQty
           FROM #PurchaseOrderProducts
             LEFT OUTER JOIN #FakeCciForRowstoreBatchMode
               ON 1 = 0 ) P
  WHERE P.RunningQty - P.Quantity < 12;

Indices I created for #2 (plans generated using INDEX hints)

CREATE CLUSTERED INDEX whatever ON #PurchaseOrderProducts( Id ASC )
CREATE NONCLUSTERED INDEX whatever2 ON #PurchaseOrderProducts( Id ASC ) INCLUDE( Quantity, Product )
CREATE NONCLUSTERED INDEX whatever3 ON #PurchaseOrderProducts( Id ASC ) INCLUDE( Product, Quantity )
CREATE NONCLUSTERED INDEX whatever4 ON #PurchaseOrderProducts( Id ASC )


Multiple criterias in a VLOOKUP in Excel VBA

Here's a different version, though I won't claim that it is significantly better. The code seemed to work just fine and was mostly easy to understand (see my comment on the original question). My only big suggestion would be to add some comments to better describe what you are doing and how this works.

For a brief description of my changes, see the comments in the code. I can elaborate more if necessary.

Public Function VLOOKUPMC(ByVal return_col_num As Long, _
    ByRef table_array_1 As Range, ByVal lookup_value_1 As Variant, _
    ByRef search_column_2 As Long, ByVal lookup_value_2 As Variant) As Variant
    'Changed table_array_2 to search_column_2 because that's all that was used in the code below.
    Dim rCell1 As Range
    VLOOKUPMC = CVErr(xlErrNA)
    'Left the For loop as-is, but maybe you want it to look only in the first column, like the normal VLOOKUP would?
    For Each rCell1 In table_array_1
        'Modified logic to all fit on one line/remove nesting.
        'This organization may not be preferred, but it's one way to clean up the so-called 'mess'.
        VLOOKUPMC = _
            IIf(rCell1.Value = lookup_value_1 And _
            rCell1.Offset(0, search_column_2 - rCell1.Column) = lookup_value_2, _
            rCell1.Offset(0, return_col_num - rCell1.Column), _
            VLOOKUPMC)
        If VarType(VLOOKUPMC) <> vbError Then Exit Function
    Next rCell1
End Function


A nice way to warm your cup of tea

  Are there any problems with implementing a reusable thread this way?

Yes. Let's have a look at a slightly different main:

int main()
{
    Reusable_Thread thread;

    std::this_thread::sleep_for(std::chrono::seconds(10));

    return 0;
}

This should just wait for 10 seconds and then exit, right?

$ g++ reusablethread.cc -std=c++11 -pthread -o demo
$ /usr/bin/time ./demo
10.00user 0.00system 0:10.00elapsed 99%CPU (0avgtext+0avgdata 3148maxresident)k
0inputs+0outputs (0major+129minor)pagefaults 0swaps

Nope. It actually runs full throttle. This is due to your choice of

void thread_worker()
{
    while (!m_thread_quit)
    {
        if (!m_thread_pause)
        {
            /* ... */
        }
    }
}

This isn't the fault of std::atomic<>, but your design. If we don't have something to do, we shouldn't check immediately afterwards. Instead, we should wait. More on that later.

howdoiturnthison

Your class is currently missing features to toggle m_thread_pause, which makes it hard to reason about other behaviour. I guess you're just missing m_thread_pause = false in set_work, e.g.

bool set_work(const std::function<void()>& work_func)
{
    if (get_readiness())
    {
        m_work_func = work_func;
        m_thread_pause = false;     // here, but wrong, see below
        return true;
    }
    else
    {
        return false;
    }
}

Furthermore, the name get_readiness is misleading. What is ready? The internal thread? Is the work slot free? is_paused is much better.

Race condition m_work_func and m_thread_pause

Assume we have our Reusable_Thread rthread and it's currently paused. We have access on our rthread from two threads A and B. Both call set_work. What happens?

void foo(){ puts("foo"); }
void bar(){ puts("bar"); }

void thread_Alice(Reusable_Thread & rthread) {
   rthread.set_work(foo);
}

void thread_Bob(Reusable_Thread & rthread) {
   rthread.set_work(bar);
}

int main(){
    Reusable_Thread rthread;
    std::thread A(thread_Alice, std::ref(rthread));
    std::thread B(thread_Alice, std::ref(rthread));
    A.join();
    B.join();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}

It's certainly possible that the result is foo. It's also possible that the result is bar. But it's also possible that it's neither and your program crashes:

We create the std::thread in rthread, we call it R
We create the std::threads A and B. Neither run yet.
A gets scheduled. It calls set_work and:

checks m_thread_pause (get_readiness())
sets the worker to foo
yields due to scheduling

B gets scheduled. It calls set_work and

checks m_thread_pause (get_readiness(), still true)
yields

A gets scheduled. It resumes the execution and

sets m_thread_pause to false
returns

A's thread of execution has ended.
R gets scheduled. It

checks m_thread_quit (is false)
checks m_thread_pause (is false due to A)
starts reading the std::function<> m_work_fun.
yields while reading

B gets scheduled. It finishes its call to set_work:

sets the worker to bar, although R currently reads from it
yields

R gets scheduled. It finishes reading m_work_fun and ends up with a corrupt std::function<...> and uses operator(). Your program crashes.
Even if your program didn't crash, after R sets m_thread_pause to true, B gets scheduled and finishes set_work, thus setting m_thread_pause to false and the corrupt function gets called again.

So depending on where the threads get interrupted, you end up with either:

bar
foo
bar
bar
foo
foo
foo
bar
bar
foo
*crash*

So, how does one get rid of this? Usually, you would use std::atomic::exchange or std::atomic::compare_exchange on m_thread_pause:

bool set_work(const std::function<void()>& work_func)
{
    if (m_thread_pause.exchange(false)) // old value was true
    {
        m_work_func = work_func;
        return true;
    }
    else
    {
        return false;
    }
}

But that doesn't work either, because R could start using m_work_func before it's actually set. The underlying problem here is that m_work_func and m_thread_pause are intertwined.

Third wheel to the rescue

We can decouple this by using a third atomic<bool>, that checks whether the function can be set safely:

bool set_work(const std::function<void()>& work_func)
{
    if (!m_function_ready && m_thread_pause.exchange(false))
    {
        m_work_func = work_func;
        m_function_ready = true;
        return true;
    }
    ...
}

Remember, only one thread will see m_thread_pause as true, due to the atomic exchange, so we're save from the previous A/B race.

void thread_worker()
{
    while (!m_thread_quit)
    {
        if (!m_thread_pause && m_function_ready)
        {
            m_work_func();
            m_thread_pause = true;
            m_function_ready = false;
        }
    }
}

Here, both the m_thread_pause and m_function_ready are checked, and the checks make sure that our function is actually set.

The memory ordering std::memory_order_seq_cst could be slightly relaxed (not to be confused with memory_order_relaxed!), but it's not trivial to get this right.

However, remember the problem in the first section of this review? You're still using active polling. A small sleep can help here:

void thread_worker()
{
    while (!m_thread_quit)
    {
        if (!m_thread_pause && m_function_ready)
        {
            m_work_func();
            m_thread_pause = true;
            m_function_ready = false;
        } else {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }
    }
}

Note that still uses more CPU power than it has to. Which brings us to condition variables.

Wait until notified

Condition variables provide a way to get notified instead of actively checking conditions. They have to be used with a mutex, so they have a  overhead compared to atomic operations. Still, they have their use.

In this case, you would add a std::mutex and a std::condition_variable to your class:

private:
    std::mutex m_mtx;
    std::condition_variable m_cv;

In set_work, you notify all thread that are currently waiting:

bool set_work(const std::function<void()>& work_func)
{
    if (!m_function_ready && m_thread_pause.exchange(false))
    {
        m_work_func = work_func;
        m_function_ready = true;

        m_cv.notify_all();       // <- notify all waiting threads

        return true;
    }
    ...
}

And worker_thread, you wait if m_thread_pause is false:

void thread_worker()
{
    std::unique_lock<std::mutex> lock(m_mtx);  // <- lock the mutex

    while (!m_thread_quit)
    {
        if (!m_thread_pause && m_function_ready)
        {
            m_work_func();
            m_thread_pause = true;
            m_function_ready = false;
        } else {
            m_cv.wait(lock);  // <- wait
        }
    }
}

Note that the std::unique_lock is placed outside the while loop to keep the number of lock aquires/releases to a minimum.

However, we have to make sure that the thread wakes up when we want to stop it, so we have to change the destructor slightly:

    ~Reusable_Thread()
    {
        m_thread_quit = true;
        m_cv.notify_all();
        m_thread.join();
    }

TL;DR

Make sure that you don't introduce race conditions and avoid while(true){if(false){ … }}. Use proper names for methods and check the behavior on non-trivial examples.


Simple Async Google Maps initializer with AngularJS

I like it,

you could clean up the commented out code and possibly replace

    $window.googleMapsInitialized = function () {
        mapsDefer.resolve();
    };

with

    $window.googleMapsInitialized = mapsDefer.resolve;

Personally, I would re-arrange the code a tiny bit, keep the URL completely on top,
keep asyncLoad and the call closer together. Keep the declaration of mapsDefer and the resolving function closer.

// Google async initializer needs global function, so we use $window
angular.module('GoogleMapsInitializer')
.factory('Initializer', function($window, $q){

    //Google's url for async maps initialization accepting callback function
    var asyncUrl = 'https://maps.googleapis.com/maps/api/js?callback=',
        mapsDefer = $q.defer();

    //Callback function - resolving promise after maps successfully loaded
    $window.googleMapsInitialized = mapsDefer.resolve; // removed ()

    //Async loader
    var asyncLoad = function(asyncUrl, callbackName) {
      var script = document.createElement('script');
      //script.type = 'text/javascript';
      script.src = asyncUrl + callbackName;
      document.body.appendChild(script);
    };
    //Start loading google maps
    asyncLoad(asyncUrl, 'googleMapsInitialized');

    //Usage: Initializer.mapsInitialized.then(callback)
    return {
        mapsInitialized : mapsDefer.promise
    };
})


Parallel foreach with configurable level of concurrency

I've made use of a CountdownEvent signal to avoid the use of the remaining integer and avoid the busy waiting involved in polling it with the unreliable AutoResetEvent onComplete:

public static void PerformActionsInParallel<T>(IEnumerable<T> elements, Action<T> action)
{
    int threads = MaxConcurrent ?? DefaultMaxConcurrentRequests;
    // Ensure elements is only enumerated once.
    elements = elements as T[] ?? elements.ToArray();
    // Semaphore limiting the number of parallel requests
    Semaphore limit = new Semaphore(MAX_CONCURRENT, MAX_CONCURRENT);
    // Count of the number of remaining threads to be completed
    CountdownEvent remaining = new CountdownEvent(elements.Count());

    foreach (T element in elements)
    {
        limit.WaitOne();
        new Thread(() =>
        {
            try
            {
                action(element);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error performing concurrent action: " + ex);
            }
            finally
            {
                remaining.Signal();
                limit.Release();
            }
        }).Start();
    }
    // Wait for all requests to complete
    remaining.Wait();
}


Generating a day event calendar based on an array of objects

Comments are in the code:

var myArray = [
    { start: 30, end: 130 },
    { start: 140, end: 147 },
    { start: 145, end: 155 },
    { start: 150, end: 175 },
    { start: 200, end: 250 }
];

var myFunc = function (dates) {

    // sort the input array from earliest start time to latest. Items with
    // identical start times will compare end times - the longer duration
    // item resolves with lower index. Assumes no exact duplicate items.
    var sortedDates = dates.sort(function (a, b) {
            // replaced the
            // var caseOne = (a.end > b.end) ? -1 : 1,
            //     caseTwo = a.start - b.start;
            // return (a.start===b.start) ? caseOne : caseTwo
            // with a shorter short cut, considering the start value are the same,
            // it evaluates to falsy (0) and the other part is taken, if evaluated
            // to truthy, the value of the first difference is taken.
            return a.start - b.start || b.end - a.end;
        }),
        factor = 2; // for some more space

    // i change the for (...) loop to the more handy Array.forEach loop
    sortedDates.forEach(function (item, i, o) {

        var itemDuration = factor * (item.end - item.start), // applied factor
            itemTop = factor * item.start,                   // applied factor
            prevItem = o[i - 1],
            nextItem = o[i + 1],
            newDiv = document.createElement('div');

        // set a default direction to each item
        item.direction = 'left';

        // determine which items overlap and set a property to indicate
        // changed the comparison nextItem !== undefined to simply nextItem
        // and the subtraction to a direct comparison
        if (nextItem && item.end > nextItem.start) {
            item.overlap = true;
            nextItem.overlap = true;
        }

        // ensure items flow in UI by staggering overlapping items
        // changed the comparison prevItem !== undefined to simply prevItem
        if (prevItem && prevItem.direction === 'left') {
            item.direction = 'right';
        }

        // set class names on new DOM element based on overlap
        // replaced item.overlap === true with item.overlap because if not set
        // then it evaluates to false and if set, but false the it stays false,
        // otherwise if set and set to true, it evaluates true, then no furter
        // comparison is needed

        // the other change is the comparison of item.hasOwnProperty('direction')
        // here logical or is applied, because item.direction evaluates to false
        // if not set, with the || '' we get an empty string, but if set, then
        // only this result becomes the value
        item.overlap && newDiv.setAttribute('class', 'split ' + item.direction || '');

        //set the size and position based on computed duration and start time
        newDiv.setAttribute('style', 'height:' + itemDuration + 'px; top:' + itemTop + 'px');
        // to see some information
        newDiv.innerText = i + ': ' + item.start + ' - ' + item.end;

        //insert new element into DOM
        console.log(newDiv);
        document.getElementById('calendar').appendChild(newDiv);
    });

};

myFunc(myArray);
#calendar {
    height: 720px;
    width: 100%;
    position: relative;
}
#calendar div {
    position: absolute;
    width: 100%;
    min-height: 5px;
    background: brown;
}
#calendar .split {
    width: 50%;
    background: pink;
}
.right {
    right: 0;
}
.left {
    left: 0;
}


Curious,

$("#delivers #servers") does not do what you think it does, $("#delivers,  #servers") might, UPDATE: unless you mean to look for #servers under #delivers in which case you should strive to only have one tag with the #servers id and then go for $("#servers")
I don't understand why you at one point use $(this).val() and at another point $("#delivers #servers").val() if you say that they both point to servers_id
Furthermore, you could simply use var sid = this.value
You are performing many jQuery calls, those could be cached.
Your comments are too much, you don't have to explain every line ;)
On the other hand, what I would really want to know ( the difference between vmtas and o_vmtas is not commented )
vmtas and o_vmtas are terrible names
Your indenting is confusing
Consider $.empty() over $.html('')

I took some guesses as to what you are trying to and incorporated my feedback into this:

var $dropdown = $('#vmtas')
var $deliverability = $('#o_vmtas')

//Listen to changes in server id
$("#delivers").change(function () {

    //What server id are we dealing with ?
    var sid = this.value;
    //Is it something we can get deliverability info on?
    if ( sid != '0') {
        $.get("/deliverability/get_vmtas/" + sid, function (data) {
            $deliverability.html(data);
            $dropdown.html('');
        });
    }
    else {
        $dropdown.html('<option value="0">All Classes</option>');
        $deliverability.html('');
    }
});


Wrapping every expression with % 2 ** 32 to get a C-like behavior

Firstly, the expensive modulo operation % 2**32 can be replaced by a cheap bitwise and: & 2**32-1. Make sure to familiarize yourself with operator precedence, because it's not intuitive when it comes to bitwise operators (if you haven't done that yet).

As a next step, you could use the following properties to optimize the equations:

(a % m + b % m) % m = (a + b) % m
(a & n ^ b & n) & n = (a ^ b) & n

That allows you get rid of many of the & 2**32-1 operations at the cost of bigger intermediate results.  If you want to make sure to get the highest speed, do some perfs. In any case, it will make the code much more readable.


This is the typical situation where a hash table that maps elements to their frequency count is particularly well suited.

(defun occurrences (lst)
  (let ((table (make-hash-table)))                   ; [1]
    (loop for e in lst
          do (incf (gethash e table 0)))             ; [2]
    (sort (loop for k being the hash-key of table    ; [3]
                  using (hash-value v)
                collect (cons k v))
          #'>= :key #'cdr)))                         ; [4]

We create the hash table: the key will be an element of the list, the value will be the frequency count. Note that it is not necessary to initialize it because the gethash function provide an initialization of the value for a key not already present in the table.
For each element of the list we increment (incf) the frequency value associated to it. This value is obtained by gethash, and if it is not yet in the table, it is initialized by default to 0 (the last parameter of gethash).
At the end, we use the “loop over hash table” syntax to collect all the pairs (key count) in a list, and we sort the list over the second element.

This solution is simple, very efficient and elegant.

If you want to use only lists, here is a solution that has the same complexity of the sorting algorithm:

(defun occurrences (lst)
  (if (null lst)                                            ; [1]
      nil
      (let ((sorted (sort (copy-list lst) #'string<=)))     ; [2]
        (do ((c 1)                                          ; [3]
             (l (cdr sorted) (cdr l))                       ; [4]
             (el (car sorted) (car l))                      ; [5]
             (res nil))                                     ; [6]
            ((null l)                                       ; [7]
             (sort (cons (cons el c) res) #'>= :key #'cdr)) ; [8]
          (if (eql (car l) el)
              (incf c)                                      ; [9]
              (progn
                (push (cons el c) res)                      ; [10]
                (setf c 1)))))))

If the list is empty return nil.
Sort the element by their names (assuming they are atoms), so that equal elements are contiguous.
Start a loop. The variabile c count how many equal elements are found (the frequency).
l is used to scan the sorted list. It starts from the second element of sorted.
el is the current element, while (car l) is the second one.
res is used to accumulate the result.
The iteration stops when l reaches the end of the list.
The result is obtained by adding the last couple (element, frequency) to the result, and sorting it by frequency.
The body of the loop: if the first element is equal to the second one increment the counter and continue to iterate.
Otherwise, a new element is found. So push the old one with its frequency on the result, and reset the counter to 1.


Connection

Is just wrapping PDO in a class Connection.
Contains hard-coded credentials.

This class provides no significant benefit over using the PDO class directly. If somehow you need to change the database credentials, you'll have to change the class' properties directly, which is also a bad thing.

I suggest you get rid of your Connection class and just stick to using the PDO class directly. It already provides everything you need.

User

Just an anemic domain object with a bunch of getters and setters. I don't see anything wrong with that.

UserService

Violates the Single Responsibility Principle.

This class serves to:

Authenticate Users.
Register Users.
Write / read from the database.

I would transform it into 3 application service classes and give them all their own responsibility:

AuthenticationService:

This will serve to authenticate Users so it contains the following methods:

Find logged in User.
Log in.
Log out.

RegistrationService:

This class will take care of your User domain object registrations and contains the following method:

Register User.

And finally UserMapper:

This class will contain all the CRUD operations for your domain object User, and it will spit out User domain objects when reading from the database. It will contain the methods:

Find user by ID.
Find user by Email.

  Is this right according to the MVC model?

Hmm, not really. You're missing the dedicated Views and Controllers of the M V C pattern.

From what I see, you've got responsibilities of the View mixed with your code on the bootstrap level. The logic of which you are controlling the model classes with is supposed to be in a dedicated Controller. And the logic of what you output to the browser needs to be in it's corresponding View.

Btw, the 3 classes I've discussed above are supposed to reside in the Model layer in your MVC structure because they contain business and application logic ( = model).

Blueprint of a potential controller:

// declare namespace

// import statements

class AuthController
{
    // dependencies

    public function __construct(AuthService $authService, View $view)
    {
        // set the dependencies
    }

    public function index()
    {
        return $this->view->index()
    }

    public function submit()
    {
        if ($user = $this->authService->logInUser('foo@bar.nl', 'password')) {
            return $this->view->success([
                'user' => [
                    'email' => $user->getEmail()
                ]
            ]);
        }

        return $this->view->failed();
    }

    // log out action
}

Note: In the original MVC pattern the Controller is not supposed to call or instantiate any views, but solely control the Model layer, nothing else. However, over the years this has changed. Nowadays what you'll mostly see and hear is that a Controller's job is to control the model layer and call / return the appropriate View.

Wrapping up

Luckily your code is not in a super bad state. All it needs is some refactoring and restructuring to make it valid according to the MVC pattern and abide by the separation of concerns.

Try to adhere to the coding standards defined by the PHP Framework Interop Group. It gives better readability to your code, especially for other programmers who do it as well. Of course, you do not have to be perfect with it.

I hope my answer is clear enough and of some help to you. :)


Overall I'd consider your approach to be "procedural" rather than object-oriented, which might have contributed to the feedback about "lack of best practices"

I agree with Shanif that it would be best to create a class with different methods and avoid static.

Below is an example of the object-oriented approach.

Under the principle of encapsulation I wondered, "Should the Board expose its inner workings of how it generates the moves?" I decided no, and kept the Board's "calculation" methods private.

When I first posted this answer I knew that the various moves had enough in common to be candidates for inheritance. And, I got around to implementing it. Now the Move family of classes all derive from an abstract base class.

I also added the Solution class to capture the steps and help output them at the end.

Admittedly, this object model might be "overkill" for an app of this size. But, I was more interested in modeling the domain than in outputting the results as tersely as possible.

Despite its verbosity in meeting the currently-modest requirements, this object model provides a foundation upon which the app could grow to any size.

Or, to put it another way... Object-oriented programming is useful for many things. Winning at code golf is not among them.

Here's the output:

And the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class App_LetterBoard
{
    public void Run()
    {
        var board = new Board("agtcf");
        board.Solve("cat");
        board.OutputResult();

        Console.WriteLine();
        var board2 = new Board("agtcfqwerqweroqiweru");
        board2.Solve("cat");
        board2.OutputResult();
    }
}

public class Board
{
    private string initial;
    private string target;
    private string current;
    private string result;
    private char next;

    public Solution Solution { get; private set; } = new Solution();

    public Board(string initial) => this.initial = initial;

    public void Solve(string target)
    {
        this.target = target;
        result = string.Empty;
        current = initial;
        var index = 0;

        Solution.Add(new Start(initial));

        while (!result.Equals(target))
        {
            next = target[index++];
            var distanceLeft = current.IndexOf(next);
            var distanceRight = current.Length - current.LastIndexOf(next) - 1;
            if (distanceLeft <= distanceRight)
            {
                captureLeft(distanceLeft);
            }
            else
            {
                captureRight(distanceRight);
            };

            result = $"{result}{next}";
        }
    }

    public void OutputResult()
    {
        Console.WriteLine($"Find -> {target}");
        Console.WriteLine(Solution.ToString());
    }

    private void captureRight(int distance)
    {
        for (var i = 0; i < distance; i++)
        {
            var move = new RotateRight(current);
            Solution.Add(move);
            current = move.After;
        }

        var take = new TakeRight(current);
        Solution.Add(take);
        current = take.After;
    }

    private void captureLeft(int distance)
    {
        for (var i = 0; i < distance; i++)
        {
            var move = new RotateLeft(current);
            Solution.Add(move);
            current = move.After;
        }

        var take = new TakeLeft(current);
        Solution.Add(take);
        current = take.After;
    }
}

public class Solution
{
    public List<Move> Moves { get; private set; } = new List<Move>();

    public void Add(Move move) => Moves.Add(move);

    public override string ToString()
    {
        var sb = new StringBuilder();
        sb.AppendLine(string.Join("\n", Moves.Select(m => m.ToString())));
        return sb.ToString();
    }
}

public abstract class Move
{
    public abstract string Name { get; }

    public string Before { get; private set; }

    public string After => advance();

    public Move(string remaining) => Before = remaining;

    public override string ToString() => $"{Name} -> {spread(After)}";

    protected abstract string advance();

    protected string removeLeft() => Before.Substring(1);

    protected string removeRight() => Before.Substring(0, Before.Length - 1);

    private string spread(string s) => string.Join(" ", s.ToArray());
}

public class Start : Move
{
    public override string Name => "Start";

    public Start(string current) : base(current) {}

    protected override string advance() => Before;
}

public class RotateLeft : Move
{
    public override string Name => "Rotate Left";

    public RotateLeft(string current) : base(current) { }

    protected override string advance() => $"{removeLeft()}{Before.First()}";
}

public class RotateRight : Move
{
    public override string Name => "Rotate Right";

    public RotateRight(string current) : base(current) { }

    protected override string advance() => $"{Before.Last()}{removeRight()}";
}

public abstract class Take : Move
{
    public override string Name => "Take";
    public Take(string current) : base(current) { }
}

public class TakeLeft : Take
{
    public TakeLeft(string current) : base(current) { }

    protected override string advance() => removeLeft();
}

public class TakeRight : Take
{
    public TakeRight(string current) : base(current) { }

    protected override string advance() => removeRight();
}


An error message ("too few"/"too many") is not helpful. Typically when an Unix utility cannot deal with the command line it prints what it expects:

For example,

fprintf(stderr, " Usage: %s sleep_duration", argv[0])

It is also customary to provide a usage() function to print such message.

In any case, do not hardcode a sleep string. Use argv[0].
strtoul has very good error handling capabilities. It is pointless to try to intercept problems it can detect.

Just let it do its job:

char * stop;
unsigned long int time = strtoul(argv[1], &stop, 10);
if (*stop != 0) {
    // strtoul failed to parse the argument. Now printing an error message is appropriate.
    usage("...");
}

It would be nice to add an option to define a SIGALRM behaviour. OpenGroup does not specify which action shall be taken, meaning it is up to you to define it.


Remove unwanted characters from a string

By having a const string which contains all of your wanted chars, you could do either a simple call to Contains() or check if IndexOf() will return a value > -1.
using string concatenation in a loop is mostly a bad idea. Use a StringBuilder instead.
omitting braces {} although they are optional for single lined if statements is a bad idea because it makes your code error prone.

Implementing the mentioned points will lead to

private const string allowedCharacters = "numkMGHzVs%-.";
private string RemoveUnwantedChar(string input)
{

    StringBuilder builder = new StringBuilder(input.Length);

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsDigit(input[i]) || allowedCharacters.Contains(input[i]))
        {
            builder.Append(input[i]);
        }
    }
    return builder.ToString();
}

@Caricorc made a good suggestion in the comments

  In my opinion allowedCharacters should be an argument to the function to allow reusability.

So by passing the allowedCharacters as an optional parameter with an additional check with IsNullOrEmpty().

If performance is an issue, you could also pass a HashSet<char> to the method or have an overloaded method like so

private string RemoveUnwantedChar(string input, string allowedCharacters = "0123456789numkMGHzVs%-.")
{

    if (string.IsNullOrEmpty(allowedCharacters)) { return input; }

    return RemoveUnwantedChar(input, new HashSet<char>(allowedCharacters));

}
private string RemoveUnwantedChar(string input, HashSet<char> allowedCharacters)
{
    if (allowedCharacters.Count == 0) { return input; }

    StringBuilder builder = new StringBuilder(input.Length);

    for (int i = 0; i < input.Length; i++)
    {
        if (allowedCharacters.Contains(input[i]))
        {
            builder.Append(input[i]);
        }
    }
    return builder.ToString();
}

you can reuse it somewhere else.


It looks like the choice of area to scan and iteration through the disk is outside the scope of this program, so we'll assume that this is a decent way of finding and recovering a jpeg file.

Implementation:

It looks like your program is set up to scan/find multiple images within the given region. As it is currently written, it will output 512 byte blocks per file if a given 512 byte block happened to start with the JPEG header. For this to be more or less general purpose, you should scan the block for the jpeg header, and then output, potentially across multiple blocks, to the same output file until you reach the end of the JPEG (FF D9, although I don't know if that can be found as random data within the image - if it can, you must parse the size fields of the format).
Going off of the Wikipedia article you can use more fields than FF D8 FF E0 (for instance, 4A 46 49 46 00 at a 4 byte offset after the initial magic. You also don't need to perform the (buffer[3] & 0xf0) operation - it looks like the whole E0 is part of the spec (although maybe some image readers don't care, but that's another story). Using a longer magic will reduce your number of false positives.
Maybe a "resume on failure" functionality could be useful? An output of where you were when the failure happened, as well as an allowed optional argument that specifies where to start within the block (you'll have to strtoull it or whatever, and then fseek in the file).

Code:

sprintf( fileBuffer, "%03d.jpg", imageCount ); can overflow the buffer. %03d guarantees that the name will be at least 3 characters (+4 from ".jpg" and +1 for the terminating '\0' for a total of 8). If your program finds more than 999 images, this sprintf will start corrupting memory. Use snprintf instead (which will truncate memory before corrupting if the correct arguments are passed - a good choice to pretty much always use it instead). In theory you could make your buffer size based on the maximum printable length of the imageCount, but for it to be truly portable you'd have to use uint32_t (or some fixed size) and can then base the buffer size on the printable length of UINT32_MAX.
If you use snprintf with the current buffer size, your program will start mangling names (to "1000.jp") as soon as it hits 1000 images.
You can put a "max check" in your loop so that you don't start overriding files at some point, although you'll probably never pass in input data that writes 4 mil images. E.g. if (imageCount == UINT32_MAX) (or whatever is appropriate for the type chosen).
fwrite( buffer, blockSize, 1, outptr); can fail, treat/warn/error.
fclose(outptr); can fail as well (in both spots), for the same reason as above. fwrite/fclose will buffer "under the hood" and call fflush at certain points to write out to disk. These fflush operations can fail at the whim of the filesystem.
fclose(inptr); in theory this can return some failure code as well, but since it's an input file I'm not 100% sure it's possible at all.


ASP.NET MVC models that can be validated without using attributes

I wholeheartedly agree that the attributes are evil.
But in my opinion having to derive from a base class is just as bad as having to add attributes. Both makes you depend on framework infrastructure you don't need to depend on. (Models should be model logic, and model logic only.)

In MVC (3 at least) you can implement a ModelValidatorProvider and a ModelMetadataProvider. The validator provider can be added in Application_Start using ModelValidatorProviders.Providers.Add(...), and the metdata provider can be injected using the standard IoC container.

The guys who wrote Professional ASP.NET MVC 3 also created fluent implementations of those, so you can have configuration like this:

validationProvider.ForModel<PersonModel>()
    .ForProperty(p => p.Name).Required()
    .ForProperty(p => p.Email).Required().Email();

This will also be picked up by the unobtrusive validation jQuery plugin, and everything else in MVC that would've used the attributes for.

As a sidenote, since you also derive from DynamicObject in your base class, the compiler won't complain if someone inadvertedly attempts to set person.name instead of person.Name.


Is this use of JavaScript prototype functions for attaching event listeners going to meet design goals?

Looks fine to me; but I think the this.evnt & this.funct abstractions are unnecessary. Would always promote readable properties over shorthand (funct -> function etc), and I think that you should change the addEvent method to accept parameters. You can then clean up the code like so:

var CustomEditor = function(id) {
    'use strict';
    this.id = id;
    this.init();
};

CustomEditor.prototype.addEvent = function(event, callback) {
    'use strict';
    var element = document.getElementById(this.id);
    // old IE work around
    if (element.attachEvent) {
        return element.attachEvent('on' + event, callback);
    }
    return element.addEventListener(event, callback, false);
};

CustomEditor.prototype.init = function() {
    'use strict';
    this.addEvent('blur', this.onCustomBlur);
    this.addEvent('keypress', this.onCustomKeyPress);
    this.addEvent('focus', this.onCustomFocus);
};

See the fiddle.


Form a string consisting of the common letters that appear in two input strings

I know the root of all evil is premature optimization, but I would first ask if this is expected to be either a hotspot or usef with large strings.

Because it can be made much more readable using the array methods, but doing so obviously comes with a performance cost. OTOH, your method has its own performance issues.

If this isn’t expected to be particularly performance sensitive, I think that a straightforward method that turned the two strings into arrays then used the filter or map method to generate an array that is then turned into a string would be much more readable, and I prefer readable over performant as long as the performance isn’t a problem.

One additional point, what should your function return for “a”, “aa”? currently it returns “aa”?