Ping Pong Pi - A Ping Pong score and serving manager

Line by line analysis

import os

You need 2 blank lines before each global function definition.

def talk(n):

n is not descriptive and associated with a number. Don't use one letter variables unless it's really obvious (for example i loop counter, k and v as dict key and a value, or d as Twisted's deferred object. Something like phrase would be better.

    if voice_mode == 1:

Where does the voice_mode come from? Global variables are bad, pas it as a parameter to a talk method. Also, canonical way of checking if boolean is True is simply if voice_mode.

        os.system("espeak -ven+m3 '" + n + "' 2>/dev/null")
    else:
        print n

def print_score(n):

Again, n does not tell reader a lot.

    if n == 0:
        other_n = 1

What is other_n? If there's no better name for it - add a comment.

    else:
        other_n = 0
    if d[n][1] == 0:

Where did d come from? Pass it to a function. Also, better name.

        score1 = "love"
    else:
        score1 = str(d[n][1])
    if d[other_n][1] == 0:
        score2 = "love"
    else:
        score2 = str(d[other_n][1])
    talk(score1 + " " + score2)

def win(n):

Same thing with the n variable. Also, docstring might be helpful for this method.

    global first_server

Global variables are bad, really bad. Make your method take and return this if you need the variable.

    talk(d[n][0] + " wins the game")

This d is really quite obscure.

    d[n][2] += 1
    d[0][1] = 0
    d[1][1] = 0
    deuce_mode = 0
    serve_turns = old_serve_turns
    if first_server == 0:
        first_server = 1
        current_server = 1
    else:
        first_server = 0
        current_server = 0
    if d[n][2] == match_points:
        talk(d[n][0] + " wins the match")
        d[0][2] = 0
        d[1][2] = 0

def add_score(n):

Same thing: add docstring, replace n with better name and pass all the global variables as arguments to the function.

    global deuce_mode
    global current_server
    global serve_turns
    d[n][1] += 1
    if n == 0:
        other_n = 1
    else:
        other_n = 0
    if deuce_mode == 0:
        if d[0][1] == d[1][1] and d[0][1] == game_points - 1:
            deuce_mode = 1
            old_serve_turns = serve_turns

I don't see old_serve_turns used anywhere.

            serve_turns = 1
        if current_server == 0:
            print_score(0)
        else:
            print_score(1)
        if d[n][1] == game_points:
            win(n)
    else:
        if d[n][1] == d[other_n][1] + 2:
            if current_server == 0:
                print_score(0)
            else:
                print_score(1)
            win(n)
        else:
            if current_server == 0:
                print_score(0)
            else:
                print_score(1)
    if (d[0][1] + d[1][1]) % serve_turns == 0:
        if current_server == 0:
            current_server = 1
            talk(d[1][0] + " is serving next")
        else:
            current_server = 0
            talk(d[0][0] + " is serving next")

d = []

You need either a better data structure, or at least a good comment explained what the d is. Also, d needs a better name.

for i in xrange(2):
    d.append(["", 0, 0])
d[0][0] = "Player 1"
d[1][0] = "Player 2"
game_points = 11
match_points = 2
deuce_mode = 0
voice_mode = 1
serve_turns = 2
old_serve_turns = 2
current_server = 2

You only play with server 0 and 1, correct? Why do you need to obscure and add server 2 which is only there to start the game? Better have a flag of some sort.

first_server = 0

talk("Ready to play")
while True:
    c = raw_input("Command: ").lower()

Better name: command.

    if c == "z":
        if current_server != 2:
            add_score(0)
        else:
            talk(d[0][0] + " is serving first")
            current_server = 0
            first_server = 0
    elif c == "x":
        if current_server != 2:
            add_score(1)
        else:
            talk(d[1][0] + " is serving first")
            current_server = 1
            first_server = 1
    elif c == "1name":
        d[0][0] = raw_input("Player 1 name: ")
        talk("Welcome, " + d[0][0])
    elif c == "2name":
        d[1][0] = raw_input("Player 2 name: ")
        talk("Welcome, " + d[1][0])
    elif c == "gm":
        game_points = int(raw_input("Game points: "))
        match_points = int(raw_input("Match points: "))
    elif c == "s":
        serve_turns = int(raw_input("Serve turns: "))
    elif c == "togglevoice":
        if voice_mode == 0:
            voice_mode = 1
        else:
            voice_mode = 0
    elif c == "quit":
        quit()
    else:
        talk("Command not recognised")

Even though this if/else tree is acceptable in your scope, you might want to look into Strategy pattern. This is further reading though.

Summary

Overall, your variable naming needs to be more readable. Don't use global variables, just pass the ones you need as arguments. For example, your talk function could be changed like this:

def talk(phrase, voice_mode=True):
    """Pronounce the phrase if the voice mode is on, otherwise print."""
    if voice_mode:
        os.system("espeak -ven+m3 '%s' 2>/dev/null" % phrase)
    else:
        print phrase

Don't forget to specify docstrings for non-trivial methods. Make them long if you need to. Use comments extensively to elaborate if variable name or a data structure is not descriptive enough.


Use DOM and XPath to make some changes in HTML document

Your code seems to globally do the right job, using a right way, and I can't see how you could really improve performance.
I only noticed a few bad points:

Unless I missed some subtleness, there is a typo in the case 'append': branch: it should be using $xpath_results->**parentNode**,like others.
You didn't take in account a possible error condition at $newNode->appendXML($replacement);: it may return FALSE, so you should cancel the process in that case.
The same applies to a possible wrong value in the task index of a pattern: it should be taken in account through the default: option of the switch().

In the other hand I would suggest some improvements at the coding level itself, essentially for readability.

You're using foreach ($patterns as $key => $value), but then always write $patterns[$key][...] so you force PHP to a few more work, while $value is never used.
I suggest to rather use foreach ($patterns as $value), then $value[...].
(or even more readable foreach ($patterns as $pattern), then $pattern[...])
Still for readability I would add a separate variable to clearly distinguish the successive "avatars" of $xpath_results, which is first a DOMNodeList then a DOMNode.
So you could change your DOMNode extraction to $node = $xpath_results->item(0);, and all following code becomes much more obvious.
Your // Assing some valuespart could be reduced to the $node assignation above: the two other variables are only used once so you could merely write $newNode->appendXML($pattern['insert']); and switch ($pattern['task']).

So here is my suggestion for the whole snippet after the remarks above:

if ($html) {
    $dom = new DOMDocument();
    if (!$dom->loadHTML($html)) {
        $error = 'Error while loading source HTML!';
    } else {
        $dom->formatOutput = true;
        // Use DomXPath
        $xpath = new DomXPath($dom);
        // Process Dom changes
        foreach ($patterns as $pattern) {
            $xpath_results = $xpath->query($pattern['xpath']);
            if ($xpath_results->length) {
                $node = $xpath_results->item(0);

                if ($task != 'remove') {
                    // Create the replacement
                    $newNode = $dom->createDocumentFragment();
                    if (!$newNode->appendXML($pattern['insert'])) {
                        $error = "Wrong insert pattern: $pattern['insert']!";
                        break;
                    }
                }
                if (!@$error) {
                    switch ($pattern['task']) {
                        case 'remove':
                            $node->parentNode->removeChild($node);
                            break;
                        case 'replace':
                            $node->parentNode->replaceChild($newNode, $node);
                            break;
                        case 'append':
                            $node->parentNode->appendChild($newNode);
                            break;
                        case 'prepend':
                            $node->parentNode->insertBefore($newNode, $node);
                            break;
                        default:
                            $error = "Wrong task pattern: $pattern['task']!";
                    }
                }
            }
        }
    }
    if (@$error) {
        // print or return $error...
    } else {
        // Save Dom
        $html = $dom->saveXML($dom->documentElement);
    }
}

For the error processing, I arbitrarily choosed one simple option among numerous different possiilities.  You can notice:

The @$error form: it is a simple and clear way to allow using variables set only in certain cases without having defined them previously.
Still for readability, I changed the initial tests into more simple (and sufficient) forms: if ($html) and if (!dom->loadHTML($html)).


Using Elixir pipeline to transform a string into a map

You can do this with an anonymous function

Enum.reduce(lines, %{}, fn(line, result) ->
  String.split(line, ": ")
  |> (fn(x) -> Map.put(result, hd(x), List.last(x)) end).()
end)

You can also do it like this

Enum.reduce(lines, [], fn(line, result) -> result ++ String.split(line, ": ") end)
  |> Enum.chunk(2)
  |> Map.new(fn [k,  v] -> {k, v} end)

which I less efficient, because it does 2 iterations, but I think it looks cleaner.


There's no reason (as far as I can tell) to do string comparison to check a class. #is_a? would presumably work fine too. And it'd be stricter, which is desirable.
There's no reason to check students.size. If there are no students, the loop just won't do anything, so why bother checking first? Conversely, if there are any students you're actually doing 2 database queries: One to get the count/size of students, and another to fetch the actual records.
Presuming non-ancient Rails, you can simply say current_user.students.memberships to get all the memberships in 1 query (admittedly with a couple of JOINs), rather than loop through students individually, and then getting their memberships.
Continuing from #3, you can (presumably) collapse the entire things into 1 database query.

I'd probably start with something like

def user_not_authorized(exception)
  redirect_path = request.referrer || root_path

  if exception.policy.is_a?(GroupPolicy)
    if current_user.students.memberships.where("group_id = ?", exception.record.id).any?
      redirect_to redirect_path, alert: t('flash.pending_acceptance') and return
    end
  end

  redirect_to redirect_path, alert: t('flash.access_denied')
end

Note that it doesn't actually load any records at all; it just checks if they're there or not.

In practice, I'd consider breaking it into separate methods where possible. It's not that great to have a naked query referencing a specific column name in the middle of your method.

Edit: Updated the code to return if the first redirect occurs, since you'd otherwise do two redirects in one action, which is not allowed. Thanks to tokland for catching that. Now the and return fix is about as quick and dirty as is gets, but check the comments for better ideas.


Nice first project! It is generally better practice to have functions return values instead of printing them. I added a power function to yours and made it more user friendly by having them type the symbol instead of a number.also you should add square, cube and other roots making the symbol '//'. otherwise it looks good, your code is nicely formatted and looks great.

def user_operation():
    return input('Type operation: ')

def user_number():
    #Return numbers used in operations
    n1 = int(input('First number: '))
    n2 = int(input('Second number: '))
    return (n1, n2)

#Operations
def add(x, y):
    a = x + y
    return ('%d + %d is %d' % (x, y, a))
def sub(x, y):
    s = x - y
    return ('%d - %d = %d' % (x, y, s))
def mult(x, y):
    m = x * y
    return ('%d * %d is %d' % (x, y, m))
def div(x, y):
    d = x / y
    return ('%d / %d is %d' % (x, y, d))
def sqr(x,y):
    d = x ** y
    return ('%d ** %d is %d' % (x, y, d))
def calculate():
    while True:
        n1, n2 = user_number()
        operation = user_operation()
        if operation.lower() == 'quit':
            break
        elif operation == '+':
            print (add(n1, n2))
        elif operation == '-':
            print (sub(n1, n2))
        elif operation == '*':
            print (mult(n1, n2))
        elif operation == '/':
            print (div(n1, n2))
        elif operation == '**':
            print (sqr(n1, n2))
        else:
            print ("That is not a valid operation!!")

def main():
    print ("Calculator program by Jfelix\n"
           "Available operations:\n1. Addition (+)\n2. Subtraction (-)\n3. Multiplication(*)\n4. Division (/)\n5. Power (**)"
           "Type their respective character(s) to perform the selected operation\n"
           "Type 'quit' to end the program.\n")

    calculate()

if __name__ == "__main__":
    main()


The code in the post does not solve the problem. Consider the following input:

1 6
0 3 3
1 UU

The code in the post prints "safe", but in fact the frog is squished, since the cars have speed 3 and separation 3, meaning that a car crosses every square in the lane on every time step, and so the lane is impassable.


Faster sorting
If the only purpose of the distance computation is for comparison, then you can speed it up by removing the call to sqrt().  You'll end up comparing the squares of the distances, which is equivalent to comparing the actual distances.


Contradicting statements

answer = 7 # sets the answer
answer = guess

Here, you are setting a variable only to immediately set it to another value in the very next line, effectively invalidating the first line. This also makes your code confusing: you do that thing you are doing in these lines, and then you start comparing the guess with this magic number 7 (which is was answer used to be).

Also, why is the answer being set to the guess? Those are two completely different things. Instead of what you are doing, to make your code much more understandable, you should get rid of this line:

answer = guess

Then, instead of comparing guess with 7, compare it with answer.

if guess < answer:
    print "That's too low."

if guess > answer:
    print "That's too high."

if guess == answer:
    print "Good. Thanks for playing."

Now your code is much more readable and follows better practices.

elif

Using elif is good because if the first conditional check fails, the rest will not be executed, which speeds up your code. Unfortunately, elif can not be used in every case due to specific code-based reasons.

Luckily for you, your code can use elif. So, instead of having three separate if statements, you should have one with two elifs:

if guess == answer:
    print "Good. Thanks for playing."

elif guess < answer:
    print "That's too low."

else:
    print "That's too high."

I also re-arranged your code. Now, the most unique conditional comes first. And, instead of a final elif, I put an else because if the guess is not greater than or equal to the answer, it has to be less than it.


Calculate Twitter Follower Changes Over Time

You should try to avoid calculating the same things over and over. The first example are your transformation functions. While it is nice that you have separated the concerns, it probably costs you quite a bit here. It might be better to make this one function:

def categorize_users(new, old):
    """
    Return the gained, lost and returned followers
    from the two `pandas.DataFrame`s `old` and `new`.
    """
    old_user_ids = set(old.Follower_ID)
    new_user_ids = set(new.Follower_ID)
    returned_user_ids = set(old.Follower_ID[old.End_Date.notnull()])

    gained = map(str, new_user_ids - old_user_ids)
    lost = map(str, old_user_ids - new_user_ids)
    returned = map(str, returned_user_ids.intersection(new_user_ids))
    return gained, lost, returned

Note that I re-used everything that was used more than once. I also skipped the unique part, because the set already does it, but you might want to add it back in to see if it is any faster.

Now, to your actual for loop:

for username in lookup_users:
    new_user_followers = new_followers_df["Handles"] == username
    old_user_followers = historical_followers_df["Handles"] == username
    new_ids, lost_ids, returned_ids = categorize_users(
        username,
        new_followers_df[new_user_followers],
        historical_followers_df[old_user_followers])

    # Add Returned Users
    if returned_ids:
        for ids in returned_ids:
            old_followers = user_followers & (historical_followers_df["Follower_ID"] == ids)
            historical_followers_df.loc[old_followers, "Start_Date"] = today
            historical_followers_df.loc[old_followers,"Returned_After_Days"] = pd.to_datetime(historical_followers_df.Start_Date) - pd.to_datetime(historical_followers_df.End_Date)
            historical_followers_df.loc[old_followers, "End_Date"] = np.NaN
    # Add Lost Users
    if lost_ids:
        for ids in lost_ids:
            old_followers = user_followers & (historical_followers_df["Follower_ID"] == ids)
            historical_followers_df.loc[old_followers, "End_Date"] = today
    # Add New Users
    if new_ids:
        gained_users_list = pd.DataFrame({
            "Handles": username,
            "Follower_ID": new_ids,
            "Start_Date": today})
        historical_followers_df = gained_users_list.append(
            historical_followers_df, ignore_index=True)

I made your three for loops into one, because now we can actually get all the three different classes in one go. I also put the selection of the relevant old followers which need to be modified into its own variable as well, so it is not computed four times per loop.

I also moved the filtering of the dataframes to one user already in the loop, so that categorize_users becomes more general.


root

The root directive is inherited. You have the same statement in the server block, and repeated in a number of location blocks. Only the first statement is necessary. See this document for details.

location ~* ^/static/.*$

This can be replaced by the prefix location:

location /static/ { ... }

The prefix location is more efficient than the regular expression location. The precedence order is different, but that does not affect your current configuration. See this document for details.

rewrite ^(.*)$ https://$http_host$1 permanent;

You can replace this with a return statement, thus eliminating a regular expression.

return 301 https://$http_host$request_uri;

Nested location blocks

A number of statements are common to three location blocks, all of which represent URIs that begin with /static/. The expires, access_log and add_header directives are inherited.

You could restructure your locations as follows:

location /static/ {
    root  /var/www/html/src;
    expires 1y;
    access_log off;
    add_header Cache-Control "public";

    location = /static/site.js {
        try_files /static/$script_file =404;
    }
    location ~* ^/static/img/.+\.(png|jpg)$ {
        add_header Vary Accept;
        add_header Cache-Control "public";
        try_files $uri$webp_suffix $uri =404;
    }
}
location / {
    ...
}

This would improve efficiency as URIs which do not begin with /static/ will not need to be checked against the regular expressions.

The add_header directive has an additional inheritance rule. See this document for details.


Efficiency / logic

In the while loop in the client class,
you recreate a DataOutputStream and a BufferedReader from the socket in every single iteration.
This is just silly.
It would be better to create these objects before the loop.

Closing resources

You didn't close any of the resources you open.
As of Java 7,
an easy way to properly close everything is using the try-with-resources idiom,
for example:

try (
    Socket connectionSocket = input.accept();
    BufferedReader iptFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    DataOutputStream optToClient = new DataOutputStream(connectionSocket.getOutputStream())
) {
    String TCPclientMess = iptFromClient.readLine();
    System.out.println("You Sent: " + TCPclientMess);
    String returnMess = TCPclientMess;
    optToClient.writeBytes(returnMess);
}

Limit variables to the smallest necessary scope

In both implementation you declare some variables at the top,
when that's really not needed and may invite mistakes.
It's best to declare variables at the smallest scope where you really need them.
For example, instead of:

    String input;
    // ...
    while(true)
    {
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
        input = inFromUser.readLine();
        // ...

This is better:

    while(true)
    {
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
        String input = inFromUser.readLine();
        // ...

Hardcoded values

Instead of hardcoding "localhost", 22003, 3000,
it would be better to put these values in constants with descriptive names,
for example:

private static final int TIMEOUT_MILLIS = 3000;
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 22003;

Redundant variable

In TCPServer,
the message read from the client input stream is stored in the TCPclientMess variable,
and then assigned to the returnMess variable,
which is not used for anything else.
You don't need both variables, one of them would be enough.

Naming

You have a String named TCPclientMess.
The convention is to use camelCase for variable names.


I see some things that may help you improve your program and have provided answers to your questions.

Be clear about your program's purpose

What the program actually does is to print out a table of temperatures.  That much is quite clear, but what is less clear is whether you really wanted the std::vector to be created or not.  If that was just a means to the end goal of creating a table, then I'd suggest you could omit it entirely and simply use a loop to print the values rather than storing them.

Use named variables

The word "Fahrenheit" appears twice within the code.  It would be better to use named variables rather than risk, say, having a typo in one of the versions.  I'd do it like this:

const std::array<std::string, 2>column_labels{"Fahrenheit", "Celsius"};

Remove unecessary data structures

As noted above, the std::vector is not really needed.  If the code simply directly prints the values, the code becomes shorter and easier to read and understand.

Eliminate redundant I/O manipulators

Once the width and precision have been set, there's little reason to assert them again.  I'd write the main loop like this:

for (double temp=min; temp < max; temp += step) {
    std::cout << std::setw(col_width) << std::fixed
              << std::setprecision(4) << temp
              << fah_to_cel(temp) << '\n';
}

Note that the limitation of std::to_string is eliminated by this means because we can use std::setprecision().

Avoid construction/destruction overhead

Each time the code calls std::string(5, ' ') it represents a constructor call and somewhere later, a destructor call.  This can be avoided either by making it a named const variable which can be repeatedly used, or better still, eliminated entirely by simply using the std::setw() manipulator to set the columns to the size you want, automatically creating the required space.

Let the computer do the work

It seems to make more sense to me to let the computer figure out which label is longest.  Here's one simple way to do that:

const auto max_width = std::accumulate(
        column_labels.begin(), column_labels.end(), 0,
        [](std::string::size_type a, const std::string &str){
            return std::max(a, str.size());
        });

This uses a lambda to return the longest string length, but this could be done using a function if you wish.

Use const where practical

Things that don't change should be declared const which includes your min, max and many other variables within the code.

Consider whether to use a function or inline

The fah_to_cel routine is quite simple and only used once, so I'd be inclined to eliminate it in favor of simply putting the code inline instead.

An alternative implementation

Using these suggestions, here's an alternative approach:

#include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>

int main()
{
    const auto min = 0u;
    const auto max = 100u;
    const auto step = 5u;
    const std::array<std::string, 2> column_labels{"Fahrenheit", "Celsius"};
    const auto max_width = std::accumulate(
            column_labels.begin(), column_labels.end(), 0,
            [](std::string::size_type a, const std::string &str){
                return std::max(a, str.size());
            });
    const auto col_width = max_width+5;
    std::cout.setf(std::ios_base::left, std::ios_base::adjustfield);
    // print column labels
    for (const auto &label : column_labels) {
        std::cout << std::setw(col_width) << label;
    }
    std::cout << '\n';
    // print column label underlines
    const std::string underline(max_width, '-');
    for (auto i=column_labels.size(); i; --i) {
        std::cout << std::setw(col_width) << underline;
    }
    std::cout << '\n';
    // print temperature table
    for (double temp=min; temp < max; temp += step) {
        std::cout << std::setw(col_width)
                  << std::fixed << std::setprecision(4)
                  << temp << (temp-32)/1.8 << '\n';
    }
}


Change the JTextField font and text with radio buttons

Java naming convention

You should read the Java naming convention. Class require PascaleCase, so
public class gui should be public class Gui.

Indentation and style

You should use an IDE or a tools to automatically correct any styling or indentation error. The spacing of your variables declarations are not correct and your indentation of your if-else are not correct either.

There are plenty of good free to use IDE and tools. This goes in pair with the Java naming convention/ Java Style recommendation.

Use better names

You're not limited in size for your variable names. Go for clarity over brievty!
This will go a long way to help you, at first glance, know what the variable is about. For the next person that read your code it will be easier too.

private JTextField tf = new JTextField( 25);
private JRadioButton regularRadio = new JRadioButton("Regular",true);
private JRadioButton boldRadio = new JRadioButton("Bold",false);
private JRadioButton italicRadio = new JRadioButton("Italic",false);
private JRadioButton boldNitalicRadio = new JRadioButton("Bold And Italic",false);;
private ButtonGroup group = new ButtonGroup();

Should probably be :

private JTextField textField = new JTextField( 25);
private JRadioButton regularRadio = new JRadioButton("Regular",true);
private JRadioButton boldRadio = new JRadioButton("Bold",false);
private JRadioButton italicRadio = new JRadioButton("Italic",false);
private JRadioButton boldAndItalicRadio = new JRadioButton("Bold And Italic",false);;
private ButtonGroup group = new ButtonGroup();

init

In most GUI code I've seen, you can create an init method and put all the initialization code in there. It helps to keep the constructor clean, but it's no big deals. It's what I'm mostly used too, but it's been a long time I've done any Swing related code.

Constant

If you see a value used over and over, ask yourself : Does this value represent the same thing?

Take "David" for example, it does represent the same named font in all your case. You could then have a private static String DAVID = "David" to represent the font.

Action command

This is a special case from your previous point. Since you hard-coded the action command names, if you change it at one place you have to remember to change it in other places.

This is a perfect example of the Java Enum class. Take a look at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html, it's a good tutorial on how to use it.

Using an enum you make it clearer and should be easier to use in the long run.

Other point

I don't think you need to create the Font object every time, you may use an const Font object to reduce object creation. It's a small thing that not improve really but it could help in other cases.


I'm going to concentrate on the Scala rather than the maths side, because that's my area.

The internal helper function doesn't need two parameters, since the value of x never changes; pushing x repeatedly onto the stack is a waste of time.  Also, better to use a case statement than a chain of if...else if...else - much less error prone.

def sqrt(x: Double): Double = {
  if (x < 0) throw new IllegalArgumentException("negative numbers not allowed")
  val threshold = if (x < 1) x / 1e15 else 1e-12
  def sqrtx(p: Double): Double = p match {
    case q if q == x / q => q // without this condition, non-termination with 1e50
    case q if Math.abs(q * q - x) < threshold => {
      def diff1 = Math.abs(x - p * p)
      def diff2 = Math.abs(x - x / p * x / p)
      if (diff1 < diff2) p else x / p
    }
    case _ => sqrtx((p + x / p) / 2)
  }
  sqrtx(x / 2)
}

I renamed the inner function sqrtx to avoid confusion about what it is doing.


Sloppiness

There are several careless mistakes that are easy to fix.

Don't use implementation types in declaration, unless you really need to use a specific feature of that implementation:

ArrayList<String> arr = new ArrayList<String>();

Use the interface type instead:

List<String> arr = new ArrayList<String>();

Instead of creating a new StringBuilder, it might be faster to reset it, like this:

sb.setLength(0);

See this discussion for more details.

Don't convert a List to an array like this:

return arr.toArray(new String[0]);

It's recommended to pass a correctly sized array:

return arr.toArray(new String[arr.size()]);

Better unit tests

Give your test cases meaningful names. So that when your IDE reports some of them failing, it will be easier to understand what failed. For example:

@Test
public void testNormalSentence() {
    final String str1 = "Because";
    final String str2 = "I'm";
    final String str3 = "Batman";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
    Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));
}

@Test
public void testStartingWithDelim() {
    final String str1 = "";
    final String str2 = "I'm";
    final String str3 = "Batman";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
    Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));
}

