Names

I've renamed:

hmn_* -> human_*
cpt_* -> computer_*
g1 -> max_score
human_1 -> human_name
game_score -> print_scores
game_running -> check_scores
rps -> start
rps_running -> running
rdm -> random
GameOptions -> GAME_OPTIONS (we usually use pascal case for a class in Python, and capitalization for variable constants)

Reason for all this renaming was to make it clear to an outside reader what all the variables mean without having to look past their declaration. If you ever revisit this code, you don't want to have to dive deep into it every time.

As for renaming the functions, we are now able to tell what they do without diving into their bodies. For example, print_scores clearly tells us that it prints the status of the scores.

check_scores

Currently you have three different outer ifs corresponding to max_score equaling 3, 5 or 7. In each of these ifs, you check if human_score or computer_score are greater than half of the total possible score. This entire function can be simplified by making this comparison work for any value of max_score:

def check_scores():
    global running, max_score

    if human_score > max_score / 2:
        running = False
        print(f"{human_1} Wins!")

    elif computer_score > max_score / 2:
        running = False
        print("Computer Wins!")

Since check_scores can only be possibly called if running == True, we don't need to reassign it to True in the else, so we can get rid of that.

start

You can make the input call for human_temp a function such that the prompt isn't specified twice in the code:

def get_human_temp():
    return input("""Please select from the following:
                        1 - Rock
                        2 - Paper
                        3 - Scissors
        \n""")

This changes the human_temp while loop to:

human_temp = get_human_temp()

while human_temp not in ["1", "2", "3"]:
    print("That was not a acceptable input!")
    human_temp = get_human_temp()

Ah, this is a do-while loop! If you're on Python 3.8, you can use the walrus operator:

while (human_temp := get_human_temp()) not in ["1", "2", "3"]:
    print("That was not a acceptable input!")

For your entire chain of elifs checking whether the human won, a more concise way to do is it to check if human_final - 1 == computer. This works for any human_final except 0. To make it work for 0, we would need to check human_final + 2 == computer. We can combine these two checks concisely as follows:

if human_final == computer:
    print('Tie Game!')

elif computer in (human_final - 1, human_final + 2):
    print('You Win')
    human_score += 1

else:
    print('You Lose')
    computer_score += 1

I believe that elif human_final == 0 and computer == 3 was a subtle bug in your original code, computer should have been checked against 2.

You can think of the elif as checking whether human_final is one ahead of computer in GAME_OPTIONS, while accounting for wrapping around GAME_OPTIONS.

Global State

There's a lot of global state in your program (show by all the global calls). We can use a class to store the state for each specific game. This state includes max_score (describes when a particular game ends), human_name (describes who is playing the game) and human_score / computer_score / running (describes current state of the game). Let's call this class Game, with an initialization method like this:

def __init__(self, max_score, human_name):
    self.max_score = max_score
    self.human_name = human_name

    self.human_score = 0
    self.computer_score = 0
    self.running = False

We would then put all of your methods using global state in Game, with self prepended to all the variables we have here in our __init__ method.

As for the code that is run before we even start the game (the code responsible for fetching human_name and max_score), we can put this in an if __name__ == "__main__" block. This makes it so we can use Game from another module without having all the input-specific code running.

Here's the final code, with some very slight consistency changes (such as standardizing the type of quotation mark you use, and getting rid of unnecessary fs at the beginning of unformatted strings):

# Rock Paper Scissors

import random

def get_human_temp():
    return input("""Please select from the following:
                        1 - Rock
                        2 - Paper
                        3 - Scissors
        \n""")

GAME_OPTIONS = ["Rock", "Paper", "Scissors"]

class Game:
    def __init__(self, max_score, human_name):
        self.max_score = max_score
        self.human_name = human_name

        self.human_score = 0
        self.computer_score = 0
        self.running = False

    def print_scores(self):
        print(f"\n The current score is {self.human_score} for you and {self.computer_score} for the computer \n")

    def check_scores(self):
        if self.human_score > self.max_score / 2:
            self.running = False
            print(f"{self.human_name} Wins!")

        elif self.computer_score > self.max_score / 2:
            self.running = False
            print("Computer Wins!")

    def start(self):
        self.running = True

        while self.running:
            while (human_temp := get_human_temp()) not in ["1", "2", "3"]:
                print("That was not a acceptable input!")

            human_final = int(human_temp) - 1
            print(f"You Chose: {GAME_OPTIONS[human_final]}")

            computer = random.randint(0, 2)
            print(f"Computer Chose: {GAME_OPTIONS[computer]}\n")

            if human_final == computer:
                print("Tie Game!")

            elif computer in (human_final - 1, human_final + 2):
                print("You Win")
                self.human_score += 1

            else:
                print("You Lose")
                self.computer_score += 1

            self.print_scores()
            self.check_scores()

if __name__ == "__main__":
    print("Welcome to Rock/Paper/Scissors!!! \n")

    max_score = input("Would you like to play a best of 3, 5 or 7: ")

    while max_score not in ["3", "5", "7"]:
        max_score = input("Incorrect Response, please select 3, 5, or 7: ")

    max_score = int(max_score)
    human_name = input("Please enter your name: ")

    game = Game(max_score, human_name)
    game.start()


Guess the number game using jupyter notebook

Pretty clean looking code, but let's look at a few ways it could be better or more pythonic:

Use elif statements:

if personInput == randnumb:
    # ...
elif personInput > randnumb:  # You already know they're != at this point
    # ...
elif ...

Use snake case for your variable names. E.g., use person_input instead of personInput (which is camel case), and rand_num instead of randnumb. In that second case, it's also more common to shorten "number" to "num" instead of "numb".
Use format strings instead of print's argument concatenation, e.g.:

print("Guess lower ({} guesses left)".format(max_guesses - guesses))

Check for and handle errors:

try:
    person_input = int(input("What is your guess? "))
except ValueError:
    print("Not sure what you meant by that, please input an integer")
    continue

I prefer to be more safe than sorry when handling my own incrementor, such as guesses, just in case I do something funky that lets it skip over max_guesses:

# Since you "break" on correct answer, we don't need to check that again
if guesses >= max_guesses:
    # ...

EDIT:

One more thing. In Python, to write a script (rather than a module), you should check if __name__ == '__main__': as follows:

from random import randint

def main():
    randnumb = randint(1,100)
    guesses = 0
    maxGuesses = 5

    while guesses < maxGuesses:
        # ...

if __name__ == '__main__':
    main()

This allows for safe code re-use, and makes sure that the code doesn't get run if this file gets imported from another file. It's not technically necessary for a one-file script like you're writing here, but it's a good practice to get into anyway.


Unlocking spreadsheet files quickly - follow-up

Good job listening to feedback. Keep at it.

Use two spaces to indent.
Name your methods verbs, not nouns (e.g., unlock_spreadsheet).
Split on comma and then use strip to remove leading and trailing whitespace.
Rather than calling the method recursively, you may want to put a loop do around the method and then break when you're done.
If you run Rubocop, you'll see that your method is too long. Instead, you can move each set of actions inside of if and else blocks into their own methods.


Limit characters by line without splitting word

String s = "Even aside from the rain and wind it hadn't been a happy practice session. Fred and George, who had been spying on the Slytherin team, had seen for themselves the speed of those new Nimbus Two Thousand and Ones. They reported that the Slytherin team was no more than seven greenish blurs, shooting through the air like missiles.";

s is not a good variable name. My rule is that you're only allowed to use single-character variable names when dealing with dimensions (yes, that also disallows i/j/k for loops, too).

