Matrix Multiplication Python -- Memory Hungry

I'm not sure I completely follow exactly what processing you're doing to your data. The comments in the code suggest it's meant to be a matrix multiplication, the description you've provided above it suggests it's a cartesian product, but your code looks like does the sum of (flattened) outer products of corresponding rows. I'll proceed on the assumption that your code is doing the right thing, but hopefully you can clarify.

There are two general pieces of advice that apply here:

Separation of concerns. You're mingling code to parse your data with code to process it once it is parsed. Instead, parse everything into the appropriate data structures first, and then do the processing.
Use appropriate libraries and data structures. When you're doing linear algebra, that means numpy. Numpy is a dedicated, LA library that has heavily optimised routines for things like various matrix products, so you don't need to roll your own. Numpy arrays will also use quite a bit less memory than Python lists. However, what you're working with is labelled data (and some of it is labelled in two dimensions), which means the best data structure is probably a pandas dataframe - it's basically like your dict of strings to lists in pat_mRNA, but much more optimised, and fully compatible with numpy's matrix manipulations.

These things together will make your code easier to follow, more maintainable, and often both faster and shorter.

So, start by looking at your core data structure:

exp_mat = [line.rstrip().split('\t') for line in ccle]

This is a list of lists of strings. For most of the rows, you don't seem to care about column 0 at all. Column 1 contains row labels, and corresponding to keys in your dictionary pat_mRNA. The rest of it is numeric data, currently stored as strings. It also contains 'header' rows - you only keep one of those around, so presumably you only expect one to be in there. I'm guessing that is column labels, which a DataFrame lets you include directly in the same data structure.

The only trick parsing this into a DataFrame is that it is a little easier (and, apparently, more efficient) to swap the columns and rows from how you have them currently.  That will affect how it prints, and which methods you call to relabel things, but not much else. This is how I would parse it into a DataFrame:

data = pd.DataFrame()
headers = []
for line in ccle:
    row = line.rstrip().split('\t')
    if row[0] == 'Name':
         headers = row
    elif row[1] in pat_mRNA:
        data[row[1]] = [float(f) for f in row[2:]]

if headers:
   data.index = headers

Note that I have modified your conditions a little, since yours seemed slightly off. The else branch of your condition effectively says "if the zeroth column is "name" or the first column isn't a match, it must be a header" - I've changed it so that instead, an appropriate value in the zeroth column is a header, and a non-matching first column on is ignored.

I've maintained a temporary 'headers' list, because your code is currently robust against those appearing anywhere in the file. A better way to maintain that robustness would be if you know - or, preferably, can parse from your file before now - how many variables you have data for. Then you could do away with that headers list and do this:

data = pd.DataFrame(index=range(nvars))
for line in ccle:
    row = line.rstrip().split('\t')
    if row[0] == 'Name':
         data.index = row
    elif row[1] in pat_mRNA:
        data[row[1]] = [float(f) for f in row[2:]]

In either case, I am assuming that you have one header for each variable. If that's a bad assumption, you may need to adjust this code.

As an aside, as a matter of commonly-accepted Python style (and in accordance with PEP 8), I have placed all of the code for each branch of the if in indented blocks, even if it is only one line. At most, you should only put it immediately after the : if there is only one branch to the if (no else or elifs), and even then, consider an indented block anyway.

I would change pat_mRNA to also be a DataFrame. You could change how you currently build it, or you could just pass the whole dictionary you have at the moment into pd.DataFrame().

Once you've done that, you can use numpy to do your LA work. As written, your entire strange product becomes this:

dot_prod_total = sum(np.outer(data[key], pat_mRNA[key]).flat for key in data)

Which should be quite a lot faster than trying to do it by list comprehensions, and may use multithreading depending on how numpy is compiled.


Object pool pattern for asynchronous socket operations

Because you don't change

private int _size;
private Func<T> _factory;
private Stack<T> _cache;

private SpinLock _spinLock; //Use Queue<T> for first-in-first-out (FIFO)

you should make them readonly.

Correction after the comment of t3chb0t:

Don't make the SpinLock readonly. Further clarification: https://stackoverflow.com/a/9235028/2655508

  The underlying problem is that the C# compiler creates a copy of a readonly value type field when you call a non-static method on it and executes that method on the copy - because the method could have side effects that change the value of the struct - which is not allowed for readonly fields.

private T RentFromCache()
{
    var cache = _cache;

    if (cache.Count > 0)
    {
        T instance = _cache.Pop();

        if (instance != null)
        {
            return instance;
        }
    }

    return CreateInstance();
}

Here you are using var cache only for checking its Count property. I don't see a reason to not use the class level _cache directly. Using the class level variable directly won't confuse the reader of the code. The same applies to ReturnToCache() as well.


Best way to split array to two sub-arrays, with maximum absolute difference between them

Some ideas:

You can replace sumArray with IntStream.of(a).sum();.
Tests should be written using JUnit or another testing framework and named according to what they are testing.
Try to write the absolutely most simple test case you can think of rather than following the writer's instinct to vary the input. You want the mental arithmetic to verify your test results to be as simple as absolutely possible. Your tests should be easy to rewrite using just -1, 0 and 1.
shouldPartitionSingleElementListAtStart and shouldPartitionListWithMultipleIdenticalValuesAtStart tests would be useful.
What happens if the input is an empty list? It's up to you whether that should fail like (I think) it does now, but the case should be tested. You might even want to raise a custom NonPartitionableListException or EmptyListException in this case.
"Difference" is usually spelled out fully or, if shortened, written as "Diff" (two "f"s).
Variable names should be understandable at the point they are defined - it should not be necessary to see all their usages to understand what they do. So for example left could be called leftPartitionSum.
On a related note, findMaxDif might be clearer as getMaxPartitionDifferenceIndex. "find" is usually used when you want to return a "non-answer" in case no answer is possible, while "get" is usually used when you want the code to throw an exception if there is no answer.

Other than that my opinion is that this code is short, readable and performant.


Fetching environment variables — can I use pattern matching?

Using the ? for a boolean predicate is fine. At least it is what I would do in
Ruby and Elixir.

You won't be able to call exists?(env) in a guard clause so pattern matching does not win you much here.

You are calling :os.getenv() twice unneccessarily.
I'm not sure why you just want to convert 'false' to 'nil', here is a way:

defmodule Envvar do
  def get(env)
    do_get(:os.getenv(env))
  end

  defp do_get(false)
    {:env, nil}
  end

  defp do_get(result)
    {:env,result}
  end
end


public List<List<Integer>> permute(int[] num) {

I'd call num, numbers.  In fact, I try to always name collections with a plural.  Also, I write names out rather than abbreviate them.  It will make things much easier if you ever have to read the code in the future.

List<List<Integer>> res=new ArrayList<List<Integer>>();

It would be helpful here to explain why res is a list of lists.  Why not just a single list?  Maybe this would be obvious to me if you came up with a more descriptive name.  I'm guessing that res is short for result.  I would have probably named it permutations.

res.add(new ArrayList<Integer>()); // Add an empty list

When commenting, try to say why you are doing things rather than what you are doing.  E.g.  // Add an empty list so that the middle for loop runs.

This seems odd though.  You pass in an int[].  Why not make a list of integer arrays then?  If that makes something not work, comment on it so that you don't regress it later.

    for(List<Integer> nestedL : res)
    {

Note that res can contain all the permutations (of which there are \$n!\$).  This is what gives you your \$O(n!)\$ time.  Note that it's actually \$O(n^3n!)\$ time, but the \$n!\$ eats the \$n^3\$.

        for(int j = 0; j < nestedL.size() + 1 ;j++)

This would be better if you pulled the nestedL.size() + 1 out of the comparison.

        for(int j = 0, n = nestedL.size() + 1; j < n ; j++)

It seems like you should be able to do a bit better here.  There's a lot of list creation and copying, which seems unnecessary.

            nestedL.add(j,num[number]);
            List<Integer> temp = new ArrayList(nestedL);
            curr.add(temp);
            nestedL.remove(j);

Ok, you add an element to a list; then you copy the list; save the copy; finally, you remove the added element from the original list.  Why not reorder things like so

            List<Integer> temp = new ArrayList(nestedL);
            temp.add(j, num[number]);
            curr.add(temp);

That saves a remove operation.

This also highlights a problem with the name number.  It's not a number from the num array.  It's an index to the array.  I'd name it either i or index.

public List<List<Integer>> permute(int[] numbers) {
    // we use a list of lists rather than a list of arrays
    // because lists support adding in the middle
    // and track current length
    List<List<Integer>> permutations = new ArrayList<List<Integer>>();
    // Add an empty list so that the middle for loop runs
    permutations.add(new ArrayList<Integer>());

    for ( int i = 0; i < numbers.length; i++ ) {
        // create a temporary container to hold the new permutations
        // while we iterate over the old ones
        List<List<Integer>> current = new ArrayList<List<Integer>>();
        for ( List<Integer> permutation : permutations ) {
            for ( int j = 0, n = permutation.size() + 1; j < n; j++ ) {
                List<Integer> temp = new ArrayList<Integer>(permutation);
                temp.add(j, numbers[i]);
                current.add(temp);
            }
        }
        permutations = new ArrayList<List<Integer>>(current);
    }

    return permutations;
}


Generators in Javascript; Project Euler #2

1) You have a few undeclared variables which means they become global. You want to use var (or let or const) always. Compare this:

var current = a = b = 1; // a and b are globals

To:

var current, a, b; // all variables are local
current = a = b = 1;

Same here:

sequence = fib_gen(); // not declared
even_fibs_total = 0; // not declared
cur = sequence.next().value; // not declared

Compare to:

var sequence = fib_gen();
var even_fibs_total = 0;
var cur = sequence.next().value;

2) Conventions:

Name your variables with camelCase instead snake_case.
Use === instead of == unless you know you really really need == (tip: you probably don't).
Always write if statements with braces, even if one line, for better readability and refactoring.

3) Generators are iterators, and iterators can be iterated with the for..of loop. If your environment supports generators it probably supports for..of:

function solution() {
  var evenFibsTotal = 0;

  for (var cur of fibGen()) {
    if (cur >= 4000000) {
      break;
    }
    if (cur % 2 === 0) {
      evenFibsTotal += cur;
    }
  }

  return evenFibsTotal;
}

4) If you have ES6 support (or compilation via Babel) you can use destructuring assignment to simplify the fibonnaci function:

function* fibGen() {
  var a = 1;
  var b = 1;
  while (true) {
    yield b;
    [a, b] = [b, a + b];
  }
}


