Good News:

Architecturally, your code looks very well designed. I can't think of any language features that would significantly improve your code's architecture. That leaves only function semantics and readability.

Advise:

This advise isn't specific to idiomatic Haskell but rather general code readability.

Your current main method does a little too much. the contents of main should have a high level of abstraction. Consider abstracting the work done at the end of your main function:

main = do drinks      <- readFile "drinks"
          ingredients <- readFile "ingredients"
          putStrLn $
              case parse drinksFile "drinksFile" drinks of
              Left error         -> "Error parsing drinks file."
              Right parsedDrinks -> showPossibleDrinks parsedDrinks (lines ingredients)

showPossibleDrinks :: [Drink] -> [Ingredient] -> String
showPossibleDrinks drinks ingredients = showDrinks $ filterByIngredients drinks ingredients

showDrinks :: [Drink] -> String
showDrinks =  unlines . map printDrink

Here we have abstracted the process of printing the possible drinks into two sub methods. This provides greater readability and also allows us to change the return type of case from IO to String. Hence the putStrLn outside the case statement.

By changing the argument order of a few functions, we can  move the functions towards pointfree form:

canMake :: [Ingredient] -> Drink -> Bool
canMake ingredients = all (flip elem ingredients) . snd

filterByIngredients :: [Ingredient] -> [Drink] -> [Drink]
filterByIngredients ingredients = filter (canMake ingredients)

main = do drinks      <- readFile "drinks"
          ingredients <- readFile "ingredients"
          putStrLn $
              case parse drinksFile "drinksFile" drinks of
              Left error         -> "Error parsing drinks file."
              Right parsedDrinks -> showPossibleDrinks (lines ingredients) parsedDrinks

showPossibleDrinks :: [Ingredient] -> [Drink] -> String
showPossibleDrinks = showDrinks . (filterByIngredients ingredients)

Given the succinctness of your methods, moving towards pointfree form is quite readable and more idiomatic.

If we import the <$> operator from Control.Applicative after transposing the function's arguments we can make filterByIngredients completely pointfree:

filterByIngredients :: [Ingredient] -> [Drink] -> [Drink]
filterByIngredients =  filter <$> canMake

You can make the following equivalence substitutions:

(flip elem ingredients) ==> (`elem` ingredients)
intercalate " " ==> unwords

Giving you:

canMake :: [Ingredient] -> Drink -> Bool
canMake ingredients = all (`elem` ingredients) . snd

printDrink :: Drink -> String
printDrink (drinkName, recipe) = unwords (map capitalize (words drinkName)) ++
                                ": " ++
                                intercalate ", " (map capitalize recipe)
                                where capitalize (x : xs) = toUpper x : xs

All together we have:

import Control.Applicative ((<$>))
import Data.Char
import Data.List
import Text.ParserCombinators.Parsec

type Drink = (DrinkName, [Ingredient])
type DrinkName = String
type Ingredient = String

-- parsing the file of drink recipes
drinksFile :: GenParser Char st [Drink]
drinksFile =  endBy drink (char '\n')

-- parsing each drink recipe
drink :: GenParser Char st Drink
drink =  do first <- drinkName
            next  <- recipe
            return (first, next)

-- parsing the drink name
drinkName :: GenParser Char st DrinkName
drinkName =  do name <- many (noneOf ":")
                sep  <- many (char ':')
                return name

-- parsing the recipe into a list of ingredients
recipe :: GenParser Char st [Ingredient]
recipe =  sepBy (many (noneOf ",\n")) (char ',')

canMake :: [Ingredient] -> Drink -> Bool
canMake ingredients = all (`elem` ingredients) . snd

filterbyIngredients :: [Ingredient] -> [Drink] -> [Drink]
filterbyIngredients = filter <$> canMake

-- pretty prints a drink with its recipe
printDrink :: Drink -> String
printDrink (drinkName, recipe) = unwords (map capitalize (words drinkName)) ++
                                ": " ++
                                intercalate ", " (map capitalize recipe)
                                where capitalize (x : xs) = toUpper x : xs

showPossibleDrinks :: [Ingredient] -> [Drink] -> String
showPossibleDrinks ingredients = showDrinks . filterbyIngredients ingredients

showDrinks :: [Drink] -> String
showDrinks =  unlines . map printDrink

main = do drinks      <- readFile "drinks"
          ingredients <- readFile "ingredients"
          putStrLn $
              case parse drinksFile "drinksFile" drinks of
              Left error         -> "Error parsing drinks file."
              Right parsedDrinks -> showPossibleDrinks (lines ingredients) parsedDrinks


I had a similar contest in high school.  I decided to win in every category :)

In modern architectures, linked lists are slow.  See https://www.youtube.com/watch?v=YQs6IC-vgmo for example.  Does it need to be a linked list?  Does it need to be a merge sort in particular?  I can advice more specifically if you update your post to add that info.

Even though it would not be a legal entry, you might try using a std::vector<std::string> and just calling std::sort and using that speed as a baseline!

  Btw: I have no memory leaks, thanks to valgrind.

That is a heroic effort to achieve something that should normally be the case in C++.  Use unique_ptr and general RAII techniques, and memory leaking in a single-threaded program is simply not an issue to worry about!  That is, you are making it too hard.

Read through and bookmark the C++ Standard Guidelines.  Numbers I note later are citations from this.

Use the proper #include files.  You have a couple project-specific includes, but no standard library stuff; maybe you are not using anything from the library, not even language-support features?  But that will change if you improve the code.

template<typename T>
T* Merge(T* firstNode, T* secondNode)
{
  if (!firstNode) return secondNode;
  else if (!secondNode) return firstNode;

  else if (firstNode->getText() >= secondNode->getText())
  {
    firstNode->setPrev(Merge(firstNode->getPrev(), secondNode));
    return firstNode;
  }
  else
  {
    secondNode->setPrev(Merge(firstNode, secondNode->getPrev()));
    return secondNode;
  }
}

So let’s see… you are taking a couple node pointers, not any kind of abstraction as the linked list as a collection?  I understand if this is the kind of stuff you are learning, but it is hard to follow as it is not “normal” programming.

So far, I see some good habits.  C++ (not C) style placement of the *, use of contextual conversion to bool as a truth test of the pointer, putting quick-return tests at the very top, in a compact manner … all very mature style!

The logic looks like straight functional programming style.  Good for Haskell, not good for C++.  I don’t think the compiler can do tail recursion elimination here.  You will run out of stack space if your list is long!

Writing this as a loop rather than recursively will make it faster and avoid the size limit.

template<typename T>
T* Split(T* my_node)
{
  if (!my_node || !my_node->getPrev()) return NULL;
  T* secondNode = my_node->getPrev();
  my_node->setPrev(secondNode->getPrev());
  secondNode->setPrev(Split(secondNode->getPrev()));
  return secondNode;
}

Forget that the NULL macro ever existed!  Banish it from your memory.  C++ has the special nullptr value.

Again, I see a good habit:  declared secondNode when you were ready to initialize it.

template<typename T>
T* MergeSort(T* my_node)
{
  if (!my_node) return NULL;
  else if (!my_node->getPrev()) return my_node;
  return Merge(MergeSort(my_node), MergeSort(Split(my_node)));
}

As before, nullptr, not NULL.

It looks like you are peeling off one node at a time, not cutting the list in half.  If I follow this right, you have implemented an insertion sort where you need a linear search over the list to find the insertion position, not a proper merge sort.  Each item will have to compare (on average) with half of the items processed already.  This is O(n²).  A proper merge will compare once for each item in the shorter list, recursively sorting the half-lists first.  That is O(n log n).

Now I’m sure you know that the “big O” will trump the linear speedup of any of the steps!

int main(void)
{
  FileStructure f;
  Key* head = new Key();
  f.loadFile("data/gibberish.bin", *head);

  head = MergeSort(head);
  Key* tempHead = head; //values

  while (tempHead)
  {
    tempHead->setValuePtr(MergeSort(tempHead->getValuePtr()));
    tempHead = tempHead->getPrev();
  }
  // save sorted data into a new file called sorted.bin
  f.saveFile(*head, "sorted.bin");

  delete head;
  //newHead = NULL;

  return 0;
}

Don’t write (void) for an empty parameter list!  Stroustrup calls that “an abomination”.  It is supported so that it can read C header files; but you should not write that in C++, ever.

  Key* head = new Key();

⧺C.149 — no naked new or delete.

You should probably make this a unique_ptr as a drop-in replacement without otherwise changing the architecture.

  while (tempHead)
  {
    tempHead->setValuePtr(MergeSort(tempHead->getValuePtr()));
    tempHead = tempHead->getPrev();
  }

I don’t understand that part.  You sorted with the call to MergeSort, right?  Why do you have to back up a node and sort it again?  This might be a work-around for a problem with the sorting or the data structure.

Then you treat the original node,  head, as the sorted list’s head?  So what was the deal with tempHead?

void Key::addValue(std::string word)
{
    if (key == word.substr(0, 2))
    {
        Value *temp = valueTail;
        valueTail = new Value(word);
        valueTail->setPrev(temp);
        return;
    }
    else if (prevKey)
    {
        prevKey->addValue(word);
        return;
    }
    prevKey = new Key();
    prevKey->setText(word.substr(0, 2));
    prevKey->valueTail = new Value(word);
}

You are taking the string word by value, copying it into the function.  You don’t modify word, right?

I don’t know what Value is, or why you don’t just store the std::string in your nodes.

substr is not a normal or good way to manipulate strings in the standard library.  If I knew what you were trying to do, I could advise how it should naturally be done.

Good luck to you!  Keep at it.


Review
If you are after a entry level job then your code shows you can code, which is a good start.
As an emploier I would ask.

Why did you choose to use class syntax over more traditional code styles?
How long did it take you to write this code?

Bad points
Some points that detract from the code quality
JS