public static void wordWrapper(String s, int limit) {

The naming is off, this is not a "word wrapper" it's a function that does wrap a string by words, so more like wrap or wrapText.

        // Time complexity: O(n) - n size of s
        // Space complexity: O(n) - n number of words in s

I'm not sure that is correct. I could be very well mistaken here because I rarely need to think about complexity limitations at all, but I think it is closer to "O(n + m)", with "n" being the number of characters (the split), and "m" being the number of words (your loop). Space should be "O(n*2)", with "n" being the number of characters in the string, as you need to keep each character twice in memory, once in the original, and once in the word string.
However, most JVMs are implementing "substrings", which means that the array of codepoints is only held one in memory, and if you do a substring, you will receive a new String with the same array but different start/end index.

        int charCount = 0;
        int i = 0;
        String[] words = s.split(" ");
        while (i < words.length) {
            if (charCount + words[i].length() > limit) {
                System.out.println();
                charCount = 0;
            }
            charCount += words[i].length();
            System.out.print(words[i] + " ");
            i++;
        }

This code could be simplified to a for-each loop:
int currentLineLength = 0;

for (String word : text.split(" ")) {
    if ((currentLineLength + word.length()) > maxCharactersPerLine) {
        System.out.println();
        currentLineLength = 0;
    }

    System.out.print(word + " ");
    currentLineLength = currentLineLength + word.length();
}

Note that your implementation, and this revised one, has three problems which should be dealt with at some point:

The spaces are not taken into account for the maximum line length.
It prints an extra space at the end of each line.
How a word should be treated that is longer than the maximum line length.

...and just use pointers instead of split(),...

There is no such thing as "a pointer for strings" in Java. Though, you most likely mean, to iterate over the String and keep track of the index, but "pointer" is a heavily prejudiced word, and I would stay clear of it and instead use "index".

int lastWhitespaceIdx = -1;

Don't shorten names just because you can, it does make the code harder to read in the end of the day.

int lineCount = 0;

The name of this variable is incorrect, it does not count lines, it counts characters on the current line, it should be named accordingly.

while (i < s.length()) {

Not sure why you use a while when a for would be perfect for what you're doing here.

System.out.print(s.charAt(i));

Printing single characters at a time can be quite wasteful, depends on whether the stream supports some sort of buffer or not.

You could use String.indexOf(String) and String.index(String, int) to iterate over the string and simplify your logic. Then use substring to extract the part of the String between the spaces and print that, or print that part character by character.


Testing

I find it weird that alarm_clock is passed to test_fun as a parameter, but the cases are hard-coded within test_fun.  They should either both be hard-coded, or both passed as parameters.

Stylistically, cases would be better as a list of tuples.  Tuples have a connotation of being non-homogeneous collections of uniform length (like a single row in a database table).  Lists have a connotation of being homogeneous collections of undetermined length.

The way you split case[0], case[1], and case[-1] is awkward.  I would put the singular expected result first, then use tuple unpacking.

For clarity, you should print repr(param) instead of param.

Here's how I would write it:

def test_fun(fun, cases):
    print('{:^30}     {:^11}'.format('Expected', 'Run'))
    for expected, *params in cases:
        funstr = '{}({})'.format(fun.__name__, ', '.join(repr(p) for p in params))
        result = fun(*params)
        success = result == expected
        print('{:21} -> {:5} ==> {:5}  {}'.format(funstr, expected, result, success))

test_fun(alarm_clock, [
  ('7:00', 1, False),
  ('7:00', 5, False),
  ('10:00', 0, False),
  …
])

Better yet, consider dropping test_fun altogether and using a doctest instead.

Implementation

For a simple problem like this, there are many ways to write it, and choosing the "best" one is a matter of taste.  Personally, I would prefer to keep it simple so that you don't have to jump back and forth among three functions to understand the code.

def alarm_clock(day, vacation):
    """
    Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a
    boolean indicating if we are on vacation, return a string of the form
    "7:00" indicating when the alarm clock should ring. Weekdays, the alarm
    should be "7:00" and on the weekend it should be "10:00". Unless we are on
    vacation -- then on weekdays it should be "10:00" and weekends it should
    be "off".

    >>> alarm_clock(1, False)
    '7:00'
    >>> alarm_clock(5, False)
    '7:00'
    >>> alarm_clock(0, False)
    '10:00'
    """
    weekday = 1 <= day <= 5
    return ( '7:00' if weekday and not vacation else
            '10:00' if weekday ==      vacation else
            'off')

The CodingBat editor seems to encourage two spaces per level of indentation.  PEP 8, the official Python style guide, says that you should use four spaces.


Python nested json parsing and splitting the values

As long as there's nothing special about the nth URL, you can just store the URLs in one list:

urls = []

for result_string in result["Result"]:
    url = result_string.split("::")[2]
    urls.append(url)

If there is something unique information you want to capture about the nth URL, you could store the URLs in a dictionary to map the URL to its type.

def url_type(n):
    """returns the type of url given its index n in the response"""

    #example
    if n == 1:
        return 'url-type-a'

    return 'url-type-b'

urls = {
    "url-type-a": [],
    "url-type-b": []
}

for i, result_string in enumerate(result["Result"]):

    url = result_string.split("::")[2]
    urls[url_type(i)].append(url)


Recursive flatten with lazy evaluation iterator

Not my idea, but I think this is better:

import collections

def flatten(lst):
    for item in lst:
        if isinstance(item, collections.Iterable) and not isinstance(item, basestring):
            for sublst in flatten(item):
                yield sublst
        else:
            yield item


Determining whether a list of pathways and its genes are all included in another list

If you were to add a cat("hello") at the top of your all_in function, you would find that your function is called 25 times, once for each combination (pair) of pathways. So yes, despite having used Vectorized, it is still essentially a big old loop you have under the hood... Here is how I would write a vectorized function so the heavy-lifting function (%in%, or in my case, match) is only called once or twice:

all_in_outer <- function(list_x, list_y) {
  uniq_x <- unique(unlist(list_x, use.names = FALSE))
  len_x <- vapply(list_x, length, integer(1L))
  as_mat <- function(list_a, ids = uniq_x) {
    vec <- unlist(list_a, use.names = FALSE)
    len <- vapply(list_a, length, integer(1L))
    idx <- rep(seq_along(list_a), len)
    mat <- matrix(0L, nrow = length(list_a), ncol = length(ids),
                  dimnames = list(names(list_a), ids))
    mat[cbind(idx, match(vec, ids))] <- 1L
    mat
  }
  (as_mat(list_x) %*% t(as_mat(list_y)) == len_x) * 1
}

all_in_outer(paths2genes, paths2genes)
#         1430728 156580 156582 194840 211859
# 1430728       1      1      1      0      1
# 156580        0      1      0      0      0
# 156582        1      1      1      0      1
# 194840        0      0      0      1      0
# 211859        1      1      1      0      1

Some explanation: After we have found the list of unique genes across all pathways in the first argument (10,  9, 3, 2), we turn both arguments into a matrix A where A[i,j] = 1 if the pathway i contains the gene j, or 0 otherwise. For paths2genes, this matrix is as_mat(paths2genes):

#         10 9 3 2
# 1430728  1 1 0 0
# 156580   1 1 1 0
# 156582   1 1 0 0
# 194840   0 0 1 1
# 211859   1 1 0 0

Then, using matrix multiplication between two such matrices, you get the number of gene matches for each possible combination of pathways. You then just have to compare that number of matches with the length of the pathway: (as_mat(list_x) %*% t(as_mat(list_y)) == len_x).

In the conversion of each input into a matrix of zero and ones, see this particular line of code: mat[cbind(idx, match(vec, ids))] <- 1L. This is what fills the ones in the matrix. It is completely vectorized, via a single call to match.


Using a thread for a SplashScreen is fine, however a much cleaner solution would to use a Handler as below...

public class SplashActivity extends BaseActivity {

    private final static int SPLASH_TIME_OUT = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        }, SPLASH_TIME_OUT);
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}

Your SPLASH_TIME_OUT constant should be declared static.


Let's look at some of the code:
Random random = new Random((int)DateTime.Now.Ticks);

You don't need to create a seed for the Random constructor from the clock, the parameterless constructor does that:
Random random = new Random();

List<string> characters = new List<string>() { };

You don't need the initialiser brackets when you don't put any items in the list at that point:
List<string> characters = new List<string>();

result += characters[random.Next(0, characters.Count)];

Using += to concatenate strings is bad practice. Strings are not appended at the end, as strings are immutable. Code like x += y; actually end up as x = String.Concat(x, y). You should rather use a StringBuilder to build the string.

Thread.Sleep(1);

Why on earth are you sleeping in the middle of the loop?

Instead of creating a list of strings, just use a string literal to pick characters from:
public static string GenerateCoupon(int length) {
  Random random = new Random();
  string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  StringBuilder result = new StringBuilder(length);
  for (int i = 0; i < length; i++) {
    result.Append(characters[random.Next(characters.Length)]);
  }
  return result.ToString();
}

Consider if all those characters should be included, or wheter you should omit similar looking characters like o, O and 0. Having the characters in a string literal makes it easy to do that.
Edit:
If you are going to call the method more than once, you should send in the random generator as a parameter:
public static string GenerateCoupon(int length, Random random) {
  string characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  StringBuilder result = new StringBuilder(length);
  for (int i = 0; i < length; i++) {
    result.Append(characters[random.Next(characters.Length)]);
  }
  return result.ToString();
}

Usage:
Random rnd = new Random();
string[] coupon = new string[10];
for (int i = 0; i < coupon.Length; i++) {
  coupon[i] = GenerateCoupon(10, rnd);
}
Console.WriteLine(String.Join(Environment.NewLine,coupon));

Example output:
LHUSer9dPZ
btK0S01yLb
hruw4IXINJ
hwMdRDRujt
cr4TDezvcZ
b8tVETNXNL
JrG6sfXgZF
Y7FRypnRiQ
JbfnhY3qOx
quWNakbybY


All possible values that will match a regular expression

A major inefficiency in your solution is that you try every fill_in character as a replacement for any character class in the pattern. Instead, you could use the character class to select matching characters from fill_in and only loop over those.

>>> pattern = 'K0[2468]'
>>> re.findall(expression, pattern)
['[2468]']
>>> re.findall('[2468]', fill_in)
['2', '4', '6', '8']

For a more complete existing solution, you may want to look into these:

Regular expression parsing in Python
invRegex.py in Pyparsing examples


OpenGL forward-compatible context creation on Windows

This looks right to me. I am a bit tired right now and usually use GLFW.

You might be interested in this page on the OpenGL wiki describing setting up the context after 3.1 which is essentially the same work.


Javascript check if server time is greater than or less than 9am EST

Your code has a bug: d.getHours() will return a plain number. Calling toLocaleString on that number calls Number.prototype.toLocaleString, which:

returns a string with a language-sensitive representation of this number.

It does not do anything with timezones; the second parameter does not recognize a timeZone property. For example, where I am now, .getHours() returns 9, and (9).toLocaleString('en-US', { timeZone: 'America/New_York' }) returns "9".
On your server, to retrieve the hours in a particular timezone, one method would be to call toLocaleString on the date object itself with the appropriate timezone, then extract the number of hours from that string:

const timeString = new Date().toLocaleString('en-US', { timeZone: 'America/New_York' });
const [, hours, ampm] = timeString.match(/ (\d+).* ([AP]M)/);
console.log('In NY, it is:', hours, ampm);

Other issues:

Since it's 2020, best to prefer at least 2015+ syntax, which should not be an issue since the code is running on the server. (Among other things, being able to use const is wonderful)
You initialize f to the empty string, but then you reassign it immediately; the empty string is not used, so there's no point to assigning it.
Or, even better: since you want to conditionally assign a value to f depending on the number of hours, it would be more appropriate (and shorter) to use the conditional operator:

const f = Number(hours) < 9 && ampm === 'AM'
  ? 'shipping available'
  : 'shipping unavailable';


Converting an integer to a 3 character String (base62)

Your problem definition is .... odd. your code, will, for the input value 1 generate the output 000. Is that what you really want? Why do you need to 1-index the value set instead of 0-index it?

Further, your code caches all values up-to-and-including the input value in a HashMap. This can become quite large.... for the full dataset you're looking at about a quarter-million values where each is about 128 bytes of memory (a String, an Integer, and a Map.Entry plus some other overheads), or about 70 megabytes of data.

Your DICTIONARY should be an array of chars, not an array of String.

The maxNumber should be a static constant too.

Finally, you return a null value for an invalid input. That's very unconventional, you should throw an IllegalArgumentException instead.

As mentioned in a comment, you can "easily" solve your problem with a few "simple" operations.

private static final char[] DIGITS = ("0123456789"
       + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
       + "abcdefghijklmnopqrstuvwxyz").toCharArray();
private static final int BASE = DIGITS.length;
private static final int MAX_NUMBER = BASE * BASE * BASE;