Creating a wrapper class to use for mocking that uses IDisposable

Congratulations! You have successfully utilized the object-oriented design pattern known as the Adapter Pattern. I think that looks perfectly good. Though, I wouldn't check pop3 for null in the Dispose() method as it will be guaranteed to not be null by the constructors and the readonly field modifier:

public void Dispose()
{
    pop3.Dispose();
}


I went functional on this one (as usual).

First of all, i removed the dependency from the third party library. I haven't anything in particular against that, but if the problem can be resolved easily with the standard tools, why bloat your app?

Then, since the main function deals mostly with lists, I looked for a way that would let me transform the list, filtering and transforming freely: reduce is a natural fit.

Now i can check the immediate list against a predicate (the filtering method you pass in) and recursively do the same on the list of childrens. The result of this filtering determines the final output structure.

Here's an implementation:

var data = [
    {
    name: 'a1', children: [
        {
        name: 'b1', children: [
            { name: 'gap' }, { name: 'bar' }
        ]
      }
    ]
  },
  {
    name: 'a2', children: [
        {
        name: 'b2', children: [
            { name: 'foo' }, { name: 'gap' }
        ]
      }
    ]
  }
];

function filterData(data, predicate) {

 // if no data is sent in, return null, otherwise transform the data
 return !!!data ? null : data.reduce((list, entry) => {

  let clone = null;
  if (predicate(entry)) {
   // if the object matches the filter, clone it as it is
   clone = Object.assign({}, entry)
  } else if (entry.children != null) {
   // if the object has childrens, filter the list of children
   let children = filterData(entry.children, predicate)
   if (children.length > 0) {
    // if any of the children matches, clone the parent object, overwrite
    // the children list with the filtered list
    clone = Object.assign({}, entry, {children: children})
   }
  }

  // if there's a cloned object, push it to the output list
  clone && list.push(clone)
  return list
 }, [])

}

var result = filterData(data, function(item) {
    return item.name === 'foo';
});

console.log(JSON.stringify(result, null, 2));

edit: I added some comments to the code. Shouldn't be needed, but it clarifies the steps.


Project Euler #6 (Sum square difference) in Swift

First, I would suggest that the solution6() function takes a parameter for
the upper bound, and returns the result instead of printing it (as also
suggested by @user16547 while I was writing this answer):

func solution6(upper : Int) -> Int {
    let firstInts = [Int](1 ... upper)
    let summed = firstInts.reduce(0) { $0 + $1 }
    let summedSquared = summed * summed
    let squaredSummed = firstInts.reduce(0, combine: squaresSummed)
    return summedSquared - squaredSummed
}

printTimeElapsedWhenRunningCode("Sum square difference") {
    let answer = solution6(10_000)
    println(answer)
}

Then you use an auxiliary function squaresSummed for computing the second
sum, but not for the first (and the name of that function is not very descriptive). In my opinion it is easier to understand if the shorthand notation is used
for both summations:

func solution6(upper : Int) -> Int {
    let firstInts = [Int](1 ... upper)
    let summed = firstInts.reduce(0) { $0 + $1 }
    let squaredSummed = firstInts.reduce(0) { $0 + $1 * $1 }
    return summed * summed - squaredSummed
}

For an upper bound of 10,000, this took about 0.001 seconds on my MacBook Pro in Release mode.

But [Int](1 ... upper) creates an array of all that numbers, which costs time
and memory. If you use a range instead

func solution6(upper : Int) -> Int {
    let firstInts = 1 ... upper
    let summed = reduce(firstInts, 0) { $0 + $1 }
    let squaredSummed = reduce(firstInts, 0) { $0 + $1 * $1 }
    return summed * summed - squaredSummed
}

the time is reduced to about 0.0002 seconds. This is about the same
time needed for a simple loop

func solution6(upper : Int) -> Int {
    var summed = 0
    var squaredSummed = 0
    for i in 1 ... upper {
        summed += i
        squaredSummed += i * i
    }
    return summed * summed - squaredSummed
}

which would be the most straightforward implementation of the algorithm.

Of course the fastest and shortest solution to the PE problem would be to

   Find the closed formula for 1 + 2 + ... + n and 1^2 + 2^2 + ... + n^2 and use that instead of a loop.


SELECT distinct Movie.title, Rate.stars

You should rarely use the DISTINCT keyword.  In this particular case it's unnecessary and may do the wrong thing.  What you want to do is to return the highest star rating for a given movie title:

SELECT Movie.title, MAX(Rating.stars)

There's the title and we use the MAX keyword to make sure that it's the highest stars.  More on when we can use MAX later.

FROM Movie, Rating,
(SELECT * FROM Rating R1 WHERE not exists (SELECT mID FROM Rating R2 WHERE R1.stars < R2.stars and R1.mID = R2.mID)) as Rate
WHERE Movie.mID = Rate.mID and Rate.stars = Rating.stars

We can make this simpler:

FROM Movie, Rating
WHERE Movie.mID = Rating.mID

No subselects required.

GROUP BY Movie.title
ORDER BY Movie.title;

The GROUP BY will allow us to use MAX.  It says to return only one row per Movie.title value.  The other columns need to be aggregated with grouping functions, like MAX.  You already had the ORDER BY clause and presumably it's correct.


pickup is defined, but never used.

You should terminate your statements with semicolons consistently.


JIT content rendering

There is no observable difference in performance (after setting up) between using an image or a canvas to render context. As rendering content can be many times faster than downloading content it is a very good method of increasing performance at startup.

Some warnings.

Clean up state

Using the 2D context requires that its state be maintained. Be sure to clean the state when you no longer have a need as the state can occupy a lot of memory.

eg

ctx.filter = url("#element-id"); // can consume lots of memory and if animated ongoing CPU/GPU resources
ctx.fillStyle = ctx.createPattern(ctx.canvas,"repeat"); // requires copy of source image
ctx.strokeStyle = ctx.createPattern(image,"repeat"); // requires copy of source image
ctx.font = "128px myFancyFont"; // a loaded font

ctx.beginPath(); // lets create a very long path
for(var i = 0; i < 10000; i ++) { ctx.lineTo(Math.random() * 100, Math.random() * 100) }
ctx.stroke();  // You may be done with the path but its still there
               // ready for another stroke or fill

All the above (and there are more) require considerable memory resources. They also prefer these resources to be readily available to the GPU so if possible will occupy GPU RAM (shadowed from RAM)

Running out of free GPU RAM is a the biggest performance killer for the browser's rendering engines as it begins to swap resources in and out of GPU RAM to complete the render (GPU bus thrashing, or GPU RAM thrashing). Do your best to keep usage as low as possible by always releasing unneeded resources.

I would make some changes

function createAndRenderResource(renderFunc, ...args)
    const img = document.createElement("canvas");
    const ctx = img.getContext("2d");
    img.width = 24;
    img.height = 24;
    ctx.save(); // save default low memory state
    renderFunc(ctx, ...args); // add the content
    ctx.restore(); // cleanup releasing any unneeded RAM or connected processes
    return img; // you can not remove the 2D context once made
                // it remains in memory
}

function render(ctx, color) {
    ctx.beginPath();
    ctx.fillStyle = color;
    ctx.arc(12, 12, 12, 0, Math.PI * 2, true);
    ctx.fill();
}

const images = [
     createAndRenderResource(render,"red"),
     createAndRenderResource(render,"green"),
     createAndRenderResource(render,"blue"),
]

Powers of two

The canvas size can be anything, an image can be anything. But the way GPU hold images is optimized for very fast access. Images are always stored in sizes that are powers of 2 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096... etc

To know the memory foot print of any resource within the GPU find the nearest power of two above the width or height.

For example a 48 by 12 (576 pixels) image will occupy, nearest width is 64, and nearest height is 16 64 by 16 (1024 pixels) almost double the amount of Ram needed to hold the image in GPU RAM.

Dead pixels.

The code you have given creates a canvas that is 24 by 24 pixels. The memory footprint on the GPU is thus 32 by 32 pixels. 77% per pixel dead (unused) RAM.

You can make things better by using a single canvas and drawing multiple sprites to that. A canvas 128 by 128 can hold 25 sprites that are 24 by 24 and have room for a one pixel boundary between them to stop pixel bleeding due to linear lookups. This reduces the dead pixel rate to ~14%

Note: the same power of two rule applies to Images.

This will only effect your code if you are getting close to the GPU memory limits imposed by the browser. The more dead pixels the quicker you get to that limit for the same resources.

For large numbers of variable sized sprites use a single canvas near a power of two size I use a sprite lookup as a property, attached to the image / canvas being used, that stores the position and size of each sprite.

// a sprite is {x,y,w,h} the position on the sprite sheet.
// sprites is an array of sprites. and spriteIndex is which to render
function drawSprite(img, spriteIndex, x,y){
    const spr = img.sprites[spriteIndex];
    ctx.drawImage(img, spr.x, spr.y, spr.w, spr.h, x, y, spr.w, spr.h);
}

BTW you break the codeReview site rules by not supplying working code, you have given example of what your working code does. It is incomplete and non functioning.


You could always clean it up using jQuery tmpl

https://github.com/BorisMoore/jquery-tmpl

You would just define the HTML of the templates, and then you could add them to the rows.


Abstract factory pattern for a system modelisation

First of all: You got it nearly right.

One thing in your implementation deviates from the standard implementation:

@Override
public Composant getComposant(String composant) {
    if(composant.equalsIgnoreCase("Boutton")) return new Boutton();
    else if(composant.equalsIgnoreCase("Menu")) return new Menu();
    return null;
}

You parameterize your factory methods with a string. Don't do that in this case. Passing a parameter to a factory may be possible but the products should be "strong" related to each other. Everybody who wants to know what your factory can produce should see it by the method signatures provided by the abstract factory and not guess (or read in the documentation... urgh). If you want to produce two different items, create another factory method. For a factory "FactoryX" this should look like this:

@Override
public Button createBoutton() {
    return new BouttonX();
}

@Override
public Menu createMenu() {
    return new MenuX();
}

One other thing: the abstract Composant-class is irrelevant to the abstract factory in your case as far as I see. Furthermore it will bind you to a set of methods that "Menus" and "Bouttons" have in common. This would hinder you to configure special properties of "Bouttons" and "Menus". The two types may of course stay derived from Composant.

I thought about it a little bit when the use of parameters in the factory pattern may be appropriate. In the following example (in pseudo code) a LabelField or a LabelArea is returned which depends on the size of the given text.

