Manage list of subjects (show, delete, add) in Python

Clear the screen
Here is the terminal after three iterations

We can clean a lot of this up by simply doing
print(chr(27) + "[2J")

after every iteration.
def clear_scr():
    print(chr(27) + "[2J")

Note that on adding this, you should also do
input("Press any key to continue...")

After the user selects an option, this way the user can wait and see what is on the screen peacefully without the program interrupting
def wait():
    input("Press any key to continue...")
    print(chr(27) + "[2J")

Or a better version that also prints a confirmation message
def wait(message):
    input(f"{message}. Press any key to continue...")
    print(chr(27) + "[2J")

wait("Subject Added!")

>>> Subject Added! Press any key to coninue...

Unnecessary comments
# ask user for selection
selection = int(input("\nPlease enter option: \n(1) Add subject\n(2) Show all subjects\n(3) Delete a subject\n(4) Quit\n"))

A comment here is totally not required, it only makes the code look convoluted for no reason. What I do suggest is the usage of docstrings.
def wait():
    """
    Wait for the user to press any key then clear the screen
    """
    ...

Print the subjects in a better fashion
I added a few more subjects in your program. When I entered Show all subjects.
These are your subjects:  ['Math', 'Science', 'French', 'Computer', 'Hindi', 'Social Science', 'Spanish', 'English']

This isn't nice at all, I suggest you print one on each line, with numbering, something like
Subjects

1. Math
2. Science
3. French
3. Computer
...

def show_subjects(subjects):
    """
    print all the subjects line-by-line
    """
    print("\n\nSubjects\n")
    for i in range(len(subjects)):
        print(f"{i+1}. {subjects[i]}")

Don't use magic numbers
            if selection == 1:
                add_subject(subjects)
            elif selection == 2:
                show_subjects(subjects)
            elif selection == 3:
                delete_subject(subjects)
            elif selection == 4:
                break
            else:
                raise ValueError

1, 2, 3, and 4 are unnamed numeric constants here. They don't really really tell anything about what the branch does. What if it was instead
            if selection == Choices.add.value:
                add_subject(subjects)
            elif selection == Choices.show.value:
                show_subjects(subjects)
            elif selection == Choices.delete.value:
                delete_subject(subjects)
            elif selection == Choices.quit.value:
                break
            else:
                raise ValueError

Without reading anything inside the if block, I can tell exactly what its going to do. That is an example of clean code.
You can achieve this by using an enum
from enum import Enum

class Choices(Enum):
    add = 1
    show = 2
    delete = 3
    quit = 4

print(Choices.add.value)
>> 1

print(Choices.quit.value)
>> 4

Colored text
This one is optional, but it adds a lot of meaning to your code :).
You can use the coloroma module to color your text to different colors in an easy way. For example, when you find that the user has entered bad input, you can do

Isn't that great! The best part about it is that it is cross-platform
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

You have a lot of options, it can help you customize the output a lot. Read the documentation
As suggested by @Reinderien, using the colorama library you can clear the screen too
import colorama as cr
cr.init()

print(cr.ansi.clear_screen()) # clears the screen

Re-written
from colorama import Fore, Back, Style
import colorama as cr
from enum import Enum

cr.init()

class Choices(Enum):
    add = 1
    show = 2
    remove = 3
    quit = 4

def wait(message = None):
    if message is None:
        input("Press any key to continue...")
    else:
        print(Fore.GREEN)
        print(Style.BRIGHT)

        print(message, end = '')

        print(Style.RESET_ALL)
        input("Press any key to continue...")

    print(cr.ansi.clear_screen())

def add_subject(subjects):
    add = input("\nWhat subject do you want to add? ")
    if add not in subjects:
        subjects.append(add)
        wait("Subject Added!")
    else:
        print("Subject already present")
        wait()

def show_subjects(subjects):
    print("Subjects\n")
    print(Fore.YELLOW)
    print(Style.BRIGHT)
    for i in range(len(subjects)):
        print(f"{i+1}. {subjects[i]}")
    wait()

def delete_subject(subjects):
    delete = input("\nPlease enter subject to delete: ")
    if delete not in subjects:
        print("Subject not found")
        wait()
    else:
        subjects.remove(delete)
        wait("Subject removed!")

def main():
    subjects = ["Math","Science","English"]
    while True:
        try:
            selection = int(input("\nPlease enter option: \n(1) Add subject\n(2) Show all subjects\n(3) Delete a subject\n(4) Quit\n"))
            if selection == Choices.add.value:
                add_subject(subjects)
            elif selection == Choices.show.value:
                show_subjects(subjects)
            elif selection == Choices.remove.value:
                delete_subject(subjects)
            elif selection == Choices.add.value:
                break
            else:
                raise ValueError

        except ValueError:
            print(Fore.RED)
            print("\nNot a viable option. Please pick 1, 2 or 3.")
            print(Style.RESET_ALL)
            wait()

if __name__ == "__main__":
    main()


Instead of

range(slice.start,slice.stop,slice.step)

you could use this expression that handles the special cases too

range(len(self))[slice]

(This works with range on both Python 2 and 3, but not with Python 2 xrange even though it is mostly equivalent to Python 3 range)


Count the status messages in a column VBA

Don't reinvent the wheel. Your homemade function will never be as fast as the built in functions.
Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String
  Dim OK As Long
  Dim NOK As Long
  Dim uploadMsg As String

  If StartRow = 0 And EndRow = 0 Then
    Exit Function
  End If

  OK = WorksheetFunction.CountIf("A" & StartRow & ":A" & EndRow, "OK")
  NOK = WorksheetFunction.CountIf("A" & StartRow & ":A" & EndRow, "NOK")

  uploadMsg = ResultStringer(OK & "OK")
  uploadMsg = uploadMsg & ResultStringer(NOK & "NOK")

  If strMsg <> vbNullString Then
    UploadStatus = strMsg & " " & uploadMsg
  Else
    UploadStatus = uploadMsg
  End If

End Function

Private Function ResultStringer(ByVal Count As Long, ByVal ID as String) as String

  If Count > 1 Then
    ResultStringer = Count & ID & " rows, "
  Else
    ResultStringer = Count & ID & " row, "
  End If

End Function


do
   digits <- someParser
   return $ someFunction digits

is just

someFunction <$> someParser

We can make parseNumberBase a lot shorter with that information:

-- | Parses a number at a specific base
parseNumberBase :: Char -> Parser LispVal
parseNumberBase 'b' = Number . fromJust . readBinary <$> many1 (oneOf "01")
parseNumberBase 'o' = Number . fst . head . readOct  <$> many1 octDigit     -- see below
parseNumberBase 'd' = Number . read                  <$> many1 digit
parseNumberBase 'h' = Number . fst . head . readHex  <$> many1 hexDigit     -- see below
parseNumberBase _   = error "Wrong number base"

readFunc digits !! 0 is head (readFunc digits), so we were able to get rid of !! too.

That being said, parseNumberBase has a lot of responsibility. Split it into multiple parsers, and it's suddenly a lot easier to grasp:

parseBinary :: Parser LispVal
parseBinary = Number . fromJust . readBinary <$> many1 (oneOf "01")

parseDecimal :: Parser LispVal
parseDecimal = Number . read <$> many1 digit

parseHexadecimal :: Parser LispVal
parseHexadecimal = Number . fst . head . readHex <$> many1 hexDigit

parseOct :: Parser LispVal
parseOct = Number . fst . head . readOct  <$> many1 octDigit

We can now test all those functions in isolation. We can now write parseNumberBase as another parser:

parseNumber :: Parser LispVal
parseNumber = parseDecimal <|> char '#' *> parseNumberBase

parseNumberBase :: Parser LispVal
parseNumberBase =  char 'h' *> parseHexadecimal
               <|> char 'd' *> parseDecimal
               <|> char 'o' *> parseOct
               <|> char 'b' *> parseBinary


In tree_find and tree_find_min [edit: and even in tree_insert] you're not really gaining anything from using recursion. For example, I think tree_find_min would probably be clearer something like:

tree_position tree_find_min( search_tree tree )
{
   if ( tree == NULL )
      return NULL;
   while (tree->left != NULL)
       tree = tree->left;
   return tree;
}

As a side-benefit, this may also be faster with some compilers. In code like:

 HATE_DATA *hatedata;

 /* ... */

 hatedata = (HATE_DATA * ) malloc( sizeof( HATE_DATA ) );

I'd change it to look more like:

 hatedata = malloc(sizeof(*hatedata));

The cast accomplishes nothing useful in C, and can cover up the bug of forgetting to #include <stdlib.h> to get the proper prototype for malloc. Using sizeof(*hatedata) instead of sizeof(HATE_DATA) means that changing the type only requires changing it in one place (where you've defined the variable), instead of everywhere you've done an allocation.


On form submission, upload an image if there is one, then start update event

I know nothing of react.js, so please forgive me if I missed something, but in a JS way I'd do it that way :

onSubmit = event => {
        event.preventDefault();
        //start with a dedicated part for testing values
        let fieldError="";
        if(!eventNameRegex.test(this.state.event_name))fieldError.="Name not correct.";
        if(!eventDescriptionRegex.test(this.state.event_description))fieldError.="Description not correct.";
        if(!priceRegex.test(this.state.ticket_price))fieldError.="Price not correct.";
        if(!eventDateRegex.test(this.state.event_date))fieldError.="Date not correct.";
        if(fieldError!=""){
          this.setState({
            error: 400,
            errorMessage:
              fieldError."Please fill in all required fields with correct data. Please try again."
          });
          return false;
        }
        // check if image changed or not then continue
        this.props.handleLoading(true);

        if (this.state.file != null) {
          startUploadImage(this.state.file).then(response => {
            this.setState({ event_image: response.data });
            return myUpdateEvent(this);
          });
        }
        else return myUpdateEvent(this);
      };

//when in doubt use a function ! here's hoping react.js can deal with it
function myUpdateEvent(myEvent){
  return myEvent.props.startUpdateEvent(myEvent.props.event.id, myEvent.state)
    .then(() => {
      myEvent.props.handleLoading(false);
      myEvent.props.history.push("/events");
    })
    .catch(error => {
      console.log("error");
      myEvent.props.handleLoading(false);
      myEvent.setState({
        error: error.status,
        errorMessage: error.data
      });
    });
}

