Multiple random falling objects animation in Java

Well done, you're making good progress.

Structural changes:

You should not be reusing the squares. Reusing objects is more efficient, and is great for things like particle systems (where tons of particles are created and destroyed every second). But your program is nowhere near resource intensive enough that reusing objects is necessary.

Reusing objects is unclear. It's not always easy to reset an object to it's original state and is not always clear when an object is reset.

You should create a new square whenever you need one, and remove them from your list when they reach the bottom.

Below is a review of the code as it currently is. Some of it will be obsolete when you stop reusing squares, so keep that in mind.

The game class:

import javax.swing.*;
import java.awt.*;

Be careful with importing .* you're importing a lot of stuff you don't need, this makes reading the code harder.

When reading code you're always wondering about the intent of the author. "Did they really mean to use a string there", and other questions like them. So as an author, you have to try your hardest to be clear about your intent. This involves not importing everything, but only the things you need.

As a side note, I talk a lot about the reader, and other people reading your code, which you might not be too worried about if you're working alone. In that case please remember that you will have to read your code as well. If you come back to your code in six months, it will be like you've never seen it before. So please make it easy on yourself, and show your intent as clearly as you can.

public class Game extends JPanel {

Game is an ok name, but you could be a bit more precise, what kind of game is it?

    //changing these values will change the size of the game, while still remaining functional
    //within the size limit specified.
    public static final int WINDOW_WIDTH = 600;
    public static final int WINDOW_HEIGHT = 400;

    //Creates a Square object Array
    Square[] squareArray = new Square[20];

While arrays are the most efficient, in this case I think it's better to use a list instead. Using a list will make it much easier to add and remove squares.

The 20 you use in the array can be a constant (TOTAL_AMOUNT_OF_SQUARES).

    public Game() {

        //initializes square objects
        for (int i = 0; i < squareArray.length; i++)
            squareArray[i] = new Square();
    }

I noticed that every method in this class starts with an empty line. This is not necessary and looks a bit sloppy.

    public void paint(Graphics graphics) {

        //makes background black

This comment is not really nessesary. The code it describes is self explanatory. It can create some annoying mistakes, because it is easy to forget to change the comment when you change the code. Here is some nice discussion on when to use comments. Be sure to look around the related questions as well.

        graphics.setColor(Color.black);

The background can be made into a constant as well (BACKGROUND_COLOR).

        graphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

        //paints square objects to the screen
        for (Square aSquareArray : squareArray) {
            aSquareArray.paint(graphics);
        }

The name of the square in the loop does not have to be aSquareArray, but can simply be square. so the line can read "for (Square square: squareArray)".

    }

    public void update() {

        //calls the Square class update method on the square objects
        for (Square aSquareArray : squareArray) aSquareArray.update();
    }

Always use brackets for loops. I know, I know, they take up a lot of space, but if you don't use them, you will run into some nasty problems. (to bracket or not to bracket, has by this point turned into somewhat of a holy war, but especially for beginners I recommend using them, because even though they take up space, they promote clarity).

    public static void main(String[] args) throws InterruptedException {

        Game game = new Game();
        JFrame frame = new JFrame();
        frame.add(game);
        frame.setVisible(true);
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Raining Multiple Squares");
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);

This whole frame setup is pretty long, you could consider moving it to it's own method, just to keep it out of the way.

        while (true) {
            game.update();
            game.repaint();
            Thread.sleep(10);
        }
    }
}

The Square class:

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Square extends JPanel {

Square does not have to extend JPanel, and actually it shouldn't. Because it's not a JPanel.

    private int squareXLocation;
    private int squareSize;
    private int squareYLocation = -squareSize;

The square size is still 0 at this point, so you're setting the location at 0 again.

    private int fallSpeed = 1;

Setting fallspeed is not necessary, since you're changing it later anyways.

    Random rand = new Random();

    /*
    //creates a random value inside the window and stores it in squareXLocation
    */
    public int generateRandomXLocation(){
        return squareXLocation = rand.nextInt(Game.WINDOW_WIDTH - squareSize);
    }

This method returns an int that isn't used anywhere. Either use that int to set the location, or don't return anything.

The generate methods should not be public. They should only be used by the square, and not outside of it. Make them private. Always make methods as private as possible.

    /*
    //creates a random value between 1-50 and stores it in squareWidth
    */
    public int generateRandomSquareSize(){
        return squareSize = rand.nextInt(50);
    }

    /*
    //creates a random value that is not zero and stores it in fallSpeed(so squares do not get stuck at 0 speed)
    */
    public int generateRandomFallSpeed(){
        return fallSpeed = rand.ints(1, 1, 10).findFirst().getAsInt();
    }

You can replace rand.ints(1, 1, 10).findFirst().getAsInt() with rand.nextInt(9)+1; to simplify.

    /*
    //paints the square with the variables generated in the random methods
    */
    public void paint(Graphics g){
        g.setColor(Color.CYAN);
        g.fillRect(squareXLocation,squareYLocation,squareSize,squareSize);
    }

The color can be made into a constant or a variable (SQUARE_COLOR) to allow for easier changing later on.

    /*
    //sets the squareWidth and square fallSpeed to a random value for every square created
    */
    public Square(){
        generateRandomXLocation();
        generateRandomSquareSize();
        generateRandomFallSpeed();
    }

You're forgetting to reset the y location at this point. You'll also notice that this code is exactly the same as the code in the if(squareYLocation >= Game.WINDOW_HEIGHT){ block. This is a good moment to abstract this code. You can create a "reset()" method here and call all the generate code from there. Then you can reuse the reset method in both places.

    public void update(){

        //changes the squares xLocation and fallSpeed if the created square reaches the bottom of the screen
        if(squareYLocation >= Game.WINDOW_HEIGHT){
            generateRandomXLocation();
            generateRandomFallSpeed();
            generateRandomSquareSize();
            squareYLocation = -squareSize;
        }

        //moves the square down if the square is inside the window
        if(squareYLocation <= Game.WINDOW_HEIGHT){
            squareYLocation += fallSpeed;
        }
    }
}


You iterate twice over the children in both branches. Avoid that by combining these lines

children = [child for child in getChildren(current) if child not in removed]
stack.extend((child, 0) for child in children)

to

stack.extend((child, 0) for child in getChildren(current) if child not in removed)

and these

children = [child for child in getChildren(current) if child not in removed]
for child in children:

to

for child in getChildren(current):
    if child not in removed:

Instead of looping in Python and moving one item at a time here

    scc = []
    while not scc or scc[-1] != current:
        scc.append(subtree.pop())
    sccs.append(tuple(scc))

try to use slicing like this. A possible disadvantage is that index searches from the beginning.

    i = subtree.index(current)
    scc = tuple(reversed(subtree[i:]))
    del subtree[i:]
    sccs.append(scc)

Use local variables to reduce dictionary lookups. You can also bind methods such as stack.pop to local variables to avoid attribute lookup inside the loop.
Also to reduce dictionary lookups, you could combine index and lowlink dictionaries. Put the pair of values in as a tuple or a list to take advantage of unpacking into local variables:

next_index = next(indexCounter)
index[current] = [next_index, next_index]
...
index_current, lowlink_current = index[current]


Code organization

This is usually a cause for concern:

Solution solution = new Solution();

Programming contests do not generally require much object design. And in this particular case, instance methods just obfuscate reading. Make them public static. And if it gets so big that you need to divvy it up, do it properly, then.

This is usually a cause for concern, too:

    }catch(IOException e){
        e.printStackTrace();
    }

Just throw the exception, if you cannot do anything with it. And some automated judges show you the STDERR but not STDOUT, so you may be wasting your chance to see whether something went wrong or you returned wrong answer, and what went wrong. (Just knowing if your program has thrown an exception is good. If the automated judge does not support exception but supports process exit codes, you do a System.exit if an exception thrown.)

Performance

Some contests test your code with just small and large data sets, which means you need to find and algorithm with good average complexity. Some contest, such as ACM, tests the code also with the known worst case scenarios of the best known algorithms that could be used to solve the problem. In that case you need to find good worst case complexity.

Some contests have inputs to weed out naive implementations as your current one. One such case would be 1000X1000 grid of 1s, and 500X500 pattern of 1s with a 2 in the bottom right corner. Against such a case you can try an algorithm like :

Scan the pattern, find the row with most diversity (e.g. with the most elements which have a different value to its right)
for each row in the grid do a KMP substring search.
for each match compare the rest of the pattern in the grid, using the row and column offset of the match.

Which, I believe, will have a complexity : O(R(C+c) + m(rc)), where m is the number of the matches for the pattern row used; which can still be bad for large m. In that case you can do a search for a pattern column in parallel (real or simulated).


I would find the alphabetically smallest and largest string and just run your algorithm on these two. That would avoid the embedded loop.

var longestCommonPrefix = function(strs) {
    if (!strs)
        return '';

    let smallest = strs.reduce( (min, str) => min < str ? min : str, strs[0] );
    let largest  = strs.reduce( (min, str) => min > str ? min : str, strs[0] );

    for (let i=0; i<smallest.length; i++) {
        if (smallest[i] != largest[i])
            return smallest.substr(0,i);
    }

    return '';
};

In answer to konijn it would be minimally faster to get the smallest/largest by doing:

let smallest = strs[0];
let largest  = strs[0];
for (let i=1; i<strs.length; i++) {
  let s= strs[i];
  if (s > largest)  largest = s;
  if (s < smallest) smallest = s;
}


Find largest smaller key in Binary Search Tree

Your code works correctly now (as far as I can tell). But due to

int temp = Math.Max( FindLargestSmallerKey(num, root.left), FindLargestSmallerKey(num, root.right));

it always traverses the entire tree. This can be improved:

If root.key < num then root.key is a possible candidate for the result,
better candidates can only exist in the right subtree.
Otherwise, if root.key >= num, keys less than the given bound can only
exist in the left subtree.

That leads to the following implementation:

public static int FindLargestSmallerKey(uint num, BstNode root)
{
    if (root == null) {
        return -1;
    } else if (root.key < num) {
        int tmp = FindLargestSmallerKey(num, root.right);
        return tmp != -1 ? tmp : root.key;
    } else {
        return FindLargestSmallerKey(num, root.left);
    }
}

This is faster because at each step, only one subtree is inspected instead of both, so that the time complexity is limited by the height of
the tree. If the tree is balanced then the result is found in \$ O(\log N) \$
time where \$  N \$ is the number of nodes.

The same idea can be used for an iterative solution:

public static int FindLargestSmallerKey(uint num, BstNode root)
{
    int result = -1;
    while (root != null) {
        if (root.key < num) {
            // root.key is a candidate, continue in right subtree:
            result = root.key;
            root = root.right;
        } else {
            // root.key is not a candidate, continue in left subtree:
            root = root.left;
        }
    }
    return result;
}

I would also add a more comprehensive set of unit tests. Start with
the simplest trees, for example

   10       10      10        10
           /          \      /  \
          5            15   5    15

and call your function with num from 1 to 20. That would already
have helped to find the flaws in your initial implementation.


The most obvious improvement would be to use LINQ's Where method to filter the lines list instead of building up a list of to-be-deleted items and then deleting them. In addition to being easier to read and understand it will have the benefit of its runtime not being quadratic in the length of lines.

You can also use the List<T>.RemoveAll method which also takes a predicate like Where (though the predicate specifies the items to be removed, so it's in a way the opposite of Where), but modifies the list in-place, like your solution did.


Querying the probability of choosing even or odd elements in a subarray

Well, first you should properly format your code. Readability means maintainability, and fewer bugs.

Try to avoid type-conversions and casts. They are danger-points, and if you use a decent warning-level, your compiler should warn about potentially dangerous type-conversions at least.
In gcd() you use int everywhere but once, where you use unsigned int. Fix that.

You have three query-types, and you seem to desperately want to make them share code. Don't do that! Branch-misprediction is expensive, and moving work out of inner loops is always a win. Hopefully, your compiler will do it for you, so the compiled code does not suffer from your choice like the source code does.

Take a look at which compound-assignment-operators are available. They make assignments more readable and concise.

Try to declare your variables in the smallest scope you can for better readability. Even if you insist on strict C89 with GCC builtins, you can go further.

Don't assume success! scanf() and malloc() can fail, so check for it.

Don't cast the result of malloc(). It's unnecessary and error-prone.

Normalize the range early-on for ease of use. A pointer and a length are sufficient unless you need the position in the surrounding array, and you don't.

You might want to experiment with using a bit-vector, or representing the array as spans of odd / even numbers.


This is somehow the most obfuscated code that I seen on this year perhaps, but it's not that bad, at least not after spending some time to figure it out.
But that's why we are here, to make it better.

For this review I will be replacing Controller.random with new Random(1) for simplification.

public Round nextRound() {
    int playersRemaining = getPlayerCount();
    List<Player> nextPlayers = new ArrayList<>();
    while (playersRemaining > 0) {
        playersRemaining = addPlayers(nextPlayers, playersRemaining);
        if (remainingPlayers.isEmpty()) {
            populateRemainingPlayers(nextPlayers);
        }
    }
    return new Round(game, nextPlayers);
}

There are some things that are not intuitive on your while body.

addPlayers update playersRemaining, letting us being uncertain on when the while exits
seems that populateRemainingPlayers can run more than once
You are adding players from remainingPlayers in populateRemainingPlayers and removing on addPlayers
and in the end it's hard to tell what you are really trying to achieve on your algorithm

public void addPlayers(List<Player> players) {
    this.allPlayers.addAll(players);
    this.remainingPlayers.addAll(players);
    Collections.shuffle(this.remainingPlayers, new Random(1));
}

If the game had a list of all players you probably could initialize the lists on the constructor instead of doing it on this method.

I tend to hate method that receive a list as a parameter and then add elements to it (like addPlayers(List<Player> nextPlayers, int playersRemaining)), but I have some good reasons to do so:

The caller needs to instantiate the list
The method that receives the list may need to call other methods with that same list
Which means that elements can be added to the list in different methods
You should separate data handling from logic handling
You can test more easily a method that returns a list that is ready to use

Let's resume your need so we can achieve a better solution.
It may be a little bit bad worded but I did the best I could.

If the game does not allowDuplicatePlayers then the player list should have enough players to play the game, however it may have more
If the list have more players than necessary, then we want to keep track of the last player that was able "to play", so all the players are able to play
After all the players have played it seems you want to have a different player order
If the game allowDuplicatePlayers you can take as many players needed from the player list sequentially, going back to start if necessary taking the same player more than once

Let's try to implement something along those lines:

private int idxLastPlayer;
public Round nextRound() {
    return new Round(game, getNextPlayers());
}

private List<Player> getNextPlayers(){
    int playersRemaining = getPlayerCount();
    List<Player> players = new ArrayList<Player>();
    for(int i = 0; i < playersRemaining; ++i){
        //with idxLastPlayer we still round robin players if game.allowDuplicatePlayers()
        int idx = (i + idxLastPlayer)%remainingPlayers.size();
        players.add(remainingPlayers.get(idx));
        ++idxLastPlayer;
    }
    updateRemainingPlayers();
    return players;
}

private void updateRemainingPlayers(){
    int playersRemaining = getPlayerCount();
    if (!game.allowDuplicatePlayers()){
        int nPlayers = Math.max(playersRemaining, remainingPlayers.size() - 1);
        for(int i = 0; i < nPlayers; ++i){
            remainingPlayers.remove(0); //removing from the start it's not the best but let's not worry about it
        }
    }else{
        //we can keep remainingPlayers always on the same state
        //Todo Should we shuffle players when we reach the end? But we could leap to an index > 0...
        return;
    }
    //if we no longer have enough players we need to reset remainingPlayers with allPlayers
    if(remainingPlayers.size() == 0 ||
        remainingPlayers.size() < playersRemaining && !game.allowDuplicatePlayers()) //this will discard the last allPlayers.size() % playersRemaining players
    {
        //Todo prioritize the players that were still on remainingPlayers?
        remainingPlayers = new ArrayList<Player>(allPlayers);
        //Start the next round on a different order
        Collections.shuffle(this.remainingPlayers, new Random(1));
    }
}


Mockup in C of hardware implementation for multiplication of signed integers

Sign bit manipulation unnecessary

I looked at your code and was puzzled by all the sign bit manipulation.  As far as I can tell, it's not necessary.  I rewrote your function to be like the following and it still passed all your tests:

int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += ((a & (1 << bit.index)) ? b << bit.index : 0);
    } while (bit.index--);

    return prod;
}

Bonus answer: no conditionals inside loop

int multiply(int a, int b)
{
    // Bit keeps track of mask bit index.
    struct {
        unsigned int index: 5;
    } bit = {31};
    int prod = 0;

    do {
        prod += (-((a >> bit.index) & 1)) & (b << bit.index);
    } while (bit.index--);

    return prod;
}

Explanation:

((a >> bit.index) & 1) is 1 or 0 depending on the masked bit.  Call this B.
-B is -1 or 0.  This sets up a mask to use for the next step (-1 is a mask of all one bits).
-B & (b << bit.index) is either (b << bit.index) or 0.


Converting an input of space delimited integers to a list

Releasing memory

If you assign None to your variables, their contents is lost and the memory will (eventually) be reclaimed.

tablou = input("Enter values delimited by space: ")

b = tablou.split()
tablou = None

t = [] # initial  list with int() contents

for l in b:
    r = int(l)
    t.append(r)
b = None
l = None
r = None

Forgetting the variables

The variables tablou, l, b, and r will still exist; they will just contain the value None.  If you accidentally use the variable tablou again, you won't get a NameError: name 'tablou' is not defined, although you may get an error stating the operation cannot be performed on the value None.

Better would be to delete the variables when they are no longer needed:

del tablou
del l, b, r

After deleting the variables, it is an error to refer to them again, without first storing a value under that name.

List Comprehension

Repeatedly appending values to a list is an expensive operation.  It is usually faster to create the list using "list comprehension".

First, note that instead of this ...

t = []

for l in b:
    r = int(l)
    t.append(r)

... you could write this, eliminating the r variable:

t = []

for l in b:
    t.append(int(l))

Then, you can replace the list creation, loop, append with the following:

t = [ int(l) for l in b ]

This does the same thing as the former code, but without the repeated append call.  As a bonus, the list comprehension variable, l does not escape into the local scope; there is no need to del l.

Mapping

Applying the same operation to every element of a list is called a "mapping", and Python comes with a built in function map() to do just that.

In your specific case, you are calling int( ) on every item in the list b, so instead of:

t = [ int(l) for l in b ]

you could write:

t = list(map(int, b))

Advance topic: The map() function actually returns an iterator, rather than a list.  In many cases, you can avoid the call to list(), which iterates over all the items the iterator can produce and builds a list of out them, and simply use the returned iterator directly.

One-liner

You can reduce your code to one line, removing all temporary variables, using nested calls:

t = list(map(int, input("Enter values delimited by space: ").split()))

I don't recommend it, however.  It does not result in easy-to-understand code.  It is better to separate "user input" from "processing".

Variable Names

t, r, l and b are horrible variable names.  Name the variables with longer, descriptive names.


I'll blame the extra-weird broken indentation on copy/paste difficulties, and ignore that.

There are as many ways to write a calculator as there are programmers willing to write one. So I'm not going to suggest other ways, instead I'm going to hint at how you could improve the flexibility of what you've got.

The first concern you have, is getting user input. Your code works when the sky is blue and the user isn't being too clever.

  QA engineer walks into a bar. Orders a beer. Orders 0 beers. Orders 999999999 beers. Orders a lizard. Orders -1 beers. Orders a sfdeljknesv.

  https://twitter.com/JimFraeErskine/status/527564769302433792

What happens if you play the QA engineer here?

Console.WriteLine ("What is your first number?: ");
num01 = double.Parse (Console.ReadLine());

