I think you did the right thing, if you used ngClick you would loose tooling: syntax highlighting, debugging, linting.

Other than that your code looks good, some minor nitpickings:

a single comma separate var statement is considered better:

var lbutton = element.find("span[class='lb-lk-comm']"),
    dlbutton = element.find("span[class='lb-dlk-comm']");

You keep repeating "lb-voted-comm", you should use a constant for it.
I only understood after reading likeACtion/dislikeAction that lbutton/dbutton stand for likeButton, dislikeButton ( I thought it was left button, double click button or something ), you should spell out those variables names.


Solution to part 1 of Day 7 Advent of Code in Scala

It seems to me that your general approach is solid. One small change I noticed you could make would be to move the Regex declarations outside of the functions parse and innerParse. The reason for doing this is that it is expensive to compile the Regexs with every call to these functions. By moving them out we only construct them once. This is supported by the Scala Regex documentation which can be read here.

case object Command {
  val assignmentRegex = """(.+) -> (.+)""".r
  val rShiftRegex     = """(\w+) RSHIFT (\d+)""".r
  val lShiftRegex     = """(\w+) LSHIFT (\d+)""".r
  val constRegex      = """(\d+)""".r
  val varRegex        = """(\w+)""".r
  val notRegex        = """NOT (\w+)""".r
  val andRegex        = """(\w+) AND (\w+)""".r
  val orRegex         = """(\w+) OR (\w+)""".r

  def parse(s: String): Assignment = {
    def innerParse(s: String): Expr = {
      // ...
    }
    // ...
  }
  // ...
}


It's hard to say anything without profiling the whole application. Two possible scenarios about this point:

  If I were to not have any logic in this code and directly return any integer, my overall code takes 100 ms to complete on an average.

#1

I guess the application processes the output of patternMatch, so maybe it handles different results differently which varies in time. Consider the following example:

public static int patternMatch(int [] pattern1, int [] pattern2, int range) {
    return 5;
}