Not tested but you get the gist.


I had no problems using a SortedSet, which is both more clear and more efficient than your implementation. You should use Scanner#nextInt() instead of parsing strings yourself.

I'm currently on a Java 6 machine. Other changes I'd suggest in Java 7+:
You should also close your scanner (use a try-with-resources block). You should prefer a PriorityQueue to a TreeSet, because as @JerryCoffin++ has already pointed out, a heap is probably the correct data structure to be using (depending on the implementation details and frequency of removes, in some cases the TreeSet may perform better).

import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;

public class QHeap1 {

    public static void main(final String[] args) {
        final Scanner input = new Scanner(System.in);
        final int numberOfCommands = input.nextInt();
        final SortedSet<Integer> set = new TreeSet<Integer>();

        for (int i = 0; i < numberOfCommands; i++) {
            final int command = input.nextInt();
            switch (command) {
            case 1:
                set.add(input.nextInt());
                break;
            case 2:
                set.remove(input.nextInt());
                break;
            case 3:
                System.out.println(set.first());
                break;
            default:
                throw new IllegalStateException();
            }
        }
    }
}


You have a static dictionary as backing store which means that all cache instances share it. Not saying that this is wrong and it might be intended but you should be aware of it.
Your cache apparently is not thread-safe. You need to protect access to the dictionary with locks or if you are using .NET 4 or later use ConcurrentDictionary. If you make the backing dictionary non-static then you might not need to make it thread-safe if you can ensure that you never access the same cache instance from multiple threads at the same time.
Items only get evicted when they are being accessed again. This means if you only ever access items once they will stay in there forever.
Make the magic number 30000 at least a const member or maybe even a tunable property/field (in which case you should prefer making it a TimeSpan as it's easier to use than plain ticks)
Your Add method will throw an exception if the entry in the cache already exists. You either need to check if it exists and just update the entry (or do nothing, whatever makes sense) or replace the entry by using _cache[key] = .. rather than _cache.Add().
Depending on your use case you might want to rename Created into LastAccessed and update it whenever someone accesses the entry (read/write) with the same key (which means items will be evicted a certain period after they have been last accessed rather than created).
Last but not least you might want to look into the MemoryCache class if you are using .NET 4 or later.


Using readonly input fields to persist data between views

On a functional level there is no problem with using readonly inputs to persist and display data in a preview screen.  When I tried this approach however I noticed that different browsers treat readonly inputs in different ways which cannot be addressed with CSS rules. For example in Chrome the inputs can be styled to look and behave like any other element, however in IE the caret will sit there blinking on readonly input fields which was not acceptable in my particular case.


If recursion has reached a leaf node then either you have accumulated
the correct sum or not, but in no case it is necessary to check the
left or right child node. Therefore I would change the first
implementation slightly to

public static boolean hasPathSum1 (Node root, int sum) {
      if (root == null) {
          return false;
      }
      if (root.left == null && root.right == null) {
          return root.data == sum;
      }
      return hasPathSum1(root.left, sum - root.data) ||
             hasPathSum1(root.right, sum - root.data);
}

If the values of all nodes are non-negative then you can
stop the search if the accumulated sum along a path is greater than the target sum:

public static boolean hasPathSum1 (Node root, int sum) {
      if (sum < 0) {
          return false;
      }
      if (root == null) {
          return false;
      }
      if (root.left == null && root.right == null) {
          return root.data == sum;
      }
      return hasPathSum1(root.left, sum - root.data) ||
             hasPathSum1(root.right, sum - root.data);
}

(and similarly for the iterative versions).

Some advice from the answers to your previous question DFS in Binary Tree
applies here as well:

Better/consistent spacing: if and while is sometimes followed
by a space (good) and sometime not (bad).
Rename the root parameter to node.
Make those methods instance methods of the Node class instead of
static methods.


Assuming that if the first object has a property set to undefined and the rule states no change then your code is almost spot on.

Some minor changes

The variable key into a const.
Return the extended object.
Vet the arguments.

Thus

function extend(obj1, obj2) {
    if (obj1 !== null && typeof obj1 === "object") {
        if (obj2 !== null && typeof obj2 === "object") {
            for (const key in obj2) {
                if (!obj1.hasOwnProperty(key)) {
                    obj1[key] = obj2[key];
                }
            }
        }
    }
    return obj1;
}
extend({a: 1, b: undefined}, {b: 1, c: 2}); // returns {a: 1, b: undefined, c: 2}


Not sure if this code is correct or will compile but here is my attempt...

private class func parseTravelData(data: AnyObject!, mode: ESTMode, completion: NSDictionary? -> Void) {
    let receivedData = data as? NSDictionary
    let routes = receivedData?["routes"] as? NSArray
    let legs = routes?.firstObject?["legs"] as? NSDictionary

    if let firstLeg = legs?.firstObject as? NSDictionary {
        let firstLegDurationDict = firstLeg["duration"] as? NSDictionary
        let firstLegDuration = firstLegDurationDict?["value"] as? Float

        if firstLegDuration > ConnectionManager().timeMax && mode == .Walking {
            completion(nil) // resend using drive mode
        } else if let durationStr = firstLegDurationDict?["text"] as? String {
            let distanceDict = firstLeg["distance"] as? NSDictionary
            if let distanceStr = distanceDict?["text"] as? String {
                completion(["duration": durationStr, "distance": distanceStr])
            }
        }
    }
}

Here are a few things I did to try to make the code more concise

I noticed that the interesting stuff only happens if the route contains a leg. So I was able to eliminate a few if statement blocks by using optional chaining and moving code out of the if conditions and into the receivedData, routes, and legs variables. (The individual variables are not strictly necessary but make the code more readable). So the first "if let" check happens to see if there is actually a leg in the optional legs array.

Another optimization I made is that I moved the if let d = dur block into the else statement above since the code will only proceed if duration["text"] exists. This also allowed me to eliminate the var dur: String? = nil statement as well.

I also renamed some variables for more clarity, for example I renamed v to firstLegDuration.

I was able to eliminate the if let v block since if v (which is now firstLegDuration) is nil then v > ConnectionManager().timeMax will be false since nil > AnyObject == false.

One thing I noticed that the completion does not get called in all cases, which to me seems weird, so if there is an error or missing data then nothing will happen.


Type signatures and naming

While it's good practice to use type signatures on top-level bindings, it's usually not necessary in expressions unless type classes are involved. For example, the two following lines don't need type signatures:

contents <- (tail . lines) <$> readFile "submitInput" :: IO [String]
let input = contents :: [String]

readFile always returns IO String, and tail . lines always changes a String into a [String]. Furthermore, input = contents is a nop, so it's not clear why it's there.

Next, you usually use camelCase instead of snake_case in names in Haskell and hide the functionality in local bindings if you don't want to reuse functions, e.g.

min_decoding :: String -> Integer
min_decoding word =
    base_conversion (toInteger . length . nub $ number) $ catMaybes number
  where
    number = fix_decoding $ min_aux word Map.empty 0
    min_aux = ...

Feel free to use let … in … instead. By the way, max_range is missing a type signature.

Recursion and Horner's method

Your base_conversion isn't really optimal. We can use Horner's method to get rid of length. For this we need a helper:

baseConversion :: Num a => a -> [a] -> a
baseConversion base = go 0
  where
    go acc []     = acc
    go acc (d:ds) = go (acc * base + d) ds

You can verify that this yields the same result:

baseConversion 10 [1,2,3,4,5]
   = go 0 [1,2,3,4,5]
   = go (0  * 10 + 1) [2,3,4,5]
   = go (1  * 10 + 2) [3,4,5]
   = go (12 * 10 + 3) [4,5]
   = go (123 * 10 + 4) [5]
   = go (1234 * 10 + 5) = 12345

But there's already a function for this, foldl':

baseConversion :: Num a => a -> [a] -> a
baseConversion base = foldl' (\acc x -> acc * base + x) 0

Either way, we got rid of the ^ (length ds) part.

Don't repeat yourself

Both min_decoding and max_decoding look very similar, and so do max_aux and min_aux.

We're repeating a lot of logic here. So instead, let us use a single function:

toDigit :: (Integer -> Integer) -> [Char] -> Map.Map Char Integer -> Integer -> [Maybe Integer]
toDigit _    []     _   _    = []
toDigit step (c:cs) m next =
  | c `Map.member` m    = Map.lookup c m : toDigit cs m next
  | otherwise           = Just next : toDigit cs (Map.insert c next m) (step next)

Now

min_aux = toDigit (+1)
max_aux = toDigit (subtract 1)

Use appropriate types

But toDigit is still not optimal. We never return Nothing in our list. Therefore, there is no reason to use [Maybe Integer] as a result type:

toDigit :: (Integer -> Integer) -> [Char] -> Map.Map Char Integer -> Integer -> [Integer]
toDigit _    []     _   _    = []
toDigit step (c:cs) m next = case Map.lookup c m of
  Just digit -> digit : toDigit step cs map next
  Nothing    -> next  : toDigit step cs (Map.insert c next m) (step next)

While we're at it, you probably want to replace Integer with Int for the digits.


Buffered RNG-wrapper using openmp in c++

There are a few (relatively minor) things here that can be improved on:

Order your includes. Specifically, group your includes by their source (i.e. current project headers, STL headers, library headers...). Most commonly, the following order is used:

Header file the current source file implements (i.e. a.h for a file called a.cpp) if any
Headers from the same project you're working on
Headers from different projects/libraries (in your case, omp.h, for example)
Headers from the standard library

This, on one hand, serves the purposes of checking whether each header file actually contains all required includes (say, for example, your header actually used something from chrono; with your current include order, your compiler would not complain because you include chrono in main.cpp before buffered_parallel_rng.hpp, thus hiding the missing include), on the other hand helps readers of you source code to verify includes quickly.
using unsigned_t = unsigned; Quite frankly, I don't see the reason you do this here. Why not just use unsigned?

Anyhow, if you really want to have this (and also have a good reason to), I would expect a similar using for int here because of consistency. Alternatively, one could argue that you should be taking an SizeType and a SeedType as template parameters, especially since the result_types and thus the seed types of random number generators in the standard library are different for different generators (for example, std::mt19937_64 uses std::uint_fast64_t whereas std::minstd_rand0 uses std::uint_fast32_t).
Instead of using iter_t = typename std::vector<result_type>::iterator;, you should write using iter_t = typename buffer_t::iterator; to prevent subtle bugs when changing the type of buffer_t.
The name BP_RNG is not very clear. Although the abbreviation "rng" is quite common, what "bp" means will not be clear to most people on first sight. Since your header is named buffered_parallel_rng.hpp, I would expect your class to have the same name.
time_rng currently takes a std::string as argument by value, but you only ever output it to std::cout, so you should take it by const reference instead.
Don't write "\n" where '\n' would suffice. For example, when writing to std::cout, the former implies a call to std::strlen and an additional indirection while the latter just passes the value directly.
iter is not really a fitting name for the second parameter you pass to time_rng. I was confused the first time I glossed over that function because, for me at least, iter almost exclusively stands for iterator. I would have grasped that parameter's meaning much more quickly if you had actually named it iterations or anything along that line.

All in all, you code is mostly well written. None of the points above constitute a "Act now! Your code is on fire!"-grade problem, only tips that could make your already good code a little better and prevent some subtle, thus nasty bugs.

However, I can't tell whether your approach is really worth anything. You should definitely perform some benchmarks to see if there are any performance improvements compared to a single threaded approach and, if yes, how big they are.

Another thing you should consider is learning to do proper testing. There are a variety of testing frameworks (for example, Google Test) which provide functionality for writing and executing tests effectively. Especially since you are concerned about determinism here, writing and executing tests at a much larger scale should help you verify that your code works correctly.


Loop through List multi-threading to ping hostnames

I think what you are looking for is the Callable<T> interface:

  A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.

Instead of having to pass around a thread-safe Collection to gather your non-pingable servers, you can call ExecutorService.invokeAll(Collection) to get a List<Future<T>>, which you can then retrieve the results.

First, I'll suggest having an implementation of Callable<T>:

public class Ping implements Callable<String> {

    private final String hostname;

    public Ping(String hostname) {
        this.hostname = hostname;
    }

    public String call() {
        // ... try to ping server
        // assume the results are stored in a boolean
        return isPingable ? "" : hostname;
    }

}

And then you can construct your Collection<Ping> to submit to the ExecutionService:

List<Ping> pingTasks = new ArrayList<Ping>(nonReplicatingRegisters.size());
for (RegisterReplicationSynchTime nonReplicatingRegister : nonReplicatingRegisters) {
    pingTasks.add(new Ping(nonReplicatingRegister.getRegisterName()));
}
// or use invokeAll(Collection, long, TimeUnit) for an explicit timeout
List<Future<String>> taskResults = es.invokeAll(pingTasks);
List<String> results = new ArrayList<String>();
for (Future<String> taskResult : taskResults) {
    try {
        String output = taskResult.get();
        if (!output.isEmpty()) {
            results.add(output);
        }
    } catch (InterruptedException e) {
        // handle accordingly
    } catch (ExecutionException e) {
        // handle accordingly
    }
}


It is a maxim in computer science that there are really "only three numbers": zero, one, and many.  You have a case of many, and you should treat it as such.  Otherwise, someday a customer might want to buy a hundred of some food item, and performance will be poor.

Therefore, I recommend…

Option four

Instead of having the table represent current supply levels, keep a transaction log, where the quantity column stores purchases as positive values and consumption as negative values.

INSERT INTO user_food_purchase (user_id, food_id, quantity) VALUES (?, ?, ?);

Then, adjust the rest of your application to accommodate the schema change.  For compatibility, you could define a view:

CREATE VIEW user_food AS
SELECT user_id, food_id, SUM(quantity) AS quantity
    FROM user_food_purchase
    GROUP BY user_id, food_id;


C random walk the alphabet on a small grid

Only Use Conditions When It Is Necessary
In the for loop that displays the grid the condition

if (!((j + 1) % 10)) {

is unnecessary. Move the new line printf outside the inner loop and it will execute when the inner loop ends.

Algorithm
The algorithm doesn't seem to be using the diagonals which means there are 4 additional spots a character  might go to.

It's not clear that the program works completely when I ran the program it went up to H and then quit so
the grid was mostly ..

Variable and Symbolic Constant Names
There are some pretty good names such as open_spaces, examined_spaces, placed, grid, TRUE, FALSE, START, END and then there are names such as N, i, j, next_j and next_i. In particular i and j seem to indicate
directions so horizontal and vertical might be better names. N might be better called GRID_SIZE.

There also seems to be a missing symbolic constant for 4 (OPEN_SPACES_SIZE).

Functions
Just because you haven't read the chapter on functions doesn't mean you shouldn't use them if you are accustomed to writing code using functions. It definitely would help the code.


Rotating background using Swing: performance issues

Here is something you could do which would work for computers not fast enough to rotate the image every 30 ms.  Instead of requesting a repaint every 30ms, define the angularVelocity (rads / second) and call a repaint every 30 ms or as fast as possible, if it can't make 30 ms.  Then compute angleRad = angularVelocity * (System.currentTimeMillis() - startTime).

Swing efficiency is not the problem. The image manipulation library is the bottleneck. I don't think you can do anything to make it faster. There are probably some (non-Java) libraries that can rotate images much faster using the GPU, but mixing those with Java would make the installation a nightmare.

Another solution would be to store all rotated images in memory.  That might work if you were rotating the image by 90 degrees increments, but you would need an awful lot of RAM for all images incremented by 0.001 rads.

As an aside, I believe repaint() now has to be called on the Swing event thread, which was not the case before Java 7.  I'm not quite sure and I could not find about this on the web, so I would be grateful if someone could comment.  You could use a SwingWorker if that is the case. Actually, for cleanness, you should probably stick to a SwingWorker.  It does exactly want you are doing, and is made especially for that.


Is there a better way to test for the exception conditions?

Your code is as simple as it can get... but if you are wanting to clean up the method then you could do something like this to make it look nicer.

public string ColumnName { get; private set; }
    public string PropertyName { get; private set; }
    private Func<colType, propType> conversion;

    public virtual void Map<T>(T obj, DataRow row)
    {
        Conditions.Check1(row, this.ColumnName).argerror(String.Format(@"Column ""{0}"" does not exist in the row.", this.ColumnName));
        PropertyInfo property = obj.GetType().GetProperty(this.PropertyName);
        Conditions.Check2(property).argerror(String.Format(@"Property ""{0}"" does not exist for object.", this.PropertyName));
        var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName];
        Conditions.Check3(conversion, property, row, this.ColumnName).casterror(string.Format(@"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.", this.ColumnName, this.PropertyName, value.GetType(), property.PropertyType));
        if (conversion != null)
        {
            value = conversion((colType)value);
        }
        property.SetValue(obj, value, null);
    }

    public static class Conditions
    {
        public class Error
        {
            private bool error = false;
            public bool isError { get {return error;}}

            public Error(bool r)
            {
                error = r;
            }
            public bool argerror(string message)
            {
                if (error)
                    throw new ArgumentException(message);
                return error;
            }
            public bool casterror(string message)
            {
                if (error)
                    throw new InvalidCastException(message);
                return error;
            }

        }
        public static Error Check1(dynamic a, string cn)
        {
            return new Error(a.Table.Columns.Contains(cn));
        }
        public static Error Check2(dynamic a)
        {
            return new Error(a == null);
        }
        public static Error Check3(dynamic a, dynamic b, dynamic c, string cn)
        {
            return new Error(a == null && b.PropertyType != c.Table.Columns[cn].DataType);
        }
    }


Here is another way to filter people by role:

class Participation < ActiveRecord::Base
  belongs_to :toon
  belongs_to :person

  validates :role, :presence => true
end

class Person < ActiveRecord::Base
  has_many :participations
  has_many :toons, :through => :participations
end

class Toon < ActiveRecord::Base
  has_many :participations
  has_many :people, :through => :participations do
    def with_role(role)
      where('participations.role' => role)
    end
  end
end

Now, you can get the people fitered by role: toon.people.with_role('producer').


Distinguishing between people who have likes to posts and those who have dislikes

As  you can easily identify from your code that link_to code for Like and Dislike  are same for all conditions only the class value is changed
so you can use below code it looks more clean:

<% like_class = current_user.voted_up_on? @post ? 'btn-outline-primary' : 'btn-outline-dark' %>
<% dislike_class = current_user.voted_down_on? @post ? 'btn-outline-danger' : 'btn-outline-dark' %>
<%= link_to "LIKE #{@post.get_upvotes.size}", like_post_path(@post), method: :post, class: "btn #{like_class}" %>
<%= link_to "DISLIKE #{@post.get_downvotes.size}", dislike_post_path(@post), method: :post, class: "btn #{dislike_class}" %>


"reasonably safe against deadlocks" is a strange expression :)
In ThreadsnQueues the if func is not None: can be turned into an else.
Your code in ThreadScore indicates that some exceptions might be expected because you handle them and continue. The problem is if that happens while you have the semaphore acquired then it will not release it. You should move the release into finally block.
In choose you join on all threads in multiple places and this code [ p.join(5.0) for p in procs ] gets repeated several times. Should be refactored into a method.
I'm not sure what the point of the semaphore is. The way I read you code is:

You initialize the semaphore with N
Then you spawn N threads each calling acquire/release in it's run method.

This means that all threads can simultaneously enter the block protected by the semaphore. So what's the point of having it?
In ThreadScore.run() the main part is the while True loop. However it never seems to take anything of the queue (it only seems to do it once at the beginning of the run method) so how does it work?


std::vector memory manipulation with serialization and deserialization

First of all, fundamentally: std::string is a data type to hold text. Exclusively. It should not be used to hold binary data. Use a std::vector<(unsigned) char> for that.

Secondly, you are using heap allocation without needing to:

T* pt = new T(t);

This makes no sense at all, and introduces the potential of a memory leak. You could simply make a copy – but you don’t even need to do that. Just work on the original data.

Next, about naming; it’s general convention in C++ to use underscore_separated_names rather than camelCase or PascalCase. This is only a convention but I’d follow it unless there’s a very compelling reason not to.

Also on the topic of naming: returnSize is redundant, return has no place in the name. Rename it to object_size or something along those lines. You are also inconsistent in your naming convention here.

To get the size of a zero-terminated string, use std::strlen, that’s more efficient than converting to a std::string.

Finally, the code simply doesn’t work. It creates a bit-by-bit shallow representation. That only works for simple composite objects, it no longer works for objects that use pointers or references internally – you’ve already noticed that, because otherwise you wouldn’t need to create a special chase for char* and std::string. Incidentally, for the case of char* you specialise returnSize but for the case of std::string you specialise Serialize and DeSerialize. That’s asymmetrical and means that you have several places that might require changing when new types are added. You should reduce this to a single point which requires specialisation.

