Your code looks nice and compiles cleanly - good signs.  Some comments, nevertheless:

all functions except main should be declared static
the opening brace { for a function should be in column 0
stack_print should take a const parameter, as you are not modifying the stack:

 void stack_print(const struct StackItem *current)

the stack variable name current would be better as (for example) stack
you define the stack current by allocating a StackItem but never use
this item.  It would be better to define the stack using just a pointer:

 struct StackItem *current = NULL;

this involves some changes to other functions because the 'empty stack'
condition is no longer (*current)->previous == NULL but simply *current
== NULL.   This affects stack_pop and stack_print.  The latter becomes:

void stack_print(const struct StackItem *current)
{
    while (current != NULL) {
        printf("%d\n", current->value);
        current = current->previous;
    }
}

for-loops are often better than while loops - eg when you are counting
through a range.  And the loop variable is best declared in the loop where
possible:

for (int i = 0; i < 10; ++i) {
    stack_pop(&current);
}

using constants in the code like 10 is often a bad idea.  Some are fine (eg
the 10 in the strtol call, but the loops would be better having a #defined
limit

#define N_VALUES  10

for (int i = 0; i < N_VALUES; ++i) {...}

Such #defines go at the top of the file after the #includes
gets is not safe and should not be used.  Using gets with a buffer of 10
bytes, if the user types in more than 10 characters the buffer overflows and
overwrites the call stack (not your stack but the process stack).  Use
fgets instead:

fgets(input, (int) sizeof input, stdin);

there is no error handling, but that is ok for an exercise.  In a real
program, you would want to check that malloc does not fail (using perror
to print an error message if it does - an then you have to decide what to do
about the failure) and you might want to return success or failure from
the push/pop functions.


Validating a date with C# and ASP.NET Core 3.1

You could easily turn your method into a one-liner expression-bodied method with a few tricks:

use the _ discard variable instead of the explicit parsedDate variable (also, it doesn't need initializing to new DateTime()).
use the conditional operator since you're returning one of two ValidationResults.
value.ToString() can be passed directly into TryParseExact without the extra local variable dateToParse.

Giving:
protected override ValidationResult IsValid(object value, ValidationContext validationContext) =>
    DateTime.TryParseExact(value.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _)
        ? ValidationResult.Success
        : new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");

Couple more items:

Recommend -- for ease of reading -- adding a using System.Globalization; to your namespace so you don't have to type that long prefix out twice.
As this is an attribute, add the suffix Attribute to your class name.


Your design doesn't follow best practice. Your Library class should create a library when you use __init__, rather than a book.
And so I'd split your code in half, create two classes; one for books, the other for the library.
You shouldn't mutate data on Library. This is as it mutates it on the class, rather than on the instance. And so if you make a new instance, then it will be tied to all the other instances.
When making the book class. This can significantly be simplified with collections.namedtuple. Such as:

Book = namedtuple('Book', 'name author ISBN price')

And so I'd change your code to:

from collections import namedtuple

class Library(object):
    def __init__(self):
        self.books = []

    def addBook(self, book):
        self.books.append(book)

    def searchBookISBN(self, ISBN):
        for book in self.books:
            if book.ISBN == ISBN:
                return book

    def searchBookAuthor(self, author):
        written_by_author = []
        for book in self.books:
            if book.author == author:
                written_by_author.append(book)
        return written_by_author

    def searchUnderPrice(self, price):
        books_under_price = []
        for book in self.books:
            if book.price < price:
                books_under_price.append(book)
        return books_under_price

Book = namedtuple('Book', 'name author ISBN price')

library = Library()
library.addBook(Book('Geometry', 'Jeff Potter', '0596805888', 22))
library.addBook(Book('Math', 'George Harr', '0594805888', 15))
library.addBook(Book('English', 'James Odd', '0596225888', 10))
library.addBook(Book('Physics', 'Jeff Potter', '0597884512', 18))
print(library.searchBookISBN('0594805888'))
print(library.searchBookAuthor('George Harr'))
print(library.searchUnderPrice(20))

After this, I'd recommend:

You read and follow PEP 8, so that your code is easier to read.
You learn list comprehensions

Which would further improve your code to:

class Library(object):
    def __init__(self):
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def book_with_ISBN(self, ISBN):
        for book in self.books:
            if book.ISBN == ISBN:
                return book

    def books_by_author(self, author):
        return [book for book in self.books if book.author == author]

    def books_under_price(self, price):
        return [book for book in self.books if book.price < price]


I do not consider your class useless, I have actually done a similar thing myself. Very similar actually. Perhaps even exactly the same, pretty much.

Overall, your code is very well-written. You use final and private where you can, which I like.

A few comments:

private static final TaggedLogger LOGGER = TaggedLogger.forClass(MainActivity.class);

Even though it is correct that constants are written in ALL_CAPS. One exception for this is loggers. If you write LOGGER.info and stuff often, that LOGGER will pick on your eyes after a while. I would recommend using the name logger (lowercase) instead.

public static final TaggedLogger GLOBAL = new TaggedLogger("Global");

I am not sure if you really need this one. Especially not inside that class.

It is good that you have not made your class a singleton at least, but I'm not sure if this public static 'global' is really necessary.

I can recommend using log4j for Android for logging. Log4j is a very nice and popular logging framework for Java, and it is possible to get it working on Android.


To improve time complexity you must sometimes trade-off space complexity. It's known as space-time tradeoff
You can transform list1 into a dictionary where key is id and value is the dictionary itself.
list1 = {d['id']: d for d in list1}
# print(list1)
# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}

Now, iterate through list2 and update list1 based on id
for d in list2:
    list1[d['id']].update(d)

#print(list1)
# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}

Take dict.values() to get desired output
print(list(list1.values()))
# [{'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}]

Dealing with Edge cases
The above approach fails when list2 has an id which doesn't exist in list1. If that's the case then use this and you want to add that new id to output too. Using dict.setdefault
# for example list2 is as below
# [{'id': 1, 'knights': 5, 'coconuts': 2},
#  {'id': 2, 'knights': 3, 'coconuts': 8},
#  {'id': 3, 'knight': 4, 'coconuts': 5}] -> new `id` that's not in `list1`

# Here we leverage on `dict.setdefault`

for d in list2:
    list1.setdefault(d['id'], dict()).update(d)

print(list1)
# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8},
#  3: {'id': 3, 'knight': 4, 'coconuts': 5}}

# To get list of dicts use `list(list1.values())

In case you dont want to update with new id, we can resolve this using if block here.
for d in list2:
    if d['id'] in list1:
        list1[d['id']].update(d)
# {1: {'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  2: {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}}
# No `id` 3 present in output

Using libraries that support vectorization?
If you are working on millions of rows you can leverage on pandas which has many vectorized operations. In your case we can use DataFrame.merge
import pandas as pd

df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)

# Now, you have to merge them on `id`

out = df1.merge(df2)

#    id  spam  eggs  knights  coconuts
# 0   1     3     5        5         2
# 1   2     5     7        3         8

To get output as a list of dict you df.to_dict with orient param set to records
out.to_dict(orient='records')

# [{'id': 1, 'spam': 3, 'eggs': 5, 'knights': 5, 'coconuts': 2},
#  {'id': 2, 'spam': 5, 'eggs': 7, 'knights': 3, 'coconuts': 8}]

If you want include new ids then set how param of df.merge to 'outer' by default it's 'inner'
df1.merge(df2, how='outer')

#    id  spam  eggs  knights  coconuts
# 0   1   3.0   5.0        5         2
# 1   2   5.0   7.0        3         8
# 2   3   NaN   NaN        4         5

Code Review

Naming variables
list1 = [...]
list2 = [...]

A new reader might not understand what's list1 and list2. Name them so they make sense to everyone.
current_users_details = [...]
new_details = [...]

This is just an example, name them accordingly. What I do is ask myself what is it storing in the data-structure?... family member details? then variable name is family_members_details, user details then user_details, pi value? then PI_VALUE... etc.

Violation of E231
list1 = [{"id":1, "spam": 3, "eggs": 5}, {"id": 2, "spam": 5, "eggs": 7}]
list2 = [{"id":1, "knights": 5, "coconuts": 2}, {"id": 2, "knights": 3, "cocounts": 8}]

The above lines use inconsistent use of spaces after :, PEP-8 suggest add a space after :.

Violation of E501
list2 = [{"id":1, "knights": 5, "coconuts": 2}, {"id": 2, "knights": 3, "cocounts": 8}]

Lines longer than 79 characters, PEP-8 standard suggests to keep characters in a line <= 79

You have missing ' here if id['id'] == i['id]:

Reusability
Make a function which takes both the lists and updates them.
def update_details(current_details, to_update_with):
    """
    updates user details
    """

    details = {d['id']: d for d in current_details}
    for user in to_update_with:
        details[user['id']].update(user)
    return details

Write a much better docstring :P

I suggest using black python code formatter.
ch3ster@ch3ster:~$ black --line-length 79 your_file.py

Formatted code
Formatted your code using black.
list1 = [{"id": 1, "spam": 3, "eggs": 5}, {"id": 2, "spam": 5, "eggs": 7}]
list2 = [
    {"id": 1, "knights": 5, "coconuts": 2},
    {"id": 2, "knights": 3, "cocounts": 8},
]

for d in list2:
    list1[d["id"]].update(d)

print(list(list1.values())) # Equivalent to print([*list1.values()])


List of variables, split based on pattern

You can extract the value from the array before hand with something like:

$arr = array($one, $two,$three,$four,$five);

&first = $arr[$_POST['x']-1];

unset($arr[$_POST['x']-1]);
$arr = array_values($arr);
add_remove($first, $arr);


Thread-safe singleton class using std::shared_ptr in C++(11)

Your code doesn’t compile, and if it would compile, it would crash.

You are trying to assign a shared_ptr to a raw pointer. You are also trying to delete a shared_ptr and this leads me to believe that you don’t understand what a smart pointer actually does.

In fact, your code contains a multitude of errors. More on that below.

First, about the use of shared_ptr. In fact, a shared pointer denotes shared ownership, and this is patently not the case here: the singleton is the owner, nobody else.

A shared pointer is inappropriate here, what you want is a unique_ptr.

Then, don’t expose a pointer to the user, expose a reference via get_instance (i.e. habe get_instance() return T&. And I would rename get_instance to plain instance (which is more C++-y), and rename the private field to something else.

Finally, reconsider your usage of a singleton in the first place. The singleton is generally considered an anti-pattern and real, legitimate uses are so rare that it doesn’t pay to have a singleton base class.

Detailed code critique

if(instance.get() == 0 || instance == (NULL && 0) || !instance) {

This is doing the same check three times. Why? Once is enough – the latter is the correct usage.

But this code isn‘t thread-safe anyway, in fact, it’s not making any effort to be thread-safe at all.

return instance;

As already said, you cannot cast a shared_ptr to a plain pointer.

static delete_instance(void)

That doesn’t compile, it’s missing a return value. Also, who is going to call this method? It should never be called probably, so just delete it.

delete instance;

As mentioned above, this doesn’t work, and is meaningless. The whole point of a smart pointer is that you don’t need manual deletion.

instance = (NULL && 0);

This code makes no sense. What is it supposed to do?

virtual ~singleton(void);

You have declared the destructor but you haven’t defined it. The implementation will be empty but you still need to define it.

static volatile std::shared_ptr<T> instance;

volatile probably isn’t meaningful here. In particular, its meaning is unrelated to cross-thread access (unfortunately). But even if it was related to cross-thread access, this wouldn’t make your code thread-safe, it would simply mean that threads would read the most up-to-date version of the variable.

friend class singleton<opengl_renderer>;

What do you need this line for?


Fetching a number of data tables from a stored procedure

Couple of things.

I would encapsulate the "magic" numbers into an enum

public enum DataSetTableInfo
{
    System = 0,
    Parameters = 1,
    DataColumns = 2
    //etc
}

then change the method Sig of CheckDataTableScope to take the enum instead of an int.

If CheckDataTableScope method isn't public or someplace else you are using it without _dataSet I would drop passing _dataSet into it.  Just makes method sig more chatty than needs to be. If you can pass others values in for _dataSet then I would still probably lean towards two methods or have a default value for parameter.  Something like

private DataTable CheckDataTableScope(DataSetTableInfo dataSetTableInfo)
{
    return CheckDataTableScope(_dataSet, dataSetTableInfo);
}

public DataTable CheckDataTableScope(DataSet ds, DataSetTableInfo dataSetTableInfo)
{
}

Then your calls to the fill in the data change to be like

 if (_dataSet != null)
 {
     _applicationContext = new ApplicationContext();

     //build the object for System Mode.
     _applicationContext.SystemMode = BuildSystemMode(CheckDataTableScope(DataSetTableInfo.System));

     //build the object for data parameters.
     _dataParameters = BuildDataParameters(CheckDataTableScope(DataSetTableInfo.Parameters));

     //build the object for data columns.
     _dataColumns = BuildDataColumns(CheckDataTableScope(DataSetTableInfo.DataColumns));

To me this seems more readable, not in love with the method name of CheckDataTableScope but I don't know what that method actually does.  Plus if the stored procedure changes you can just update the enum to add more tables or change it to match the new table order and not touch any other piece of code.

You can cast the enum to the int of the DataTable in CheckDataTableScope

var tableIndex = (int) dataSetTableInfo;

if (tableIndex <= ds.Tables.Count)
{
   var dt = ds.Tables[tableIndex];
}


Calculator for scoring dives in a competition

Variables should be initialized with proper values when declared (if not, they should be declared as close to the point of usage as practical). This way there's no need to initialize them to some invalid value, or risk leaving them uninitialized. (difficulty and ret are the main offenders here, but total, min and max should be declared just before the loop using them).
I'm not sure there's much point in the using std::foo;. It's probably as much work to keep track of what you're using and update the declarations than just typing std:: where necessary. But it's better than using namespace std;, so that's good. :)
The prompt message to the user asking for input could be passed as a parameter to getInput and printed as part of the function.
The min and max values could also be shown when requesting an input.

Consider splitting the main function into two phases: getting input, calculating the result. This may make the program a little easier to understand.
Certain things could be split off into separate functions. e.g. String to float conversion and calculating the overall score.

These last two are really just suggestions though; the original code is very good.

Edited code, with some alternative ways of doing things:

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>

constexpr auto JUDGES = 7;
constexpr auto FUDGE_FACTOR = 0.6f;
constexpr auto MIN_DIFFICULTY = 1.2f;
constexpr auto MAX_DIFFICULTY = 3.8f;
constexpr auto MIN_SCORE = 0.f;
constexpr auto MAX_SCORE = 10.f;

bool toFloat(std::string const& string, float& value)
{
    std::stringstream ss(string);
    return (ss >> value && ss.eof());
}

bool isInRange(float value, float low, float high)
{
    return (value >= low && value <= high);
}

float getFloatInput(float low, float high, std::string const& prompt)
{
    while (true)
    {
        std::cout << prompt << " [" << low << ", " << high << "]: ";

        std::string line;
        std::getline(std::cin, line);

        auto value = 0.f;
        if (toFloat(line, value) && isInRange(value, low, high))
            return value;

        std::cout << "invalid input!\n";
    }

    assert(false);
    return -1.0f;
}

std::vector<float> getJudgesScores()
{
    auto scores = std::vector<float>();

    for (auto i = 0; i != JUDGES; ++i)
        scores.push_back(getFloatInput(MIN_SCORE, MAX_SCORE, "score #" + std::to_string(i + 1)));

    return scores;
}

float calculateOverallScore(std::vector<float> const& scores, float difficulty)
{
    auto min = MAX_SCORE;
    auto max = MIN_SCORE;
    auto sum = 0.f;

    for (auto score : scores)
    {
        min = std::min(min, score);
        max = std::max(max, score);
        sum += score;
    }

    sum -= (min + max);

    return sum * difficulty * FUDGE_FACTOR;
}

int main()
{
    auto difficulty = getFloatInput(MIN_DIFFICULTY, MAX_DIFFICULTY, "difficulty");
    auto judgesScores = getJudgesScores();
    auto overallScore = calculateOverallScore(judgesScores, difficulty);

    std::cout << "The dive scored: " << overallScore << std::endl;
}


Predicting words based on swiping a keyboard

To me it looks fine. Just some minor adjustments:

I think it would look even nicer if you defined constants for the magic numbers.

 const int AlphabetLength = 26;
 const int MinWordLength = 5;

In place of 97 I'd put simply an 'a'.

Instead of

currentPosition == -1

I suggest

currentPosition < 0

The -1 looks like a magic number. I sometimes use a constant for it that I name IndexOutOfRange.

You use var everywhere but here :-)

int currentPosition = 0;

It might also be a good idea to move the code from the constructor into a new method like AddWords or AddWord so you can extend the dictionary later if necessary. Usually those dictionaries can learn new words.


Retrieve Internet explorer proxy settings from the registry

As is, the (my) code is really hard to test (needs actual registry modifications or env variable edition).

To ease the testing, one could change some functions:

func overrideEnvWithStaticProxy(conf ProxyConf, setenv envSetter) {
    ...
}
type envSetter func(string, string) error

func parseRegedit(regedit regeditValues) ProxyConf {
   ...
}

With this change overrideEnvWithStaticProxy and parseRegedit become self contained and can be easily tested!

This incurs a minor rewrite of getConf (which does only some plumbing):

func getConf() ProxyConf {
    once.Do(writeConf)
    return windowsProxyConf
}

func writeConf() {
    regedit, _ := readRegedit()
    windowsProxyConf = parseRegedit(regedit)
}


Reorganizing inventory items into a data structure

The first thing to note is that Java no longer requires the generic types to be specified in the declaration of the collections you have, so, for example, the code

Map<String, ArrayList<TreeMap<String, String>>> map = new TreeMap<String, ArrayList<TreeMap<String, String>>>();

can be replaced with:

Map<String, ArrayList<TreeMap<String, String>>> map = new TreeMap<>();

That simplifies your line-lengths in a few places.

This is how I would simplify the code cosmetically:

Map<String, ArrayList<TreeMap<String, String>>> map = new TreeMap<>();
String charsToFilter = "[" + Pattern.quote("_-") + "]";
ArrayList<String> productNameArray = new ArrayList<>();

for (Map<String, String> baseDataItem : baseDataArray) {
    productNameArray.add(baseDataItem.get("product_name")
                    .replaceAll(charsToFilter, " ")
                    .toLowerCase());
}

for (Map<String, String> inventoryItem : inventoryArray) {
    //moving this to the for loop below increase execution time by 100%
    String processedInventoryItem = inventoryItem.get("title")
          .replaceAll(charsToFilter, " ")
          .toLowerCase();

    for (String productName : productNameArray) {
        if (processedInventoryItem.contains(productName)) {
            ArrayList<TreeMap<String, String>> currentListingArray = new ArrayList<>();
            TreeMap<String, String> currentListingMap = new TreeMap<>();
            for (Map.Entry<String, String> keyValue :  inventoryItem.entrySet()) {
                currentListingMap.put(keyValue.getKey(),  keyValue.getValue());
            }

            currentListingArray.add(currentListingMap);
            if (map.get(productName) == null) {
                map.put(productName, currentListingArray);
            } else {
                map.get(productName).add(currentListingMap);
            }

            break;
        }
    }
}
return map;

OK, that fits on a single screen, and is almost narrow-enough for StackExchange code blocks.

Right, now, what are you doing? You're iterating over the inventoryArray, and, for each inventoryItem, you check to see whether there's a baseDataArray member who's filtered name is part of the filtered inventoryItem's name.

You extract the processing of the baseDataArray names to a separate loop to prevent recalculating it often. That's a good idea. It would be better if you reused a single compiled Pattern:

Pattern charfilter = Pattern.compile("[" + Pattern.quote("_-") + "]");

Then, use that pattern in the loop, replacing the following

for (Map<String, String> baseDataItem : baseDataArray) {
    productNameArray.add(baseDataItem.get("product_name")
      .replaceAll(charsToFilter, " ").toLowerCase());
}

with:

for (Map<String, String> baseDataItem : baseDataArray) {
    productNameArray.add(charfilter.matcher(baseDataItem.get("product_name"))
      .replaceAll(" ").toLowerCase());
}

Similarly, inside the inventory loop, you can also do:

String processedInventoryItem = charfilter.matcher(inventoryItem.get("title")).replaceAll(" ").toLowerCase();

That should reuse the pattern more efficiently, and improve the replaceall time (though Java probably does a good job of detecting that misuse, and compiling it efficiently anyway.

There is a potential bug in your code, though, and it possibly accounts for the speed-up too.

In the original code, you check every inventory item against every product.

In the second code, you check each product against only the first inventory. You "break" the inner loop.

As a result, your "faster" code does not do a full join between the data sets, but only a partial one. This may or may not impact your results, but it will impact the performance.

As an aside, this code would look great in Java 8 with streams... do you have Java 8 available?


The correct answer depends on a few application design decisions.

Reasons why you should embed Comments in Posts:

You have a limit on the number of comments that can be on a post
The comment limit is relatively small (mongodb docs have a hard limit
of 4mb but you don't want to be pulling 4mb data down at once, so
your limit should take this into consideration)
You need access to all comments on a post when you load a post

Reasons why you should reference Posts from Comments:

You want to have unlimited comments on a post
You're ok with loading the post first then going back to the database every time you need comments
You want to fetch comments without posts

I offer a combined approach. Store comments in their own collection but store a total comments counter and possibly recent comments against the post. This way you can have unlimited comments but still have access to important information when listing posts without having to go back to the database.

I hope this helps


Plotting quadratic equations with varying parameters

tl;dr: Use numpy's broadcasting features:

coefs = np.array([-2, -1, 0, 1, 2])

#set up the plot and 3 subplots (to show the effect of varying each coefficient)
f, axes = plt.subplots(1, 3, sharey=True, figsize=(18, 6))

#some x values to plot
x = np.linspace(-2, 2, 30)

# calculate the y-values, varying each coefficient separately
y_values = [coefs[:, None] * x[None, :] ** 2,                 # vary a
            x[None, :] ** 2 + coefs[:, None] * x[None, :],    # vary b
            x[None, :] ** 2 + coefs[:, None]]                 # vary c

for ax, ys in zip(axes, y_values):
    for c, y in zip(coefs, ys):
        ax.plot(x, y, label="Coefficient is {}".format(c))
    ax.axhline(y=0, color='k')
    ax.axvline(x=0, color='k')
    ax.grid()
    ax.legend()
plt.show()

Calculating all necessary y-values would make this a 3D array (one dimension being x, one being the different plots and one being the different values of the coefficients).

To make it slightly easier than that we can handle each plot as a 2D array and make a list of the plots. This way we don't have to deal with the fact that the quadratic term should always appear.

If you really wanted to you could probably make that into a vectorized computation as well, but three dimensions was a bit too much to get straight in my head right now.

Explanation of broadcasting:

You can use the fact that numpy has something called broadcasting. It automatically adapts the shapes of vectors you do some operations on, if they are consistent. It can make things look very confusing but allows you to vectorize operations along multiple dimensions (using the fact that doing so loops at C speed, instead of at Python speed).

A small example: You want to multiply two arrays, both of shape (2, 2). numpy then simply does an element-wise multiplication (so \$c_{ij} = a_{ij} \cdot b_{ij}\$).

But if you multiply two arrays of shape (1, 2) and (2, 2), this is not directly possible. So instead it repeats the first array along its first dimension (since it is only of lenth one) and then does an element-wise multiplication. In other words \$c_{ij} = a_{0j} \cdot b_{ij}\$.

To make this abstract example concrete:

>>> a = np.arange(2).reshape(1,2)
array([[0, 1]])
>>> b = np.arange(4).reshape(2,2)
array([[0, 1],
       [2, 3]])
>>> a * b
array([[0, 1],
       [0, 3]])

Now, the final piece is the ability to cast arrays to different shapes (as I already did in the above example using numpy.reshape. Apart from that command you can also use fancy slicing to achieve the same effect:

>>> np.arange(2)[None, :].shape
(1, 2)
>>> np.arange(2)[:, None].shape
(2, 1)

So it repeats it along the axis where I put None (and puts all values in the axis where I put :).


TLE in APS - Amazing Prime Sequence in Python at Spoj

The best way to solve this is to precompute the prime factors of n for n in range(1:10**7) I would suggest using a sieve of Eratosthenes.

def sieve5(n):
"""Return a list of the primes below n."""
prime = [True] * n
result = [2]
append = result.append
sqrt_n = (int(n ** .5) + 1) | 1    # ensure it's odd
for p in range(3, sqrt_n, 2):
    if prime[p]:
        append(p)
        prime[p*p::2*p] = [False] * ((n - p*p - 1) // (2*p) + 1)
for p in range(sqrt_n, n, 2):
    if prime[p]:
        append(p)
return result

Once you have the list of primes, you can just run the same type of algorithm you would for the fibs.


A Simple Media Generator with Directional Control

The overall approach looks fine. Some suggestions:
Delegated click logic The current backForth being used both as a click listener and on the initial load feels a bit clunky since you have to pass in {target:{className: "buttonS"}}. Consider making a separate function that you pass an index to increment (either 1 or -1), and call that inside backForth, and call it with (1) initially.
Don't move buttons User interfaces are slightly friendlier when buttons stay in the same place - when they don't move based on the content size. Consider either moving the buttons above the output, or giving the output a fixed (or high minimum) height.
For variable name is really weird - it's very close to for, which is a reserved word, and regardless doesn't really indicate what the variable contains very well. Consider naming it something like displayedMediaIndex.
Variable initializers - you use var, let, and const:

If you're going to write in ES6+ (which you are, and you should), always use const or let to declare variables. var has a few gotchas (such as an unintuitive function scope rather than block scope, and of automatically assigning itself to properties of the global object when on the top level.) See ESLint rule no-var.
When deciding between const and let, use const whenever possible, since it indicates that the variable won't be reassigned, which improves readability when a reader of the code can understand that at a glance.

Prefer strict equality over sloppy equality, since sloppy equality operators have some very strange type coercion rules that a reader of the code should not have to have memorized to be entirely confident of the logic your code is implementing.
This is how I'd do it:

const medias = [
    '',
    '
Text\
Hello I am text
',
    '<video controls source src="FILE.mp4" type="video/mp4"></video>',
    '',
    '<audio controls source src="FILE.mp3" type="audio/mpeg"></audio>',
];
const mediasLength = medias.length;
let displayedMediaIndex = -1;
const output = document.querySelector('output');
const paginator = document.querySelector('.paginator');
const changeMedia = (indexChange) => {
    displayedMediaIndex = (displayedMediaIndex + indexChange + mediasLength) % mediasLength;
    output.innerHTML = medias[displayedMediaIndex];
    paginator.textContent = displayedMediaIndex + ' / ' + (mediasLength - 1);
};
document.addEventListener('click', (event) => {
    if (event.target.className == 'buttonS') {
        changeMedia(event.target.textContent === "Back" ? -1 : 1);
    }
});
changeMedia(1);

    <button class="buttonS">Back</button>

    <button class="buttonS">Forth</button>

<output></output>


Simon, Mat's Mug, what's the (rating) difference?

The static chatName() method isn't used at all. Just get rid of it because it is only adding noise.
Why is the static clearName() method public ? Make it either private and non static or place it in some other class which has the responsibility to do such cleaning to get the clear name.

Or to ask different, what is wrong with using org.apache.commons.lang.StringEscapeUtils.unescapeHtml like you do in AnswerInvalidationCheck ?
StringBuilder

IMO if you "know" or if you can narrow the resulting capacity of the StringBuilder you should use the overloaded constructor which takes the initial capacity as a parameter.
I like the fluent methods of the StringBuillder. IMO taking advantage of the fluent way makes it easier to read the code.
doing string concatenation to build a parameter for the append() method is somehow strange. Why don't you just use the append() method ?

Some vertical spacing would be good for your code. It groups related code and makes it more readable.

def max = users.stream().max(Comparator.comparingInt({it.reputation})).get();
def min = users.stream().min(Comparator.comparingInt({it.reputation})).get();

StringBuilder str = new StringBuilder();
str.append(clearName(max.display_name) + " vs. " + clearName(min.display_name) + ": ");
str.append((int)max.reputation - (int)min.reputation);
str.append(" diff. ");

diffStr(str, max, min, "Year", {it.reputation_change_year});
diffStr(str, max, min, "Quarter", {it.reputation_change_quarter});
diffStr(str, max, min, "Month", {it.reputation_change_month});


boolean add = true;
    for(int i=1; pi.setScale(digits, BigDecimal.ROUND_DOWN).equals(realPi) == false; i++){
        if(add){
            pi = pi.add(new BigDecimal(4.0 / (-1 + (i*2))));
            add = false;
        }
        else {
            pi = pi.subtract(new BigDecimal(4.0 / (-1 + (i*2))));
            add = true;
        }
    }

You don't need an add variable.  Consider

    int i = 1;
    while (!pi.setScale(scale, BigDecimal.ROUND_DOWN).equals(realPi)) {
        pi = pi.add(new BigDecimal(4.0 / i));
        i += 2;
        pi = pi.subtract(new BigDecimal(4.0 / i));
        i += 2;
    }

This may do one extra subtract operation, but it does half as many equals operations.  And it doesn't waste time on setting and checking a variable just to alternate between two operations.

We don't need the (-1 + (i*2)) part.  If we increment by 2 instead of 1, we get the same stream of values with strictly less math.  1, 3, 5, 7, 9, 11, ...

I changed the == false to the more idiomatic !.

I also changed digits to scale as I had trouble reading the original.

BigDecimal gives precise results, not quick results.  It is quite possible that you are hitting real limits of the format.  It's unclear at the moment why you are calculating \$\pi\$.  With more context, we might be able to give more help.


Pairwise programming challenge - Free code camp

My only comments would be stylistic so may be more a matter of opinion. Am open to any counter comments.

Whitespace

All your code is bunched together and is not as easy to read as it could be.

Single Statement if braces

It is often beneficial and consistent to always have braces on if and other blocks even if there is only a single statement. It's easy to introduce undesirable functionality if you come back to the code later and comment/add lines e.g.

if(someValue)
    //doThis();
alwaysDoThis();

Shorthand arithmetic

returnValue = returnValue + innerCounter + outerCounter;

can be shortened to

returnValue += innerCounter + outerCounter;


Counting average protein length from a proteome fasta file

The first thing to do to accelerate processing is to read the file only once. species_name_function reads the entire file, and is called multiple times. Extract the line which parses it and inline into the main loop:

    for fasta in SeqIO.parse(open(infile), "fasta"):
        species_name = fasta.description.split('[', 1)[1].split(']', 1)[0]

Now,

        dna = str(fasta.seq)
        freq = Counter(dna)

does unnecessary work. There's no need to convert to a string before counting.

listofbases is unused, and genomesize is calculated by a large explicit sum. My best guess is that you were experimenting, trying to come up with

        genomesize = sum(freq[base] for base in "GALMFWKQESPVICYHRNDT")

Using those changes and applying some further simplifications which I don't think need individual explanation, I get:

from Bio import SeqIO
import sys
from collections import Counter

if __name__ == '__main__':
    infile = sys.argv[1]
    genomesizes = []

    for fasta in SeqIO.parse(open(infile), "fasta"):
        species_name = fasta.description.split('[', 1)[1].split(']', 1)[0]
        freq = Counter(fasta.seq)
        genomesizes.append(sum(freq[base] for base in "GALMFWKQESPVICYHRNDT"))

    avgproteinlength = sum(genomesizes) / len(genomesizes)
    towrite = str(avgproteinlength) + '\t' + species_name + '\t' + '\n'

    with open("proteinlength.csv", "a") as myfile:
        myfile.write(towrite)

However, I'm not very convinced by the explicit output filename. Also, I would be inclined to simplify the usage by supporting multiple files:

from Bio import SeqIO
import sys
from collections import Counter

if __name__ == '__main__':
    for infile in sys.argv[1:]:
        genomesizes = []

        for fasta in SeqIO.parse(open(infile), "fasta"):
            species_name = fasta.description.split('[', 1)[1].split(']', 1)[0]
            freq = Counter(fasta.seq)
            genomesizes.append(sum(freq[base] for base in "GALMFWKQESPVICYHRNDT"))

        avgproteinlength = sum(genomesizes) / len(genomesizes)
        print(str(avgproteinlength) + '\t' + species_name)

called as

find . -name "*.faa" | xargs python proteinlengthgen.py >>proteinlength.csv


Efficient and fast way to send data from Android to server

The code can be made more memory efficient if you refactor it to use HttpURLConnection.

If you wish to write your own solution to upload the video file instead of using a 3rd party library, you can use HttpURLConnection to create a "read-write" while loop.  In this while-loop, while bytes have been read, read either InputFileStream up to a maxBufferSize OR available bytes left in the InputFileStream and store it into a buffer array (max array size is maxBufferSize). Then write this buffer array into HttpURLConnection's DataOutputStream.

If you can post new code that implements this approach in a background thread/service, then we could review that.


First a slight style note (IMHO, of course). You called your function check_domain_format, but it's actually returning a modified string and you're using the result, not checking it. I'd go for a name like validate_domain_format

About it being slow:

Yes, multi-threading would help in checking multiple domains at once, but if that was the only problem you could just make a separate bash script to launch your python script with different parameters.
You said that you own the domains, so I'm assuming you have RAW socket capabilities. If that's the case, you can speed up your check by using a SYN check. You can have a look here , even if the question has been down-voted, it should give you the general idea. Here you can find that same check.
If you're doing this for educational purposes that's ok, otherwise nmap will most likely do a better job, give you more options and be faster (because SYN check is already implemented and you can also scan for UDP ports, for example).


PHP - Packing widgets into the fewest number of boxes, plus minimum order quantity

OK, I agree that this is a bit harder than I assumed yesterday. You basically have two opposing demands:

No more widgets than necessary should be sent.
The fewest packs possible should be sent.

You cannot fulfill both. So if I tried to send 1200 widgets, rule 2 says I should send a pack of 2000, however, rule 1 says I should send 2 packs: one of 1000 and one of 250. Which rule should prevail?

I chose that rule 1 should prevail in the solution below. The reason is that no customer wants more widgets than absolutely necessary.

$packSizes = [ 250,
               500,
              1000,
              2000,
              5000];

function optimizePacks($packSizes,$number)
{
    rsort($packSizes);
    $requiredPacks = array_fill_keys($packSizes,0);
    foreach ($packSizes as $size) {
        $packs = floor($number/$size);
        if ($packs > 0) {
            $requiredPacks[$size] = $packs;
            $number -= $packs*$size;
        }
    }
    if ($number > 0) $requiredPacks[min($packSizes)]++;
    return $requiredPacks;
}

$packs = optimizePacks($packSizes,6666);

print_r($packs);

This will work for any array of pack sizes and any number of widgets. The output of this code is:

  Array (
      [5000] => 1
      [2000] => 0
      [1000] => 1
      [500] => 1
      [250] => 1 )

Which is one pack more than rule 2 would demand (one of 5000 and two of 1000). It would, of course, be possible to let rule 2 prevail, but I cannot fulfill both rules.


The Regex will validate some email addresses. Because the Domain Name System allows UniCode. the Regex does not match all valid characters in the Doman Name. Therefore it will not validate all valid email addresses.
Alternatives:
Validating over all allowable Unicode with Regex in a meaningful way is non-trivial.

Sending a confirmation email requiring reply is a straight-forward method for validating email procedurally.

When possible, not collecting email addresses at all is easy to implement.


Reinventing the wheel

Please note that encryption should, in principle, always be two way. A 'one way encryption' just sounds weird. Normally something is encrypted with the intention to decrypt it at a later stage. This is not what you do. What you do is called hashing or perhaps 'encoding' as you indicated in your title.

You could improve the formatting of your code. I really miss the empty lines before and after the functions, and a space before { in a function. Your code is also not working because of the ==> in it at the end. This should be // ==>. Is is just nice if your code is working like published here.

The naming of your variables seems somewhat sloppy. In the beginning you call an encoded password $newPass. Is it a new password? I don't think so. Then in the authorise() function you rename it correctly to $passEncode, by which you probably mean $passEncoded.

So the big question is, why do you define your own hashing routine? Is it any better than the existing routines? PHP offers many of them!

See this link to tutsplus which addresses some issues that are encountered in hashing passwords. Is your routine resistent to all these issues? I don't think so.

It is far better to use a good existing password hashing library that is present in PHP. Have a look here: http://php.net/manual/en/faq.passwords.php

There's a lot of information about hashing and PHP out there. Find it and use it. I do really support new and inventive ways to solve problems but in this case it is definately not a good idea to reinvent the wheel.


Loop through a worksheet and insert a row with layout when value is true

Always use Option Explicit and declare your variables as close as possible to their first use.
Fully qualify your worksheet references (see #5)

When calculating your LastRowMatchC, always make sure to fully qualify ALL worksheet references like this

Worksheets("Compliance").Cells(Worksheets("Compliance").Rows.Count, 1).End(xlUp).Row

or

With Worksheets("Compliance")
    LastRowMatchC = .Cells(.Rows.Count, 1).End(xlUp).Row
End With

(Notice the dot in front of the Rows) Otherwise, the the Rows.Count is looking at the currently active worksheet and not the one you intended.

Use EnableEvents and ScreenUpdating when you're making changes directly on the worksheet.

You can turn off events and screen updating before and after your loop to give a big speed boost to the reformatting:

Application.EnableEvents = False
Application.ScreenUpdating = False

For rc = rngc.Count To 1 Step -1
    '--- do your thing here
Next rc

Application.EnableEvents = True
Application.ScreenUpdating = True

(More on this in the next comment)

Avoid using Select and try to define any constant "magic values" in an expression. No one knows why you're looking for the value "2" here (and you may not remember a year from now). So replace the MAGIC_VALUE name with something meaningful to your application.

A partial example using your code:

Option Explicit

Sub InsertRows()
    Dim lastRow As Long
    With Worksheets("Compliance")
        lastRow = .Cells(.Rows.Count, "S").End(xlUp).Row
    End With

    Dim rngc As Range
    Set rngc = Worksheets("Compliance").Range("S8:S" & lastRow)

    AppPerformance SetTo:=False

    Const MAGIC_VALUE As Long = 2

    Dim rc As Long
    For rc = rngc.Rows.Count To 1 Step -1
        If rngc(rc).Value = MAGIC_VALUE Then
            rngc(rc + 1).EntireRow.Insert
            Dim newRow As Range
            Set newRow = rngc(rc + 1).EntireRow
            With newRow
                With .Interior
                    .Pattern = xlSolid
                    .PatternColorIndex = xlAutomatic
                    .ThemeColor = xlThemeColorAccent1
                    .TintAndShade = 0.599993896298105
                    .PatternTintAndShade = 0
                End With
                .Borders(xlDiagonalDown).LineStyle = xlNone
                .Borders(xlDiagonalUp).LineStyle = xlNone
                With .Borders(xlEdgeLeft)
                    .LineStyle = xlContinuous
                    .ColorIndex = 0
                    .TintAndShade = 0
                    .Weight = xlThin
                End With
                '--- keep going with formatting ...
            End With
        End If
    Next rc

    AppPerformance SetTo:=True

End Sub

Private Sub AppPerformance(ByVal SetTo As Boolean)
    With Application
        .EnableEvents = SetTo
        .ScreenUpdating = SetTo
    End With
End Sub


Menu and SideBar Slides, Fades, and Hides

This code can use quite a bit of work.

Run this code through a beautifier, ideally prior to posting it to codereview ;)
You are repeating yourself a lot, example :

// Sidebar tab highlight when clicked
$("#sidebar-tabs-container table td").click(function() {
  $("#sidebar-tabs-container table td").removeClass("sidebar-tab-selected");
  $(this).addClass("sidebar-tab-selected");
});

Unless you have a dynamic number of sidebar tabs ( seems unlikely ), you can do the following.

var $sidebarTabs  = $('#sidebar-tabs-container table td');
var selectedClass = 'sidebar-tab-selected';

$sidebarTabs.click(function() {
  $sidebarTabs.removeClass( selectedClass );
  $(this).addClass( selectedClass );
});

The interesting part is that you do this type of code twice, so you could also write a helper.

function wireClassToggler( elements, className )
{
  elements.click(function()
  {
    elements.removeClass( className );
    $(this).addClass( className );
  });
}

wireClassToggler( $('#sidebar-tabs-container table td'), 'sidebar-tab-selected' );
wireClassToggler( $('#activity-media-icons-container span'), 'activity-new-media-icon-clicked' );

You also seem to use copy pasted code for the slideUp and slideDown functions, you should generalize that as well.


Calling a Haskell MD5 hashing function from C, and returning the result back to C land

First, you have way too many comments.  They clutter the code, and some of them are completely redundant.

-- | Hash pointer to array of unsigned chars
hash :: CInt -> Ptr Word8 -> IO (Ptr Word16)

The comment provides no information beyond the function's name and signature.  But it doesn't answer these questions:

What hashing algorithm is being used?
Why is the output Ptr Word16?  UTF-16?
Is the output in hexadecimal, or raw bytes?  If it's hexadecimal, does it use capital or lowercase letters?

Before we dive into foreign API details, we can do a little refactoring.  There's a big chain of pure function application here.  Let's move it outside so it doesn't clutter the scary foreign pointer stuff:

hashPure :: ByteString -> Text
hashPure sbyte =
    let lbyte    = chunk sbyte empty
        digest   = encode . md5 $ lbyte
        hexBytes = toLazyText . foldr (\x y -> y <> hex x) mempty . unpack $ digest
     in toStrict hexBytes

I think we can improve this a bit.  Let's first take a step back.  Here's all hashPure needs to do:

Hash the input string (a strict ByteString) using MD5
Convert it to a hex string (as Text)

To get there, we have to do a bunch of annoying conversions.  But we can avoid these if we tweak a couple of our library choices.

Because of the Hash instance on MD5Digest, we can eliminate a strict to lazy ByteString conversion:

import Crypto.Classes (hash')
import Data.Digest.Pure.MD5 (MD5Digest)

hashPure :: ByteString -> Text
hashPure sbyte =
    let digest   = encode (hash' sbyte :: MD5Digest)
        hexBytes = toLazyText . foldr (\x y -> y <> hex x) mempty . unpack $ digest
     in toStrict hexBytes

Your code for converting to hex is bogus.  To illustrate why:

>foldr (\x y -> y <> hex x) mempty [1,2,3]
"321"

Namely:

Your use of foldr flips the order.  What you meant was: foldr (\x y -> hex x <> y)
The hex function does not pad the number to two characters.

To avoid the first problem, you could have just said mconcat (map hex).  foldr/build fusion should optimize it.

To fix the second problem, and avoid two more conversions, you can use the base16-bytestring package.  You could avoid yet another conversion if you make hash return an array of chars instead of wide chars, but I won't do that yet.

hashPure :: ByteString -> Text
hashPure sbyte =
    let digest   = encode (hash' sbyte :: MD5Digest)
        hexBytes = Base16.encode digest
     in decodeUtf8 hexBytes

We can make it a little prettier using point-free style:

hashPure :: ByteString -> Text
hashPure =
    decodeUtf8 . Base16.encode . Serialize.encode . md5
  where
    md5 s = hash' s :: MD5Digest

Now on to the ForeignPtr stuff.  I saved the best for last.

hash :: CInt -> Ptr Word8 -> IO (Ptr Word16)
hash count addr =  do
    fptr <- newForeignPtr_ addr
    let sbyte = fromForeignPtr fptr 0 (fromIntegral count)
    unsafeForeignPtrToPtr . fst <$> asForeignPtr (hashPure sbyte)

Your two points of interaction with C:

Convert a C array of bytes to a ByteString
Convert a Text to a block of wide chars, and return a pointer to it.

Your first conversion is sound, but I would use unsafePackCStringLen instead (which does the same thing):

hash :: CInt -> Ptr Word8 -> IO (Ptr Word16)
hash count addr =  do
    sbyte <- unsafePackCStringLen (castPtr addr, fromIntegral count)
    unsafeForeignPtrToPtr . fst <$> asForeignPtr (hashPure sbyte)

The second conversion is wrong.  ForeignPtr is for managing C objects in Haskell, not the other way around.  The returned pointer will be invalidated when the ForeignPtr returned by asForeignPtr is garbage collected.

You fix this, you would need to malloc a large enough buffer, then copy the text content into it.  Unfortunately, Data.Text.Foreign does not provide a convenient way to do this without a needless allocation.

I would change the signature of the C function from this:

uint16_t *hash(int blksize, uint8_t *block);

To this:

void hash(uint8_t *block, size_t blksize, char out[33]);

Namely:

Write a string to a caller-supplied buffer of the correct size, rather than allocating a buffer that the caller has to free.  A hex-encoded MD5 hash is always 32 characters long.  The 33rd byte is for the zero terminator.
Output a C string instead of UTF-16.  Unless you plan to throw the output into a system call or something that takes UTF-16, you shouldn't be using UTF-16.
Flip pointer and size arguments.  This is mainly a matter of taste.

See if you can implement this part yourself.  This post is already too long.


Killing a tunnel and establishing a tunnel through SSH

How about using pgrep with the -f option to match the whole command line so that we can match the desired process precisely?

For example, in you case something like:

pgrep -f 'ssh.*27017:localhost:27017'

might give the accurate PID. If you desire, you can modify it to make it more robust.

Implementing this in Python:

import subprocess
import os
import signal

def kill_tunnel():
    try:
        tunnel_pid = subprocess.check_output(['pgrep', '-f', 'ssh.*27017:localhost:27017'])
    except subprocess.CalledProcessError:
        return 'No Such Process'
    os.kill(tunnel_pid, signal.SIGKILL)


Controlling a Windows Service from a WPF app

async void methods should generally be avoided, yes, but this looks like it's one of the cases where they make sense.

var frame = new StackFrame(1);
var methodName = frame.GetMethod().Name;
_logger.Warn("'ExecuteWithTimeout' exception from: '{0}': {1}", methodName, ex.Message);

I don't see how is methodName useful here, it's always going to be Handle.

var frame = new StackFrame(1);
var methodName = frame.GetMethod().Name;
_logger.Warn("'{0}' timed out after {1} milliseconds.", methodName, timeout);

I think [CallerMemberName] would be simpler here.

throw exception;

This means that the stack trace of the exception is going to be rewritten. If you don't want to wrap the exception in another exception, you can use ExceptionDispatchInfo to preserve the stack.


I don't understand what you mean by "thrice nested", or why you call this an OS. I'm reviewing it as a login prompt.

  The entire rest of my code isn't bug free but this section is

Beware of believing something is bug-free. It never is. This is especially important for code which needs to be secure, as this presumably does.

Now for the review:

Many variables need names that say what they mean:

What does innerLoopFlag mean? Something like successful_login, right?
makeNew: command?
ui: credentials?
createFileSyst: (There's no need to abbreviate such a rarely used name.) Something like createUserDirectory? But it should be called from createAccount, not here.
takeCheck: What does this do? Is it isValidLogin?
all: Is it something like runUserSession?

Simplifications:

The conditional break at beginning of the loop can become the loop condition: while not innerLoopFlag.
The if ui test is always true.
The inner loop can be simplified by making the loop condition do the work:

while not takeCheck(ui):
    print "Failure logging in, retrying..."
print "Successful login..."
break

This also makes innerLoopFlag unnecessary. However, why are you retrying at all? Do you expect login to fail and then succeed?

Bugs:

Stripping the password is not safe, because passwords can contain whitespace.
Security hole: the isdir call lets anyone test for the existence of arbitrary directories. Imagine trying to log in with a username like '../../../some/private/directory'. Also, it depends on the current directory. Is there a user table you could look the user up in instead?
(Revealing whether a user exists is also sometimes considered a security hole, but that's debatable.)

Usability:

Are "c-na" and "l-a" user-supplied strings, or generated by raw_input, or what?
Output ending in "... " looks like a progress message ("Please wait..."), not a prompt. "Login: " and "Password: " are the standard prompts.


Subset pandas DataFrame based on two columns ignoring what order the match happens in

First, some comments on your question-asking: in your initial statement, you talk about matching 'col1' etc., but in your actual code, you have 'from, 'to', 'source', and 'target'. You talk about subsetting, but then you talk about pd.merge(), and those are completely different things. You formatting is poor, resulting your column names not lining up with the actual columns when you show the output in your code. When you generate random sample data, you should set a seed so that people will get the same data, and can check whether their code is doing the same thing as yours. Your test data is poorly chosen. For instance, does row for which 'from' matches one of the to_keep columns have to match the row in which 'to' matches, or can they match different rows? Can they both match the same column (e.g. 'from' and 'to' both match 'target'), or do they have to match different columns.  Neither your test cases nor your problem description are clear on those points; one has to go through your code to figure out what you mean.

Assuming that they have match on the same row, and in different columns, this code should work:

def check(row):
    forward = (to_keep['source'] == row['from']) & (to_keep['target'] == row['to'])
    reverse = (to_keep['source'] == row['to']) & (to_keep['target'] == row['from'])
    return any(forward) | any(reverse)

kept_df = df_all.loc[[check(row) for row in df_all.iterrows()]]


Generic type declaration

Your Stacks are missing the type parameter, i.e. in your case Stack<Integer>. This ensures they can only contain Integer objects.

static vs instance fields

sorted is the only instance field used in the only method of your SortStack class. This means it is likely better to exist as a method variable, and in turn your SortStack class becomes an utility class where sort(Stack<Integer> input) is now a static utility method.

Primitive unboxing

On a related note to the first point, you are implicitly relying on primitive unboxing, i.e. converting an Integer to int when you do this:

int temp1 = (int) unsorted.pop();

If a null is lurking in your unsorted object, this will fail.

Debugging and variable naming

If possible, use a logging framework like SLF4J so that you can configure when you want to see the debug statements, instead of simply printing via System.out.println(). Also:

" pushed from s1 to s2"

Isn't that meaningful - is s1 or s2 the sorted one? You may want to specify that. Same goes for temp1 and temp2, it's not possible to identify which contains the previous/current iterative element from the unsorted or sorted stack.

Future considerations

If you don't want to restrict to sorting Stack<Integer> objects, you can generic-fy it as such:

public static <T> sort(Stack<T> input) {
    // ...
}

However, you can't use your arithmetic-based comparison, so you can change that to:

public static <T extends Comparable<T>> sort(Stack<T> input) {
    // ...
    if (fromUnsorted.compareTo(fromSorted) >= 0) {
        // ...
    }
    // ...
}

And if you will like to make it even more 'generic' and cater for non-Comparable types, you can specify a Comparator<T> to do so:

public static <T> sort(Stack<T> input, Comparator<T> comparator) {
    // ...
    if (comparator.compare(fromUnsorted, fromSorted) >= 0) {
        // ...
    }
    // ...
}


Recurrent merge sort (without recursion)

I see a number of things that may help you improve your code.

Rearrange the code to reduce the need for declarations

A function declaration is only needed by the compiler if it hasn't already encountered the function itself.  With that said, if the functions in the file are in the order check_sort, merge, merge_sort and then main, no separate function declarations would be needed.

Separate I/O from logic

The check_sort routine is not bad as it is, but I'd advocate separating the I/O from the logic.  That is, rename check_sort to is_sorted and have it return a bool value of true only if the vector is sorted.  Leave the printing to the calling function instead.

Use const where practical

The check_sort function does not alter the passed vector, so that should be passed as const &:

void check_sort(const std::vector<int> &array)

Consider using references

While this code works, there is still some room for improvement.  The easy thing to do to speed up the code is to simply use references like this:

std::vector<int> merge(std::vector<int> &array, unsigned int b, unsigned int c, unsigned int e) {

By having it &array instead of array you tell the compiler that it may use the passed object directly rather than making a copy.  This single change makes the code run about twice as fast on my machine.

Omit return 0

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so it is not necessary to put return 0; explicitly at the end of main.

There's more, but that's all I have time for at the moment.


Python 2 Stack and LinkedList implementation

Notes on LinkedList:

The import is unused.
It should allow creation of an empty list.
Normally a linked list inserts items after the last item. Maybe I'm confused by the way insert works, but it looks like in your case head is always the last inserted entry in the list, and the list is traversed from head backwards through history using .next.
delete should use search.

Notes on Stack:

self.data should be self.entries or something else descriptive.
prnt should be as_string or even __str__.
int(val) does not check whether something is an integer, it just tries to convert a value to an integer.
+, -, * and / are arithmetic, not binary, operators.
In Python 3 mathematical operators are modeled as functions.
is_integer, is_binary_operator and postfixEval should not be part of Stack - they are not fundamental to the stack in any way.


First, I suppose it would be cheating to just use a std::shared_mutex, right? :)

Second, it seems a little weird to declare uintmax_t writers for a variable that can only ever hold the value 0 or 1. But, on the other hand, the symmetry between readers and writers is kind of nice.

uintmax_t readers = {0}, writers = {0};

Strongly prefer to declare one variable per line. Also, I know some people like to write int i{0};, and of course the natural thing to write is int i = 0;, but your belt-and-suspenders approach is relatively unusual. Prefer

uintmax_t readers = 0;
uintmax_t writers = 0;  // or, bool has_writer = false;

explicit MySharedLock() {}

I am a big fan of this explicit zero-argument constructor! However, you should probably be in the habit of =defaulting things instead of {}.

if (writers != 0) {
  rw_cv.wait(lk, [this]() { return (this->writers == 0); });
}

Nit: A lambda that doesn't escape should generally just capture [&]. And you needn't write out this-> if you don't want to. So:

if (writers != 0) {
  rw_cv.wait(lk, [&]() { return (writers == 0); });
}

However, this could be more cleanly expressed as simply

while (writers != 0) {
  rw_cv.wait(lk);
}

lk.unlock();

unique_lock is an RAII type; it unlocks the controlled mutex automatically in its destructor. You don't need to (and therefore shouldn't) write .unlock explicitly in your code.

This implementation has the potential problem that it delegates all of the "queueing" logic to the mutex/cv themselves. It is possible that if customers show up as "reader, writer, reader, writer, reader, writer...", then the readers could starve out the writers, or even vice versa. The only way to fix this, AFAIK, is to implement some kind of a "queue" of waiters, so that each waiter knows exactly when it's at the head of the queue. (Imagine the ticketing system in a deli: "Now serving number 47!")

Inside reader_unlock, you have rw_cv.notify_all() — but I think that this could safely be changed to rw_cv.notify_one(). We know that nobody is waiting to read; therefore all waiters are writers; therefore at most one of them will actually be able to do any work right now; therefore it is sufficient to wake up just one of them.

(And of course by the time that guy wakes up, somebody new may have come in and stolen the lock. So even that guy might not get to do any work.)

However, what notify_all does do is transfer over all the waiters from waiting on the rw_cv to waiting on the rw_mutex. If std::mutex implements some kind of fair queueing system, this ensures that no writer will get starved for longer than one epoch-of-readers, because as soon as the epoch ends, all the writers will get woken up and transferred over to the mutex, so that their respective epochs-of-writers will happen bam bam bam one after the other.

Yeah, I think I've convinced myself that notify_all is actually the most effective thing to do here. But it probably deserves a code comment explaining why you think it's the right thing to do!

Finally, it's worth mentioning that the standard names for your methods (according to the standard SharedMutex concept) are:

read_lock     ->  lock_shared
read_unlock   ->  unlock_shared
write_lock    ->  lock
write_unlock  ->  unlock

There's no standard C++ name for the promotion of a held reader lock to a writer lock (which is deceptively tricky), nor for the downgrading of a held writer lock to a reader lock (which is trivial). You might think about whether you want to provide these operations, and if so, what the interface to them should be.


Find a value in a comma delimited String

This could be a better/cooler way:

return (parameter as string)?.Split(',').Contains(value as string) ?? (object)false;

Your example is so short that I don't know what else I could say. You are looking for a short solution, so here is one.


Inserting nodes into a singly linked list based on size of number

You don't need the else if(pointer.next == null) case, it's covered by if (!inserted).
Declare variables in as small a scope as possible to increase readability. inserted and pointer aren't needed until the while loop.
You can save a nesting level if you put your code into a insertSorted method, and then call printList afterwards in the calling method. That way, you can write the initial head insert as a guard clause and thus save the else.
You could also save the break by adding && !inserted to the while clause.
many of your comments just repeat the code they comment on, and are thus not really needed.
// Insert at end. is quite misleading, as the insert doesn't happen at the end of the list.

With all these changes, your code already looks a bit cleaner:

if (head == null || term.getNumber() > head.data.getNumber()) {
    insertAtHead(term);
    return;
}

Node pointer = head;
boolean inserted = false;
while (pointer.next != null && !inserted) {
    if (term.getNumber() > pointer.next.data.getNumber()) {
        insertAfter(term, pointer);
        inserted = true;
    }
    pointer = pointer.next;
}

if (!inserted) {
    //If not inserted it must be the smallest so add to the end.
    insertAfter(term, pointer);
}

You could also return early after inserting, and thus get rid of the inserted variable:

// guard clause for head insert

Node pointer = head;
while (pointer.next != null) {
    if (term.getNumber() > pointer.next.data.getNumber()) {
        insertAfter(term, pointer);
        return;
    }
    pointer = pointer.next;
}

//If not inserted it must be the smallest so add to the end.
insertAfter(term, pointer);

But you still have a separate case for the last insert which is a bit ugly. You should be able to get rid of it with something like this:

// guard clause for head insert

Node pointer = head;
while (pointer.next != null && term.getNumber() < pointer.next.data.getNumber()) {
    pointer = pointer.next;
}
insertAfter(term, pointer);


Vectorizing a complex nested for loop in R (running models on different subsets of a data set, subsetting the data differently for each loop)

I'm not familiar with BGLR but I think I can give some pointers.

First to your direct question - yes you can vectorise.  A simple approach is to use one of the apply functions.  lapply usually is a good fit for such loops.  However this is not a magic bullet and I would strongly suggest to review the code.

I think the main thing that slows you down - besides the time BGLR needs - is how R deals with memory.  The relevant properties are:

most objects need to be placed continuous in memory
memory isn't immediately freed - but R waits till it is necessary and does garbage collect then
the time when R creates a copy of memory is a bit tricky.  It is not when one writes an assignment - at this point the variable just holds a reference to the original data.  But as soon as a change on the data is performed it creates a full copy.

All this effects don't appear in a "clean" R session, but as memory clogs things get significantly slower - agreeing with your observation.

I see following issues in the code:

Growing lists
fold.Res and rep.Res are growing lists.  As grow them they need to be written anew.  This means first all the previous entries need to be copied (which can take some time) - but more important they can not be written in the same place as the new list takes more space.  This will create fragmented memory - meaning whenever R can't fit the new list where a whole from a previous was created it will first need to garbage collect and then maybe defragment memory.  I think this is the serious slow down you are experiencing.
Allocating lists unfortunately doesn't help, but with the apply functions like lapply this is also taken care of.

creating modified copies
You create phen2 and phen3 as copies - but you only modify and use column 2.  Meaning there is some unnecessary copying going on.  Also this will lead faster to some extra garbage collects as memory fills up.

possible side effects of BGLR
While the first runs are relatively free where to put their data, later may run into troubles finding suitable spots - causing again some superfluous memory cleanups.  This is not so easy to deal with.  I worked with stan which is quite the hog - and the best solution was to run it in separate R processes and save the results and the kill it - it was way faster than having these cleanups going on.  The main scripts would then just collect the files.  I described how I do it in my answer to: Using doParallel to cycle through *.rds files (specifying how to do it outside doParallel).

to style
It is a bit confusing that you sometimes refer to columns by name and sometimes by column number.  This makes things harder to read than necessary.  I would suggest always using the name approach.

Those apply functions are awkward to write.  Personally I would consider to rewrite it to use dplyr - in particular piping and do.  However that may be to much work.


Using a TreeSet effectively

Since you are already using a TreeSet as the underlying data structure, you need not check if it contains the incoming number val or not in addNum(int) as any Set implementation will not store duplicate values. Also, to skip the first element in the TreeSet, you can do:

int start = streamNums.first();
Iterator<Integer> streamIter = streamNums.tailSet(start, false).iterator();

This avoids having to next() on the Iterator manually.

Inverting ifs

public List<Interval> getIntervals() {
    ArrayList<Interval> buffer = new ArrayList<Interval>();
    if(!streamNums.isEmpty()) {
        // ...
    }
    return buffer;
}

You can reduce one level of nesting if you simply returned a new ArrayList first:

public List<Interval> getIntervals() {
    if(streamNums.isEmpty()) {
        return new ArrayList<>();
    }
    List<Interval> buffer = new ArrayList<>();
    // ...
    return buffer;
}

Interfaces over implementations and type inference

As illustrated above, buffer can be declared as a List instead of ArrayList, and at least you are not making the same mistake in the method return type declaration. Also, since Java 7, you can rely on type inference to eliminate mentioning the generic type a second time, by using the 'diamond operator' <>.

Java 8 stream-based processing

Since you are on Java 8, you can look towards its stream-based processing capabilities as the appropriate way of solving your problem. It's relatively simple to adapt your solution to reduce an integer stream to a List<Interval>, or more specifically to create a Collector out of your solution:

public class TreeInterval implements Collector<Integer, TreeInterval, List<Interval>> {

    private final TreeSet<Integer> cache = new TreeSet<>();

    @Override
    public BiConsumer<TreeInterval, Integer> accumulator() {
        return (ti, integer) -> ti.cache.add(integer);
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.singleton(Characteristics.UNORDERED);
    }

    @Override
    public BinaryOperator<TreeInterval> combiner() {
        return (a, b) -> { a.cache.addAll(b.cache); return a; };
    }

    private List<Interval> toResult() {
        if (cache.isEmpty()) {
            return new ArrayList<>();
        }
        List<Interval> buffer = new ArrayList<>();
        int start = cache.first();
        int end = start;
        Iterator<Integer> iterator = cache.tailSet(start, false).iterator();
        while (iterator.hasNext()) {
            int i = iterator.next();
            if (i == end + 1) {
                end = i;
            } else {
                buffer.add(new Interval(start, end));
                start = i;
                end = i;
            }
        }
        buffer.add(new Interval(start, end));
        return buffer;
    }

    @Override
    public Function<TreeInterval, List<Interval>> finisher() {
        return TreeInterval::toResult;
    }

    @Override
    public Supplier<TreeInterval> supplier() {
        return TreeInterval::new;
    }
}

In summary, a Collector needs to know how to:

supply an accumulator: represented by the supplier() method.
accumulate an Integer: represented by the accumulator() method.
combine the accumulators into one: represented by the combiner() method.
extract the results of the last accumulator to the required type: represented by the finisher() method. In turn, your solution is used as a method reference within this.
provide a set of characteristics that describes itself, for potential optimization: represented by the characteristics() method.

For illustration, this is how it can be used:

public static void main(String[] args) {
    IntStream.of(1, 3, 7, 2, 6)
        .boxed()
        .collect(new TreeInterval())
        .forEach(System.out::println);
}

// Output
[1,3]
[6,7]

Construct an IntStream with the values 1, 3, 7, 2, 6.
Box it into a Stream<Integer>.
Collect the values using an instance of TreeInterval.
For each Interval, print it using System.out.println(Object).


There's not a lot to review here.  It's Valgrind clean, though that's not difficult to achieve.

Certainly consider closing stream 3, unless you want to keep a means to emit unprefixed stderr messages.

One shortcoming is that the shell won't wait for sed to finish when it terminates.  If the last process's output is still being filtered at this point, then you may fail to capture it - I observed this (repeatably) when running the program in Emacs compilation-mode.

One way you can improve on this if you're using GNU sed is by passing -u ("unbuffered") flag to sed.  If you don't have GNU sed but do have GNU coreutils, then the stdbuf utility could make sed line-buffered for you:

stdbuf -oL -iL sed 's/^/ERROR: /'

With any sed, we could (and should) close stderr when we terminate and wait for sed to finish to be sure of catching all error output.

Modified code

#!/bin/bash

exec 3>&2
exec 2> >(sed -u 's/^/ERROR: /' >&3)
exec 3>&-
# shellcheck disable=SC2064
trap "exec 2>&-; wait $!" EXIT

echo stdout
echo stderr >&2


Python: Use of class methods to change data

It might be best to move
today = datetime.today().date()
since = datetime(today.year, 1, 1)

into the class's __init__. As it is, the code will just be run once when the module loads, whereas it would make more sense to work out the date when you construct Toggl.
I'd also say that having two methods for what is essentially the exact same task could be streamlined. Perhaps something like this?
import math

# Default page size in the Toggl API.
PAGE_SIZE = 50

class Toggl:
    def __init__(self):
        today = datetime.today().date()
        since = datetime(today.year, 1, 1)
        self.data = []
        self.total_calls = None
        self.params = {
            'workspace_id': '5604761',
            'since': since,
            'until': today,
            'user_agent': 'john@doe.com'
        }

    def fetch_page(self, page_number):
        params = self.params
        params['page'] = page_number
        r = requests.get('https://toggl.com/reports/api/v2/details',
                         params=params,
                         auth=('APIKEY', 'api_token'))
        r.raise_for_status()
        return r.json()

    def retrieve_data(self):
        r = self.fetch_page(1)
        self.data = r['data']
        pages = self.total_pages(r['total_count'])
        for i in range(2, pages + 1):
            r = self.fetch_page(i)
            self.data += r['data']

    def total_pages(self, total_count):
        return math.ceil(total_count / PAGE_SIZE)

In particular, any "magic number" constants should be taken out and put at the top as constants (by convention in SCREAMING_SNAKE_CASE). I tweaked the function names to be more descriptive, and replaced first_api_call and make_subsequent_calls with a function that doesn't affect the state: instead it just makes a call to fetch the required page and retreive_data decides what to do with it. I don't think there's anything inherently wrong with doing it as you did though, I just personally thought fetch_page seemed cleaner and reduced duplication.
You can simplify the calculation to work out how many pages you need using math.ceil as I demonstrate above too: for example 101 / 50 = 2.02, which is mapped to 3 by math.ceil.
To make the code even better, you could avoid storing the API key hard coded: take it as a parameter in the constructor and store it in self. You could also take since and today as parameters so the user can choose the range that they want to obtain.


Using CanBuildFrom will help you here. What you need is an implicit CanBuildFrom[M[K, T], (K, T), M[K, T]] in scope, which will be provided by the standard library if it is possible to construct instances of the correct types.

import scala.collection.generic.CanBuildFrom

implicit def mapUpdatedFunctor[M[KT, TT] <: Map[KT, TT], K, T]
  (implicit cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]]) = {
  new UpdatedFunctor[M[K, T], K, T] {
    override def upd(a: M[K, T], k: K, t: T): M[K, T] = {
      val builder = cbf()
      builder ++= a.updated(k, t)
      builder.result()
    }
  }
}

scala> m.upd("A", "2")
res1: scala.collection.immutable.Map[String,String] = Map(A -> 2)

scala> sm.upd("A", "2")
res3: scala.collection.immutable.SortedMap[String,String] = Map(A -> 2)

I actually answered a similar question recently using Maps and updated on SO.


Expanding a bit on what the first answer mentioned: There are no Quiz, Question etc. classes.

Your current code has this data:

data = [{
  'question': 'What does the fox say?',
  'hints': ['not the sound of cat', 'not the sound of dog'],
  'answer': 'Its a mystery',
  'category': Category.PUZZLE,
  'score': Score.BAD
}, {
  'question': 'What is the worst case run time of binary search of n elements?',
  'hints': [
    'Think about the best case',
    'Would need to search exhaustively until one element'],
  'answer': 'Log(n) base 2',
  'category': Category.CS,
  'score': Score.BAD
}];

So it is a list of objects of this:

Question - String
Hints - array of String
Answer - String
Category - enum value
Score - enum value

This looks like the start of a Question class. But wait, how/why does a Question have a Score? What does it mean that the score for a question is "Bad"? That depends on how you answer that question, doesn't it? I would remove that from this data, that value belongs elsewhere. You could possibly have some "points" integer value in the data to indicate how many points a question is worth though.

You say that you are not looking to make your program give the points, but the user to honestly give the points. This is good, and reminds me about Anki Flashcards (although Anki doesn't have hints AFAIK).

  TODO: Find a way to persist the questions with updated score. Make the questions with lower score come first.

Ah, this is where the score comes in again. It's important to distinguish between a Question and the user's answer to a question. Maybe your system should support multiple users that should be able to answer different things? Then you need to connect each question that a user has answered to a score.

So, besides the Question class that I've already mentioned, you could have some more things:

UserAnswer (contains reference to Question and to a Score), a list of UserAnswers is basically a user's progress, so you could load/save multiple of these for each "Lesson" a user has ongoing/completed.
Quiz (contains a list of question, might not be necessary though as you have a category so you could filter the list of all questions based on a category)
Category can be a string instead of an enum, as I don't see a reason to programmatically hard-code a limit of possible categories

Also, I would strongly recommend to keep your data as a file or in a database and not inside your code.


Compare 2 arrays and preserve the row number

The stock managing system needs to preserve the order of row number (orderline) when you do the returns, but don't send the items that are not refunded.

If that's the requirement, then you should store the row number in the database at the time that the order is placed.  The problems that you are having come from trying to rebuild this information later.  If you want something to be persistent, store it.  You would only want to build it on the fly if you want it to change with other changes.  But in this case, that's explicitly not what you want.

This would be easier to answer if you included more code.  For example, how do you write to your database?  I'm suggesting a change in that.  How do you read from your database?  I'm suggesting that you read another column.  How do you build your data structures?  They might change as well.

In the following:

    foreach ($creditmemo->getAllItems() as $key => $item) {

            //if item is inside a grouped element, i.e 2-7 put the orderline at 2 then the next one at 8
            foreach($result as $val){
                if(strpos($val,"-")){
                    $piece = explode("-", $val);
                    if(($piece[0]) == $i){
                        $orderline = $piece[0];
                        $i = $piece[1] + 1;

                    }
                }
            }
//if item is single
            if(in_array($i, $result)){
                $orderline = $i+1;
                $i++;
            }
            else{
                $orderline = $i;
            }

You could just say

    foreach ($creditmemo->getAllItems as $item) {
        $orderline = $item->getOrderLine();

Of course, this adds additional work when inserting into the database, but since you don't provide that, we can't help you make changes to it.  Nor can we help with the changes to the $item object, as we don't see how it's built.


Nullable
Your fields are optionals: you put a ? after the type.
This means every time you need to access them, you need to check if it is null...
If you want the fields to be always present, throw the NullPointerException when findViewById doesn't return a view.
Then you can make your field not nullable and you can remove all the (now) redundant checks...
oneline function
override fun getLayout(): Int {
    return R.layout.input_text_layout
}

This function doesn't need 3 lines of attention...
Change it to one:
override fun getLayout(): Int = R.layout.input_text_layout

you could remove the return-type as well:
override fun getLayout() = R.layout.input_text_layout

init
Personal choice:
I like to make everything as short as possible.
This can be done by declaring the fields straight away instead of in the init block:
class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {

    var onInputOkListener: OnInputOkListener? = null

    var colorError: Int = Color.RED
        set(colorError: Int) {
            field = colorError
            error!!.setTextColor(colorError)
        }

    private var input: EditText = view.findViewById(R.id.input)!!
    private var error: TextView = view.findViewById(R.id.error_text)!!

    init {
        error!!.setTextColor(colorError)
    }
}

also
We can make the code above a bit simpler by using also:
also is a function which is called upon a variable (called the receiver).
also will return the receiver and accepts a lambda as parameter.
Inside that lambda, it gives one parameter: the receiver.
Therefor the following code:
class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {
    private var error: TextView = view.findViewById(R.id.error_text)!!

    init {
        error!!.setTextColor(colorError)
    }
}

can be reduced to:
class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {
    private var error: TextView = view.findViewById(R.id.error_text)!!
        .also{ v: TextView -> v.setTextColor(colorError) }
}

And if there is only one param, it can be accessed using it:
class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {
    private var error: TextView = view.findViewById(R.id.error_text)!!
        .also{ it.setTextColor(colorError) }
}


Algorithm for two languages that merges and sorts two arrays without mutating one

Python doesn't use semicolons at the end of a line.
The function ParseListA does nothing that the built-in function sorted doesn't do already.  Remove it.
In MergeSort, you can use the built-in function any to make sure you have at least one zero in ListB, like this:

if not any(i==0 for i in listB):
    raise ValueError("Needs zeros")

These two lines replace all the code beginning with zeroCount=0 and ending with return;.  The return statement is, incidentally, unreachable code since it follows a raise statement.
At the end of MergeSort, you concatenate the two lists and then sort them.  If you are going to do that, the initial sort of listA is redundant.

When all is said and done, the function ParseListA is gone and MergeSort is only four lines long.  Only one sort operation is required:

def MergeSort(listA, listB):
    if not any(i==0 for i in listB):
        raise ValueError("Needs zeros")
    newB = [i for i in listB if i != 0]
    return sorted(listA + newB)


Don't reinvent the wheel

For getting the files with a specific extension you should use glob:

xmlFiles = glob.glob('*.xml')

(Note that this will work relative to the current path.)

Avoid code duplication

You have some serious code duplication going on, replace it my appropriate code like:

#I don't really know the semantics of your paths so you should rename this accordingly
allowedPaths = 'ABCDEFGHI'
for filename in filelist:
    for character in allowedPaths:
        if character in f[-6:]: shutil.copy(os.path.join(path, f),
                                            os.join.path(path, r"folder" + character))

Magic numbers

Avoid these magic numbers by replacing them with "constants"

PREFIX_LENGTH = 31
POSTFIX_LENGTH = 6
#...
os.rename(os.path.join(path, f),os.path.join(path, f[PREFIX_LENGTH:]))
#...
if character in f[-POSTFIX_LENGTH:]:


The conversion of the code isn't that easy because of two key differences between PHP and ASP.NET:

.NET doesn't do Unix timestamps, so you'll have to introduce a conversion from DateTime to timestamp.
ASP.NET doesn't set the current directory to your application's directory, so relative paths aren't going to point to files existing in your web application.

So all code you have there is relevant. Not shorter, but more readable and less repetitive is the following:

using System.IO;

public static string AssetTimestamp(string filename)
{
    string filePath = HttpContext.Current.Server.MapPath(filename);
    string absoluteUri = System.Web.VirtualPathUtility.ToAbsolute(filename);

    if (!File.Exists(filePath))
    {
        return absoluteUri;
    }

    DateTime dt = File.GetLastWriteTimeUtc(filePath);
    int unixTimestamp = (int)(dt.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
    return absoluteUri + "?" + unixTimestamp;
}


Is this proper usage of "safe publication"?

Chapter 3.5. Safe Publication in Java Concurrency in Practice contains a very similar example. To cut a long story short: it's not thread safe. ThreadB could see its bag reference as null. Furthermore, ThreadB could see its bag reference as not null, but the referenced Bag's item field could be seen as null by ThreadB.

On my machine sometimes it's an endless loop but I can't reproduce the second scenario when just the Bag.item is null.

Please note that making the Bag.item field final does not make it thread-safe, access to ThreadB.bag also have to be synchronized:

public class ThreadB extends java.lang.Thread {
    private Bag bag;

    public synchronized void setBag(Bag bag) {
        this.bag = bag;
    }

    @Override
    public void run() {
        try {
            while (true) {
                synchronized (this) {
                    if (bag != null) {
                        System.out.println(bag.getItem());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Or you can use an AtomicReference:

public class ThreadB extends java.lang.Thread {
    private final AtomicReference<Bag> bag = new AtomicReference<Bag>();

    public void setBag(final Bag bag) {
        this.bag.set(bag);
    }

    @Override
    public void run() {
        try {
            while (true) {
                Bag bag = this.bag.get();
                if (bag != null) {
                    System.out.println(bag.getItem());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Some other notes:

1,

public String Item() {
    return item;
}

From Code Conventions for the Java Programming Language:

  Methods should be verbs, in mixed case with the first letter
  lowercase, with the first letter of each internal word capitalized.

So, this method should be called getItem:

public String getItem() {
    return item;
}

2, According to the same document, chapter File Organization, methods should appear after constructors:

public class Bag {
    private String item;

    public Bag(String item) {
        this.item = item;
    }

    public String getItem() {
        return item;
    }
}


Using the ConcurrentBag as an object pool for an ASP.NET application

Instead of

    if (initializeCount > 0)
{
    int counter = 0;
    while (counter++ < initializeCount)
    {
        _objects.Add(_objectGenerator());
    }
}

I would prefer a for loop for initial initialization:

for (int i = 0; i < initializeCount; ++i)
{
    _object.Add(_objectGenerator());
}

The biggest problem however is that GetObject will return a new object anyway - even if the pool is empty. This violates your requirement:

  The object pool must have a maximum size restriction, so that callers of GetObject wait in line to get an instance of the pooled object.

As mentioned by Scott in his comment to your question you should use Take to retrieve an item as it will block until one is available.
You might want to consider providing some sort of "object resetter" action which gets called whenever you have retrieved an item from the pool which puts the item into a clean initial state automatically.


As for your question about NaN: this is also a situation where conversion to decimal is likely to be problematic. Assuming that you resolve that problem, the question then is what to do about it in the comparison.

It depends on the goals of your comparison. The semantics of NaN are "this thing isn't even a number, so asking which one is bigger is a nonsensical question", and therefore any operation on NaN is false. That means that NaN is not greater than any number, not smaller than any number and not equal to any number, including itself. If that's acceptable for your comparison purposes then that's the semantics you should implement.

Those semantics are not acceptable for sorting. If the comparison is being used in a comparison sort then the comparison is required to produce a total consistent order. It must be reflexive -- every number must equal itself. It must be antisymmetric -- if a < b is true then b < a must be false. And it must be transitive -- if a < b is true and b < c is true then a < c must be true. The usual way to deal with NaNs is to say that all NaNs are equal to each other -- achieving reflexivity, and that all NaNs are smaller than every non-NaN -- achieving antisymmetry and transitivity.

And don't forget that you'll need to deal with positive and negative infinities.


Text box intuitive user-interaction using focus listeners

It is in fact pretty good code, just some small nitpicks:
Order
The fields should go before the methods; in fact, it should be near the front of the class, only after the public static final and private static final fields.
Conventions
This piece of code:

private void jTextFieldFocusGained(FocusEvent evt) {
    if(jTextField.getText().equals(TEXT_DEFAULT))
    {
        jTextField.setForeground(FOCUSED_COLOR);
        jTextField.setText(TEXT_FOCUSED);
    }
}
private void jTextFieldFocusLost(FocusEvent evt) {
    if(jTextField.getText().equals(TEXT_FOCUSED))
    {
        jTextField.setText(TEXT_DEFAULT);
        jTextField.setForeground(COLOR_DEFAULT);
    }
}

In the if statement, if you don't put a new line before the method brace, you shouldn't put a new line before the if brace.

You are inconsistent in order. You set the foreground color first in one, and the text in another. Be consistent.

You should put 2 new lines between methods, and any non-related lines.

It is recommended to have a space after the if.

Naming
evt should be event: names are concise names that shouldn't be abbreviated.
jTextField could just be textField. I know you are using a JTextField, but textField is a more readable name.
Final Code:
private final String TEXT_FOCUSED = "";
private final String TEXT_DEFAULT = "Type text here...";
private final Color COLOR_FOCUSED = Color.BLACK;
private final Color COLOR_DEFAULT = Color.LIGHT_GRAY;

private void textFieldFocusGained(FocusEvent event) {
    if (textField.getText().equals(TEXT_DEFAULT)) {
        textField.setForeground(FOCUSED_COLOR);
        textField.setText(TEXT_FOCUSED);
    }
}

private void textFieldFocusLost(FocusEvent event) {
    if (textField.getText().equals(TEXT_FOCUSED)) {
        textField.setForeground(COLOR_DEFAULT);
        textField.setText(TEXT_DEFAULT);
    }
}


Try to use named group. As your pattern becomes more complex, it will get harder to maintain.

@"(?:{[yY][eE][aA][rR])([+-])(\d+)}"
var operation = m.Groups[1].Value;
int.TryParse(m.Groups[2].Value, out int value);

PlaceholderDefinition implementation requires way too much boilerplate code to use:

 foreach (var placeholder in RegisteredPlaceholders)
  {
      var match = new Regex(placeholder.Pattern).Match(content);
      while (match.Success)
      {
          content = content.Remove(match.Index, match.Length).Insert(match.Index, placeholder.Apply(match));
          match = match.NextMatch();
      }
  }

It could be boiled down to: content = placeholder.Apply(text);
There is no need to use Match.NextMatch & string.Remove, when you can use Regex.Replace
_logic seems to be a poorly chosen name. While it describes the essence, but not its concrete job. You should name Func with "Selector, factory, builder, ...", and prefix it with a noun ("result, replacement, ...") and the private member prefix _ (if this is the convention, you choose to follow).

Modified PlaceholderDefinition class:

public class PlaceholderDefinition
{
    public string Name { get; }
    public Regex Pattern { get; }

    private readonly Func<GroupCollection, object> _replacementSelector;

    public PlaceholderDefinition(string name, string pattern, Func<GroupCollection, object> replacementSelector)
         : this(name, new Regex(pattern), replacementSelector)
    {
    }
    public PlaceholderDefinition(string name, string pattern, RegexOptions options, Func<GroupCollection, object> replacementSelector)
         : this(name, new Regex(pattern, options), replacementSelector)
    {
    }
    public PlaceholderDefinition(string name, Regex pattern, Func<GroupCollection, object> replacementSelector)
    {
        this.Name = name;
        this.Pattern = pattern;
        this._replacementSelector = replacementSelector;
    }

    public string Apply(string input) => Pattern.Replace(input, m => _replacementSelector(m.Groups).ToString());
}

There is various overloads of ctor to accommodate different needs, like the one suggested by @t3chb0t. Feels free to add more, if it help you to keep the declarations as clean as possible.

And, the rest of the code:

var text = "Today is {today}. The year is {year}. Last year was {year-1}.";
var placeholders = new List<PlaceholderDefinition>();
placeholders.Add(new PlaceholderDefinition("Today", @"{today}", RegexOptions.IgnoreCase, _ => DateTime.Today.ToShortDateString()));
placeholders.Add(new PlaceholderDefinition("Year", @"{year}", RegexOptions.IgnoreCase, _ => DateTime.Today.Year));
placeholders.Add(new PlaceholderDefinition(
    "YearAddition",
    @"{year(?<sign>[+-])(?<value>\d+)}",
    RegexOptions.IgnoreCase,
    g => DateTime.Today.Year + int.Parse(g["sign"].Value + g["value"].Value)
));

foreach (var placeholder in placeholders)
{
    text = placeholder.Apply(text);
}

The _replacementSelector takes in GroupCollection, so we can skip writing m => m.Group..., and the object TResult allows us to skip the necessary .ToString() or a parenthesis on binary operation.
int.Parse will parse number prefixed by a + sign as positive number, allowing us to skip the ternary operation.


Rendering logos for guitars and basses listed in a database

The database should know which as bass

Type
ID
name

1 guitar
2 bass

Brand
ID
name
image

where you link the Brand to the Type and a Brand

TypeBrand
IDtype
IDbrand

select Brand.Name
from Brand
join TypeBrand
  on Brand.ID = TypeBrand.IDbrand
 and TypeBrand.IDtype = 2