@Test
public void testEmptyString() {
    final String str1 = "";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1, delim);
    Assert.assertEquals(Arrays.asList(str1), Arrays.asList(parts));
}

These new names describe well exactly what they are testing. This should help understanding the code.

The assertions can be simplified, instead of:

String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
Assert.assertTrue(parts.length == 3);
Assert.assertTrue(parts[0].equals(str1));
Assert.assertTrue(parts[1].equals(str2));
Assert.assertTrue(parts[2].equals(str3));

You could simplify like this:

String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));

This is exactly the same, but shorter, and a lot easier to write.

I would add some more test cases:

@Test
public void testOnlyDelim() {
    final String str1 = "";
    final char delim = ' ';
    String[] parts = StringUtility.split("" + delim + delim, delim);
    Assert.assertEquals(Arrays.asList(str1, str1, str1), Arrays.asList(parts));
}

@Test
public void testNotContainingDelim() {
    final String str1 = "hello";
    final char delim = 'x';
    String[] parts = StringUtility.split(str1, delim);
    Assert.assertEquals(Arrays.asList(str1), Arrays.asList(parts));
}

Suggested implementation

@heslacher's implementation is very close to my taste. Here's a variation of that, with some minor changes:

public static String[] split(String strToSplit, char delimiter) {
    List<String> arr = new ArrayList<>();
    int foundPosition;
    int startIndex = 0;
    while ((foundPosition = strToSplit.indexOf(delimiter, startIndex)) > -1) {
        arr.add(strToSplit.substring(startIndex, foundPosition));
        startIndex = foundPosition + 1;
    }
    arr.add(strToSplit.substring(startIndex));
    return arr.toArray(new String[arr.size()]);
}