Ignoring that, I’d rewrite the code as follows:

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

typedef unsigned char byte_t;
typedef std::vector<byte_t> buffer;

std::size_t object_size(const char* s) {
    return std::strlen(s);
};

template<typename T>
std::size_t object_size(T const& obj) {
    return sizeof(obj);
};

template<typename T>
buffer serialize(const T& obj) {
    std::size_t size = object_size(obj);
    buffer buf(size);

    byte_t const* obj_begin = reinterpret_cast<byte_t const*>(&obj);
    std::copy(obj_begin, obj_begin + size, buf.begin());

    return buf;
};

template<>
buffer serialize<std::string>(std::string const& str) {
    return serialize(str.c_str());
};

template<typename T>
T deserialize(buffer const& buf) {
    return *reinterpret_cast<const T*>(&buf[0]);
}

template<>
std::string deserialize<std::string>(buffer const& buf) {
    return deserialize<char*>(buf);
}

int main() {
    using std::cout;

    int x = 97;
    buffer c = serialize(x);
    cout << deserialize<int>(c) << "\n";

    char g = 'g';
    buffer c2 = serialize(g);
    cout << deserialize<char>(c2) << "\n";

    std::string k = "blabla";
    buffer c3 = serialize(k.c_str());
    cout << deserialize<char*>(c3) << "\n";

    std::string ka = "string";
    buffer c4 = serialize(ka);
    cout << deserialize<std::string>(c4) << "\n";
}

… but like I said, this solution doesn’t generalise and is pretty useless in practice. Have a look at Boost.Serialization for a proper implementation. Unfortunately this is quite a complex problem.


Eigenvector calculation involving three matrices

Performance

Here's where all the action happens:

# Select the first r columns of u corresponding to the r principle Eigenvector of
# MatrixForEigenvalues
TRANSPOSE_NEW_EIGVEC = array(NEW_EIGVEC).real.T   # Done for easy accessibility of matrix
TRANSPOSE_MATRIX_U = array(NEW_U).real.T  # Done for easy accessibility of matrix
FINAL_ARRAY_EIGVAL = []
FINAL_ARRAY_EIGVEC = []
FINAL_MATRIX_U = []
for i in range(len(array(NEW_EIGVAL).real)):
    j = argmax(array(NEW_EIGVAL).real)
    FINAL_ARRAY_EIGVAL.append((array(NEW_EIGVAL).real)[j])
    FINAL_ARRAY_EIGVEC.append(TRANSPOSE_NEW_EIGVEC[j])
    FINAL_MATRIX_U.append(TRANSPOSE_MATRIX_U[j])
    TRANSPOSE_NEW_EIGVEC = concatenate((TRANSPOSE_NEW_EIGVEC[:j], TRANSPOSE_NEW_EIGVEC[j+1:]))
    TRANSPOSE_MATRIX_U = concatenate((TRANSPOSE_MATRIX_U[:j], TRANSPOSE_MATRIX_U[j+1:]))
RESULT_MATRIX_U = array(FINAL_MATRIX_U).T     # This is the actual R

The first thing I notice is multiple calls to array(), specifically for array(NEW_EIGVAL).real. This is inefficient; doing all the necessary conversions at the beginning and then referencing the variables would be much more efficient. Next, I get the strong suspician that j = argmax(array(NEW_EIGVAL).real) could be moved out of the loop, since array(NEW_EIGVAL).real isn't changing between iterations of the for loop. This in turn makes me strongly suspect that the line appending to FINAL_ARRAY_EIGVAL is buggy in some manner, since it's just getting the same element of NEW_EIGVALUE each time. Another thing I notice is that neither FINAL_ARRAY_EIGVAL nor FINAL_ARRAY_EIGVEC is referenced outside of the loop, making them functionally useless at the moment. If you plan to use them later, they can stay, but otherwise, they are just unnecessary cycles. Finally, concatenate is a very hacky and non idiomatic way to remove one element of an array; I would probably try to use delete() instead.

Since I'm unfamiliar with matrix eigenvector calculations, I unfortunately can't help you much more with optimization, unless I did some more research (and I probably would need some more information about your datasets). Anyway, I have some other suggestions to help you improve your Python coding style in general:

Descriptive variable names are useful

I recommend looking at PEP 8 variable naming conventions. It would improve the readability of your code.

In particular, instead of using names like U and K, I would recommend using more descriptive names. Also, instead of continually phasing names out and deleting them, it may be better to create temp variables to store the new value and then delete those, so the same variable has the same name throughout, but that's a matter of personal style (I'll address this more in the next section.)

Touch-ups

I notice a lot of del statements in your code. This can be avoided by taking advantage of the for-loop scope and not naming one use variables:

U = []
for k in uread('U.csv'):
    # ...

S = []
for s in uread('s.csv'):
    # ...

EIGVAL = []
for e in uread('EIGVAL.csv'):
    # ...

EIGVEC = []
for e in uread('EIGVEC.csv'):
    # ...

With statements can use an as clause to specify the name of the file so you don't have to define it on a separate line:

def uread(filename):
    with open(filename, 'r') as UFILE:
        READER = csv.reader(UFILE)
        for i in READER:
            yield i

List comprehensions can significantly simplify your code, and eliminate unnecessary (explicit) variable assignment:

Original:

for k in ufinal:
    TEMP = []
    for j in k:
        TEMP.append(eval(j))
    U.append(TEMP)
    del TEMP
    del k

Improved:

for k in ufinal:
    U.append([eval(i) for i in k])
    del k

Better yet, you can just turn most of your initial loops into list comprehensions:

Original:

U = []
for k in uread('U.csv'):
    U.append([eval(i) for i in k])

S = []
for s in uread('s.csv'):
    for t in s:
        S.append(eval(t))

EIGVAL = []
for e in uread('EIGVAL.csv'):
    for l in e:
        EIGVAL.append(eval(l))

EIGVEC = []
for e in uread('EIGVEC.csv'):
    for l in e:
        EIGVEC.append(eval(l))

Improved:

U = [[eval(j) for j in i] for i in uread('U.csv')]
S = [eval(j) for i in uread('s.csv') for j in i]
EIGVAL = [eval(j) for i in uread('EIGVAL.csv') for j in i]
EIGVEC = [eval(j) for i in uread('EIGVEC.csv') for j in i]

Final improved code