Your code is making the assumption that the user will enter a valid double! Look into TryParse, and write a separate function with the sole purpose of turning a string into a double. I'd actually make that function return a double? (or Nullable<double>, so that the calculator knows the number isn't valid when that function returns a null).

Console.WriteLine ("\nPlease select one of the following (1-4)");
Console.WriteLine ("1 - Add");
Console.WriteLine ("2 - Subtract");
Console.WriteLine ("3 - Divide");

Console.Write("Select number 1-3: ");

That's ...rather interesting. It looks like at one point it was intended to support 4 - Multiply, but the idea was dropped and now 4 is an invalid input despite the instructions at the top saying (1-4), and the instructions at the bottom saying 1-3!

How about you take the concern of creating the menu out of there, find a way to encapsulate each operation into its own strategy object, and generate the menu based on how many available strategies you have?

Say you had an enum:

public enum CalculatorOperation
{
    Add,
    Subtract,
    Divide,
    Multiply
}

You could then "map" each enum to a function taking two double values and returning another - that's a Func<double,double,double>:

var strategies = new Dictionary<CalculatorOperation,Func<double,double,double>>
{
    { CalculatorOperation.Add,      (x, y) => x + y },
    { CalculatorOperation.Subtract, (x, y) => x - y },
    { CalculatorOperation.Divide,   (x, y) => x / y },
    { CalculatorOperation.Multiply, (x, y) => x * y },
};

What just happened here? You've given yourself the tools to eliminate that switch block - given userChoice is parsed into a CalculatorOperation instead of just an int, you could do this:

var result = strategies[userChoice](num01, num02);

How does that work? Delegates, my friend. And generics. But delegates, my friend. You see, this:

(x, y) => x * y

Is shorthand for:

delegate(double x, double y) { return x * y; }

Which could just as well be this:

private double Multiply(double x, double y)
{
    return x * y;
}

And, if you had one such method for each operator, you could just as well define your dictionary like so:

var strategies = new Dictionary<CalculatorOperation,Func<double,double,double>>
{
    { CalculatorOperation.Add, Add },
    { CalculatorOperation.Subtract, Subtract },
    { CalculatorOperation.Divide, Divide },
    { CalculatorOperation.Multiply, Multiply },
};

Because the signature double Multiply(double x, double y) matches that of a delegate taking two double parameters and returning a double - that's really all delegates are: functions that you can encapsulate, and pass around as parameters, or store inside a dictionary to execute later.

You could then generate the menu items simply by iterating the dictionary keys.

Now, you'll still have to worry about division by zero and overflows (what happens if you add double.MaxValue and double.MaxValue?), and then separate the concerns.

One of the most important principles, IMO, is the Single Responsibility Principle. Your current code has user input/feedback, validation(?) and the actual logic intertwined, which makes it harder to maintain/extend than it needs to be.

Identify what the concerns are, and extract them into their own methods; monolithic blocks of code are the easiest to write, but the hardest to maintain.


Processing files retrieved through FTP in parallel

Exception order changes processing

This looks really odd to me:

catch (AggregateException ae)
{
    foreach (var ex in ae.InnerExceptions)
    {
        if (ex is ArgumentException)
            Console.WriteLine(ex.Message);
        else
            throw ex;
    }
}

It's basically saying write ArgumentExceptions to the Console, but only until you find an error that isn't an ArgumentException.  Then throw that exception.

I don't like it firstly because it could have different results based on order that the exceptions have been added to the queue and secondly because it discards any exceptions after the first one.

Exceptions for program flow

Having ProcessFiles which is a private method return void and throw an aggregate exception, which is immediately caught in the public caller, feels wrong to me.  You've already collected the exceptions into a queue, why not just have the method return the queue?  The caller can then decide what to do based on the collection being empty or not.


Simple function that simulates survey results based on sample size and probability

As I discovered recently, summing a lot of booleans, where the chance that the value is False is not negligible, can be surprisingly slow.

So I would change your survey result calculation to:

sum([1 for _ in range(sample_size) if r.random() < percent_subscribes])

This allows sum to use its faster integer implementation and you do not sum a bunch of zeros.
Alternatively, you could look at this problem as an application of the binomial distribution. You have some chance that a certain result is obtained and you want to know how often that chance was true for some population. For this you can use numpy.random.binomial:

import numpy as np

def simulate_survey(sample_size, percent_subscribes):
    subscribers = np.random.binomial(sample_size, percent_subscribes)
    return sample_size, percent_subscribes, round(subscribers / sample_size, 2)

Using numpy here may also speed up your process in other places. If you need to run this function many times, you probably want to use the third argument to generate multiple values at once.

IMO, the readability is also greatly increased by using one temporary variable here, instead of your many levels of parenthesis.
I am not a fan of your function returning its inputs. The values of those should already be available in the scope calling this function, so this seems unnecessary. One exception would be that you have other, similar, functions which actually return different/modified values there.
You should add a docstring describing what your function does.


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

Use consistent formatting

Almost every other line in the program is a blank line.  This doesn't really help readability, and then we have lines like these:

if ((j<m-1) && (i<n-2)) { if (map[i+2][j+1]!='x'){ graph[a].push_back(a+2*m+1); }} // x+1 y+2
if ((j<m-1) && (i>1)) { if (map[i-2][j+1]!='x'){ graph[a].push_back(a-2*m+1); }} // x+1 y-2

First, add some whitespace and second, don't jam nested if statements all on one line like that.  These could be reformatted like this:

if ((j < m - 1) && (i < n - 2)) {
    if (map[i + 2][j + 1] != 'x') {
        graph[a].push_back(a + 2 * m + 1);
    }
}                   // x+1 y+2
if ((j < m - 1) && (i > 1)) {
    if (map[i - 2][j + 1] != 'x') {
        graph[a].push_back(a - 2 * m + 1);
    }
}                   // x+1 y-2

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.

Avoid the use of global variables

graph, visited, mydistance and others are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. For example, the visited is only used within BFS, so it should be a local variable there instead of a global.

Eliminate "magic numbers"

In a number of cases, the code uses "magic numbers" such as 990000 that have no obvious meaning.  These would be better as named constants.

Fix the error

This line may be accepted by your compiler, but it is not compliant with the C++ standard:

char map[n][m];

The reason is that the standard will only allow this if both n and m are const and they are not in this program.  One could address that by dynamically allocating the object, as:

char *map = new char[m*n];

And then re-doing all references to change from this:

map[i][j] = x;

To this:

map[i * m + j] = x;

However, I think the better way is in the following suggestion.

Use object orientation

Because you're writing in C++, it would make sense to have methods that operate on a class such as Board and Knight (because the legal moves you describe are those that a knight can make in the game of chess) be member functions rather than separate functions.  You may not yet have learned about objects or classes, but they're one of the main strengths of C++ and something you should learn soon if you haven't already.  Use objects where they make sense.

Have functions return something useful

Instead of a void function, it would make more sense to have BFS() return the distance.

Omit return 0

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


In a sense, your code has already been reviewed, though I disagree with the excessively negative assessment.  It is far from being awful and some of the worst JavaScript code ever.

you manually concatenate your data string instead of using the JSON library

As the documentation for $.ajax() says:

  The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent.

To create the query string from the form, you could take advantage of the .serialize() function.

So, that's what you should use instead.  Concatenating your own data is wrong because you are failing to escape special characters.  If any of the fields contains a =, &, or % character, the application will break — possibly in a way that introduces a security problem.
Your selectors are terrible ($('div#foo') instead of $('#foo'))

From the jQuery Learning Center:

  Beginning your selector with an ID is always best. … ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

So do that.
you compare things with == instead of ===

The == operator does type conversion.  In this case, all of your comparisons are between strings anyway.  Using === would be better practice, but use of == in this code is not that harmful.
you return false instead of preventing the default action alone

Your version works, but event.preventDefault() is clearer.
copy-paste code all over the place

"All over the place" is an exaggeration.  However, it would be better to extract repeated code into a function.

$('.button').click(function(event) {
    function checkRequiredFieldFilled(fieldSelector, errorSelector) {
        if ('' === $(fieldSelector).val()) {
            $(errorSelector).show();
            $(fieldSelector).focus();
            return false;
        }
        return true;
    }

    $('.error').hide();
    var ok = checkRequiredFieldFilled('#phone', '#phone_error') &
             checkRequiredFieldFilled('#email', '#email_error') &
             checkRequiredFieldFilled('#name',  '#name_error');
    if (!ok) event.preventDefault();
}

Note that this version validates all of the fields at once and focuses on the first field with a problem, to provide a better user experience.


Checking to see if a string is alphabetic

It's not harder than this:

public static boolean checkAlphabetic(String input) {
    for (int i = 0; i != input.length(); ++i) {
        if (!Character.isLetter(input.charAt(i))) {
            return false;
        }
    }

    return true;
}

The idea is to return false as soon as you encounter a character c for which Character.isLetter returns false. If no such, return true since the string does not contain non-letter characters.


Maybe something like this?

success: function (json) {
  var decorators = {},
      handlers = {};

  // decorators prepare content for insertion
  decorators.naslov = stripslashes;
  decorators.tekst  = stripslashes;

  // specialized handlers
  handlers.tag_title = function (value) {
    // do the tokenization-stuff here
  };

  // Go through the response
  $.each(json, function (index, item) {
    var value = item.value;
    // if the field has its own handler, use that
    if( typeof handlers[item.field] === "function" ) {
      handlers[item.field](value);
    } else {
      // Otherwise, send the value through the decorator
      // (if there is one for the given field), and
      // insert the value in the corresponding input
      if( typeof decorators[item.field] === 'function' ) {
        value = decorators[item.field](value);
      }
      $("#" + item.field).val(value);
    }
  });
}


Validating CSV headers against an expected list

Move the data column validation into a function

bool invalidDataColumns(string[] headers) {
    int[] numbers = headers.Skip(2).Select(s => int.TryParse(s, out var n) ? n : 0).ToArray();
    return !(numbers[0] == 1 && numbers.Zip(numbers.Skip(1), (previous, current) => current - previous).All(diff => diff == 1));
}

And call it within the if condition.

//...

if (!string.Equals(headers[0], "Marker", StringComparison.InvariantCultureIgnoreCase)
    || (!string.Equals(headers[1], "Category", StringComparison.InvariantCultureIgnoreCase))
    || invalidDataColumns(headers)
    ) {
    throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv).");
}