@Override
public AbstractLabel getAbstractLabel(String text) {
    if (text.length > 120) {
        return new LabelArea(text); // multi line presentation
    } else {
        return new LabelField(text) // single line presentation
    }
}

The parameter is not technically connected to the return value but semantically. You can see the strong relationship between those return values. They were built to present text.


Climbing the Leaderboard: HackerranK, Terminated due to timeout

There are some important inefficient elements in the posted implementation.

Inserting into a sorted array

To insert Alice's next score into the array of sorted scores,
the posted appends Alice's score at the end and then sorts the array.
What's the typical time complexity of sorting an array?

   \$O(n \log n)\$

Is it possible to do better?

   When you have a list of sorted values, you can use binary search to find the position to insert a value so that the list stays sorted.

The general idea of binary search goes something like this: pick the middle position m of the array. Is it bigger than the value? Then pick the middle position between 0 and m. Or else if the value was smaller, then pick the middle between m and the end of the array. Follow the same logic, in each step dividing the interval to check by 2, quickly converging on the target position.

What would be the time complexity to find that position using binary search?

   \$O(\log n)\$

That's a lot faster than \$O(n \log n)\$.

By the way, since Alice's score only increases,
the range of values to search for the correct position shrinks,
so the fast solution just keeps getting faster for finding the higher scores.

By the way, once you found the right position, do you actually need to insert into the array?

   No, in this particular challenge, you could just overwrite the position with the new value.

Why is that even a question, why not just insert the value and be done with it?

   Inserting a value into an array typically requires copying the values that come after the insertion position, which is expensive. Depending on the programming language and how arrays work, a reallocation of the entire array (copying all elements) may also happen, which is even more expensive.

And keep in mind that we have to do this m times, where m is the number of scores of Alice.

What is the overall time complexity of the solution with sorting?

   \$O(m n \log n)\$

What is the overall time complexity when we replace sorting with binary search? (Without shrinking the search range, to keep the theory simple.)

   \$O(m \log n)\$

If we take into account the shrinking of the search range, then we can achieve a performance faster than \$O(m + n)\$.

Processing the two lists together

An alternative linear time solution is possible if we process the two lists together:

Compute the ranks of the leaderboard (see the next section of my answer)
Iterate over the scores of Alice, in increasing order
From the end of the leaderboard, find the next score that is  greater than or equal to Alice's current score