public static String generateCode(int num) {
    if (num < 1 || num > MAX_NUMBER) {
        throw new IllegalArgumentException("Illegal input value: " + num);
    }

    int value = num - 1;

    char ac = DIGITS[((value / BASE) / BASE) % BASE];
    char bc = DIGITS[(value / BASE) % BASE];
    char cc = DIGITS[value % BASE];
    return new String(new char[]{ac, bc, cc});
}

Note that I compute each digit separately (in to ac, bc, and cc) and then return the combination as a string.

Further, when running the code, I discovered that you are off on your zzz assertion .... the max value you propose for zzz is wrong, what you have is yyy. - I discovered I had a text transpose of zy instead of yz in my constant.

See the code running on ideone: https://ideone.com/EZqXlJ

For the inputs supplied in the tests I get the values:

Value 0 Error Illegal input value: 0
Value 1: 000
Value 2: 001
Value 62: 00z
Value 63: 010
Value 1000: 0G7
Value 238328: zzz
Value 238329 Error Illegal input value: 238329


Simple unit test in C of input using freopen

The thing that feels unusual is the use of freopen to send the test data to stdin.
Are there better ways to implement this kind of test?

C has a freopen() footnote

The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned.

This looks like a good direct way to test code, although I'd expect stdout, strderr being re-opened to capture output.

Are there better ways

Enable all compiler warnings - save time.
The mismatch of specifier and type implies code is not efficiently using the 1st round of code improvement:  Compiler warnings.
// printf("ok: tmpnum == %ld\n", tmpnum);
printf("ok: tmpnum == %zu\n", tmpnum);

Code is strange in that it passes in tmpnum for no good reason.
//static size_t get_num(size_t tmpnum) {
//  if (scanf("%zu", &tmpnum) != 1) {

