Design of thread pool reuse with Executors.newFixedThreadPool in Java

Answers:

It is better to reuse the ExecutorService.  Destroying threads and then recreating this is expensive.  (The only scenario where destroying and recreating a pool might be advisable is when the pool is going to be unused for a long time, and physical memory usage is a problem.  But even then, some flavors of executor are able of shrinking the thread pool size when there is no demand.)
Well yes, that would be a problem.  But that really means that you should not call shutdown on an executor if you still may need to submit new tasks in it.
You can't reuse an executor after calling shutdown on it.
There should be no memory leaks ... apart from the fact that the idle threads themselves are using memory (for thread stacks), and will continue to use it until the executor is shut down.  For a fixed sized / bounded sized pool, that memory usage by threads is bounded.  Most people would not call a bounded memory usage a "leak".

In fact, not reusing an executor is likely to lead to a (real) memory leaks= if you somehow neglect to call shutdown on the executor.


How to refactor the boolean logic of this F# function?

I would avoid using Option .IsNone and .Value, mainly because .Value will throw an exception if you made a mistake and called it at the wrong time. Almost all F# code will avoid that property and use pattern matching instead or some other function.
Here's another way to write the patternPredicate function, which I renamed to includePath do describe what it actually does:
let includePath (includePattern: string option) (excludePattern: string option) path =
    let isIncluded =
        match includePattern with
        | Some includePattern -> matchWildcard includePattern path
        | None -> true
    let isExcluded =
        lazy
            match excludePattern with
            | Some excludePattern -> matchWildcard excludePattern path
            | None -> false
    isIncluded && not isExcluded.Value

My approach here was to first build up the values isIncluded and isExcluded so that we can write isIncluded && not isExcluded.Value. This breaks the problem down into understandable and explicit parts.
Note the use of a lazy value for isExcluded. This means that it won't be evaluated unless isIncluded is true, so we don't need to call matchWildcard unnecessarily.


I see a few things that might help you improve your code.

Declare local routines static

If you declare bitmap_get and the other routines as static, the compiler will know that they can never be called outside this one file.  With that information, much more agressive optimization can be done and the inline keyword will probably not even be needed.

Eliminate unused routine

The code defines a routine bitmap_set but it is not actually used and can be eliminated from the code.  Smaller code typically runs faster, so there's a small chance that this could improve speed as well.

Use calloc and reverse the sense of the bits

You could eliminate the initialization of all of the bits to 1 by using calloc instead of malloc and reversing the meaning of the bits in the bitmap.  On my Linux box, the times were about the same, but of course the calloc version was shorter.

Skip all even numbers

Your bitmap could be half the current size by simply eliminating the storage of even numbers.  The only even prime is 2, so your program doesn't really need to allocate bits for even numbers.

Optimize the inner loop

If we only test odd numbers, as per the last suggestion, we can also optimize the inner loop.  Once we know that i is an odd number, it's obvious that 2*i must be an even number, so there's no reason to mark it as non-prime since we already know that all even numbers except 2 are non-prime.  Using both suggestions, we can double the speed of both inner and outer loops by writing them like this:

for (int i = 3; i < sqrt(NUMBERS_TO_CALCULATE); i+=2)
{
    if (bitmap_get(bitmap, i - 2))
    {
        for (int j = 3 * i; j < NUMBERS_TO_CALCULATE; j += 2*i)
        {
            bitmap_unset(bitmap, j - 2);
        }
    }
}

Prefer portable constants

If you elect not to use calloc, you could still revise the way the constant is written.  At the moment, the code uses this:

bitmap[i] = 0xFFFFFFFFFFFFFFFFLL;