It's nice that you're using strict and warnings.

Subroutine Arguments

A subroutine should first unpack the argument list, e.g. like my ($foo, $bar) = @_;, then do some processing, and explicitly return a value. While we can return implicitly and can access items in @_ directly, both can be error-prone and should be avoided in most situations.

For example, this would change the is_strike to

sub is_strike {
    my ($frame) = @_;
    return $frame == 10;
}

The line (is_strike(@_) || is_spare(@_)) ? 2 : 1; is similar obfuscation. First, we'll get rid of the unnecessary ternary operator:

return 2 if is_strike(@_) || is_spare(@_);
return 1;

Next, we make it clearer by unpacking the arguments here as well. Don't mind the implied copy, we are optimizing for readability not performance!

my ($frame_1, $frame_2) = @_;
return 2 if is_strike($frame_1) || is_spare($frame_1, $frame_2);
return 1;

Why is this better? We immediately see that this function only uses its first two parameters.

We can do the same exercise with score_frame. You are using the @_ argument array throughout the whole subroutine, instead of giving each argument a self-explaining name.

# sum the score for x throws,
# where x is the number of throws that count for this frame's score
sub score_frame {
    my ($frame, $index) = @_;
    my $frame_end = $index + 2;
    my $score_end = $index + throws_for_score(@$frame[$index .. $frame_end]);
    return sum @$frame[$frame_index .. $score_end];
}

Let's look at this excerpt:

(my $game = $_[0]) =~ s/-//gi; #remove hyphens
my @throws = split(//, $game); #create an array of throws

The /i flag (case insensitive) on the substitution makes no sense, as you aren't using any characters that have a case. Try to avoid /i, as it makes many optimizations in the regex engine impossible.

If you are only deleting a set of characters, you can use the more efficient transliteration tr/-//d, where d is “delete”. Together with proper argument unpacking, we get:

my ($game) = @_;
$game =~ tr/-//d;
my @throws = split //, $game;

Whether you use parens for the arguments to builtin functions is largely a matter of taste. I prefer to omit them as I find the resulting code cleaner (and faster to write). Others enjoy that parens make the argument list explicit, which is otherwise hard to understand (technically, Perl parsing is not decidable).

This line is hard to understand:

while($current <= $#throws-2); #while the current index is not beyond the tenth frame

I don't know what the tenth frame is about, but wouldn't a condition like $current <= 10 be better if this is about the tenth frame?.

The map Function

The find_strikes function has a number of problems. Here is it's current form:

sub find_strikes { #replace strike marks with 10
    foreach(@{$_[0]}) {
        if($_ eq 'X') {
            $_ = 10;
        }
    }
}

Modifying data that has been passed in is generally frowned upon. If you do something like that, document it. Even better, return a new list.
Whenever possible, name the iteration variable instead of using $_.
Some people prefer the statement if condition form instead of the verbose if (condition) { statement }. Note that the braces are not optional in this case.

For example, we could rewrite the code like this:

sub find_strikes {
    my ($frames) = @_;
    my @frames_with_strikes;

    for my $frame (@frames) {
        if($frame eq 'X') {
            push @frames_with_strikes, 10;
        }
        else {
            push @frames_with_strikes, $frame;
        }
    }

    return @frames_with_strikes;
}

That is excessively verbose, and actually a good example where the ?: operator can be set to good use:

sub find_strikes {
    my ($frames) = @_;
    my @frames_with_strikes;

    for my $frame (@frames) {
        push @frames_with_strikes, ($frame eq 'X') ? 10 : $frame;
    }

    return @frames_with_strikes;
}

We can shorten this further by using a map list transformation instead of an explicit loop:

sub find_strikes {
    my ($frames) = @_;
    return map { $_ eq 'X' ? 10 : $_ } @$frames;
}

It is more “perlish” to take a list of values rather than an array reference:

sub find_strikes {
    my (@frames) = @_;
    return map { $_ eq 'X' ? 10 : $_ } @frames;
}

or without unnecessary copies:

sub find_strikes {
    return map { $_ eq 'X' ? 10 : $_ } @_;
}

In either way, it could now be invoked as

my @frames = find_strikes(split //, $game);

Less action at a distance, and clearer code.

say > print

You have lines like print score_game("X-X-X-X-X-X-X-X-X-X-XX") . "\n". This can be improved

… by passing a list rather than a single string:

print score_game("X-X-X-X-X-X-X-X-X-X-XX"), "\n";

all arguments will be joined without a space (unless you change certain settings).
… by using say instead of print. The say function behaves exactly the same, but automatically appends a newline. Prefer it for normal text output. Use print when you don't want to print out a line, e.g. when handling binary data, a protocol with specific requirements on line endings, or when printing half a line.

use feature qw/say/;  # activate the "say" function, available since v5.10.0

say score_game("X-X-X-X-X-X-X-X-X-X-XX");

Testing

In comments to your print invocations, you have given the expected output. Let's make an automated test out of this!

The Test::More module is Perl's most commonly used test framework. Here is how we can write a test:

use Test::More;

is(score_game("X-X-X-X-X-X-X-X-X-X-XX"),          300, '"X"es');
is(score_game("55-55-55-55-55-55-55-55-55-55-5"), 150, 'fives');
is(score_game("00-00-00-00-00-00-00-00-X-X-XX"),   60, 'zeroes and "X"es');

done_testing;

The is test compares for string equivality (which is also good enough for numbers). There is also the ok test which asserts that some condition is true. The last argument is an optional test description.

When we now execute the script, we get the following output:

ok 1 - "X"es
ok 2 - fives
ok 3 - zeroes and "X"es
1..3

everything passed, nice! If I'm sneaky and change the expected output of one of the functions, we get:

ok 1 - "X"es
not ok 2 - fives
#   Failed test 'fives'
#   at so1.pl line 54.
#          got: '150'
#     expected: '42'
ok 3 - zeroes and "X"es
1..3
# Looks like you failed 1 test of 3.

The is test outputs a reason for the test failure when the input doesn't match our expectations.

The output format is called TAP (Test Anything Protocol), and rarely used manually. Test suites are usually executed with the prove tool, which ships with Perl:

$ prove some_test.pl
some_test.pl .. ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.04 usr  0.00 sys +  0.02 cusr  0.00 csys =  0.06 CPU)
Result: PASS


The suggestions I'd make are all around making the code more robust and more explicit in error handling.

Representing errors

Your methods return Strings. However, I'd say that's not really a good representation of what the methods do. Here's what I mean...

getJiraID can fail. You've checked for this in an assert, which is great. That will give an informative message, but will also stop the program. (It's totally possible that's OK for your case, but in general, it's not). What you could do instead is have the methods return perhaps an Either[Error, String] where Error could be a case class that captures the relevant details of what went wrong.

Why is that important? If I'm using your code, the signature says I'll get a String back no matter what I pass in. However, what really happens is that the programme could stop. That would be very surprising to me as a user.

If, instead, I see the signature is Either[Error, String] I know it could fail, and I have to handle that appropriately.

To be clear: I'm making a general point. Your getJiraID is private, and you could say it's an internal helper, and will never fail in reality, but hopefully, you see the point I'm making.

That carries through into createJIRA which also returns a String (no matter what), but clearly this can fail. It can fail in more ways: presumably, the http client you're using could fail due to network error or a server error.  This is essentially the same point I made above.

JSON

The value data represents JSON. What happens if project contains a quotation mark? You'll have invalid JSON. I'd suggest using a JSON library to construct JSON safely, which will handle the cases of properly encoding String. Circe is a good one, but there are plenty of others.

Hardcoded credentials

You have included a username and password in the body of the code. When that password expires (or changes), you'll have to hunt that down. I'd suggest making those parameters. For example:

case class JiraClient(user: String, pass: String) {
  def create(...) = ...
}

... and then creating a JiraClient at the edges of your code (e.g., in a main) and perhaps reading those credentials from the environment (command-line arguments, configuration file, environment variables). You'd then have something anyone could use, and is easy to change without a recompile.

That same suggestion might apply for the url, too. I don't know how often that might change.

Trivial

Some of the formatting looks a little odd to my eye. E.g., String ={ vs. String = {. Take a look at scalafmt as a way to automatically format your code for consistency.


Setting the position of a navigation highlight

Refactoring

Disclaimer: Sorry, I didn't have a solid chunk of time to test the code, so please consider it as a direction rather than an exact prescription.

It's always possible to break away from loop execution interfering keywords like continue and break. It is also almost always possible to quickly rewrite the code in a "more functional" way. Question is, what exactly is the motivation.

First, in functional world it all about function. And even though my code below does not use function composition, I'm adding getPosition(), isCloseToTop(), and isScrollAfterPosition() to simplify a few conditions. Another benefit of that is that these local functions' names are replacing the ugly comments.

Second, nav.positions.findIndex(...) is used to find out whether there's an item close to top. This is made as an independent step in the code and IMO it's more expressive this way.

If there's no item close to the top of window, we can try to find the last position before the scroll. Again, now it's implemented as a dedicated step (via map() and filter()).

Hopefully, it's now closer to what you wanted the code to be.

function setHighlightPosition(nav) {
  const scrollTop = window.scrollY;
  const scrollMiddle = scrollTop + (window.innerHeight / 2);

  const getPosition = item => document.getElementById(item.id).offsetTop;
  const isCloseToTop = position =>
    Math.abs(position - scrollTop) < 25 ||
    scrollTop < position && position - scrollTop < 50;
  const isScrollAfterPosition = position => scrollMiddle > position;

  const indexOfItemCloseToTop = nav.positions.findIndex(item => item.targeted && isCloseToTop(getPosition(item)));

  if (indexOfItemCloseToTop >= 0) {
    highlightItem = indexOfItemCloseToTop;
  } else {
    const positionsBeforeScroll = nav.positions
      .map((item, itemIndex) => (item.targeted && isScrollAfterPosition(getPosition(item))) ? itemIndex : null)
      .filter(index => index !== null);
    highlightItem = positionsBeforeScroll[positionsBeforeScroll.length - 1];
  }

  const documentEnd = document.documentElement.scrollHeight - window.innerHeight;
  if (scrollTop === documentEnd) {
    highlightItem = nav.positions.length - 1;
  }

  const highlight = document.getElementById('nav-highlight');
  highlight.style.transform = `translateY(${nav.positions[highlightItem].position}px)`;
  highlight.dataset.position = highlightItem;
}

BTW, I moved variable declarations around so that the declarations are located next to their first usages. This reduces brain cycles and eliminates the need of scrolling the code up and down.


Set args = (int(s != None), int(p != None), int(o != None)) [or args = ''.join(map(str, (int(s != None), int(p != None), int(o != None))))]

Now args will be (1, 0, 1) [or '101'] if p is None and the other two aren't.
Also, instead of using for loops you can use generator expressions to make the code more concise.

def triples(self, (s, p, o)):
    try:
        args = (int(s != None), int(p != None), int(o != None))
        if args == (1, 1, 1):
            #if o in self._spo[s][p]: #See sindikat's comment below
            #   yield (s, p, o)
            return iter([(s, p, o)] if o in self._spo[s][p] else [])
        if args == (1, 1, 0):
            return ((s, p, ro) for ro in self._spo[s][p])
        if args == (1, 0, 1):
            return ((s, rp, o) for rp in self._osp[o][s])
        if args == (1, 0, 0):
            return ((s, rp, ro) for rp, oset in self._spo[s].items() for ro in oset)
        if args == (0, 1, 1):
            return ((rs, p, o) for rs in self._pos[p][o])
        if args == (0, 1, 0):
            return ((rs, p, ro) for ro, sset in self._pos[p].items() for rs in sset)
        if args == (0, 0, 1):
            return ((rs, rp, o) for rs, pset in self._osp[o].items() for rp in pset)
        if args == (0, 0, 0):
            return ((rs, rp, ro) for rs, pset in self._spo.items() for rp, oset in pset.items() for ro in oset)
    except KeyError:
        pass

Combining this with Winston's suggestion you get the following definition

def triples(self, (s, p, o)):
    try:
        args = (int(s != None), int(p != None), int(o != None))

        if args in [(1, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 0)]:
            lookat  = self._spo
            a1 = s; a2 = p; a3 = o;
            invperm = [0, 1, 2]
        if args in [(0, 1, 1), (0, 1, 0)]:
            lookat = self._pos
            a1 = p; a2 = o; a3 = s;
            invperm = [2, 0, 1]
        if args in [(1, 0, 1), (0, 0, 1)]:
            lookat = self._osp
            a1 = o; a2 = s; a3 = p;
            invperm = [1, 2, 0]

        permute = lambda x, p: (x[p[0]], x[p[1]], x[p[2]])

        if sum(args) == 3:
            #if a3 in lookat[a1][a2]: #See sindikat's comment below
            #   yield permute((a1, a2, a3), invperm)
            return iter([permute((a1, a2, a3), invperm)] if a3 in lookat[a1][a2] else [])
        if sum(args) == 2:
            return (permute((a1, a2, ra3), invperm) for ra3 in lookat[a1][a2])
        if sum(args) == 1:
            return (permute((a1, ra2, ra3), invperm) for ra2, a3set in lookat[a1].items() for ra3 in a3set)
        if sum(args) == 0:
            return (permute((a1, a2, a3), invperm) for ra1, a2set in lookat.items() for ra2, a3set in a2set.items() for ra3 in a3set)
    except KeyError:
        pass

Although this is slightly longer, it is easier to maintain in the sense that if you feel that the dictionary to look at should be changed (for better performance) for some combination of input, then the modification is easily accomplished with the second definition.


Error Handling - Controller's OnException and Application_Error

The OnException() methods does 2 things.

It logs the exception
It creates an return value

So let us refactor these two points to two separate methods.

private void LogException(ExceptionContext exceptionContext)
{
    logger = log4net.LogManager.GetLogger(exceptionContext.Controller.ToString());
    logger.Error(exceptionContext.Exception.Message, exceptionContext.Exception);
}

private const String XMLHttpRequest = "XMLHttpRequest";
private const String XRequestedWithHeadername= "X-Requested-With";
private const String JSONErrorMessage = "Sorry, an error occurred while processing your request.";
private void CreateExceptionContextResult(ExceptionContext exceptionContext)
{
    if (exceptionContext.HttpContext.Request.Headers[XRequestedWithHeadername] == XMLHttpRequest )
    {
        //Return JSON
        exceptionContext.Result = new JsonResult
        {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new { error = true, message = JSONErrorMessage }
        };
    }
    else
    {
        //Redirect user to error page
        exceptionContext.ExceptionHandled = true;
        exceptionContext.Result = this.RedirectToAction("Index", "Error");
    }
}

If we want to handle the different error types, we should create a new class which only keeps the values for actionName and controllerName.

public class ActionControllerName
{
     public String ActionName { get; private set; }
     public String ControllerName { get; private set; }
     public ActionControllerName(String actionName, String controllerName)
     {
         ActionName = actionName;
         ControllerName = controllerName;
     }
}

Now we add a Dictionary and a method to fill this dictionary, which should be called in the constructor, or injected by an property.

private const int DefaultEntryKey = -1;
private Dictionary<int,ActionControllerName> redirectDictionary = new Dictionary<int,ActionControllerName>();
private void FillRedirectDictionary()
{
    redirectDictionary.Add(DefaultEntryKey , new ActionControllerName("Index", "Error"));
    // more to add
}

Next we implement a method to get a RedirectToRouteResult passing the exception as parameter

private RedirectToRouteResult GetRedirect(Exception exception)
{
    int errorCode = DefaultEntryKey;
    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        errorCode = httpException.ErrorCode;
        if (!redirectDictionary.ContainsKey(errorCode))
        {
            errorCode = DefaultEntryKey;
        }
    }
    ActionControllerName acn = redirectDictionary[errorCode];
    return this.RedirectToAction(acn.ActionName , acn.ControllerName);
}

We go back to this else part

else
{
    //Redirect user to error page
    exceptionContext.ExceptionHandled = true;
    exceptionContext.Result = this.RedirectToAction("Index", "Error");
}

and change it to

else
{
    //Redirect user to error page
    exceptionContext.ExceptionHandled = true;
    exceptionContext.Result = GetRedirect(exceptionContext.Exception);
}


Follow some standards, use code linting (for example ESLint) and code formatting (for example Prettier), try to prevent code duplication as much as possible,
use design patterns and don't complex things. Those things will make your code more readable for others.

There is no right or wrong while the code works and it's easy to read.

Martin Fowler.

  Any fool can write code that a computer can understand. Good
  programmers write code that humans can understand.


Asking the user to input a proper email address

Okay so as a general comment, validation like this is fine (well except
it's discarding potentially valid addresses with the check for . and
the minimum length, but I guess you know that), but in a real
application you most likely want to just send an email and check if it
was received, that also deals with a whole lot of other problems.

That said, of course this snippet can be shortened.  I don't see why the
two permutations of the loop are necessary in the first place.

Everything duplicated has the potential to be eliminated, but the
result might be more or less readable and possibly longer (because there
are only two cases here for example, so making the code more generic
would only pay off with more cases).

What's the function going to be here?  Checking if all the characters
are in the email string, e.g. check_email_contains.  What varies?
Only the specific characters really.  So pass that in and return the
final address (without using globals) to be future proof.

Looks like this:

email_address = check_email_contains(input("What is your email address? "), "@.")

Lastly, the check function is very simple too:

def check_email_contains(email_address, characters, min_length=6):
    while True:
        for character in characters:
            if character not in email_address:
                email_address = input("Your email address must have '{}' in it\nPlease write your email address again: ".format(character))
                continue
        if len(email_address) <= min_length:
            email_address = input("Your email address is too short\nPlease write your email address again: ")
            continue
        return email_address

The loops in there are doing a bit too much, I'll leave that as an
exercise for the reader to optimise it.


Prefixing prices of certain product categories with text in Woocommerce

You could reduce your script to this: (untested)
add_filter('woocommerce_get_price_html', 'change_product_price_html');
function change_product_price_html($product, $price) {
    $categories = ["17"];
    if (!is_shop() || !array_intersect_key(array_flip($product->get_category_ids()), array_flip($categories))) {
        return $price;
    }
    return "<span class=\"woocommerce-Price-amount amount\">Starting at </span>{$price}";
}

pass the $product into the custom function's scope as an argument to avoid the global declaration.

merge the un-prefixed return conditions into a single expression.

while only a benchmark executed on your system will tell the real truth, I am employing a key-based comparison between two arrays.  The downside is that it may do more work than it needs to (by finding multiple matches). The good news is, it is not going to perform multiple full array scans like a looped in_array() technique might.  I'm not going to be too pushy about how to best compare the two category arrays -- I just wanted to show an alternative.

Alternatively, this will be an easier array-to-array comparison to read:
if (!is_shop() || !array_intersect($product->get_category_ids(), $categories)) {
    return $price;
}

I assume you were calling your posted function like change_product_price_html($price);.
To add the $product variable as the first expected argument, call my custom function like this:
change_product_price_html($product, $price);


LeetCode: Queue Reconstruction by Height C#

API

I assume it's part of the platform requirements, but int[] is a terrible data-structure for storing the (k, h) pair, because it could have any length and implies an ordering that doesn't really exist. This should be a small class or immutable struct. (Not a Tuple, because Tuples are structural, and therefore only solve part of the problem).

Even if this was imposed upon me, I would want to map it to something sensible before doing anything else. This mapping would act as a (necessary) validation layer, to check I'm not being given nonsense.

ReconstructQueueList

This should document what it does.

I don't see the point in initialising every element of res, when you could just assign them a copy of the existing person array when you set them. This makes the code much tidier. I would move the declaration of res toward where it is actually used.

list is a completely meaningless variable name. These are the positions in the queue that you have yet to be assigned, so I will call it positions; however, I'm sure you can think of something much better. I would create positions with Enumerable.Range(0, people.Length), which is more compact and has less scope for errors. I doubt the added overhead will be significant, but feel free to measure it.

PairComparer

PairComparer is not a fantastic name for something that sorts people.

It's good that you've given some description of what the custom comparer does. However, I don't understand the description you provide.

I'd prefer to see x[0].CompareTo(y[0]) instead of x[0] = y[0]: it's much clearer what is going on, and it doesn't risk overflowing for numbers with large magnitude.

Performance

This section is pretty underwhelming

If we ignore the problem size limit of 1100 (where did they find that number?), the main performance concern is the List.Remove(int) calls, which means this algorithm is quadratic in the worst case (though linear in the best case). You can address this by using a data-structure which allows log(n) removal by index. I threw together a simple OrderedShrinkList, where removing every has a cost of n log(n) and n is the number of elements with which it begins, and ran some benchmarks.

Swapping this appears to give a significant performance boost for large problems: it is 10 times faster on a particular random instance of size 200000 gist of code and results (it seems to be slower for smaller ones).

Running small problems (e.g. size 1100 and smaller), the potential inefficiency of List based method is not immediately revealed, and the overhead of my shoddy OrderedShrinkList seems to make it significantly slower. I've run out of energy to keep trying things, but a linked list might actually improve things, because it replacing a linear 'move' with a linear scan, and you can choose at which end to start.

Note: I did run benchmark for some different seeds, and the general trend was similar, but this isn't the most rigorous test ever.


Software drivers for the mcu peripherals in C++

Avoid the placement new
The placement new you are doing looks redundant. PeripheralRegs is a POD type, so its member values will probably not be initialized, but to avoid any doubt I would just write:
Peripheral::Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address):
    regs{reinterpret_cast<PeripheralRegs*>(base_address)}
{
    regs->control_reg.cfg_bit_01 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_1);
    regs->control_reg.cfg_bit_02 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_2);
    regs->control_reg.cfg_bit_03 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_3);
}