Warning: this is untested, so one or two things may be broken (but I've tried my very best to avoid that.) Since I don't know your datasets, I thought I'd leave testing up to you.

# -*- coding: utf-8 -*-
from numpy import array, argmax, delete
import csv

def uread(filename):
    with open(filename, 'r') as UFILE:
        READER = csv.reader(UFILE)
        for i in READER:
            yield i

U = [[eval(j) for j in i] for i in uread('U.csv')]
S = [eval(j) for i in uread('s.csv') for j in i]
EIGVAL = [eval(j) for i in uread('EIGVAL.csv') for j in i]
EIGVEC = [eval(j) for i in uread('EIGVEC.csv') for j in i]

NEW_U = []
NEW_EIGVAL = []
NEW_EIGVEC = []
for i in range(len(S)):
    if S[i] > 0.001:
        NEW_U.append(U[i])
        NEW_EIGVAL.append(EIGVAL[i])
        NEW_EIGVEC.append(EIGVEC[i])
del U
del EIGVAL
del EIGVEC
# Select the first r columns of u corresponding to the r principle Eigenvector of
# MatrixForEigenvalues
NEW_EIGVAL = array(NEW_EIGVAL).real
NEW_EIGVEC = array(NEW_EIGVEC)
TRANSPOSE_NEW_EIGVEC = NEW_EIGVEC.real.T   # Done for easy accessibility of matrix
TRANSPOSE_MATRIX_U = array(NEW_U).real.T  # Done for easy accessibility of matrix
FINAL_ARRAY_EIGVAL = []
FINAL_ARRAY_EIGVEC = []
FINAL_MATRIX_U = []
j = argmax(NEW_EIGVAL)
for i in range(len(NEW_EIGVAL)):
    FINAL_ARRAY_EIGVAL.append((NEW_EIGVAL)[j])
    FINAL_ARRAY_EIGVEC.append(TRANSPOSE_NEW_EIGVEC[j])
    FINAL_MATRIX_U.append(TRANSPOSE_MATRIX_U[j])
    TRANSPOSE_NEW_EIGVEC = delete(TRANSPOSE_NEW_EIGVEC, j)
    TRANSPOSE_MATRIX_U = delete(TRANSPOSE_MATRIX_U, j)
RESULT_MATRIX_U = array(FINAL_MATRIX_U).T     # This is the actual R
with open('r.csv', 'w') as r_file:
    WRITER = csv.writer(r_file)
    WRITER.writerows(RESULT_MATRIX_U)
print(RESULT_MATRIX_U)


interface BarCode

The interface is a good idea, but it shouldn't be just a marker interface. It seems very probable that all the implementations that you will add later, will contain a String code value. So, a method declaration like String getCode(); would be useful here. It will allow to access the value when necessary, without worrying about the concrete BarCode type behind.

Over-engineering

But I'm also asking myself if a separate class per BarCode type is really necessary here. Should ean just remain a basic field within Product?

@Entity
public class Product { ...

  @Column
  private String eanCode;
  ...
}

The idea would be to validate the candidate eanCode value before setting it on the object. Not sure that dedicated classes are necessary, because they are just wrappers for the only field, aren't they?

Exceptions Handling

Taking into account the current listing, the code

try {
  BarCode ean = new Ean13Factory().create(code);
  p.setEan((Ean13) ean);
} catch (InvalidBarCodeException e) {
  logInvalidCode(e, code);
}

does exactly the same thing as if it were

if (BarCodePredicate.isValid(code) {
  p.setEan(new Ean13(code));
} else {
  logInvalidCode(code);
}

This resembles drastically to what we can find in item#59, page 247 of Effective Java.


Unsafe collection which allows immutable access while also allowing push()

Safety First

Unfortunately, programming in unsafe Rust requires respecting a number of rules; and you have broken at least one here.

Rust memory safety is based on the principle of Aliasing XOR Mutability, which is enforced as much as possible at compile-time for obvious performance reasons. When you wish to shift the responsibility from compile-time to run-time, you need to inform the compiler about it at the type level, lest it infers properties about the code that do not hold.

For interior mutability, use UnsafeCell.

This is the basic block that is used by all abstractions which defer the enforcement of the principle to run-time. For example, here is AtomicBool:

#[cfg(target_has_atomic = "8")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct AtomicBool {
    v: UnsafeCell<u8>,
}

Thus, your type should be:

pub struct UnsafeHolder<T> {
    items: UnsafeCell<Vec<Box<(T,String)>>>,
}

Clean-up

UnsafeCell comes with a get method: UnsafeCell::get(&self) -> *mut T, and thus your change_mut function is unnecessary:

pub fn add_element(&self, element: T, key: String) {
    if !unsafe { & *self.items.get() }.iter().any(|i| i.1 == key) {
        let items = unsafe { &mut *self.items.get() };
        items.push(Box::new((element, key)));
    }
}

Nits and bits

Your add_element method should indicate when insertion fails; silent failures make programs harder to debug.

It seems strange to me to pass the element before the key; most APIs seem to do the reverse so I would advise following in their steps.

The complexity of your look-up is O(N), so that inserting repeatedly has O(N2) complexity; if you were sorting by key look-up could be O(log N) instead, and repeated insertion O(N log N).

I recommend avoiding unnecessary parentheses (such as in if !(...)); they clutter the code for no obvious gain.

Final Word

If you wish to venture into the world of unsafe, I recommend reading the Nomicon. Until Rust gets official unsafe semantics, it is probably the best reference about the dos and don'ts.


Method and class method debugging decorator

To address your specific questions:

Is it Pythonic enough? I think so.
Is there any additional data that should be debugged? If I was using this for my debugging, I’d want a bit more information:

The name of the function that’s been called – knowing which args/kwargs were supplied to an unknown function is not that useful
The return value of that function
A trace statement when the function returns

There should also be something to distinguish trace output from regular output. That makes it much easier for me to reconstruct the call flow afterwards. Here’s an example of the sort of output I mean:

[trace] enter my_function {
[trace]   args: (10, 10)
[trace]   kwargs: {}
hello world
[trace] return 100 } exit my_function

For extra brownie points, use the traceback module to indent a function and its arguments/return value to match their level in the call tree.
Do I need a separate function and method decorator? It seems like it would be possible to do. I haven’t tried it, but https://stackoverflow.com/q/19314405/1558022 seems like it might have a couple of approaches.

If applied to a method, your function decorator will always print the repr() of the object. That might be enough in most cases – perhaps rather than defining a second decorator, you add an argument debug_object to your function decorator which additionally prints the object dict on demand.
Is it compatible with Python 2.7 and Python 3? As far as I can tell, yes.

Two other (minor) comments:

I would rename the decorators. The first is misleading, because it’s described as “method debug”, but actually gets applied to functions. More generally, I’d be inclined to violate naming principles and make these lowercase instead, so they don’t look out of place next to the decorated functions. I’d probably call them something like @internaltrace.
The docstring for “debug” is not very useful. A better docstring would tell me exactly what debugging means in this context – here, something like “print the arguments supplied to the function” would be better.

I’d be inclined to rename this parameter to “trace”, but I think correcting the docstring is more important.

A couple of additional ideas that came to me this morning:

You might want to tie this into the logging library, and direct all trace output to a dedicated file (say inttrc.log). That isolates trace statements from regular prints without putting [trace] everywhere, and is easier to search through later.

This will get you timestamps, which are worth including, but I forgot about yesterday.
Although pprint is nice, I think a one-line string might be better. You can always unpack it later if you need to, but having all the associated parts of args/kwargs on the same line will be easy for parsing later.


Generic menu class for console applications

I see some things that may help you improve your program.

Separate the interface and implementation

Perhaps you posted it as just one file for the sake of simplicity and compactness, but if you were to actually use this, I think it's more likely that it would be useful as separate header and implementation files.  This has the additional benefit of making the interface part of the code (the part that a user would have to see) a little shorter and easier to comprehend.

Allow the user to specify streams

Right now, the code is tied to std::cin and std::cout, but what if I wanted to use the menu, say, remotely over a socket connection?  This could very easily be allowed by adding input and output stream references to the class.  One way to do it would be to have std::istream and std::ostream arguments with defaults to std::cin and std::cout.

Prefer const references

The printChoices routine is currently this:

bool ConsoleMenu::printChoices() {
  bool successful = false;
  for (auto commandByChoice : commandsByChoice_) {
    successful = static_cast<bool>(
        out << '[' << commandByChoice.first << ']' << '\n');
  }
  return successful;
}

The for loop should instead use const auto & rather than auto to assure no copies are made of the strings.  Further, the successful flag isn't really necessary.  Instead we could write it like this:

bool ConsoleMenu::printChoices() const {
  for (const auto &commandByChoice : commandsByChoice_) {
    out << '[' << commandByChoice.first << ']' << '\n';
  }
  return !!out;
}

The !!out construct assures that out is interpreted as a bool but you could use a cast if you think it's more readable.  (Perhaps I've been writing too much Javascript lately!)

Prefer unordered containers for performance

The std::map container has logarithmic search performance, but the std::unordered_map container has constant time performance.  For that reason, it makes sense to prefer the unordered container unless there's actually a need for a sorted one.  There isn't in this case.

Use const where practical

Right now, it's not possible to declare and use a const ConsoleMenu.  There's no reason that shouldn't be possible.  To do that, all of the functions except the constructor would have to be const.  Mostly that means simply adding const to the declaration of the function, but we need to do a little more to adapt use.  The reason is the last line:

commandsByChoice_[userChoice]();

There are a few problems with this simple line.  First, the operator[] has a side effect you probably don't want.  Specifically, if the key is not found, it is inserted into the map.  That's definitely not what's wanted here whether we are trying for const or not.  Two alternatives are using at (which can throw an exception) or find.  A way to do that would be this:

const auto result{commandsByChoice_.find(userChoice)};
if (result != commandsByChoice_.end()) {
    result->second();
}

Since you're already calling find in the helper function, it would make sense to only call it once and save (and use) the result.  I'll show that later on.

Rename use

The use method is a bit awkwardly named in my view.  I'd suggest instead to use operator()().  This would allow us to rewrite the sample main like this:

int main() {
    bool running{true};
    const ConsoleMenu menu{"What should this program do?\n",
            "Invalid operation; ", "> ",
        {
            {"run", [&running] { running = true; }},
            {"stop", [&running] { running = false; }}
        }};
    while(running) {
       menu();
    }
}

Note that I consistently use the C++11 uniform initialization syntax to reduce ambiguity.

Avoid re-doing work

Because there is no way within this code to insert or delete menu choices once the ConsoleMenu is created, we can create the entire menu as a static string once (perhaps within the constructor) and simply use that rather than iterating through the menu choices and making multiple calls to operator<< every time printChoices() is called.  Further, one could create a single string that includes message_, all choices and prompt_.

Results

Using all of the suggestions above, we can simplify considerably and remove the two private helper functions.  Here's the header file:

menu.h

#ifndef MENU_H
#define MENU_H
#include <functional>
#include <iostream>
#include <unordered_map>
#include <string>

class ConsoleMenu {
  public:
    ConsoleMenu(const std::string& message,
        const std::string& invalidChoiceMessage,
        const std::string& prompt,
        const std::unordered_map<std::string, std::function<void()>>& commandsByChoice,
        std::istream &in = std::cin,
        std::ostream &out = std::cout);
    void operator()() const;
  private:
    std::string invalidChoiceMessage_;
    // the prompt_ string contains the message, all choices and prompt
    std::string prompt_;
    std::unordered_map<std::string, std::function<void()>> commandsByChoice_;
    std::istream &in;
    std::ostream &out;
};
#endif // MENU_H

And this is the implementation.

menu.cpp

#include "menu.h"
#include <sstream>

ConsoleMenu::ConsoleMenu(const std::string& message,
    const std::string& invalidChoiceMessage,
    const std::string& prompt,
    const std::unordered_map<std::string, std::function<void()>>& commandsByChoice,
    std::istream &in, std::ostream& out) :
        invalidChoiceMessage_{invalidChoiceMessage},
        commandsByChoice_{commandsByChoice},
        in{in},
        out{out}
{
    std::stringstream ss;
    ss << message;
    for (const auto &commandByChoice : commandsByChoice_) {
      ss << '[' << commandByChoice.first << ']' << '\n';
    }
    ss << prompt;
    prompt_ = ss.str();
}

void ConsoleMenu::operator()() const {
    std::string userChoice;
    const auto bad{commandsByChoice_.cend()};
    auto result{bad};
    out << '\n';
    while ((out << prompt_) && (!(std::getline(in, userChoice)) ||
            ((result = commandsByChoice_.find(userChoice)) == bad))) {
        out << '\n' << invalidChoiceMessage_;
    }
    result->second();
}

Additional features

There are some additional things that might be nice.  One thing that comes immediately to mind is that it would be useful to be able to create a constexpr ConsoleMenu.  One way to do that might be to use C++17's std::string_view instead of std::string and to use an array instead of a map.

Another feature that might be nice would be the ability to optionally use wide strings.  This is pretty easy to accommodate by turning the class into a templated class.