Clock constructor takes an argument that is not used.constructor(props)
Unused variable in Clock constructor const baseEl = document.querySelector("#clock");
Hard coded object is tested for a key it will never have if (key === "ampm") return;
Clock can only exist as a single instance, but nothing prevents clock being constructed many times.
Setting element content via innerHTML even though the content has no markup.this.nextDigitEls.forEach(el => el.innerHTML = this.value);
Redundancy suggests you are not sure about type coercion if (parseInt(value) < 10) {
You have Not used getters and setters yet have the functions Digit.setValue, Clock.getCurrentTime
The Clock takes on a Digit s responsibility ? Clock.getDigitProps
Statement with only two outcomes written using switch not as a ternary in function Clock.getDigitProps
Lots of redundant code. An example const {prevDigitEls, nextDigitEls } = this; followed by the line [...prevDigitEls, ...nextDigitEls].
Use event listener to get the flip animation end rather than using setTimeout

CSS & HTML
Its a complete mess, I was going to fix it but it is unusable and needs to be worked from the ground up.

Bad name for flip animation class turned which you add to an element to start the animation and remove to reset.
Your code uses ECMAScript6+, yet you include legacy browser CSS, all the legacy CSS is wasted as the clock will not start on those browsers.
It would be far better to have a container that contains data properties and then build the elements in code. For example HTML only needs

 to create the clock

Rewrite
Its just the code.
Personally I would not have written it as follows because the class syntax forces you to break the rules of encapsulation (No privates) and as its only ever to be a single instance Clock which in reality only needs the tick function which could just be a function.
;(() => {
    const digitNames = ['hours-tens', 'hours-ones', 'minutes-tens', 'minutes-ones', 'seconds-tens', 'seconds-ones'];
    const pad0 = num => ("" + num).padStart(2, "0");
    const time = (d = new Date()) => pad0(d.getHours()) + pad0(d.getMinutes()) + pad0(d.getSeconds());
    const elementsText = (elements, text) => { for (const el of elements) { el.textContent = text } }
    class Digit {
        constructor(name, timeString) {
            this.index = digitNames.indexOf(name);
            const [type, position] = name.split("-");
            const container = document.querySelector(`#${type} .${position}-digit`);
            this.flipperEls = container.querySelectorAll('.flipper');
            this.nextDigitEls = container.querySelectorAll('.next .digit');
            this.currentDigitEls = container.querySelectorAll('.prev .digit');
            this.next = this.val = timeString[this.index];
            this.current = this.val;
        }
        set time(timeStr) {
            if (timeStr[this.index] !== this.val) {
                this.next = this.val = timeStr[this.index];
                this.flippers = "turn";
                setTimeout(() => {
                    this.current = this.val;
                    this.flippers = "turned";
                }, 500);
            }
        }
        set next(value) { elementsText(this.nextDigitEls, value) }
        set current(value) { elementsText(this.currentDigitEls, value) }
        set flippers(action) {
            for (const el of this.flipperEls) {
                if (action === "turn") { el.classList.add('turned') }
                else { el.classList.remove("turned") }
            }
        }
    }
    class Clock {
        constructor() {
            const timeStr = time();
            this.digits = digitNames.map(name => new Digit(name, timeStr));
            (this.tick = this.ticker.bind(this))(); // start the clock
        }
        ticker() {
            const timeStr = time();
            this.digits.forEach(digit => digit.time = timeStr);
            const now = Date.now();
            const nextSecondIn = ((now / 1000 | 0) + 1) * 1000 - now;
            setTimeout(this.tick, nextSecondIn + (nextSecondIn > 500 ? 0 : 1000));
        }
    }
    new Clock();
})();


Convert boolean list to list of base10 integers

The individual steps that you describe in the Problem section are each simple and easy to follow. Yet you write your code in basically a single line. To understand it I had to tear it apart like you did in your "explanation for humans":

scaled = [
    int(int(str(bin), 2)/2.55)+50
        for bin in [
            int(''.join(map(str, num)))
                for num in [
                    l[i : i+8] for i in
                        range(0, len(l), 8)]]]

I have also reformatted the code to better see the underlying structure. Together with your explanation, this works for understanding it.

But since you chose to not include the explanation within your code, I would have no chance to understand it by reading it alone.

Therefore, I find it easier to understand when you name the intermediate steps:

chunks = [l[i : i+8] for i in range(0, len(l), 8)]
binaries = [int(''.join(map(str, chunk))) for chunk in chunks]
numbers = [int(str(binary), 2) for binary in binaries]
scaled = [round(50 + (150 - 50) * number / (255 - 0)) for number in numbers]

There is a pythonic shortcut for step 1, and steps 2 and 3 can be combined into one:

chunks = zip(*[iter(l)]*8)
numbers = [sum(bit << shift for bit, shift in zip(chunk, reversed(range(8))) for chunk in chunks]
scaled = [round(50 + (150 - 50) * number / (255 - 0)) for number in numbers]

The aim of PEP8 is to ensure readable code. Having too many different ideas in a single line of code does not count as readable to me. Therefore I prefer the form with the intermediate steps.

Sure, the broken down version of the code is longer, but the reader of your code can take a deep breath after each step and inspect the intermediate result, just as you did in your explanation. Therefore the code should look this way.

By the way, I replaced the very last int with round since I think it is more appropriate. Decide for yourself. I also replaced the magic number 2.55 with the numbers from your explanation. This makes the numbers less magic.


Class that holds calculation results and has to be immutable

At the moment your class is not immutable because the Map given in the constructor is not copied (and Map itself isn't immutable). You should instead have a constructor like

public Result(final Map<String, T> result) {
    this.result = new LinkedHashMap<>(result);
}

What's the goal of the of() method ? Shouldn't it be named empty() instead ?

public static final Result<Number> empty() {
    return new Result<>(new LinkedHashMap<>());
}

Or having two parameters (1 key, 1 value) ?

public static final Result<Number> of(final String key, final T value) {
    Map<String, T> base = new LinkedHashMap<>();
    base.put(key, value);
    return new Result<>(base);
}

The fact that get() throws an IOException or a ClassNotFoundException bothers me because it makes the current underlying implementation "leaking" out of your class. Who wants (and expects) to have to handle an IOException when getting a value from a Map ?
Since these exceptions are not supposed to happen in this case, I would rethrow them as unchecked exceptions

@SuppressWarnings("unchecked")
public T get(final String key) throws Exception {
    try {
        return ((T) convertFromBytes(convertToBytes(result.get(key))));
    }
    catch(IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}


A few comments about your Cipher interface:

A cipher is an algorithm to encrypt something, so your cipher method should be renamed to encrypt. To match encrypt, you should change decipher to decrypt.
getCipherChar and getDecipheredChar is only really applicable to a few ciphers and not to a general cipher. For example, in the Viginere cipher, the encrypted character depends on the relative position compared to the repeated key. Therefore you can't tell what the result will be without additional information regarding where it is in the string. Other algorithms are more complex. These methods can still be used internally in CeasarCipher, but should be removed from the Cipher interface.

Regarding CeasarCipher:

Chars aren't just A-Z and a-z, and the Cipher interface is a guarantee that you will encrypt/decrypt an arbitrary string. Currently any other character stays the same, which is not what the Ceasar cipher is. Therefore you should change your code to just increment a char's value by the shift, modulo Character.MAX_VALUE, with some care as a negative shift could lead to a negative modulo which can be fixed by calculating the final char as described in the following code:

char shiftedChar(char c, int shift):
    int ROLLOVER = Character.MAX_VALUE;
    return (((c + shift) % ROLLOVER) + ROLLOVER) % ROLLOVER;

Alternatively you could specify some sort of Alphabet type (which should be something like a List<Character>) which restricts the subset of Character's that you are interested in.


Is this a good implementation of the Factory Pattern?

Two things strike me:

There's no need to have a separate factory class when you could put the functionality into the enum, unless you expect to have other factory implementations
As you say, if the classes are stateless, there's no need to create a new instance on each call. (I've only just spotted your factory map class, which effectively does something like this, but there's no need to use a map.)

Combining these:

public enum BaseTypesValues {
    EXTENDED_TYPEA(new ExtendedTypeA()),
    EXTENDED_TYPEB(new ExtendedTypeB());

    private final BaseType instance;

    private BaseTypesValues(BaseType instance) {
        this.instance = instance;
    }

    public BaseType getBaseType() {
        return instance;
    }
}

Then to use:

BaseType type = EXTENDED_TYPEA.getBaseType();

Or:

public void doSomething(BaseTypesValue baseTypeValue) {
    baseTypeValue.getBaseType().someCallOnTheBaseType();
}

EDIT: Note that here, if you want to introduce a new type which isn't stateless, it could override the getBaseType method:

EXTENDED_TYPEC(null) {
    @Override public BaseType getBaseType() {
        return new ExtendedTypeC();
    }
};

Admittedly this would break code which assumed all implementations were stateless...


matplotlib get_legend_handles_labels always return empty

When you adding curves, bar to your chart specify label, like:

ax.plot(x, y, linewidth=1.75, color='#00ff00', label='curve1')

After that everything works like a charm.


Speeding up script for processing three huge files

A major problem with your code is that you're doing very long linear searches to find matches-- worse, you're doing those in a nested fashion.

Instead, you should take advantage of Python dictionaries, which have very fast lookups.  Something like this:

def read_sentences(filename):
    with open(filename) as fp:
        data = {line[:line.index("#")]: line for line in fp}
    return data

eng_lines = read_sentences("eng_lines.txt")
all_lines = read_sentences("all_lines.txt")

with open("all_links.txt") as fp:
    all_links = dict(line.rstrip().split("#") for line in fp)

with open("matches2.txt", "w") as fp_matches:
    for idcode in sorted(eng_lines, key=int):
        print "working on", idcode
        if idcode in all_links:
            fp_matches.write(eng_lines[idcode] + "\n")
            fp_matches.write(all_lines[all_links[idcode]] + "\n")
        else:
            print "warning: could not match eng_line", idcode

builds dictionaries for both eng_lines and all_lines, using the id as the key and the line as the value.  It also builds a dictionary all_links to store the connection between the id values in eng_lines and all_lines.   On some test data I mocked up, it produces a file looking like yours:

1#eng#This is example sentence number 1

995072#cmn#This should really be in Mandarin 995072

2#eng#This is example sentence number 2

1732074#cmn#This should really be in Mandarin 1732074

in about ten to twenty seconds on a dataset of your size.


Multiplying by 3

The multiplication part seems overly complicated. The problem is, mul doesn't take an immediate, and the register that I want to multiply is ebx, not eax, so I need to do a couple movs before I can multiply.

This is all true, but based on the premise that the mul instruction must be used. Here are a couple of alternatives:

imul ebx, ebx, 3, listed in the manual as a signed multiplication, but that makes no difference, because only the low half of the product is used.
lea ebx, [ebx + 2*ebx], even the +1 can be merged into it: lea ebx, [ebx + 2*ebx + 1]. As a reminder, lea evaluates the address on the right and stores it in the destination register, it does not access memory despite the square-brackets syntax. 3-component lea takes 3 cycles on some processors (eg Haswell, Skylake), making it slightly slower than a 2-component lea and a separate inc. 3-component lea is good on Ryzen.

Dividing by 10
The simplest way is of course to use the div instruction, but that's not the fastest way, and it's not what a compiler would do. Here is a faster way, similar to how compilers do it, based on multiplying by a fixed-point reciprocal of 10 (namely 235 / 10, the difference between 235 and 232 is compensated for by shifting right by 3, the remaining division by 232 is implicit by taking the high half of the output of mul).
; calculate quotient ecx/10
mov eax, 0xCCCCCCCD
mul ecx
shr edx, 3
mov eax, ecx
mov ecx, edx
; calculate remainder as n - 10*(n/10)
lea edx, [edx + 4*edx]
add edx, edx
sub eax, edx

push edx in print_int
This will put 4 bytes on the stack for every character of the decimal representation of the integer, 1 actual char and 3 zeroes as filler. That looks fine when printed because a zero does not look like anything, so I'm not sure if this should be classed as a bug, but it just seems like an odd thing to do. The characters could be written to some buffer byte-by-byte, with a store and decrementing the pointer, then there would not be zeroes mixed in. A similar "subtract pointers to find the length"-trick could be used, that's a good trick.
Small tricks

mov edx, 0  ; Zeroing out edx for div

That's fine but xor edx, edx is preferred, unless the flags must be preserved.

    jmp .end
.even

Given that n is odd, 3n+1 is even, so you could omit the jump and have the flow of execution fall straight into the "even" case. Of course that means that not all integers in the sequence are printed, so maybe you can't use this trick, depending on what you want from the program.
If skipping some numbers to accelerate the sequence is OK, here is an other trick for that: skip a sequence of even numbers all at once by counting the trailing zeroes and shifting them all out.
tzcnt ecx, ebx
shr ebx, cl

   mov esp, ebp
   pop ebp

If you want (it doesn't make a significant difference, so it's mostly personal preference), you can use leave instead of this pair of instructions. Pairing the leave with enter is not recommended because enter is slow, but leave itself is OK. GCC likes to use leave when it makes sense, but Clang and MSVC don't.

       cmp ecx, 0
       jne .loop

That's fine, but there are a couple of alternatives that you may find interesting:

test ecx, ecx
jne .loop

Saves a byte, thanks to not having to encode the zero explicitly.

jecxz .loop

This special case can be used because ecx is used. Only 2 bytes instead of 5 or 4. However, unlike a fusible arith/branch pair, this costs 2 µops on Intel processors. On Ryzen there is no downside.


Two points:

echo $(something that already prints) is just redundant. This is simpler

source ./buzz.sh $i

There does not appear to be any need for two separate files. Put buzz in a function. Also, you are using a lot of subshells that are unnecessary (a). I'd stick with the more verbose but clearer if

buzz() {
    if (( $1 % 15 == 0 )); then
        echo 'FizzBuzz'
    elif (( $1 % 5 == 0 )); then
        echo 'Buzz'
    elif (( $1 % 3 == 0 )); then
        echo 'Fizz'
    fi
    echo $1
}

then

for i in $(seq $1); do buzz $i; done

a) if you want a grouping construct without the overhead of spawning a new shell, use braces:

{ echo foo; echo bar; echo baz; } | tac


Data transfer objects vs Entities in JAVA REST server application

Short answer:

Don't create a DTO per entity. Use the exposed domain model pattern instead.

Very long answer:

When you say "send to the client," as it is a webapp, this really means render to the browser (or mobile app) in the servlet tier. In which case, it's typically your own teams code and there is little or no value to copying entities into DTOs. There is overhead to copying into DTOs which is a reason not to do it. The exposed domain model pattern considers copying to DTOs as an anti-pattern. The POJOs In Action book by Chris Richardson is old, but still excellent and covers the exposed domain model pattern. The library versions in the sample code are now very out of date as it is many years later but the design and implementation approaches described in detail are IMHO timeless.

There is a use for some DTOs when writing code with entities. The canonical use is a search results screen which is, say, a grid with many columns which come from many entities. An example would be a summary of customer orders. That would have each row be taken from entities such as customers, addresses, products, orders etc. In such a case it is wasteful and slow to load all the entities to memory to render them in the flat search results screen. In that case you can create a DTO which represents a row on the screen and use JPA select new syntax as described in this answer to join across entities which is translated into a database join query that is efficiently loaded into the DTO object.

We should note that the DTO described above models the search result screen not the business domain. That's an important distinction. The DTO may change completely if the screen changes or be deleted if the screen is deleted. What you really want to do is model the business problem as entities and mature that model carefully and keep DTOs to an absolute minimum. Screens which work closely with a few entities in detail should work with root entities that control other entities directly.

I would strongly recommend putting as much business logic as you can into entities as public methods, and try to have all the code which creates and connects entities default/package protected and as hidden as possible. When you do that you get better OO design. An example would be the Order entity has a method getOrderItems to list the OrderItem entities but a protected setOrderItems method. The client would invoke a public method on the Order called addItem which took all the fields needed to construct the OrderItem entry internally using a protected constructor and add it into its list of order items. The Order becomes a "root/aggregate entity" which manages the relations and business logic of subordinate entities. This is a more naturally OO design than having "behaviourless" DTOs with the business logic entirely in service classes; or worse spread out across UI code. Have the service classes that query and load root entities then call method on the root entities that contain the business logic. That way different service class methods that work with the same root entities won't duplicate logic as the logic will be within the entities that are shared.

If your entities are dumb with no logic then they are just DTOs which is the Anemic Domain Model anti-pattern. If your entities are strong with business logic then copying the entities to DTOs would make no way for a client to use that business logic.

Given all this advice, it may seem strange that so much j2ee code still copies all entities into DTOs. One reason for this may be that the original "Core J2EE Design Patterns" book published by Sun had DTOs as a core pattern. That was required reading for a decade at the turn of the century. It's still around on the Oracle site, but that version makes it clear that it's to abstract over JDBC or LDAP and clearly JPA is the modern and standards compliant way of abstracting over a database; therefore, that page is obsolete.

Edit I have created a sample project on GitHub that demonstrates some of the ideas in this answer.


Singleton handler for reading and writing configuration.json

Rather than os and os.path use pathlib.Path.
def _save_config_data(content):
    CONFIG.parent.mkdir(parents=True, exist_ok=True)
    with open(CONFIG, 'w') as f:
        json.dump(obj=content, fp=f, indent=2)

def _load_config_data():
    file = CONFIG if CONFIG.exists() else DEFAULT_CONFIG
    with open(file, 'r') as f:
        return json.load(f)

Your code doesn't follow idiomatic Python.
Python uses errors for control flow so returning True/False in set_setting is not idiomatic.

You should make a walk function which you call from both get_setting and set_setting.

Reduce is generally not a good solution.
I would say in the specific example of your code, get_setting_old has far superior readability to get_setting.

import os
import json
from functools import reduce

from definitions import CONFIG, DEFAULT_CONFIG

__all__ = [
    "get_setting",
    "set_setting",
]

# Helper functions

def _save_config_data(content):
    CONFIG.parent.mkdir(parents=True, exist_ok=True)
    with open(CONFIG, 'w') as f:
        json.dump(obj=content, fp=f, indent=2)

def _load_config_data():
    file = CONFIG if CONFIG.exists() else DEFAULT_CONFIG
    with open(file, 'r') as f:
        return json.load(f)

def _walk(obj, path):
    for segment in path:
        obj = obj[segment]
    return obj

def get_setting(*args, default=_SENTINEL):
    try:
        return _walk(_CONFIG_DATA, args)
    except LookupError:
        if default is _SENTINEL:
            raise LookupError(f"cannot walk path; {args}") from None
        else:
            return default

def set_setting(value, *args):
    *args, segment = args
    try:
        node = _walk(_CONFIG_DATA, args)
        node[segment] = value
    except LookupError:
        raise LookupError(f"cannot set path; {args}") from None

_SENTINEL = object()
_CONFIG_DATA = _load_config_data()

I think using a class would be better as then you can define __getitem__ and __setitem__ for a potentially nicer interface.

class Walker:
    def __init__(self, data):
        self._data = data

    def __getitem__(self, args):
        if not isinstance(args, tuple):
            args = (args,)
        return self.get(*args)

    def __setitem__(self, args, value):
        if not isinstance(args, tuple):
            args = (args,)
        self.set(value, *args)

    def _walk(self, obj, path):
        for segment in path:
            obj = obj[segment]
        return obj

    def get(self, *args, default=_SENTINEL):
        try:
            return _walk(_CONFIG_DATA, args)
        except LookupError:
            if default is _SENTINEL:
                raise LookupError(f"cannot walk path; {args}") from None
            else:
                return default

    def set(self, value, *args):
        *args, segment = args
        try:
            node = _walk(_CONFIG_DATA, args)
            node[segment] = value
        except LookupError:
            raise LookupError(f"cannot set path; {args}") from None


Firstly, your installfromdownload function should be install_from_download (and have a docstring to go with it explaining what it does).

This line:

targetfolder = r"C:\Program Files (x86)\Mod Manager\Mods\f_" + filename[:-4]

should probably check and make sure that the file actually ends with .zip (or whatever format you're actually expecting it to come in):

if filename.endswith('.zip'):
    target_folder = ...

Something doesn't seem quite right with:

unzip(r"C:\Program Files (x86)\Mod Manager\Mods\z_" + filename + ".scd", targetfolder)

You're stripping the last 4 characters off filename before, and here you're appending '.scd'. I assumed you were stripping .scd off above, but then realized you're unzipping it, so it's actually a .zip (or something like that). Either way, it's confusing and something like:

target_folder = r"..." + filename.split('.zip')[0]

would make it much more clear what you're actually doing (commenting would help a bit too).

Don't explicitly check against False:

if checkdirs(targetfolder) == False:

This should be:

if not checkdirs(targetfolder):

Don't join paths together with "\\" (which is OS specific anyway):

 filepath = targetfolder + "\\" + file

Use os.path.join instead:

 filepath = os.path.join(target_folder, file)

Some of the variable names here make your code really, really hard to follow (newfolderonelist, newfolderone).

This line should make your script crash:

if os.checkdirs(newfolders) == False:

As you're trying to call your checkdirs function (os.checkdirs doesn't exist).

Let's look at the checkdirs function:

def checkdirs(target):
    isfile = 0
    targetlist = os.listdir(target)
    for files in targetlist:
        for letters in files:
            if letters == ".":
                isfile = isfile + 1
if isfile == len(os.listdir(target)):
    return False
else:
    return True

Again following Python naming convention, this should be check_dirs (although the name needs a lot of work - what's it checking them for?). Further, a lot of the work here can replaced with os.path.isfile. From reading it, it looks like you're checking that everything in a given directory is not a file, so I'm going to call it not_all_files:

def not_all_files(directory):
    '''Checks the given directory, returning False if it contains only files,
    and True otherwise. If the argument given is not a directory,
    raises IOError.
    '''

    if not os.path.isdir(directory)
        # Oops, passed in something that wasn't a directory
        # Handle this error
        raise IOError('....')
    return not all((os.path.isfile(f) for f in os.listdir(directory)))

Given how you're using it above, I'd rather swap around what it returns: have it return True if everything in the directory is a file, False otherwise. This would then be:

def all_files(directory):
    '''Checks the given directory, returning True if it contains only files,
    and False otherwise. If the argument given is not a directory,
    raises IOError.
    '''

    if not os.path.isdir(directory)
        # Oops, passed in something that wasn't a directory
        # Handle this error
        raise IOError('....')
    return all((os.path.isfile(f) for f in os.listdir(directory)))

Your code in install_from_download would then become:

 if all_files(target_folder):

which I think is much easier to read.


Interesting question,

my first point is that it is not clear how you wrote the Room module, but ideally, that module should do 2 things:

Provide the created room to complete
Provide a way to deal with failure

Then, I would expect in the top code to see something like this:

var Room = require('../models/database').Room

exports.create = function (req, res) {
    Room.create({
        room_name: req.body.roomName
    })
    .complete(function ( success, room ) {
        if( success )
            res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );
        else
            res.redirect('cuteapologetickittenvideo/');
    });
};

You will notice that I also changed req.body.roomName -> room.room_name -> room.roomName which makes more sense to me. On a general note I find it bad practice to require room_name in your call to the constructor, but roomName in the request. I would suggest to stick to 1 convention (The JavaScript One) and use roomName everywhere. Then you could write

var Room = require('../models/database').Room

exports.create = function (req, res) {
    Room.create( req.body ).complete(function roomComplete( success, room ) {
        if( success )
            res.redirect('rooms/videochat/' + room.roomName + '/' + room.roomId );
        else
            res.redirect('cuteapologetickittenvideo/');
    });
};

For the Jade processing, you should be able to get room id and name from the matching on '/rooms/videochat/:roomName/:roomId'.

Same for the client side javascript, I would be more inclined to get this from the URL than from a field in the HTML.


SELECT from "vertical" table and display on "horizontal" table

You can use conditional aggregation to get the expected result set:

SELECT cityID,
       MAX(CASE WHEN parameterID = 1 THEN value END) AS temp,
       MAX(CASE WHEN parameterID = 2 THEN value END) AS humidity,
       MAX(CASE WHEN parameterID = 3 THEN value END) AS rain
FROM mytable
GROUP BY cityID

Demo here


As explained in comments (in which I pointed out a few possible edge cases), even though it's not optimized in terms of performance, this is about as clear as it gets.

A more clever algorithm - calculating the number of weekdays without iterating through all of them - is probably possible, but I bet it would be much less readable. If performance isn't a concern at this point, I'd leave it.

You could maybe replace the loop with a LINQ-based solution.

int WhichWorkingDay(DateTime day)
{
    // edge cases
    switch (day.DayOfWeek)
    {
        case DayOfWeek.Saturday:
            return day.Day > 1
                // Friday the day before
                ? WhichWorkingDay(day.AddDays(-1))
                // or next Monday if previous Friday was on last month
                : WhichWorkingDay(day.AddDays(2));
        // analogically here
        case DayOfWeek.Sunday:
            return day.Day > 2
                ? WhichWorkingDay(day.AddDays(-2))
                : WhichWorkingDay(day.AddDays(1));
    }

    // or you could inline it, obviously
    Func<DateTime, bool> isWorkingDay = d => d.DayOfWeek != DayOfWeek.Saturday
        && d.DayOfWeek != DayOfWeek.Sunday;

    return Enumerable
        .Range(1, day.Day)
        .Select(d => new DateTime(day.Year, day.Month, d))
        .Count(isWorkingDay);
}


Well, the problem is that the example code provided effectively does a % 256 on the input characters. So it's possible that your version and the example code yield two different values for the same input.

However you said I believe the code above might work for every possible input - I take it then that password will never contain any characters where the wrap-around will play a role? If that's the case then your version should be equivalent.

If you are paranoid then replace Encoding.UTF8.GetBytes in your code with the same loop as used in the example but leave your other refactorings intact.

In fact I would refactor the result into:

string.Format("{0}?server_time={1}&hash_value={2}&validminutes={3}", mediaUrl, dateTimeString, hashValue, validMinutes);

Which means you could also get rid of the validMinutesString.


What is the Data.Map doing there?  It looks like you were going to use it, but then changed your mind and used a list of pairs instead.

The stringMapReplace function is doing explicit recursion.  A more advanced Haskeller would recognize this pattern as some kind of fold:

-- if the list is empty, the result is the initial value z; else
-- apply f to the first element and the result of folding the rest
foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)

-- if the list is empty, the result is the initial value; else
-- we recurse immediately, making the new initial value the result
-- of combining the old initial value with the first element.
foldl f z []     = z
foldl f z (x:xs) = foldl f (f z x) xs

In this case, the function can be tersely written as

stringMapReplace :: Dictionary -> String -> String
stringMapReplace = flip $ foldr $ uncurry strReplace

Intermediate steps to get there

First, recognize that your dictionary is the thing that is being iterated through.  (That is, your (m:ms) plays the role of the (x:xs) in the fold.)  In Haskell, it is usually more convenient to place the parameter that varies the most at the end.  So, rewrite your original

stringMapReplace (m:ms) s = stringMapReplace ms (strReplace (fst m) (snd m) s)

as

stringMapReplace :: Dictionary -> String -> String
stringMapReplace map s = stringMapReplace' s map
  where
    stringMapReplace' s [] = s
    stringMapReplace' s (m:ms) = stringMapReplace' (strReplace (fst m) (snd m) s) ms

Now, we can see that stringMapReplace' fits the pattern for foldl.  However, foldr is preferable to foldl.  If we perform the substitutions in a different order…

stringMapReplace :: Dictionary -> String -> String
stringMapReplace map s = stringMapReplace' s map
  where
    stringMapReplace' s [] = s
    stringMapReplace' s (m:ms) = strReplace (fst m) (snd m) (stringMapReplace' s ms)

… we can make stringMapReplace' fit the pattern for foldr.

stringMapReplace map s = stringMapReplace' s map
  where
    stringMapReplace' s map = foldr f s map
    f m = strReplace (fst m) (snd m)

Notice that in stringMapReplace' s map = foldr f s map, the s map is repeated on both sides.  We can write that in point-free style as stringMapReplace' = foldr f.

But what is f?  We can simplify it as uncurry strReplace.

stringMapReplace map s = stringMapReplace' s map
  where
    stringMapReplace' = foldr $ uncurry strReplace

What is the relationship between stringMapReplace and stringMapReplace'?  The parameters are flipped.

stringMapReplace = flip $ foldr $ uncurry strReplace

QED.


Accessing a REST WebService and updating local HTML objects with Modular JS

declared but never used:

url
data (it my look like it is used but it is only assigned to results and card)
results
card

used but never declared:

baseUrl
mainSettings (though there is a comment about it)
value

Unnecessary:

applyLanguageSettings
settings
obj
status
jqXHR

I had to assume card and value were the same thing or else as mentioned above data wasn't really used. Readability can be improved by giving dfd a name that would be understood by more people. I also made use the the data setting for the ajax function.

Potential rewrite:

$(function() {
    var language = mainSettings.getLanguage(); /* there is an object in the page called mainSettings with current language */
    language = language === "en" ? "en" : "es";

    var pageName = window.location.pathname.split("/").pop();
    pageName = pageName.substring(0, pageName.indexOf('.aspx'));
    var understandableName = $.ajax({
        url: mainSettings.getUrl() + language + "/db/items",
        data : { "$filter" : "PageName eq '" + pageName + "'" },
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose"
        }
    });

    understandableName.done(function(data) {
        if (!data.d)
            return;
        var results = data.d.results;
        if (results && results.length > 0) {
            var value = results[0];
            $("#Img").attr("src", value.Img);
            $("#Title").text(value.Title);
        }
    });
});