Toggle using XOR
You can rewrite toggleReset() by using the XOR operation:
void Peripheral::toggleReset()
{
    regs->control_reg.reset_bit ^= 1;
}

Why the k prefix for enum class values?
I see the values of enum class FunctionUsage are prefixed with a k. This looks like Hungarian notation, but I don't see Hungarian notation used anywhere else in this code. I suggest you drop it. Since it's an enum class, there is no chance that these values would conflict with anything else.
Use arrays where appropriate
I see several variables being repeated with just a different number at the end. Those are often a candidate to be replaced by arrays. Consider writing:
struct PeripheralCfg
{
  FunctionUsage cfg_bits[3];
};

...

struct DriversCfg
{
    PeripheralCfg periph_cfgs[2] = {
        {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed, FunctionUsage::kAdcUsed},
        {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed},
    };
};

...

class Hal {
    ...
    Peripheral *peripherals[2];
    ...
};

And so on. You can always rename the variables you used before to refer to an array element, for example periph_01 becomes periph[0]. Also, it opens up possibilities to use for-loops to avoid repetition:
for (auto &periph: hal.peripherals)
    periph->enable();

Although it looks silly now with an array of only two elements, it will quickly become more useful if you have to support hardware which supports more peripherals.
Make Hal::configuration static const
It looks like Hal::configuration is only meant to be read once, and never changed. You should change it into a static const variable:
class Hal {
    ...
    static const DriversCfg configuration;
    ...
};

Although it does look a bit weird this way. If it's only used by the constructor of Hal, then this should not be a (static) class member at all. You could move it completely into Hal.cpp:
static const struct
{
    PerpheralCfg periph_configs[2] = {...};
} configuration;

Hal::Hal() {
    perhiperal[0] = new Peripheral(configuration.periph_cfgs[0], PERIPH_01_BASE_ADDRESS);
    perhiperal[1] = new Peripheral(configuration.periph_cfgs[1], PERIPH_02_BASE_ADDRESS);
}

You could also keep the configuration in DriversCfg.h, but then still exactly as I've shown here.
As for the order of instantiation: global variables are instantiated before main() runs, so configuration will be valid before the variable hal is constructed. If it was still a regular member variable, then it would also have been instantiated before the body of the constructor was run, so your code is fine in that respect.
Avoid unnecessary memory allocations
Why does Hal need to allocate the Peripherals on the heap? Especially on an MCU you want to avoid dynamic memory allocations. So instead of having pointers to Peripherals inside class Hal, just have them by value:
class Hal {
public:
    Peripheral peripherals[2];
    Hal();
};

...

Hal::Hal():
    peripherals{
        {configuration.periph_cfgs[0], PERIPH_01_BASE_ADDRESS},
        {configuration.periph_cfgs[1], PERIPH_02_BASE_ADDRESS},
    }
{}