static size_t get_num(void) {
  size_t tmpnum;
  if (scanf("%zu", &tmpnum) != 1) {


Welcome to code review and thanks for sharing your code.

When writing UnitTests keep in mind that they are documentation.
Test code has less restrictions for identifier names.
This means that method names are usually longer and you should not "shorten" your unit test methods.

The test name should describe the expected behavior in detail

@Test
public void getAllVideos_returnsCompleteListFromRepository() throws Exception{
    // ...

A unit test always has three parts: arrange, act and assert.
You should always have this three parts visible in your test methods.

In your example you do the act part implicitly in the assert line.
This prevents you from introducing variable that could give useful information about the result:

@Test
public void getAllVideos_returnsCompleteListFromRepository()
    // arrange
    List<Video> allVideosInRepository = new ArrayList<>();
    when(videoRepository.findAll()).thenReturn(new ArrayList<Video>());
    // act
    List<> allVideosFromRepository = videoService.getAllVideos();
    // assert
    assertEquals(allVideosInRepository, allVideosFromRepository, "tested");
}

For the same reason the String parameter of the assert* method should always be a useful hint in case the test fails because it is part of the error message:

    assertEquals(allVideosInRepository,
                 allVideosFromRepository,
                 "is same object");

  I feel like i just compare the same mock values ArrayList of Video and what's the point of doing this or i just do it wrong way.

This is not a problem of your unit tests but of your current design.

For the time being your VideoService class is nothing more than a facade to a Collection, there is no business behavior (yet) to be tested.


Finding the sum closest to a target number

Style

You code is not properly indented which makes it quite hard to understand.

Calling your function argument input conveys pretty much as much information as calling it argument. I guess weights or weightList would be more meaningful.

It would probably make sense for target to be a parameter of the walrusWeight function.

Bug

Calling your function with var weights = [4, 900, 500, 498, 4, 1000]; and var target = 1000; gives 1002 as a result.

Tests

Before you try to fix anything, I suggest you write a test suite with your function being called with various inputs and the result you are expecting. This will make the developement of a new solution much easier.

Algorithm

Because your current solution is wrong, you'll need to think about a new algorithm.

A simple, yet, efficient enough with small-ish inputs it to iterate over the weight and keep tracks of the various possible sums :

With [4, 900, 500, 498, 4, 1000], you'd get something like :

iteration 0 : possible sums = [0]
iteration 1 : possible sums = [0, 4]
iteration 2 : possible sums = [0, 4, 900, 904]
iteration 3 : possible sums = [0, 4, 900, 904, 500, 504, 1300, 1304]
iteration 4 : possible sums = etc
iteration 5 : possible sums = etc

When you'll have all candidates, it's easy to pick the best.

Then, you'll find various optimisations (get rid of values that won't need to solution early on) but it's a good idea to make it right and then make it fast.

Code example

I've tried to implement the suggestions above :

var weights = [2000, 1003, 4, 900, 500, 498, 3, 8];
var target = 1000;

function walrusWeight(weights) {
    var optimum = 0;
    var optimum_distance = target;
    var sums = [0];

    for(var i=0; i < weights.length; i++) {
        var weight = weights[i];
        var newSums = [];
        for(var j=0; j < sums.length; j++) {
            var sum = sums[j];
            if (true) // An optimisation could be added here
            {
                newSums.push(sum)
                var newSum = sum + weight;
                var distance = Math.abs(target - newSum)
                if (newSum <= target)
                {
                    newSums.push(newSum)
                    if (distance < optimum_distance) {
                        optimum = newSum;
                        optimum_distance = distance;
                    }
                }
                else if (distance < optimum_distance || (distance == optimum_distance && newSum > optimum))
                {
                    optimum = newSum;
                    optimum_distance = distance;
                    newSums.push(newSum)
                }
            }
        }
        sums = newSums;
        print(sums)
    }
    return optimum;
}

print(walrusWeight(weights, target));


Type Hints

From these lines:

from typing import List, TypeVar

T = TypeVar('T')

it looks like you intend to add type-hints for a type T to you code.  But nowhere are you using T as a type hint.  You probably wanted to actually use T, such as like:

def __init__(self, node_value: T) -> None

Either that, or delete the typing code.

Exception Handling

You have:

class ExceptionHandling(Exception):
    pass

but nowhere are you actually executing raise ExceptionHandling("Your error message").  Moreover, nowhere do I actually see a need to raise an exception; you aren't doing anything that could fail.  Until you have a need for raising your own custom exception, you could remove this code.

class Node(object):

Since you are using f-strings, it is clear, you are using Python 3.  In Python 3+, you don't need to inherit from object; it is automatically implied.

Names & Types

def insert(self, new_node: int) -> None:

Is new_node a Node or an int?  The variable name suggests it would be a Node, but it is typed as an int.  When you use it, you are passing in an int.  Maybe new_value would be clearer?

def _insert(self, parent: int, new_node: int) -> int:

Now we're definitely confused.  Is parent an int?  Does this function return an int?  Both seem to be a definite "no".  Those types should be Node.  And again, new_node should be renamed, because it isn't a Node.

Method naming (and docstrings)

What does inorder do?  I'd expect it to return the contents of the tree "in order".  But the type-hint says it returns None, so that is not correct.  Let's consult help:

>>> help(BinarySearchTree.inorder)
Help on function inorder in module __main__:

inorder(self) -> None
    Calls the _inorder traversing method;

>>>

Well, that's entirely unhelpful.  It calls a private _inorder traversing method.  Ok, but what does it do???

Name functions based on what they do.  Your inorder function prints the tree in order, so name it with print in its name, such as print_inorder.

Also, write docstrings to tell a caller what the function does.  Use a high-level description.  Include any requirements, preconditions and/or postconditions.  Do not include implementation details.  The caller cares only about what it does and how to use the function properly; they only care the function works, not how it works.

def print_inorder(self) -> None:
    """
    Print the tree in ascending order, one element per line, to sys.stdout
    """
    self._inorder(self.root)

Finally, your class is named BinarySearchTree, yet it provides no methods for searching.  Hmm.

Pointless f-string

The statement:

print(f'{parent.node_value}')

is a complicated way of writing:

print(parent.node_value)

Algorithm

Your insert / _insert functions are overly complicated.  There is no need to use recursion.  Moreover, returning the parent from _insert is mostly useless, because the caller is passing parent to the function; it only matters when the caller passes None in as the parent.

A non-recursive approach:

def insert(self, new_value: int) -> None:

    new_node = Node(new_value)

    if self.root:
        parent = self.root
        while True:
            if new_value < parent.node_value:
                if parent.left_child:
                    parent = parent.left_child
                else:
                    parent.left_child = new_node
                    break
            else:
                if parent.right_child:
                    parent = parent.right_child
                else:
                    parent.right_child = new_node
                    break
    else:
        self.root = new_node

Possible Improvements

Encapsulation

Node is an internal detail of the BinarySearchTree.  You could make it an internal class:

class BinarySearchTree:

    class Node:
        def __init__(self, node_value:T ) -> None:
            self.node_value = node_value
            self.right_child = None
            self.left_child = None

    def __init__(self) -> None
        self.root = None

    ...

       parent = BinarySearchTree.Node(new_node)

    ...

Iterator

Instead of the method inorder printing the contents of the tree, perhaps it could return an iterator which would traverse the tree returning elements one at a time.  The caller could then print them, or perform whatever operation they desired.

for value in tree.inorder():
    print(value)

Instead of naming this iterator creating function inorder, it could be named __iter__, in which case, the caller would just need to write:

for value in tree:
    print(value)

You'd create this iterator in one of two ways.  The "hard way", returning a new iterator object, with a __next__ method.  Or the "easy way" using a generator function, using yield and yield from statements.


Is this Scala/Akka idiomatic and correct for Akka 2.1?

I'm not an akka expert but I did used akka in a project so these are just some of my observations:

result is blocking.

val result = Await.result(master ? Run, timeout.duration)

On case the master takes longer due to load or whatever, the pending result will
exceed the timeout. Try async ask directly.

val result ask(actor, msg).mapTo[String]

In order to remain async you may carry on with an onComplete as
Future callback:

result onComplete {
    case Success(result) => doSomethingOnSuccess(result)
    case Failure(failure) => doSomethingOnFailure(failure)
}

In this case no operation ever blocks the running thread. Read the Akka docs for more details

  And is there a better approach to waiting for a result from an
  optionally distributed parallel reduction of a collection? In other
  words, is this an Akka equivalent of
  collection.par.map(work).par.reduce(result) or is there a better way?

Operating on distributed data-sets is much better done on an in-memory data processing engine. Using the distributed word count as example, in Spark you do:

   file.flatMap(line => line.split(" "))
    .map(word => (word, 1))
    .reduceByKey(_ + _)

Actors are made for message processing such as Twitter or WhatsApp but for  computing tasks that must be fast, you use either MapReduce (Hadoop) for offline crunching of Spark/Storm for real-time processing.  Hope that answers your question.


A slightly more efficient dynamic programming approach means you only need O(n) space:

def partitions(n):
    parts = [1]+[0]*n
    for t in range(1, n+1):
        for i, x in enumerate(range(t, n+1)):
            parts[x] += parts[i]
    return parts[n]

In []:
partitions(50)

Out[]:
204226

Note: this is trivial to extend to the coin change problem (the number of ways you can make change with certain coins: Ways to make change for a dollar), by restricted the values in the outer loop, e.g.:

def coin_change(n, coins):
    parts = [1]+[0]*n
    for c in coins:
        for i, x in enumerate(range(c, n+1)):
            parts[x] += parts[i]
    return parts[n]

In []:
coin_change(100, {1, 5, 10, 25, 50, 100})

Out[]:
293


Solution to Project Euler problem 5 (LCM of 1 to 20)

Let's start with the loop inside findPrimeFactors. You have the right idea, but it's complicated because you're flattening two loops into one: looping over the primes, and looping over the factors for your target number.

So let's do those one at a time. First, let's create a function that finds the next prime factor:

let rec findNextFactor candidates n =
    match candidates with
    | x::xs when n%x=0I -> x
    | x::xs -> findNextFactor xs n
    | _ -> failwith "No factor found"

The first line matches when a factor is found, the second when no factor is found, and the third when the collection is empty. Note how matching on the collection makes it very easy to recursively loop through it by matching against x:xs. This helps avoid your issue of looping by index.

Now that we know how to find the next prime factor, it's easy to find all of them:

let rec loop acc n =
    match findNextFactor primes n with
    | n -> n:acc
    | p -> findPrimeFactors p:acc n/p

We're not passing primes in here as we're not iterating it here. The primes referred to is the outer one which always contains all the primes up to 20. By splitting out the loop, we only need to deal with these two simple cases.

Just glue those together and you get your findPrimeFactors implementation.

For findPrimeFactorsPowers, you're again increasing the complexity by completely changing your data type, from a list of factors, to a map of factors to the count of those factors. This isn't actually that hard. For a single number n it might look like:

let findPrimeFactorsPowers n =
    findPrimeFactors n
    |> Seq.groupBy i -> i
    |> Seq.map i -> (i.Key, i.Count)

I'm honestly not quite sure what your version is doing, so I can't compare very closely.

But actually, there's something even simpler we can do. Really all we want to do is merge two lists in a special way: for each value, the number of times that value appears in the merged list should equal the maximum number of times it appears in each individual list.

By taking advantage of the fact that our lists are sorted, we can do that very easily:

let rec merge a b acc =
match a,b with
| x::xs, y::ys when x = y -> merge xs ys (x::acc)
| x::xs, y::ys when x < y -> merge xs b (x::acc)
| x::xs, y::ys -> merge a ys (y::acc)
| _, [] -> List.append (List.rev acc) a
| [], _ -> List.append (List.rev acc) b

We loop over the lists, take the head of each one. If they're equal, remove both heads and add it to the accumulator, otherwise take just the lowest and add that. Finally the last lines let us terminate once a list is empty.

This is the last piece we need. Now we just need to get the prime factor lists for each number under 20, and merge each one in turn into an empty list. Finally find the product of the numbers in the resultant list, and you have your answer.

For more general comments, there isn't much I can find to fault. There's a couple of times you declare a variable, then only use it once in the next line. Not doing that means you can get rid of the cumbersome name smallestNumberDivisableByAllNumbersBelown.

Also, you should probably trim out some unnecessary comments. If you're just learning F#, the idea that the last expression of a function is what gets returned might cause enough cognitive friction for you that you want to leave yourself a comment, but those shouldn't be in part of a finished piece of code.

Generally, though, stylistically the code is good, including both naming and organization.


Form with a country list statically or dynamically generated

This depends on your plans for maintaining the software. If it will not be maintained, it does not matter much. If it will be maintained irregularly and manually, not a big issue unless the country code list is used elsewhere, too, e.g. in a database where you store some submitted information or that contains some data per country. But other things being equal, it is better to generate a large dropdown from a table rather than hard-code it. And if the software will be regularly maintained by checking, among other things, the country list and country names against a reliable source, then a table is surely better. It is easier to generate just a table from the reference data.

Note that reliable and useful data can be difficult to find and the set of countries will change (and is subject to political debate). In your example, the second entry does not refer to a country but to an autonomous area. There are definitions of “country codes” that include many non-country entries for various purposes.


It appears that this Product entity is meant to be a POJO.  POJOs should be responsible only for holding the relevant data in memory to be accessed by, and possibly manipulated by, someone else.

The second you put in logic that is not directly related to the POJO, such as persistence, the flexibility of your application drops like a stone.  You will be unable to use this POJO in other contexts where the repository will not be relevant, or worse, when this comes from a different repository altogether (it does happen!).


Improving Twitter JSON parser for big data set

Just a few quick considerations:

You have import os twice
You are not using matplotlib and numpy, so the imports can go
The line tweet = tweets[0] is useless
You're not closing the files you open, you should use the with keyword

Two optimizations:

I'd remove the print(file). This is probably single best optimization you can do
You're already looping once, why do you loop another five times?

What about something like this (not tested!):

from collections import defaultdict

elements_keys = ['ids', 'text', 'lang', 'geo', 'place']
elements = defaultdict(list)

for dirs, subdirs, files in os.walk('/Users/mymac/Documents/Dir'):
    for file in files:
        if file.endswith('.json'):
            with open(file, 'r') as input_file:
                for line in input_file:
                    try:
                        tweet = json.loads(line)
                        for key in elements_keys:
                            elements[key].append(tweet[key])
                    except:
                        continue

df=pd.DataFrame({'Ids': pd.Index(elements['id']),
                 'Text': pd.Index(elements['text']),
                 'Lang': pd.Index(elements['lang']),
                 'Geo': pd.Index(elements['geo']),
                 'Place': pd.Index(elements['place'])})
df


A function to find temperatures closest to zero

Bugs

The loop

for (let i = 0; i < tempArray.length - 1 ; i++) {

omits the last array element, it should be

for (let i = 0; i < tempArray.length ; i++) {

If all array elements have the same sign then
either plusTemps or minusTemps is an empty array, and accessing
its first element in

if (plusTemps[0] === Math.abs(minusTemps[0])) {

is undefined. Those cases must be treated separately in your approach.
If the array is not empty, but all array elements are zero then
both plusTemps are minusTemps are empty, again making the result
undefined. What would be the expected result for this case?
Returning zero looks like a sensible choice to me.

Simplifications

The first and second check in

if (plusTemps[0] === Math.abs(minusTemps[0])) {
    return(plusTemps[0])
}

if (plusTemps[0] < Math.abs(minusTemps[0])) {
    return(plusTemps[0])
}

if (plusTemps[0] > Math.abs(minusTemps[0])) {
    return(minusTemps[0])
}

can be combined to

if (plusTemps[0] <= Math.abs(minusTemps[0])) {
    return(plusTemps[0])
}

if (plusTemps[0] > Math.abs(minusTemps[0])) {
    return(minusTemps[0])
}

and the second if is better done with an else:

if (plusTemps[0] <= Math.abs(minusTemps[0])) {
    return(plusTemps[0])
} else {
    return(minusTemps[0])
}

This saves a comparison and makes it clear that a value is returned
in any case. And since we know that minusTemps[0] is negative we need
not call Math.abs:

if (plusTemps[0] <= -minusTemps[0]) {
    return(plusTemps[0])
} else {
    return(minusTemps[0])
}

A better approach

As already mentioned in the comments and in the other answers, the solution
can be determined with a single traversal of the array, without the need to
create additional arrays or any filtering or sorting.

Just keep track of the closest element found so far, and replace it if a
negative element with a closer distance is found, or a positive element
with the a closer or the same distance.

closest stays zero until the first non-zero array element is found.
If non non-zero element exists then zero is returned. This covers the case
of an empty array, making the check for the array length obsolete.

function calculateClosestTo0 (arr) {
    let closest = 0
    for (let i = 0; i < tempArray.length ; i++) {
        if (closest === 0) {
            closest = arr[i]
        } else if (arr[i] > 0 && arr[i] <= Math.abs(closest)) {
            closest = arr[i]
        } else if (arr[i] < 0 && -arr[i] < Math.abs(closest)) {
            closest = arr[i]
        }
    }
    return closest
}

Using Array.reduce this can be written more concisely as

function calculateClosestTo0 (arr) {
    return arr.reduce((acc, x) =>
        acc === 0 ? x :
        x > 0 && x <= Math.abs(acc) ? x :
        x < 0 && -x < Math.abs(acc) ? x : acc
    , 0)
}

Unit tests

The first versions of my suggested code had bugs as well: It “looked”
simple and correct, but returned a wrong result in special cases.
It is a good idea to collect those (and similar) cases, as well as
other special cases that you think of, into a list. Then each iteration
of the code can be tested against that list, to ensure that it does
not introduce new bugs.

Here is the list that I came up with, it should cover many of the
possible situations:

function calculateClosestTo0 (arr) {
    return arr.reduce((acc, x) =>
        acc === 0 ? x :
        x > 0 && x <= Math.abs(acc) ? x :
        x < 0 && -x < Math.abs(acc) ? x : acc
    , 0)
}

let tests = [
    // Single element:
    { array: [5], result: 5 },
    { array: [-5], result: -5},
    // Positive element is closer to zero:
    { array: [-3, 2], result: 2 },
    { array: [1, -2, 3, -4], result: 1 },
    // Negative element is closer to zero:
    { array: [-2, 3], result: -2 },
    { array: [-1, 2, -3, 4], result: -1 },
    // Two elements with same distance but opposite sign:
    { array: [1, -1], result: 1},
    { array: [-1, 1], result: 1},
    { array: [0, 1, -1], result: 1},
    { array: [1, 0, -1], result: 1},
    { array: [1, -1, 0], result: 1},
    { array: [0, -1, 1], result: 1},
    { array: [-1, 0, 1], result: 1},
    { array: [-1, 1, 0], result: 1},
    // Only elements of same sign:
    { array: [4, 2, 3], result: 2},
    { array: [-4, -2, -3], result: -2},
    // Empty array, or only zeros:
    { array: [], result: 0},
    { array: [0, 0, 0, 0], result: 0},
    // Closest element is at front, medium, or tail position:
    { array: [2, 0, -2, 0, -3], result: 2},
    { array: [-2, 0, 2, 0, -3], result: 2},
    { array: [-2, 0, -3, 0, 2], result: 2}
]

for (let i = 0; i < tests.length; i++) {
    console.log(calculateClosestTo0(tests[i].array) == tests[i].result)
}


Search algorithm to find a point from a given X value

The NPts == 1 case shouldn't need to be handled separately.  The min-max clamping should take care of it, if you write it smartly (using <= and >= tests).

The min-max clamping should should do a short-circuit return.

Once clamped, there shouldn't be any need to test if (nearestIndex < curve.NPts).

I would prefer to calculate the delta based on the min and max, for better precision.  Extrapolating based on Points[1].X - Points[0].X could let floating-point inaccuracies accumulate.

A sanity check before returning the value might be a good idea — it's up to you depending on how much you trust the data.

private ZedGraph.PointPair findPoint(ZedGraph.CurveItem curve, double x)
{
    // Look for the min and max value
    double min = curve.Points[0].X;
    double max = curve.Points[curve.NPts - 1].X;

    // Prevent error if mouse is out of bounds.
    if (x <= min) return curve.Points[0];
    if (x >= max) return curve.Points[curve.NPts - 1];

    double delta = (max - min) / (curve.NPts - 1);
    int index = (int)Math.round((x - min) / delta, 0);

    Debug.Assert(Math.Abs(x - curve.Points[index].X) <= delta / 2, "Interpolation error");
    return curve.Points[index];
}


Combining horizontal and vertical sliders into one

Once your control is active, just keep tracking until the touch ends, even if the touch moves outside of the view:

- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchPoint = [touch locationInView:self];

    CGFloat hLimitLeft = horizontalSliderFrame.origin.x + .5* ksliderThickness;
    CGFloat hLimitRight = hLimitLeft + horizontalSliderFrame.size.width - ksliderThickness;
    CGFloat vLimitTop = verticalSliderFrame.origin.y + .5* ksliderThickness;
    CGFloat vLimitBottom = vLimitTop +  verticalSliderFrame.size.height - ksliderThickness;

    self.thumb.center.x = MAX(hLimitLeft, MIN(hLimitRight, touchPoint.x));
    self.thumb.center.y = MAX(vLimitTop, MIN(vLimitBottom, touchPoint.y));

    [self setNeedsDisplay];
    [self updateValues];

    return YES;
}

Note also that I changed the calculation of hLimitLeft and vLimitTop. I think this approach is clearer (in particular I missed the different signs on the .5 * ksliderThickness term the first couple of times through).

It's been a while since I've done iOS development, so there might be some minor mistakes, but this should get you going in the right direction.


First thing I noticed is you don't seem to be checking if your commands are executed. There's no Exception handling to be found.

Second, avoid the use of magic numbers.

telnetlib.open('10.100.100.103') should be telnetlib.open(TARGET_IP)

time.sleep(3) should be time.sleep(SLEEP_INIT)

Etcetera. Ofcourse, those variables should be declared on the top of your file. Although Python does not support constant by default, there's a workaround if you're interested.


Function returning a vec with prime factors of number

pub fn factors(n: u64) -> Vec<u64> {
    let mut m = n; // is it possible to convert n to a mutable type without using another variable?

use pub fn factors(mut n: u64) to allow the parameter to be mutable
    let mut a:Vec<u64> = Vec::new();

You don't need : Vec<u64>, rust will infer it.
    while m % 2 == 0 {
        m /= 2;
        a.push(2);
    }

    // in C we can just write for (int i = 3; i <= sqrt(m); i+= 2) ... just saying... and C is not even as fast as python to code... am I really doing it right??
    for i in (3..((m as f64).sqrt() as usize + 1usize)).step_by(2) {

Generally speaking, Rust is less verbose than C, but you've hit one of the major exceptions. Rust is pickier about types, it won't let you mix and match different numeric types. But we can make some improvements here.

You don't need 1usize just use 1.
You can also use 3 ..= (m as f64).sqrt() as usize (..= includes the end)

Alternatively, you could reverse the check:
for index in (3..).step_by(2).take_while(|i| i * i <= m)

I'm not sure if that's better or not.
        while m % i as u64 == 0 { // is there a way to avoid all the casts to u64
            a.push(i as u64);
            m /= i as u64;
        }

You need casts because you are being inconsistent about your types. If you change the usize in the for loop to u64 there will be no need for casts.
    }
    if m > 2 {
        a.push(m);
    }
    return a;
}


Getting a list of all computer objects in each AD domain

One thing that I notice, you can change this repetitive fragment

if($($domain.DistinguishedName) -like "*DomainA*"){
    Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": Moved $($comp.DistinguishedName) to $DomainAOUDump") | Out-File $log -Append
    Move-ADObject -Identity $comp.DistinguishedName -Server $($Domain.ReplicaDirectoryServers[0]) -TargetPath $DomainAOUDump
}

Into the following (minus some variable definitions, e.g. $TimeStamp):

$DomainPrefix = Get-DomainPrefix $Domain
$TargetPath = Get-Variable -Name "Domain$($DomainPrefix)OUDump"

Write-Output "$TimeStamp: Moved $DistinguishedName to $TargetPath" | Out-File $log -Append
Move-ADObject -Identity $DistinguishedName -Server $Server -TargetPath $TargetPath

with Get-DomainPrefix defined to capture the first character after "Domain", e.g.

Function Get-DomainPrefix([String] $DomainName){
    $DomainName -match "Domain(?<Prefix>.)" | Out-Null
    $Matches.Prefix
}

So, the script will become (minus definition for necessary functions to hide the complexity)

foreach ($Domain in Get-Domains) {
    foreach ($Comp in (Get-ComputerArray -Domain $Domain)) {
        if ( ShouldBeMoved -Computer $Comp ) {
            $DomainPrefix = Get-DomainPrefix $Domain
            $TargetPath = Get-Variable -Name "Domain$($DomainPrefix)OUDump"
            $TimeStamp = Get-TimeStamp
            $CompName = $Comp.DistinguishedName
            $Server = Get-Server

            Write-Output "$TimeStamp: Moved $CompName to $TargetPath" | Out-File $log -Append
            Move-ADObject -Identity $CompName -Server $Server -TargetPath $TargetPath
        }
    }
}

Note that the else clause is not handled in the simplified script above.

For further cleaning, you can redefine how you store the $TargetPath into a more friendly structure so that we don't need to use Get-Variable. Perhaps a map from DomainPrefix to the TargetPath.

Note: I'm not familiar with ADObject and stuff, so the variable naming might be a little off.


Progress report for a long-running process using 'yield'

I see three basic options you have, to structure progress feedback:

yield
a callback function
inline, hard-coded feedback

Using yield, as you've shown, is one approach.  Ensure you are familiar with Python's implementation of yield and iterables and generators, since several languages share the yield keyword superficially but have subtle implementation differences that might surprise you if, for example, you're used to C#'s yield. Here's a reference on that -- it's subtle but worth reading. Essentially, in Python when your function yields, it returns a generator which can be usefully assigned to a variable, capturing iteration to that point, but you may or may not want to do that.

So there is fundamentally nothing wrong with using yield for this job.  It carries the big advantage of separating pure computing from progress IO.

A decent alternative to yield which is easy to understand is a callback function.  If you passed a callable as a final parameter to your process_data function then a block of code can be executed, instead of a yield or hardcoded inline feedback, also separating processing from feedback.

One advantage a callback approach carries is it allows communication back to the process_data function which could be used to pause or halt processing.  For example, if your callback function is aware of the console or UI, then while updating progress it can also monitor buttons or keys and return a value to the process_data function.  This could indicate, for example, that the user wants to abort processing and this doesn't pollute the process_data function with awareness of specific UI or IO.  So a callback would also work well and allow you to pass a lambda block or full function in Python.  (Languages without a yield facility may have no choice but to use callbacks.)

Example code:

def process_data(data, sleep, report_frequency, report_callback=None):
    for ...
        ...
        if not (i % report_frequency):  # or whatever criteria
            if report_callback:
                if report_callback(i) == USER_ABORT:  # or other codes, by convention
                  return

Please let me also address what I see as a big, very practical, issue with the code defining report_frequency in terms of data elements or loop iterations.

I have see two problems with this pattern of progress tracking:

It's difficult to know in advance what a good value of report_frequency is, when it's expressed in loop iterations.  Trial and error can quickly get you into the ballpark, but that leaves problem #2.
Depending on the nature of your computation, the process_datum function may not run in constant time.  For example, it may take longer as you get deeper into the dataset, if numbers are getting larger and depending on what you're calculating.  What I'm getting at is there may not be a constant number of loop iterations per second.

So I'll propose a better way for you to think of report_frequency. Use seconds, not iterations or data elements.  Time is likely what you had in mind, anyways. It's natural to want to see an update every X seconds, regardless of how many loop iterations that is.  This eliminates both problems and is especially useful when your process_datum function does not run in constant time.

Your code:

def process_data2(data, sleep, report_frequency):
    """loop over a lot of data"""
    for i, item in enumerate(data):
        process_datum(item, sleep)
        if not (i % report_frequency):
            yield i

Can become this:  (I'm putting the yield vs inline vs callback issue aside for the moment, to illustrate the concept)

def process_data3(data, sleep, report_frequency):
    """loop over a lot of data"""
    t_updlast = datetime.now()
    t_update = t_updlast + timedelta(seconds=report_frequency)
    for i, item in enumerate(data):
        if datetime.now() >= t_update:
            print("%6.2f%%\n" % (i*100.0/len(data)))
            t_update = datetime.now() + timedelta(seconds=report_frequency)
        process_datum(item, sleep)

Now you'll see a report every report_frequency seconds that looks like:

56.12%
56.83%
...

And this simplifies how you call process_data3 from main. By dropping the yield, you simply call the following from main, without wrapping it in a for loop:

process_data3(mydata, sleep, report_frequency)

And now that you're in the domain of measuring time, if your process_datum function runs in constant time, you can add a fairly simple calculation for "estimated time to completion".  I'll leave that as an exercise for you. :-)

Remember to add this at the top of your module:

from datetime import datetime, timedelta

Sorry for the long answer and timedelta diversion. I hope this is helpful. Good luck!


private readonly TimeSpan _maxPeriod;
private readonly System.Threading.SemaphoreSlim _throttleActions, _throttlePeriods;

I would add using System.Threading; at the top of the code file, so as to avoid having to fully qualify everything you're referencing in that namespace.

Also, at a glance (especially with the fully qualified SemaphoreSlim) it looks like you're declaring two readonly fields here, but there's really 3. I find this requires less brain juice to glance at:

private readonly TimeSpan _maxPeriod;
private readonly SemaphoreSlim _throttleActions;
private readonly SemaphoreSlim _throttlePeriods;

That said I like that the fields are readonly and that you're using an underscore prefix, which avoids having to qualify the fields with this in the constructor:

public Throttle(int maxActions, TimeSpan maxPeriod)
{
    this.throttleActions = new SemaphoreSlim(maxActions, maxActions);
    this.throttlePeriods = new SemaphoreSlim(maxActions, maxActions);
    this.maxPeriod = maxPeriod;
}

...and the reason you would have to qualify the fields in the constructor without that underscore prefix, is because you have a consistent naming scheme for your constructor parameters vs. the fields they're assigning, and that's excellent.

I'm not very familiar with asynchronous programming, multithreading or even the TPL - but Throttle tickles my Name-O-Meter™, as it's a verb more than a noun.. and class names should be nouns. Would Throttler be weird for a class like this? The only time a verb seems fine to me is when the class is static, such as Convert.

public Task<T> Queue<T>(Func<T> action, System.Threading.CancellationToken cancel)

Here we have the opposite situation: you're using a noun where a verb would be more appropriate - Enqueue<T> sounds more like it.

I'm on the fence about these comments:

    // Release after period
    // - Allow bursts up to maxActions requests at once
    // - Do not allow more than maxActions requests per period

It seems to me that they wouldn't be needed if the constructor had XML comments for its parameters:

/// <summary>
/// Instantiates a new <c>Throttle</c> object
/// </summary>
/// <param name="maxActions">The maximum number of actions allowed per period.</param>
/// <param name="maxPeriod">The time span to use for delaying tasks.</param>
public Throttle(int maxActions, TimeSpan maxPeriod)
{
    this.throttleActions = new SemaphoreSlim(maxActions, maxActions);
    this.throttlePeriods = new SemaphoreSlim(maxActions, maxActions);
    this.maxPeriod = maxPeriod;
}

I've never used Task.Delay, so I'm not 100% on the actual meaning of maxPeriod - but you get the idea: not only XML documentation cleans up comments in the middle of your implementation, it's also picked up by IntelliSense and shown when you're writing the client code.


Using statement in context of streams and WebClients

Under normal circumstances, you should always either call Dispose() explicitly or use a using block. This applies especially for streams and related types (like StreamWriter), where not disposing can have very visible bad consequences (e.g. the end of the text won't be written to the file).

But there are some types for which calling Dispose() doesn't actually do anything useful. And WebClient and MemoryStream are among them. They are IDisposable primarily because they inherit that interface from their base class (Component and Stream, respectively). So, I think your Option 1 is fine.

If you are unsure whether you should dispose objects of some type or whether it's one of the few types where not disposing is safe, err on the side of caution and dispose it.


I see no problem with a programming challenge that has a low accuracy stopwatch.  I have problems with your particular implementation.  Since one aim of exercise is to be fully aware of state, I am surprised in how it maintains state indirectly and privately based on the value in _start.  A simple stopwatch has a very simple state: its either running or not.  So I would just directly offer a Boolean IsRunning property with public getter and private setter.  This removes any mystery as to what the state is, and it exposes that state clearly and publicly to the consumer of the stopwatch.

I personally would prefer _start to be renamed _startTime, but that's no big deal.  I would have the Start() method do 2 things: (1) sets IsRunning to true, and (2) sets _startTime to DateTime.UtcNow.  Note that UtcNow is not only faster than Now (Now actually calls UtcNow first), but also allows the stopwatch to not have any odd side effects from Daylight Saving Time transitions (really the biggest reason to use UtcNow).

My other big gripe is the Stop() method should just stop the stopwatch.  Your implementation has it stopping and also returning the duration.  I would change Stop() to be void, and then offer a TimeSpan Duration property.  Stop() should set IsRunning to false, and somehow store the duration for later retrieval.

This now gives you flexibility that you did not possess before.  What behavior do you want the stopwatch to exhibit if someone asks for the Duration while its running?  Do you want to throw an exception because Stop() has not been issued first?  Or would you like to return a Duration while running?


I haven't worked with Twisted,
and also cannot recommend existing internationalization implementations,
but I can code review in terms of Python in general.

You are not following PEP8,
the official coding style guide of Python.
The coding style violations are not so bad but they are noticeable.
I won't comment on those one by one,
I suggest to give the doc a good read and follow it.

It's nice that you documented this method with a comment:

## load the JSON resource from the path and return the parse obj (dict in this case)
def getJSON(path):
  file = open(path)
  data = json.load(file)
  file.close()
  return data

Why not go all the way and document with a proper docstring?
Also, closing files manually is old-fashioned.
The recommend way is simpler and better:

def getJSON(path):
    """
    load the JSON resource from the path and return the parse obj (dict in this case)

    @param path: JSON file to parse
    @return: parsed object as a dict
    """
    with open(path) as fh:
        return json.load(fh)

In this code, the initialization of locales = [] is unnecessary,
because you assign to the variable in both branches of the if, so you can remove it:

    locales = []
    if setLocales:
      locales = json.load(setLocales)
    else:
      lang_header = request.headers.get("Accept-Language", "en") # for example en-US,en;q=0.8,es;q=0.6
      locales = [locale.split(';')[0] for locale in lang_header.split(',')]


In a list of pairs, replace snds with median of all snds with the same fst

Fixing things first

First of all, median is wrong:

median [1,2,3,4,5] /= median [3,1,4,5,2]

Both should return 3, but on the first list median returns 3 and on the latter 4. Make sure to sort your list, or state in the (currently missing) documentation that your list has to be sorted.
Also, using !! twice is rather slow. Instead, drop the first elements up to mid and then take the mean:

median :: (Fractional a, Ord a) => [a] -> a
median [] = error "median: empty list"
median xs
 | odd len  = xs' !! mid
 | otherwise = mean $ take 2 $ drop mid $ xs'
 where
     len = length xs
     mid = len `div` 2
     xs' = sort xs

mean :: (Fractional a) => [a] -> Maybe a
mean xs = -- exercise; it's not trivial to get this right

-- Alternatively, just use meanDuo in median:
meanDuo :: Fractional a => [a] -> a
meanDuo [x,y] = -- ...

Also, if you use error, make sure to include the function's name in the error message; best practice include the completely qualified name, i.e.

error "Data.TupleMagic.median: empty list"

After all, there are (usually) no stack traces, and it's really nice to know where things went wrong. Note that you should add this behaviour in a documentation, since the type doesn't really tell what would happen on an empty list. Since Fractional a is also an instance of Num, any fixed number could be feasible. Alternatively use Maybe a as return type or NonEmpty as input.

Use the tools you have at hand

mapSnd is second from Control.Arrow. Also, Data.Map is an instance of Functor, which means you can replace

M.toList >>> map (second f) >>> M.fromList

with

fmap f

Furthermore, be honest. Although medianMap is called *Map, it's actually a function. While GHC might call it only once, it's not guaranteed, so remember the map. And last, since you know that every key x will be contained in toMap pairs, you can use Data.Map.! instead of Data.Map.findWithDefault:

solve :: [(String, Float)] -> [(String, Float)]
solve pairs = map replaceWithMedian pairs
  where
    toMap     = map (second pure) >>> M.fromListWith (++) >>> fmap median
    medianMap = toMap pairs
    replaceWithMedian (x, _) = (x, medianMap M.! x)

Furthermore, there's usually no reason to use Float nowadays, unless you've checked

that it's faster,
that it's reduced accuracy fulfils your needs, and
you're having memory constraints (which usually also contradicts String and lists).

Instead, Double is used most of the time.


I am surprised that you chose to use /dev/random  although I can understand that for some purposes like generating private keys a source of strong entropy is preferred and there are even devices for that. Then this discussion could interest you. But the built-in random module in python should be sufficient here.
To read the file to a list of items you can just do this:
with open('/usr/share/dict/words', 'r') as f:
    lines = f.read().splitlines()

Good thing is that you are using the context manager for the open function.
Try to avoid IndexError rather than handle it and ignore it.
If your file is small (check size before opening) you can be lazy, load all items to a list, then filter it, and return one item at random:
def generate_random_word(min_length=8, max_length=13):
    with open('/usr/share/dict/words', 'r') as f:
        lines = f.read().splitlines()

    # select words matching desired length
    # selection = [line for line in lines if len(line) <= max_length and len(line) >= min_length ]
    selection = [line for line in lines if min_length <= len(line) <= max_length]
    # no match found
    if len(selection) == 0:
        return None

    return random.choice(selection)

If no matching item is found (or the file is empty) then I chose to return None.
If you want to filter lines at the source the implementation could be like this:
def generate_random_word(min_length=8, max_length=13):
    with open('/usr/share/dict/words', 'r') as f:
        selection = [line for line in f.read().splitlines() if min_length <= len(line) <= max_length]

    # no match found
    if len(selection) == 0:
        return None

    return random.choice(selection)

The file has to exist but it can be empty, then there is no error but the function will return None. Use os.exists to test that the file is present.
Yes, there is an import but it is a built-in module, does not require installation of a third-party module with PIP. It is also portable and not just Unix.
However, if you insist on /dev/random and want no import one thing you could do is retrieve a random integer like what you are doing now and use it in a modulo-type fashion against the list of matching items, to pick one word at random. Be careful with implementation as you may introduce unwanted bias in the selection. Random functions exist for a reason.
While it is possible to rely solely on /dev/random reimplementing the functionality with decent randomization will result in more code and reinventing the wheel.


Some points:

The shouldSwap variable is not needed. Instead, set indexOfSmallestItem to currentIndex at the beginning of the loop (this is necessary for the next step to work) and check is the indexOfSmallestItem is currentIndex:

if (indexOfSmallestItem != currentIndex) {
    int temp = v[currentIndex];
    v[currentIndex] = v[indexOfSmallestItem];
    v[indexOfSmallestItem] = temp;
}

value is also not needed, as you can access the vector directly:

    if (v[i] < v[indexOfSmallestItem]) {
        value = v[i];
        indexOfSmallestItem = i;
    }

The outside while loop can be a for loop, because:

int currentIndex = 0; // initialization

while (currentIndex < v.size()) { // condition

    // ...

    currentIndex++; // increment
}

So it would be:

for (int currentIndex = 0; currentIndex < v.size(); currentIndex++) {
    // ...
}

You actually can start on currentIndex + 1 because the first one is the current value.
The naming of the vector is not good, as one-letter names are hard to read. Change it to vect or something similar.

Now all you need is the indexOfSmallestItem and the vector:

void SelectionSorter::sort(std::vector<int> &vect) {

    for (int currentIndex = 0; currentIndex < vect.size(); currentIndex++) {

        int indexOfSmallestItem = currentIndex;

        for (int i = currentIndex + 1; i < vect.size(); i++) {
            if (vect[i] < vect[indexOfSmallestItem]) {
                indexOfSmallestItem = i;
            }
        }

        if (indexOfSmallestItem != currentIndex) {
            int temp = vect[currentIndex];
            vect[currentIndex] = vect[indexOfSmallestItem];
            vect[indexOfSmallestItem] = temp;
        }

    }

}

Optionally, you can remove the if (indexOfSmallestItem != currentIndex) completely, as it is not much of an improvement.

Also, you can extract the swapping part into a method. In fact, you should. This makes code (even this size) easier to maintain.

void SelectionSorter::sort(std::vector<int> &vect) {
    for (int currentIndex = 0; currentIndex < vect.size(); currentIndex++) {
        int indexOfSmallestItem = currentIndex;
        for (int i = currentIndex + 1; i < vect.size(); i++) {
            if (vect[i] < vect[indexOfSmallestItem]) {
                indexOfSmallestItem = i;
            }
        }
        swap(vect, currentIndex, indexOfSmallestItem);
    }
}

void swap(std::vector<int> &vect, int i, int j) {
    int temp = vect[i];
    vect[i] = vect[j];
    vect[j] = temp;
}


GroupBy field with and without white spaces

I could not produce an error when an invoice number contains white spaces. I made some minor tweaks.

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,',
'5|20150301|INV WITH WHITESPACE|29,']

def lines = invoices
    .findAll { it.contains('|') }
    .collect { it.tokenize('|') }

def headers = lines.first()
def invoiceMap =  lines.tail().collect{
    [headers, it].transpose().collectEntries()
}.groupBy{ it.INVOICE_NUMBER }


Efficient way to deal with maintaining Many:Many relationships in EF Code-First

I know this is an old question, but I think the problem is timeless. Many to many associations (i.e. without junction class) in Entity Framework are always independent associations, so you can only establish or remove them by manipulating object collections, not primitive key values. Inefficiency is inherent to the implementation.

But it is not prohibited to have a second context that only contains junction tables.

You could create a context that contains the MasterInstanceInstaller junction table and use this to update the associations in the most efficient way you can get using EF:

var installer = installerModel.Installer;

var junctions = context.MasterInstanceInstallers
                       .Where(x => x.InstallerId == installer.InstallerId)
                       .ToList();

// Delete deselected instances.
foreach(var mi in junctions
                  .Where(x => !installerModel.SelectedMasterInstances
                                             .Contains(x.MasterInstanceId)))
{
    context.MasterInstanceInstallers.Remove(mi);
}

// Add newly selected instances.
foreach(int instanceId in installerModel.SelectedMasterInstances
                                        .Except(junctions.Select(j => j.MasterInstanceId)))
}
    context.MasterInstanceInstallers.Add(new MasterInstanceInstaller
                                             {
                                                InstallerId = installer.InstallerId,
                                                MasterInstanceId = instanceId
                                             }
                                        );
}
context.SaveChanges();