//...

The condition could be reduced further by moving the entire thing into its own function as well

bool invalidHeaders(string[] headers) {
    return !string.Equals(headers[0], "Marker", StringComparison.InvariantCultureIgnoreCase)
        || (!string.Equals(headers[1], "Category", StringComparison.InvariantCultureIgnoreCase))
        || invalidDataColumns(headers);
}

which now simplifies the code to

//...

if (invalidHeaders(headers)) {
    throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv).");
}

//...

Unit test used to verify expected behavior

[TestClass]
public class InvalidDataColumnsTests {
    [TestMethod]
    [DataRow("Marker,Category,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15", false)]
    [DataRow("Marker,Category,1,2,3,4,5,6,7,8,9,10", false)]
    [DataRow("Marker,Category,1,2,3,4,5", false)]
    [DataRow("Marker,Category,x,2,3,4,5,6,7,8,9,10", true)]
    [DataRow("Category,1,2,3,4,5", true)]
    public void Should_Validate_Columns(string headerLine, bool expected) {
        //string headerLine = "Marker,Category,1,2,3,4,5,6,7,8,9,10";
        string[] headers = headerLine.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        invalidHeaders(headers).Should().Be(expected);

        ////Example Use case
        //if (invalidHeaders(headers)) {
        //    throw new Exception("Invalid file format. Please use template (MarkerTemplate.csv).");
        //}
    }

    bool invalidHeaders(string[] headers) {
        return !string.Equals(headers[0], "Marker", StringComparison.InvariantCultureIgnoreCase)
            || (!string.Equals(headers[1], "Category", StringComparison.InvariantCultureIgnoreCase))
            || invalidDataColumns(headers);
    }

    bool invalidDataColumns(string[] headers) {
        int[] numbers = headers.Skip(2).Select(s => int.TryParse(s, out var n) ? n : 0).ToArray();
        return !(numbers[0] == 1 && numbers.Zip(numbers.Skip(1), (previous, current) => current - previous).All(diff => diff == 1));
    }
}


Design considerations for classes/methods using JDBC to ensure resources closed correctly

JDBC has always been a PITA when it comes to handling/closing resources.

One of the big advancements in the past while has been the advent of ConnectionPools and abstraction layers.... If you are inside a framwork like tomcat, or WebSphere, these are built in. Otherwise you can use things like Apache DBCP or C3PO. For both of these frameworks, when you close the Connections it closes any created Statements.

Using a pool like this allows you to trust in the pooling layer... but, I would still recommend that you use a 'clean' implementation for your code. What I have used in the past, and I think is the neatest method, is to have an abstract class like:

public abstract class DBCallable<T> implements Callable<T> {
    private final ConnectionPool pool;

    public DBCallable(ConnectionPool pool) {
        this.pool = pool;
    }

    public <T> call() throws SQLException {
        try (Connection con = pool.getConnection()) {
            return execute(con);
        }
    }

    protected abstract T execute(Connection con);
}

Then, you can do all sorts of things....

For example, you need to populate some widget:

final Widget widget = new Widget();
final ConnectionPool pool = .......

new DBCallable<Integer>(pool) {
    Integer execute(Connection con) {
        try (Statement stmt = con.createStatement()) {
            int count = 0;
            try (ResultSet rs = con.executeQuery("...")) {
                while (rs.next()) {
                    count++;
                    widget.doSomethingWith(rs.get(1));
                }
            }
            return count;
        }
    }
}

You can even supply one of those to an ExecutorService, and get a  Future from it, and then then run these things in alternate threads.

Very versatile.

Edit: If you would prefer to have (easy) access to the Statement instead of the Connection, create an abstract sub-class of the DBCallable:

public abstract class StmtCallable<T> extends DBCallable<T> {

    public DBCallable(ConnectionPool pool) {
        super(pool);
    }

    protected T execute(Connection con) {
        try (Statement stmt = con.createStatement()) {
            return query(stmt);
        }
    }

    protected abstract T query(Statement stmt);
}

Then, if you want a clean statement each time for your code, you can have

new StmtCallable<Integer>(pool) {
    Integer query(Statement stmt) {
        int count = 0;
        try (ResultSet rs = stmt.executeQuery("...")) {
            while (rs.next()) {
                count++;
                widget.doSomethingWith(rs.get(1));
            }
        }
        return count;

    }
}


I don't know how you are using this information, but I think that you could create a very small table variable or temp table with like one column and then sort and select the information in order.

DECLARE @Table1 TABLE
(
     Dimension VARCHAR(10),
     Size DECIMAL(4,2)
)

INSERT INTO @Table1
(
     Dimension
     , Size
)
VALUES
('Length', @lLength),('Width', @lWidth),('Height',@lHeight)

SELECT * FROM @Table1 ORDER BY Size DESC