And then use it like so:
int main(...)
{
    Hal hal;
    for (auto &periph: hal.peripherals)
        periph.enable();
}


Changing the environment if it sees the incorrect environment in the setting

The built in JS array transformation functions could help you reduce duplicated code.
const environments = ['environmentProduction','environmentDevelopment'];

class SettingsPage extends Page {

    changeEnvironment(appName) {
        const all_buttons = environments.map(
            env=>appName.$(PreferenceScreen[env])
        );
        const displayed_buttons = all_buttons.filter(button=>button.isDisplayed());
        displayed_buttons.forEach(button=>button.click());
    }
}


Slicing a list makes a copy of it, e.g.:

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = a[:5]
>>> b
[0, 1, 2, 3, 4]
>>> b[2] = 0
>>> b
[0, 1, 0, 3, 4]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

So each of your recursive calls is creating a copy of half of the list before passing it down, which is not the best use of time. I think it is a much better approach to pass around the whole list, which simply passes a reference to it around, no copies involved, and a couple of indices marking the range you want to work on:

def mergesort(alist, lo=0, hi=None):
    if hi is None:
        hi = len(alist)
    if hi - lo <= 1:
        return
    mid = lo + (hi - lo) // 2  # mid = (lo + hi) // 2 can overflow
    mergesort(alist, lo=lo, hi=mid)
    mergesort(alist, lo=mid, hi=hi)
    # Copy out the left side, which may be overwritten by the merge
    temp = alist[lo:mid]
    read_left = 0  # index into temp, copy of left subarray
    read_right = mid  # index into alist's right subarray
    write = lo  # index into alist
    while read_left < len(temp) and read_right < hi:
        if alist[read_right] < temp[read_left]:
            alist[write] = alist[read_right]
            read_right += 1
        else:
            alist[write] = temp[read_left]
            read_left += 1
        write += 1
    # Copy any unprocessed items in temp back to alist
    alist[write:write+len(temp)-read_left] = temp[read_left:]
    # Any unprocessed items in right subarray are already in place!
    # Nothing returned: the list gets sorted in-place


You are distinguishing between hasNextInt() and hasNextDouble() in the input stream, but treating them identically afterwards.  hasNextDouble() will return true if the next token is an integer, because integers can be successfully parsed as a double too.

So your loop could be simplified into:

double width = 0.0;

for(;;) {
    System.out.print("Enter width: ");
    if (input.hasNextDouble()) {
        width = input.nextDouble();
        if (width > 0)
            break;
    }
    System.out.println("Input error. Try again.");
    input.nextLine();
}

A few notes:

The unnecessary validWidth variable has been removed.  A break statement exits the infinite for(;;) loop, skipping over the "cleanup, try again" code.
.nextLine() is used to cleanup after invalid input. This is important, because if the user enters "one fish two fish red fish blue fish" instead of say -12, your current approach will print out "Input error. Try again" 8 times.  Using .nextLine() discards everything up to and including the new line character.  Which brings us to zero and negative numbers.  If the user enters a valid integer/double, but not a positive one, your code didn't skip any tokens, where as my code (as mentioned above) will skip the remaining input up to and including the new line character.  Assuming the next character was a new line (as in the user entered -12 and pressed the return key) the following .hasNextDouble() will skip over the new line (and any other blank space) looking for the next token, so the effect is approximately the same.
But my code performs differently if the user enters red 5.  You original code will print "Invalid input.  Try again.", and then immediately consume the 5 as valid input, where as my code will discard the remainder of the line, and wait for the user to enter another line.

Since you are using the code multiple places, putting it into a method is prudent.  Here is one using a DoublePredicate functional interface in order to validate the input according to the caller's requirements:

double getDouble(Scanner input, String prompt, DoublePredicate validate) {
    double value = 0.0;

    for(;;) {
        System.out.print(prompt);
        if (input.hasNextDouble()) {
            value = input.nextDouble();
            if (validate.test(value))
                return value;
        }
        System.out.println("Input error. Try again.");
        input.nextLine();
    }
}

Which you could use with a lambda function like:

    double width = getDouble(input, "Enter width: ", x -> x > 0);


There is an easy way to clean up your loop:

lastSeven = [endDate]
for x in range(1, 7):
    lastSeven.append(endDate - datetime.timedelta(x))

Essentially, I am working backwards instead of forwards. This yields the correct dates, but in backwards order.

If you want them in chronological order do:

lastSeven.sort()

Also, just in case you don't like the sorting thing, here's a version which goes forwards:

lastSeven = [endDate - datetime.timedelta(7)]
for x in range(1, 7):
    lastSeven.append(lastSeven[x-1] + dateTime.timeDelta(1))

Lastly, there are some issues with your coding style:

Don't write code like this:

shortName    = 3
veryLongName = 4

Write code like this:

shortName = 3
veryLongName = 4

Also, put a space between arguments (so foo(x, y) is correct, while foo(x,y) is not).

This is in line with PEP8, the python style guide

Lastly, you can use a list comprehension for a bit of extra speed as one of the answers suggests, but it comes at the cost of readability, which is something that Python strives to maximize over speed (usually).

Here are two below:

# go backwards, then sort
lastSeven = [endDate - datetime.timedelta(x) for x in range(7)].sort()

# go to start, then iterate forwards
startDate = endDate - datetime.timedelta(7-1)
lastSeven = [startDate + datetime.timedelta(x) for x in range(7)]


Get _m_s time format from milliseconds value

Seems overly complicated.  Let the builtin math and parsing functions do the work for you.  And name time values something like t.

const ms = t => alert( `${parseInt( t/1000 / 60 )}m${parseInt( t/1000 % 60 )}s` )
ms(1040370);


Sanitising user inputs and user inputted data outputs

Personally I tend to work with a white-list of characters.

So instead of sanitizing and removing bad stuf, I simply only accept good stuff.
e.g. [0-9]+ when validating an age field

This approach is less error prone because you don't have to think of all the bad things one can enter. And you know that the data you are serving is actualy what you tink it is (e.g. a number when referencing age).


Sorts and data structures: a bucket sort

You have implemented an unusual bucket sort. First, the logic to compute the
bucket number makes assumptions about the values themselves and will fail on
many types of numbers (for example, positive integers). And second, if N is the size
of the input list, you are creating N buckets. Typically, bucket sort uses a
number of buckets that is smaller than N. A common approach is to make an initial pass
over the values to find their min and max. Then each bucket will have a
span of (MAX - MIN) / K, where K is the number of buckets
(which might be set either by the caller or by the code based on N).
For any x value, I think its bucket index would be
min(K - 1, int((x - MIN) / SPAN)) (you should double check that).
My other comments relate to code readability and simplicity.
Use convenience variables to eliminate repeated calculations, such as
len(array). If you need it multiple times, create a variable and lighten the
visual weight of your code.
Organize your code into commented "paragraphs" -- one paragraph per
small step in the logic of your algorithm (shown below).
If you need to iterate over values in a collection, do it directly, not
indirectly via indexes. Use for x in xs not for i in range(len(xs). If the
algorithm requires both values an indexes, use enumerate(). Only iterate
over indexes if you don't actually need the values or if the algorithm's
readability is simpler that way (for example, in your
insertion_sort() function).
Your code to reassemble the sorted buckets it overly complicated --
specifically, the size of the buckets is not important. The work can be done
either with a list comprehension (as shown) or the equivalent use of 2 for
loops.
Consider using a naming convention that I learned from functional programming:
xs for a collection of things and x for one thing.
Its extendable (ys and y, zs and z, etc) and
it works quite nicely in
generic situations like this where we know nothing about the substantive
meaning of the values. This also lightens up the code weight -- enhancing
readability without any loss of understandability.
The variable naming in insertion_sort() is backwards. You iterate over the
indexes but call each index an unsorted_val. If it's an index, just call it
index or, even better, i (a convention everyone understands). Then if you
also need the value, get it with xs[i]. Again, notice how these short
variable naming conventions can often enhance readability -- especially if the
scope is small and well defined.
Finally, it is unusual to modify an index value during an
iteration over indexes, as you do in insertion_sort(). It forces
your reader to puzzle things over. I've seen more intuitive insertion
sort implementations. For comparison, see the this pseudo-code.
Note how the use of "swap" in that alternative implementation really
helps the reader understand what's going on. Either adjust your
code or add some guidance to your reader.
Here's an edit focused on the readability and simplicity issues only:
def bucket_sort(xs):
    # Convenience variables.
    N = len(xs)

    # Put values into buckets.
    buckets = [[] for _ in range(N)]
    for x in xs:
        i = int(N * x)
        buckets[i].append(x)

    # Sort each bucket.
    #
    # To keep hammering the point, `b` is a better variable
    # name than `bucket` within this tiny, well-defined context.
    for b in buckets:
        insertion_sort(b)

    # Return the sorted values.
    return [
        x
        for b in buckets
        for x in b
    ]

def insertion_sort(xs):
    # Only stylistic edits here.
    for i in range(1, len(xs)):
        x = xs[i]
        while i > 0 and xs[i - 1] > x:
            xs[i] = xs[i - 1]
            i -= 1
        xs[i] = x


functools.singledispatch

functools library includes the singledispatch() decorator.  It lets you provide a generic function, but provide special cases based on the type of the first argument.

import functools
import random

@functools.singledispatch
def shuffle(arg, order):
    """this is the generic shuffle function"""

    lst = list(arg)
    return type(arg)(lst[i] for i in order)

@shuffle.register(dict)
def _(arg, order):
    """this is shuffle() specialized to handle dicts"""

    item = list(arg.items())
    return dict(item[i] for i in order)

def ordered_shuffle(*args):
    min_length = min(map(len, args))

    indices = random.sample(range(min_length), min_length)

    return [shuffle(arg, indices) for arg in args]

Usage:

a = (1, 2, {3: 4}, 5)
b = [(5,6), [7,8], [9,0], [1,2]]
c = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}

ordered_shuffle(a, b, c)

Output:

[({3: 4}, 1, 2),
 [[9, 0], (5, 6), [7, 8]],
 {0: ('x', 2), 'arrow': 5, 'knee': 'guard'}]


In this code:

for i in range(0,len(prices)):
    added_value = (prices[i] - prices[i-1])/prices[i-1]

You start with i = 0. In that case, prices[i-1] will be prices[-1] which will access the last element in the prices list. That is, prices[len(prices) - 1].

I think this probably isn't what you want. You might want to do:

for i in range(1, len(prices)):

instead, so that prices[i-1] starts at zero. But then you won't run the loop on i=0, if that matters.