It would be shorter, less potentially error prone (quick -- how many F's should there be?) and easier to read like this:

bitmap[i] = ~0;

On my machine, using gcc as the compiler, they compile to the same thing.

Consider using pointers

On some compilers, depending on optimizations used, the use of pointers can be faster than using indexing.  You could test this on your machine with your compiler.  For example, the initialization loop could be written like this:

for (bitmap_entry_t *p = bitmap;
        p < &bitmap[(1 + NUMBERS_TO_CALCULATE / BITMAP_ENTRY_BITS)]; ++p)
{
    *p = ~0;
}

Optimize printing

As you may already know, it's the number conversion and printing of the results that takes most of the time for this program.  If that's of interest, you could write your own special purpose output formatter.  By keeping a static string array in memory and using that to increment through the numbers, you may be able to speed the entire program.


Kattis "Chasing Subs" custom decryption challenge

Alternative approach

You are repeating a lot of work.  Each time you advance a character, you rebuild the matching.  But you don't need to do that.  Instead create an array that says where to find the next instance of that character in the string.

public static int buildNextArray(String s) {
    int[] next = new int[s.length() - 1];
    for (int i = 0; i < next.length; i++) {
        next[i] = s.indexOf(s.charAt(i), i + 1) - i;
    }

    return next;
}

This converts the string into a unique array holding the relevant information:  how far away is the next instance of that character in the string?  Now, if the array you build for the decrypted key matches a portion of the array for the encrypted line, then it is a possible cipher match.

I'll leave the exact implementation for you to develop.  Note that a negative number in the array for the key may match an unequal number in the array for the line.  You may want to think about when it can match and when it can't match.

I would expect this approach to be faster because you can quickly see if a particular sequence matches by climbing the sequence for a particular letter.  Consider the case where the input is

  abcdefghijklmnopqrstuvwxyz
  abca

In your version, you would match the first three letters to all twenty-three possible sequences and only find out on the fourth letter that it didn't work.  With my suggestion, you would find out on the second letter that it won't work.  And while there may be some inputs for which this is slower, the general result will be faster.  Because starting with three or more different letters is more common than having the first and fourth letter the same.

It also saves the overhead of the HashSet and HashMap accesses.  Instead, you can do array accesses.

Some other coding comments that won't affect performance:

Code to the interface

            HashMap<Character, Character> dictionary = new HashMap<>();
            HashSet<Character> used = new HashSet<>();

This could be

            Map<Character, Character> dictionary = new HashMap<>();
            Set<Character> used = new HashSet<>();

It won't matter much here, but in general, you want to code to the interface.  It makes it easier to switch implementations later.

Delegate

        for (int i = 0; i < line.length() - key.length() + 1; i++) {
            HashMap<Character, Character> dictionary = new HashMap<>();
            HashSet<Character> used = new HashSet<>();

            for (int j = 0; j < key.length(); j++) {
                Character keyChar = key.charAt(j);
                Character sourceChar = line.charAt(i+j);

                if (dictionary.get(keyChar) == null) {
                    if (!used.contains(sourceChar)) {
                        dictionary.put(keyChar, sourceChar);
                        used.add(sourceChar);
                    }else{
                        break;
                    }
                } else if (!dictionary.get(keyChar).equals(sourceChar)) {
                    break;
                }

                if (j == key.length() - 1) {
                    counter++;
                    if (counter == 1) {
                        startIndex = i;
                    }
                }
            }
        }

This gets a lot simpler if you make a helper method.

    public bool canMatch(String haystack, String needle) {
        Map<Character, Character> dictionary = new HashMap<>();
        Set<Character> used = new HashSet<>();

        for (int j = 0; j < needle.length(); j++) {
            Character keyChar = needle.charAt(j);
            Character sourceChar = haystack.charAt(j);

            if (dictionary.get(keyChar) == null) {
                if (used.contains(sourceChar)) {
                    return false;
                }

                dictionary.put(keyChar, sourceChar);
                used.add(sourceChar);
            } else if (!dictionary.get(keyChar).equals(sourceChar)) {
                return false;
            }
        }

        return true;
    }

I flipped around some of the internal logic.  I find an if (false)/else structure confusing.  I would rather check truth.  And in this case, that also means that we can get rid of the else, as the original else clause finishes with a return (break).  This has a side effect of reducing the indent on the other clause, which can sometimes be helpful.

Now, if the needle matches, we can return true.  Otherwise, we return false.  This allows us to change the caller

    for (int i = 0; counter == 0 && i < 1 + line.length() - key.length(); i++) {
         if (canMatch(line.substring(i), key)) {
             counter++;
             startIndex = i;
         }
    }

    if (counter == 0) {
        return "0";
    }

    for (int i = startIndex + 1; i < 1 + line.length() - key.length(); i++) {
        if (canMatch(line.substring(i), key)) {
            counter++;
        }
    }

    if (counter == 1) {
        return line.substring(startIndex, startIndex + key.length());
    }

    return Integer.toString(counter);

Now we don't have to compare j to the last index of the key on every iteration.  The helper method will only return true when that was true.

I also changed the original method to return a string rather than print.  Then the caller can do the print.  This is a good habit that makes the method more flexible.  Of course, it would be even better if we returned something other than a string, perhaps a result object.


A haskell beginner using Control.Lens... Certainly better than my first program which happened to a tic tac toe solver, so I can compare. We all know Why functional programming matters, don't we?

Make your imports more specific:

import Control.Lens (set,ix)
import Data.List (transpose)
import Data.Maybe (catMaybes)

You will note I replaced your isNothing by pattern matching.
You only use type Position = (Int, Int) once. I would not declare this one.

instead of

    fDiag = zipWith (\ i x -> i !! (n - x - 1)) grid [0..]

I recommend

    fDiag = zipWith (!!) (reverse grid) [0..] -- or
    fDiag = zipWith (!!) grid [n-1,n-2..]

Why force isWin to take Game? Grid would suffice.
I suggest you to write a program that uses this module, then you know better.

OK, now for

move :: Game -> Position -> Game

I'd write

move :: Int -> Int -> Game -> Maybe Game

Instead of throwing an error, return Nothing. Then you can compute all possible moves with

moves :: Game -> [Game]
moves game = catMaybes [move x y game | x<-[0..2], y<-[0..2]]

and I put Game in the last position so you can compose functions like move 2 0 . move 1 1 $ newGame. Actually, that won't work because move now encapsulates in Maybe. But now you can write:

  test = Just newGame >>=
              move 1 1 >>= -- first move in center
              move 2 1 >>=
              move 2 0 >>=
              move 0 2 >>= -- forced
              move 0 0     -- setting up the trap

because Maybe is a monad, and >>= allows forward chaining instead of .! The modified move looks like this:

move :: Int -> Int -> Game -> Maybe Game
move i j (Game grid player) = case grid !! i !! j of
   Just _ -> Nothing
   Nothing -> Just $ Game {
     board = set (ix i . ix j) (Just player) grid,
     curTurn = nextPlayer player
  }

nextPlayer X = O
nextPlayer O = X

I also made nextPlayer a top level function, I'd export it, it looks useful.


When you add a number to its reverse, its value approximately doubles, on average.  If you do it 10000 times, you should get a result that is very roughly 210000 times the original. That will certainly overflow a long, which only holds values below 263.  You need to either

lower the iteration limit
check for overflow
use BigInteger
reinvent arithmetic for large numbers using strings or arrays

The use of OOP is awkward and inappropriate. Constructing an object should just involve just allocating and initializing some memory to model something. Your Main() constructor, though, is the entire input, calculation, and output loop of the program.

Your program isn't object-oriented at all. Just make everything static, and merge the constructor code into the main() function.


Breadth First Search to find connected primes

There are 3 major performance problems you currently have:

the primes is currently a list and every time you do something in primes - this is O(n) average-time complexity (where n is the length of primes) - define primes as a set instead
the visited is a list, same O(n) lookups - define it as a set instead
the del q[0] is also a O(n) operation - removing an element from the beginning of a list requires rearranging all following elements - use a collections.deque in place of a list for O(1) deletes from both ends (.popleft() for the left-end deletion)

Revised version (works for me in an instant for all the test inputs):

import math
from collections import deque

class Node:
    __slots__ = ['value', 'parent']

    def __init__(self, value, parent):
        self.value = value
        self.parent = parent

    def get_adjacent(self, primes):
        for i in powers_of_two:
            if self.value + i < upper_limit and self.parent != self.value + i and self.value + i in primes:
                yield Node(i + self.value, self)
            if self.value - i >= 2 and self.parent != self.value - i and self.value - i in primes:
                yield Node(self.value - i, self)

def sieve(n):
    numbers = list(range(0, n))
    for prime in numbers:
        if prime < 2:
            continue
        elif prime > n ** 0.5:
            break

        for i in range(prime ** 2, n, prime):
            numbers[i] = 0

    return {x for x in numbers if x > 1}

def bfs(f, to, primes):
    f = Node(f, None)

    q = deque([f])
    visited = set([f.value])
    while q:
        if q[0].value == to:
            return q[0]
        else:
            for x in q[0].get_adjacent(primes):
                # print(q[0].value, x.value)
                if x.value not in visited:
                    # print("added", x.value)
                    visited.add(x.value)
                    q.append(x)
        q.popleft()

if __name__ == '__main__':
    upper_limit, p, q = [int(x) for x in input().split(' ')]

    m = int(math.ceil(math.log2(upper_limit))) if math.log2(upper_limit) % 1 != 0 else int(math.log2(upper_limit))
    powers_of_two = [2 ** i for i in range(m)]

    primes = sieve(upper_limit)

    x = bfs(p, q, primes)

    counter = 0
    while x is not None:
        print(x.value)
        x = x.parent
        counter += 1

    print("--------------------")
    print(counter)

You can also see some other changes:

removed the while True loop (from what I understand you just need a single run)
using if __name__ == '__main__':
avoiding using globals and passing the primes set to the bfs() and get_adjacent() as an argument
using __slots__ for the Node class
used list unpacking for reading the input numbers
used upper_limit, p and q variables to increase readability (p and q variable names are used in the problem description)


Connecting to EC2 instances using the instance name instead of IP

It's mostly fine, but I would suggest some minor improvements.

Give a proper name to $1 early on, for example:

host=$1
if [ -z $host ]; then
  echo "Please enter machine name"
  return 1
fi

You use it in several places later and it will make the code more readable.

Instead of this:

if [ -z "${instance}" ]; then

you can use [[ ... ]] instead and drop the double quotes:

if [[ -z $instance ]]; then

This is a bit ugly:

ip=$(echo $instance | awk '{print $2}')
pem=$(echo $instance | awk '{print $1}')

It's ugly because you're spawning two awk processes for the same input. You could use a single read instead:

read pem ip junk <<< $instance

Or perhaps slightly cleaner to read into an array:

read -a arr <<< $instance
ip=${arr[1]}
pem=${arr[0]}

The array solution is especially good if the indexes of ip and pem are dynamic, for example if they come from variables:

read -a arr <<< $instance
# given: ip_idx=2 and pem_idx=1
ip=${arr[$ip_idx - 1]}
pem=${arr[$pem_idx - 1]}

(It would be cleaner to have the *_idx 0-based, but I used this example for the sake of illustrating simple arithmetics in array indexes.)

For the record, here's my earlier uglier awk solution:

set -- $(awk '{print $1, $2}' <<< $instance)
pem=$1
ip=$2

This is not as good as read, because it spawns an awk process, and it overwrites the positional parameters $1, $2, ... Other variants using $pem_idx and $ip_idx:

set -- $(awk "{print \$$pem_idx, \$$ip_idx}" <<< $instance)
# or:
set -- $(awk -v ip_idx=$ip_idx -v pem_idx=$pem_idx '{print $(pem_idx), $(ip_idx)}' <<< $instance)

In this code:

local curw
COMPREPLY=()
curw=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=($(compgen -W "${_sash_instances}" -- $curw))

The first COMPREPLY=() is unnecessary because you overwrite it soon after anyway.

Also, I think it's better to write local on the same line as the assignment:

local curw=${COMP_WORDS[COMP_CWORD]}

Actually, since the line fits within 80 characters, I'm not sure I would use the local curw at all:

COMPREPLY=($(compgen -W "${_sash_instances}" -- ${COMP_WORDS[COMP_CWORD]}))

The final return 0 is unnecessary if the last operation is successful. If the last operation is not successful, you probably want to let the function return failure anyway.


My take on this is the following:

rename the middleware to something meaningful (I took example from VerifyCsrfToken middleware)
throw exception if token is mismatched
rename checkToken to verify, reader of the code knows that code checks/verifies token because thats the point of the middleware
simplify even more verify function and add docblock
optimize the query to the following

select exists(select `id` from `tokens` where (`client` = 'Android' and `token` = 'OuK0ELzYkN3Ss9Zf')) as `exists`

So ApiAccess becomes following:

<?php

namespace App\Http\Middleware;

use App\Exceptions\TokenMismatchException;
use App\ApiToken;
use Closure;

class VerifyApiToken
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     * @throws \App\Exceptions\TokenMismatchException
     */
    public function handle(Request $request, Closure $next)
    {
        if ($this->verify($request)) {
            return $next($request);
        }

        throw new TokenMismatchException;
    }

    /**
     * Verify token by querying database for existence of the client:token pair specified in headers.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    public function verify($request): bool //optional return types
    {
        return ApiToken::select('id')->where([    // add select so Eloquent does not query for all fields
            'client' => $request->header('client'), // remove variable that is used only once
            'token'  => $request->header('token'),  // remove variable that is used only once
        ])->exists();
    }
}

Create new Exception, php artisan make:exception TokenMismatchException - yes kind of same as Laravel's stock one used when CSRF token is mismatched.

With body:

<?php

namespace App\Exceptions;

use Exception;

class TokenMismatchException extends Exception
{

    /**
     * Report the exception.
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response|null
     */
    public function render($request)
    {
        if ($request->wantsJson()) { // if request has `Accept: application/json` header present
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        return abort(403);
    }
}

  Note: remove use function response; statements because helpers are auto-loaded from Laravel's helpers


It seems like you may not quite grasp the interplay between do-notation and monad transformer stacks. Take a look at how I've rewritten program here to leverage the actual machinery of StateT. The version you wrote is needlessly verbose due to your manually plumbing the state around!

program :: StateT TodoList IO ()
program = do
    choice <- requestChoice
    parseChoice choice
    printList
    program

parseChoice can be cleaned up by favoring pattern matching over guards. Whenever you see a wall of guards that depend only on Eq, consider pattern matching instead.

parseChoice :: Text -> StateT TodoList IO ()
parseChoice choice =
    case split (== '|') (toLower choice) of
        ["add", date, message] -> addItem $ TodoItem date message
        ["remove", index]      -> removeItem $ parseInt index
        ["save", file]         -> saveList file
        ["load", file]         -> loadList file
        ["quit"]               -> lift exitSuccess
        (invalid:_)            -> invalidChoice invalid

I think you can probably guess what can change about removeItem after reading my other changes now, so before reading this next code block try rewriting it on your own.

removeItem :: Maybe Int -> StateT TodoList IO ()
removeItem Nothing  = lift $ putStrLn "Invalid index entered"
removeItem (Just n) = modify (removeAt n)


Since you mentioned morelinq in your question.  It does have the Batch method which is similar.  It's an IEnumerable<IEnumerable<TSource>> instead of IEnumerable<TSource[]> but if you look at the source code it's actually an IEnumerable of an array but you can't count on that as it's an implementation detail.

The only issue I see with your implementation is that source.GetEnumerator() returns back IEnumerator<T> which implements IDisposable and should be wrapped in a using statement.


Controlling parallel jobs with condition_variable

Overall
Unfortunately your code is broken.
The main thread can potentially call notify_all() twice before any of the threads are released from the first call wait(lock). Say I hit return several time very quickly.
It's even possible for the main thread to call notify_all() before any of  the children call wait(lock) the first time (what happens if I pipe a file into standard in).
If you want all threads and the main to wait and sync at a common point you must explicitly create what is called a sync barrier. This is usually done by having a variable that counts the threads that have reached the sync point and only allowing progress after all threads have reached it and decremented the counter to the point where it reaches 0.
To avoid confusion you will also need to use a separate condition_variable for sync and start points.
Finally this code will never finish.
for (auto& job : jobs) { job.join(); }

Waits for all the threads to finish. But none of the jobs ever exit the callback function work().
Note: you can't just remove this line. A thread who's destructor is called before the thread of execution finishes its work will generate an exception that causes the application to quit. So you should call join() on all threads to verify that the thread of execution has completed.
Design.
I understand the need to force all the children thread to wait at an initial sync point. They need to verify that the main thread has successfully initialized all the global state.
But after that each worker thread does not need to wait at a sync point (unless there is an application requirement to do so). It just needs to wait for work to become available grab it then do it. Once the work is done it is usual for a thread to check if there is more work available (as creating threads is rather expensive you usually don't want to create and destroy threads regularly). If no work is available then make it wait on a condition variable until there is work.
All threads should periodically check to see if they are still needed and expire when they are no longer required. Thus allowing the main thread to exit.
Simple Code Review
Global variables a re a bad idea.
std::mutex mx;
std::condition_variable global;
bool start = false;
bool ready = false;
std::map<int, std::atomic<bool>> status;

wrap all this up in a class that you can then use locally inside a function.
Don't do this.
using namespace std;

If your code is more than 10 lines long you are going to cause issues sooner or later. See: Why is “using namespace std;” considered bad practice?
Threaded job Queue.
The following is a generalized job queue.
Now I read in your question that you need to have work done in synchronized bursts. This class does not do that but with some small adjustments that can be done.
void JobQueue::jobWorker()
{
    while(true)
    {
        auto job = getWork();
        if (job.execute())
        {
            // Indicate a thread should exit by returning true from execute.
            break;
        }
    }
}

class JobQueue
{
    private:
       void jobWorker();
    public:

        // Both addWork()/getWork() modify internal state.
        // So calls must be synchronized via locks.
        template<typename F>
        void addWork(F&& work); // Adds a job to an internal queue.
        Job getWork();          // If no work is available will cause the
                                // thread to wait (on a condition variable)
                                // until there is work available.

         // Constructor initializes all internal state.
         // Then creates `count` threads of execution that call jobWorker.
         JobQueue(int count);

         // The destructor waits for all work (added via addWork())
         // to be finished.
         //
         // This means it must:
         // 1) wait for the work queue to drain.
         // 2) all threads must be given a job that will return true.
         //    This will allow all the worker threads to exit.
         // 3) Wait for all worker threads by calling join() on them.
         ~JobQueue();
};

Then main is simplified too:
int main()
{
    JobQueue    jobQueue(4);  // not much point it making this number
                              // larger than the number of cores available
                              // on your machine. Actually you can get a default
                              // value that is the number of cores.

    // Call addWork() as many times as required.
    for(int loop = 0;loop < 1'000'000;++loop) {
        jobQueue.addWork([](){std::cout << "Some Work\n";sleep(5);});
    }
}


Importing modules for private use in Python

NO
This is not pythonic... and this is ugly... aaah, I can't get that code out of my head...
There is this thing called __all__
1. How does it work
Make a list, put everything you want to make public in it and boom, you're done.
2. What it doesn't do
You will still be able to do my_module.datetime if datetime is imported in my_module
3. What does it do
When you do from my_module import *, it doesn't import datetime.  Autocomplete will use __all__ if it exist.
4. What are some great conventions that goes with this
You can put it in the __init__.py if it exists
5. Show me
Numpy uses the warning module but it doesn't pollute your namespace.
>>> import numpy
>>> 'warnings' in dir(numpy)
True
>>> 'warnings' in numpy.__all__
False
>>> from numpy import *
>>> warnings
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'warnings' is not defined

Update:
Every autocomplete in the world* uses __all__ except ipython which uses "some custom logic"(github issue). So I believe the most pythonic solution is go complain on the github issue.
*extrapolation of "the editors I use"


Using Python tricks to find Minimum Coin Change (Amazon Interview)

Welcome to Code Review! Your code looks fine, and is fairly easy to follow. A few points to note though:
Since your initial if-elif clauses are returning values immediately, no need to wrap an else (and even elif) there:
if n in coins:
    known_results[n] = 1
    return 1
if known_results[n] > 0:
    return known_results[n]
for i in [c for c in coins if c<=n]:
    .
    .

is achieving the same thing.
In python, multiple assignments can be done in a single statement:
known_results[n] = min_coins = count

As an aside, you can make use of type hinting to make the values and parameters more understandable. If I was only reading through the function definition, I'd have no idea what known_results was supposed to be.


General disclaimer: I have tried to find as many things in your code that you can fix, but I may not have found everything. Similarly, just because there may be a lot below doesn't mean the code is useless.

Before the review

I will be reviewing the code as posted on KhanAcademy, since I cannot get the code working here. I presume it is run through some kind of compiler. You are currently using an undefined function millis and use min and pow without the Math prefix, which makes those undefined in regular javascript as well.

Use a linter

You have completely disabled the linter in your code. I recommend against this, except for the cases where you have to include a dependency within your own code and cannot spare the time to rewrite it to the same code style you are using.

Linters force you to write consistent code. Their rules have been debated over and over, and their defaults are usually workable. If you do not like a certain rule, you can disable it, or change the rule. If you have a good reason to do something in a specific way and it trips a rule, you can disable that rule for that single line or single block.

KhanAcademy seems to use JSHint. You can find the documentation here. In your case you consistently don't use semicolons. I personally prefer to always use them, because they prevent typos from causing weird bugs, but you can tell JSHint to stop bugging you about it with // jshint asi: true. Most of the weird behaviour will be catched by other rules.

Readability

Naming your variables

The biggest issue with your code is the naming of your variables and functions. Variables and function names are the primary way of understanding what a piece of code does. Comments come second to elaborate on some expectations you have.

mm is used in the beginning. From the context I understand that this is the start time of your benchmark, so name it something like startTime.
Single letter variable names are usually a bad idea. S is used to define the dimensions of your grid. Lets just call it that: dimensions.
In your pick function, you use queue. A queue is a structure where you push things at the end and retrieve things from the beginning. Instead you pick a random element. A better name would be pool or collection or pickableRooms.
Variables with a number in them usually indicate that you should rename them. dir2 is no exception. Considering that it is in a createPath function, I assume that it is a direction. After reading the context, I think this is actually something like oppositeDirection.
pos2 is used just below that. Since it is going to point to the position in the direction given, lets call it adjecentPosition.
t in your redo function puzzles me. I think it is supposed to be the distance from the center, so lets call it distance.
The function name redo is unclear. You should replace it with what the function actually does, which seems to be to recalculate the distances for created rooms.

Unused variables

You have an unused variable in the argument list of your pick function. I am surprised the linter did not catch that. In any case, if you do not use an argument to a method in the method body, you should not include it in the signature.

If you would have used this argument array, you should have renamed it to what the variable actually contains, not its type. You could have used roomMatrix or distanceMatrix for example.

Odd bitwise NOT

You are using a double bitwise NOT operator in your code. After trying it out, I am guessing that this is some kind of operation to get the integer part of a float.

Since you never pass it negative numbers1, considering you are calculating an index, just use Math.floor for readability.

Indentation

Somewhere in your code you have the following lines:

var t = min(min(rooms[i-1][j],rooms[i][j-1]),
            min(rooms[i+1][j],rooms[i][j+1]))

I think there are two things wrong with those two lines:

You are manually aligning the two lines. Don't do this, because when you start using version control it will bite you. Lines that have not been changed should not be changed, because they cause merge conflicts and cause lines to show up in commits that have only whitespace changes.
If you put an opening brace at a certain indentation, you should put the closing brace at the same indentation. This goes for [, { and (.

The following code is better readable, and highlights that you believe that you can only use two arguments in the Math.min(..) function, which is not the case.

var t = min(
  min(rooms[i-1][j],rooms[i][j-1]),
  min(rooms[i+1][j],rooms[i][j+1])
)

So we can change it to the following code, which makes it clear that you want to actually get the minimum of all adjacent rooms.

var t = min(
  rooms[i-1][j],
  rooms[i][j-1],
  rooms[i+1][j],
  rooms[i][j+1]
)

Code structuring

Functions

You have put part of your code into functions. A notable exception is the initialisation code. Consider moving it to it's own function.

Function syntax

The syntax var a = function (arguments) is a bit odd. It nicely demonstrates that a function is actually a variable that you can call, but it does not seem very useful in this case. Consider just using function a (arguments).

I noticed that KhanAcademy finds this wrong syntax. I am clueless why this is.

Abstract away the underlying data structure

Your functions all interact with the underlying data structure in some way or another. You are currently also not checking for any errors. Once you start doing that, you will probably notice that you are duplicating code.

You probably want to hide the implementation of getting adjacent rooms to separate functions, such as north, and add error handling in there to handle cases where you are trying to get a room outside the boundaries.

Working of the program

Overlapping squares

Because of how you are calculating the width, you are adding up errors on the width of your squares, causing some of them to be off by one pixel.

Any easy way of dealing with that is by calculating an effective width and height, and use that everywhere:

var effectiveWidth = floor(width / dimensions)
var effectiveHeight = floor(height / dimensions)

and

for (var i = 0; i < dimensions; i++) {
  for (var j = 0; j < dimensions; j++) {
    if (rooms[i][j] !== Infinity) {
      fill(rooms[i][j] * 255 / dimensions, 255, 255)
      rect(i * effectiveWidth, j * effectiveHeight, effectiveWidth, effectiveHeight)
    }
  }
}

The dimensions constant

You have a constant that defines on what grid we are playing. Except that you 'auto-correct' it. Don't produce erroneous behaviour when wrong input is given, but instead just give an error.

var dimensions = 6

if (dimensions % 2 !== 0) {
  throw new Error('Dimensions must be even')
}

You are off by one... twice

When you set dimensions to 4, you can have a maximum of 2 by 2 rooms. When you set it to 6, you can have a maximum of 4 by 4 rooms. You'll notice that the center is therefore also never in the center.

What you actually want is to have the dimensions to be odd, so you can actually get the middle. Then you have to loop over all possible rooms. Then you just have to check if you are trying to find the value of a room outside the grid, and return Infinity in that case.

The result

//The "rainbow" part represents the distance from the center "room" (the reddest square) to the colored room.

//jshint asi: true

var startTime = millis()

var rooms = []
var paths = []
var dimensions = 5
var numberOfRooms = Math.floor(pow(dimensions, 2))
var padding = 20

var startX = Math.floor(dimensions / 2)
var startY = Math.floor(dimensions / 2)

var squareWidth = floor((width - padding * 2) / dimensions)
var squareHeight = floor((height - padding * 2) / dimensions)

if (dimensions % 2 !== 1) {
  throw new Error('dimensions should be odd')
}

var initialize = function() {
  for (var i = 0; i < dimensions; i++) {
    rooms[i] = []
    paths[i] = []
    for (var j = 0; j < dimensions; j++) {
      rooms[i][j] = Infinity
      paths[i][j] = [false, false, false, false] // up, right, down, left
    }
  }
}

var north = function(pos) {
  if (pos[1] === 0) {
    return Infinity
  }

  return rooms[pos[0]][pos[1] - 1]
}

var west = function(pos) {
  if (pos[0] === 0) {
    return Infinity
  }

  return rooms[pos[0] - 1][pos[1]]
}

var south = function(pos) {
  if (pos[1] === dimensions - 1) {
    return Infinity
  }

  return rooms[pos[0]][pos[1] + 1]
}

var east = function(pos) {
  if (pos[0] === dimensions - 1) {
    return Infinity
  }

  return rooms[pos[0] + 1][pos[1]]
}

var pickRandomRoom = function() {
  var pool = []

  for (var i = 0; i < dimensions; i++) {
    for (var j = 0; j < dimensions; j++) {
      if (rooms[i][j] === Infinity) {
        var pos = [i, j]

        var t = min(
          north(pos),
          west(pos),
          south(pos),
          east(pos)
        )

        if (t < Infinity) {
          pool.push([i, j, pow(dimensions, 2)])
        }
      }
    }
  }

  return pool[Math.floor(Math.random() * pool.length)]
}

var createRoom = function(pos) {
  rooms[pos[0]][pos[1]] = pos[2]
}

var createPath = function(pos, dir) {
  var oppositeDirection = (dir + 2) % 4
  var adjacentPosition = [pos[0], pos[1]]
  paths[pos[0]][pos[1]][dir] = true
  switch (dir) { //there's gotta be some better way to do this
    case 0:
      adjacentPosition[0]--
        break
    case 1:
      adjacentPosition[1]--
        break
    case 2:
      adjacentPosition[0]++
        break
    case 3:
      adjacentPosition[1]++
        break
  }
  paths[adjacentPosition[0]][adjacentPosition[1]][oppositeDirection] = true
}

var drawRooms = function() {
  pushMatrix()
  //scale(4.0)
  colorMode(HSB)
  background(255, 0, 255)

  //noStroke()
  for (var i = 0; i < dimensions; i++) {
    for (var j = 0; j < dimensions; j++) {
      if (rooms[i][j] !== Infinity) {
        fill(rooms[i][j] * 255 / dimensions, 255, 255)
        rect(
          padding + i * squareWidth,
          padding + j * squareHeight,
          squareWidth,
          squareHeight
        )
      }
    }
  }
  popMatrix()
}

var recalculateDistances = function(x, y, distance) {
  if (
    x >= 0 &&
    x < dimensions &&
    y >= 0 &&
    y < dimensions &&
    rooms[x][y] !== Infinity &&
    rooms[x][y] > distance
  ) {
    rooms[x][y] = distance
    distance += 1
    recalculateDistances(x, y + 1, distance)
    recalculateDistances(x + 1, y, distance)
    recalculateDistances(x, y - 1, distance)
    recalculateDistances(x - 1, y, distance)
  }
}

initialize()
createRoom([startX, startY, 1])
for (var i = 0; i < numberOfRooms - 1; i++) {
  createRoom(pickRandomRoom())
}
recalculateDistances(startX, startY, 0)

drawRooms()
fill(0)
var benchmark = millis() - startTime
text('Took ' + benchmark + ' milliseconds to run.', 10, 10)

Or as working on KhanAcademy

Footnotes

1 Math.floor returns the highest integer smaller than the argument passed to it, so Math.floor(-1.5) === -2. The bitwise not trick returns something different: ~~-1.5 === -1. Add a comment to these kind of tricks so your future self does not have to figure out what such an odd trick does.


Function to get type of the value entered in a textbox

Here's what you can do:

Since you are not using the out var variable you can remove them altogether and use the discard character which is the underscore to just ignore them _.
I usually prefer to use {} in ifs but this method is so short and all conditions are so similar that I'd make them one-liners.
Don't call the parameter inputValue but simply value. It might be an input outside but inside this method input has no meaning. The value can come from any source.
Don't return a string but let the user of this method do with the Type whatever he likes or call this method GetTypeName so its purpose is clear.

Example:

public Type GetType(string value)
{
    if (int.TryParse(value, out _)) return typeof(int);
    if (decimal.TryParse(value, out _)) return typeof(decimal);
    if (bool.TryParse(value, out _)) return typeof(bool);

    //If all parse fails, return string type.
    return typeof(string);
}


You could simplify with Regular Expressions:

Pattern pattern = Pattern.compile("log-(\\d+)sr");
Matcher matcher = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();
while(matcher.find()) {
  Long value = Long.parseLong(matcher.group(1), 10);
  Long increased = value + 100;
  matcher.appendReplacement(buffer, increased.toString());
}
System.out.println(buffer.toString());


I've cleaned up my CloseTabAction class see below:

I took out the method 'Implements' because the interface is attached to my BaseViewModel so I know that every VM will have it, no need to check.

I created a new method to check if the content is dirty. Rather than putting it in my Invoke method. From there I raise my dialog and get the results back.

It still may need some work, but it's much better now.

internal class CloseTabAction : TriggerAction<Button>
{
    protected override void Invoke(object parameter)
    {
        var args = parameter as RoutedEventArgs;
        if (args == null) return;

        var tabItem = FindParent<TabItem>(args.OriginalSource as DependencyObject);
        if (tabItem == null) return;

        var tabControl = FindParent<TabControl>(tabItem);
        if (tabControl == null) return;

        var region = RegionManager.GetObservableRegion(tabControl).Value;
        if (region == null) return;

        var content = Implementor<IRequestTabItemClose>(tabItem.Content);

        if (IsDirty(content))
        {
            content?.ConfirmCloseRequest((canSave, cancel) =>
            {
                if (cancel) return;
                if (canSave)
                {
                    content.SaveContent();
                    region.Remove(tabItem.Content);
                    return;
                }
                region.Remove(tabItem.Content);
            });
        }
        else
        {
            region.Remove(tabItem.Content);
        }
    }

    private static bool IsDirty(IRequestTabItemClose content)
    {
        var isContentDirty = false;

        content?.IsContentDirty(isDirty =>
        {
            if (isDirty)
                isContentDirty = true;
        });
        return isContentDirty;
    }

    private static T FindParent<T>(DependencyObject child) where T : DependencyObject
    {
        while (true)
        {
            var parentObject = VisualTreeHelper.GetParent(child);

            if (parentObject == null) return null;

            var parent = parentObject as T;
            if (parent != null) return parent;

            child = parentObject;
        }
    }

    private static T Implementor<T>(object content) where T : class
    {
        T implementor = content as T;
        if (implementor != null) return implementor;

        var element = content as FrameworkElement;
        if (element != null) implementor = element.DataContext as T;
        return implementor;
    }
}


Algorithm A seems the clearest to me.  An improvement might be to use Vec::with_capacity to avoid the allocation.  Indeed, arrays in Rust are currently somewhat cumbersome to use.
My advice would be to wrap it in a function and not worry about it later on:
pub fn to_bytes(input: &[u32]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(4 * input.len());

    for value in input {
        bytes.extend(&value.to_be_bytes());
    }

    bytes
}

#[cfg(test)]
mod tests {
    #[test]
    fn to_bytes() {
        use super::*;

        assert_eq!(to_bytes(&[]), &[]);

        let input = &[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
        let output = &[
            0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 0x89, 0x98, 0xBA, 0xDC, 0xFE, 0x10, 0x32,
            0x54, 0x76, 0xC3, 0xD2, 0xE1, 0xF0,
        ];

        assert_eq!(to_bytes(input), output);
    }
}

(playground)


Finding roughly matching genome sequences in Python dictionary

You need a faster search method

You are comparing every entry in duplexDict directly with every entry in duplexDict. This means the number of operations will increase with the square of the number of entries in duplexDict. This stands out from the lines:

    for i in duplexDict:
        ...
        for j in duplexDict:

More formally, you algorithm runs in \$\mathcal{O}(n^2)\$, where n is the length of the input dictionary. So, for 500 million (5e8) reads of sequence data, you need to run about 250 thousand trillion (25e16) operations. This is why it takes days to run.

You will need to index your reads based on the sequences themselves. Find and implement an architecture, whether hash tables, binary trees, or something else, that allows fast searching of the input list of sequencing reads.

Of course, a hashing method is built-in with Python's dict. There is no hard limit on the length of the key strings, and the number of entries you can put in the dict is limited by available memory.

Using dictionary search

In your case, in order to use Python's built-in dictionary to make and search the hash table, you might first do something like this:

seq_dict = {}
for i in duplexDict:
    seq_dict[i['seq']] = {info: i['header']}  # add whatever info you need to find
                                              # the original entry again in `duplexDict`}

The resulting dictionary has the sequences themselves as the keys. Searching for a particular sequence takes \$\mathcal{O}(1)\$ operations.

(Note: I am assuming you need to be able to refer back to the original duplexDict once you have your hits. Then, you don't need all of the extra information to accompany the sequencing reads in the new dictionary. If each entry in duplexDict has an identifier like umi, just put that alone as the value in the new dictionary.)

Generate mismatches and search

As you are only looking for sequences different by one base, you can just generate all possible mismatches. If you eventually want to include other types of sequence similarity, you will need to use more specialized sequence analysis tools (such as BLAST).

So, you will need a simple function to generate all possible one-base-pair mismatches from each input sequence. Assuming you are using only genomic bases A,T,C,G, for each sequence, there will be 3 x n possible one-base-pair mismatches, where n is the length of the sequencing reads.

def get_one_bp_mismatches(seq):
    mismatches = []
    bases = ['A','T','G','C']
    for e,i in enumerate(seq):
        for b in bases:
            mismatches.append(seq[:e] + b + seq[e+1:])
    return mismatches

Then, search the dictionary like this:

for seq_list,info in [get_one_bp_mismatches(i['seq']),i['info'] for i in duplexDict.items()]:
    for seq in seq_list:
        if seq in seq_dict:
            finalList.append({'search_seq': info,
                              'found_seq': seq_dict[seq]['info']})

Your finalList will contain all matching pairs, identified by whatever information you use to look them up in the original duplexDict.

The whole search process will take on the order of \$\mathcal{O}(n)\$ operations, and should likely finish within minutes for 500 million sequencing reads. You can then use the last lines of your existing code to generate the output file.


Finding the indices where a selected player appears in a list of hashes

Your current code is calling an \$O(n)\$ function \$n\$ times. This leads to \$O(n^2)\$ time complexity on the whole. Instead I'd make a function to change pwsarr to a Hash, where the key is the player name, and the value is a list of 'player objects'. This can then cause your program to be \$O(n)\$ as hash lookup is \$O(1)\$.

The loop can then become: (I don't know Ruby.)

pwsarr = [
    {'player'=>'first1 last1', 'stat'=>0.0},
    {'player'=>'first1 last1', 'stat'=>2.0},
    {'player'=>'first2 last2', 'stat'=>0.0}
]

def group_by(list_hash, key)
    h = Hash.new { |hash,key| hash[key] = [] }

    for hash in list_hash do
        h[hash[key]].push(hash)
    end
    h
end

pws_by_player = group_by(pwsarr, 'player')
for player in pwsarr do
    puts pws_by_player[player['player']]
end


shared_ptr and FILE for wrapping cstdio (update: also dlfcn.h)

I should start with the fact that I don't entirely agree with the widespread belief that "explicit is better than implicit". I think in this case, it's probably at least as good to have a class that just implicitly converts to the right type:

class file {
    typedef FILE *ptr;

    ptr wrapped_file;
public:
    file(std::string const &name, std::string const &mode = std::string("r")) :
        wrapped_file(fopen(name.c_str(), mode.c_str()))
    { }

    operator ptr() const { return wrapped_file; }

    ~file() { if (wrapped_file) fclose(wrapped_file); }
};

I haven't tried to make this movable, but the same general idea would apply if you did. This has (among other things) the advantage that you work with a file directly as a file, rather than having the ugly (and mostly pointless) .get() wart, so code would be something like:

file f("myfile.txt", "w");

if (!f) {
   fprintf(stderr, "Unable to open file\n");
   return 0;
}

fprintf(f, "Hello world");

This has a couple of advantages. The aforementioned cleanliness is a fairly important one. Another is the fact that the user now has a fairly normal object type, so if they want to use overloading roughly like they would with an ostream, that's pretty easy as well:

file &operator<<(file &f, my_type const &data) {
    return data.write(f);
}

// ...

file f("whatever", "w");
f << someObject;

In short, if the user wants to do C-style I/O, that works fine. If s/he prefers to do I/O more like iostreams use, a lot of that is pretty easy to support as well. Most of it is still just syntactic sugar though, so it generally won't impose any overhead compare to using a FILE * directly.


Converting a natural number to a permutation matrix in Python. How to speed it up perhaps avoiding messing around with lists, sets and dicts?

I haven't really tried to follow your code, but it sounds like you're complicating things unnecessarily by talking about "permutation matrices" instead of just "permutations." IIUC, it's trivial to get from a permutation matrix to a permutation or vice versa. The hard part is getting from an integer index ("give me the 42nd permutation of these elements") to the actual permutation.

So, the non-trivial functions you're looking for are

def nth_permutation(num_elements, which):
    [...]

def index_of_permutation(num_elements, which):
    [...]

The speedy algorithm for nth_permutation is described here (with C and PHP code)
and here in Python, although apparently the first version doesn't produce permutations in the traditional order and the second version is quadratic.

On your actual code, I'm confused by this passage:

    res, bit = divmod(res, base)
    if res + bit == 0:
        bit = 0

How can res + bit == 0, unless (res == 0) and (bit == 0)? But if (bit == 0), then it's redundant to assign bit = 0.

I also don't understand the significance of 35. Is it significant that there are 10+26-1 non-zero "digits" available in base 36? If 35 was picked completely at random, then you should really make it a parameter to the function. It'd be what I called num_elements in my signatures above.

Trivial nit: you forgot

from operator import itemgetter

big_number = digits[0]
pos = 0
base = b = 35
for digit in digits[1:]:
    big_number += b * digit
    pos += 1
    base -= 1
    b *= base

This looks suspiciously like "convert string to int." Is this essentially equivalent to

alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXY"
big_string = ''.join([alphabet[i] for i in digits])
big_number = int(big_string[::-1]], 35)

?


I can't think of any way the file size could change without the mtime
changing too. On the other hand, it does no harm to check, aside from
making the code a little more complex.

You use the expression backup_loc + subpath quite often, so I would do
this:

subpath = root.replace('/home/prahlad/','')   # note extra slash
backup_path = os.path.join(backup_loc, subpath)
...
dfilename = os.path.join(backup_path, f)
...
if not os.path.exists(backup_path):
    os.makedirs(backup_path)
    print 'creating directory: ' + backup_path

For these lines, I would do one thing per line, and move the complex
expression into a function:

sz = os.path.getsize(filename); lm = datetime.fromtimestamp(os.path.getmtime(filename)).timetuple()
dsz = os.path.getsize(dfilename); dlm = datetime.fromtimestamp(os.path.getmtime(dfilename)).timetuple()

As follows:

def file_mtime(path):
    return datetime.fromtimestamp(os.path.getmtime(path)).timetuple()
...
sz = os.path.getsize(filename)
lm = file_mtime(filename)
dsz = os.path.getsize(dfilename);
dlm = file_mtime(dfilename)

However, since you're only comparing one timestamp to another, and not
doing anything else with the timestamps, I don't see why you couldn't
just do this:

lm = os.path.getmtime(filename)
...
dlm = os.path.getmtime(dfilename)

time.clock() returns time in seconds, not minutes; and num is
already an int; so:

mins = round((time.clock() - start) / 60)
print "{0} files copied in {1} minutes".format(num, int(mins))


Calculating the font size to fit the width of a website

Use strict-mode

Start your code with "use strict";:
https://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it

Don't pollute the global namespace

When you don't use var x; to declare a variable, it is implicitly declared in the global namespace. If another script does the same, both scripts will be using the same variable.

It is not very easy for this to happen with an odd name like newWidthGhost, but fontHeight sounds like a better candidate for these surprises.

Run the code through JSLint

Run your code through JSlint, and try to understand the errors and suggestions it gives you.

That alone will greatly improve the quality of your code.


I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view.

Let the client, its view, its display control, or whatever sort the items according to its needs.


I suggested to think about following:

Extract every step into the separate asynchronous method
Think about more careful locking technique. Asynchronous operations by its nature could be long running and using global write lock can degrade performance dramatically. Maybe its possible acquire locks only during processing results.
Global exception handling: in general global exception handling is a code smell. Its really hard to create generic logic for different operations. I suggested to use such techniques with some tools like MEF, but avoid using its manually.

Here slightly modified version of your code:

private static Task GetDistributorBackpressure44LogicAsync()
{
  Task.Factory.StartNew( () =>
  {
    using (DistributorBackpressure44Logic logic = new DistributorBackpressure44Logic())
                logic.RefreshDistributorBackpressure44Cache();
  }
}

private static Task DeltaPressureLogicAsync()
{
  Task.Factory.StartNew(() =>
  {
    using (DeltaPressureLogic logic = new DeltaPressureLogic())
                logic.RefreshDeltaPressureCache();
  }
}

public static void RefreshCoaterCaches()
{
    try
    {
        CicApplication.CoaterDataLock.EnterWriteLock();

        var t1 = GetDistributorBackpressure44LogicAsync();
        var t2 = DeltaPressureLogicAsync();

        // You can switch back to you list-based approach if you'll have
        // much more other operations
        Task.WaitAll(t1, t2);
    }
    catch (System.AggregateException exception)
    {
        // I'm really not sure that its a good idea to create "generic"
        // exception handling scheme. Maybe you should handle them manually right here.
        // And what is string.Empty is all about?
        CicServerLogic.HandleUnexpectedAggregateException(exception.Flatten(), string.Empty);
    }
    // You should not catch System.Exception thats why I removed it
    finally
    {
        CicApplication.CoaterDataLock.ExitWriteLock();
    }
}

Now, about your generic exception handler (I mentioned already that this technique can lead to errors hiding and complicated "generic" logic) (see my comments right in the code):

internal static void HandleUnexpectedAggregateException(AggregateException aggregateException)
{
    // What are we afraiding of, why we're using try/catch here?
    // We should now swallow unknown exception because it can lead to
    // hiding bugs in our code!
    try
    {
        // This technique is ok
        foreach (Exception exception in aggregateException.InnerExceptions)
        {
         ...
         ...
         Do some stuff with the current exception, like logging etc.
         ...
        }
    }
    catch (Exception)
    {
       // I strongly not recommended to use empty catch blocks!!
    }
}


A class to store the number of seconds since midnight

Your validation is too strict, as a minute can sometimes have 61 seconds. Limiting it to 60 seconds is what causes computer crashes during leap seconds.

To avoid code duplication, the Time(hour, minute, second) constructor should just do:

public Time(int hour, int minute, int second) {
    this.setHour(hour);
    this.setMinute(minute);
    this.setSecond(second);
}

Your spacing is a bit weird here:

return String .format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond());

It would be more conventional to write:

return String.format("%02d:%02d:%02d", getHour(), getMinute(), getSecond());


I have to agree with Corbin, while I would be annoyed if my email address got leaked, I would not be overly concerned. Spam filters are pretty decent now, and without a password all they can do is spam me. Or, if I have a gmail account, WoW hackers can find more loopholes that allows them to spam FROM my address. I don't even play WoW anymore, I wish they'd just leave me alone -.- Anyways...

This looks like sample code, so there's not much I can help with. I would suggest that you be sure to escape early whenever possible. For instance, in the first if statement. This ensures there is no wasted processes parsing code that ins't necessary. Also, not sure how much of a difference this would make, but I believe your email comparison should be absolute, not loose.

if( $email_test === $hash_email ) {

Only other thing I can think of is using extract() to get those array indices. But there's a couple of problems with that. First, its not always well liked by the community. Second, it dumps the entire array index list into the function's local variable scope, which is sometimes unnecessary and may lead to security issues. I only bring this up because if these are the only two fields in this table then there shouldn't be any issues here. As for speed, I'm not sure, you'd have to profile it.

The biggest thing here is premature optimization. Yes, its nice to plan ahead, but ask yourself this: How likely is it that your database will ever reach a size where this will become an issue? Every developer dreams that their creation will be the next biggest thing and will have millions of viewers, but the likelihood is slim. Plus, with regular maintenance and periodic deletion of inactive accounts will help ensure that the size, even in these extreme cases, is less likely to become a factor.


There is already a JavaScript function to aggregate values in an array: array.reduce(). You can use it like this:

const invalidValueForItem2 = -9999;

let result = {
    item1: { sum: 0, count: 0},
    item2: { sum: 0, count: 0},
};

result = array.reduce(function(acc, item) {
    acc.item1.sum += item.Item1;
    ++acc.item1.count;

    if (item.Item2 != invalidValueForItem2) {
        acc.item2.sum += item.Item2;
        ++acc.item2.count;
    }
}, result);

Using an object to hold your temporary data we may scale better when you will need more properties and/or if you will average all properties without any knowledge about them. Don't you need to average both Item1 and Item2? Just drop the outer object and keep { sum: 0, count: 0}:

let result = { sum: 0, count: 0};

result = array.reduce(function(acc, item) {
    if (item.Item2 != invalidValueForItem2) {
        acc.sum += item.Item2;
        ++acc.count;
    }
}, result);

Now you have your result you can calculate the average:

const average2 = result.item2.count > 0 ? (result.item2.sum / result.item2.count) : NaN;

Do not forget to handle the corner case where there aren't items to sum, in this example when there aren't items the average is NaN (but you might want 0), if Infinity is appropriate then just make the division.

Few more notes about your code:

Indentation is incredibly important. Write just few hundred lines without proper indentation and you won't be able to understand what your code is doing without re-reading everything (and probably introducing bugs here and there).

Unless you have to support older browser you'd better use let instead of var (and const where appropriate).

Let your code breath, add space (both horizontally and vertically) and it will be much easier to read. To make code unreadable but small is the job of Minifiers/Uglifiers! Compare this with your original call to reduce():

var avg1 = array.reduce(function(sum, a, i, ar) {
    sum += a.item1;
    return i == ar.length - 1 ? (ar.length == 0 ? 0 : sum / ar.length) : sum;
}, 0);

Those lines let me introduce few more things:

Do not nest ternary operators unless you're dealing with incredibly simple expressions.

You do not need all the parameters of the reduce() function (ar is just array) then it might be function(sum, a). Also you'd better find a meaningful name for a (especially in this case because function documentation talks about an accunulator then it may be misleading if you do not work often with it). Removing i will also stop you to do two things in this function (accumulate the sum and then return the average for the last one).

If your accumulator is a number (initialized to zero) then you do not need to explicitly give it as parameter.

How can you rewrite this? Just few lines when using an arrow function:

let sum = array.reduce((acc, item) => acc + item.item1);
let average = sum / array.length;

However you won't need this code because average for Item1 is calculated together with Item2, use this code for simpler cases.


To use the modulo in equations, You need to maintain the equivalence of the Equation. The Equation you wrote in comment is not according to equivalence. See Division Under Equivalences

So, going by the equivalence you have to calculate it like this :

  [ ( (n) %x ) * ( (n+1) %x ) * ( ( 2*n + 1 ) %x ) ) * ( (1/6)%x ) ] %x

Have a look at this.

Note that this will not work If given n is any multiple of x. So, n & x must be Co-prime. In your case, x = 10234573 is already a prime number as pointed by Toby's Comment


As stated by 200_success +1 string is immutable

StringBuilder also has Replace but getting it to loop is trickier
You would need to time this

string s = "Pibabakekezza";
string r = "bake";
StringBuilder sb = new StringBuilder(s);
while (sb.Length != sb.Replace(r, "").Length) { }
Debug.WriteLine(sb.ToString());

A character can only be:

start of replace
in replace
other

Not real clean code - this is more just the algorithm
I know should use { } on every if else
Store partial matches in a Stack
I tested with a very large hard input and it was 40 milliseconds

public static void QuickReplaceTest()
{
    string s = "Pibabakekezza";
    string r = "bake";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    s = "babakekePbakeibabbakeakebakekezbakezabake";
    r = "b";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    StringBuilder sb = new StringBuilder();
    sb.Append("piz");
    for (int i = 0; i < 100000; i++)
        sb.Append("qrsuvw");
    //sb.Append("piz");
    for (int i = 0; i < 100000; i++)
        sb.Append("xyz");
    sb.Append("za");
    s = sb.ToString();
    sb.Clear();
    r = "qrsuvwxyz";
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

    s = s.Insert(400000, "pie");
    Debug.WriteLine(QuickReplace2(s, r));
    Debug.WriteLine(QuickReplace3(s, r));

}
public static string QuickReplace2(string s, string r)
{
    if(string.IsNullOrEmpty(r))
        return string.Empty;
    if (string.IsNullOrEmpty(s))
        return string.Empty;
    s = s.Trim();
    r = r.Trim();
    if (r.Length > s.Length)
        return string.Empty;
    if (r.Length == 1)
        return(s.Replace(r, ""));

    StringBuilder sb = new StringBuilder(s.Length / 2);
    char[] rArray = r.ToCharArray();
    int rArrayLen = rArray.Length;
    Stack<byte> partialMatches = new Stack<byte>();
    byte curMatchCount = 0;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    foreach(char c in s)
    {
        //Debug.WriteLine(c);
        if (c == rArray[0])
        {
            if (curMatchCount > 0)
                partialMatches.Push(curMatchCount);
            curMatchCount = 1;
        }
        else if (c == rArray[curMatchCount])
        {
            curMatchCount++;
            if (curMatchCount == rArrayLen)
            {
                if (partialMatches.Count == 0)
                    curMatchCount = 0;
                else
                    curMatchCount = partialMatches.Pop();
            }
        }
        else
        {
            //need to unload the stack
            if (partialMatches.Count > 0)
            {
                foreach (int count in partialMatches.Reverse())
                    for (int i = 0; i < count; i++)
                        sb.Append(rArray[i]);
                partialMatches.Clear();
            }
            for (int i = 0; i < curMatchCount; i++)
                sb.Append(rArray[i]);
            curMatchCount = 0;
            sb.Append(c);
        }
    }
    if (partialMatches.Count > 0)
    {
        foreach (int count in partialMatches.Reverse())
            for (int i = 0; i < count; i++)
                sb.Append(rArray[i]);
    }
    for (int i = 0; i < curMatchCount; i++)
        sb.Append(rArray[i]);
    sw.Stop();
    Debug.WriteLine(sw.ElapsedMilliseconds.ToString());
    return sb.ToString();
}
public static string QuickReplace3(string s, string r)
{
    if (string.IsNullOrEmpty(r))
        return string.Empty;
    if (string.IsNullOrEmpty(s))
        return string.Empty;
    s = s.Trim();
    r = r.Trim();
    if (r.Length > s.Length)
        return string.Empty;
    if (r.Length == 1)
        return (s.Replace(r, ""));

    StringBuilder sb = new StringBuilder(s.Length / 2);
    char[] rArray = r.ToCharArray();
    int rArrayLen = rArray.Length;
    Stack<byte> partialMatches = new Stack<byte>();
    byte curMatchCount = 0;
    Stopwatch sw = new Stopwatch();
    sw.Start();
    foreach (char c in s)
    {
        sb.Append(c);
        if (c == rArray[0])
        {
            if (curMatchCount > 0)
                partialMatches.Push(curMatchCount);
            curMatchCount = 1;
        }
        else if (c == rArray[curMatchCount])
        {
            curMatchCount++;
            if (curMatchCount == rArrayLen)
            {
                sb.Length -= rArrayLen;
                if (partialMatches.Count == 0)
                    curMatchCount = 0;
                else
                    curMatchCount = partialMatches.Pop();
            }
        }
        else
        {
            curMatchCount = 0;
            partialMatches.Clear();
        }
    }
    sw.Stop();
    Debug.WriteLine(sw.ElapsedMilliseconds.ToString());
    return sb.ToString();
}


Converting an SVG polygon path from relative to absolute coordinates

Your variable names are overly terse. It's had to follow the logic when it's all to do with a two-letter variable that also happens to be a 2D array.

Basically, you seem intent writing it as densely as possible rather than making it readable. But minifying javascript is what minification tools are for.

It's also strange that you pass in a complete path string, but you get an array back. An array that's missing the commands, and where you manually have to prefix M and postfix z. Why not output a complete path?

Your test just assumes that all the commands (apart from the initial M) was a L command. Which, since that the only command your code can interpret, isn't too terrible. It'd still be neater to rewrite the path code itself, though, and return a string.

Adding the z smells especially buggy, as it closes the path even if the original path wasn't closed.

As for overall structure/approach, I'd use replace with a callback and a global pattern, rather than create a match object, and much around with its contents.

In other words, I'd do this:

function pathToAbsolute(relativePath) {
  var pattern = /([ml])\s*(-?\d*\.?\d+)\s*,\s*(-?\d*\.?\d+)/ig,
      offset = null;

  // Scan the string for an M/L command (case-insensitive) and its two
  // coordinates, replacing any lower-case (relative) command with an
  // absolute version
  return relativePath.replace(pattern, function (match, command, x, y) {
    x = parseFloat(x);
    y = parseFloat(y);

    // If we don't have an offset yet or the command is absolute already,
    // then use the matched coordinates as the offset, and return the matched
    // string unaltered
    if(offset === null || command.toUpperCase() === command) {
      offset = { x: x, y: y };
      return match;
    }

    // If we're here, the command is relative, so add its coordinates to the
    // offset, and output the absolute version of the matched string
    offset.x += x;
    offset.y += y;

    return command.toUpperCase() + offset.x + "," + offset.y;
  });
}

// ========================
// Test code

var star = document.getElementById('star'),
    svg = star.parentNode,
    absPath = pathToAbsolute(star.getAttribute('d'));

var newStar = document.createElementNS('http://www.w3.org/2000/svg','path');
newStar.setAttribute('d', absPath);
newStar.setAttribute('fill','green');
newStar.setAttribute('transform','translate(30,30)');
svg.appendChild(newStar);
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">
   <path id="star" fill="#eee" d="M301.113,12.011l99.25,179.996l201.864,38.778L461.706,380.808 l25.508,203.958l-186.101-87.287L115.01,584.766l25.507-203.958L0,230.785l201.86-38.778L301.113,12.011z"></path>
</svg>

Like yours it only looks for M and L commands - not any of the many other SVG commands. Though it shouldn't actually be too terrible to extend it to handle those as well. Especially, as this returns a complete path string that can be used right away. Not joining necessary, and no assuming all commands are Ls.

It does however still assume that the path is valid; that it starts with an m or M. So it's gigo: Garbage in, garbage out.

Edit: Although I do feel the code above answers the question as originally stated, here's a version that doesn't "transform a path", but parses it and returns an array.

function pathToAbsolute(relativePath) {
  var pattern = /([ml])\s*(-?\d*\.?\d+)\s*,\s*(-?\d*\.?\d+)/ig,
      coords = [];

  relativePath.replace(pattern, function (match, command, x, y) {
    var prev;

    x = parseFloat(x);
    y = parseFloat(y);

    if(coords.length === 0 || command.toUpperCase() === command) {
      coords.push([x, y]);
    } else {
      prev = coords[coords.length-1];
      coords.push([x + prev[0], y + prev[1]]);
    }
  });

  return coords;
}


Something like if (foo == false) will always be frowned upon. If you find the negation hard to spot you might consider using not instead (see this for more info).
E.g. if (not foo)

From what I've seen macros are generally discouraged as they tend to obfuscate code and are not typesafe.


Python preprocesser that allows "until" and "unless" statements

Remco Gerlich is quite right to point out that this preprocessor does not work on general Python code, because it uses string replacement. Thus unless will be changed to if not in strings (such as regular expressions, templates, and docstrings), potentially breaking the code. The preprocessor itself is just one example of the kind of code which will be broken: it is not good enough to respond that this concern is "silly".
Additionally, Bakuriu is quite right to point out that the transformation of unless to if not is inadequate: it only works on very simple examples. But consider:

a unless b or c else d

which would be changed to:

a if not b or c else d

where the condition is wrong, because not b or c parses as (not b) or c. The correct transformation is:

a if not (b or c) else d

This problem makes it hopeless to attempt this preprocessing at the level of text, or even of tokens: you need a parser to find the end of the condition. Consider an expression like:

a unless b or (c unless d and e else f) else g

which needs to be transformed into:

a if not (b or (c if not (d and e) else f)) else g


snapping code: from separate checks to 1 formula

1) Do not hard-code the distance that will define 'near', but rather make it a variable/parameter.
2) Split the solution : 1) do we 'approximatively' overlap ? and 2) are we on the left or right, and are we up or down ?
3) Use as much 'standard' code as you can : here 'update' will define a BBox based on a list of points, 'expand' and 'overlaps' will do what-you-guess.

var nearDistance = 5;
var newBox new BoundingBox();
var boxSize = null;

for (var i = 0; i < elements.length; i++) {
            var thisElement = elements[i];

            // newBox is now the BBox of thisElement
            newBox.update(thisElement);

            // do we approximatively overlap ?
            newBox.expand(nearDistance);
            var overlaps = newBox.overlaps(box);
            if (!overlaps) continue;

            // are we on the left/right, up/down ??

            newBox.expand(-nearDistance);
            boxSize = box.size() ;

            var newXPosition = -1, newZPosition = -1;

            if ( newBox.min.x - box.max.x > -boxSize.x / 2) {
                // left
                newXPosition = newBox.min.x - ((box.max.x - box.min.x) / 2) - 0.5;
            } else {
                // right
               newXPosition = newBox.max.x + ((box.max.x - box.min.x) / 2) + 0.6;
            }

            if (newBox.min.z - box.max.z > -boxSize.z / 2 ) {
                // up
                newZPosition = newBox.min.z - ((box.max.z - box.min.z) / 2) - 0.5;
            } else {
                // down
                newZPosition= newBox.max.x + ((box.max.x - box.min.x) / 2) + 0.6;
            }

            //adjust position
            activeElement.position.x = newXPosition ;
            activeElement.position.z = newZPosition;

            box.update(activeElement);

            activeElement.snapped.push( /* thisElement was snapped */);
            debug.snapped = true;
            }
}


First of all let's talk about method names:

The get_ prefix is usually not used in ruby - you'd just leave it off.

Further the name get_li (or just li) is not very descriptive of what the method does. It tells me that it will produce an
, sure, but it doesn't tell me that the
 will contain a link. From the method name I would just assume that this is a general helper method I can use whenever I want a list item. It should probably be called something like list_item_with_link or possibly navigation_entry, assuming that the
s produced by this method are meant as entries in a navigation bar/menu.

The name of the argument is also not very descriptive. I assume you called it a because of the  tag, but a does not really contain an a tag, just the information you use to build one. I'd call it something like link instead.

Your methods should also be commented. Sure in the case of short methods like this, it's easy enough to tell what it does from looking at the code, but there should still be comments explaining what the method does, when and how it's intended to be used and what the arguments should look like.

Now to the actual code: Instead of building the li tag using string concatenation, you should use the content_tag helper instead, which builds HTML-tags containing content, like
.

I also feel that the code would become nicer if the the logic to determine whether a link points to the current page was factored into its own method. I'm sure it could be useful in other places as well.

On a general design note, it seems wrong that you're restricting the links to only contain :controller and :action. Maybe you would later like to add a link to an action with a specific parameter. Your current design would not allow that.

For this you could just use your current system and just remove the :text key out of the hash after retrieving it and then passing the rest to link_to. However this would break if you ever have an action to which you want to supply a parameter named text.

So what I would do is the separate the link text from the link location. For example an array where the first element is the link text and the second is the location might work. This way ["Meetings List", {:controller => 'meetings', :action => 'index'}], ["Meetings List", {:controller => 'meetings'}] and ["Meetings List", {:controller => 'meetings', :action => 'index', :show_only_active => true}] would all be valid links.

Instead of an array, it could be even nicer to use a struct/class. This way you could also put the logic of determining whether the link points to the current page and how to turn the link to HTML into that class.

With all those points, my code would probably look like this:

# Class to represent links.
# First argument to new will be the text to be displayed for the link and the second
# argument will be the location that the link points to as a hash.
Link = Struct.new(:text, :location) do
  include ActionView::Helpers

  # Turns this link into an HTML link
  def to_html
    link_to(text, location)
  end

  # Returns true if this link points to the same controller and action as the given
  # location hash.
  def points_to?(other_location)
    # If no action is specified, the :index action is used
    # This way the locations {:controller => :foo} and {:controller => :foo, :action => :index}
    # will be treated as equal
    action = location[:action] || :index
    other_action = other_location[:action] || :index
    location[:controller] == other_location[:controller] && action == other_action
  end
end

# Returns an li tag containing a link to the location represented by the given Link object.
# The tag's id will be "selected" if the link points to the current action and controller.
def navigation_item(link)
  selected = link.points_to?(params) ? "selected" : nil
  content_tag(:li, link.to_html, :id => selected)
end

You'd then use Link.new("title", :controller => "foo", :action => bar) inside get_tab_options to create a link.

As a last note, it also seems a bit icky to me to hardcode which links will be available in which controller into a helper method. It seems that this should rather be handled in the controllers.


Well I don't now coffeescript, but guess I can read it anyway :D

I think both are good and readable.
I don't know if you can add empty lines to the code. If you can:

strToCoordinates = (input) ->
    halves = input.split(',')
    if halves.length isnt 2
        console.log 'Please enter coordinates in format: x,y';
        return

    [x, y] = (parseFloat s for s in halves)
    unless isInteger(x) and isInteger(y)
        console.log 'The coordinates must be integers.';
        return

    if not inRange(x, y)
        console.log "Coordinates must be between 1 and #{GRID_SIZE}.";
        return

    {x, y}

But this really is a minor arguable tweak (some will like it, some don't, I do).
Another point would be the "overuse" of returns. Functions are easier to read, if they do have lss return-statements. But Again, this usually applies to larger functions only.


The third argument of copy_until could of course be a unary predicate, then instead of while (first != last && *first != delim) it would say while (first != last && !p(*first)).

Even better: remove the I last argument entirely! Just use the predicate for the whole thing, and the condition becomes while (!p(first)).

You're returning I (the place you stopped parsing the input stream), but similar functions in the STL return O (the place they stopped outputting to the output stream). The latter is more useful in STL cases, because typically the caller knows where he stopped parsing the input: it's last!

In your case, both I and O are useful; so why not return both?

template<typename I, typename O, typename Pred>
std::pair<I, O> copy_until(I first, O d_first, Pred pred)
{
    while (!pred(first)) {
        *d_first = *first;
        ++first;
        ++d_first;
    }
    return {first, d_first};
}

Your main thus becomes:

int main()
{
    std::istreambuf_iterator<char> first(std::cin);
    std::istreambuf_iterator<char> last;
    std::ostreambuf_iterator<char> d_first(std::cout);

    while (first != last) {
        std::tie(first, std::ignore) = copy_until(
            first, d_first, [=](auto it){ return it == last || *it == '\n'; }
        );
        if (first == last) break;  // Whoops!
        std::cout.put(*first);
        ++first;
    }
}

The // Whoops! comment indicates the fix for a crashing bug in your original main.

Boost.Algorithm actually has both copy_until and its inverse, copy_while: http://marshall.calepin.co/copy_while.html
Strangely, Boost's version takes last as a parameter exactly the way yours does. In Boost's case, I think that might be because they're trying to target C++03, which doesn't have lambdas, so there's no way that's both easy and lightweight to express [last](auto it) { return it != last && *it != delim; } — in C++03 you had to do that with boost::bind and maybe boost::function as well.

  I am not sure how to declare that the two iterators need to point to the same type as the type of the delimiter or the argument to the unary predicate.

The short answer is "don't"; complicated dependencies like that usually indicate that you've put the abstraction boundary in the wrong place (e.g. in this example, passing First, Last, Delim instead of First, Pred). But just for the record, you could do something crazy with enable_if, which can go on the return type of the function or on one of its parameters or on one of its template parameters, your choice.

auto copy_until(I first, I last, O d_first, T delim)
    -> std::enable_if_t<std::is_same_v<decltype(*first), T>, I>
{
    // ...
}

I'm pretty sure you don't want to assert that decltype(*d_first) is T, because that would prevent you from using something like a back_insert_iterator<vector<T>> with this algorithm.


Some general comments:

I think your program is small enough not to warrant any functions. Of course, this can be a matter of taste. It's also reasonable to do input parsing, for instance, in a separate function.
To avoid hardcoding the possible binary operators, I suggest taking a more data-driven approach and storing all possibilities in a suitable container (like a map).
You use integers as your operands, but you support division. Because you truncate the result into an integer type, 1/2 will equal 0 in your calculator. For this reason, you might want to use a floating point type.

We could rewrite your program into the following 50 lines or so:

#include <iostream>
#include <limits>
#include <map>
#include <functional>
#include <cassert>

int main()
{
    typedef std::function<float(float, float)> binary_op;
    const std::map<char, binary_op> binary_ops =
    {
        { '+', std::plus<float>() },
        { '-', std::minus<float>() },
        { '*', std::multiplies<float>() },
        { '/', std::divides<float>() },
        // NOTE: see how easy adding new functionality is.
        { '#', [](float x, float y) { return x * x * x + y; } }
    };

    std::cout << "Enter your expression: ";
    float result = 0.0;

    float x;
    float y;
    char op;

    if (!(std::cin >> x >> op >> y))
    {
        std::cout << "ERROR!\n";
        return 0;
    }

    const auto op_iter = binary_ops.find(op);
    // Handle errors as you wish.
    assert(op_iter != binary_ops.end());
    result = op_iter->second(x, y);

    while (std::cin.peek() != '\n')
    {
        if (!(std::cin >> op >> y))
        {
            std::cout << "ERROR!\n";
            return 0;
        }

        const auto op_iter = binary_ops.find(op);
        // Handle errors as you wish.
        assert(op_iter != binary_ops.end());

        result = op_iter->second(result, y);
    }

    std::cout << "Result: " << result << "\n";
}

Comments about this solution:

We do not correctly handle operator precedence. If you want to do this, I suggest looking at something like the Reverse Polish notation.
The std::map now implements the data-driven approach as suggested: you easily add more binary operators as long as they satisfy the required interface. That is, any operator will do as long as it takes two operands (castable to floats) and returns a float. For example, you could add in a fifth line for operator '#' (or whatever you want to call it), and parsing etc. is done automagically for you.


Rails conditional sorting based on params

Don't use select - that requires loading all records, and then filtering/sorting them in Ruby. But sorting and filtering is what databases and SQL is for.

For the first part, something like this should work (my Rails query-fu is rusty, so no guarantees):

current_user.bids
  .joins(real_property_sale: :real_property_sale_projects)
  .where(real_property_sale_project: { failed_date: nil })

On a side note, it seems like your models are overly complicated. They share the same prefix ("real property sale") which would seem to suggest they're been split up in a strange way. Not saying that's the case, but it does seem... off, somehow.

Whatever your app is doing, I'd wager that a user's bids are pretty important. So it seems strange that it'd take this much work to load them. A "bid status" should probably be front-and-center in the models; not a complex derived value, requiring loading not just 1st order but 2nd order associations. Just seems suspect to me.

Anyway, that code should probably be hidden away in a scope on the Bid model, so you can just say:

current_user.bids.active

or whatever name makes sense for this particular collection of bids.

Also, in your current code it seems that for the "awarded" value, you redo the same filtering you've already done once (checking failed_date).

Anyway, I imagine something like this:

@bids = case params[:bid_status]
        when 'in_progress'
          current_user.bids.active.where(real_property_sale: { status: "published" })
        when 'awarded'
          current_user.bids.active.where(status: "accepted")
        when 'lost'
          current_user.bids.active.where(status: "rejected")
        when 'history'
          current_user.bids
            .joins(real_property_sale: :real_property_sale_projects)
            .where("real_property_sale_project.failed_date IS NOT NULL")
        else
          current_user.bids.active
        end

Again, I can't guarantee it'll work as-is, but it illustrates the structure.

Note also that scopes can be chained, so you could conceivably make scopes for each of the filters, and do things like bids.active.accepted, bids.active.rejected, etc..

If you have named scopes for each filter, you could even do stuff like:

current_user.bids.active.send(params[:bid_status])

provided that a) you're sure it's safe to send the param (i.e. it's been whitelisted), and b) you use the same param values as the scope names.

Right now, it's a little odd that none of your param values actually match anything in the data models; "awarded" really means "accepted", "lost" really means "rejected", "in progress" actually means "published", etc..

Again, it seems like your data modelling is little off.


Some notes:

An array is not the best data structure to store the words, operations will be O(n). Better a hash {word_id => word}
Use 2-space indentation.

Then you can write:

define_singleton_method(:delete) do |id|
  if @@words.delete(id)
    Definition.delete_by_word_id(id)
  end
end


Changing an element in a list when a predicate holds

I'm not super familiar with Catan, having played it only once in my life and not even to completion, but a grid's a grid, and hex grids can be modeled using three axes instead of the usual two. The data structure you're searching for is an Array. (Or a Vector, if you wanna get fancy with mutability.)
Before I get to the demo, just a few notes on your various versions. #1 lies, if there's no match it just returns the first element in the array. The right thing to do is crash, or if you're feeling nice you can make your return value a Maybe Board. Returning the wrong thing is a good way to end up with subtle bugs that corrupt your data which you still just have to track down later, crashes get fixed. All your versions clobber any building that was already in that coordinate, which I have no idea if that's a thing that you do in Catan or not but I'm going to assume it's an illegal move.
These sorts of problems are easy to lose in the line noise when you haven't modeled your data correctly. One dimensional linked lists are great, but they're not the solution to everything. So, on to Arrays. You find them in the “array” package, which is part of the Haskell 2010 standard so you can expect it to be present in all modern compilers (GHC, GHC, and uh... GHC).
I've no idea what your vertex_coordinate :: ((Int, Int), Int) is supposed to represent (aside, use camelCase for your Haskell names, and did you intentionally choose a 2-tuple containing a 2-tuple over just using a 3-tuple?) but hexagonal grids are easy, especially hexagonally shaped ones like the Catan board is. Instead of just x- and y-coordinates, you use x-, y- and z-coordinates representing ↗, ↖, and ↓. Now the trick is to recognize that the axes aren't independent like in the Cartesian plane, they actually have a relation. Try drawing out a grid and figuring out what that is.
Hint:

 Remember that the origin is at \$(0,0,0)\$.

Solution:

 Using the arrows as given above for the positive direction of each axis, you'll notice that \$x + y + z = 0\$.

Now if I remember correctly Catan boards have a radius of 2, so we'll make an empty board.
type Coordinate = (Int, Int, Int)
type Board = Array Coordinate (Maybe Building)

emptyBoard :: Board
emptyBoard = listArray ((-2, -2, -2), (2, 2, 2)) (repeat Nothing)

And then write a place function that maintains the game logic.
placeBuilding :: Board -> Coordinate -> Building -> Either String Board
placeBuilding board coord@(x, y, z) building
  | x + y + z /= 0 = Left "Invalid coordinate"
  | not (inRange (bounds board) coord) = Left "Coordinate out of range"
  | otherwise = case board ! coord of
    Just _ -> Left "Coordinate occupied"
    Nothing -> Right $ board // [(coord, Just building)]


This might be a small improvement but there is no need to check that destination is inside boundingRec on each frame, you just need to check it when creating a new destination.

Here is a modified codepen in which destination creation is done in a separated function, removing the unneeded check:

function createNewDestination(originalPosition, radius) {
    var destination = null;
    while (!destination || !destination.isInside(boundingRec)) {
        destination = originalPosition.add(paper.Point.random().multiply(radius));
    }
    return destination;
}


Reading a file named on the command line is a common task.  I suggest making use of the ARGF to accomplish that.

Not all lines of the input are to be treated uniformly.  Since the first line is to be treated differently, I suggest defining lines to exclude it.

top_n, *lines = ARGF.to_a
puts lines.sort_by(&:length).last(top_n.to_i).reverse


You can use the union of two different data structures to have an O(1) data structure (thinking in terms of # of operations):

You need random access to element K in constant time (get and set), a hash table is a good candidate for this.
You want constant time inserts and deletes at the front and back of the structure (add_front, remove_back, etc.). This is what a deque is good for (double-ended queue).

So you can use both structures at the same time, and you'll solve some operations using one or the other structure. The key part is how to keep them synchronized in constant time, and the answer to that is: you only insert/remove elements using the deque, so once you insert/remove an element in the deque (which is O(1)) you go and insert/remove from the hash table too (which is also O(1)).

Some considerations:

This solution uses O(n) memory, but that is not a restriction of the statement of the problem.
A hash table's insert isn't actually O(1), they call it "amortized constant time" because at times the hash table needs to resize its internal storage to accommodate for the new element, which takes O(n) time.
A hash table's get/set is not O(1) either, it depends on the hash function and your elements (worst case scenario all elements fall in the same bucket and you have O(n) search time).


Is it a valid use case of using java.util.MissingResourceException?

This is easy to answer: The Exception does not belong to your problem domain. It is not "your" exception. So its use is not appropriate.

Another point to mention is: MissingResourceException is used when the code would expect a static resource provided by a deployment or packaging. Resource-files may be somthing like images or i18n-files. Furthermore configuration-files and everything that is expected to be available in a static way. So your use case does not match the proper usage either.

My suggestion is not to reuse java exceptions that have special usages within the java language unless you are working on the same "abstraction level". You should inherit your own exceptions from "Exception" or far better "RuntimeException" (not signature relevant) and match the exceptions to YOUR problem domain. Everything else is misleading and you have a hard time to identify the proper exception for YOUR context. I do not think that it even exists because of the different abstraction levels. JAVA Exceptions deal with the JAVA language semantics. Everything you do as a developer is nearly always on a higher abstraction level.

JAVA Documentation:

https://docs.oracle.com/javase/7/docs/api/java/util/MissingResourceException.html

https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html


Counts instances for each category for many Matlab files

You felt it right, there's a lot of unnecessary copy/paste in the first part.

Your 5 data structures are similar, and you create a lot of variables to perform the same processing 5 times.

I did a quick factorisation which brings back the code to a reasonable 12 lines (I could not test, obviously, but that seems OK):

result_list = []

for name in ["AWA","Rem","S1","S2","SWS"]:
    xx_y=sio.loadmat('/home/{}_FeaturesAll.mat'.format(name))['y'].astype('int')
    xx=np.ravel(xx)
    result_list.append(np.bincount(xx))

#Joining the 5 vectors
table= (np.vstack(result_list)).T
TABLE = np.delete(table, (0), axis=0)
print(TABLE)

As the names are logical, I don't have to make a list of full names, only a part is enough. I just apply 5 times the same operation in the correct order, then store in result_list.

Joining the vectors is now a piece of cake. Just pass the result list.

Had you needed the individual vectors further in your code, then a collections.OrderedDict would be better to store them by name and recall them afterwards.


Giving an alternative Async method to a service

If your implementation does not create interrupts of some sort there is no point in making it async. If the consumer does not want to wait for your code to execute its better to let them control that and execute your code seperate from the main thread.
Edit: if the interface and implementation are shipped seperate or if its possible someone will replace default none async implementation with a async implementation. Than it could be a good practice to make the interface Async and in your default implementation return Task.FromResult or Task.CompletedTask.


LeetCode 124: Binary Tree Maximum Path Sum

Not sure why you decided to use std::int_fast64_t over the common int that is used as the type of the tree nodes values.
But since you did, it would be more idiomatic to do at least:
static_cast<std::int_fast64_t>(0);

instead of
(std::int_fast64_t) 0;