This eliminates 3 variables and all if statements (which are not very efficient in RDBMS's)
Setting variables over and over again is not very efficient in a RDBMS.

you can select these into the variables like this

SET @lMax = SELECT TOP (1) FROM @Table1 ORDER BY Size DESC
WITH orderedTable AS
(
    SELECT Size, ROW_NUMBER() OVER (ORDER BY Size) as `RowNumber`
    FROM @Table1
)
SET @lMid = SELECT Size FROM orderedTable WHERE RowNumber = 2;

WITH orderedTable AS
(
    SELECT Size, ROW_NUMBER() OVER (ORDER BY Size) as `RowNumber`
    FROM @Table1
)
SET @lMin = SELECT Size FROM orderedTable WHERE RowNumber = 3;

I am sure that Phrancis could come up with a better query than this, especially because I call the same CTE twice and I know that it could be more efficient perhaps with a temp table or something.

after seeing what @Phrancis is going to post I came up with something to get rid of the second CTE

because there are only 3 numbers you can subtract the middle number and the largest number to retrieve the minimum number using mathematics, like this

SET @lMax = SELECT TOP (1) FROM @Table1 ORDER BY Size DESC
WITH orderedTable AS
(
    SELECT Size, ROW_NUMBER() OVER (ORDER BY Size) as `RowNumber`
    FROM @Table1
)
SET @lMid = SELECT Size FROM orderedTable WHERE RowNumber = 2;
SET @lMin = SELECT (SUM(Size) - @lMid - @lMax) FROM @Table1 --Thanks @Phrancis

So the Whole thing looks like this

DECLARE @Table1 TABLE
(
     Dimension VARCHAR(10),
     Size DECIMAL(4,2)
)

INSERT INTO @Table1
(
     Dimension
     , Size
)
VALUES
('Length', @lLength),('Width', @lWidth),('Height',@lHeight)

SET @lMax = SELECT TOP (1) FROM @Table1 ORDER BY Size DESC
WITH orderedTable AS
(
    SELECT Size, ROW_NUMBER() OVER (ORDER BY Size) as `RowNumber`
    FROM @Table1
)
SET @lMid = SELECT Size FROM orderedTable WHERE RowNumber = 2;
SET @lMin = SELECT (SUM(Size) - @lMid - @lMax) FROM @Table1 --Thanks @Phrancis

I removed SELECT * FROM @Table1 ORDER BY Size DESC because we are filling in the variables in a different way.

If you were using this information in a program or something then I would tell you to just do it there, but it sounds like you are stuck in SQL Server


Welcome to Code Review, and welcome to Java! Overall your code is clean and easy to understand, so thank you for that.

Enums

Storing these values in a string array is not very extensible:

public final String[] SUITS = { "H", "D", "C", "S" };
public final String[] RANKS = { "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2" }

The first thing to note is that a List provides more options and flexibility than a raw array.  However, I think it would be best to store these values as an Enum:

public enum SUITS {
    H, D, C, S
}

This will allow you to use these values in a switch statement, and provides other benefits.  Most of all, it is more readable and more extensible.

Variable Names

I would strongly recommend against single letter variable names outside of simple constructs such as for (int i = 0; i < something; i++);.  Instead of H, D, C, and S, I would just spell them out as HEARTS, DIAMONDS, etc.  There is no disadvantage to using the extra characters to make the code more readable. In the rest of your code you do not make this mistake, so that is good.

Improper OOP

I do not think that Hand should inherit from Deck:

class Hands extends Deck {

I would advise that you think about inheritance as an "is a" relationship.  A hand is not a deck, and should not be treated like one. For example, it is unlikely that you will need to "shuffle" a hand.  To me, this is the same as having Hand or Deck inherit from a Card.  It is not going to end up being helpful to the organization or understanding of the code.

I don't understand why Cards is a class:

public class Cards {

A singular Card should be the class here.  Then, the Hand and Deck can have a "has a" relationship with cards, and use Card objects.  The way you have this set up here:

    List<String> cards = new ArrayList<>();
    Deck deck = new Deck(cards);
    deck.shuffle(cards);

    Hands hands = new Hands();
    hands.getHand(cards);
    hands.showHand();

really does not make a whole lot of sense.  Why would a Cards object have Decks or Hands as objects?  It should definitely be the other way around.

I look forward to seeing a revised version of your code in another question!


Making an alphabatical list grouped by letters

Well, you have a good learning exercise project. here is some notes on the artiest code you've provided :

You're using string query, which opens SQL Injections. To overcome that, you'll need first to mark your query as const or readonly and end the query with a semicolon (which you did), and ensure that the query itself not having any SQL bugs that might be used in inappropriate way. However, if you want the proper way to manager your database, you can use Object-relational Mapping AKA ORM such as Entity Framework.
Store images in a psychical disk and store their path (or filename) into the database. Storing the file bytes into the database would impact the system performance as you'll need to read and render the images every time you select them. While if you store the files physically, it would be faster to render. So, create a folder inside the project folder, store the images in that folder (in any structure you want) then store the path of each image in the database. Then, in your application, you just get the path, adjust the path to be viewable to the user. For example, if the stored path images/artists/someartist.png then you just add the current web url to it like https://www.somewebsite.com/images/artists/someartist.png.
Always use PNG images for web, as png images are more balanced between the quality and size, and would be better option than other types for the web.

In your code, sorting operations should not be done on the presentation layer, in fact, it would be more beneficial if it's moved to early application stages like sorting artists in your case, your application has a core feature to filter artists names in alphabetical order. This means, this functionality needs to be applied to the data before it's even inserted to the database, because it's used as a core feature and not an addon functionality.
There are different ways to do it though, one way is to add a property stores the first name letter like this :
public class LibraryArtistViewModel
{
    public char FirstLetter => FirstName?.Length > 0 ? FirstName.ToUpper()[0] : char.MinValue;

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get; set; }

    public string PrimarySlug { get; set; }

    public bool HasImage { get; set; }

    public int NumberOfLyrics { get; set; }

}

Then, you would do this in GetAllArtistsAsync():
  while (await reader.ReadAsync())

      {
        var artist = new LibraryArtistViewModel
        {
            FirstName = reader[0]?.ToString(),
            LastName = reader[1]?.ToString(),
            FullName = textInfo.ToTitleCase($"{reader[0]?.ToString()} {reader[1]?.ToString()}"),
            PrimarySlug = reader[2]?.ToString(),
            HasImage = reader[3] != System.DBNull.Value;
            NumberOfLyrics = int.TryParse(reader[4]?.ToString(), out int number) ? number : 0;
        };

        artists.Add(artist);
      }

    var dictionary = artists.GroupBy(x=> x.FirstLetter).ToDictionary(x => x.Key, x => x.ToList()).OrderBy(x=> x.Key);

Though this would give you what you want, it would take out some tiny performance. As I stated before, since your artists are supposed to be sorted, you need to sort it from the time you insert the data, either from the database which would be faster, or on CreateNewArtistAsync action. So, in your Get you won't need to re-sort on every request.


Functions!

Functions are what this code needs. You've already started separating your code logically, which is the first step in creating functions. Just look at your comments. You can start by making each commented section its own function. Of course, this isn't the end of it. We still have to make our PDO connection and query parameters available to these functions, and ideally we will want to make them reusable as well, but it will help us get started. I'll do the first one for you.

function getPeople( $conn, $json_id ) {
    $query = "SELECT people.id, people.surname, people.firstname, people.email, leases.room_id, DATE_FORMAT(leases.in_date, '%e %M %Y') as in_date, DATE_FORMAT(leases.out_date, '%e %M %Y') as out_date, leases.rent_type FROM people, leases WHERE people.id = :json_id AND leases.person_id = :json_id";
    $result = $conn->prepare($query);
    $result->bindValue(":json_id", $json_id);
    $result->execute();
    return $result->fetch( PDO::FETCH_ASSOC );
}

A function is a reusable script. Each function must have a unique name that should be indicative of its purpose. For instance, the above function sets up a query to get a list of people from a database and then returns the results. Thus its name tells us exactly what it is doing and it should do no more and no less. This is a principle called Single Responsibility. As the name implies, the function has one responsibility. Any additional tasks must be delegated to other functions. The two parameters, $conn and $json_id, are components that it needs to do its task. Instead of fetching these components each time, which is beyond the scope of this function's responsibilities, we inject them into our function via the parameters.

Just like PHP, MySQL and PDO do not care about whitespace. I'm still unfamiliar with the SQL syntax to properly space that out for you, but know that you can add as many newlines and whitespace as you need to make that more legible, in fact I would encourage you to.

Reusing our Functions

So, I created the first function for you. If you went ahead and made the other functions, like I suggested, then you might hate me for this, but they will be unnecessary. It was good practice though. You only need one function here. There is a general programming principle called "Don't Repeat Yourself" (DRY). As the name implies, your code should not repeat itself. There are many different ways you can keep your code DRY (variables, loops, and functions to name a few), but we are specifically going to talk about not repeating functionality right now. However, these concepts should be easily transferable to the other aspects of DRY.

How do we know if our code is DRY? If you look at all of those queries, you should begin to notice a pattern. They are all almost identical. This is a clear sign that we can apply the DRY principle. In order to do it with our functions we are going to have to abstract anything that is not exactly the same and inject those properties into our script through some other means. With functions we should do this with the parameters.

function query( $conn, $query, $params ) {
    $result = $conn->prepare( $query );

    foreach( $params AS $key => $value ) {
        $result->bindValue( ":$key", $value );
    }

    $result->execute();
    return $result->fetch(PDO::FETCH_ASSOC);
}

//usage
$params = array(
    ':json_id' => $json_id
);
query( $conn, $query, $params );

As you should be able to see from this, you will no longer need to manually fetch each query, instead you can use this function and pass in the required components. But, as I mentioned above, DRY doesn't stop here. If we were to leave it at this then already our code would be 10 times better, but we are still violating DRY by manually calling our new query function each time we need it. Remember that I mentioned DRY didn't have to be all about functions? Well, how would you handle this? I'll give you a hint, but I'm not going to write this next bit for you.

Mouseover for hint:

   Try using an array and foreach loop.

Bonus

Another thing we can do to help ensure we get the right kind of parameters is to implement something called type hinting. This is a little more advanced and not something you really need to know right now, but simply put, if you add the type of variable you are expecting to get as a parameter, PHP will throw errors and stop execution if any other type is used. This is a good way to ensure our function can do what we are asking of it. For example, if we passed in a non PDO object we should not expect it to be able to use PDO methods, so we could prevent this by explicitly requiring the PDO type.

function getPeople( PDO $conn, $json_id ) {

You'll notice that only $conn has been type hinted. This is because $json_id is a scalar type and is unnecessary to type hint due to PHP's loose typing. If that variable happened to be an int and you needed a string you could just treat it as a string and it would work. And vice-versa. Sometimes this is undesirable and you will have to explicitly check for these types, but you can not do this with typehinting. Instead you would have to use one of the is_*() functions. Replace the wildcard with the type of variable you are looking for (int, string, etc...). You don't really need to understand this right now, but it is a good thing to keep in mind.

Another, much more advanced topic, is OOP. Though I tell this to everyone, get proficient with functions and the concepts I mentioned above before trying to tackle OOP. Once you are fluent with functions, then you should take a look at classes and different OOP strategies.

UPDATE

Sorry for the delay in my answer. I'm typically unavailable over the weekend. This is much better, you still have a minor violation of DRY with that second query(), but overall it is much much better. Let's look at a couple things I missed last time and something new you are doing this time.

Connection

This is something I forgot to mention last time, but you should also abstract all of your connection information so that you can set this up to come from anywhere. Remove the following from your PDO instantiation and replace them with variables.

$dsn = "mysql:host=$host;dbname=$db";
$params = array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" );

The benefit of doing it like this is that you can now abstract all of your connection information to a config file or to any other source to allow for easier extension. The config file would be my suggestion for now as it is fairly simple to implement while still being a pretty powerful tool. I wont go into the specifics on how to implement one here, but a quick Google search should yield immediate results. You can also set up a PHP file with constants to serve as a config file.

Arrays

Another thing I missed was your array. First the $rent_types and now the $queries. Always define your array initially before pushing anything onto it.

$queries = array();
$queries[ 'general' ] = //etc...

Of course, then the better way to do what you are trying to do is to just do it all at once. For instance.

$queries = array(
    'general' => /*general SQL*/,
    'owed'    => /etc...
);

The reason we do this is to avoid accidentally manipulating a preexisting array or string. With an array it probably wont be as noticeable, unless you end up needing that array again elsewhere, but the string should become immediately apparent. Strings can be accessed with array syntax to easier allow for specific character accessing. However, I believe trying to do so with an associative key would cause errors. Likewise, trying to later access a string's contents like an array would yield unexpected results, such as a single letter or NULL. Even if you are 100% sure that you aren't going to have any conflicts, just in case you ever need to extend this later, it is always better to explicitly define it. Besides, you are probably getting a warning initially about how that array is undefined. Make sure your error reporting is turned up so that you can catch these kinds of things.

Variable-Variables

${$label}
//or
$$label

What you are doing here is called variable-variables. For the most part variable-variables, or variable-functions, should never be used. Assume they are, 99% of the time, a bad idea. There are exceptions (MVC Controllers rendering variables for Views and Factories dynamically accessing unknown functions are pretty common), but this is not one of them. The reason variable-variables are so disliked is because of how easy they are to miss, and thus debug. There is also a security concern, because the information you are typically converting to variables is from userland and thus untrustworthy.

For instance, imagine this scenario: The very first thing you did was load your config file for your database connection, but, for some reason, you had to load variable-variables into scope before connecting. It could have been an accident, or a malicious user, but now your connection variables have been overwritten and break the system, or point to another database altogether. The problems just become bleaker and can get down right ugly.

So, instead of using variable-variables, or variable-functions, what we are going to want to do is either do something with the information immediately, thus creating a temporary generic variable, or do the same thing you are currently doing, only with an array.

${$label} = //etc...
//becomes
$query_results[ $label ] = //etc...

As you can see, this is almost identical, except we are using a more verbose array instead. There is less security concern and ambiguity here. For instance, now if we have a key that conflicts with a variable in the current scope it wont interact with it in any way. It has been abstracted, or perhaps namespaced, and thus is safer. It also becomes easier to debug. Instead of having variable-variables that could easily hide among the current scope variables, all we have to do is var_dump() the array to peek at its contents. Everything is self-contained.


Loading Configurations from plist into singleton

I don't have a whole lot to add, as this is pretty straightforward and seems like a completely reasonable way to do what you're trying to do.

In regards to your questions:

There's a tradeoff for using accessor methods for properties. Every time you add a new one, you need to add a constant to the Key struct, and add an accessor method to the Configuration class to get its value. If you misspell either of them (in the plist or the string in the Key struct), you won't have the compiler to tell you so, and you can end up with some odd bugs that become hard to track down. However, I personally prefer the way you're doing it because it's easier to read for the future. Your set of configurations is currently fairly small, so it's pretty easy to maintain. I'd go with what you've got unless you think there will be a lot of configuration options that will be controlled by a plist file.
It's better to read the file in the constructor in my opinion. This is known as RAII - Resource Acquisition is Initialization. The idea being that if you do it in the constructor, if it fails, you don't end up with a partially initialized object.


Yes, that looks good.

Minor comment:  Normally an id is an integer.  Should it have been "i" in your bind_param?

Connection Details

First, I am not a security expert.  However, I would recommend storing the connection details in a location that is not served by your web-server.  It should be somewhere in your PHP include_path or accessible from your autoloader.

Having the file in a directory accessible from your web-server could open up the connection details if you had an incorrectly configured web-server.


PEP 8

Line length

E501:11:80:line too long (107 > 79 characters)
E501:19:80:line too long (110 > 79 characters)

Odd spacing

E222:36:58:multiple spaces after operator

No newline at end

W292:36:71:no newline at end of file

General comments

Main

You want to use __name__ to allow importing without running your code. This explains it better

def main():
    # my code here

if __name__ == "__main__":
    main()

Storing food items

A = ["Big Mac", float(2.50), 50], ["Large Fries", float(0.50), 200], ["Vegetarian Burger", float(1.00), 20]

This may be better represented as either instances of a class, or just namedtuples, making the code more readable, as you access them by name a dictionary may clean up the code for this, rather than a list


I had no trouble figuring it out what it does, but I'm not sure I'd call it "easy to understand".

All the declarations are implicit and thus if you're familiar with all the in's and outs of Array and the map method, it's pretty straight forward what the code is attempting to do. Some of the logic takes a bit of thinking about,

I did puzzle a bit over this line

file_id = lines.index( next_line)

I think the most puzzling part is the unstated requirement that the input files are already sorted. Otherwise this line doesn't work. Once I figured out that this line meant that the input files were sorted, the rest fell into place.

The exit condition is also a bit tricky to figure out.

The code really feels like a translation to ruby from a more explicitly functional language, it doesn't feel "ruby-like" at all.


I think there is nothing wrong with using IDisposable whenever a class requires some sort of clean-up. It might have been originally designed to release unmanaged resources, but it is definitely no longer the case. Nowadays people use IDisposable to do all sort of things: unsubscribe from events, release pooled objects, flush buffers... this list goes on and on.

I also would prefer extension method over other options. It looks cleaner IMHO. What I don't like is the Context word. Not only because the method name should be a verb, but also because its somewhat misleading. I think a lot of people will assume that ...Context class is the class that implements context object (anti-)pattern. But your class doesn't. For example, class LayoutSuspender both sounds funny and describes what the class does. Win-win.

The thing you should be careful about is using this class with nested methods. For example, this:

public void UpdateAllControls()
{
    using (container.SuspendLayoutContext())
    {
        UpdateControlA();
        UpdateControlB();
    }
}

public void UpdateControlA()
{
    using (container.SuspendLayoutContext())
    {
        UpdateControlA();
    }
}

won't work as you want it to. So eventually you might want to implement some sort of reference counting.


Thread Safe Service to Perform Tasks in a Queue

pendingDirs should not be static. It's one thing to maintain a static instance to implement a singleton, but that object should interact with its state using normal instance variables. And you may as well initialize it in its declaration instead of the constructor.

The service should create the thread itself instead of creating it in getService() to make it self-contained. This allows another implementation to use a thread pool for parallel directory creation and easier testing.

getService() is not thread-safe and could allow two or more instances to be created.

Use a blocking queue, so you don't have to poll and sleep. The thread will be put to sleep if the queue is empty and be awoken once a new directory is added to the queue. This will shrink your run loop to a few lines and allow you to rely on the well-tested thread-management in java.util.concurrent.


Find valid triples for a sorted list of integers

1. Review

The code is not portable to Python 3 due to the use of the print statement.
The code is not fully organized into functions: most of it runs at the top level of the module. This makes it hard to understand and hard to test.
It's not allowed in Python to raise a string. If you try this you'll get the following:

>>> findUpperBound([], 0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr143389.py", line 4, in findUpperBound
    raise 'value eror'
TypeError: exceptions must derive from BaseException

What you need is something like:

raise ValueError("no numbers")

But it isn't right to raise an exception when there are no numbers to search. The function is supposed to return an index into numbers that is greater than or equal to start and points after all entries less than or equal to value. So if numbers is empty then it should return start.
Functions for binary search of a sorted sequence are already built into Python: see the bisect module. In this case you'll want to use bisect.bisect_left.
The two nested loops for i and j can be combined into a single loop using itertools.combinations. This leads to the revised code:

from itertools import combinations, islice
from bisect import bisect_left

def triangles(seq):
    """Given a sorted sequence of unique numbers, generate triples a, b, c
    that satisfy the triangle inequality, that is, where a + b > c.

    """
    for i, j in combinations(range(len(seq) - 1), 2):
        a, b = seq[i], seq[j]
        for c in islice(seq, j + 1, bisect_left(seq, a + b, lo=j+1)):
            yield a, b, c

In the general case, the number of triples satisfying the conditions is \$O(n^3)\$. Consider as an extreme case the set of numbers \$\{n, n+1, \ldots, 2n\}\$: in this case every triple satisfies the conditions. So in general you don't lose any asymptotic efficiency by iterating over all the triples:

for triple in combinations(numbers, 3):
    a, b, c = triple
    if a + b > c:
        yield triple

2. Answers to questions

In comments, you wrote:

  I think time complexity is the same of your algorithm and my algorithm.

Yes, the algorithms are identical. The point of using itertools.combinations is to reduce the length of the code and make it clearer, not to change the behaviour.
You asked:

  Wondering if you are thinking of any better algorithm which could improve the time complexity even better?

See §1.7 above — in the worst case there are \$O(n^3)\$ triples satisfying the conditions, so no algorithm can have runtime \$o(n^3)\$ in the general case. Possibly for some distributions of inputs it would be possible to do better, but I don't know.
You asked:

  What do you think is the time complexity of current algorithm you are writing in general (I mean average)?

Before you can describe the average runtime of an algorithm, you have to specify the distribution of inputs. With knowing the distribution of inputs, it's impossible to say.


The algorithms in the standard library which care about order usually have an additional overload that takes a comparison function to replace operator<. It can be useful to compare instances of types that do not have an overloaded operator< or to compare things differently (for example, passing an instance of std::greater<> to std::sort will sort a collection in reverse order). Transforming your algorithm to take such a comparison function is more or less trivial:

template <class RandomIt, class Compare>
void RunAwareMergeSort(RandomIt first, RandomIt last, Compare compare) {
    RandomIt m_first(first); // the begin of first run of merge
    RandomIt i(first); // the locater
    while (true) {
        while (++i < last && !compare(*i, *(i-1))); // locate the first run
        if (!(i < last)) { // i has located the end of the last run
            if (m_first == first) return; // the range has only one run; sorting completed
            else { // the range has odd number of runs
                m_first = i = first; // start over
                continue;
            }
        }
        RandomIt m_middle(i); // the end of first run of merge; the begin of second run of merge
        while (++i < last && !compare(*i, *(i-1))); // locate the second run
        std::inplace_merge(m_first, m_middle, i, compare); // merge
        if (i < last) m_first = i; // next
        else m_first = i = first; // start over
    }
}

From a style point of view, your code could use more braces to avoid a potential Apple goto fail; bug and to let it breathe a bit more. Also, when you have to comment almost every line, it's almost always better to put the full explanation along the algorithm and not into it.

You also seemed to be concerned about the performance of your algorithm. I tested it with several patterns and compared it to several stable sorting algorithms that I had in a library. It always sorts an std::vector<int> with \$10^6\$ elements. Here are the results (Stable sort is std::stable_sort, yours is the natural mergesort, the other algorithms are not in the standard library):

As you can see, you algorithm is a bit better than Timsortfor its worst case (random data) and beats every other algorithm for the very specific "ascending sawtooth" pattern, which corresponds to a succession of ascending data (more or less log2(std::distance(first, last)) in our case). However, it slower than almost any other sorting algorithm whenever the data isn't mostly sorted in ascending order and it really doesn't like descending patterns.


My biggest complaint on readability would be your findmatch() function. There are too many non-descriptive variables (i.e. i, j, p, etc). Changing the names to be more descriptive, or adding some comments to elaborate on what you're trying to do would help a lot.


Three small things:

Firstly, docstrings exist. Use them. Put the explanation for how to use your method in them. That means that instead of this:

# Longest substring with at most 2 distinct characters
#
# Given a string S, find the length of the longest substring T that contains at most 2 distinct characters
#
# For example,
#     Given S = "eceba"
#     T is "ece" which it's length is 3

def longest_substring(string):

you have this:

def longest_substring(string):
    """ Longest substring with at most 2 distinct characters
    Given a string S, find the length of the longest substring T that contains t most 2 distinct characters
    For example,
        Given S = "eceba"
        T is "ece" which it's length is 3"""

At least, if I've understood their purpose correctly.

Secondly, if someone passes in None, that should probably be an error, not a return 0 case. Same if someone passes in a number, Duck, or any other invalid type.

Thirdly, according to PEP8, the official style guide, none of your lines should be longer than 80 characters. The (new) second line violates this; it even did before. Just split it in half and you're good.


This is a design issue, and there's no single answer.

We need to consider what's important about a Weapon.  Is it value-like, or is its identity important?  The real-world analogy is, "are copies all equivalent?".  The answer to this lies partly in the type, but also in how we intend to use it.

In the real world, Excalibur has an identity.  You can't copy it, but if you could, then each copy would have its own identity, and be owned by one person (let's ignore shared ownership, and losing it in the lake).  The same couldn't be said for the name (or the colour) of Excalibur - you can write the name as many times as you like, and they are all equal.  If you rename Excalibur to "a light-sabre", it doesn't change all the places you've written "Excalibur".

In cases where object identity is important, it's normal to delete the copy constructors and assignment operators:

class Weapon {
    // not copyable
    Weapon(const Weapon&) = delete; // also removes Weapon(Weapon&&)
    Weapon& operator=(const Weapon&) = delete;

    // instance data
    std::string name;

public:
    Weapon(std::string n = "rusty sword");
    ~Weapon();

    std::string getName();
};

Now we can't copy a Weapon.  We might be able to create another like it, but the two would be distinct.

Our hero needs to be assigned a Weapon.  Let's assume that giving Excalibur to Arthur means that he owns it, until it's destroyed or he gives it to someone else:

#include <memory>
class Hero {
    std::unique_ptr<Weapon> weapon;

public:
    void describeWeapon() {
      std::cout << name << " now swings " << weapon->getName() << std::endl;
    }
    void setWeapon(std::unique_ptr<Weapon>&& w) {
      weapon = std::move(w);
      describeWeapon();
    }
    ~Hero();
};

If the ownership is shared (perhaps it also belongs to a pool of weapons that secretly communicate with each other), then we'll want to use std::shared_ptr<Weapon> instead of a unique pointer.

One thing we need to be careful of is weapon->getName() in the code above.  If we're using pointers rather than objects or references, we'll need to be aware that we could be passed a null pointer.  We can specify that callers must not pass us null pointers, but calling code is notorious for forgetting such contracts.  An alternative is the Null Object pattern, where we create a no-effect weapon to stand in place of the null pointer.

We can arrange that like this:

class Hero {
    std::string name;
    const std::shared_ptr<Weapon> no_weapon
        = std::make_shared<Weapon>(name + "'s bare hands");
    std::shared_ptr<Weapon> weapon = no_weapon;

public:
    Hero(std::string n)
        : name(n)
    {
        std::cout << "hero '" << name << "' constructed" << std::endl;
        describeWeapon();
    }

    void describeWeapon()
    {
        std::cout << name << " now swings " << weapon->getName() << std::endl;
    }

    void setWeapon(const std::shared_ptr<Weapon>& w)
    {
        weapon = w ? w : no_weapon;
        describeWeapon();
    }
    ~Hero()
    {
        std::cout << "hero '" << name << "' destroyed" << std::endl;
    }
};

A further consideration, that's specific to C++: the constructors that take a single argument are candidates for conversions.  You could have written:

Hero h = "Arthur";
h.setWeapon("The Holy Hand Grenade of Antioch");

and those strings would be converted to new objects.  We don't want that to happen, so we should probably declare the constructors explicit.


Yes you can do this in O(n) time.
You just need to scan through the array 1 time and track the 3 largest numbers and 2 smallest numbers. At the end compare the product of the 2 smallest * the largest vs the product of the 3 largest. One of those will be the max product of three numbers.

You only have to track the 2 smallest because the product of 3 negative will be negative. I put in checks to ensure the neg1 an neg2 are negative numbers, but this isn't strictly necessary for just finding the max product. Just storing the 2 smallest numbers will still return the correct answer for this problem.

I think the purpose of this question in an interview setting may be to show that sometimes the a longer block of code may run faster that a one liner.

let arr = [-2, 7, 3, 4,4,4,2,-11];
console.log(maxProduct(arr));

function maxProduct(arr) {

    //special cases
    if (arr.length<3) return null;
    if (arr.length===3) return arr.reduce( (a,b) => a*b);
    if (arr.length===4) return arr.sort((a, b) => a - b).slice(1,4).reduce( (a,b) => a*b);

    //otherwise
    let seeds = arr.slice(0,5).sort((a, b) => a - b);
    let [min1, min2, max3, max2, max1] = seeds;

    for (let i = 5; i < arr.length; i++) {
        let cur = arr[i];
        if (cur >= max1) {
            max3 = max2;
            max2 = max1;
            max1 = cur;
        } else if (cur >= max2) {
            max3 = max2;
            max2 = cur;
        } else if (cur >= max3 ) {
            max3 = cur;
        } else if (cur <= min1) {
            min2 = min1;
            min1 = cur;
        } else if (cur <= min2) {
            min2 = cur
        }
    }

    return Math.max(min1 * min2 * max1, max1 * max2 * max3);
}


First off, post any and all code that you want reviewed. Just posting a little and saying the rest is "here" is not going to get you many good answers. Some of us dislike venturing to sites unknown to view someone else's code. If you post the rest of it and drop me a comment I will return to take a look at it if you wish. That being said, here is my take on your current code. Note: I reference the other two answers heavily, so this is merely an addition and not a true answer.

Incremental Variables

I don't really agree with Hermann's first comment. "x" is only a bad variable name if it is being used for something concrete and easily expressible in some other way. Here it is an incremental, a throw-away variable, so nothing is wrong with it. It's odd, "i" is usually used as the default incremental with "j" usually being secondary, but there's nothing wrong with "x". I do agree that it came out of no where and might be a little jarring, but if you move that line down to just above the loop it will be less so. Also, following jsanc623's example would also be acceptable.

For vs Foreach

The advantage to using a foreach loop over a for loop is that the first uses internal pointers that are dynamically updated, while the second uses external pointers that are statically updated. Another advantage is speed. A foreach loop is usually faster than a for loop. There are more advantages, but I'm going to stick with the ones that are important here. There is one instance where a for loop is better than a foreach loop. That is when you are looping over an associative array and using an external pointer inside of it that coincides with the internal pointer. So, instead of using a foreach loop in these circumstance, it may be best to use a for loop with array_keys() to access the array index manually. If, on the other hand, you are looping a numerically indexed array you can just use the key of the current element.

foreach( $LineArray AS $x => $s ) {

Variable Names

Again, I have to disagree with Hermann, there is nothing wrong with calling your variables an array, or a map, or anything else that indicates what they hold. Unnecessary? Sure, but at the same time it doesn't hurt anything and can actually help in some cases. Now, I won't say that calling a variable a "String" or an "Int" is good. PHP is very loosely typed, and that can easily change those contents, but adding an "array" or "obj" suffix to your variable lets those reading it know what it is supposed to be and is common enough.

I do agree with Hermann about $s however. It is a horrible name. I would expect to see $line or something similarly related to the array. The only single letter variables you should have are incremental (i, j) or something else that is commonly expressed with a single letter, such as coordinates (x, y, z).

Strings

I'm going to get argued with about this next suggestion, so let me just say up front that it is a stylistic choice that has some basis in fact. PHP allows for two methods of adding variables to a string. The first is escaping. Using double quotes to surround a variable or escape sequence you can escape the variable or sequence without any special syntax, just include them between the double quotes ("$var\n"). The second is concatenation and is the method you are currently using ('abc' . $var1 . "\n"). When concatenating it is best, in my opinion, to use single quotes instead of double. There's one major reason for this, double quotes tells PHP your string has entities that need escaping, whether they are PHP variables or manually escaped returns, tabs, etc... doesn't matter. So when you use double quotes PHP expects these escape routines and uses a small amount of extra processing power to parse the string for them. Now the processing power required and the time it takes are both negligible, but there is a difference and I like to point it out.

For Loops

Another thing about for loops. The arguments passed to a for or while loop are reparsed on each iteration. So passing a function in as an argument is usually a bad idea, at least if that function's return value is not meant to change i.e.(count() or in this case mb_strlen()). Both get the number of iterations the loop is going to go through. These numbers typically don't change between iterations so there is no need to recalculate it. It is just taking up extra processing power. If you move this function out of the argument list and set it as a variable it will run a bit faster, though it may be negligible in this case. jsanc623 touched on this, but I wanted to give the full reason.

Nested Functions

Again, I agree with Hermann, don't have long nested function calls in a statement. Declare it a variable before checking it, especially if you are going to be using it again elsewhere. This follows the DRY (Don't Repeat Yourself) Principle. Personally, I would break it up further, as I don't like nested function calls at all, but that might just be a stylistic choice. Here's how I'd write your if statement.

$bin = iconv('UTF-8', 'UCS-2', $char);
$hex = strtoupper( bin2hex( $bin ) );//Only one nested, and still not as desirable.
if( $hex != "FEFF" ) {

Functions

Again jsanc623 brings up a good point. This single function should be broken up into multiple functions. He doesn't come right out and say it, but it is implied. So I figured I'd go ahead and say it for him. Functions should do one thing and do it well. They should not be concerned with anything else. This is the Single Responsibility Principle.

Pushing to an Array

The following is equivalent to pushing onto the end of an array, and is usually the preferred method for appending array data.

TextCharacters[ 0 ] [] = go( '304A' );

Now, in your comment you said that you were pushing each element. Am I to assume you are doing so manually? If so, a better way would be to create an array of these hex values and loop over them to add them. Even better would be to create a JSON document, that way they could be accessed from both PHP and JS if needed.


Since exactly one element will exist at a time, you can retrieve it by alternating with || between both getElementById calls. Then, there's no need for any existence test later.

Since you set disabled to true in both branchTransitNumber.length < 6 and depositAccountNumber.length < 8, you can combine those blocks together:

const button = document.getElementById('sortcodeError') || document.getElementById('accountnameError');
button.disabled = false;
if ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {
    if ($scope.data.branchTransitNumber.length < 6 || $scope.data.depositAccountNumber.length < 8) {
        button.disabled = true;
    }
}

(The above can be made even more concise via destructuring or optional chaining to avoid the double ifs, but I think it'd look too confusing.)

Or, if you need the addClass call only in the case of $scope.data.depositAccountNumber.length < 8 and accountnameError existing:

const button = document.getElementById('sortcodeError') || document.getElementById('accountnameError');
button.disabled = false;
if ($scope.data.branchTransitNumber && $scope.data.depositAccountNumber) {
    const depositNumberProblem = $scope.data.depositAccountNumber.length < 8;
    if ($scope.data.branchTransitNumber.length < 6 || depositNumberProblem) {
        button.disabled = true;
        if (depositNumberProblem && button.id === 'accountnameError') {
            angular.element($('#btnSubmi')).addClass("gray");
        }
    }
}

Depending on the logic of your script, the above may be simplifiable. For example, you may wish to do .addClass("gray") regardless when you disable the button.

Other notes:

It's 2020, best to at least use ES2015 syntax in new code by declaring variables with const, not var (which has too many gotchas)
Whenever you do have to compare two different values, use strict equality with === or !== - avoid loose equality == and !=, since loose equality has too many strange rules that a developer should not have to memorize.
If the alternation trick above weren't possible, you'd still be able to reference the variable names you saved the elements into to keep things concise. Eg, with const sortcodeError = document.getElementById("sortcodeError"), you should never have to call document.getElementById("sortcodeError") later - instead, just reference the sortcodeError variable.
Use consistent indentation. If one statement is in the same block as another, it should begin at the same indentation level. This significantly improves a code's readability.
Either use semicolons wherever appropriate, or don't. (If you're not an expert, I'd recommend using them, otherwise you'll occasionally run into strange bugs.) Consider using a linter to automatically prompt you to fix potential mistakes (and to make the code nicer-looking).
The overall logic looks a bit weird. Do you really need to check that both branchTransitNumber and depositAccountNumber exist, but disable a button if either of them fail a length test? In a validation situation, I'd expect to disable a button if either fail, rather than if both exist and either fail. Double-check the logical paths your code requires and results in, and consider what sort of effect you really want.


You might want to validate the value of $1, or at least that it's not empty, for example add a line like this near the top:

test "$1" || { echo usage: $0 param; exit 1; }

You are not checking for errors, for example what will happen if the mv command fails for whatever reason? Maybe you have no reason to suspect a problem there, but just in case it would be good to add the -e flag to the shebang (#!/bin/ksh) so that execution will stop immediately there. Otherwise execution would continue after the failed mv, and the grep ... > ... might clobber a file by accident.

In any case, adding the -e flag in the shebang is a good practice in general.

It seems your variables will not normally contain spaces. If they ever do, remember to quote them properly, for example:

mv "$T/conbase_updates" "$U/conbase_updates.br.drqs$1"

(in your current example it's unnecessary)


Scoping

In Emacs Lisp a nesting a defun inside another defun does not create a lexically scoped function. The symbol for the 'nested' function is still interned at in the current objarray. The behavior is unlike that of Scheme.

In Emacs Lisp let ((f (lambda (x) (body))))...(funcall f some-value) is the general structure for a 'local' function.

Formatting

The formatting of the code within the call to pcase is difficult to read. When the condition and consequent cannot be listed on the same line, it is probably more common to place the consequent below the conditional.

Suggested Alternative Format

(defun expand-pattern (pattern)
  (mapcar (lambda (tokens)
            (mapconcat (lambda (token)
                         (format "%s" token))
                       (reverse tokens)
                       ""))
          (expat '(()) pattern)))

(defun expat (parents expr)
  "Utility function for expand pattern."
  (pcase expr
    ((or (pred stringp)
         (pred numberp))
     (mapcar (lambda (parent)
               (cons expr parent))
             parents))
    (`(and ,first)
     (expat parents first))
    (`(and ,first . ,rest)
     (expat (expat parents first)
            (cons 'and rest)))
    (`(or . ,args)
     (apply #'append
            (mapcar (lambda (arg)
                      (expat parents arg))
                    args)))
    (_ (error "unknown %S" expr))))

Other Remarks

Because expat throws an error, it might make sense to have expand-pattern invoke expat within a try...catch block. Alternatively, expat could return nil when no match is found. If nil is a possible return value from processing the pattern, then a "Lispy" thing to do is to return two values, the first being the result of processing the expression and the second being either nil or t to indicate an error or no error.


pros

you don't inherit from JFrame (as too many tutorials out there do...)
you (almost) follow Java naming conventions
your variable names almost express the meaning of the values they hold

cons

you break Java Naming conventions with the ActionListener implementation.
frame.setVisible(true); is not the last line of frame configuration.
you use literal strings instead of constants with meaningful names
you use a static method.
you use an if/else cascade instead using polymorphism to find the calculation.

suggestions

Naming conventions

start class names with an uppercase letter.
start names of variables and methods with lower case letter
chose nouns to name classes and variables
start names of methods with a verb maybe followed by nouns.

position of frame.setVisible(true);

The problem with that is that modifications to the Layout may not be visible if dome after frame.setVisible(true);. Therefore you should get used to write it ata position where you cannot write something behind it by accident.

One way to asure this is to do the configuration in a method where you pass the JFrame as parameter and call  frame.setVisible(true); after that method like this:

   public static void main(String[] args) {
        JFrame frame = new JFrame("Simple Calculator");
        Calculator calculator = new Calculator();
        calculator.configureGui(frame);
        frame.setVisible(true);
   }

variable names

some of your names are already good, but others need improvement
 e.g.:  list -> operators

static method

You need a static method for a technical reason. This is because you don't know (yet) the differences between inner classes, anonymous inner classes and top level classes in same file and their consequences for the visibility of variables and methods.

In your case the Action listener should be an anonymous inner class so that is has full access to the members (variables and methods) of the containing class:

public void run() {
    ActionListener buttonListener = new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            if (!inputOne.getText().equals("") & !inputTwo.getText().equals("")) {
                double numberOne = (parseDouble(inputOne.getText()));
                double numberTwo = (parseDouble(inputTwo.getText()));
                String function = (String) list.getSelectedItem();
                // calculate is accessible as member from here...
                output.setText("" + calculate(numberOne, numberTwo, function));
            }
        }
     };
     // ...

But on the other hand there is the MVC (or MVVC) pattern to separate User Interface (UI = View) the data structure (model) and the business logic (controller). This pattern works with (public) top level classes accessing public methods.

if / else cascade -> polymorphism

To resolve this we need to introduce an interface, that all the operations can implement so that we can do the same call on any operation:

interface Operation {
   double  calculate(double term1, double term2);
}

This could be declared within the Calculator class just as you did with your ActionListener implementation.

Then we need to create and store implementations of this interface and map them with their symbols. The best solution for this is: --- a Map.
Therefor we change your variable symbols to a HashMap:

 private Map<String,Operation> symbols = new HashMap<>();

In your configuration method we initialize this Map.

// literals replaced with constants...
symbols.put(PLUS, new Operation(){
     public double calculate(double summand1, double summand2){
        return summand1+summand2;
     }
});
// same as Java8 Lambda
symbols.put(MINUS, (minuend, subtrahend) -> minuend-subtrahend);
//...

having this your calculate method would change to this:

 double calculate(double a, double b, String symbol) {
   if(symbols.containsKey(symbol))
     return symbols.get(symbol).calculate(a,b);
   else
     throw new IllegalOperationException("symbol "+symbol+" unknown!");
 }

isn't that nice?


Well, for starters, your redirect will never work if you pass in both $key and $page, as you're asking for the following:

1. is not isset($page)
2. is not empty($page)

Which means that the redirect will happen only when $page is NOT set and NOT empty. Because empty() calls isset() internally, you should only need this:

if(!empty($page))

Additionally, you're not managing your buffers. Ideally, you should use the ob_ functions as well as headers_sent() to check if headers have already been sent. If you don't manage your buffer, you're very likely to hit the infamous "Cannot modify header information - headers already sent" error. This post goes into further detail on how to fix that error, especially using the ob_ functions.

Aside from all that, your construct is doing nothing. If your Redirect class only has the to() method, perhaps you're better off making it a standalone function, or adding additional functionality.


Can this architecture of base + derived classes be coded more efficient?

This works but is very unusual. The standard way of doing this would actually be virtual methods

public abstract class building {
   ...
   protected virtual CreateWalls() {
      //create 4 walls by default
   }
   protected virtual CreateFoundation() {
     //straightforward foundation by default
   }

   public void Construct() {
      CreateWalls();
      CreateFoundation();
   }
}

public class SkyScraper : Building {
   public override CreateFoundation() {
      //create deep foundation in bedrock
   }
}

While this is the simplest and is certainly acceptable architecture it is always a good idea to also consider Composition over Inheritance

So instead you might do something like

public abstract class Building {
   protected Building(WallConstruction walls, FoundationConstruction foundations, ...) {
      walls.ConstructFor(this);
      foundations.ConstructFor(this);
   }
}

or even more generic

public abstract class Building {
   protected Building(IBuildingComponent[] components) {
      components.ForEach(x => x.ConstructFor(this));
   }
}

a couple more things to consider.

Does it make sense for a Building to be in an unconstructed state? Should this instead be something like BuildingBuilder (or just Construction) and have a Build method that produces a building?
The whole (EventArgs, object) pattern for events really hasn't made much sense since we got good delegate signatures in .Net 3.5. Just make the signature for the event exactly what you want it to be and use a Action or Func<> type.
When using events, instantiate the event to an empty one

   public event Action foo = delegate {};

that way the delegate will never be empty so there will be no need for a null check.


What are the top voted comments on closed questions, and who made the comments?

SEDE has two great features that you should incorporate into your code:

Input parameters
Magic markup columns

Input parameters
SEDE lets you declare fields to be input towards the query, like so:
##Parameter:type?defaultvalue##

And so, I suggest you use three of them for the following things:

Threshold (The threshold of comment scores to select)
Amount per page (The amount per page of comments)
Page number (To go with the above one)

By using pages, you can simplify your returning dataset and help to reduce the massive call times of the query.

Magic markup columns
SEDE has a great feature where certain columns can be transformed into special markup. The specific columns are:

Post Link (generated from Post Id)
User Link (generated from User Id)
Comment Link (generated from Comment Id)
Suggested Edit Link (generated from Suggested Edit Id)
Tags

As it stands...
your code is good, but you are doing a few things you can improve on:

Your generation of Commenter can be easily replaced with UserId as [User Link] to save extraneous calling of another table.
SELECT Id, ClosedDate your SELECTion is redundant. To use the field, you don't actually have to select it, simply reference it. Seeing as the resulting table is only used for the Id anyway, it's pointless to have it.