Alternatively, you might want to try:

last_price = 0
for i, price in enumerate(prices):
    added_value = 1.00 if last_price == 0 else (price - last_price)/last_price

    # ...
    last_price = price

Get rid of magic numbers

Your declaration that "buy_index == 1" means buy, and 2 means sell is ridiculous. If your code produces those numbers, then change your code. If you are reading the numbers from somewhere, change the numbers:

crossovers = ((t, 'buy' if a == 1 else 'sell') for t,a in crossovers)

You might use an enum instead, but if you're going to JSON, or reading from JSON, the string is probably easier.

Use modern Python idioms

One of the tenets of "modern Python" (3.x-style) is a bias towards iteration, especially the notion of infinite iterables. In other words:

Expect iterables, not sequences.
Generate, don't return a list.

I suggest that you convert prices to a series of (time, price) tuples, so that there is only one "source of truth" when it comes to what time should associate with a price.

Next, treat prices and crossovers as series, not lists: assume they are potentially infinite, and iterate them instead of trying to index them:

xo = iter(crossovers)
x_time, x_action = next(xo)

for time, price in prices:
    if time == x_time:
        if x_action == 'buy':
            #...
        x_time, x_action = next(xo)

Similarly, don't build a values = [] list and return it. Instead, yield your values when appropriate. And since they aren't indexed in a list, provide a timestamp to go along:

        yield time, round(cash, 2)
        # or
        yield time, round(stock_at, 2)


Radio button selection and flash object initialization

From the looks of it, you are using jQuery as your JavaScript library. Here are the improvements that I think will make your code better.

Don't duplicate code. Use functions (objects).

For example:
flashObj must be accessible to this function.

 var getDataFromButton = function(elementId, state, isLiveData){
   $("input:radio[name=preview-options]").click(function () {
     var isLiveData = $(this).val();
     flashObj.ext_sendLayoutDefinition(elementId, state, isLiveData);
   });
 }

Use local variables were possible.
Instead of defining the variable 'base' and 'flashObject' twice, define it once outside the if/else statements and modify it inside them.

Or you can redesign the logic by making an object that has properties such as base, isLiveData, and flashObject.

Without knowing the purpose of this code, this is all I can suggest as improvements.


I wrote my answer in c++, it might help you. On first look, our solutions are quite similar, at least from an idea standpoint.

//
// Created by Felix Crazzolara on 09.12.17.
//

#include <cstdlib>
#include <iostream>

using namespace std;

int main (int argc, char* argv[]) {
    int position = 277678;

    // Find spiral radius
    int n = 1;
    while (position > n*n)
         n += 2;
    // Find side
    int side = 4;
    int pos = n*n;
    while (side > 1 && position < (pos - n + 1)) {
        pos -= n + 1;
        --side;
    }
    int middle_point = pos - (n - 1) / 2;
    int dist = abs(position - middle_point);
    dist += (n - 1) / 2;
    cout << dist << endl;
}

Explanation:
The highest number in every spiral is the bottom right corner, that has the value \$n^2\$ if we denote the length of the sides of a spiral with \$n\$.

If a spiral has side length \$n\$ obviously the next spiral has side length \$n' = n + 2\$.

Let's assume that our point is in the spiral with side length \$n\$. There are 4 corners. Our point got to be somewhere, so we want to find a corner that is greater-equal our point. Once we got the "smallest" corner being greater-equal then our point, we know, that our point must lay on the side given by the found corner and the next smaller corner.

When starring a bit on the first numbers of the memory layout, once you'll remark that the way to go the origin is given by the way to go to the closest point being vertical/horizontal in respect to the origin, being on the current spiral, plus the way from that point to the origin.

How these ideas fit together in code, I'll leave up to you to think about.


Finding the maximum sum of any 2 elements in an array of integers

Your code tries all \$ n (n+1)/2 \$ combinations of array elements to find the
combination with the largest sum, so the complexity is \$ O(n^2) \$.

A better solution would be to find the two largest elements in the
array, since adding those obviously gives the largest sum.

Possible approaches are:

Sort the array elements in increasing order and add the last two
elements. Efficient sorting algorithms (such as Quicksort) have an
average complexity of \$ O(n \log(n)) \$.
Traverse the array once and keep track of the largest and second
largest element encountered so far. Then add those elements.
The complexity is \$ O(n) \$.

Other remarks:

Your main program computes maxSum(array) twice,
which is not necessary.
You should check if the user entered at least 2 elements, otherwise
the problem is ill-defined.
The if (!in.hasNextInt()) check is not really helpful. If the user
enters a non-integer, "put an integer! " is printed, but then in.nextInt() fails with an exception. You could for example
skip the entire input line until a valid integer is entered:

while (!in.hasNextInt()) {
    System.out.println("Enter an integer! ");
    in.nextLine();
}
int size = in.nextInt();


Concat a collection's sub arrays and merge their parent

This can be done natively:

var revisionMap = arr.reduce((map, entry) => {
  var revision = entry.revision;

  if(map.hasOwnProperty(revision))
    map[revision].details.push(...entry.details);
  else
    map[revision] = _.clone(entry);

  return map;
}, {});

/*
{
  1: { revision: REV, text: TEXT, details: [] },
  2: { revision: REV, text: TEXT, details: [] },
}
*/

var expected = Object.keys(revisionMap).map( key => revisionMap[key] );

/*
[
  { revision: REV, text: TEXT, details: [] },
  { revision: REV, text: TEXT, details: [] },
]
*/

First, make a mapping of ID to revision data. This way, we can easily check the existence of an already visited revision and know when to append rather than assign. Then, we convert that object into an array.

The only thing not native is the use of _.clone as we don't want to be modifying the original data when we're be appending details.


C program to count number of lines in a file

As you say, it works fine.  But I can nitpick.

The main flaw is that you could get a wrong count if any line is longer than 999 bytes.  (In general, you should stress-test your code by cranking down the buffer size to ridiculously small numbers and checking whether you obtain the same results.)

The performance could be improved.  Since fgets() has no way of knowing in advance where the newlines occur, it must read the file contents into a temporary buffer (which is invisible to you), then copy each line into the line buffer.  Since only care about counting '\n' characters, you could read fixed-size blocks to avoid this internal copying.

It's awkward to read 1000 bytes at a time.  You would be better off reading chunks that are aligned with the blocks on the disk.  A better choice would be 1024.

You could use the perror() function to report why I/O operations failed.  Technically, fgets() could fail too, so you should check for that.

It's a good habit to ensure that your fopen() is paired with fclose().

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 1024

int main(void) {
    const char filename[] = "test";
    FILE *in_file;
    char buffer[SIZE + 1], lastchar = '\n';
    size_t bytes;
    int lines = 0;

    if (NULL == (in_file = fopen(filename, "r"))) {
        perror(filename);
        return EXIT_FAILURE;
    }

    while ((bytes = fread(buffer, 1, sizeof(buffer) - 1, in_file))) {
        lastchar = buffer[bytes - 1];
        for (char *c = buffer; (c = memchr(c, '\n', bytes - (c - buffer))); c++) {
            lines++;
        }
    }
    if (lastchar != '\n') {
        lines++;  /* Count the last line even if it lacks a newline */
    }
    if (ferror(in_file)) {
        perror(filename);
        fclose(in_file);
        return EXIT_FAILURE;
    }

    fclose(in_file);
    printf("Number of lines in the file is %i\n", lines);
}

The for loop above is a bit tricky for beginners, but should be acceptable for experienced C programmers.  The loop

for (char *c = buffer; (c = memchr(c, '\n', bytes - (c - buffer))); c++)

means:

Search for the next newline, starting from the pointer c, in the remaining bytes - (c - buffer) bytes that have been read but not examined yet.
If a newline is found, make c point to the position just after it.
If no newline is found, then we're done with this chunk.  Try reading more input then.

The extra set of parentheses around c = memchr(…) is an indication to the compiler and to other programmers that the = is indeed intentional, and is not supposed to be ==.


Shorten dict comprehension with repeated operation

dc = dict(line.split('=') for line in txt)


Reducing a list of points into a list of pairs of points

Let's start with the first version: A loop

var i = 0
while i < points.count {
    // ...
    i += 2
}

can be written as a for-loop over a stride:

for i in stride(from: 0, to: points.count, by: 2) {
    // ...
}

which restricts the scope of i to the loop body, and makes it a constant. Now each loop iteration appends exactly one element to var result: PointPair, which means that we can write this as a map operation:

let result: PointPair = stride(from: 0, to: points.count, by: 2)
    .map { i in
        (start: Point(x: points[i].0, y: points[i].1),
         end: Point(x: points[i+1].0, y: points[i+1].1))
    }

This may already be the “functional” version that you are looking for, but let's also have a look at your other two variants.

The “intuitive code” creates two additional arrays by filtering the original one for even/odd indices. After filtering the arrays the offsets are not needed, giving the warnings

Immutable value 'offset' was never used; consider replacing with '_' or removing it
Immutable value 'offsetTwo' was never used; consider replacing with '_' or removing it

This can be fixed with

let (_, point) = one
let (_, otherPoint) = other

A better way is to use compactMap() (which can be thought of as a combination of filter() and map()) to create arrays of the points with even/odd indices, without the element offsets.

Using reduce() for creating the result array is inefficient, as it creates intermediate arrays for each iteration. reduce(into:_:) would be an improvement, but actually this is just a map():

let result: PointPair = zip(
    points.enumerated().compactMap { (offset, element) -> Point? in
        offset % 2 == 0 ? Point(x: element.0, y: element.1) : nil },
    points.enumerated().compactMap { (offset, element) -> Point? in
        offset % 2 == 1 ? Point(x: element.0, y: element.1) : nil }
).map { ($0, $1) }

This looks a lot “less messy” than your original version, but still has the disadvantage of creating intermediate arrays.

I have not much to say about your last version. It uses reduce(into:) which is good to avoid the creation of intermediate arrays. The only disadvantage is that temporary pairs are created and modified in every second step.

So the  “stride + map” variant looks like the best to me: It is efficient and easy to read.

A final remark: The type alias

typealias PointPair = [(start: Point, end: Point)]

is misleading, because it does not define a pair of points but an array of pairs of points. I would probably define a dedicated type for a pair of points instead

struct Line {
    let from: Point
    let to: Point
}

and then use [Line]  as the result type.


Temperature and speed unit converter class in JS