If that score is equal to Alice's, then Alice's rank is the same as of that score
Otherwise (the score is greater than Alice's), Alice's rank is 1 + the rank of that score

Repeat for all scores of Alice. Note that when looking for the next leaderboard score, you can continue from the position of the last one found, do not restart from the end

This algorithm visits all elements of the two arrays once, performing a constant number of operations for each. What is the overall time complexity?

   \$O(m + n)\$

This is not as good as using binary search that can skip many leaderboard scores at once, but probably fast enough for this exercise, and simpler to implement.

Computing the rank

The current implementation recomputes the ranks up until Alice's position for every single position.
That's unnecessary.
You could compute the ranks just once up front, and store in an array.
Then, once you know Alice's position, you could use the index of that position to find the rank directly.

Style

It's recommended to declare variables right before you need them.
For example i and rank are declared too early,
when they are only used after the sorting step.
The reason to delay declaration as much as possible is to reduce the possibility of mistakes: a variable is not defined yet, a use by mistake is likely going to crash badly and so you discover the problem early.
Otherwise it may get overlooked.

A common convention to improve readability is to add spaces around operators, after commas, before ( and after ), for example:

function ladder(arr1, arr2) {
  while (arr2.length) {
    let i = 0


Can this method be changed to remove all objects in one call?

There is no way to remove multiple objects from multiple tables in one statement and there shouldn't be (cascading foreign key constraints notwithstanding).

The problem is that Remove(int key) is a poor name for that function. Something like RemoveObjectInputsOutputsPropertiesAndGroups(int key) would be better. Similarly, I would have on idea what a RemoveChildren() function should do in this context.


A primitive folder listing implementation on Windows

Thous shalt not mix C/C++ unless you have a good reason to do so. Jokes aside, using pure C++ will lead more bug-free code (in terms of memory management etc.) especially since your statement

  What I've learned is to avoid using namespace std; and making the includes in alphabetical orders.

implies (to me) you are a newcomer. You're welcome, by the way. That being said, learning C way of doing things is really helpful, especially if you are not familiar with pointers etc. You will experience first hand, say why C++ smart pointers and containers are a thing.

My advice would be to study exactly why

  You should not mix C/C++ unless you have a good reason to do so.

What you are doing with this code is nothing but plain C (except iostream methods). I did not check your code thoroughly though. So why do you want to use C++? If you want to use C++, why do you write C code and compile as C++ (again, except iostream, which can be as well stdio.h)?

Since you are using Digital Mars, for which I can't find any standard compliance information, I am not sure if you can use C++17 STL. If you can, there is a filesystem library which can be used to do what you are trying to accomplish with a few lines of code. If you can't, you can try to find a more up-to-date compiler.


Receiving a user's registration submission and inserting row into database #2

While it is sensible to some people to precisely specify the cause of the submission failure, I prefer to return compound messages rather than a length error message and a quality error message.  I would probably save on screen space (versus piling upto a dozen separate email messages on the user), and merge some responses like:

First name is a required field and may only contain letters and/or digits.

Also, you are repeating yourself a few times with these error messages and you can easily implement a looped battery of checks -- and it is simpler to do that within the $_POST array.  Not only does this avoid some code bloat, you are assured to have consistent error message and reduce your chances of copy-pasting typos.  (Maybe you didn't realize that you wrote last name in the username errors  -- this is the kind of thing that really perplexes users!)
Note: ctype_alnum() will return false on a zero-length string so the !trim() can be omitted.
$alnums = ['first_name', 'last_name', 'username'];  // whitelist of required alphanumeric fields
foreach ($alnums as $field) {
    if (!isset($_POST[$field]) || !ctype_alnum($_POST[$field])) {
        $errors[] = "$field is a required field and may only contain letters and/or digits.";
    }
}

if (!isset($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Email is a required field and must be valid.";
}

if (!isset($_POST['pw'], $_POST['pw2']) || $pw !== $pw2) {
    $errors[] = "Password and Password 2 are required fields and must be identical.";
}

Ultimately, all of these server-side checks are to protect you and your database -- NOT to help your users.  For the best possible user experience (UX), you need to duplicate all of these validations with javascript onsubmit of the form.  This way you inform the user as quickly as possible AND avoid making a fruitless trip to your server.
You can check for unique usernames and email addresses in a single trip to the database.  Because the earlier validation assures no leading or trailing whitespace, the posted data will match the respective result set values (iow, no trimming is needed).
if (!$errors) {
    $stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
    $stmt->bind_param("ss", $_POST['username'], $_POST['email']);
    $stmt->execute();
    foreach ($stmt->get_result() as $row) {
        foreach (['username', 'email'] as $field) {
            if ($row[$field] == $_POST[$field]) {
                $errors[] = "Sorry, the submitted $field is already in use.";
            }
        }
    }
}

Once you have fully validated all incoming data as valid, THEN you can happily insert the new user into your database and save the SESSION data.  By the way, I don't recommend changing the naming convention from username to id.
If any of the checkpoints are failed then present your $errors.  As already pointed out, you are not actually displaying your error messages.  In simplest terms, you could create
 tags as you loop.
if (!$errors) {
    $pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' => 14]);
    $stmt = $con->prepare("INSERT INTO users (first_name, last_name, username, email, pw) VALUES (?, ?, ?, ?, ?)");
    $stmt->bind_param(
        "sssss",
        $_POST['first_name'],
        $_POST['last_name'],
        $_POST['username'],
        $_POST['email'],
        $_POST['pw']
    );
    $stmt->execute();

    $_SESSION["username"] = $_POST['username'];  // I always expect an id to be an integer
    header("Location: ../../index.php");
    exit();
}

foreach ($errors as $error) {
    echo "
$error
";
}

None of the above snippets have been tested; I make no guarantees that they will work "out of the box".


Counting slides shift in javascript object

You never use the shiftcounter variable, so feel free to remove it.

You don't care about the keys in the object you're iterating over, you only care about the objects at each key - so, it would be more appropriate to iterate just over the values, rather than the keys. Use Object.values instead of for..in.

The .group property is already an integer in the dataset, so there's no need to call parseInt with it. Since you want to extract the group property into a variable named group, you can do this more concisely with destructuring.

Rather than hard-coding the action to take when the group is 1 (the first), you can initialize lastGroup to 1 so that the //fill rest of array with repeated count and match length section will take care of the logic you need - it'll be more DRY.

const shiftCount = [];
let lastgroup = 1, // initial group
  lastcount = 0; // initial count
for (const { group } of Object.values(slides)) {
  if (group !== lastgroup) {
    lastcount = shiftCount.length;
    lastgroup = group;
    shiftCount.push(lastcount);
  } else { //fill rest of array with repeated count and match length.
    shiftCount.push(lastcount);
  }
}

const slides = {
  1: {
    content: "",
    group: 1
  },
  2: {
    group: 1
  },
  3: {
    content: "",
    group: 1
  },
  4: {
    content: "",
    group: 2
  },
  5: {
    content: "",
    group: 3
  },
  6: {
    content: "",
    group: 3
  },
  7: {
    content: "",
    group: 3
  },
  8: {
    content: "",
    group: 4
  },
  9: {
    content: "",
    group: 4
  },
  10: {
    content: "",
    group: 4
  },
  11: {
    content: "",
    group: 5
  },
  12: {
    content: "",
    group: 5
  }
};

const shiftCount = [];
let lastgroup = 1,
  lastcount = 0;
for (const { group } of Object.values(slides)) {
  if (group !== lastgroup) {
    lastcount = shiftCount.length;
    lastgroup = group;
    shiftCount.push(lastcount);
  } else { //fill rest of array with repeated count and match length.
    shiftCount.push(lastcount);
  }
}
console.log(shiftCount);


LINQ method to create objects of different types

Considering that most of the options of MutateAddressData seem to be identical for both cases, I'd extract that into a method. But then you'd need yearsDB to contain items of the type TaxReturn.

So you'd basically end up with something like this:

var yearsDB = this.uow.TaxReturns.Where(x => taxReturnIds.Contains(x.Id)).ToList();

var ibAndVpb = yearsDB.Where(x => (TaxReturnType)x.TaxReturnType.Id == TaxReturnType.IB ||
                                  (TaxReturnType)x.TaxReturnType.Id == TaxReturnType.VpB);
if (ibAndVpb.Any())
{
    addresses.Add(CreateMutateAddressData( customer,  ibAndVpb));
}

var averaging = yearsDB.Except(ibAndVpb);
if (averaging.Any())
{
    addresses.Add(CreateMutateAddressData( customer,  averaging));
}

return addresses.ToArray();

This is the method that's called:

private MutateAddressData CreateMutateAddressData(Customer customer, List<TaxReturn> taxReturns)
{
    return new MutateAddressData
                    {
                    AddressType = AddressType.TaxReturn,
                    CityId = customer.PaCity.Id,
                    CountryId = customer.PaCity.Country.Id,
                    HouseNumber = customer.PaHouseNumber,
                    HouseNumberPostfix = customer.PaHouseNumberPostfix,
                    Street = customer.PaStreet,
                    ZipCode = customer.PaZipCode,
                    Years = string.Join(", ", taxReturns.Select(t => t.Year.ToString())),
                    TaxReturnType = (TaxReturnType)taxReturns.First().TaxReturnType.Id,
                    };
}


Transform this to one line arrow function ES6+

First of all, onAuthStateChanged expects a callback and can be fired multiple times. To resolve that you can use unsubscribe() after the first success.
Secondly, for your code to work, you need to wait for signInAnonymously. At the moment you assign it to a temporary variable, but I can't see it working. Because onAuthStateChanged accepts a callback that can be fired multiple times, it won't wait in the main scope. To solve this, I suggest using Promise constructor.
Finally, you call signInAnonymously, but you don't do anything with its response. You need to use user.uid if the user is logged in, otherwise you need to use signInAnonymously().user.uid
So the final solution:
const getUID = async () => new Promise(resolve => {
    const unsubscribe = firebase.auth().onAuthStateChanged(user => {
        unsubscribe();
        resolve(user ? user.uid : firebase.auth().signInAnonymously().then(v => v.user.uid))
    });
})

const uid = await getUID()

Explanation:

Wrap everything to Promise and resolve it when we get uid
Auth & listen on onAuthStateChanged
Unsubscribe on the first onAuthStateChanged callback trigger (because one trigger it's enough in your case)
Check if a user is defined (that means the user is signed in), resolve promise with user uid
If the user is not defined, use signInAnonymously to sign anonymous user, resolve that user `uid.


Review the code to copy List of custom class to another list of Custom class

One thing I guess you can consider is to add a constructor for class FlowCopy that handles (or encapsulates) the copy task to release this burden from function getFlow():

public class FlowCopy {
    public FlowCopy(FlowObject obj) {
        setId(obj.getId());
        setAudioRefs(obj.getAudRefs());
        setCallSteps(obj.getFlowSteps());
    }
   ...
}


Wrap a callback method in an awaitable method

Error Handling

You are relying on OAuthGetRequestTokenAsync to catch all exceptions for you.

flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>
{
    if (r.HasError)
        tcs.TrySetException(r.Error);
    else
        tcs.TrySetResult(r.Result);
});

Unhandled errors

However, OAuthGetRequestTokenAsync internally calls  FlickrResponder.GetDataResponseAsync, which as you can see in the Reference Source does not catch all exceptions.

Most exceptions are caught and provided to the callback:

// .. snippet from FlickrNet.Internals.FlickrResponder.GetDataResponseAsync()
if (e.Error != null)
{
    result.Error = e.Error;
    callback(result);
    return;
}

But some are thrown to the caller:

// .. snippet from FlickrNet.Internals.FlickrResponder.GetDataResponseAsync()
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
    string responseData = responseReader.ReadToEnd();

    throw new OAuthException(responseData, ex);
}

Refactored Code

To wrap this call in an async task, I would also catch these exceptions and handle them in the Task.TrySetException. In addition, since you provide a public API, I suggest to avoid NullReferenceException and check required arguments against null. Perhaps callbackUrl should also be checked early against null. I'm not sure about this, you'd have to verify.

public static Task<OAuthRequestToken> OAuthGetRequestTokenAsync(
    this Flickr flickr, string callbackUrl)
{
    if (flickr == null) throw new ArgumentNullException(nameof(flickr));
    var tcs = new TaskCompletionSource<OAuthRequestToken>();
    try
    {
        flickr.OAuthGetRequestTokenAsync(callbackUrl, r =>
        {
            if (r.HasError)
                tcs.TrySetException(r.Error);
            else
                tcs.TrySetResult(r.Result);
        });
    }
    catch (Exception uncaughtError)
    {
        tcs.TrySetException(uncaughtError);
    }

    return tcs.Task;
}


All permutations of the pairs that add to squares

Since you don't seem to be concerned with the order of any of the collections of objects you use, only membership in those collections, Set is probably the better Collection to use, instead of List.  I imagine that Set.contains is going to be more efficient than List.contains.

Also, it's not clear to me that recursion is the way to go here.  If I were you, I would try to walk through the code with a low value for the input number and see what it's doing.  It looks like for every integer between 1 and num, you're calling getSqaureLists num x num times.  That seems like overkill.  Recursion typically does some work and then passes a smaller set of work to the recursive call.  You need to clarify how you split up that work.  If that's not working, a iterative solution might be clearer.

You also have some code to check for duplicates.  You shouldn't need to do that.  Whether you a doing an iterative or recursive solution, you should be able to avoid ever testing duplicate values.


Hello World using Python embedded in C++, with RAII library initialization

Are you sure also scoping de-initialization of Python to main (by removing static) is not an option?
As-is, you cannot use Python in a globals initializer or destructor anyway.
Having taken a look at Py_Finalize, I actually would not deinitialize it at all, at least not in a release-build, as none of the reasons that option is provided apply to you:

  This function is provided for a number of reasons. An embedding application might want to restart Python without having to restart the application itself. An application that has loaded the Python interpreter from a dynamically loadable library (or DLL) might want to free all memory allocated by Python before unloading the DLL. During a hunt for memory leaks in an application a developer might want to free all memory allocated by Python before exiting from the application

  Bugs and caveats: [... lots ...]

Next, you shouldn't be using a function-pointer, use an empty function-object instead.
Using a function-object facilitates inlining and as it's empty, reduces memory-overhead.
Actually, are you sure you actually need / want a std::shared_ptr?
Either because you are already irretrievably locked into using that type, or because you actually might need weak pointers somewhere?

If the answer is no, look into boost::intrusive_ptr, as that will save you an allocation every time you hand a PyObject to a smart-pointer's oversight, and reduces smartpointer-size by half, to raw-pointer-size.

// Hooks in same scope as PyObject (global scope), so ADL in intrusive_ptr finds them:
void intrusive_ptr_add_ref(PyObject* p) noexcept { Py_INCREF(p); }
void intrusive_ptr_release(PyObject* p) noexcept { Py_DECREF(p); }
// typedef for ease of use:
typedef boost::intrusive_ptr<PyObject> PyPtr;
// Use as:
PyPtr string(PyString_FromString("Hello World!\n"), false);


selecting an item in a listbox to assign it as a temp variable - Review Code

Not sure if this question really fits here, but I'll try to help anyway.

  With the first 2 lines of code (At the top of the answer), where would
  i place this (I'm new to C# so .Datasource & DisplayMember are new
  things to me).

DataSource is used when you're databinding a control to a collection.
DisplayMember is used to determine which member (property) of the databound type will be used. For instance you have a class Person (id, firstname, lastname) and you want to display lastnames in your listbox. So you set listbox.DisplayMember = "lastname"

You can put these lines pretty much anywhere. When you fire up the method containing these commands, your listbox will get populated by the data specified in DataSource. You can use Load event for instance, however, I'd recommend to use an extra method called PopulateListBox and call that from Load event...

  would i place the location of my text file within the brackets?

That depends on many things..For instance what exactly are you trying to achieve, how is the rest of your application structured, what are you programming habits etc...
If you wanted to use the code from Scorpi0, the method GetAllMoviesFromTextFiles expects to have everything it needs without any input. It should contain a method body to get all movies.

Furthermore, I'd suggest you one thing - if this is too advanced for you and you still don't understand, get some books and start with something simpler. You need to understand how to divide the application into logical layers, how to separate UI from data access etc. This is a topic for multiple books and a few years experience. You can't expect just to start typing some code and immediately get it all right. From a big part it's very opinionated as well, there are rarely "the best practices". You ask 10 different programmers and you get 10 different answers. You need to learn many things, so you will be able to decide for yourself what suits you the best in the current situation you're in.


There is not a whole lot to say, but I found a few small things that could be improved.

Consistency

DECLARE @username as NVarchar(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId as int = ##UserId:int?-1##;
DECLARE @limit as int = ##Limit:int?100##;

Would be better as:
DECLARE @userName AS NVARCHAR(60) = RTRIM(LTRIM(##DisplayName:string? ##));
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;

Aliases
I think your aliases mostly obfuscate the query. It's also recommended to explicitly state the type of join, e.g.:
FROM Posts AS posts
  INNER JOIN Users AS users ON p.OwnerUserId = u.Id
  INNER JOIN Posts AS questions ON p.ParentId = q.Id

Trim
Your left and right trim operations don't really achieve anything. Do you expect a user name to have a bunch of white space before or after it? I'm not sure SE would even allow that. I removed them and got identical results.

Everything combined:
DECLARE @username AS NVARCHAR(60) = ##DisplayName:string? ##;
DECLARE @userId AS INT = ##UserId:int?-1##;
DECLARE @limit AS INT = ##Limit:int?100##;

SELECT TOP 100
  users.Id AS [User Link],
  posts.Id AS [Post Link],
  posts.CreationDate
FROM Posts AS posts
  INNER JOIN Users AS users ON posts.OwnerUserId = users.Id
  INNER JOIN Posts AS questions ON posts.ParentId = questions.Id
WHERE
  (@username = '' OR users.DisplayName = @username)
  AND (@userId = -1 OR users.Id = @userId)
  AND posts.Score = 0
  AND posts.Id = questions.AcceptedAnswerId
ORDER BY posts.CreationDate DESC

Eliminating the empty string check
There is a way to eliminate the @username = '' check, however it does have a performance impact. I ran it and it runs in ~400 ms, which is not bad but a bit slower. It makes the index scan on the [Users].[UIX_Users_Id] table take longer due to partial string match.
WHERE
  u.DisplayName LIKE CONCAT('%', @username, '%')
  AND (@userId = -1 OR u.Id = @userId)
  AND p.Score = 0
  AND p.Id = q.AcceptedAnswerId


For a given balance and an annual interest rate, calculate the minimum fixed monthly payment to pay off debt in a year

This is a problem that can be solved exactly with a little math, so there should be no need to program a search.

Suppose that we borrow initial capital \$c\$ at a monthly interest rate \$r\$, paying it off in \$n\$ months with a monthly payment \$p\$. (Here \$r\$ is expressed as a multiplier, for example if the monthly percentage rate is \$2\%\$ then \$r = 1.02\$.)

In this scenario the outstanding balance is $$ \eqalign{
cr - p &= cr^1 - p(1) & \quad\text{after 1 month;} \\
(cr - p)r - p &= cr^2 - p(1 + r) & \quad\text{after 2 months;} \\
((cr - p)r - p)r - p &= cr^3 - p(1 + r + r^2) & \quad\text{after 3 months;}}$$ and so after \$n\$ months the balance is $$
cr^n - p(1 + r + r^2 + \dots + r^{n - 1}) = cr^n - p{r^n - 1\over r-1}. $$ If this pays off the debt exactly then $$ cr^n - p{r^n - 1\over r-1} = 0 $$ and so $$ p = {cr^n(r-1) \over r^n - 1}.$$

Since payments typically have to be made in integer numbers of pennies (or whatever the minimum unit of account is) then you'll want to round \$p\$ up to the nearest penny.


How about this?

private static string InsertMethodNameHere(bool hasCondition1, bool hasCondition2, bool hasCondition3)
{
    return ((hasCondition1 ? 1 : 0) +
            (hasCondition2 ? 2 : 0) +
            (hasCondition3 ? 4 : 0)).ToString(CultureInfo.InvariantCulture);
}

If you want a more general solution, you could write an extension method that converts a list of bools to an int:

public static int ToInt(this IEnumerable<bool> bools)
{
    return bools.Select((t, i) => (t ? 1 : 0) << i).Sum();
}


I believe this can be simplified quite a bit. My immediate reaction would be to write code something like this:

#include <sstream>
#include <iostream>
#include <numeric>

int main() {
    std::istringstream in("$AIVDM,1,1,,A,13HOI:0P0000VOHLCnHQKwvL05Ip,0*23");

    std::string sentence;

    std::getline(in, sentence, '*');

    std::string received_checksum;

    // Save the checksum that was at the end of what we received.
    std::getline(in, received_checksum);

    // Re-compute the check-sum:
    char check = std::accumulate(sentence.begin()+1, sentence.end(), 0,
        [](char sum, char ch) { return sum ^ ch; });

    // Print out both the received and computed checksums:
    std::cout << "received checksum: " << received_checksum;
    std::cout << "\ncomputed checksum: " << std::hex << (int)check << "\n";
}

Looking at specific details of the code, I see a few things that even if you were going to preserve roughly your current implementation, you could still simplify and clarify. The first point would be to fix your indentation. Right now, it appears to be almost entirely arbitrary, and unrelated to the structure of the code.

Then you could clean up some of your loops. For example:

bool done = false;
while (!done)
{
    int h ( MsgLine.at (i) );
    i++;
    AsciiValues.push_back(h);

if ( i == j )
    done = true;
}

...can be turned into something like this:

for (int i=0; i<j; i++)
    AsciiValues.push_back((int)MsgLine.at(i));

Or, you could just use std::copy. Likewise, your code for computing the checksum:

bool done = false;
while (!done)
{
    a = (AsciiValues[d]);
    b = c;
    c = a ^ b;
    d++;

if ( d == e )
    done = true;
}

...could be simplified down to something like this:

do {
    a = AsciiValues[d];
    b = c;
    c = a ^ b;
    ++d;
} while (d != e);

...or you could do something closer to the accumulate (it still seems a lot cleaner to me to use std::accumulate), as I showed to start with.


Number of occurrences of strings in array

if q in dic is pointless. You initialized dic so that it does have all queries.
dic = dict.fromkeys(queries, 0) should be a bit faster.
dic is not a particularly meaningful name, counter or ctr would be better.
Creating results at the start of the function gives the false impression that it's needed there already. I'd create it right before the loop that builds it. Then you'd have the complete counting part first, and the complete querying part afterwards. Or better yet, ...
... use a list comprehension, which is faster and nicer.
Python already has a Counter class that does a lot for you and is probably faster.

from collections import Counter

def matchingStrings(strings, queries):
    ctr = Counter(strings)
    return [ctr[q] for q in queries]

For fun: 1000*1000 isn't super big, and HackerRank's calling code really only needs an iterable, so... this also gets accepted:
def matchingStrings(strings, queries):
    return map(strings.count, queries)


First and foremost, I must absolutely recommend against doing anything of this sort.

If you want to know what classes are available in the scope, you need only look up at the imports you're making.  All of the imports will either be your own files, for which you should only really have one visible class per import, or they will be library/framework imports.  The library/framework imports are likely bringing multiple classes with them, but they should be well documented.

Anything that a program like yours does manage to find is going to fall into one of two categories:

Stuff we already know about anyway.
Stuff that's undocumented and we almost certainly shouldn't be using.

And perhaps more importantly, this is incredibly inefficient.  The difference between just looking at your source code and making this run-time check is, well, your check is happening at run-time.  But, what useful thing can you actually do with that knowledge?  None, really.

More importantly, when do you know to stop looking?  There's not a character limit to class names (as far as I know).  All we can do is check literally every character combination.  The math to figure out how many combinations we need to check is:

Number of characters = N
Maximum length = M
Minimum length = m

  (N^M) - (N^(m-1))

(roughly... I might be slightly off)

If we don't impose a minimum length, and we just want to check every combination with 8 characters, we have to check 248,155,780,267,521 combinations.  That's 248 trillion, and that's just for every combination of characters up to 8 length, so forget about discovering anything that starts with NSMutable which alone is already 9 characters long before we count the last part (Array, Dictionary, Set, Data, String, etc).

If I do 63^255 on the OS X calculator, it says simply "Infinity".  While that's not technically correct, it might as well be.  And I don't even know that 255 characters is actually any sort of limit on class name length.

But, with all of this said, a little multithreading can go quite a long ways.

With two threads working on this problem, you're checking twice as many strings per cycle.  With four, four times as many, etc.  All that is required is a strategy for effectively breaking your total workload into equal chunks of work for all of the threads to work on.

And it doesn't matter if you create more threads than your CPU can actively work on.  The overhead for creating threads is relatively low.

What might make sense is to create 53 separate threads--one for each of the valid starting characters (class names can not start with numbers).  It's unlikely we'll be running this on a CPU that can simultaneously process 53 threads at a time any time soon, so this should be more than plenty to make sure we're getting maximum value out of our CPU.


One major problem with this code that I can see is that you need to consider what you are synchronizing, and why. I understand your main objective here is learning concurrency but I've also added some other suggestions you may or may not want to use.

Concurrency

There are a couple of issues with the way you are synchronizing things. In your case, the things you'd want to prevent happening are:

Interleaving on the players' attacks. This might happen if two
separate threads try and damage the same enemy.
Preventing both the Hero and Monster 'winning' (killing each other). Note: you might not want to prevent this

The synchronized blocks will prevent any code with the same lock executing at the same time. Therefore you need to synchronize:

Modifications to health of self or enemy.
Checks of health of self or enemy.

You should not synchronize the Thread.sleep(); calls because each thread will have stop and wait for all the other ones to stop sleeping. So what does this look like for your code? Let's see:

public void hitHero() {
    boolean isFighting = true;
    while (isFighting) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (lock) {
            monster.attack(hero, random.nextInt(20));
            if (hero.getHp() < 0) System.out.println("Monster won.");
            isFighting = hero.getHp() > 0 && monster.getHp() > 0;
        }

    }
}

Note that I have used the boolean isFighting in order to move the checks to HP inside the synchronized block.

This solution will not prevent the two from killing each other if one dies while the other is waiting to attack. To prevent this, you'll need to add other checks inside the synchronized block.

Encapsulation

Consider the Monster and the Hero. They both share some common traits. They both have HP, a name, and can both attack something. Why not make a parent class (let's call it Fighter) that is not just an interface, but provides implementation for attack, and a hp + name:

public class Fighter {
    private int hp;
    private String name;

    public Fighter (int hp, String name) { ... }
    public int getHp() { ... }
    public String getName() { ... }
    public void decreaseHp(int dmg) { ... }

    public void attack(Fighter f, int dmg) {
        System.out.println(f.name + " hp: " + f.getHp());
        System.out.println(name + " dealt " + dmg + " damage");
        f.decreaseHp(dmg);
        System.out.println(f.name + " hp is now: " + f.getHp());
        System.out.println("--------------------------");
    }

The great thing about this is that you lose the need for the instanceof check, since you know you can attack any fighter you want. Now adding a new type of fighter is super easy:

public class Hero extends Fighter {
    public Hero (int hp, String name) {
        super(hp, name);
    }
}

In addition to this, I would certainly consider making all the variables inside ThreadFight private, and creating + starting the two Threads inside ThreadFight's constructor (or inside a startFight() method).

Overall though, I think you've done a good job! You're running the threads correctly and nearly got the synchronization right. It can take a while to fully understand what's happening with multiple threads and locks. Though there are possible improvements the Monster and Hero were also built well. It's a nice little program and you could certainly expand upon it if you wanted to practice more complex threading situations.


Functional implementation of collecting objects into groups

Well you can avoid a few variable assignments by returning immediately,
also by using some details of the Underscore.js API, that is by
specifying the used indexes for groupBy/map directly.

_.chain(a)
 .groupBy(0)
 .mapObject(function (val, key) {
    return _.chain(val).map(1).uniq().value();
 })
 .value();

I doubt there's a good way to avoid mapObject, after all, that's what
it's for.

With 1.7 you could also write that even less verbose:

_.chain(a)
 .groupBy(0)
 .mapObject((val, key) => _.chain(val).map(1).uniq().value())
 .value();

Looks pretty functional to me.


Just looking at you Main class, you notice some strange things.

Passing an already known instance:

ChessBoard chessBoardView = new ChessBoard(myController);
View myView = new View(myController, chessBoardView);

The ChessBoard holds (normally) an instance of Controller. The View hold an instance of ChessBoard who holds the instance of Controller. So passing the controller to View is not needed, if you need the controller in the View just call chessboard.getController();.

Beans who have each other instances:

Controller myController = new Controller();
View myView = new View(myController, chessBoardView);
myController.addView(myView);

It's a strange setup, but if used for the Observer-observable pattern I can see your logic. But still, it's at the wrong place. If you need this, pass the instance of view to the controller in the constructor of view.

public View (ChessBoard board) {
    this.board = board;
    board.getController().addView(this);
}

Attention, you will have a leaking constructor warning with this.

Method naming:

I see you use in the Controller addModel, addView,... When you use addXxx this should mean that you add this to a Collection. If it's not adding to a Collection use setXxx so everyone who reads your code knows it.

Why is this important:

With set you know you lose the previous instance.
With add you normally hold your previous instance.

MVC:

Your pattern is almost correct except the fact that your View holds ChessBoard, as I can see from the name of the variable is also a view. If your ChessBoardModel is changed, it should notify the View itself and not the ChessBoard itself.


Screen manager and its screens having access over the screen manager

I just happened to code my own StateMachine a week ago, which is similar to your ScreenManager, so here are my thoughts on the subject.

A vector of state can work, but I think using a stack instead saves you the index management. Also, the stack would resize itself during both pop and push operations.

A state (or a screen in your case) manages its own lifetime. As a consequence, it can remove itself from the stack during an update operation, and must survive until the next loop is processed. Thus, I choosed std::shared_ptr to work out this problem.

std::stack<std::shared_ptr<Screen>> _screens;

Since you're using C++11, the more you avoid manual dynamic allocations, the better. Using templates, you can use a safer way of creating your screen, and even provide parameters to them :

template<typename Screen, typename... Args>
void push_screen (Args && ... args)
{
    if (!_screens.empty())
        _screens.top()->pause(); // Pause the current state

    _screens.emplace(std::make_shared<Screen>(std::forward<Args>(args)...));
    // Or, if you still use std::unique_ptr
    // _screens.emplace(new Screen { std::forward<Args>(args)... }); // C++11
    // _screens.emplace(std::make_unique<Screen>(std::forward<Args>(args)...)); // C++14
    _screens.top()->enter(); // Start the new state
}

This way, you can pass a reference of your ScreenManager and avoid using a bare pointer.

push_screen<MainMenuScreen>(*this);


Making two sequential asynchronous requests using promises

You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)

async function getFullNote(noteId) {
    const note = await db.collection('notes').doc(note_id).get();
    const author = await getAuthorData(note.author_uid);
    return {
        id: note_id,
        title: data.title,
        ext: data.text,
        author: author
    }
}

This is how MDN defines an async function:

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function


Design To Handle Multiple Similar Model Class

I would suggest the following potential improvements.

Change the Quotation class to the following

public class Quotation
{
    private Customer customer;

    private List<BaseEvent> events = new List<BaseEvent>();

    // Getters and setters to access the two entities above.
}

So now you have divided you elements into specific entities like Quotation, Customer and Events.

Adding more details to a Customer or adding a new Event type, don't require change to the Quotation class, but only changes to the specific entity.

On the side, you might also find it beneficial to look into a simple visitor pattern for the events and provide algorithms to etc. calculate total price, date collisions, number of participants etc. etc.

Enjoy.


Promisifying a third-party JS library with minimal code overhead

You are correct that you can avoid a lot of the structure duplication in this class. A promisify function would help a lot. Node has a built in util.promisify. Alternatively, you could write a simple method to apply the arguments and resolve when called. In vanilla JS this is simple enough.

function callPromised(method, ...args) {
    return new Promise((resolve, reject) => {
        method(...args, (error, result) => error ? reject(error) : resolve(result))
    })
}

Unfortunately, this method is difficult to type correctly in TypeScript. There's a proposal here. The best we can do now is write several overloads which gets incredibly messy with only a few parameters.

function callPromised<TResult>(method: (cb: Auth0Callback<TResult>) => void): Promise<TResult>;
function callPromised<TResult, Arg1>(method: (arg1: Arg1, cb: Auth0Callback<TResult>) => void, arg1: Arg1): Promise<TResult>;
function callPromised<TResult, Arg1, Arg2>(method: (arg1: Arg1, arg2: Arg2, cb: Auth0Callback<TResult>) => void, arg1: Arg1, arg2: Arg2): Promise<TResult>;
function callPromised(method: Function, ...args: any[]): Promise<any> {
    return new Promise((resolve, reject) => {
        method(...args, (error, result) => error ? reject(error) : resolve(result))
    })
}

The downside of this function is that this will not be bound correctly. This could be rectified by passing in a self parameter and would be required for your usage.

function callPromised<TResult>(method: (cb: Auth0Callback<TResult>) => void, self: any): Promise<TResult>;
function callPromised<TResult, Arg1>(method: (arg1: Arg1, cb: Auth0Callback<TResult>) => void, self: any, arg1: Arg1): Promise<TResult>;
function callPromised<TResult, Arg1, Arg2>(method: (arg1: Arg1, arg2: Arg2, cb: Auth0Callback<TResult>) => void, self: any, arg1: Arg1, arg2: Arg2): Promise<TResult>;
function callPromised(method: Function, self: any, ...args: any[]): Promise<any> {
    return new Promise((resolve, reject) => {
        method.call(self, ...args, (error, result) => error ? reject(error) : resolve(result))
    })
}

// For example
public loginWithDefaultDirectory(options: a0.DefaultDirectoryLoginOptions): Promise<any> {
    return callPromised(this.wa.loginWithDefaultDirectory, this.wa, options)
}


Coding style

Please follow PEP8, the Python coding style guide.
You have really a LOT of coding style violations,
and it's really hard to read your code this way.

In addition, the variable names are extremely poor,
especially a file handle named d,
and a node named i,
but an index named j is also not great.

Choice of data structure

The index is backed by TextIndex, a list,
which is inefficient.
The time complexity of a lookup (the Search function) is \$O(n)\$.
You can do much better by using a dictionary,
mapping words to nodes.
In fact, the Search function would completely disappear,
as you could replace it with a simple condition like word in TextIndex to check if something is in the index or not.

Working with files

Since all 3 input files are processed exactly the same way,
there's no need to process them all in the same with block.
If an error occurs during the processing of one,
the program would exit, so this is fragile,
and at the same time a very rigid setup.
It would be better to have a helper function in charge of opening and processing a file,
and call this function for each file sequentially.

It's also not great to pass a file handle to another function.
It's a lot clearer to work with a file handle in the with block,
read data from it, and then it's ok to pass the read data to another function for further processing.


getNode does not replace an iterator. It always starts at the beginning of the list. It means that scanning over the list has a quadratic time complexity.
A Node default constructor is dubious. It assumes that T can be constructed from a NUL character. It seems like an unnecessary restriction. Assuming that T itself has a default constructor, and using it is more logical.
length() method is expected to have a constant time complexity. A linear one is at best surprising. I recommend to make a member, to be incremented at each insertion, and decremented on each removal.


Can this localStorage login script be written more efficiently?

Separate UI from logic

You might want to keep the logic for localStorage handling separate from the DOM fetching logic. That way, your system for handling the local storage can easily be detached and reused elsewhere without that extra baggage. Also works the other way around, when you replace your UI.

Basic login API

In continuation with the previous paragraph, you could model it to have this API:

bic.login(username,password);   // Return true if logged in, false if not
bic.isLoggedIn();               // Return true if someone is logged in, else false
bic.getUserId();                // Gets the current user's ID
bic.logout();                   // Logout current user

bic.register(username,password) // Registration
bic.destroyCurrentUser();       // Just for fun. Only a logged in user can delete himself

The UI logic is separate. It consumes this API rather than being one with it.

LocalStorage is synchronous

Note that localStorage is a synchronous operation. Doing heavy IO against localStorage could mean an unresponsive experience. This has an amplified effect on mobile devices, since they are times slower. Don't pull out or put in huge data. Do it by chunks. Use multiple small keys rather than one big key to house everything your system needs.

JSON.parse() and JSON.stringify()

localStorage is a string-based, key-value storage. But that's it. You need some form of format to structure highly complex data, like user data. Something that may look like:

[
  {id:1,name:"foo",password:"***"},
  {id:1,name:"bar",password:"***"},
  {id:1,name:"baz",password:"***"}
]

To store data like a JS object, you need JSON.stringify() to turn it into a string. Then you can store it to localStorage. To get it, retrieve it from localStorage and then use JSON.parse() to convert from string.

Storage routine

What I typically do when using localStorage is to create an in-memory object of the data. On every save, I serialize the data with JSON.stringify and store it to the localStorage. If ever there are other code that modifies that same data, there are localStorage events to tell you if the data is modified in the storage.

Code refinements

Since I advertised array-based storage, then Array filter, splice, push would be your best friends here. In addition, I believe I introduced you to JSON stringify and parse already.


First of all, you should definitely switch to using with context manager which is gonna safely and automatically close the opened file handler.

Also, you need to improve your variable names, l1, l2, l3 or z are not descriptive.

And, you may use .writelines() to write a list of strings each of them on a separate line.

In the end, you might get something along these lines:

print("Type the name of the file for overwriting.")
file_name = input(">")

with open(file_name) as input_file:
    print("The contents are currently: \n", input_file.read())
    print("Enter in the new lines")

lines = [input(">") for _ in range(3)]

print("Entering new lines.")
with open(file_name, 'w') as output_file:
    output_file.writelines(lines)

with open(file_name) as input_file:
    print("The new contents are:")
    print(input_file.read())


Of course not.

If you do c, a, b = a + b, b, c, this is what you get

a, b, c = a0, b0, c0
c, a, b = a + b, b, c
## c become a0 + b0
## a becomes b0
## b becomes c0

I'm pretty sure this is not your intention.

In tuple assignment, the right tuple is evaluated first and then assigned to the left tuple. I'm guessing you thought it's done in order. Sorry, but no.

You can instead eliminate the variable c and do this

a, b = a0, b0
a, b = b, a + b
## a becomes b0
## b becomes a0 + b0

UPDATE

This is what is done by the machine, imagine the left values as an array of variables waiting to be assigned values that are on the left. Like this

[c, a, b] = [a + b, b, c]

Imagine the right values as an array of expression waiting to be evaluated. The right one gets evaluated first, then one by one the left variables takes the right values. No assignment is done until the left expressions are evaluated.


Simple UDP server/client written in Python to report back IP address

sys.argv is already a list. I don't see a purpose of list(sys.argv).
Creating sockets in the mainline looks strange. It is more natural to create them in corresponding __init__ calls. Same applies to serv.listen().
from socket import * is really bad practice, especially when socket is used as a parameter:

self.socket = socket

makes me wonder whether the parameter is an instance or a callable.
recvfrom may raise a socket.error exception. Some of them are recoverable, so you may want to catch then as well.


Reading a file and storing all the data in a buffer

I recommend to pass a file pointer rather than a path. This will enable the code to work with streams as well. It would also simplify the awkward error handling.
Modern c allows, and recommends, to declare variables closer to their use.
It is OK to realloc even when data is NULL.
sizeof(char) is guaranteed to be 1.
Incrementing data_size after memcpy lets you drop data_cursor and cursor_pos, which IMHO obfuscate the code. You'd need to

    memcpy(data + data_size, buffer, n);
    data_size += n;

Allocating an array on the stack is usually not recommended. Consider reading directly into data + data_size, and get away without buffer and memcpy.


Rather than using recursion (which is pretty slow), you can for this using a Set of all reachable nodes, and a Queue of nodes you still haven't searched.  This is a basic implementation of Breadth-First Search.

private boolean isNodeReachableFrom(GraphNode start, GraphNode target) {

    // These are GraphNodes who's connected GraphNodes we haven't looked at yet.
    // Maybe the target is connected to one of these!
    Queue nodesToSearch = new LinkedList<GraphNode>();
    nodesToSearch.add(start);

    // These are GraphsNodes which we have proved are reachable from the given node.
    // If we are ever about to add the given target to this list, we return true.
    Set reachableNodes = new HashSet<GraphNode>();

    // As long as there are still nodesToSearch, we could still find our target.
    while (nodesToSearch.peek() != null) {
        GraphNode node = nodesToSearch.remove();

        // If we have already seen this node, we don't want to look at its connected
        // nodes again, because we could get stuck in a cycle.
        boolean isNewNode = reachableNodes.add(node);

        // If this is a new node, see if the target is connected.  If it is, we are
        // done successfully.  Otherwise, add all of the connected nodes to our
        // list of nodesToSearch.
        if (isNewNode) {
            for (GraphNode connectedNode : getConnectedNodes(node)) {
                if (connetedNode.equals(target)) {
                    return true;
                }
                nodesToSearch.add(connectedNode);
            }
        }
    }

    // There are no nodes we haven't searched, so the target is not reachable.
    return false;
}

Note: I made up getConnectedNodes(node) because your code didn't show me how to do this with the GraphNode object.

Note that this is an implementation of isNodeReachableFrom.  However, you seem to want to figure out the list of nodes which aren't reachable from a starting node.  Notice that we build up the list of all reachableNodes in the call above, which is probably what you really want.  You could write a function to return that reachableNodes structure, which would reuse the above logic without the target sections.  Something like this:

public Set<GraphNode> getReachableNodes(GraphNode start) { ... }


Your code is correct, but can be simplified. ok method usually gets an expression rather than a in-place function that is immediately evaluated.

Here is how I would write this test:

test('Mixin Test Runner', function () {
    var receiver = {
        name: 'Abul Moksud',
        age: '60'
    };

    var supplier = {
        hands: 2
    };

    mixin(receiver, supplier);

    //Assertion phase
    ok(receiver.hasOwnProperty("hands"), "hands property is defined on reciever");
    equal(receiver.hands, 2, "Abul Moksud now has two hands");
});


Connecting to a database and running CRUD operations

I think the database class as you wrote it has no use. You write a database class to provide an easier interface with the database. Instead you split up queries into multiple parts, but are still somewhat writing sql. A good database class allows you to use it without having to worry about escaping data, or even if the query was executed (instead of loaded from a cache).
Whitespace
Take some time to fix the whitespace in your code. The whitespace around several operators is inconsistent, such as the spaces around the assignment operator, and the spaces after a comma.
The indentation of your code is incorrect. Make sure that all your code is consistently indented. This makes the code a lot more readable, and thus more maintainable.
Documentation
Your code lacks any documentation or comments. This makes it hard to understand and hard to use, because it is unclear what code can return at any time.
Methods and variables
connect(..)
I am not sure what you are trying to accomplish splitting your code between connect(..) and dbConnect(..). There are several issues with this code. If dbConnect(..) throws, you return the exception, which is not falsy. This means that the if-statement in connect(..) will never be false. This results in connect(..) returning either true or nothing at all.
If connect(..) is called multiple times, you simply connect multiple times instead of just ignoring future calls based on $dbConn.
$dbConn
Why is this variable public? The naming could be better, and you probably don't want external code to modify this variable. Instead provide access to it via a getter.
table_exists(..)
I am unsure why this function exists. The name suggests that it would take an argument with a table name, and would return true or false. Instead it gives an array with table names.
select(..)
This code is vulnerable to sql injection. I would expect a database class to sanitize anything you pass to it. Why would surrounding code do that for the Database class? Check each of the arguments against what you expect the arguments to contain.
PDO::query returns a PDOStatement or false. You do not check for false, resulting in warnings and errors in the following code.
PDOStatement::fetchAll returns false on failure. Since your code lacks documentation I can't determine if this is the intended behaviour, but usually when you build a Database class you do this to encapsulate the PDO interface and provide easier to use methods.
insert(..)
This code is vulnerable to sql injection. See the previous section.
This method prints an error message. I do not expect a database class to print anything! Either provide a different way of accessing the error if it is required or log it. Make the method return true or false based on if it succeeds.
Don't use a catch all catch block. Instead figure out what the code can throw, and act accordingly. According to the documentation, that method does not throw.
setUpdateVals(..)
This function should be removed. It is not the responsibility of other code to escape values. In any case, you should not use PDO::quote and instead use prepared queries.
update(..)
While an update query without a where clause is possible, it is extremely unlikely you need it. Instead, the chances are much greater that you instead forgot to pass a value or did not properly check if a variable existed, or a return value was set.
You probably are tired of hearing it, but the code in this method is vulnerable to sql injection. A prepared query without any placeholders could as well be a normal query. You know how to bind variables to a variable number of placeholders, as you used it before. Use it here.
This method either returns true or nothing at all. Instead just return $stmt->execute(). The same problem where you do not check if PDO::prepare returned a boolean exists here too.
delete(..)
confirmTableDelete(..) does not exist. In any case, it is not the responsibility of a database class to interact with the user. It provides an interface between the database and the rest of the code. Assume that when delete is called, it is intended to be used.
You bind to :Value, but no such placeholder exists. $Data_options does not exist either.
The method does two separate things. I think you should split it into two distinct methods, each doing exactly one thing. This prevents unfortunate mistakes with missing tables.


if internal_state is None:
      internal_state = function()

What if function() returns None?

  Or maybe even some function from the standard library?

functools.lru_cache


Using UPSERT to maintain word counts for subtitles

Like Pankaj Gupta already mentions, you could move the query for @idSerie outside the IF-statement, as it is exactly the same query on exactly the same table with exactly the same data (it does not change anywhere in this stored procedure).

Secondly, I find the code a bit hard to read because of the casing of the table and field names.  This is, of course, a matter of style, but unless you are not "in charge" of the naming style, I would suggest to case them differently.  E.g. using camelCase for field names as you do for variable names (and the APPEARS.counter column), and use PascalCase for the table names.  This way, using UPPERCASE for reserved SQL keywords makes them stand out, instead of having them look just the same as the rest.

Separation of concerns is probably a bit harder in T-SQL, because writing beautiful T-SQL is not always the same as writing well-performing T-SQL.  But you could split up your stored procedure into three parts: the first part would get the @idSerie value from the SERIE table.  The second part would fetch the @idWord from the WORD table, inserting it if it's not already in there.  The third part then would upsert the correct values into the VALUES table.  Not only will this make the code more readable (you only have to remember one table and one or two variables in each part), but also more maintainable, because the INSERT INTO APPEARS command would be only in one place.

Those three parts have generally the same form: 1) select @id, 2) insert or update that row, and 3) get the real @id.  2 and 3 don't apply to each part, so they are optional (you don't need to insert a SERIE row, and you don't need to update a WORD row).

You didn't mention which version of SQL Server you use, but since version 2008, you could look into the MERGE statement, which combines tho logic of inserting and updating into a single statement.

About performance (of which I don't know whether it is in the scope of code review): I suspect that the WORD table contains a unique entry for each word.  As you mention that the query takes more and more time, the more words are in there, you might want to add a (unique) index on the WORD.WORD column, but I don't really know much about performance, so you might want to experiment.

Finally, it's good practice to specify the columns you are inserting into, for readability and maintenance purposes.  So I'd change

INSERT INTO APPEARS VALUES (@idWord, @idSerie, @counter);

To:

INSERT INTO APPEARS (IDWORD, IDSERIE, counter) VALUES (@idWord, @idSerie, @counter);

Likewise for the other inserts.

By the way, I like that you are ending all statements with a semicolon, which is not mandatory, but a good practice, and can help prevent a kind of errors with changing code, using CTE's or query hints for example.


Readable code with many components (Swing)

Try to NOT add each UI component in Class fields. Keep then local if possible, as close to usage as possible. Too much class fields does not make class easy readable - as reader think that all of them are do matter.

JLabel and other components, content(text) of which will never be changed, are good candidates to be declared as local variable or without variable at all:

add(new JLabel("text"));


Minecraft server querier that generates an image of online players

Maybe it will not increase the performance, but I have some general tips:
Use while loops instead of for-loops with break. It will make your code more readable.
I have rewritten the createImage function for you:

def createImage(players):
    # create a blank transparent image with the dimensions: 212x147px.
    baseImage = Image.new("RGBA", (212, 147))
    slotList = [(17, 17), (82, 17), (147, 17), (17, 82), (82, 82), (147, 82)]

    x = 0
    while x < len(players) and x < 6:
        face = Image.open(str(players[x]).lower() + "_face.png", 'r')
        baseImage.paste(face, slotList[x])
        x += 1
    baseImage.save("server1_online.png")

If you prefer for over while, you can use:

def createImage(players):
    # create a blank transparent image with the dimensions: 212x147px.
    baseImage = Image.new("RGBA", (212, 147))
    slotList = [(17, 17), (82, 17), (147, 17), (17, 82), (82, 82), (147, 82)]

    for slot, player in zip(slotList, players):
        face = Image.open(str(player).lower() + "_face.png", 'r')
        baseImage.paste(face, slot)
    baseImage.save("server1_online.png")

Read more about zip here

You need to close the files you open:

# If nothing changed, pass!
if nameList == oldNameList:
    print("same thing!")

# Else, if no-one is on, but the text file says people are on, empty the text file.
elif len(nameList) == 0 and len(oldNameList) > 0:
    print("everyone left :'(")
    tempFile = open('server1_previous_players.txt', 'w')
    tempFile.write("")
    tempFile.close()
    createImage(nameList)

# Else, if at least 1 person is on, generate a new image accordingly.
elif len(nameList) > 0:
    tempFile = open('server1_previous_players.txt', 'w')
    # write should be used instead of print
    tempFile.write('\n'.join(nameList))
    tempFile.close()
    createImage(nameList)

An if-statement can be used without an else, so if there is only pass in there you don't need it.

If you want to create an empty / transparent image when nobody is on, you can combine both elif-statements:

# If nothing changed, pass!
if nameList == oldNameList:
    print("same thing!")

# else generate image and write new player list to file
else:
    if len(nameList) == 0 and len(oldNameList) > 0:
        print("everybody left")
    tempFile = open('server1_previous_players.txt', 'w')
    tempFile.write('\n'.join(nameList))  # writes "" for an empty player list
    tempFile.close()
    createImage(nameList)


Using c++11 random header to generate random numbers

First of all, note that std::default_random_engine and std::uniform_int_distribution<int> are both non-portable in the same sense as rand() is non-portable: they won't produce the same sequence of numbers on different platforms, because their behavior is implementation-defined. For uniform_int_distribution there effectively is no portable alternative, so it's the best game in town. But for the PRNG itself, I don't think any expert would ever recommend default_random_engine. Just pick a known engine, such as std::mt19937. (Which isn't good but again it's the only game in town at the moment.)
For seeding: notice that you're giving only 32 bits of seed (and a very predictable seed at that) to the PRNG's constructor. You should be seeding from a random_device, something like this (stolen from here):
std::random_device rd;
int data[624];
std::generate_n(data, std::size(data), std::ref(rd));
std::seed_seq sseq(data, std::end(data));
std::mt19937 g(sseq);

(Of course nobody does this in practice.)

for (int i = 1; i <= 100; i++)

Prefer
for (int i = 0; i < 100; ++i)

even if it means you have to refer to i+1 inside the loop. Using half-open ranges that start at 0 is good practice for everywhere in C and C++ and every modern language.

std::uniform_int_distribution<int> num(1, 100);

Personally I'd write this as
auto dist = std::uniform_int_distribution<int>(1, 100);

to get that nice clear = separation visible at a glance. Also, notice my conventional variable names throughout: rd for the random device, g for the PRNG itself, dist for the distribution. It might make sense to use a more descriptive name than dist... but certainly num is not more descriptive, and num is less truthful — a distribution is not a single number!

Finally, you don't need that final return 0 (main returns 0 on success by default), and you don't need std::endl because '\n' (or "\n") will do just as well.
But basically you're doing the dance correctly: PRNG created outside the loop, distribution called-like-a-function from inside the loop.
You could move the variable definition of the distribution outside the loop as well, if you wanted. It probably doesn't matter in practice because uniform_int_distribution is unlikely to have any state worth preserving between iterations. But if it were a std::normal_distribution, say, then destroying and recreating the distribution every time through the loop would be costing you basically 50% of your speed.
auto dist = std::uniform_int_distribution<int>(1, 100);
for (int i = 0; i < 100; ++i) {
    std::cout << (i+1) << "==> " << dist(g) << '\n';
}


Turning a grayscale image into a histogram of the intensity of the pixels of that image

JPG vs PNG
Somehow, your code seems to produce wrong results with the above JPG. When used with the same image converted to PNG, the histogram looks much better, and much closer to what Photoshop displays.
ImageIO.read(file) seems to not return the correct RGB values with the above JPG. It is outside of your code though, and seems to be called by Picture class.
As mentioned by @Nayuki, it seems to be a known bug/feature:

https://bugs.openjdk.java.net/browse/JDK-5051418
https://stackoverflow.com/questions/31312645/java-imageio-grayscale-png-issue
https://stackoverflow.com/questions/32583772/reading-grayscale-png-image-files-without-distortion

Double -> int
getIntensity returns a double.
For example, getIntensity(new Color(1, 1, 1)) returns 0.9999999999999999, which is very close to 1.0 but strictly smaller than 1.0.
When you cast this double to an integer in int intensity = (int) a[i][j], it gets converted to 0, which isn't desired.
With your current code, the first histogram bins look like this:
[37509, 2429, 0, 3981, 0, 1763, 1757, 4131, 0, 2016, 4718, 0, 6498, 0, 3526, 7824, ...

If you replace the line with int intensity = (int) Math.round(a[i][j]);, the first bins look like this:
[32317, 5192, 2429, 2327, 1654, 1763, 1757, 2034, 2097, 2016, 2230, 2488, 2947, 3551, 3526, 3683, 4141, ...

Which should produce a smoother and more correct diagram.
As mentioned by @MarkRansom:

the goal should be to redistribute the values in a way that preserves
their overall distribution.

Rounding the doubles should work fine in the above case, because the values are very close to integers. In the general case, truncating might be preferred.


Hm, this could probably be done using foldM or similar, but that would require you to convert to and from lists. My first impulse would be to try to write the top-level of example using Applicative style:

import Control.Applicative

example = head $ (,,,,) <$> m <*> m <*> m <*> m <*> m

But that doesn't work directly here, as you want each m to know the list# of the last action.

One way to realize this without breaking up the above structure would be to have a StateT monad transformer take care of passing around the current list#:

import Control.Monad.State

example = head $ flip evalStateT [0,1] $
          (,,,,) <$> m <*> m <*> m <*> m <*> m

This allows us to write m as a list monad with state:

  where m :: StateT [Int] [] Int
        m = do list <- get
               e <- lift list
               put (phi list e)
               return e

Now admittedly, this is a bit advanced. It might be easier to try to restructure phi or use a foldM type solution.


What’s your opinion on a Throw() method?

I would avoid using such statement. It doesn't seem to be a right place for this construction inside ?: operators and I do not see major benefits in using it. I would consider using following options:

1)

Type variable;
if (condition1) variable = value1;
else if (condition2) variable = value2;
...
else throw new InvalidOperationException();

This has a disadvantage that in each line you have variable = but anyway compiler will let you know if you haven't initialized variable value before using it so it won't bother me much.

2) Also if your value1, value2, etc cannot be null then I would consider using this:

var variable =
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    null;
if (variable == null) throw new InvalidOperationException();

P.S.: Of course I cannot be sure without knowing the context but if you have to write such statements frequently then it already seems to be wrong for me, maybe something may be changed on higher level?


First and foremost, is there a way to generalize this function so that I can input any type of data and output the combination patterns on that?

Yes, if you supply the alphabet/element set as input to your function, and treat your output as indices into that alphabet.  Right now, your output is a list of numbers per combination (rather, a string, but see later).  This makes them feasible to use as an index into an arbitrary list.

In the least intrusive form, without modifying existing code, you can add this function that will do what you want.  (It's not efficient, though.)

/** Returns a list of all combinations over <var>alphabet</var> of length <var>patternLength</var>. */
public static <T> List<List<T>> choosePatterns(List<T> alphabet, int patternLength) {
    final int n = alphabet.size();
    String[] patterns = choosePatterns(n, n - patternLength, combi(n, patternLength));
    List<List<T>> retval = new ArrayList<>();
    for ( String pattern : patterns ) {
        List<T> list = pattern.chars()
                .map(Character::getNumericValue)
                .map(i -> i - 1)
                .mapToObj(alphabet::get)
                .collect(Collectors.toList());
        retval.add(list);
    }
    return retval;
}

/** n \choose k */
static int combi(int n, int k) {
    int result = 1;
    for (int i = 0; i < k; i++) {
        result *= (n-i);
        result /= (i+1);
    }
    return result;
}

/* Example usage */
public static void main(String[] args) {
    List<String> alphabet = Arrays.asList("C", "A", "T", "G");
    for ( List<String> pattern : choosePatterns(alphabet, 3) ) {
        System.out.println(pattern);
    }

    List<?> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
    for ( List<?> pattern : choosePatterns(numbers, 3) ) {
        System.out.println(pattern);
    }
}

  Secondly, are there ways to optimize these methods so it runs in the faster time possible?

Yes, if only because you're working with Strings/objects where you don't really need to.  But it depends on how far you want to take it.

On the surface, there are a number of inefficiencies that you can eliminate:

Working with List<Integer> rather than int[] : all your lists are fixed-size.  Working with arrays will allow you to use primitives, which will improve performance when making calculations.  (When not making calculations, this difference is still noticeable but much less pronounced.)
Returning String rather than int[] : if you return the indices in directly usuable form, you can avoid having to translate back and forth when using them, and also reduce the number of object allocations.  (Allocations are cheap but not free.)
data = new StringBuilder("") : it's typically cheaper (but not as 'clean') to wipe your current buffer than to allocate a new one.  For reasons beyond my comprehension, StringBuilder does not have a clear() method, but you can use delete(0, xyz.length()).  (Even better to just not use Strings, then this becomes moot.)

Depending on your use case, you can also consider a different approach (*).  Right now, you generate all possible combinations before returning.  If you don't need all combinations at the same time, this may be overkill.  (If you do, then making them all in one go is probably the most efficient.)

(*) Because the set of possible combinations is enumerable, you can assign a unique number to a combination, given an alphabet and a pattern length.  Meaning you can have a mapping function, i → combination(alphabet, k), as the base of an (spl)iterator or even a java.util.List implementation with a very efficient contains operation.  But that may be beyond the scope of this answer.


Bash script to send notifications when low on ram

Kudos to you! This is a nice little script, easy to read and to understand. However, there is no reason to reach for expr. Most shells (including dash or even busybox sh) can interpret arithmetic expressions on their own:

WARNING=$(($total / 5))
CRITICAL=$(($total / 10))

Also, in [ ] expressions, I'd use quotes around variables, to make sure that they don't contain any spaces. In this case, we can be sure that they won't contain some, but it's still good practice to use them:

if [ "$available" -lt "$CRITICAL" ]; then
    ...
elif [ "$available" -lt "$WARNING" ]; then
    ...
fi

Other than that, I'd write the -u comment as a direct negative instead of a positive:

# Don't use `-u critical', as it will keep the notification even after -t ms
# and will cause notifications to queue up.

This comment still contains the same message: "don't use -u critical", but it's much more direct.

Since no bashism are used, we can even change the shebang to #!/bin/sh. By the way, some of those remarks were also found by ShellCheck, but it rightfully marks them as info level only.