I try to start from part dealing with removing of checked attachments.

First, I can't find purpose of puts lines. Only if it used for debugging in development.

Second, @lesson.attachments.each.with_index - every time updating single attachment, you need to go through all existing records. I think, that is what 'Codeclimate' "says". So, that structure must be simplified.

Here is how I suggest to rewrite 'deletion' part:

def update

  params[:delete_array].try :each do |id|
    @lesson.attachments.find(id).destroy
  end

# other code

end

Other parts (for params[:order_array] and params[:description_array]) can be refactored in the same way. I hope, you've got the idea.

If you need more detailed explanation of above code or need help with other parts - let me know and I'll explain it in details.


It seems that your allFipsRM function takes as input a data variable name and rolling mean length and outputs information about the rolling mean with the indicated length, computed for each fips value separately.

I see two key issues with the code as currently written:

In two places you are growing objects element by element. Please see Circle 2 of The R Inferno for why this is an inefficient way to grow objects.
A vectorized rolling mean function should be much more efficient than one you code on your own with a loop in R.

The following code fixes these two issues by combining the data for all fips codes in a single call to rbind and by using a vectorized rolling mean function from the RcppRoll package. I did a few other cleanup tasks: passing the data to the function to make it more flexible and using paste0 instead of paste with sep="".