Now, if necessary you can populate the updated many to many association through the main context.


Assigning entire column of data to specific column of an array in VBA

First things first, your variables. The names aren't great. For the ws1 to ws3 you're using numbers, which should tell you it's not specific enough or you aren't being effective with your variables.

Worksheets have a CodeName property - View Properties window (F4) and the (Name) field can be used as the worksheet name. This way you can avoid Sheets("Data") and instead just use Data.

Also lastcol3 - what's that? lastColumn? Why the 3, also you missed camelCase on that one. Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names. You could just call it resultsLastColumn instead.

i,r,j,k - these are counters right?

r - currentColumn. i,j,k are acceptable, but personal preference I like to avoid those.

Dim arr - When you don't define your variable, VBA will declare it as a Variant, which are objects:

Performance. A variable you declare with the Object type is flexible enough to contain a reference to any object. However, when you invoke a method or property on such a variable, you always incur late binding (at run time). To force early binding (at compile time) and better performance, declare the variable with a specific class name, or cast it to the specific data type.

By not declaring variables, you could possibly be paying a penalty.

In this case, it is a variant, but it's good to note for the future. It should have a more descriptive name, though.

lastColumn and numRows are integers - Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Additionally, your numRows is set to 1000 and never changed. Why not

Const NUMBER_OF_ROWS As Long = 1000