Getting input from user about 2×2×2 Rubik's Cube state

You can store the sides on an array and loop over that, something roughly like this:

import java.util.Scanner;

public class scanCube {

    public static void main(String[] args) {
        String[] sides = { "TOP", "LEFT", "FRONT", "RIGHT", "BACK", "BOTTOM" };
        int side_index = 0;
        Scanner in = new Scanner(System.in);

        int[][] input = new int [6][4];
        System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
                + "Please enter your cube");

        for (String side: sides) {
            System.out.println("Enter the colors for the " + side + " side");
            System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
            int counter = 0;
            while(counter < 4){
                input[side_index][counter] = Integer.parseInt(in.nextLine());
                counter++;
            }
            side_index++;
        }
    }
}

I would personally add a String.split so that the user can input the numbers for a single side on a single line, without having to hit enter every time.

If you want to have an alternative approach, with this the user can enter something like 0312 and it will be split and assigned to the array.

Keep in mind that this is just the general idea, not complete / nice code.

import java.util.Scanner;

public class scanCube {
    public static void main(String[] args) {
        String[] sides = { "TOP", "LEFT", "FRONT", "RIGHT", "BACK", "BOTTOM" };
        int side_index = 0;
        int max_colors_per_side = 4;
        Scanner in = new Scanner(System.in);

        int[][] input = new int [sides.length][max_colors_per_side];
        System.out.println("Welcome to the 2x2x2 cube solver :)\n \n"
                + "Please enter your cube");

        while (side_index < sides.length) {
            System.out.println("Enter the colors for the " + sides[side_index] + " side");
            System.out.println(" 0 = white \n 1 = orange \n 2 = green \n 3 = red\n 4 = blue\n 5 = yellow\n");
            String[] side_colors = in.nextLine().toString().split("");

            if (side_colors.length != max_colors_per_side+1) { // Account for CR/LF
                System.out.println("Invalid input!");
            } else {
                for (int i = 1; i <= max_colors_per_side; i++) {
                    // You should check here also that the input is valid (0..3)
                    input[side_index][i-1] = Integer.parseInt(side_colors[i]);
                }
                side_index++;
            }
        }
    }
}

You should also check that the user didn't input something presumably wrong like a cube with 10 white squares, because the amount of squares should be the same for every color.


For a beginner this is some good code. I would make some additional adjustments.

One-line docstrings should be on one line, not over 3. And should end with a period.
You should only pass the marks to percentage and not rely on a global student_marks.
You can use sum to compute total_marks.
I'm not a fan of having format in the percentage function.
You should move all the main code into a main function, if __name__ == '__main__': should really only call this.
It's more idiomatic to use comprehensions than map, even more so when you have list(map(...)).
It's pretty rude to call a student a query. You can just use name.

def percentage(marks):
    """Find percentage of marks of the student."""
    return sum(marks) / len(marks)

def main():
    """Main code."""
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *scores = input().split()
        student_marks[name] = [float(score) for score in scores]
    name = input()
    result = percentage(student_marks[name])
    print(format(result, '.2f'))

if __name__ == '__main__':
    main()

You can use statistics.mean rather than a custom made percentage.
You can change the for loop into two comprehensions, a generator and dictionary comprehension.

Note: I don't think comprehensions are better here, but are an 'as good' alternate.

import statistics

def main():
    """Main code."""
    _marks = (input().split() for _ in range(int(input())))
    student_marks = {
        name: [float(score) for score in scores]
        for name, *scores in _marks
    }
    result = statistics.mean(student_marks[input()])
    print(format(result, '.2f'))

if __name__ == '__main__':
    main()


I like it.

For some very specific cases where a class needs to be tested and its functionality depends on what System.DateTime.Now returns, then you need an abstraction to wrap the static method calls, if you want to be able to write unit tests that have full control over that dependency.

Your ITimeMachine does that nicely. While a meaningful name, IDateTimeService seems more appropriately generic though. ITimeTraveler might be superfluous.

The dependent code would look like this:

public class MyClass
{
    private readonly IDateTimeService _service;

    public MyClass(IDateTimeService service)
    {
        _service = service;
    }

    public void DoSomething()
    {
        var now = _service.Now(); // instead of DateTime.Now;
        //...
    }
}

I also like that you made Now() a method. It abstracts away the fact that DateTime.Now is really a method in a property suit.


Infinite scroll pagination with a Wookmark layout

The code looks pretty good, but here are a couple suggestions:

The semicolon at the top is unnecessary: ;(function(myApp,$){
You use _this in many places where this would work:

Consider Function.bind (see MDN, only works on modern browsers)
This very much depends on personal style

This is a little confusing. I don't write jQuery much, but it isn't clear what the first this is referring to (and the second this has a different meaning than the one above, which is also confusing):

$.fn.wookmark_pagination = function(options) {
  return this.each(function() {
    new WookmarkPagination(this, options).init();
  });
};


Some good practices:

Assert on NULL parameter

Whenever you have a function passing an array you should either do a runtime check to see if it's NULL or do an assert(array). To catch bugs where a NULL array is passed to the functions.

Check return values for alloc functions

You should always make sure you get a non-NULL result from any allocation, malloc, realloc and such to fail gracefully, or at least exit(1) with a nice out of memory message. Good for catching bugs where accidentally an uninitialized count value is passed to an allocating function.

Check for negative input

Since for instance your numElements is an int instead of size_t you should either change it, or at least check for negative values.

Deleting many values

I don't know how common a use case this would be, but since on each delete, you might move a large chunk of values. Adding a function that either takes a list of indices to delete and do it in one go, by simply refilling the array with those indices excluded. Otherwise iterating over and deleting values can be a huge operation depending on the size of the array.

Destroy function

I agree with this comment:

/* Probably useless macro */
#define array_free(ARRAY) free((ARRAY)->data)

This should be a function that both resets the numElements = 0, capacity = 0 and does the free(array->data) as well as array->data = NULL.

This ensures that any reuse of the array will still result in a reallocation and hence not writing to freed memory. However please note that array_add in this case must check that capacity > 0 and at least set it to 1, otherwise the realloc will be 0.


Leetcode longest substring with no duplicates

The linearity of your approach is due to the fact that your longest could never be longer than the size of the alphabet (otherwise it'd have a duplicate for sure). It means that your code runs at \$O(N * A)\$, where \$N\$ is a length of the string, and \$A\$ is a size of alphabet. Since the latter is a constant, you may safely take it out of the big-O, yielding \$O(N)\$.

The asymptotic constant is still a little bit too large (I don't know what alphabet is used in the test cases, but it is safe to assume at least 26), so there is a room for improvement. You correctly noticed that the immutability of the strings may hurt performance; try to get rid of them. A most obvious approach is to preallocate a list (of the alphabet size), and use it as a circular buffer.

In fact, even that is suboptimal. Try to get rid of the explicit buffer at all (hint: two indices into the original string).

It also may be beneficial to keep a dictionary indexed by letters currently present in the buffer with the values being their corresponding indices. This way you can do a constant time lookup rather than linear search in the buffer. Keep in mind however that such a dictionary may itself be costly; I expect it to improve performance if the alphabet is quite large. Try and profile it.

As for the code, it is simple and clean. Not much to say.


Http Request response time within C# application

I found that a webclient with custom settings gave me the fastest result.
Personally I was building a framework for web crawling & scraping, where you want it to do the requests quickly.

Might be an alternative to check out.

public class DefaultWebClient : WebClient {
    public DefaultWebClient() {
        ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
        ServicePointManager.DefaultConnectionLimit = Int32.MaxValue;
        ServicePointManager.Expect100Continue = false;
    }

    protected override WebRequest GetWebRequest(Uri address) {
        var request = base.GetWebRequest(address) as HttpWebRequest;

        if (request != null) {
            //This might work in your case, it didnt do the trick for me.
            //request.Method = WebRequestMethods.Http.Head;
            request.Proxy = null;
            request.Timeout = 5000;
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        }

        return request;
    }
}

This, in combination with retrieving the response url should do the trick.

    protected override WebResponse GetWebResponse(WebRequest request) {
        var response = base.GetWebResponse(request);
        if (response != null) {
            var responseUri = response.ResponseUri;
            // Redirect found.
        }
        else {
            // No Action.
        }

        return response;
    }

If you do a lot of requests to get the redirects, it might be a good idea to raise it as an event.


There's nothing to optimise here.

Your steps are:

Open connection

Execute about the simplest SQL query possible

End

There's nothing we can change there that would make any difference.

Now, if you want to post a separate question, detailing your Database Structure, your SQL query, and asking how to optimise it, we could help there.

That aside, thoughts on your code:

You never use tr.

This:

Dim strsql1, tr As String

Does not actually Dim both as strings. When you declare variables, each variable must have a datatype or it will default to Variant.

This is what your code is actually doing, implicitly:

Dim strsql1 [As Variant], tr As String

Your database connection string should be a constant

If you're targeting a database, and you don't need to build the connection string dynamically, you should just have a project constant like so:

Public const FP_DATABASE_CONNECTION_STRING As String = "Provider=Microsoft.ace.OLEDB.12.0; Data Source=\\REDACTED.accdb;"

Now it's in one place, and you know where it is, and if it ever changes, you know where to go to change it.

You should name your query

strsql1 tells me absolutely nothing useful.

selectFpId5683 would be a much better name. Sure, it's a bit verbose, but it actually lets us know what the variable is. And now, when we use it later, we can know that we're using the right thing.

selectFpId5683 = "SELECT * FROM FP WHERE SUBMISSION_ID = 5683;"

And now:

Option Explicit

Public Const FP_DATABASE_CONNECTION_STRING As String = "Provider=Microsoft.ace.OLEDB.12.0; Data Source=\\REDACTED.accdb;"

Function GetAllFpRecordsWithId5683() As ADODB.Recordset

    Dim fpConnection As ADODB.Connection
    Set fpConnection = New ADODB.Connection
    fpConnection.Open FP_DATABASE_CONNECTION_STRING

    Dim selectFpId5683 As String
    selectFpId5683 = "SELECT * FROM FP WHERE SUBMISSION_ID = 5683;"

    Dim recordsWhereId5683 As ADODB.Recordset
    Set recordsWhereId5683 = New ADODB.Recordset
    recordsWhereId5683.Open selectFpId5683, fpConnection, adOpenStatic

    Set GetAllFpRecordsWithId5683 = recordsWhereId5683

End Function

Much, much easier to understand, work with, debug etc.

And then make it even better:

You'll probably want to target more than 1 ID in the future, so why not make your function a general one that can target any ID?

Option Explicit

Public Const FP_DATABASE_CONNECTION_STRING As String = "Provider=Microsoft.ace.OLEDB.12.0; Data Source=\\REDACTED.accdb;"

Function GetAllFpRecordsWithId(ByVal targetID As String) As ADODB.Recordset

    Dim fpConnection As ADODB.Connection
    Set fpConnection = New ADODB.Connection
    fpConnection.Open FP_DATABASE_CONNECTION_STRING

    Dim selectFpId As String
    selectFpId = "SELECT * FROM FP WHERE SUBMISSION_ID = " & targetID & ";"

    Dim recordsWhereId As ADODB.Recordset
    Set recordsWhereId = New ADODB.Recordset
    recordsWhereId.Open selectFpId, fpConnection, adOpenStatic

    Set GetAllFpRecordsWithId = recordsWhereId

End Function


I think your code is pretty readable and looks like idiomatic enough Clojure code¹. So from a readability standpoint your code seems fine. However performing assoc on a vector of length n takes O(log n) time, so your runtime will be in O(n log n) as opposed to O(n), which an imperative implementation would be in.

However there's not much you can do about this other than perhaps using java arrays imperatively, but that would be very unidiomatic Clojure code. And O(n log n) isn't that bad (definitely not as bad as the O(n^2) I incorrectly claimed before).

(Note that my previous note about transients was wrong as assoc! on a transient vector has the same runtime complexity as on a persistent vector).

¹ Usually you'd avoid index-based loops wherever possible, but the nature of the algorithm makes that pretty much impossible here.


Helper is not a good class name. You should be able to come up with something that provides more context to what the functions are doing.

In getPlayers(), I would loop and add instead of adding all and then removing.

private static List<User> getPlayers(List<User> users) {
    List<User> filteredUsers = new ArrayList<User>();
    for (User user : users) {
        if (user.isPlayer()) {
            filteredUsers.add(user);
        }
    }
    return filteredUsers;
}

I also added curly braces around the if block. It's not necessary, but it will prevent errors if you need to add an extra line later. You also included them in createPlayersScoreMap(), so it's best to be consistent.

If you have a large number of players and scores, you can make createPlayersScoreMap() more efficient (in terms of Big O processing). If n is the number of users and m is the number of scores, the method is currently O(n*m). However, if you sum all the scores first and then filter the players, you can get O(n+m).

public static Map<User, BigDecimal> createPlayerScores(List<User> users, List<Score> scores) {
    List<User> players = getPlayers(users);
    Map<User, BigDecimal> playerScores = new HashMap<User, BigDecimal>();

    for (Score score: scores) {
        User player = score.getPlayer();
        BigDecimal sumScore = score.getResult();
        if (playerScores.containsKey(player) {
            sumScore = sumScore.add(playerScores.get(player));
        }
        playerScores.put(player, sumScore);
    }
    Map<User, BigDecimal> filteredScores = new HashMap<User, BigDecimal>();
    for (User player : players) {
        filteredScores.put(player, playerScores.get(player));
    }
    return filteredScores;
}

I also change the name of the function/variable. They type system makes it obvious that you are dealing with a Map, you don't need to include it in the variable name. If the calling method has Lists and Maps that deal with players and scores, then it might be acceptable to include the type as part of the variable name.


Consider portable shell
The only Bash feature we're using is [[ ]]  for testing file properties.  It's easy to replace [[ -d $1 ]] with [ -d "$1" ] and that allows us to stick with standard shell, which is more portable and lower overhead:
#!/bin/sh

Careful with quoting
Most of shellcheck's output is due to failure to quote parameter expansions:
236052.sh:9:31: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:9:50: error: Delete trailing spaces after \ to break line (or use quotes for literal space). [SC1101]
236052.sh:10:5: warning: This flag is used as a command name. Bad line break or missing [ .. ]? [SC2215]
236052.sh:11:15: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:12:28: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:12:74: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:18:14: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:18:27: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016]
236052.sh:18:53: note: Expressions don't expand in single quotes, use double quotes for that. [SC2016]
236052.sh:18:75: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:22:16: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:23:20: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:24:16: note: Double quote to prevent globbing and word splitting. [SC2086]
236052.sh:26:12: note: Double quote to prevent globbing and word splitting. [SC2086]

Ironically, you do have quotes in some places they aren't strictly necessary, so it's unclear why you missed all these.
Errors go to standard output

echo "Argument missing"
exit 1

That should be:

echo >&2 "Argument missing"
exit 1

The test here is slightly wrong: the argument may be present, but not the name of a plain file or directory.  So I'd replace that with:
elif [ -e "$1" ]
    echo "$1: not a plain file or directory" >&2
    exit 1
elif [ "$1" ]
    echo "$1: file not found" >&2
    exit 1
else
    echo "Argument missing" >&2
    exit 1
fi

It may be worthwhile to move that testing into the resize function, because at present we assume that the contents found in directory arguments are plain files (that said, we're covering a tiny corner case with that, so I wouldn't sweat it - just let the commands there fail).
Don't assume previous commands succeeded
In resize, if ffmpeg fails, there's little point running exiftool, so connect them with &&.  Also consider removing the file if it was created with errors (so we're not fooled by a partly-written output into thinking this file doesn't need conversion).
Avoid temporary files
There's no need for the file /tmp/fl_$timestamp: we could simply use a pipeline there.
Consider accepting more arguments
Instead of only allowing a single argument (and ignoring all but the first), let the user specify as many files as needed; it's easy to loop over them using for.
Handle directories using recursion
Instead of the while loop, we could invoke our script recursively using xargs.  I'll make it a separate function for clarity:
resize_dir() {
    exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' |
        xargs -r -d '\n' -- "$0" || status=false
}

(xargs -r is a GNU extension to avoid running the command with no arguments.  If this option isn't available, we'll need to modify the script so that passing no arguments isn't an error.)

Modified code
This is Shellcheck-clean, but I'm not able to test it (lacking the requisite directory of MPEG files).
#!/bin/sh

set -eu

status=true
fail() {
    echo "$@" >&2
    status=false
}

# Resize a single file
resize() {
    echo "Filename $1"
    filename=$(basename -- "$1")
    extension=${filename##*.}
    filename=${filename%.*}
    new_filename=${filename}.${timestamp}.${extension}
    if
        ffmpeg -v quiet -stats -i "$1" -map_metadata 0 \
               -vf scale=-1:720 -c:v libx264 -crf 23 \
               -c:a copy "$new_filename" < /dev/null &&
            exiftool -TagsFromFile "$1" '-all:all>all:all' \
                     -overwrite_original "$new_filename"
    then
        # success
        true
    else
        # failed; destroy the evidence
        rm -f "$new_filename" 2>/dev/null
        fail "Failed to convert $1"
    fi
}

# Resize all *.mp4 files in a single directory
# N.B. only immediate contents; not recursive
resize_dir() {
    # shellcheck disable=SC2016
    exiftool "$1"/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' |
        xargs -r -d '\n' -- "$0" || status=false
}

[ $# -gt 0 ] || fail "Usage: $0 FILE FILE..."

timestamp=$(date +%s)

for arg
do
    if [ -d "$arg" ]
    then
        resize_dir "$arg"
    elif [ -f "$arg" ]
    then
        resize "$arg"
    elif [ -e "$arg" ]
    then
        fail "$arg: not a plain file or directory"
    else
        fail "$arg: file not found"
    fi
done

exec $status # true or false


Too many objects, too "deep" class structure?

I think you should definitely keep class structure as close as possible to actual data structure. So, for example, if your MainStep "contains" SequenceStep, you should reflect that in your code by using aggregation:

class MainStep
{
    public List<SequenceStep> SequenceSteps { get; set; }
    .....
}

etc...

If you want an easy access to some parts of your data, you should implement additional methods on highest level. For example, to iterate through SequenceSteps, you can implement following extension method:

public static IEnumerable<SequenceStep> GetSequenceSteps(this ConfigurationSheet sheet)
{
    foreach(var main in sheet.MainSteps)
    {
        foreach(var sub in main.SequenceSteps)
        {
            yield return sub;
        }
    }
}

(or you can use Linq).

I think the line sheet.ConfigurationRows[1].Arguments[120].Configurations.Tolerances.HighLimit is fine, as long as it reflects the actual data structure. Its definetely not the most complex thing in the world, far from it (mappings for complex databases often have way more layers of aggregation :) ). There is not much that can be done.

If you have control over your data, you can try to change its format to simplier one.
You can also try to move the logic to lower level, where possible. So it will look like row.Arguments[120].Configurations.Tolerances.HighLimit instead. Its hard to tell an exact refactoring without seeing the bigger picture. Using "shortcuts" for commonly accessed fields is fine as well, as long as you don't overdo it. Use extension methods for that where possible, so that class structure remains clear.
You can use shorter naming. Do you really need to have ConfigurationSheet.ConfigurationRow, for example? Isn't ConfigurationSheet.Row just as readable?
Also if Arguments is an equivalent of individual "cells", then using indexers makes sense: sheet[1][120]


Modelling user preference system with categories

I have used Postgres's arrays to build a system to avoid joins. NB. I'm not using proper keys at the moment for simplicity.

One person's simplicity is another person's denormalized nightmare. Are you avoiding joins because of some already-analysed performance rationale? If so, fine. But if it's based on superstition, this is probably premature optimization.

All of that is to say, the "traditional" normalized relational approach to this would be:

A user table with an integer primary key
A food table with an integer primary key
A meal table with an integer primary key
A preference table with foreign keys to user, food and meal

Don't be afraid of join. Or if you are, consider using a denormalized or "tabular" database like Mongo.


There are not much to say other than the usual missing argument null check:

It is valid to write the following:

  string test = null;
  test.RemoveDuplicateChars();

and RemoveDuplicateChars will be called with a null for the this argument text. Therefore you'll have to test for null:

public static string RemoveDuplicateChars(
    this string text, Func<string, string> normalizer = null)
{
  if (text == null)
    return text;

  ...

or throw an exception...

The default initialization  of normalizer could be a little less verbose:

  normalizer = normalizer ?? ((x) => x.Normalize());

A minor detail: Angstrom and Å: is also represented by \u00C5, which your code interprets as equal to Angstrom, but MS Word interprets them as different when using its Find-function?


A bug

This just won't work:

sys.exit(
    "'\033[1m%s\033[0m' is not a valid ten-digit clipcode," % i,
    "please check your input and try again.")

sys.exit takes a single integer parameter to use as the status code of the program, so that callers can check if the program terminated normally or failed.
I suppose you wanted to print instead and then sys.exit(1).

Move all code to methods

Don't keep code in the global namespace.
A good practice is to move everything to methods,
and call them from inside a if __name__ == "__main__": guard, like this:

def parse_args():
    # arg parser code

def main():
    args = parse_args()
    proxy = args.proxy
    clipcodes = args.clipcode

if __name__ == "__main__":
    main()

This way it will be possible to import the module into a larger app later.
Another advantage is that it doesn't pollute the global namespace,
which could lead to obscure bugs.

Use print() if you want to print

Printing with sys.stdout.write is very unusual and tedious.
Using print() is more common and simple.
If you don't want to print a newline, use the end='' flag, for example:

print(message, end='')

Naming

i is really a very poor name in this loop:

for i in CLIPCODES:
    if not i.isdigit() or not len(i) == 10:
        # ...

It would be better to use something more descriptive, for example clipcode.

Another thing here, not len(i) == 10 is a very odd way of writing len(i) != 10.

It's very unusual to see ALL_CAPS for variable names that are not global constants.
For example DEFAULT_PROXY_PORT = 8080 would make a fine global constant,
but these look really odd:

PARSER = argparse.ArgumentParser(...)
CLIPCODES = PARSER.parse_args().clipcode


Printing a singly linked list in reverse order

Even with such a short piece of code there is a lot to say.

Firstly, your example code is an example, designed to test just one piece of skill. A real list should never expose the fact that the implementation relies on a ListNode. In fact, your method is private, indicating that the detail is not public. The real printReverse method should have no argument, and should be public, because it should start with the head node of the list, and use that to start the recursive reverse print.

Also, that would be the right place to handle the nulls....

Recursive methods often (normally?) come in pairs, a setup method, and the actual recursive method. Your pair would look like:

public void printReverse() {
    if (head == null) {
        System.out.println("null");
    } else {
        printReverseRecursive(head);
    }
}

private void printReverseRecursive(ListNode node) {
    if (node == null) {
        return;
    }
    printReverseRecursive(node.next);
    System.out.print(node.val + " ");
}

Note, that while we are there, you have one of those wtf moments in your variable names. the name l1 is a really, really bad name. l is very easy to confuse with 1, and should never be used as a simple 1-letter variable name, and then, to make it worse, you put them together? Huh.


Swift append an array when it's been declared as Any

Since myDictionary values are declared as Any, you could have anything (or even nothing) assigned at "scores", so you need to safe-cast the value in to a variable first and then reassign it.

I don't know about Python, but Swift doesn't check dictionary values at compile time.


Project Euler #645 -- speed up Monte-Carlo simulation in Python

Welcome to Code Review. Nice implementation, easy to read and understand.
Optimization
There are some "expensive" operations that can be simplified. Below I commented the relevant parts:
def Exp(D):
    # the method "all" takes O(D)
    while all((d == 1 for d in day_list)) == False:
        # O(D)
        zero_ind = (i for i,v in enumerate(day_list) if v == 0)
        # O(D)
        for ind in zero_ind:
            # Here there are only O(1) operations
    return num_emperor

By \$O(D)\$ I mean that in the worst case such operation will iterate D times, where D is the number of days.
The condition in the while loop can be simplified by checking if the number of holidays is < days:
def Exp(D):
    holidays = 0
    while holidays < D:
        # increment holidays
    return num_emperor

The second optimization is to avoid the inner loops. Once the new birthday has been calculated, it's enough to "look around" that specific day:
def Exp(D):
    # ..
    while holidays < D:
        bday = np.random.randint(0,D)
        # Increment holidays only if birthday is not in a holiday
        if day_list[bday] == 0:
            holidays += 1
        day_list[bday] = 1
        num_emperor+=1

        yesterday = (bday - 1) % D
        day_before_yesterday = (bday - 2) % D
        if day_list[day_before_yesterday] == 1 and day_list[yesterday] == 0:
            day_list[yesterday] = 1
            holidays += 1

        tomorrow = (bday + 1) % D
        day_after_tomorrow = (bday + 2) % D
        if day_list[day_after_tomorrow] == 1 and day_list[tomorrow] == 0:
            day_list[tomorrow] = 1
            holidays += 1
    return num_emperor

The % operator prevents to overflow the array, so you don't need to catch exceptions.
Running the average:
avg_n_emperor = my_mean(monte_carlo(iters=1000,D=365))
# Output: 1173.786
# Running time: around 2 seconds

Regarding the style, @Peilonrayz already provided an excellent review.


Python 3.6 Dice Histogram: Using random.seed effectively

Various small comments:

you can write a[x+y] += 1
you always call random.seed with the same input so you'll always have the same output. You could call it with no value so that it uses the time (which is different from one run to another).
instead of having an explicit 13 at the end of your code, you could use len(a)
you could use a constant to store 100 to avoid having a magic number in the middle of your code
you could use a constant to store the number of faces per dice
you could initialise a by using list multiplication. In particular, you could reuse the constant introduced just before.

At this stage, you have:

NB_ITER = 100
DICE_MAX_NUM = 6

random.seed()

# declaring an array to count the occurrences
a= [0] * (2 * DICE_MAX_NUM + 1)

# looping and saving the count in array
for i in range(NB_ITER):
    val = random.randint(1, DICE_MAX_NUM) + random.randint(1, DICE_MAX_NUM)
    a[val] += 1

# printing histogram
for i in range(2, len(a)):
    print(str(i).rjust(2) + "s: ", "*" * a[i])

To be continued but you could use collections.Counter...


All possible groups of combinations of array

After spending more hours than I'd like to admit on trying to figure out your algorithm and why it is slow, and after multiple false epiphanies, thinking that I have finally discovered the weakness in your program, I believe that, now, I have really found out where the problem with your code lies. Considering all the drafts I've written for explaining where your algorithms wastes performances, trying to format it so that it is easy to read, and even trying out some LaTeX expressions, the emphasis on the word "painfully" becomes all the more justified when I say that the explanation for your algorithm's unsatisfactory performance is really painfully simple. So here goes … the reason your code is slow is:
$$...$$$$...$$$$j$$
Seriously, when the for loop that introduces int j is executed after the first time, it does nothing it hasn't already done the first time around. All local variables declared outside the loop except result (i.e. the method parameters) have the exact same values as they did during the first execution of the loop. I can't believe I didn't see this earlier.

But now that I'm writing an answer to this question, I will also tell you what I did to make the code a bit more read-/understandable (in my opinion). Since, inside the method body, only elements from initialArray with an index larger than or equal to i are queried, and i doesn't serve any other purpose than to mark this index, I've eliminated i altogether and adjusted the recursive calls so that they only pass a sublist of the array with the relevant elements:

public Set<Set<Set<Integer>>> recurseGroups(List<Integer> integerList, List<Set<Integer>> currentGroups) {
    if (integerList.isEmpty()) {
        // ...
    }

    for (int j = 0; j < integerList.size(); ++j) {
        // ...
        Set<Integer> newGroup = new HashSet<>(Collections.singletonList(integerList.get(0)));
        currentGroups.add(newGroup);
        result.addAll(recurseGroups(integerList.subList(1, integerList.size()), currentGroups));
        currentGroups.remove(newGroup);

        // ...
        for (int k = 0; k < currentGroups.size(); ++k) {
            currentGroups.get(k).add(integerList.get(0));
            result.addAll(recurseGroups(integerList.subList(1, integerList.size()), currentGroups));
            currentGroups.get(k).remove(integerList.get(0));
        }
    }

    // ...
}

That way, no information that isn't needed enters the method, which makes it easier to understand its workings.

Also, the following line is really unnecessarily complicated:

Set<Integer> newGroup = new HashSet<>(Collections.singletonList(integerList.get(0)));

This creates a List that is never used again and serves no other purpose than to save one line of code. You might as well do this:

Set<Integer> newGroup = new HashSet<>();
newGroup.add(integerList.get(0));

Even with two lines, it still takes up less characters than the above version, and it doesn't do more than it needs to do, hence easier to read.

That's it, now I really have to go to sleep. Happy coding!


tl;dr

The major reason for not doing this is that dynamically requiring modules breaks static analysis.

In a pure Node.js project, this does not have major repercussions aside from breaking IDE's autocompletion. Everything else will still work as expected.

diving deeper

Should this pattern be used in a webpack project for instance (targetting server or client), it would fail, as bundlers need to statically compute the dependency tree at compile-time.

The require() function  (CommonJS) was implemented in Node because, at the time, the core Javascript language didn't have the concept of modules. However this has changed, as ES modules are now available in all evergreen browsers, and in Node 13.x without a feature flag.

The new keywords import and export do not support variable interpolation for the purpose of static analysis, and are even required to be declared on top of the module. In practice, this makes the patterns if (dev) { require('debug') } or  require(name) unusable, once adapted to ES modules.

recommendation

In my opinion, this is a case where anything “clever” you try to make will just make the code harder to read and maintain. I've been down that path too, and I can tell you that the long-term costs are not worth the 2 seconds it will take you to add manual exports to your files. In my experience, reading code is 10 times more costly than writing it.

You also don't even have to create index.js loaders; you can require the files directly. Ryan Dahl, creator of Node, even said at JSConf 2018 that he considered the addition of index.js a mistake because “it needlessly complicated the module loading system.”

Good luck, and be kind to future-you.