library(RcppRoll)
allFipsRM2 = function(dat, varName, len){
  y <- do.call(rbind, lapply(split(dat, dat$fips), function(x) {
    data.frame(fips=x$fips[1], rm=roll_mean(x[,varName], len), year=seq_len(nrow(x)-len+1)-1)
  }))
  colnames(y)[2] <- paste0("rm",len)
  y
}

We can confirm that this given the same merged results as the original code:

rm1b = allFipsRM2(dat, "x",1)
rm2b = allFipsRM2(dat, "x",2)
outdat2 = merge( dat[, c("fips","x","year")], rm1b, by=c("fips","year") )
outdat2 = merge( outdat2, rm2b, by=c("fips","year") )
all.equal(outdat, outdat2)
# [1] TRUE

To see the performance impact, let's run on a modestly larger version of dat, with 66k rows:

dat <- dat[rep(seq_len(nrow(dat)), 1000),]
system.time(allFipsRM("x", 2))
#    user  system elapsed
#   5.964   2.511   8.549
system.time(allFipsRM2(dat, "x", 2))
#    user  system elapsed
#   0.109   0.007   0.117

We see a speedup approaching 100x for this test data.

You could also update your function to take a vector of lengths in a pretty straightforward way using sapply:

library(RcppRoll)
allFipsRM3 = function(dat, varName, len){
  do.call(rbind, lapply(split(dat, dat$fips), function(x) {
    all.rm <- as.data.frame(sapply(len, function(l) c(roll_mean(x[,varName], l), rep(NA, l-1))))
    colnames(all.rm) <- paste0("rm", len)
    cbind(data.frame(fips=x$fips[1]), all.rm, data.frame(year=seq_len(nrow(x))-1))
  }))
}
outdat3 <- allFipsRM3(dat, "x", c(1, 2))