Your indenting is non-existent.
It's good practice to indent all of your code that way Labels will stick out as obvious.

Always turn on Option Explicit. You can have it automatically by going to Tools -> Options in the VBE and checking the Require Variable Declaration option. This way if you have any variables not defined, the compiler will let you know. In this case your variable wb isn't defined.

You use Application.Calculation a lot. You set it to Manual and do some stuff, then set it to Automatic. Then you loop up to 5000 times in your r loop turning it manual and back to automatic. None of that is needed. The calculations you're doing in VBA aren't affected by the worksheet calculation. I don't know what kind of resources that's using, but I can't imagine it's helping.

Comments - "code tell you how, comments tell you why". The code should speak for itself, if it needs a comment, it might need to be made more clear. If not, the comment should describe why you're doing something rather than how you're doing it. Here are a few reasons to avoid comments all together.

ActiveSheet.DisplayPageBreaks = False - this will only work on the active sheet, what if the sheet isn't active. Why not tell it which sheet to do it on?

Also your last Application.EnableEvents is missing the ..

I don't quite understand this line

ws1.Range("D1") = classArray(1, r)

Does this need to move down column D with the class names?

With your arr array

ReDim arr(1 To NUMBER_OF_ROWS, 1 To resultsLastColumn)
For r = 1 To resultsLastColumn
    ws1.Range("D1") = classArray(1, r)
    For i = 1 To NUMBER_OF_ROWS
        arr(i, r) = ws1.Cells(6 + i, 11)
    Next