A static Object
The class syntax is not very well suited to this type of object use. The object should be a static object, as you would only ever need one instance, and you should not need to instantiate it each time you need to use it.
Reduce complexity
Having to write a conversion from each type of unit means you add a lot of extra code.
Say you added a Kelvin Unit to temperatures, your code would need to convert from C => F, C => K, F => C, F=> K, K => C, and K => F. For some types of units this would quickly balloon out of control.
For conversion you always convert to a standard unit, and then convert that value to the unit you want. This reduces the complexity. I would advice you to use SI units, however what units you choice is is irrelevant.
Units have meaning
Be aware that there are limits to some units.
Temperatures have a base of -273.15C, returning a value less than that is meaningless.
The speed of light is the upper limit of speed, however conceptually speeds above this limit can still have meaning.
Why create the converter
A conversion object is by its nature an object of convenience, as the actual computations are trivial and for any computational work should be inline. So when you design such an object, consider how it is to be used. Adding common constants for example, provide aliases
You can also add functionality dynamically, see example that creates direct conversion function, eg the function Units.kmph2mph(kmph) is created dynamically
Example
The example has added a lot of extra functionality, none of it is a must outside your direct conversions, its just to give you some ideas on how these things can be done.
The snippet contains a static object 'Units' created via a self invoking function. It includes some aliases eg unit.F is same as unit.fahrenheit. some constants, and some dynamic functions.
All units are converted to a base unit type (kelvin and meters per second)
Usage as follows
Units.kmph = 100;
const mph = Units.mph;
Units.celsius = 38;
const f = Units.fahrenheit;

//or via direct conversion

const mph = Units.kmph2mph(100);
const f = Units.C2F(38);
const zeroF = Units.K2F(Units.ABSOLUTE_ZERO_K);
Units.C2K(-10000); // will return 0

Please note I have not tested this snippet and it may contain typos, it is as an example only.
const Units = (() => {
    var tempK = 0;
    var ms = 0; // meters per second
    const secondsPerHour = 60 * 60;
    const zeroC = - 273.15
    const API = {
        /* Temps */
        get fahrenheit(){ return API.celsius * 1.8 + 32},
        get celsius() {return API.kelvin + zeroC},
        get kelvin() {return tempK < 0 ? 0 : tempK },
        set fahrenheit(f) {tempK = (f - 32) / 1.8 - zeroC},
        set celsius(c) {tempK = c - zeroC},
        set kelvin(k) {tempK = k},
        /* Speeds */
        get milesPerHour() {return ms / secondsPerHour / 1600},
        get kilometersPerHour() {return ms / secondsPerHour / 1000},
        get metersPerSecond() {return ms },
        set milesPerHour(mph) {ms = mph * 1600 * secondsPerHour},
        set kilometersPerHour(kmph) {ms = kmph * 1000 * secondsPerHour},
        set metersPerSecond(ms) {ms = ms},
        /* Aliases */
        get F() {return API.fahrenheit},
        get C() {return API.celsius},
        get K() {return API.kelvin},
        set F(f) {API.fahrenheit = f},
        set C(c) {API.celsius = c },
        set K(k) {tempK = k },
        get mph() {return API.milesPerHour},
        get kmph() {return API.kilometersPerHour},
        get ms() {return ms},
        set mph(mph) {API.milesPerHour = mph},
        set kmph(kmph) {API.kilometersPerHour = kmph},
        set ms(ms) {ms = ms},
        /* Constants */
        SPEED_OF_LIGHT_MS : 299792458, // ms
        SPEED_OF_SOUND_MS : 343, // ms
        ABSOLUTE_ZERO_K : 0, // K
        MILES_PER_KILOMETER : 1 / 1.6,
        KILOMETERS_PER_MILE : 1 * 1.6,
    };

    // Create direct conversion from alias names using 2 for to. eg F2C
    [["F", "C", "K"], ["kmph", "mph", "ms"]].forEach(type => {
        for(const unitFrom of type) {  // unitFrom must be const or let
            for(const unitTo of type) { // unitTo must be const or let
                if (unitFrom !== unitTo) {
                    API[unitFrom + "2" + unitTo] = function(unit) {
                        API[unitFrom] = unit;
                        return API[unitTo];
                    }
                }
            }
        }
    });
    return Object.freeze(API); // freeze it so it can not be damaged
})();


MD5 shuffling with a defined pattern of numbers

Will this make storing passwords more secure?

Using MD5 for passwords is a bad idea, not because of its cryptographic weaknesses, but because it's fast. This means that an attacker can try billions of candidate passwords per second on a single GPU.

I wouldn't even bother creating my own secure hashing functions if I'm not an expert at it. There are libraries out from people who have already done all the hard work for you and have tested them thoroughly for security. PHPass is one of them.

Matter of fact, if you run PHP 5.5 or greater, you can use its native function: password_hash().


Splitting a div and positioning an inner div

There are 2 more ways to do this using css without the calculation. They are:

css positioning

Make the position of parent relative and child absolute. Now, using the slots value, left and right properties can be easily calculated for child div which will place it properly. The entire logic is reduces to the following without adding any additional elements:

const DivColoring = props => {
  let parentDivWidth = props.parentDivWidth;
  let totalSlots = props.totalSlots;
  let startSlot = props.startSlot;
  let endSlot = props.endSlot;
  return (

      <div
        style={{
          ...childDivStyle,
          position: "absolute",
          left: `${((startSlot - 1) * 100) / totalSlots}%`,
          right: `${((totalSlots - endSlot) * 100) / totalSlots}%`
        }}
      />

  );
};

The entire code can be found here: https://stackblitz.com/edit/react-qj3xsp

css flex

The DivColoring component can contain 3 child divs instead of one and you can use flex property to define relative width of the divs. The relative width can be easily calculated using totalSlots, startSlot and endSlot. The basic logic can be written as:

const DivColoring = props => {
  let totalSlots = props.totalSlots;
  let startSlot = props.startSlot;
  let endSlot = props.endSlot;
  let div3 = totalSlots - endSlot;
  let div2 = endSlot - startSlot + 1;
  let div1 = startSlot - 1;
  return (

  );
};

The complete code can be found here: https://stackblitz.com/edit/react-4mgl4c.
You also need to apply some extra css. Pros are calculation is reduced but con is that DOM will become heavy. Instead of 1, now there are 3 divs for each block.

The recommended approach will be using css positioning.

Hope it helps. Revert for any doubts/clarifications.


Remarks

Using an internal function, recursion, and a trampoline is a good way to structure recursive procedures on a lists.
The code fragment (+ accu (- (first lst) accu))) is the same as (first lst).
The name accu suggests an accumulator, however, the value it stores is the maximum, so max might be better.
Because of the letter l can be confused with 1, lst can be read as slang for 'first'. I prefer xs as the name for a list of x's. The nomenclature has become more common in Lisps over the past few decades due to the influence of other functional languages.
No matter how it is dressed up, there's a max procedure in the code somewhere. And it has to be written. It is better to be explicit about it than to try to hide max by embedding it in some other function.

Alternative

For procedures that try to find a property of a list, folding is often a good place to start. This code uses foldl. Usually I find foldl rather than foldr is what I want, for whatever that's worth.

#lang racket
(define (highest-number xs)
  (define (max x1 x2)
    (if (> x1 x2) x1 x2))
  (foldl max (first xs) (rest xs)))

Maybe it's worth pointing out, that the starting point for writing the highest-number was wishful thinking where I wished I had max. Then at the next lower level of abstraction down, I wrote it. Credit goes to Ableson and Sussman's SICP lectures.


Recursive binary search implementation in Python

Use an inner function

As you make recursive calls, some conditions are unnecessarily reevaluated, for example checking if the collection is iterable. This is kind of ugly, along with the "sentinel" you put in place for mid == 0.

In a more conventional implementation, you don't slice the input collection, but narrow down the search range, by adjusting start and end boundaries. You could create an inner function with signature:

def _binary_search(start, end):
    # ...

And call it with parameters 0 and len(collection). The function will call itself recursively, replacing the start our end parameters with the recalculated mid. There is no list slicing, no unnecessary conditions, and no odd check on mid == 0. The inner function is not visible outside, it's a hidden implementation detail.

Unit testing

It's generally best to have one assert per test case.
It's a bit more work, but it's clearer, and its worth it.
The practice also makes you think twice before adding redundant tests that are just noise, and think through more carefully what you're testing and why is it important.

Some interesting cases that would be nice to see cleanly separated:

should return correct result when match is the first element
should return correct result when match is the last element
should return correct result when match is the only element
should return correct result when match is exactly at mid point
should return correct result when list is empty

Magic string

The string "Not found" appears multiple times in the implementation. It would be better to put it in a constant and reuse.

Alternative return value for missing

A common practice for the return value of a failed binary search is to return -1 -insertAt where insertAt is the position where the element should be inserted to keep the list sorted.


This is good in general. The main point is that you confused a model and a mapper. Your mapper must be a model (or, to avoid a confusion, better to call it an entity) whereas your model is actually a mapper.

People often mistake  the term "model", so I had to write an article to explain it.

So

src
   Controllers
      PostController.php
      CommentController.php
   Entities
      Post.php
      Comment.php
   Mappers
      PostMapper.php
      CommentMapper.php
   Dependencies.php
   Middleware.php
   Routes.php
   Settings.php

where Post.php would be

namespace App\Entities;

class Post {

    protected $postId;
    protected $post;

    public function __construct(){}

    public function getPostId()
    {
        return $this->postId;
    }

    public function setPostId($postId)
    {
        $this->postId= $postId;
        return $this;
    }

    public function getPost()
    {
        return $this->post;
    }

    public function setPost($post)
    {
        $this->post= $post;
        return $this;
    }
}

and PostMapper would be

namespace App\Mappers;

class PostMapper {

   public function getPostById($id){

      $sql = "SELECT `post_id`, `post` FROM `posts` WHERE `post_id` = :id";
      $stmt = $this->db->prepare($sql);
      $stmt->execute(['id' => $id]);
      return $stmt->fetchObject('\App\Entity\Post');
   }
}

Please note that a lot of code has been removed from PostMapper class. First, a harmful try .. catch has been removed. A try .. catch that silently returns false is as bad as any other error suppression operator, and shouldn't be used such casually. As a programmer, you crave to know what the error was, so you'll be able to fix it. So always let errors go, unless you have a certain handling scenario. See more in my article, PHP error reporting basics.

Also, rather useless condition is removed too, as fetchObject() already returns false if a row not found, so we can return its result right away.

Also, consider making your PHP code style to conform with the standard