My experience with Android and handling touch events is that it's very hard to look at the code and understand how it will work when you're running the application. It can even be a difference with different Android devices, so make sure that you test your app on an Android 2.3.5 device as well as an Android 4+ device (assuming you're targeting Android 2.3.5 as well).

From what I understand, "moving the map by touch" you mean that you are scrolling through the map, like a HorizontalScrollView combined with an ordinary (vertical) ScrollView. It is said to be possible to combine these two together to create a "two dimensional scroll view", I myself have not been able to accomplish that in a way that creates a smooth user experience (I actually think this is a bad way of doing it). I have however, managed to find a quite easy-to-use Android view class that takes care of all this scrolling. It seems however like the link has disappeared but you could try this GitHub project, if that doesn't work for you then let me know either by a comment or find me in The 2nd Monitor chatroom and I can provide the implementation I'm using.

As for your existing code, it's clean, it's straight-forward. But where/how is speedX/speedY and touchX/touchY used? Could the problem be there?

I only have one suggestion for improvement of your code:

switch(event.getAction()) {

Should be (see here)

switch(event.getActionMasked()) {

A general suggestion when working with touch events:

Log, Log, and Log Use Log.d("YOUR_TAG", "A whole bunch of information") like a maniac! The more you log, the more you will hopefully be able to understand about MotionEvents, and the better code you will be able to write.


Calling a method in parallel which returns the future

An executor service will be able to do a invokeAll with a timeout and return a set of futures holding all the values or return when the timeout expires.

This means that your executeAsync should take a set of keys and build all the tasks from those at once and then submit the tasks as a batch:

@Override
public List<Future<DataResponse>> executeAsync(Collection<DataKey> keys,  long timeout, TimeUnit unit) {
    List<Task> tasks = new ArrayList<>(keys.size());
    for(DataKey key : keys){
        tasks.add(new Task(key, restTemplate));
    }

    return executor.invokeAll(tasks, timeout, unit);
}

@Override
public List<DataResponse> executeSync(DataKey key) {
    List<DataResponse> responseList = new ArrayList<DataResponse>();

    // make a List of DataKey using single key passed to this method.
    List<DataKey> keys = new ArrayList<DataKey>();

    List<Future> futures = executeAsync(keys, 300, TimeUnit.MILLISECONDS);

    for (Future<DataResponse> future : futures) {
        try {
            if(future.isDone())
                responseList.add(future.get());
            //otherwise future didn't complete in the 300 milliseconds
        } catch (Exception e) {
            // do something
        }
    }
    return responseList;
}


This is a case where a dynamic variable is the ideal solution:

(def ^:dynamic *described-entity*)

(defn it [fun & v]
    (assert (apply fun *described-entity* v)))

(def it-is it)
(def it-is-the it)

(defmacro describe [value nest]
  `(binding [*described-entity* ~value]
     ~nest))

(defmacro when-applied-to [& args-and-nest]
  (let [args (butlast args-and-nest)
        nest (last args-and-nest)]
    `(binding [*described-entity* (*described-entity* ~@args)]
       ~nest)))

(defmacro when-applied [nest]
  `(when-applied-to
    ~nest))

Online resources can probably explain dynamic vars better than I can here.  For the purposes here, think of it like your atom except that it's thread local and will restore the original value when the binding context exits.

To use a macro from another macro, you'll want to do it as shown here rather than trying to literally def it in terms of another macro.  The reasons why should probably be saved for when you get a little more macro experience.

And of course, butlast.

In when-applied-to you can do your argument wrangling outside of the macro.  Note though, I'd probably consider passing args in a vector like (when-applied-to [42 35] (it = 77)) to make the arguments more explicit and require less pre-processing.


To start I know nothing about GRIB-2 that being said I know some ways that you could improve your code.

"Magic Numbers"

Generally you shouldn't put numbers in code where their meaning is unknown. You should set the hanging numbers to constants. Javascript (ES5) doesn't have constants but there are ways to fake it. The number "8" in your code is abstract and one would only know what it is for because you told them. But a without that it would be hard for anyone to know what it means from an initial read through of your code.

Possible Solution - You could create a constant object literal.

var Constants = {
  FLOAT_BIT_LENGTH: 8
}
console.log(Constants.FLOAT_BIT_LENGTH);

Polluting the Global Namespace

As it goes right now your code is putting a bunch of functions and variables into the Global namespace. You should encapsulate your code in a self invoking function, so you can set variables that are global to your code without foo-ing with the global variable scope, if you want other people to be able to embed your code as a module in someone else’s code.

Possible Solution - Self invoking anonymous function to create scope

(function (document) {
 /* code goes here */
})(document);

Non-Descriptive Variables and Parameters

You should be able to read the method signature and know what it does. convert(s, e, d) means nothing to anyone even knowing what the code is for. You could add documentation blocks via JSDocs, and make your function variables more descriptive.

Possible Solution - JSDocs used along with descriptive function arguments

/**
 * Converts a foo into a foobar using bar as the radix and baz as the offset
 * @param {integer} foo - Does x
 * @param {integer} bar - Does y
 * @param {float} baz - Does z
 * @return {float} - x AND y AND z
 */
convertByRadix(foo, bar, baz)

Not Making Use of Function Expressions in Callbacks

Function expressions can be used as a callback function, they are inline and make your code easier to read when the function is only a line or two and have no side effects. Also you don't need to declare all the parameters of a callback, only the ones you are using.

return values.reduce(function(prev, curr) {
  return prev + curr;
});

It may also be worth looking into typed values (that are not boxed) that are available in some Javascript compilers/libraries, like "ASM.js" or "LLJS". As well as looking into possibly using some of Javascripts bitwise operators. Also look into running your code through a linter such as JSHint.


Before looking at your code, I want to give a general notice: don't use linked lists. They are almost always the wrong choice of data structure. They are useful primarily pedagogically.

Furthermore, I should warn you that implementing a doubly-linked list will not look like typical Rust. You can't implement a doubly-linked list in Rust without using escape hatches like Rc, RefCell, or raw pointers. These escape hatches are necessary when doing low level things like implementing a data structure, but normal Rust code avoids them as much as possible. If you want to get used to "thinking in Rust" you should pick a different exercise.

The first thing about your code I note is that Node::add function. It takes a pointer to itself twice. self and this. Having two different pointers to the same thing is unhelpful. Just drop the &self parameter and refer to this consistently in the function. Then you can call the function as Node::add.

The second thing is that you have RefCells containing Rc's. However, the standard way is to have it the other way around. It should be Rc<RefCell<?>> not RefCell<Rc<?>>. You'll find that your current design does not let you modify the value of each node.

A third thing is the lack of mutable references. Your add method allows adding to your list without the list being mutable. That doesn't really make sense, your add method really should take a mutable reference to the list. You get away with this because of the previous point.

Finally, you would be better off not using recursion to add the item to the end of list. Recursion is much slower than iteration. It would make more sense to scan through the nodes looking for the end of the list in a loop than in a recursive function call.


The function concurrent.futures.ThreadPoolExecutor.map is built into Python 3 and does almost the same thing as the code in the post. If you're still using Python 2, then there's a backport of the concurrent.futures package on PyPI.
But considered as an exercise, the code here seems basically fine (apart from the lack of documentation), and the remaining comments are minor issues.
Worker.run could be simplified slightly by writing the loop condition like this:

while not self.in_queue.empty():
    # ...

There's no need to pass a maxsize argument to the Queue constructor—the default is that the queue is unbounded, which is fine.
The only use of the workers list is to start the workers. But it would be easier to start each one as you create it:

for _ in range(num_workers):
    Worker(function, in_queue, out_queue).start()

The results come out in random(-ish) order because threads are nondeterministic. But for many use cases you would like to know which input corresponds to which output, and so you'd like the outputs to be in the same order as the inputs (as they are in the case of concurrent.futures.ThreadPoolExecutor.map).


I can only point out cosmetic issues (I don't know sqat about VBA),
I hope another reviewer will pass by and cover other aspects.

Unused variables

These variables seem to be unused, so why not remove them:

Dim selection As Object
Dim bookmark As String
Dim test As String
Dim pageLoading As Boolean

Magic string

This string appears twice:

"http://www.albumoftheyear.org/ratings/6-highest-rated/"

It would be better to define it one place, so you can change it one place if needed.

Readability

This block:

aotyYear = InputBox("Input the year you're scraping")
If aotyYear < 1900 Then Exit Sub
url = "http://www.albumoftheyear.org/ratings/6-highest-rated/" & aotyYear & "/1"
Set sheet = ThisWorkbook.Worksheets("ScrapeSheet")
row = 2
exitFlag = False
page = 1

Would be more readable if you break a line after the early return:

aotyYear = InputBox("Input the year you're scraping")
If aotyYear < 1900 Then Exit Sub

url = "http://www.albumoftheyear.org/ratings/6-highest-rated/" & aotyYear & "/1"
Set sheet = ThisWorkbook.Worksheets("ScrapeSheet")
row = 2
exitFlag = False
page = 1

It might be a matter of taste,
but I think this would be more readable if the condition was not split,
on a single line.

    If nextPage.Length = 2 _
    Or nextPage(0).innerText = "Next >" Then
        page = page + 1
    Else
        exitFlag = True
    End If


Project Euler Problem 7: Find 10001st prime number

One of the major problem I would like to address is performance.

When thinking about performance, the first question you should ask yourself is: could I use a better algorithm? Turns out there are better algorithms for generating primes, though they would be more difficult to implement (especially since they find all primes up to a certain number, which is not the same as finding the n-th prime).

It's probably not worth it in this case.

  An easy way to improve the performance would be to stop the fold when a prime number is found

You can use Seq.exists for that, which will also make your code simpler:

let isPrime x previousPrimes = not (Seq.exists (isDivibleBy x) previousPrimes)

(I'm using partial function application instead of a lambda, to make the code shorter.)

Other notes:

let isDivibleBy num denum = num % denum = 0

I think this function should be called isDivisibleBy.

match prime with
| true -> …
| false -> …

This is what if is for.

 getPrimesInternal count (num + 1) previousPrimes

If you start with num = 3 (and not 2), you can be sure that all primes that you test will be odd, so you can use num + 2 here, speeding up your code by about 50 %.


Buffer<T>

This class seems fine for the most part. Some small issues:

The while(true) loops in insert(T) and remove() only ever run one iteration. Those loops can be replaced by their body.
add calls m_buffer.push_back(x), which might not compile for types without a copy constructor. Try m_buffer.push_back(std::move(x)) instead: That will move if possible, and fall back to copy if not.
m_buffer is treated like a stack (push_back and pop_back are used only), so newest insertions get removed first. Maybe a queue was intended (using e.g. push_front and pop_back)?
The constructors initialize Buffer<T>::m_size (an unsigned int) with a signed value (1 or int s, respectively).
notify_all() is called on the condition variable. This would wake up every thread waiting on it - but very likely only one would actually be able to do anything. notify_one() would likely be a better fit.
The notify_all calls on the condition variable aren't needed every time: remove only needs to notify if other threads might be waiting to add elements, which is only when m_buffer.size() == m_size - 1 after the call to pop_back. Similarly, add only needs to notify if m_buffer.size() == 1 after push_front.
Buffer<T>::m_size doesn't represent the current size of the buffer (= number of elements contained), but the maximum capacity. Maybe m_capacity would be a better name.
Buffer itself isn't very descriptive of what it actually does. ConcurrentQueue, MessageQueue or similar would better represent its behavior.
While add and remove by themselves are fine names, common expectation for queue-like types are push and pop.
This actually is a working queue for n producers and m consumers. It seems a bit overkill for a 1 producer + 1 consumer scenario.

Furthermore, some improvements could be made:

bool try_push(T&&)/bool try_push(const T&)/bool try_pop(T&) member functions could be added that return early if the operation would otherwise have to wait.
push could be overloaded for const T& and T&& to enable better performance for moveable types.

Producer<T>/Consumer<T>

Both of these don't really seem necessary. Generally, its unlikely that someone will ever need generic producers/consumers (other than maybe for testing purposes), so I won't go into too much detail

Default constructors initialize m_buf to nullptr, but this is never checked afterwards. Either add checks for nullptr in the other member functions, or simply remove the default constructor.
Similarly, the buf parameter of the other constructor can be nullptr. If m_buf should never be nullptr (as the member functions seem to assume), simply make buf a Buffer<T>& instead. m_buf could then be initialized to &buf - but it might be more reasonable to change m_buf to Buffer<T>&, too.
Access to std::cout isn't synchronized. In some cases, this means the consumer might print before the producer does.
There is no way to stop a producer/consumer (other than forcefully terminating the program).
The member m_id is never used.
The second constructor takes a std::string&& id parameter - but initializes m_id without moving - which creates a copy. Generally, it would be expected that the object id refers to would be moved from after construction.

General stuff

main never checks if argv[1] is actually valid.
Using struct data when referencing the type isn't necessary in C++, just data suffices. So typedef struct data elem_t; could be simplified to typedef data elem_t;, or with a more modern approach, using elem_t = data;. (The struct data would be necessary in C, but this code will never interact with C as C doesn't support templates anyways.)
Many places use parentheses to initialize objects, like std::unique_lock<std::mutex> locker(m_mtx);. Prefer braces {} instead: In the example, if m_mtx could be interpreted as a type, then the compiler would be forced to make locker a function declaration. Using braces would prevent that from happening.
Prefer the utilities in the <random> header for generating random numbers, as std::rand is kinda terrible.
There's no need to create buffer, p and c on the heap (inside main). Using local variables would be just fine. (Also, they never get deleted properly. If allocation on the heap is absolutely needed, prefer using smart pointers like std::unique_ptr or std::shared_ptr.)
I cannot think of a 1 producer/1 consumer scenario in which threads are necessary: Most could be simplified to this pseudocode:

int main() {
    while(keep_running()) {
        consume_one(produce_one());
    }
}


Python functions to save JSON and H5 to local files and S3

The S3-functionality wraps the specific code, which does not change the variables. So how about a decorator?

from functools import wraps

def handle_s3_upload(fcn):
    @wraps(fcn)
    def inner(data_fp, data, *args, **kwargs):
        # handle S3 path
        s3 = False
        if data_fp.lower().startswith('s3://'):
            s3_data_fp = data_fp
            data_fp = os.path.join(_TMP, os.path.basename(data_fp))
            s3 = True
        # call decorated function
        fcn(data_fp, data, *args, **kwargs)
        # S3 upload
        if s3:
            save_in_s3(data_fp, s3_data_fp)
    return inner

@handle_s3_upload
def save_json(data_fp, data, sort_keys=True, indent=4):
    with open(data_fp, 'w') as output_file:
        json.dump(data, output_file, cls=NumpyEncoder, sort_keys=sort_keys,
                  indent=indent)

@handle_s3_upload
def save_hdf5(data_fp, data, metadata=None):
    if metadata is None:
        metadata = {}
    mode = 'w'
    if os.path.isfile(data_fp):
        mode = 'r+'
    with h5py.File(data_fp, mode) as h5_file:
        for key, value in data.items():
            dataset = h5_file.create_dataset(key, data=value)


What's wrong with jQuery?  It doesn't get much easier than:

$(document).delegate("<identifier>", "<event>", function (e) { do stuff; });

However, the following link might help you with base javascript event listening and delegation.
https://mattandre.ws/2014/08/small-beautiful-dom-delegation/


If you're using ContainsKey, you're probably doing it wrong and you need to use Dictionary<TKey, TValue>.TryGetValue Method (TKey, TValue).

Your first method would then become:

public double GetTransition(T p1, T p2)
{
    Dictionary<T, int> p1Value;
    if (!_sparseMarkovChain.TryGetValue(p1, out p1Value))
    {
        return 1f/_size;
    }

    int p2Value;
    if (p1Value.TryGetValue(p2, out p2Value))
    {
        return (1f + p2Value)/(_countEltLeaving[p1] + _size);
    }

    return 1f/(_countEltLeaving[p1] + _size);
}

Your naming could be improved. The "MC" in _sparseMC makes sense in context, but why not write "MarkovChain" in full? p1 and p2 aren't clear to me, but I don't know the convention.

These three lines could be a single one:

Dictionary<T, int> nd = new Dictionary<T, int>();
nd.Add(p2, 1);
_sparseMC.Add(p1, nd);

versus:

_sparseMC.Add(p1, new Dictionary<T, int>{{ p2, 1 }});

Use braces everywhere to avoid introducing bugs, even for code like this:

if (_sparseMC[p1].ContainsKey(p2))
{
    _sparseMC[p1][p2] += 1;
}
else
{
    _sparseMC[p1].Add(p2, 1);
}

_sparseMC and _countEltLeaving can be made readonly.


Ages ago I did a Tetris clone, and my idea for a data structure was this:

A circular linked list of matrices.

How do you rotate?  Walk the list...

You can have a single array of these lists (one per each block type), and your game logic's notion of the "current piece" is a reference to something inside that table.  That way the game logic can have no knowledge of the different shapes, and you declare a small array that defines what the shapes are.


Thread-safe arraylist with get, put, add, remove functions

Definitely not!

While using the ReadWriteLock pattern instead of simple intrinsic locking for collections is a good thing to do, you are doing almost everything wrong.
I recommend you to take a deeper look at Synchronizers in Java and also the Decorator Pattern. Following points are done wrong in your snippet:

You are having a ReadWriteLock attribute but don't use it.
The synchronized Collection Wrapper is used in some methods but
doing that will not create any kind of Thread-Safety since the Mutex aquired is chaning every time the method is invoked.
You are having two other locks where as one should be the read and the
other one the write lock. But using those to guard code sections in useless,
since they both have no connection to each other and you don't even lock
every critical section.

Important for you to understand is, that when using locking every access must be serialized / guarded or your locking is worthless. Before you are having an important interview you may take a look at the Book Concurrency In Practice which gives a very good introduction to Java Concurrency.


Rebol View layout compose, seek minima notation

Try to avoid mixed casing in new dialect designs

Rebol preserves the case of characters when they match the lexical rules to become a symbolic type in the homoiconic structure being produced:

>> to-string quote field1.Process
== "field1.Process"

>> to-string quote field1.process
== "field1.process"

Yet despite keeping the case in the symbol, it does not use this to distinguish lookups in the (DO "dialect") evaluator:

>> field1.Process: 10

>> print field1.Process
10

>> print field1.process
10

This is why you will rarely see mixed case symbols in Rebol.  That is, unless they are in a block representing a dialect that was specially written to have case-sensitive behavior.  Your example here is not quarantined in that way.  It's all just running in the default evaluator.

Even if it were quarantined in a dialect: not only is lowercase typing consistent with the language's lookup rules, it's easy on the shift key (as is Rebol's choice of square brackets for the primary block delimiter...)  Try to stick with it where possible.

Don't fight the lexer, use structure!

When you write something like field1.Process that's going to become a single symbol, you're setting yourself up for further processing work.  Now you have to find the position of the period, separate things out, etc.  Luckily Rebol makes that easy:

>> parse "field1.Process" [copy left to "." skip copy right to end]
== true

>> print left
field1

>> print right
Process

Still, it's a bit of a shame to not think a little more outside the box.  Why not filenames (starting with %) to identify fields, and tags (enclosed in <>) to identify your steps?  You don't need to do any extra work:

>> length? [%field1 <Process>]
== 2

>> type? first [%field1 <Process>]
== file!

>> type? second [%field1 <Process>]
== tag!

Depending on your needs, it might be good to free up ordinary words for your dialect keywords.  I don't have an immediate intuition for what you are trying to accomplish here.  But the point is, the more you can leverage the Rebol typeset the better.  And of course there are paths, which are structural:

>> type? quote field1/Process
== path!

>> length? quote field1/Process
== 2

Don't fight the evaluator, make a dialect!

Remember that COMPOSE is (a) something you could have written yourself, and (b) there to help you as a tool in creating your own dialect.  You can even use the /NEXT refinement of DO to chain to the Rebol evaluator to execute one full expression and stop:

niftyprint: function [spec [block!]] [
    pos: head spec
    reversed: false
    while [not tail? pos] [
        case [
            #backwards = first pos [
                reversed: true
                pos: next pos
            ]

            #forwards = first pos [
                reversed: false
                pos: next pos
            ]

            true [
                result: do/next pos 'pos
                prin either reversed [
                    reverse form result
                ] [
                    form result
                ]
                prin space
            ]
        ]
    ]
    prin newline
]

Trying it out, you'll get:

>> niftyprint [{Sum is} #backwards 1020 + 304 {,looc} #forwards "huh??"]
== Sum is 4231 cool, huh??

So you didn't have to reinvent the wheel to delegate to Rebol's inner logic of figuring out (for instance) that infix addition needs to have its two arguments fulfilled.  This can be a way of reducing the need to go around putting brackets on everything, and it can become more free.

Of course, that freedom has some drawbacks.  You get less checking.  But when the tradeoffs are balanced you can get something that has a lot of the feeling of just writing sentences as one would in English.

Moreover, the PARSE dialect itself can be used to make processing your odd blocks all the easier.  Consider an alternative implementation of the above:

niftyprint: function [spec [block!]] [

    direction: #forwards

    output: function [value [any-type!]] [
        str: form value
        if direction = #backwards [reverse str]
        prin str
        prin space
    ]

    parse spec [
        (print "hi" probe pos print "there")
        any [
           set direction #backwards
        |
           set direction #forwards
        |
           pos: (output do/next pos 'pos) :pos
        ]
    ]
]

Just a few thoughts to consider.

P.S. As with LISP eventually going with the trends and going by Lisp, REBOL has "modernized" by officially changing to Rebol (Although the originating company, currently inactive after the open-sourcing, is still incorporated as REBOL Technologies.)  I personally think it looks better to start scripts with Rebol [], but as mentioned above the lookup is case-insensitive... and mixed case is discouraged.  So it's up to you.  Kind of a special case.


Formatting a list of strings as a comma-separated string

It looks idiomatic to me.

There's one slight improvement to the code that I could come up with.  There is a function that does what you're doing in the middle, called intercalate.  Here's the definition, from Data.List:

intercalate :: [a] -> [[a]] -> [a]
intercalate xs xss = concat (intersperse xs xss)

Using that, your function becomes:

asList :: [String] -> String
asList ss = "[" ++ (intercalate "," ss) ++ "]"


Simulate the way that PHP receives the form

I’m not sure if you still maintain this code but if so, you could consider using a FormData object. I see it has been documented on MDN since 2015 and the link to the specification points to whatwg.org, which has been archived since 2012. I found a post on SO from 2011 that uses it. That way you wouldn’t have to manually query the DOM for inputs (I.e. var form = $(':input').not(':submit,:button,:image,:radio,:checkbox'); $.merge(form, $(':checked').not('option'));)- you could just iterate over a newly created FormData object. You would still need to alter input names to remove the brackets when multiple values are allowed.

You might be able to remove jQuery as a dependency, unless there are specific plugins used on the page. For more information, check out youmightnotneedjquery.com/.

I see places where bracket notation is used to alter properties of objects, like below:

input['name'] = name;

and

input['value'] = files[files.length - 1];

However dot notation could be used instead, just as it is used to check the type of the object being iterated over (i.e. if(obj.type==='file'){). It is "faster to write and clearer to read"1

1https://stackoverflow.com/a/4968448/1575353


Largest palindrome made from the product of two 3-digit numbers

When checking to see if a number is a palindrome, you effectively do:

StringBuilder sb1 = new StringBuilder(""+value1);
String sb2 = ""+value1;
sb1.reverse();
if(sb2.equals(sb1.toString()) && ....) {

That should be extracted to a function:

private static boolean isPalindromeSB(final int value1) {
    StringBuilder sb1 = new StringBuilder(""+value1);
    String sb2 = ""+value1;
    sb1.reverse();
    return sb1.equals(sb2);
}

so that you can use it as follows:

if (isPalindromeSB(value1) && ....) {

That neatens up your code, and does what is called "Functional Extraction".

Additionally, if you look at that function it does a lot of work... it does 2 string concatenations, creating three Strings, a StringBuilder, and a bunch more.

It would be more efficient to keep everything as numbers, and have a function like:

private static boolean isPalindrome(final int product) {
    int p = product;
    int reverse = 0;
    while (p != 0) {
        reverse *= 10;
        reverse += p % 10;
        p /= 10;
    }
    return reverse == product;
}

Note that this creates only two int values.... and it loops once per digit.

I tested it, and it is about 4 times faster than the String version.


Ruby: comparing two Arrays of Hashes and mapping one to the other

def mapped_tasks(expected, subtasks, fields)
  fields_match = ->(t1, t2) {fields.all? {|f| t1[f] == t2[f]}}
  expected.map do |e|
    subtask = subtasks.find {|s| fields_match.(e,s)}
    subtask ? e.merge(subtask) : nil
  end.compact
end

should do the same as your original.

use merge rather than explicitly adding each field you want
create a lambda to name the condition of "all relevant fields matching".  this makes the loop within which it is called more readable.
rather than procedurally declaring an array and adding items to it, simply use map to chang all the expected items.  the ones that don't match are changed to nil, and we remove them at the end using compact

notes on the original code:

the data structures that we're assuming exist seem ill-fitted to the problem.  if they're within your control, consider simplifying them.  this should make the solution to the problem here more natural
avoid extraneous information in your variable names.  it gives the illusion of greater clarity but in fact makes the code harder to read at a glance.  eg fields is a clearer name than fields_to_check


Filtering JSONArray by Branding & Modelling

As it happens I have been working with JSON formatted data a little bit recently. I have some ideas that will help you simplify your code.

As for the efficiency, performance wise it looks good. I don't think it can go much faster. In terms of code structure though, there's a few things that can help.

I'll put together a laundry-list of items, and then follow it up with your code restructured...

make your parameters final when you can. It helps with discipline, and occasionally performance too.
Use interfaces instead of concrete classes if you can. The input Parameter ArrayList<JSONObject> should be reduced to an interface, but, not just List, and not even Collection, but Iterable. You should have Iterable<JSONObject>.... which means pretty much anything that has an iterator() method.
jsonFiltersList.size() < 1 is better expressed as jsonFiltersList.isEmpty()
Don't use parenthesis unless they're needed:

if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1))

should be:

if (jsonFiltersList == null || jsonFiltersList.isEmpty())

1-liners should be expressed with a full braced block:

if ((jsonFiltersList == null) || (jsonFiltersList.size() < 1)) return true;

should be

if (jsonFiltersList == null || jsonFiltersList.isEmpty()) {
    return true;
}

The check above shows that you know how to return early (you don't need to wait for the end to return... so, use that to your advantage. Return when you have a result.
You have redundant brandMatch checks:

if (j.get("brand").equals(brand)) {
    brandMatch = true;
}
if (brandMatch) {
    .....

can simply be:

if (j.get("brand").equals(brand)) {
    .....

There is no need to populate the full models array... you can just return if you find a match...
Don't catch Exception, catch JSONException because that's what's thrown.

Putting this all together, your code ends up like:

public static boolean filterMatch(final String brand, final String model,
        final Iterable<JSONObject> jsonFiltersList) {
    if (jsonFiltersList == null) {
        return true;
    }
    try {
        for (JSONObject j : jsonFiltersList) {
            if (j.get("brand").equals(brand)) {
                if (!j.has("models")) {
                    return true;
                }
                JSONArray jArr = (JSONArray) j.get("models");
                if (jArr == null) {
                    return true;
                }
                for (int i = 0; i < jArr.length(); i++) {
                    if (model.equals(jArr.get(i).toString())) {
                        return true;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


Your interface Iclock exposes methods GetNow and GetUtcNow.
Your TestClock class implements it, but because you also want to be able to modify the values you end up by implementing the properties Now and UtcNow.

In my opinion would be a better alternative that IClock would expose a read-only properties,
and that your class would expose the public setter as well:

public interface IClock
{
    DateTime Now{ get; }
    DateTime UtcNow{ get; }
}

public class TestClock : IClock
{
    public DateTime Now { get; set; }
    public DateTime UtcNow { get; set; }
}

Your Increase method in Fuse class is hard to get grasp on.

So... I migth be wrong but you do not want to keep track of the current time when Increase method is called.
What this means is that this line Point = Clock.GetUtcNow(); would become

Point = Point ?? Clock.GetUtcNow();

Furthermore I would consider to move this to some other method.
It could be a wise choice to move it to the constructor, however if you want to have a better control about exactly which tim ite is related to you could have a start method.

public Fuse Start(){
    //if you want to you can check if Point is null and throw an exception if it's not
    Point = Clock.GetUtcNow();
}

It also seems that your Increase method sometimes decides to do his trick and call Reset method.
If I were a consumer of any API I would never guess that a method called Increase would reset something.

In my opinion one simple thing you can do it have a boolean flag that would decide if Reset should be called "automatically".

Obviously this change would be accompanied by a slightly better named method.
Unfortunately nothing better than ShortenFuse comes to mind.

public class Fuse
{
    public Fuse(Threshold threshold)
    {
        Threshold = threshold;
        AutoReset = true;
    }

    public bool AutoReset{ get; set; }

    public Fuse ShortenFuse(int value)
    {
        if (TimedOut && AutoReset) { Reset(); }
        Count += value;
        return this;
    }
    //...
}

One more thing. In your "tests" you do this:

(fuse.Clock as TestClock).UtcNow = new DateTime(2016, 11, 12, 9, 0, 0).AddSeconds(20);

Wouldn't it be much better to put the seconds on the constructor?


I would explicitly refer the constants in class variables :

class Elipsoids:
    airy = Elipsoid(6377563.396, 299.3249646, 'airy', 'Airy 1830', 'Britain', 7001),
    mod_airy = Elipsoid(6377340.189, 299.3249646, 'mod_airy', 'Airy Modified 1849', 'Ireland', 7002),
    ...

This way :

You get rid of global variables : you simply do module.Elipsoids.airy .
You get rid of dirty assigning code
You can get rid of alias if it's not used anywhere else in the code
You get more readable access to variables


Curry function with function constructor

The problem here isn't the Function constructor in and of itself (although it's not a great idea): It's the rest of the code that'll cause trouble, I'm afraid.

You're discarding almost the entire body of the function, and retaining only the return line. And only the first return line at that.

If the test function instead looked like this:

var test = function(a,b,c,d) {
  var product = a * b * c * d;
  return product;
};

you just get an error, since the curried function becomes just:

function(a) {
  return function(b) {
    return function(c) {
      return function(d) {
        return product; // ReferenceError
      }
    }
  }
}

It'll also break if you've got nested functions, like:

var test = function(a,b,c,d) {
  function getRandomNumber() {
    return Math.random() * 10;
  }

  return a * b * c * d * getRandomNumber();
};

since your code only looks at the first return line, and thus the curried function ends up being nothing more than return Math.random() * 10.

And you can't have any close braces before a return line, so even something like this will break:

var test = function(a,b,c,d) {
  if(a == 1) {
    console.log("got: a == 1");
  }
  return a * b * c * d;
};

Since the if's } is before the return, you end up slicing the wrong stuff out of the function's body. This causes the new Function invocation to fail due to a syntax error.

Similarly, a function with no return statement will cause problems:

var test = function(a,b,c,d) {
  console.log(a * b * c * d);
};

And weird comments in the code can trip you up too:

var test = function(a,b,c,d /* more args, y'know */) { ...

Oh, and you're not propagating the context either, so within each level of nesting, this may not refer to the right/expected object.

Lastly, length is not a great way to check arity. Functions may be variadic, taking any number of arguments, whether listed or not (see below, for instance).

So, no, this is not a good way to go. Besides, the Function constructor is just eval in disguise, and should be avoided. Just use bind, or a function like below.

The usual approach is to just wrap the target function as-is. Something like:

function curry(func, args) {
  var spice = [].slice.call(arguments, 1);

  return function () {
    var args = [].slice.call(arguments);
    return func.apply(this, spice.concat(args));
  };
}

This lets you do something like:

var curried = curry(test, 1, 2, 3);
curried(4); // => 24

And it'll work for all the test function variations above.

If you do insist on rewriting code and recursively nesting things, the best I can offer (and it's not a good solution) is to not rewrite the body of the function at all.

Your current solution basically creates nested closures, meaning that the function's body can stay completely intact, only its arguments have to change. It'll just become the inner-most nested closure.

var curry = function(fn) {
  var source = fn.toString(),
      args = source.match(/\((.*?)\)/)[1].trim().split(/\s*,\s*/),
      body = source.replace(/(^.*?\{|\}[^\}]*$)/g, "");

  return args.reverse().reduce(function (nested, arg) {
    return new Function(arg, "return " + nested.toString())
  }, new Function(args.shift(), body));
};

Which produces a function like:

function anonymous(a) {
  return function anonymous(b) {
    return function anonymous(c) {
      return function anonymous(d) {
        // original function body
      }
    }
  }
}

Efficient? No. Robust? Heck no! I won't recommend using it.

But it'll work a lot better for some of the examples listed above. It'll still choke on weird comments, it doesn't do context propagation, can't handle variadics, and it's basically a big fragile hack.  But at least it'll work with local variables, nested functions, additional close braces, and missing return statements.


Find first questions with answers posted within 24 hours

I have to compliment you on how well your query reads. Your aliases are short enough not to be a PITA to reference, yet descriptive enough to not have to scratch your head about what they mean.

Your CTEs are well formatted, pretty easy to read and have good names. Overall, if I was a DBA and saw that in my code base, I'd think the person who wrote it put some work into making it good.

Well done.

Now for a few things to make it even better.

Magic Numbers

Here:

WHERE Q.PostTypeId = 1
-- and later
WHERE (p.PostTypeId = 2

1 and 2 are primary keys in the PostTypes table. This is fine for someone who knows the schema already, but for someone who sees this for the first time, they will have to query the table with those keys to know what they actually mean. So, I recommend using variables, like so:

DECLARE @QuestionPostType INT;
SET @QuestionPostType = 1;
DECLARE @AnswerPostType INT;
SET @AnswerPostType = 2;

Then just reference them by name in your query:

WHERE Q.PostTypeId = @QuestionPostType
-- and later
WHERE (p.PostTypeId = @AnswerPostType

Proliferation of CTEs

It's easy to get lost in data sets in SQL, and while yours works fine, I think it could be simplified a bit. Take for instance:

WITH QData(OwnerId, CDate)
AS
(
  SELECT
  Q.OwnerUserId [OwnerId]
  ,MIN(Q.CreationDate) [CDate]
  FROM Posts Q
  WHERE Q.PostTypeId = 1 AND Q.OwnerUserId IS NOT NULL
  GROUP BY Q.OwnerUserId
),

You have a whole CTE following to extract basically this:

(Q.CreationDate = CDate AND Q.OwnerUserId = OwnerId)

You could just adapt that in your first CTE and simplify it, kind of like this:

WITH QData(OwnerId, CDate)
AS
(
  SELECT
  Q.OwnerUserId [OwnerId]
  ,MIN(Q.CreationDate) [CDate]
  FROM Posts Q
  WHERE Q.PostTypeId = 1 AND Q.OwnerUserId IS NOT NULL
  AND (Q.CreationDate = CDate AND Q.OwnerUserId = OwnerId)
  GROUP BY Q.OwnerUserId
),

Take advantage of joins

Many think of joins as basically just linking keys between one table and another. But, you can use joins to filter data, and keep related conditions/filters together in one join, rather than splitting them up in a bunch of CTEs or where clauses.

For example, you could extract some of the Q & A logic into a join. Whether or not it is desirable, it-depends. But for the sake of example, this:

FROM
  FirstQs JOIN FirstQsA ON QPostId = AParentId

...along with your other filters which are included in your CTEs, could be something like:

FROM
  FirstQs
  JOIN FirstQsA
    ON QPostId = AParentId
   AND Q.PostTypeId = 1 -- or @QuestionPostType
   AND A.PostTypeId = 2 -- or @AnswerPostType


Sorry for bluntness, intended or not, but here we go!

Not very good readability IMO. It takes a while to understand what the code does. Unit tests or at least some sample input and output may make it obvious.

In general, naming should be improved. It's difficult to understand what a function or variable does from its name.

There's also much shuffling of data back and forth that seems unnecessary. It looks like this can be simplified quite a bit, see inline comments.

Also, you use tuples in many situations where a list would be more natural.

As I had problems understanding the code, I may have misunderstood things in it, so read the following inline comments with that in mind.

# notes: separate addresses from data lest the loop of doom cometh

Not a very helpful comment, is it?

class Interpreter:

Can you find a class name that better tells what this class does? It not only interprets.

  def __init__(self):
    self.memory = { }

I'd like a comment on what self.memory is.

    self.dictionary = {"mov" : self.mov,
                       "put" : self.put,
                       "add" : self.add,
                       "sub" : self.sub,
                       "clr" : self.clr,
                       "cpy" : self.cpy,
                       "ref" : self.ref }

No shit, it's a dictionary. But can you find a name that tells what kind of dictionary it is?

To reduce code size, you may consider self.dictionary = dict(self.getattr(attr) for attr in 'mov put add sub clr cpy ref'.split()), but some people may find it too "clever."

    self.hooks = {self.val("0") : self.out }

Very unclear what hooks is for. This is the only value that is every put in it. self.val("0") seems to be just a complicated way of saying (0,). What's up with that?

  def interpret(self, line):
    x = line.split(" ")

Bad variable name: x. Should it be tokens instead?

    vals = tuple(self.val(y) for y in x[1:])

Here, vals could be a list instead, like vals = [self.val(y) for y in x[1:]]. Making it a tuple just makes the code a little bit more complicated for no reason.

    dereferenced = []
    keys_only = tuple(key for key in self.memory)

Consider keys_only = self.memory.keys()? Oh, and by the way, keys_only is never used, so just remove it.

    for val in vals:
      while val in self.memory: val = self.memory[val]

Looks like this while loop will be infinite if it runs at all. Is it supposed to be an if?

      dereferenced.append(val)
    vals = tuple(y for y in dereferenced)

Pointless conversion of dereferenced to tuple.

    self.dictionary[x[0]](vals)

I think the whole interpret method can be rewritten to something like the following. Note the changed names.

  def interpret(self, line):
      command, *tokens = line.split()  # Python 3 only
      values = [self.val(y) for token in tokens]
      dereferenced = [self.memory.get(value, value) for value in values]
      self.dictionary[command](dereferenced)

Some may say it's a bit too terse. I could have written the dereferenced = ... line as a couple of more explicit statements perhaps.

I won't go into the rest, but the comments about naming and unnecessary complexity applies.


In several places you use fmt.Println followed by os.Exit.
You may create your own Exit function to write error message to stderr and terminate.

Note: it is common practice to write error messages to stderr.
stdout is for program output - translated text in your case.

item.Data = v[0].(interface{}).([]interface{})[0].([]interface{})[0].(string)

This statement will trigger a panic someday. I bet you need some recover.

if err := json.Unmarshal(bytes, &result); err != nil {

Hm, you've shaded previous err. Do you need one more error variable?
When you use := operator, it will declare all missing variables on the left that doesnt present in current scope. Example:

str := "What??"
if str != "" {
    str := ""
    fmt.Printf("str is '%s'\n", str)
}
if str != "" { panic(str) }

Other notes:

I see you've used bufio.Scanner to get first line from input. You may consider reading all via ioutil.ReadAll. This way one may pipe some text to your program: cat ./text.txt | go-translate
No need for else branch in main function
value variable is used only once. You may pass result.Data directly to fmt.Printf call.

Example:

func Exit(err interface{}) {
    fmt.Fprint(os.Stderr, err)
    os.Exit(1)
}

func main() {
    fmt.Fprint(os.Stderr, "\nEnter text\t: ")

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    query := scanner.Text()

    response, err := http.Get("https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=es&dt=t&q=" + url.QueryEscape(query))
    if err != nil {
       Exit(err)
    }
    defer response.Body.Close()

    bytes, err := ioutil.ReadAll(response.Body)
    if err != nil {
        Exit(err)
    }

    var result Result
    if err = json.Unmarshal(bytes, &result); err != nil {
         Exit(err)
    }

    fmt.Printf("Translation\t: %s\n", result.Data)
}


Sorting a list but the sort order isn't known until runtime

This:
     if (lvalue == null || rvalue == null)
        return 0;

doesn't seem very safe. It says that if either of the values does not have a defined order, then don't care about the order, consider them equivalent. This will have the effect of interleaving such items throughout your sorted list.
Technically this fails the requirement of Comparator that

The implementor must also ensure that the relation is transitive

In other words, given some strings a, b and c with ordering indices 1, null and 2, your existing implementation will say that a == b, b == c but a != c - this is non-transitive.
Instead: either throw an exception if there is a value with an undefined order; or choose to default undefined-order values at the beginning or end of the list.