Next
For k = 1 To resultsLastColumn
    For j = 1 To NUMBER_OF_ROWS
        If arr(j, k) = 15 Then
            ThisWorkbook.Data.Cells(6 + j, 4) = 1 + ThisWorkbook.Data.Cells(6 + j, 4)
        ElseIf arr(j, k) = 28 Then
            ThisWorkbook.Data.Cells(6 + j, 5) = 1 + ThisWorkbook.Data.Cells(6 + j, 5)
        ElseIf arr(j, k) = 50 Then
            ThisWorkbook.Data.Cells(6 + j, 6) = 1 + ThisWorkbook.Data.Cells(6 + j, 6)
        End If
    Next
Next

This is pretty inefficient. Why not just pull everything into the array and do the sorting in it, rather than on the sheet. That will be quicker.

arr = Data.Range(Cells(1, 6), Cells(NUMBER_OF_ROWS, resultsLastColumn))

Now you can loop with your j and k in the arr or just eliminate k and reuse i.

So at the very least, you'll have this

Option Explicit
Private Sub UpdateData()

    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.EnableEvents = False
    ActiveSheet.DisplayPageBreaks = False
    Application.Calculation = xlCalculationManual

    Const NUMBER_OF_ROWS As Long = 1000
    Dim resultsLastColumn As Integer
    Dim classArray As Variant
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim arr As Variant

    resultsLastColumn = Results.Cells(4, Results.Columns.Count).End(xlToLeft).Column - 1
    ReDim arr(1 To NUMBER_OF_ROWS, 1 To resultsLastColumn)
    classArray = Results.Range(Results.Cells(4, 2), Results.Cells(4, resultsLastColumn + 1))

    ClassCalculationSheet.Range("D1:D" & resultsLastColumn) = classArray()

    arr = Data.Range(Cells(1, 6), Cells(NUMBER_OF_ROWS, resultsLastColumn))
    For j = 1 To resultsLastColumn
        For i = 1 To NUMBER_OF_ROWS
            If arr(i, j) = 15 Then
                Data.Cells(6 + j, 4) = 1 + Data.Cells(6 + i, 4)
            ElseIf arr(i, j) = 28 Then
                Data.Cells(6 + j, 5) = 1 + Data.Cells(6 + i, 5)
            ElseIf arr(i, j) = 50 Then
                Data.Cells(6 + j, 6) = 1 + Data.Cells(6 + i, 6)
            End If
        Next
    Next

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.EnableEvents = True
    ActiveSheet.DisplayPageBreaks = True

End Sub

Some tweaking might be needed as I can't run the macro to see what needs adjusting.


Classes for user registration and authentication

Why are you starting a new database connection for each class? Pass in a database connection object to the constructor:

public function __construct(mysqli $dbConnection) {

This allows your class to work without worrying about actually doing the connection. The class's job is to handle users, not handle database connections!
You not only said LIMIT 1 in your query, but you also check that $query->num_rows is 1, and then you even loop over the results (even though there's only one). This sort of triple check is redundant and unreadable. You know there's either 1 or 0 results because you LIMITed the query!
Your hashing algorithm is not secure. Use PHP 5.5's password_hash(), or if you don't use 5.5 (And you should!!!) use Password Compat, a library written by the same guy who wrote the password_hash() function for PHP's core.
Do not limit your users' password length - Setting a minimum length is good. Setting a maximum length is a kitten killing crime. Don't.
Your login() method returns false on error, but nothing on success. Either return true on success, or simply throw an exception on errors.
Your UserData class is not a class, it's a namespace. You only use it for static functions (even though you don't declare them as static in your class!).
What does your getAndSet method does? It's not clear. Use a proper name or add documentation.
Your UserUtil class does absolutely nothing.

Generally, I'd say you can improve the structure of your code by having the following 3 classes:

UserService - is responsible for registering, authenticating and verifying users using the following two objects. Basically higher level management.
User - Represents a single user in the system. Has absolutely no database interaction whatsoever, and has no idea where it came from. It accepts parameters through the constructor and getters/setters:

class User {
    public function __construct($id, $username, $hashedPassword, $name) {

UserMapper - Which is responsible for mapping and/or creating user objects to/from the database. For example

class UserMapper {
    public function fetch(User $user) {
        //$user object will already have the ID filled in. Fetch according to that and fill the same $user object.
    }
}

Example of execution:

class UserService {

    private $mapper;

    public function __construct(UserMapper $mapper) { ... }

    public function register($username, $password, $name) {
        $user = new User($username, $password, $name);
        $user->validateRegistrationDetails(); //Throws ValidationException on validation error.
        $user->generateHash();
        $this->mapper->save($user); //Save user to database;
    }
}

Note that in the above, the User is unaware of the database, which means it's perfectly reusable across applications with different storage systems.


Loading the stylesheets and scripts on my website

While your code is technically review-able, any review won't help you with your request, because the limited example page doesn't provide a realistic use case for your site, mostly because it doesn't have a style sheet and doesn't actually use any of the fonts, so they won't be downloaded.

Why do want to have the HTML "remain legible"? (Minifying HTML usually doesn't help much with performance anyway, but it's a strange reason for not wanting to do it).

There are automatized performance tests out there, which should be your first stop. For example, Google Chrome's Lighthouse: https://googlechrome.github.io/lighthouse/viewer/?psiurl=http%3A%2F%2Fdiscourse.rf.gd%2F%3Fi%3D1&strategy=mobile&category=performance&category=accessibility&category=best-practices&category=seo&category=pwa&utm_source=lh-chrome-ext

One big resource hog is jQuery. Unless you are using every single feature it provides multiple times, you shouldn't be using it, if performance is important to you.

Make sure you are actually using the fonts and corresponding style sheets.

Some remarks to the HTML:

Don't use on* attributes to add JavaScript event listeners. You generally want to keep HTML, CSS and JavaScript separate. Event handlers are part of the JavaScript and don't belong in the HTML, just like you don't use style attributes to assign CSS in the HTML. See https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_dont_use_these
Don't (only) use JavaScript to handle the login. Use a normal HTTP POST from the form.
Don't use <br>s for line breaks or spacing. They are for logical line breaks such as lines in a postal address or in the stanzas of poems. To separate the input fields of a form wrap each label/field  pair in a block element, such as a div, or put the input inside the label and give the label display: block.


Load JSON file into model using Javascript / jQuery (deferred, asynchronous)

Storing deferred in the model and then passing a callback to getData is a bit obscure. You could write it like this instead:

getData: function() {
    var deferred = $.Deferred();

    if(!this.data) {
        $.getJSON('...',).done(function (data) {
            this.data = data;
            deferred.resolve(data);
        }.bind(this)).fail(deferred.reject);
    } else {
        deferred.resolve(this.data);
    }

    return deferred.promise();
}

model.getData().done(function (data) { /* ... */});

Use either $ or jQuery, don't mix them.
Use Function.prototype.bind instead of var self = this.
Use semicolons after each statement (or leave them out entirely if you prefer that).
this.data = null; seems pointless, newly created objects don't have such a property.


Decorator Pattern in PHP Simple implementation

Just because a class like User has a dependency on another class (like an objects instance of type NotifierService) it does not mean that class has to implement that same interface.  Here it seems that User should not implement this interface at all. You can remove the Notify() method on this class and just call the Notify() method on the passed dependency in your adduser() method.
I don't think decorator pattern makes sense at all for what you are trying to do here.  You are not really trying to "decorate" objects adhering to NotifierService interface with additional functionality related to that interface, but rather simply consume a class of this interface in User.  This is a straight dependency injection situation.
The class implementation of EmailNotifierService is pretty trivial here with hard-coded to/from/message values, almost to the point that this code does not meet code review criteria.  Surely this is not something that is production ready.
Don't echo out output from classes such as this. Leave that to some other functionality.  If you simply want to "log" out class activity, then actually log it (you know to application/server logs).
Why does a class called User deal with multiple users?  Should this class be renamed?
Don't start method/function names with uppercase letters like you do here with Notify() and SendMail().  This should be notify() and sendMail().
$notifierservice should probably be $notifierService (camel-cased). adduser() should be addUser().
You should consider adding validation on public methods, either through type hinting of parameters (like you do for the notifier dependency) or through guarding clauses at beginning of method.  Here, for example, you do nothing to ensure you are getting a valid user passed to your adduser() method.


Binary values in hexidecimal notation written directly to video memory

This is a very nice routine that totally succeeds in using a direction flag set to 1. I've seen others fail at this.

Some observations:

731  BF200A            mov     di,0xa20      DI = 5DC

It's not clear what you mean with "DI = 5DC"

  One thing I had considered here is adding 444H to DI instead, which in effect does exactly the same and then the left column would stay relative if the word at 709H was changed.

I would definitely choose adding 444h to DI in such a specially crafted routine. Relative addressing is so much more flexible to work with.

6F6  B82D0F            mov     ax, 0xf2d
6F9  66AB              stosd                  Write bright white hyphen

This is the only place where your code conceivably could fail. You store the dword from EAX without making sure the high word has any meaningful content. If the high word is empty you're in the clear, if not the screen will get disrupted.
Since modern BIOSes do use 32-bit registers, you can't be sure...

The shortest way to 'correct' this is:

mov     ax, 0x0F2D
stosw
dec     di
dec     di


Custom multiple div appends in JavaScript

Indentation

I don't understand the indentation. The second line should be indented the same as the first line.

Multiple var declarations

If you declare multiple variables, you can use the var keyword only once, and separate variables using the comma operator, for example:

var article = document.getElementsByTagName('article')
   ,obj = {}
   ,wrappers = ['a', 'b', 'c']

Semicolons

From another answer of mine:

  You're using many semicolons. JavaScript has a nice feature called
  automation semicolon insertion, which means you almost don't need to
  use semicolons at all, with just a few exceptions. From npm style
  guide:

    Don't use them [semicolons] except in four situations:

    for (;;) loops. They're actually required.
    null loops like: while (something) ; (But you'd better have a good reason for doing that.)
    case 'foo': doSomething(); break
    In front of a leading ( or [ at the start of the line. This prevents the expression from being interpreted as a function call or
    property access, respectively.

  Note that it's only a matter of style. You don't have to follow it if
  you don't like it, but personally I think that if something is not
  required, there's no reason to use it.

Meaningless identifiers

Identifiers like a1, a2, a3 doesn't tell much about the purpose of the variable. Try to name them in a way that explain what they are used for.

Only class names should begin with an uppercase letter

It's recommended to use identifiers starting with an uppercase letter (like Constructor in your case) only to declare classes. As you don't use new operator when calling that function, I assume it's not a class and therefore should have a name starting with a lowercase letter.

Use const instead of var to declare variables that should never be changed

You don't intend to change most of the variables, especially these that refer to the DOM elements. You could use const keyword instead of var to make sure don't override them accidentally.

Using variables or functions before they are declared

You're using create function before you define it. It is recommended not to use variables or functions before declaring them. Therefore, you should move your create function declaration to the top.

Use for...of loop

If you don't need array indexes, you can use the for...of loop instead of the traditional loop.

Example:

for (let element of array) {
  console.log(element)
}

Miscellaneous

I don't see a point in declaring the set function and immediately calling it. If you want to create a separate scope, use IIFE, but I don't think you need it here. The same is with the Constructor function.

a1, a2, and a3 should definitely merged in one array.


I think this is OK, but there are a few things I'd consider changing.

Your helpers should be protected or private, since they should only be being called by the non-helper methods.
You should consider the const-ness of your methods. e.g. you want void printTree() const.
If you're using this pattern a lot, you could consider using a visitor pattern for things that traverse the tree, and a builder style pattern for things that build the tree. This way printTree could be moved outside the class and implemented as something like

void printTree(const Tree& tree) {
  tree.visit( TreePrinter() );
}

And similarly the deserializeTree function would be replaced with a constructor like this

Tree tree( TreeBuilderFromString(rep) );

It looks like the code reads a balanced (or almost balanced) tree. But since presumably you can build a non-balanced tree, serialization followed by deserialization will not generate the original tree. (Maybe this is expected and OK, but it may surprise someone when they try to use the class)


Arduino driver for 7 segment display with bit-shift register

What's really in show[2]?`

According to your comment:

int show[4]; // (thousands, hundreds, tens, ones)

the digits in show are in descending order.  But according to your code:

show[0] = ((int)number2show/1000);
show[1] = ((int)number2show%1000)/100;
show[3] = (((int)number2show%1000)%100)/10;
show[2] = ((((int)number2show%1000)%100)%10);

you swapped show[2] and show[3].  Was this a copy paste error?

Simplification

Your code for setting the show array can be simplified.

There's no need for an int cast because everything is already an int.
(((n % 1000) % 100) % 10) is equivalent to n % 10
Three of the four lines in the if and else case are common.

I would rewrite it like this:

    if (number2show >= 0) {
        show[0] = (number2show / 1000) % 10;
    } else {
        show[0] = MINUS_SIGN;
        number2show = -number2show;
    }
    show[1] = (number2show / 100) % 10;
    show[2] = (number2show /  10) % 10;
    show[3] = number2show % 10;
    for (int i=0; i < 4; i++)
        showDigit(show[i], digitPins[i]);

Variable scopes

I'm not sure if you use show anywhere else, but if you don't then you should make it be a local variable instead of a global.  Also, your other global arrays can be marked const since they are read-only.