int result = patternMatch( [] pattern1, int [] pattern2, int range) {
if (result < 10) {
    // do nothing
} else {
    // do something complicated and slow
}

Of course, it might not be so obvious. Profile it!

#2

JMV is smart about optimizations. If you put the simple return 5 statement into the method (as above) the JVM might have fooled you and did not even call the patternMatch method and probably eliminated or optimized other codes too which call patternMatch.

  For example, reconsider the code in Listing 4: note
  that main not only computes result but also uses result
  in the output that it prints. Suppose that I make just
  one tiny change and remove result from the println. In
  this case, an aggressive compiler might conclude that it
  does not need to compute result at all.

Source: Robust Java benchmarking, Part 1: Issues

I've created a test class for testing the runtime. It takes only 8,766 ms on my machine.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.junit.Test;

import com.google.common.base.Stopwatch;

public class AppEngineCompareTest {

    private final Random random = new Random();

    @Test
    public void test() {
        final Stopwatch stopwatch = Stopwatch.createStarted();
        final int count = 20000;
        final int[] ranges = createRandomIntegerArray(count);
        final List<int[]> patternOneList = createPatterns(count);
        final List<int[]> patternTwoList = createPatterns(count);
        System.out.println("gen: " + stopwatch);
        stopwatch.reset();
        stopwatch.start();
        int result = 0;
        for (int index = 0; index < count; index++) {
            final int[] pattern1 = patternOneList.get(index);
            final int[] pattern2 = patternTwoList.get(index);
            final int range = ranges[index];
            result += AppEngineCompare.patternMatch(pattern1, pattern2, range);
        }
        System.out.println("run: " + stopwatch);
        System.out.println(result);
    }

    private int[] createRandomIntegerArray(final int count) {
        final int[] ranges = new int[count];
        for (int index = 0; index < count; index++) {
            ranges[index] = random.nextInt();
        }
        return ranges;
    }

    private List<int[]> createPatterns(final int count) {
        final List<int[]> result = new ArrayList<>(count);
        for (int index = 0; index < count; index++) {
            final int[] patterns = createRandomIntegerArray(60);
            result.add(patterns);
        }
        return result;
    }
}


Grouping utility methods for View classes

Refactoring and renaming isRightEdgeOfScrollViewHasBeenReached

How about like this:

public static boolean isAtRightEdge(ViewGroup viewGroup) {
    View childView = viewGroup.getChildAt(viewGroup.getChildCount() - 1);
    return childView.getRight() == viewGroup.getWidth() + viewGroup.getScrollX();
}

I haven't tested this, but it compiles.
As such, I don't really see a reason to limit the method to take a HorizontalScrollView as parameter.
Do let me know if you see some shortcomings in your tests.

Also, I removed the unnecessary parentheses from the return statement.

Organizing helper methods and utility classes

Here are some general tips:

Only move a method from your real class to a utility class if you will actually use it in at least two unrelated classes, right now. Don't add utility classes that "seem like a good idea", or if you're sure "you'll definitely use it sometime really soon". Don't speculate, wait until you have an actual use case.
Don't nest utility classes. Nested classes were not intended for this purpose, it would be misusing the language. This page in the docs explains when it is appropriate to use nested classes.
If you start to have too many methods in the utility class, or when it makes sense, split to multiple classes. (As you proposed in option 2.)
Avoid overloaded helper methods with the same number of parameters. (This is just a tip for the future, there was no such example in your post.)
Prevent instantiation of utility classes by adding a private parameterless constructor, for example:

private ViewUtils() {
    // utility class, should not instantiate
}


Data analysis code (finds coincidences in three sets of data)

Undefined behavior
There's UB in case when empty vector passed to the binary_search.
unsigned int mid;

it is uninitialised and will pop whatever compiler think he want in release mode. To solve this issue it is require initialise value with some error value (usually it is ~0 but you can choose your own), or use std::optional (c++17) and handle error case in lambda.
probably it is not an issue if vectors guaranteed to be non-empty and there's at least one proper value inside them.
mix of signed and unsigned types
Return type of binary_search is int, but branches can be unsigned int.
As it is actually return position in vector best way to use special unsigned integral type macro size_t meant to be used like this. So final check will be like.
...
constexpr size_t ERR = ~0;
siz_t res_i = binary_search(vec2, tstamp);
if (ERR == res_i) return; // early exit from lambda
...

But that kind of handling raise question about how to handle res_i-- if binary search return position 0. It probably will return INT_MAX for according integral type, but that kind of subtraction is implementation defined behavior so result defined by compiler.
potential out of bounds
if binary search return 0 position access to -1 will crash your program.
double r = dabs(tstamp-vec2[res_i-1]);

tightly related to previous issues.
probably it is not an issue if found position never meant to be 0
unnecessary variable reusing
If your program don't meant to be run on some embed device this kind of optimization basically do nothing - compilers usually smart enough to get rid of it by themselves. Probably good idea create some small function and p,q,r manipulations in it. Also it will prevent chance to make copy-paste errors
size_t someRoutine(double tstamp, const auto& vec, size_t res) {
  double p = dabs(tstamp-vec[res]);
  double q = dabs(tstamp-vec[res+1]);
  double r = dabs(tstamp-vec[res-1]);

  if(r<q && r<p) return res-1;
  if(q<r && q<p) return res+1;
  return res;
}
//...
res_i = someRoutine(tstamp, vec2, res_i);
res_j = someRoutine(tstamp, vec3, res_j);

structs clearer than vector
it is good idea to create a struct instead of using a vector - less memory print, clearer usage.
struct SomData{
  double tstamp, vec2,vec3, first, second, third, fourth;
};
//...
coincidences.push_back({tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth});
// OR
// coincidences.emplace_back(tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth); // construct struct in-place,
//...
std::sort(coincidences.begin(), coincidences.end(),
   [](const SomData& A, const SomData>& B){
            return A.fourth < B.fourth;
});
///...
cache.insert(pair.vec2);cache.insert(pair.vec3);

no need to use find if you don't need an iterator
maps ands sets have convenient method count which represents amount of items found by the key. You just need to check whether its zero or one
if(cache.count(pair.vec2) == 0 && cache.count(pair.vec3) == 0) {
  std::cout << "Coincidence found!\n";
  cache.insert(pair.vec2);
  cache.insert(pair.vec3);
}

cycle copy elements
probably just missed &
for(const auto& pair : coincidences){


#include <iostream>

You don't seem to need this include.

size_t _width;
size_t _height;

These should both be std::size_t.

CSV(const std::string& filepath)

Single argument constructors should almost always be explicit.

if (!file)
    throw std::exception();

What you want to throw here is std::runtime_error or something derived from it, not std::exception.

for (std::string line; std::getline(file, line);)
{
    std::stringstream ss1(line);
    std::vector<T> row;

    for (std::string field; std::getline(ss1, field, ',');)
    {
        std::stringstream ss2(field);
        T item;

        ss2 >> item;
        row.push_back(item);
    }
    _data.push_back(row);
}

Alright, let's get into the meat of this.

for (std::string line; std::getline(file, line);)

There's really nothing you can do to improve the outer for loop prologue. One would hope line's memory would get reused, so there will be allocations only until the longest line is read. You could pull line out of the for prologue and reserve() a reasonable size for it to potentially eliminate all allocations in the loop, but then you'd have to know in advance how much to allocate, which doesn't seem generally likely.

std::stringstream ss1(line);

Here is where you can start making gains. The purpose of ss1 is just to split line by commas. That doesn't seem necessary. You can drop ss1, and change the inner for loop to:

std::string field;
for (auto p = line.cbegin(); get_field(p, line.cend(), field); )

Then you could write a get_field() function (maybe private and static in the class) something like:

template <typename ForwardIterator>
auto get_field(ForwardIterator& next, ForwardIterator last, std::string& field) -> bool
{
    if (next == last)
        return false;

    if (*next == ',')
        ++next;

    // This just gets everything up to the next comma, as your
    // current code does... but you could modify it to handle
    // escaped or quoted values.
    auto const first = next;
    next = std::find(next, last, ',');
    field.assign(first, next);

    return true;
}

Taking field (and first) by non-const reference is generally bad practice, but for an internal implementation function, it's okay - especially given that you're gunning for speed gains.

On top of this, you can move field outside of even the outer for loop - again, generally bad practice, but you're gunning for speed not beauty.

Here's another optimization opportunity. Currently you don't bother to check for row size until after everything's read. Instead, what you can do is start with _width as zero, and then at the end of the loop, set it to row.size(). Then right after you create row, you can do row.reserve(_width);. That will (hopefully) prevent the push_back()s in the inner loop from triggering allocations.

Now the inner loop is:

{
    std::stringstream ss2(field);
    T item;

    ss2 >> item;
    row.push_back(item);
}

There's not much you can do to improve this for efficiency, except that the last line should be row.push_back(std::move(item));. What you should do, though, is check that the formatting worked.

And of course, after the loop, you should move the row into _data, not copy it.

So the modified loop might look something like:

std::string field; // outside the loop so we can continually reuse the memory
for (std::string line; std::getline(file, line);)
{
    std::vector<T> row;
    row.reserve(_width); // reserve what we think the width is going to be, to prevent allocations when doing push_back()

    for (auto p = line.cbegin(); get_field(p, line.cend(), field);)
    {
        std::stringstream ss{field};

        T item;
        if (!(ss >> item))
            throw std::runtime_error{"invalid field"};

        row.push_back(std::move(item));
    }

    _width = std::max(_width, row.size()); // get a better estimate of the width
    // Note that you could actually do a check here to make sure the
    // width stays consistent, and fail early if not rather than
    // waiting until the whole file has been read before failing.

    _data.push_back(std::move(row));
}

That is about the best I can think of, performance-wise, for the main loop.

if (!_height)
    throw std::exception();

Again, you should throw std::runtime_error, not std::exception. std::exception should only be used as base class.

_width = _data[0].size();

If you get the width in the loop as I suggested, you don't need this line.

for (auto& row : _data)
    if (row.size() != _width)
        throw std::exception();

This could be done with an algorithm:

if (!std::all(_data.cbegin(), _data.cend(), [_width](auto&& row) { return row.size() == _width; }))
    throw std::runtime_error{"different widths"};

On to the other functions....

size_t  Width(void)
{
    return _width;
}

You don't need to declare void to specify an empty argument list; that's archaic C stuff.

This function, and Height() as well, can be both const and noexcept, and should be at least const.

const std::vector<std::vector<T>>   &Data(void)
{
    return _data;
}

It is standard practice in C++ to keep pointer and reference modifiers with the type. In other words const std::vector<std::vector<T>>& Data(), not const std::vector<std::vector<T>>   &Data().

This function should also be both const and noexcept.

Summary

Try to use as much information from previous iterators to make subsequent iterators more efficient. For example, once you know the width of a row, use that to preallocate the row vector.
Moving allocating variables (like strings) that get reused repeatedly out of the loop may allow you to reuse the memory, and avoid allocations.
Move whenever possible, rather than copying.
You don't need to create a string stream just to split on commas.
std::exception is a base class, not a general use exception class. Use std::logic_error or std::runtime_error or derived classes as appropriate.


What's a better way to decrease cardinality when serializing records

You can use XElement.
It is especially useful when constructing XML.

using namespace System.Xml.Linq
Add-Type -AssemblyName System.Xml.Linq

Get-Data | Group-Object Invoice | ForEach-Object {

    $items = $_.Group | ForEach-Object {
        [XElement]::new('Item', @(
            [XElement]::new('Line', $_.Line)
            [XElement]::new('Description', $_.Description)
            [XElement]::new('Price', $_.Price)))
    }

    $xml = [XElement]::new('I', @(
        [XElement]::new("Invoice", $_.Name)
        [XElement]::new("Date", $_.Group[0].Date)
        [XElement]::new('Items', $items)
    )).ToString()

    $xml
}


Setting fixed height panes based on window's width

Your provided code is fairly small, so there's not much to review, but nevertheless.

Your comment on making 768 a constant is a valid idea,

const MAX_WINDOW_WIDTH = 768;

...

if (window.innerWidth > MAX_WINDOW_WIDTH) {

for magic numbers (unexplained numbers meaning unexplained things), it's best to declare as a const, but your version of JavaScript may not support this, so you can also use var.

I don't particularly understand why you have double underlines in '.search__results', and to answer your question: you could declare it as a variable if you like, but it really wouldn't matter either way.

I think 'overflow-y-scroll' is a bad name for a CSS class as it's, basically the content of the class.

  where it is the single point for setting the breakpoints?

You can set breakpoints in the relevant debugger on your browser, usually labelled Developer Options, or something similar.

You don't really need to worry about your code violating DRY principles, the if-else loop cases aren't really similar enough for that. If you had something like twenty identical lines in there, maybe so.

Good questions, and clean code, good work!


Multiple source of information

You have 4 data structures (1 list and 3 dictionnaries) whose content needs to be kept in sync because values in the list need to be keys of the dictionnaries and keys from the dictionnaries not in the list are pointless.

Maybe thing would be clearer if you had only a single source of truth. For instance, you could have a single dictionnary mapping values to idealWeight, bagCoins and coinWeight (whatever it means). Python offer simple ways to do so via tuples or namedtuples.

FOr instance, you could do something like:

from collections import namedtuple
bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0

CoinInfo = namedtuple('CoinInfo', ['idealWeight', 'bagCoins', 'coinWeight'])

COINS = {
    '2':    CoinInfo(120,  10, 12),
    '1':    CoinInfo(190,  20,  9.5),
    '0.50': CoinInfo(160,  20,  8),
    '0.20': CoinInfo(250,  50,  5),
    '0.10': CoinInfo(325,  50,  6.5),
    '0.05': CoinInfo(325, 100,  3.25),
    '0.02': CoinInfo(356,  50,  7.12),
    '0.01': CoinInfo(356, 100,  3.36),
}

def inputs():
    global bagWeight
    global totalCoinsAdd
    global totalCoinsRemoved
    #The above grabs the global variables for use in the function
    bagWeight = int(input("How much does the bag weigh? "))
    denomination = ""
    while denomination not in COINS:
        denomination = input("What denomination is the money? £")
    coin = COINS[denomination]
    AddCoins = True     #This defines a variable for whether to add/remove coins.
    differentWeight = coin.idealWeight - bagWeight
    #This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
    coinInBag = bagWeight/coin.coinWeight
    #This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
    coinChange = coin.bagCoins - coinInBag
    #Calculating the amount of coin difference in the bag

The AddCoinss variable

The comment This defines a variable for whether to add/remove coins. is very verbose and could be a simple Add/remove coins.

By the way, there is a style guide for Python code called PEP 8 which is definitly worth reading and worth following if you don't have any good reason not to do it (legacy project, company code style, etc). Among other things, it says that snake_case should be used for variable (instead of CamelCase).

Also, the way we check it later on can be improved for 2 reasons :

when a variable (or any expression) is known to be a boolean, it is better to write if var (resp. if not var) instead of if var == True (resp. if var == False). In a real life situation, you'd say "if it rains" rather than "if it is True that it is raining".
you check if AddCoins == True and then just after if AddCoins == False without changing the value of AddCoins. This is exactly what the else keyword is for. It makes the code much clearer to the reader because one knows at first glance that we'll go though one and only one of the block.

So far, we have:

add_coins = True  # Whether to add/remove coins.
if differentWeight < 0:
    add_coins = False
    differentWeight = differentWeight  * -1
    coinChange = coinChange * -1

if add_coins :
    print('The bag is ',str(differentWeight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange
else:
    print('The bag is ',str(differentWeight), 'g more than it should be')
    print('Remove ', int(coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved + coinChange

Now, this variable is not so useful at all because we are performing the test that really matters (differentWeight < 0) just before and we could handle the different processing directly here.

Also, here again, variable name can be improved and you could use var *= -1 instead of var = var * -1.

The code would look like:

if different_weight < 0:
    different_weight *= -1
    coinChange *= -1
    print('The bag is ',str(different_weight), 'g more than it should be')
    print('Remove ', int(coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved + coinChange
else:
    print('The bag is ',str(different_weight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange

As pointed out in Mathias Ettinger's comment, you might as well get rid of the multiplication altogether and just consider the negative value when printing :

if different_weight < 0:
    print('The bag is ',str(-different_weight), 'g more than it should be')
    print('Remove ', int(-coinChange), ' coin(s)')
    totalCoinsRemoved = totalCoinsRemoved - coinChange
else:
    print('The bag is ',str(different_weight), 'g less than it should be')
    print('Add ', int(coinChange), ' coin(s)')
    totalCoinsAdd = totalCoinsAdd + coinChange

String formatting

Python offers different nice ways to format string and providing multiple arguments to print is not the favorite way to do this. You can find documentation online about string formatting but pyformat.info provides a very nice summary.

Using this, you could write something like:

    if different_weight < 0:
        print('The bag is {}g more than it should be'.format(-different_weight))
        print('Remove {} coin(s)'.format(-coinChange))
        totalCoinsRemoved = totalCoinsRemoved - coinChange
    else:
        print('The bag is {}g less than it should be'.format(different_weight))
        print('Add {} coin(s)'.format(coinChange))
        totalCoinsAdd = totalCoinsAdd + coinChange

again = 'yes'
while again != 'no':
    inputs()
    totalBagsChecked = totalBagsChecked + 1
    again = input('Would you like to weight another bag? ("no" to quit)')

print('Total coins added: {}'.format(totalCoinsAdd))
print('Total coins removed: {}'.format(totalCoinsRemoved))
print('Total bags checked: {}'.format(totalBagsChecked))

Global variables

In general, it is a bad idea to use global variables and it tends to show that there is a problem in the way your code is organised.

In any case, bagWeight does not need to be a global variable.


Web-App for to determine gender, age, emotions of a person (shown on an image)

Addressing Your Questions

Is my usage of fetch-API and Promises correct and done in a good way?

Yes it seems fine. The Fetch API is supported by all major browsers but not IE1 but some argue that it doesn't really have a simple way to cancel requests. If there arises a need to abort requests, then other libraries like SuperAgent or reqwest could be used.

Is there are better solution then deleting the unnecessary sub-object?

Obviously there are other ways to handle setting the values within the emotion property on faceAttributes, but those might likely require more lines. One could also conditionally display list items (e.g. add if (typeof facesAttributes[key] !== "object") { before the line that pushes strings into listItems). If there was a way to filter with a callback when calling Object.extend() that would be an advantage here but unfortunately it doesn't appear that is the case.
Other review points
Feedback
The code looks quite succint. There are two DOM lookups at the start but then one DOM lookup in the click handler so that could be cached in a variable.
Suggestions
var vs let/const
Perhaps you have already learned more about let and const since posting this question but many es-6 developers would prefer using const for values that don't change (e.g. imgUrl, initObject, etc.)
Template
One could also utilize a script template to display the list items, though that may not be desirable here.
Invalid HTML when Error occurs
This line in the promise catch:

attributesList.innerHTML = 'Have you entered a valid image URL?';

Sets the inner HTML of the unordered list tag to a text string. That is technically unpermitted content for an unordered list. Perhaps a better solution would be to have a separate element for the error message.
P.S.
Here is the output from that AJAX call using that image of Tesla, so you could fake it now that the key is invalid:

const output = [{"faceId":"950c26ae-70f0-4365-8279-fcd987f56e70","faceRectangle":{"top":75,"left":32,"width":117,"height":117},"faceAttributes":{"gender":"male","age":37.0,"emotion":{"anger":0.0,"contempt":0.0,"disgust":0.0,"fear":0.0,"happiness":0.007,"neutral":0.992,"sadness":0.0,"surprise":0.0}}}];
const p1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, output);
  });
p1.then(console.log);


Well, it works. Better algorithms will be given in the discussion list on the Project Euler site, so I'll just look at JavaScript style.

    for (d = 1; d <=20; d++) {

For consistency, there should be a space in <= 20.

        if (number % d === 0) {
            continue;
        } else {
            return false;
        }

When the code skipped by continue is so short, it's more readable to invert the condition and remove the continue:

        if (number % d !== 0) {
            return false;
        }


First, proper indentation helps a lot. I do appreciate you not putting the closing parens on separate lines though. Thank you.

(defun string-to-list (string)
  (loop for char across string collect char))

(defun is-vowel (char) (find char "aeiou" :test #'char-equal))

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun letter-type (char)
  (if (is-vowel char) "V"
      (if (is-consonant char) "C"
      "0")))

(defun analyze-word (word-string)
  (loop for char across word-string collect (letter-type char)))

We're talking about Common Lisp, so there's no call to go defining your own string-to-list, especially if you're doing it in terms of loop. You can do the same thing with a coerce call.

CL-USER> (coerce "an example" 'list)
(#\a #\n #\  #\e #\x #\a #\m #\p #\l #\e)

Though now that I look at it, you don't call string-to-list anywhere anyway, so we may as well just remove the definition.

(defun is-vowel (char) (find char "aeiou" :test #'char-equal))

(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun letter-type (char)
  (if (is-vowel char) "V"
      (if (is-consonant char) "C"
      "0")))

(defun analyze-word (word-string)
  (loop for char across word-string collect (letter-type char)))

Common Lisp convention is to use a suffix of p or -p for predicates, rather than an is prefix.

(defun vowel-p (char) (find char "aeiou" :test #'char-equal))

(defun consonant-p (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))

(defun letter-type (char)
  (if (vowel-p char) "V"
      (if (consonant-p char) "C"
      "0")))

You can use cond rather than chaining ifs. Typically, this makes the intent clearer.

(defun letter-type (char)
  (cond ((vowel-p char) "V")
        ((consonant-p char) "C")
        (t "O")))

If you want to make the result of analyze-word a string, you'll need to return a character rather than a string from letter-type

(defun letter-type (char)
  (cond ((vowel-p char) #\V)
        ((consonant-p char) #\C)
        (t #\O)))

At that point, you can coerce its result.

CL-USER> (coerce (analyze-word "supercalifragilistiwhateverthefuck") 'string)
"CVCVCCVCVCCVCVCVCCVCCVCVCVCCCVCVCC"

Since your function is taking a sequence of characters, and returning a sequence of characters in the same form, it's actually easier to define analyze-word in terms of map than in terms of loop (in my experience, this is atypical but still worth looking out for).

(defun analyze-word (word-string)
  (map 'string #'letter-type word-string))

That will take "the function named letter-type", apply it to each element of word-string and return the resulting string. This also saves you from having to coerce its result after the fact.

CL-USER> (analyze-word "supercalifragilistiwhateverthefuck")
"CVCVCCVCVCCVCVCVCCVCCVCVCVCCCVCVCC"

Take this last point with a grain of salt though, because if you ever need to re-write analyze-word to return something like (list :consonants 21 :vowels 13), you'll be right back to loop.


Calculate co-occurrences of some words in documents dataset

There is no docstring. What does the function do? What argument does it take? What does it return?
city_list is a global variable. It would be better if this were passed as a parameter to the function: this would make it easier to reuse the function or write unit tests.
The algorithm has nothing to do with cities: it would work just as well for countries, or people, or any other set of search terms. It would make this generality clearer if city_list were named something like terms.
The variable names are vague and the code would be easier to understand if they were more specific. data is a collection of documents, so documents would be clearer. temp is a document from the collection, so document would be clearer. com is a data structure containing counts of co-occurrences that will be returned as the result of the function, so a name like result would be clearer.
There are two loops over i and j such that 0 <= i < j < len(city_list). These could be combined into a single loop using itertools.combinations:

for i, j in combinations(range(len(city_list)), 2):

The only purpose of these indexes is to select the two cities. It would simpler to iterate over the cities directly, avoiding the need for their indexes.

for w1, w2 in combinations(city_list, 2):

The data structure com is a mapping from first city to mappings from second cities to counts of co-occurrences. Unless you really need all those mappings it would simpler if the data structure were a mapping from pair of cities to count of co-occurrences.
When you have a data structure containing counts of items, using collections.Counter often makes the code simpler. First, create the counter object:

result = Counter()

and then increment the count:

if " " + w1 + " " in temp and " " + w2 + " " in temp:
    result[w1, w2] += 1

Searching for terms with spaces before and after will miss matches at the beginnings and ends of documents. It would be more reliable to use a regular expression match together with the \b (word boundary) code:

if all(re.search(r'\b{}\b'.format(re.escape(term)), temp) for term in (w1, w2)):

(See the documentation for re.search and re.escape.)
The implementation in the post searches for every pair of cities in every document. If there are \$k\$ cities, \$n\$ documents, and \$w\$ words per document, then the overall runtime is \$Θ(nk^2w)\$.

An alternative approach is to check each word in each document to see if it is a city, and then to iterate over all pairs of cities found in the document. This has runtime \$O(k + n(w \log w + \min(w, k)^2))\$ since there can be \$O(w)\$ cities found in each document. This is more efficient than the original code in all cases, and much faster if (as one might expect) most words in the document are not search terms.

This could be implemented like this, by joining the search terms together into a single regular expression and then using the findall method:

from collections import Counter
from itertools import combinations
import re

def co_occurrences(documents, terms):
    """Return mapping from pairs of search terms to a count of documents
    containing both terms.

    """
    # Ensure that longer terms match in preference to shorter terms
    # that happen to be initial substrings.
    terms = sorted(terms, key=len, reverse=True)
    # Regular expression matching any of the terms, as complete words.
    search = re.compile(r'\b(?:{})\b'.format('|'.join(map(re.escape, terms))))
    result = Counter()
    for document in documents:
        matches = sorted(set(search.findall(document)))
        result.update(combinations(matches, 2))
    return result


Computing integer square roots in Java - follow-up

When using function parameters, use the primitive types when available:

Function<Long, Long> function

is a red-flag, and should be LongUnaryOperator.

Your code will spin in to an infinite loop for 25% of all long values .... anything larger than Long.MAX_VALUE/4 will cause this loop to become infinite:

    // Do the exponential search.
    while (4 * sqrt * sqrt <= number) {
        sqrt *= 2;
    }

About that loop.... why do you have a magic number 4....? What does it do?

This code needs more testing... and magic numbers need to be removed.


Mapping file data to environment variables

This code is very clean and is definitely a clear improvement from your last version.

Your code is easy to understand and follow, now that's it's more broken up (aside from one big block of code).

I recommend storing your regexular expression for locating the extension .env like this:

var env = new RegExp("\.env$/", "");

The reason is for this: RegExp.test.

The test method of a RegExp object does the following:

Returns true if the regexular expression matches the input string.
Returns false if the regexular expression does not match the input string.

Now, your isEnv function does this:

return env.test(fileName);

Why is this better? Well...

The test method of RegExp only has to worry about the regexular expression matching at all.
The match method of a string has to worry about the regexular expression matching AND it has to worry about creating and returning an array of all the matches.

That being said, the test method is obviously faster than using match.


A program that spells a given number [1-999,999,999,999]

There is no reason for dictionaries when you have an ordered list of items starting at zero with no missing indexes, a list will do just fine.

 suffixes = ['billion', 'million', 'thousand', '']

names_dict could be two seperate variables, because you are only accessing it with literal keys.

ONES = {0: '', 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}
TENS = {0: '', 2: 'twenty', 3: 'thirty', 4: 'fourty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninty'}

although it may not be as efficient, digit_extract() can be made very simple with a list comprehension:

def digit_extract(num, digits=12):
    return [
        (num // (10**n)) % 10
        for n in range(digits, -1, -1)
    ]

note the default amount of digits, so if your requirements change it will be easy to modifiy your code. If you choose to go this route, then you will have to account for the number of digits not being divisible by three.
Your solution for digit_extract() is also fine, but consider using reversed(digit) instead of digit[::-1] as reversed is more readable.
Since hundred() takes exactly three args, there is no need to pass it a list.

def hundred(hundreds, tens, ones):
    ...

would work instead, and if one wanted to pass a list they could call hundred(*three_digit).
when documenting python functions, the convention is to provide a docstring

def hundered(three_digit):
    """
    list [3 digit] to str
    """

this allows documentation to be accessed by hundred.__doc__.
Consider passing an integer argument to numberNames() and returning a string. Example:

def numberNames(num):
    ...
    return final_name.title()

if __name__ == "__main__":
    print(numberNames(input('Enter the number: ')))

This way numberNames can be reused in other contexts. the if __name__ == "__main__": condition allows your program to be imported as a module and its code reused  without runnint the program.
You can also simplify the for loop by iterating over digits and suffixes seperatly:

for suffix, i in zip(suffixes, range(0, 12, 3)):
    hund = hundered(digits[i:i+3])
    if hund != '':
        final_name += hund + ' ' + suffix + ' '

  feedback on my variable naming practices

Just because you mentioned it, try not to mix camel case (i.e. functionName) and undersocres (i.e. function_name).
pep8 suggests underscores and naming constant variables in all caps.


def combinations_permuted(n_elm):

IMO n (as used in the description of the code in the question) is more readable than n_elm.

    items = list(range(0,n_elm+1,1))

1 is the default step, and range isn't so obscure a function that the maintenance programmer would wonder what range(0, n+1) does.

    combinations = pd.DataFrame(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.combinations_with_replacement(items, n_elm)))))
    comb_permuted = pd.DataFrame()
    for index, combination in combinations.iterrows():
        comb_permuted=comb_permuted.append(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.permutations(combination.tolist(), n_elm)))))

    return(comb_permuted.drop_duplicates().as_matrix())

There are two things here which sound warning bells:

comb_permuted=comb_permuted.append. The documentation for DataFrame.append says

  Iteratively appending rows to a DataFrame can be more computationally intensive than a single concatenate. A better solution is to append those rows to a list and then concatenate the list with the original DataFrame all at once.

drop_duplicates(). That says that the generation process is doing more work that it needs to.

A KISS approach would be to replace the combinations_with_replacement, permutations, drop_duplicates chain with itertools.product. This is much faster at n = 3, but already slower at n = 5 (because it's still doing more work that it needs to, and filtering).

The efficient approach is to do only the work that's necessary. A quick and dirty implementation (i.e. please tidy it up before using) calculates for n = 6 in less time than it takes the original code to calculate n = 3:

def combinations_recursive_inner(n, buf, gaps, sum, accum):
  if gaps == 0:
    accum.append(list(buf))
  else:
    for x in range(0, n+1):
      if sum + x + (gaps - 1) * n < n: continue
      if sum + x > n: break
      combinations_recursive_inner(n, buf + [x], gaps - 1, sum + x, accum)

def combinations_recursive(n):
  accum = []
  combinations_recursive_inner(n, [], n, 0, accum)
  return pd.DataFrame(accum).as_matrix()

Online test and benchmark


Macro for transforming 2 way matrix into 1 way matrix

Your description is not very clear, but I see the usual suspects.

Indenting

Always indent your code properly - this makes it easier to read, easier to pick out the logic loops and easier to maintain. In itself, it does not guarantee code correctness.

Option Explicit

Always put Option Explicit at the top of your modules.

Variable names

Use descriptive variable names. For what you tell us the code is intended to do, curDate and curCountry mean nothing. Neither does colsX, rowsX, def, Rng or Mrange.

Use arrays

Using arrays will improve your performance significantly. The reason for this improvement is that you stop switching between the VBA Engine and the Excel Engine (which comes at a cost) and you work purely in the one context. You also stop working with complex objects, which also incur an overhead.

The following is an example of how to adjust the code, but is not intended to be an accurate representation of your code.

Dim originalMatrix as Variant
originalMatrix = Selection.Value '<-- creates an array from the range values - only time to touch Excel
Dim title as String
title = CStr(originalMatrix(LBound(originalMatrix,1), LBound(originalMatrix,2))
Dim finalMatrix(,) As Variant '<-- or whatever type you want here
ReDim finalmatrix(UBound(originalMatrix,1) * UBound(originalMatrix,2),2)

' Adjust following loops to pick the right rows and columns.
For iterator1 = LBound(originalMatrix,1) To UBound(originalMatrix,1)
    For iterator2 = LBound(originalMatrix,2) To UBound(originalMatrix,2)
        finalMatrix(someCounter,1) = someValue1
        finalMatrix(someCounter,2) = someValue2
    Next iterator2
Next iterator1

'.... some code here to select output range and resize to match finalMatrix …
' … and then
outputRange.Value = finalMatrix '<--- again, a light touch against the Excel model

The use of LBound and UBound protect you against any confusion as to whether your array is 1-based or 0-based.You could store these in variables if you wanted the code to read a bit better.


For each pair of strings, eliminate the characters they have in common

I hate this code, but it is faster.

You said you are only working with strings made of characters from a-z.
That means 26 characters. The idea is to use 26 counters, each belonging to a character from a-z.

Go through the first(second) string, and every time you find a character c, you increment(decrement) c's counter by 1.

If every counter is zero, that means the strings are permutations of each other, i.e. it's a draw.

Otherwise if every counter is non-negative, you'll know that the first string won; if every counter is non-positive, you'll know that the second string won.

Finally, if some counters have different signs, then it's again a draw.

You can check if all the counters are non-negative like so.
Set a variable allnonneg to true if the first counter is non-negative. Then loop through the remaining counters.

If during the \$i\$-th iteration you find a counter, which is negative, then you change allnonneg to false. Otherwise you keep allnonneg as it is.
If in the end allnonneg is true, then you know that every counter was non-negative. If it's false, then you'll know that there was a counter which was negative. This is because the only way the value of allnonneg can change is if there is a counter which is negative.

To do this manipulation, you need a function f, such that f(allnonneg, charset[i] >= 0) is true precisely when both allnonneg, and charset[i] >= 0 are true. Luckily there's already an operator && which does this, so we get

allnonneg = f(allnonneg, charset[i] >= 0) = allnonneg && (charset[i] >= 0)

which is the same as allnonneg &= (charset[i] >= 0).

private static int decide(String sa, String sb){
    int [] charset = new int[26];

    for(int i = 0; i < sa.length(); charset[sa.charAt(i) - 97] ++, i++);
    for(int i = 0; i < sb.length(); charset[sb.charAt(i) - 97] --, i++);

    boolean allnonneg = charset[i] >= 0;
    boolean allnonpos = charset[i] <= 0;

    for(int i = 1; i < 25; i++) {
        allnonneg &= (charset[i] >= 0);
        allnonpos &= (charset[i] <= 0);
    }

    if(allnonneg && allnonpos)
        return 0; // every counter 0 => draw
    if(allnonneg)
        return 1; // 1st won
    if(allnonpos)
        return 2; // 2nd won
    else
        return 0; // mixed signs => draw
}


Style conventions

Following the PEP style guide, class names should be named with CamelCase and documentation strings should be formatted like the following.

class DirectoryStatistics:
    """Gets the total size of a given dir and counts how many folders and
    files are in the given path directory. Also offers a printing utility to output
    the diagnosis results.
    """
    def __init__(self, ...):
        # etc.

Classes

You can't return values from __init__ (aka. the class constructor), because it is called when you instantiate an object, thus the return value is the object itself. But you can call methods in your __init__ method, that's why you should move the content of your get_directory_statistics method into the __init__ method:

class DirectoryStatistics:
    """Gets the total size of a given dir and counts how many folders and
    files are in the given path directory. Also offers a printing utility to output
    the diagnosis results.
    """
    def __init__(self, file_path):
        self.root_directory = path(file_path)
        self.file_count = 0
        self.total_size = 0
        self.non_hidden_files_count = 0
        self.folder_count = 0
        for f in self.root_directory.glob('**/*'):
            if f.is_file():
                self.file_count += 1
                self.total_size += f.stat().st_size
                if not f.name.startswith("."):
                    self.non_hidden_files_count += 1
            if f.is_dir():
                self.folder_count += 1

That way, by calling:

statistics = DirectoryStatistics(file_path)

you run the directory diagnosis and save the results in your object.
Then you can pretty-print the results using your print_statistics() method.


What is killing your performance is memoContains. It turns your algorithm from O(n) into O(n^2).

The better solution is to create a second array of the same size as your input, where you mark each cell visited. Then you can do the check in O(1).

Next, you need to implement a short circuit for your logic. If right is true, there is no point in computing the other directions.

Why do you define right and the other three bools as references?

There are some more tricks you can apply, for example to avoid checking for out-of-bounds indexing by simply making the array one cell larger on all sides, and filling those positions with x.

Finally, regarding recursion. It's a nice way of describing the algorithm. You might get better performance if you use a stack instead. But the only way to know for sure is to try it out and time it. :)

Oh, and one more thing:

std::vector<std::string> space;

Is highly inefficient. Your data is all over the memory because the data for each array is allocated independently. You should probably make this a single vector (or string if you must) that you index as row * width + column. Note that now you can index neighboring cells using simple pointer arithmetic (add 1 to the pointer to access the cell on the right, for example).


This

Directory.Exists(args[0]);
Directory.Exists(args[1]);

doesn't serve any purpose because you aren't evaluating the returned boolean value. In fact its more dangerous to use it with the args not checked for null at all. Your application will just crash if the application is called using only one or no argument at all.

The static void FileDiscovery() method would benefit from a better name like CalculateDirectorySize() and by returning a long instead of void.

Another point to mention is that the DirectoryInfo class contains the method GetFileSystemInfos() which would lead to the following change

    private static long CalculateDirectorySize(String dir)
    {
        long directorySize = 0;
        var dirInfo = new DirectoryInfo(dir);
        try
        {
            foreach (var fileInfo in dirInfo.GetFileSystemInfos("*", SearchOption.TopDirectoryOnly))
            {
                directorySize += fileInfo.Length;
            }

            foreach (var directory in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
            {
               directorySize += CalculateDirectorySize(directory);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("[DISCOVERY][WARNING] : Couldn't open directory : {0}", dir);
        }
        return directorySize;
    }

I have added private access modifier to the method, because it is a good habit to add one.

Because _fileCount is no where used I have removed it.

The FileCopy() method is using a strange way to copy the files by reading and writing them using FileStream's.

A more idiomatic way would be to use one of the overloaded File.Copy() methods. This methods are doing under the hood the same like your code but the streams are properly closed if any exception occurs.
Directory.CreateDirectory() can be called regardless if the directory exists or not. You can just skip the check for Exists().
Having three times Path.Combine(dest, dir) won't be necessary if the result is stored in a variable.
Instead of calling GetFileName() for a directory you should call GetDirectoryName()

this would result in the following change

    private static void FileCopy(String source, String dest)
    {
        try
        {
            foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
            {
                try
                {
                    File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));

                    _byteProgress += new FileInfo(file).Length;

                    _progressCount.Report((double)_byteProgress / (double)_byteCount);
                }
                catch (Exception e)
                {
                    Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                }
            }
            foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.TopDirectoryOnly))
            {
                if (directory == @"G:\$RECYCLE.BIN") continue;

                var dir = Path.GetDirectoryName(directory);
                var destination = Path.Combine(dest, dir)

                Directory.CreateDirectory(destination);

                FileCopy(directory, destination);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("[COPY][WARNING] : Couldn't open directory  : {0}", source);
        }
    }

Based on the comment

  I was aware of the File.Copy() method at the time of writing the application BUT (and that's why I included the context) this method was throwing the same error as my explorer when used : that the file was not accessible and/or corrupted.

I would like to suggest to only use this kind of copy operation if the File.Copy() method throws an IOException having its own method like so

private static readonly int blockSize = 104857600;
private static bool SafeFileCopy(string source, string destination) {

    try
    {
        using(var sourceStream = File.OpenRead(source))
        using(var destinationStream = File.Open(destination, FileMode.Create,
                            FileAccess.ReadWrite))
        {
            sourceStream.CopyTo(destinationStream, blockSize);
            return true
        }

    }
    catch (Exception ex)
    {
        // do some logging
    }
    return false;

}

Resulting in the former foreach like so

           foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
            {
                string destinationFile = Path.Combine(dest, Path.GetFileName(file));
                try
                {
                    File.Copy(file, destinationFile);

                    _byteProgress += new FileInfo(file).Length;

                    _progressCount.Report((double)_byteProgress / (double)_byteCount);
                }
                catch (IOException ioex)
                {
                    if (!SafeFileCopy(file, destinationFile))
                    {
                         // do some logging here
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                }
            }

Basically you should only catch exceptions which you can handle or which you only need to log/swallow. But you should always catch specific exceptions only. Catching Exception itself is a bad habit so for the SafeFileCopy() this would be for you to change.


Security of API Keygen for a cryptocurrency trading platform

It feels like you are combining lots of hashing and string transformation in hopes that complexity will make your scheme more secure.  That's not engineering or computer science, though — it's Cargo Cult Programming.

There are two ways that an API key scheme could work:

To generate the API key, concatenate the username with a salt and site-wide secret, then hash it.  When it is later presented, verify it by concatenating the username, salt, and secret, and see if the hashes match.

Advantages:

It may be possible to verify the API key without a database lookup.
You can immediately revoke all API keys ever issued by simply changing the site-wide secret.

Disadvantages:

It's tricky to revoke the API key for a particular user without a database lookup.

Generate any distinct, unguessable string.  Store it in the database, associated with the user.  When it is later presented, verify it by looking it up in the database.

Advantages:

It's easy to understand how it works.

Disadvantages:

Verification requires a database lookup.

What you have done is a combination of the two strategies.  You store the generated API key in the database, associated with the user.  However, while you could have used just any random string, you used a convoluted process involving lots of randomizing, hashing, concatenating, and shuffling, all without much justification, and in a way that offers no additional security benefits.

Consider, for example:

$hash_merge = array_merge($hashed_b, $hashed_a);
$from_merge = implode($hash_merge);
$exploded_2 = str_split($from_merge);
$key_hash_last = implode($exploded_2);

That just converts an array to a string, back into an array, and reconstitutes the same string again.

If you consider the properties of cryptographic hash functions, you will notice that much of the manipulations are unnecessary.  In particular, cryptographic hash functions are designed such that if inputs a and b differ by as little as one bit, hash(a) and hash(b) will not resemble each other at all.

Therefore, if you choose option (2), you can generate an API key securely using something as simple as

$api_key = hash('sha256', (time() . $id . $some_sitewide_secret . rand()));

The result will be secure because:

Cryptographic hashes are one-way (irreversible) functions, so knowing the hash reveals nothing about the input that was hashed. (Unguessable)
The input varies by time and includes randomness, so it is not repeatable. (Distinct)
The input includes the user ID, so no two users should be able to generate the same key. (Distinct)
The input includes some site-wide secret string (which you can set in your configuration file), so even if an attacker tried to generate a lot of keys using the same technique in an attempt to brute-force a match, knowing the approximate time at which the key was generated and even cracking the pseudorandom number generator would not help.  Pick a very long random string for the site-wide secret (a SHA-256 of any word processing document would do). (Unguessable)
The output has 256 bits of entropy, which is impossible to crack by exhaustive enumeration. (Unguessable)

Furthermore, the chance that the same API key would be generated twice is about 2-250.  It's more likely that your server would be struck by an asteroid tomorrow than that it would generate the same key twice using this technique, so don't worry about accidental collisions.


Get the Nth Term in the Fibonacci Sequence

A few points about improving code

It seems that your naming convention for constants is to use a capitalized identifier. If so, that should be applied consistently for all constants including inputFailure.
The loop in the function getTermCount can be simplified. A for-loop is clearer IMO.
The output of getNthFibonacciTerm is actually off by one term (assuming the sequence starts with 0 at index 0). It outputs 1 for input 3. The conditional checks before the loop could also be avoided to simplify the code.
Since the Fibonacci sequence is non-negative, the output could use an unsigned integer to allow slightly larger inputs.

About input range: since the output exceeds the limit of unsigned long long when the input is over 93, I do not see how it can be accurately represented unless you try to implement representations of big integers yourself in C.
About performance: there are several \$\Theta(\log n)\$ algorithms for computing Fibonacci numbers for a given input \$n\$. If you want that, here is a list of all algorithms.

Here is an improved version:

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

static const int MinimumTerm = 0;
static const int MaximumTerm = 93;
static const int MaxTries = 3;
static const int InputFailure = -1;

static int getTermCount()
{
    const char *fmtstr = "Please enter an integer value between %d and %d\n";

    for (int count = 0; count < MaxTries; count++)
    {
        int term;

        printf(fmtstr, MinimumTerm, MaximumTerm);    // IMO it is fine to just output to stdout before all attempts fail
        scanf("%d", &term);
        if (term >= MinimumTerm && term <= MaximumTerm)
        {
            return term;
        }
    }

    return InputFailure;
}

static unsigned long long getNthFibonacciTerm(int term)
{
    unsigned long long nthValue = 0;
    unsigned long long nextValue = 1;  // (n+1)th value, you may find a better name for that

    for (int termCount = 0; termCount < term; termCount++)
    {
        unsigned long long newValue = nthValue + nextValue;
        nthValue = nextValue;
        nextValue = newValue;
    }

    return nthValue;
}

int main()
{
    int term = getTermCount();
    if (term == InputFailure)
    {
        fprintf(stderr, "Invalid Input\n");
        return EXIT_FAILURE;
    }

    printf("The %d term of the Fibonacci Sequence is %llu\n", term, getNthFibonacciTerm(term));
    return EXIT_SUCCESS;
}


To elaborate on some comments you got on the SO version of this question, the main thing you're missing is stack alignment, a requirement of the SysV ABI calling conventions that's often overlooked by beginners.
The requirement is (ABI 3.2.2):

The end of the input argument area shall be aligned on a 16 (32 or 64, if
__m256 or __m512 is passed on stack) byte boundary.

So that means that, at the instant before you execute a call instruction, the stack pointer %rsp needs to be a multiple of 16.  In your case you have a push of 8 bytes without a pop in between your two calls to multiply, so they can't both have correct alignment.
Some wrinkles are introduced here by the fact that your parent function is _start instead of main or another function called by C code:

The conditions on entry to _start are described in 3.4 of the ABI.  In particular, the stack is aligned to 16 bytes at the instant _start gets control.  Also, since you cannot return from _start (there is no return address on the stack), you have to exit with a system call as you do, and so there is no need to save any registers for the caller.

For main or any other function, the stack would have been aligned to 16 bytes before your function was called, so the extra 8 bytes for the return address mean that on entry to your function, the stack is now "misaligned", i.e. the value of rsp is 8 more or less than a multiple of 16.  (Since one would normally only manipulate the stack in 8-byte increments, it's only really ever in two possible states, which I'll call "aligned" and "misaligned".)  Also, in such functions, you would need to preserve the contents of the callee-saved registers %rbx, %rbp, %r12-r15.

So as it stands, your first call to multiply has correct stack alignment, but your second does not.  Of course, it's only of academic interest in this case, because multiply doesn't do anything that needs stack alignment (it doesn't even use the stack at all), but it's good practice to do it right.
One way to fix it would be to subtract another 8 bytes from the stack pointer before the second call, either with sub $8, %rsp or (more efficiently) by simply pushing any random 64-bit register.  But why should we bother to use the stack at all to save this value?  We could simply put it in one of the callee-saved registers, say %rbx, which we know multiply must preserve.  Normally this would require us to save and restore the contents of this register, but since we are in the special case of being _start, we don't have to.

A separate comment is that you have a lot of instructions like mov $7, %rdi where you operate on 64-bit registers.  This would be better to write as mov $7, %edi.  Recall that every write to a 32-bit register will zero the upper half of the corresponding 64-bit register, so the effect is the same as long as your constant is unsigned 32 bits, and the encoding of mov $7, %edi is one byte shorter as it doesn't need a REX prefix.
So I'd revise your code as
.globl _start

_start:

    # Calculate 2*3 + 7*9 = 6 + 63 = 69
    # The multiplication will be done with a separate function call

    # Parameters passed in System V ABI
    # The first 6 integer/pointer arguments are passed in:
    #   %rdi, %rsi, %rdx, %rcx, %r8, and %r9
    # The return value is passed in %rax

    # multiply(2, 3)
    # Part 1 --> Load the parameters
    mov $2, %edi
    mov $3, %esi
    # Part 2 --> Call the function (`push` return address onto stack and `jmp` to function label)
    call multiply
    # Part 3 --> Save the return value
    mov %rax, %rbx   # could also do mov %ebx, %eax if you know the result fits in 32 bits

    # multiply(7, 9)
    mov $7, %edi
    mov $9, %esi
    call multiply

    # Add the two together
    add %rbx, %rax
    mov %rax, %rdi

    # for the 64-bit calling convention, do syscall instead of int 0x80
    # use %rdi instead of %rbx for the exit arg
    # use $60 instead of 1 for the exit code

    mov $60, %eax    # use the `_exit` [fast] syscall
                      # rdi contains out exit code
    syscall           # make syscall

multiply:
    mov %rdi, %rax
    imul %rsi, %rax
    ret

If you want to rely on the result of multiply fitting in 32 bits, you could replace mov %rax, %rbx with mov %eax, %ebx to save one byte.  And likewise, the "Add the two together" could use 32-bit instructions instead to save two more bytes.
Finally, there's a stylistic point on whether to use the AT&T-syntax operand size suffixes, like addq versus add.  They are optional when one operand is a register, since the operand size can be deduced from the size of that register (e.g. 32 bits for %eax, 64 bits for %rax, etc).  My personal preference is to always use them, as a little extra verification that you're really writing what you mean, but omitting them as you (mostly) did is also common and fine; just be consistent.  You did have one instance of movq $60, %rax where it wasn't needed, so for consistency I omitted the suffix there. (I also changed it to %eax for the reasons noted above.)


I would not personally put LoggingService implementation inside factory, as it reduces testability and usually needed to play some tricks with generics type parameters only.

To have a predictable behavior according to your design it might look like:

public static class LoggingServiceFactory
{
    static ConcurrentDictionary<string, ILoggingService> Services { get; } =
        new ConcurrentDictionary<string, ILoggingService>();

    public static ILoggingService GetService(string connectionString) =>
        Services.GetOrAdd(connectionString, cs => new LoggingService(cs));
}

Anyway, it makes sense to think about delegating it to IoC container...

I don't think that it is a responsibility of this class to verify if connection string is the same. This interface delivers different perception.


Creating a database, a table within the database and inserting some values into it in one go

From the title alone, this sounds like something that should not be done, particularly since this is not a lightweight database such as SQLite. Creating the database, its tables, columns, constraints etc. is not, and should not, be the job of the application - but rather an external setup script with administrative permissions. The application, then, should not have such permissions and should only be able to insert/select/update/delete.
For some reason I thought autocommit is enabled by default for the MySQL Python connector, but apparently it's not:
https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
So your explicit call to commit is fine.
I can't tell from the documentation whether the cursor and connection objects support context management. Try putting both of those in with statements, and if it complains that there's no __enter__, switch to a try/finally that guarantees cursor and connection closure.


Have you tried running this with a "big" input? Try it with fibonacci(10000) for example. At least on my machine with default settings this gives a StackOverflowError.

This is because java doesn't handle recursion well. Since you're going to recalculate all the values for each call to ´fibonacci(n)` you might as well solve it with a simple for loop instead.

public static int fibonacci(int n) {
    if (n < 0) throw new IllegalArgumentException("n must be non-negative.");
    if (n == 0) return 0;
    if (n == 1) return 1;

    int f1 = 0;
    int f2 = 1;
    for(int i = 2; i <= n; i++){
        int temp = f2;
        f2 += f1;
        f1 = temp;
    }
    return f2;
}

It's not possible to change the return type dynamically based on a runtime value. Seeing how fibonacci numbers grow incredibly fast, you might want to consider returning BigInteger by default. (For ints, you can't even get to number 50).

public static BigInteger fibonacci(int n) {
    if (n < 0) throw new IllegalArgumentException("n must be non-negative.");
    if (n == 0) return BigInteger.ZERO;
    if (n == 1) return BigInteger.ONE;

    BigInteger f1 = BigInteger.ZERO;
    BigInteger f2 = BigInteger.ONE;
    for(int i = 2; i <= n; i++){
        BigInteger temp = f2;
        f2 = f2.add(f1);
        f1 = temp;
    }
    return f2;
}

Personally I would also not memoize fibonacci numbers further than these 2 temp veriables to keep track of the last 2 values. If your program is intended to request fibonacci numbers over and over and you're willing to get a little bit of speed in exchange for some memory you could also precompute a lot of those numbers. Except for learning purposes I don't think it's actually worth doing though.


Count the number of vowels and consonants

This avoids loops completely and expresses your intent more clearly, I think.

Also, note that you should explicitly define the valid consonants, so that you will properly ignore numbers, punctuation, etc.

function getCount(words) {
  var words      = (typeof words == 'string') ? words : '',
      count      = re => (words.match(re) || []).length,
      vowels     = count(/[aeiou]/ig),
      consonants = count(/[bcdfghjklmnpqrstvxzwy]/ig);

  return {vowels, consonants};
}


Remove Duplicates from Array in Swift 3.0

Your code works correctly, as far as I can see. A small simplification
would be

func removeDuplicates(_ nums: inout [Int]) -> Int {
    nums = Set(nums).sorted()
    return nums.count
}

because sorted() can directly be applied to any collection of
comparable elements and returns an array.

However, your code does not take advantage of the fact that the
given array is already sorted. Two intermediate collections (a set
and an array) are created, and the new array is sorted.
That can be improved.

Since the array elements are sorted, you can traverse through all
elements and only keep those which are different to the previous
one. This leads to the following implementation:

func removeDuplicates(_ nums: inout [Int]) -> Int {

    guard let first = nums.first else {
        return 0 // Empty array
    }
    var current = first
    var uniqueNums = [current] // Keep first element

    for elem in nums.dropFirst() {
        if elem != current {
            uniqueNums.append(current) // Found a different element
            current = elem
        }
    }
    nums = uniqueNums
    return uniqueNums.count
}

In addition, you can save memory by overwriting the elements
in the given array directly. If a different element is found then it
is copied directly to its new position. At the end of the loop,
surplus elements are removed:

func removeDuplicates(_ nums: inout [Int]) -> Int {

    guard let first = nums.first else {
        return 0 // Empty array
    }
    var current = first
    var count = 1

    for elem in nums.dropFirst() {
        if elem != current {
            nums[count] = elem
            current = elem
            count += 1
        }
    }

    nums.removeLast(nums.count - count)
    return count
}

In my tests, the last two methods were about a factor 10 faster
than yours.


I would recommend using mean method:

ds_movie.map(lambda (userid, movieid, rating): rating).mean()

It is not only more concise but should have much better numerical properties (it is using a modified version of the online algorithm).

On a side note it is better to avoid tuple parameter unpacking which has been removed in Python 3. You can check PEP-3113 for details. Instead you can use Rating class as follows:

from pyspark.mllib.recommendation import Rating

ratings = ds_movie.map(lambda xs: Rating(*xs))
ratings.map(lambda r: r.rating).mean()

indexing (arguably much uglier than unpacking):

ds_movie.map(lambda r: r[2]).mean()

or standard function instead of lambda expression (kind of verbose for such a simple use case):

def get_rating(rating):
    userid, movieid, rating = rating
    return rating

ds_movie.map(get_rating).mean()


I would group all of your properties together. Right now you have Code separated from the other properties by the ctors.
When overriding Equals, it's important to be sure that it can't throw an exception. The current implementation can throw an InvalidCastException.

    public override bool Equals(object obj)
    {
        var other = (DisplayLanguageSetting) obj;
        return Code.Equals(other.Code);
    }

A proper implementation would look something more like this.

public override bool Equals(object obj)
{
    var other = obj as DisplayLanguageSetting;

    if (other == null)
        return false;

    return Code.Equals(other.Code);
}

I don't much care for the control either.

 public partial class GeneralSettingsControl : UserControl

That's more or less all I need to see to know I don't care for it. How's that? Because that's all I need to know about the class to know that business logic is being put into the code behind instead of a presenter class. We've got a "smart" form on our hands here. Invert the control. This should be implementing an interface that exposes properties for the different view elements.

public interface IGeneralSettingsView
{
    DisplayLanguageSetting CurrentSetting {get; set;}
    IList<DisplayLanguageSetting> {get; set;}
}

Note that once you do this, the class no longer needs a Configuration Service at all. (The presenter will still need it though).


Given the bad indentation of the original code, I will assume you meant to post code that looks like this

while True:
    try:

        income = int(input("Please enter your taxable income: "))
    except ValueError:
        print("Sorry, I didn't understand that please enter taxable income as a number")

        continue
    else:
        break

if income <= 18200:
    tax = 0

elif income <= 37000:
    tax = (income - 18200) * 0.19

elif income <= 90000:
    tax = (income-37000) * 0.235 + 3572

elif income <= 180000:
    tax = (income - 90000) * 0.37 + 20797

else:
    tax = (income - 180000) * 0.45 + 54097

print("you owe", tax, "dollars in tax!" )

I would suggest you use an IDE or a linter, both of which will point out syntax problems in the code.

The idea behind the code can be summarized as

Get the income from user input
Calculate the tax
Print the amount owed

This is a good structure to have. You have three clear boundaries and have split the work appropriately. You can make this explicit with well named functions. I would lay it out like this

def get_income():
    while True:
        try:

            income = int(input("Please enter your taxable income: "))
        except ValueError:
            print("Sorry, I didn't understand that please enter taxable income as a number")

            continue
        else:
            break

    return income

def compute_tax(income):
    if income <= 18200:
        tax = 0
    elif income <= 37000:
        tax = (income - 18200) * 0.19
    elif income <= 90000:
        tax = (income - 37000) * 0.235 + 3572
    elif income <= 180000:
        tax = (income - 90000) * 0.37 + 20797
    else:
        tax = (income - 180000) * 0.45 + 54097

    return tax

if __name__ == "__main__":
    income = get_income()
    tax = compute_tax(income)
    print("you owe", tax, "dollars in tax!")

The advantage of this is that your code for working out how much tax is owed is easy to use in another python module.

# tax_credits.py
from tax import compute_tax
...

If we look at how the tax is computed, the pattern is very clear. At each tax bracket we subtract an amount, multiply by a percentage, and add back an amount

tax = (income - S) * P + A

We could change the code to first figure out the tax bracket the income falls into, then compute the tax amount. While this doesn't look any better now, it will be beneficial to explore this path.

def compute_tax(income):
    if income <= 18200:
        S, P, A = 0, 0, 0  # Values picked so the tax amount is always 0.
    elif income <= 37000:
        S, P, A = 18200, 0.19, 0
    elif income <= 90000:
        S, P, A = 37000, 0.235, 3572
    elif income <= 180000:
        S, P, A = 90000, 0.37, 20797
    else:
        S, P, A = 180000, 0.45, 54097

    tax = (income - S) * P + A
    return tax

Since this repeated code now looks a bit easier to manager, let's turn it into a loop. I'll leave the details out as there are a few features of python that might be new to you, and are worth looking up yourself.

def compute_tax(income):
    # (C,      P,       A)
    # (cutoff, percent, additive)
    # S is reused from the previous iteration of the loop
    # so no need to store it.
    tax_brackets = (
        (18200, 0, 0), (37000, 0.19, 0), (90000, 0.235, 3572), (180000, 0.37, 20797)
    )
    # The final bracket, use if the income is bigger than any cutoff
    last_bracket = (None, 0.45, 54097)
    previous_cutoff = 0
    for cutoff, percent, additive in tax_brackets:
        if income <= cutoff:
            break
        previous_cutoff = cutoff
    else:
        # If we get here we never found a bracket to stop in
        _, percent, additive = last_bracket

    tax = (income - previous_cutoff) * percent + additive
    return tax

We should probably include some sanity checks incase somebody incorrectly changes values. As an example, we could check each cutoff is bigger than the last.

Note that this code is a bit denser than the original, and I don't know if I would recommend using a loop. If the original code ever gets more complex this is how I would try and simplify it. But until then I would leave the explicit if/elif/else statements in previous suggestion.

def get_income():
    while True:
        try:

            income = int(input("Please enter your taxable income: "))
        except ValueError:
            print("Sorry, I didn't understand that please enter taxable income as a number")

            continue
        else:
            break

    return income

The logic here is pretty solid. I would be hesitant to change to much. The only thing I do not like is int, as it is perfectly reasonable to earn a fractional unit of the currency.

There are a lot of ways you could code this sort of function. Here is one alternative that removes a few unnecessary parts.

def get_income():
    while True:
        try:
            return float(input("Please enter your taxable income: "))
        except ValueError:
            print("Sorry, I didn't understand that please enter taxable income as a number")


Looking for a way to create a particular matrix in python in a less amount of time

The NumPy Reference should be the first place you look when you have a problem like this. The operations you need are nearly always in there somewhere. And functions that you find while browsing the reference are sure to come in useful later in your NumPy career.

For the first row, you could use numpy.arange and numpy.repeat:

>>> np.repeat(np.arange(4), 4)
array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3])

For the second row, you could use numpy.tile:

>>> np.tile(np.arange(4), 4)
array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])

For the third row, you could use numpy.ones:

>>> np.ones(4 * 4, dtype=int)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

Putting that together (using numpy.ones_like for row3 so that it has the same shape and data type as row2):

row1 = np.repeat(np.arange(row), col)
row2 = np.tile(np.arange(col), row)
row3 = np.ones_like(row2)
output = np.vstack([row1, row2, row3])

This is about 100 times as fast as the code in the post.

But you can do better than that! There is a hint in the documentation for numpy.tile:

  Note: Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions.

Broadcasting is the way that NumPy adapts the inputs to an operation so that they match in shape. Using this we can write the whole function using array indexing and reshaping operations, like this:

output = np.zeros((3, row, col), dtype=int)
output[0] = np.arange(row).reshape(-1, 1)
output[1] = np.arange(col).reshape(1, -1)
output[2] = 1
output = output.reshape(3, -1)

This is about 160 times as fast as that code in the post.

A slightly clearer way to write this is to use numpy.meshgrid to generate the coordinate arrays:

output = np.zeros((3, row, col), dtype=int)
i, j = np.meshgrid(np.arange(row), np.arange(col), indexing='ij', sparse=True)
output[0] = i
output[1] = j
output[2] = 1
output = output.reshape(3, -1)

This isn't any faster than the previous version but the use of numpy.meshgrid gives more of a clue to the reader as to what is happening.

(You might be able to do even better than that. Do you really need to construct the whole matrix? Could you combine broadcasting and numpy.meshgrid to get the results you want instead? I can't answer this since you didn't explain what you are going to use this code for. But maybe you can ask another question showing us more of your program.)


Building a table from the result of an AJAX call

i think it is good approach, if data return from database is in small size (i.e limited record say 10,20 etc).


Changing the prototype of the String object

Extending native objects is bad practice.

When you're expecting nothing, then something shows up. That's natural behavior of prototypes.
Forwards compatibility. The same reason why Object.keys(someObjectInstance) is designed that way instead of someObjectInstance.keys() - because some implementations may already have used keys as a property. So what if ECMAScript 9 wants to use left() and right() for some string operation, your app will break.

For alternatives:

You can create your own functions in a separate namespace, that looks like the native functions. For instance, the native forEach looks like array.forEach(fn). Underscore writes it differently with _.forEach(array,fn).
You can extend native objects. Mileage may vary on this one as some (not sure which, but most) native objects are not subclassable.
You could create "wrapper objects" that just wrap the object into another object, who has methods that operate on the wrapped object. A good example is jQuery which wraps an array of stuff in a "jQuery object" which hosts a myriad of DOM manipulation methods that operate on that set.
Create a custom object that doesn't necessarily extend/inherit/wrap anything. Something like var string = new CustomString('hello world').


How to improve method of opening file in python then writing to another?

import os, re

Here, make sure you put a colon after virtual

with open('virt_host', 'r+') as virtual:

Avoid using built-in Python keywords as variables (such as file here)

    f = virtual.read()

This part is explicit, which is a good thing. Depending on whether or not you have control over how your variables are defined, you could use string formatting to pass a dictionary containing your values into the read file, which would save a few function calls.

    f = re.sub('{{dir}}', '/home/richard', f)
    f = re.sub('{{user}}', 'richard', f)
    f = re.sub('{{domain_name}}', 'richard.com', f)

Same as above regarding the colon

with open('new_virt', 'w+') as new_file:
    new_file.write(f)

One of the main benefits of using a context manager (such as with) is that it handles things such as closing by itself. Therefore, you can remove the new_file.close() line.

Here is the full code with the adjustments noted. Hope it helps!

import os, re

with open('virt_host', 'r+') as virtual:
    f = virtual.read()
    f = re.sub('{{dir}}', '/home/richard', f)
    f = re.sub('{{user}}', 'richard', f)
    f = re.sub('{{domain_name}}', 'richard.com', f)

with open('new_virt', 'w+') as new_file:
    new_file.write(f)


That's a very good code. Speaking of the things that are written in it, there is very little I would change. Only a few things are coming to my mind,

I would move the database connection code into a separate file and then just include in other scripts that needed a database connection.
Using the Refresh header is old fashioned, inconvenient and buggy. I would rather redirect a user to the newly created account page. So they would know that an account has been created at once.
I wouldn't hardcode a particular hashing algorithm, and rather use PASSWORD_DEFAULT instead.

That's all. But of course some things could be added to this code as well. You can add some verifications, like as to see

if the username is not empty or already exists
whether the password is not strong enough
whether email follows the proper format or already exists
all other verifications you can think of

And for this purpose it is useful to make $msg not a string but an array of strings, to collect all possible errors in one variable. You can check this approach in my recent answer


How about "cheating" a bit by creating two copies of those elements whose values should change and then just alternate between which element to show. Something like this:

    &#9660; Show playlist

    &#9650; Hide playlist

And then somewhere in your JavaScript you call the .toggle() function from the jQuery UI:

$(".toggleable").toggle();

Now it would look as though the texts changed, while actually you are hiding one element and displaying another.


Your regular Python implementation generally looks reasonable, and unless numpy
offers a performance boost that you really need, I would not recommend it for
this use case: the brevity/clarity tradeoff seems bad.
My biggest suggestion is to consider clearer names. A function with signature
of take_upto_n(A, n) makes me think the function takes an iterable and
returns a sequence of n values. Something like take_upto_sum(A, total)
seems more communicative to me. And even "take" isn't quite right: take
implies a filtering process (we'll take some and leave some). But we
are limiting or capping. Perhaps you can think of something even better.
This example presents a classic Python dilemma: you want to do a simple map
over a list to generate a new list, so of course you would like to knock it out
in a comprehension or something equally cool. But while iterating,
you also need to modify some other variable to keep track of state, and Python
mostly lacks the assignments-as-expression idiom that allows such trickery in
other languages (for example, old-school Perl map/grep one-liners and their
ilk). If you are using a sufficiently modern Python, you can use the walrus
operator to compress the code a bit, but it doesn't get you all the way there.
Honestly, I wouldn't even bother with the walrus (but I would assign min() to
a convenience variable to avoid repetition and thus help readability). In any
case, the walrus approach:
def take_upto_sum(A, total):
    out = []
    for x in A:
        out.append(y := min(total, x))
        total -= y
    return out

I suppose it is possible to express this as a single list comprehension if we
take advantage of the built-in itertools and operator modules. Like the
numpy solution, this approach reminds me of the Spinal Tap quote: It's such a
fine line between stupid, and uh ... clever.
from itertools import accumulate
from operator import sub

def take_upto_sum(A, total):
    return [
        max(min(x, acc), 0)
        for x, acc in zip(A, accumulate(A, sub, initial=total))
    ]


To use:

if optionalVariable == nil {} else {
    // do stuff with optionalVariable!
}

would absolutely not be recommended.

For starters,

if optionalVariable != nil {
    // do stuff with optionalVariable!
}

would be slightly better, but still, I can't even remotely recommend this.

Given that optionalVariable is nullable, what happens if it is made null inside this closure?

if optionalVariable != nil {
    doStuff(optionalVariable!)
    optionalVariable = funcThatCouldReturnNil()
    doStuff(optionalVariable!)
}

At the end of the day, we should simply minimize our use of forced unwraps.

if let variable = optionalVariable {
    doStuff(variable)
    variable = funcThatCouldReturnNil() // <-- compile time error
}

If variable is not a nullable, then you can't assign the result of a function that could return nil to it without force unwrapping the result.

The exclamation point should mark to us that something special is happening here... and if we can use the exclamation point, we might need to rethink our method.

At the end of the day, we shouldn't be asking ourselves purely whether or not our results remain the same for both methods.  We should also ask ourselves whether one way or the other opens the path for future maintainers to do something stupid and write some bugs into your code.

If I'm assigning the result of a non-optional returning function to a non-optional variable, if it is later determined that the function needs to return an optional, then Swift and Xcode will politely alert me to every occurrence that I need to go look at for my variable.

And if I'm not using the if let syntax and instead using the ! force unwrap everywhere, then Xcode can't remind me, and I'm asking myself for a huge swampy headache of bugs...


operator== and operator!= should be const.
You need to #include <cstddef> to use nullptr_t.
You are defaulting the copy constructor and assignment operator, but not the move constructor and move assigment operator. That's fine because the defaults are generated anyway, but it is inconsistent, I think.
What is the point of operator==(bool)?
Proxy should be private. You don't want to have users create Proxys.
ELockWrapper does not actually own the pointer it holds. It is copyable and will just copy the pointer it holds. It also does not create anything or delete anything in the constructor/destructor. Nontheless you provide a Delete member. That seems very wrong to me. You don't know how the memory you point to was aquired, it could be with static storage or an array. In both cases calling Delete would cause undefined behavior. The object creating the pointer with new should also be responsible for deleteing it. Calling Delete on two copies of ELockWrapper also causes undefined behavior.
The fact that the pointer is not owned seems to be a major flaw here anyway. Currently the user of your class needs to gurantee that the object pointed to keeps in scope until all ELockWrapper's holding it are destroyed and then it has to take care of proper deletion. Using it outside of ELockWrapper is not allowed. So why not move the responsibility of managing the pointer to ELockWrapper?
The same holds true for the lock. Currently the user needs to provide a suitable lock and keep it live until no ELockWrapper references it anymore. Why not create the lock/mutex inside the constructor from pointer? Though I realize if you do it like this you need to manage references to the lock and you end up with fully reimplementing std::shared_ptr. Therefore I will just assume that this wrapper is explicitly only about locking and not managing ressource lifetime and that the user is required to run the destructors properly.
operator-> is fine if copy elision is performed (not required in C++11, but in C++17), but operator* is not either way. The Proxy object you create in operator* is destroyed before the function returns. That means that Unlock is called before the caller expression using the pointer ends.
operator* currently returns a copy. It should return a reference. At least that is the usual way this operator is interpreted.
In general the approach with operator* and operator-> has some limitations. You may not call either twice in one expression or you have deadlock. But you are also not allowed to save the pointer returned by operator* or a pointer/reference to the object referred because these are not guarded any more by the lock.
I guess it would be much better to let the caller call a aquire which returns a Proxy. Access to the holding pointer is then only allowed via operator* and operator-> of this Proxy. As soon as Proxy goes out of scope its destructor releases the lock, similar to std::lock_guard.

This still allows the user to misuse a saved reference/pointer to the raw object, but at least more than one usage can me made in the same lock aquisition.

An implementation via C++11 standard library would be similar to this (not tested):

template<typename T, typename Mutex>
class ELockWrapper {
    T* t;
    Mutex* mut;

    class Proxy {
        T* t;
        std::unqiue_lock<Mutex> lock;
        Proxy(ELockWrapper& wr) : t(wr->t), lock(wr->mut) { }
        friend ELockWrapper;
    public:
        T& operator*() { return *t; }
        T* operator->() { return t; }
    };

public:
    ELockWrapper() : t(nullptr), mut(nullptr) {}
    ELockWrapper(nullptr_t) : ELockWrapper() {}
    ELockWrapper(T* t, Mutex* mut) : t(t), mut(mut) {}
    ELockWrapper(T* t, Mutex& mut) : t(t), mut(&mut) {}

    Proxy aquire() { return {*this}; }
};


Convert an integer to 4 bytes without bitshift operators

There's not a ton that can be improved here, but:

lut should be made const
Due to implicit promotion, lut can be stored as integers instead of floats. Your expressions should evaluate to the same thing.
Consider representing your lut constants in hexadecimal (0x) format - or as 1 << x notation.
Your lut doesn't strictly need to be an array; you're not iterating over it or indexing it dynamically. As such, you may be better off simply making individually-named constants such as XL, YL, ZL.


Routes for a user controller in a Node.js application

Looking at users.js, you can see that I tried to DRY things up by creating sequelizeSuccessHandler and sequelizeErrorHandler (I hate those names), but there's still a lot of repetition.

I suppose you're talking about these repeated lines in the route handlers:

  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));

I don't really know Node,
but it seems to me that you could add another helper function:

function handle(query, response) {
  query
  .then(sequelizeSuccessHandler(response))
  .catch(sequelizeErrorHandler(response));
});

router.get('/', function(request, response) {
  handle(User.findAll(), response);
});

router.post('/', function(request, response) {
  handle(User.create(User.params(request.body)), response);
});

(The names "handle", and "query" might not be the best.)


Retrieving three separate sorted lists of items

If you're concerned about repeating yourself, you can look into the Java workaround/equivalent of C# delegates, though it might be more trouble than it's worth with regard to clarity and conciseness (http://www.javacamp.org/javavscsharp/delegate.html).

Everything below is just a hyper-abridged and incomplete explanation of one use of delegates.

Think of delegates as a stand-in for any method with a specific signature.  In this case, you could use it for searchRep.findAreaMatches and searchRep.findCityMatches (searchRep.findPostcodeMatches has a different signature).  At a high level, it might do something like this:

delegate List<Area> functionDelegate(string s);
functionDelegate f;
if (areaMatch):
    f = searchRep.findAreaMatches
else if (cityMatch):
    f = searchRep.findCityMatches
else:
    f = /* Your choice of what goes here */
functionDelegate(areaOrCity)

As a bit of an semi-related side-note, languages like Python allow for similar behavior without the need to explicitly declare something a delegate and without worrying about signatures, though you do have to make sure your types are correct.

def findMatches(arg):
    func = someFunction
    if areaMatch:
        func = searchRep.findAreaMatches
    elif postcodeMatch:
        func = searchRep.findPostcodeMatches
    elif cityMatch:
        func = searchRep.findCityMatches
    return func(arg)

Apologies if I totally missed the mark on what you were asking, I'm new to this.  Hope it helps!


Newbie Map/Reduce word frequency counter

A few initial points:

Your mapping phase is all done on one process, so you're not getting any parallelism. You should fire off M mappers to do the mapping for you, and give them bits of the data to map over. They can pass this on to one of R reducers who do the reduction.
[KeyValueTuple] ++ KeyValueTuples is slow as you're creating lists and concatenating them together. Instead, just prepend values to the list in O(1) time: [KeyValueTuple|KeyValueTuples]
The way you're spawning/creating the reducer process is a bit unnecessary. If I were you I'd spawn R reducers up front and dish out the work in a round-robin fashion. This will give you better control of load distribution.
Instead of calling dict:is_key then, if true, calling dict:fetch do both of them in one step by calling dict:find, then matching against {ok, Value} or error. This saves on the double-lookup.

As a general comment, you've really tied together both map/reduce and word counting. Ideally what you'd want to do is have a structure/module which knows about how to do map/reduce by itself, and be ignorant of the work that's going on. You would then have another module which is able to invoke a map/reduce job by passing in the Map function, the Reduce function, the number of mappers and reducers and the data that's being processed.

I realise you're learning, so you don't need to do all this. But down the track I'd recommend attempting to abstract away the map/reduce stuff into a reusable module.

Hope that helps.
OJ

PS. were you hoping for someone to show you how they'd code it up? I'm new to this code review site and I'm not sure whether I should be posting "fixed" code or not :)


You should create a function that returns all the subscribers for a product:

def get_subscribers(product, current_price):
    tracker_document = db.trackers.find_one({'product_id': product['_id']})

    subscribers = set()
    for user_id, desired_price in tracker_document['subscribers']:
        if current_price <= desired_price:
            subscribers.add(user_id)

    return subscribers

This could even be condensed even more using a list comprehension:

def get_subscribers(product, current_price):
    tracker_document = db.trackers.find_one({'product_id': product['_id']})

    return set([user_id for user_id, desired_price in tracker_document['subscribers']
                if current_price <= desired_price])

This change makes your code look like this:

subscribers = set()
for product in product.collection:
    current_price = get_current_price(product['url'])
    if current_price == product['current_price']:
        continue

    product['history'].append((datetime.datetime.utcnow(), current_price))
    product.collection.save(product)

    subscribers |= get_subscribers(product, current_price)

The next change I would suggest is: instead of using several lists for your queues, wrap them into a single defaultdict. This simplifies this code and would require only minimal changes in your alert_users code.

It may actually be better, depending on your alert_users function, to to alert a single user at a time instead of building queues of the users and calling alert_users with a batch of users.

Here is the batch example:

from collections import defaultdict

queues = defaultdict(list)
for user_id in subscribers:
    user_document = db.users.find_one({'_id': user_id})

    queues['email_id'].append(user_document['email_id'])
    for queue_type in ['twitter', 'ios_push_id', 'droid_push_id', 'chrome_push_id']:
        queues[queue_type].append(user_document['channels'][queue_type])

alert_users(queues)

Here is the user-at-a-time example:

for user_id in subscribers:
    user_document = db.users.find_one({'_id': user_id})

    alert_user(user_document['email_id'], *user_document['channels'])