Python/Sklearn code optimization (New at Python)

I can't give you any advice on performance but here are some notes on coding style:

There is no need to add comments to obvious things. You can safely delete all of them and it won't hurt readability. But you could make a docstring from # Create & fit a GB model using GridSearch optimised parameters.
Instead of generate_new_model() in the end of your script write this:

if __name__ == '__main__':
    generate_new_model()

You can read about it for example here.
You have some hard-coded paths and magic numbers. How about taking them to function's signatures? You also could use type hints.
It is a common practice to name dataframes simply as df instead of dataframe. But it's not really critical.
Instead of deepcopy you could use a copy method, and a drop method instead of del.
Why using as_matrix()? As docs say, train_test_split accepts pandas dataframes.
Instead of writing:

x_train, x_test, y_train, y_test = train_test_split(
    features, output, test_size=0.3)
return [x_train, y_train, x_test, y_test]

You can write just:

return train_test_split(features, output, test_size=0.3)

and change the order in the place where you call this function.
Instead of:

dataset = prepare_dataset()
x_train = dataset[0]
x_test = dataset[1]
y_train = dataset[2]
y_test = dataset[3]

you can write:

x_train, x_test, y_train, y_test = prepare_dataset()

Personally, I prefer dict constructors:

params = dict(learning_rate=0.01,
              loss='ls',
              max_depth=4,
              max_features=0.3,
              min_samples_leaf=9,
              n_estimators=500)

It took me some time to understand the meaning of mae. Can we just name those variables as train_error and test_error?
I suggest adding keyword arguments to your call of draw_benchmark_graphs, so it would look something like this:

draw_benchmark_graphs(model=model,
                      parameters=params,
                      x_test=x_test,
                      y_test=y_test,
                      train_error=train_error,
                      test_error=test_error)

Also from draw_benchmark_graphs import draw_benchmark_graphs looks strange. Choose better names. How about import draw and call the function like draw.benchmark_graphs(...)?
You have redundant parentheses in return. Also, why do you pack errors in a tuple? Flat is better than nested, so make your return like this:

return model, train_error, test_error

Think of splitting your script to more functions. How you do it depends on your workflow. It's just your function is called generate_new_model but what you actually do is: reading csv file to dataframe, splitting it to samples(or how you call it), instantiating and fitting a model, calculating and printing errors, saving model in a file and drawing a graph. Also, you return data consists of different types which I think is not a good thing.

Here is how it can look like in the end. Except the fact that I didn't include docstrings and didn't try to split it to smaller functions.

from typing import (Tuple,
                    List)

import pandas as pd

from sklearn import ensemble
from sklearn.externals import joblib
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

import draw

def generate_new_model(
        path: str = 'datasets/eggs_data_set.csv',
        *,
        save_path: str = 'models/trained_eggs_classifier_model.pkl',
        output_column: str = 'days_remaining',
        test_size: float = 0.3,
        learning_rate: float = 0.01,
        loss: str = 'ls',
        max_depth: int = 4,
        max_features: float = 0.3,
        min_samples_leaf: int = 9,
        n_estimators: int = 500,
        **kwargs) -> Tuple[ensemble.GradientBoostingRegressor, float, float]:
    (x_train, x_test,
     y_train, y_test) = prepare_data(path,
                                     output_column=output_column,
                                     test_size=test_size)

    model_parameters = dict(learning_rate=learning_rate,
                            loss=loss,
                            max_depth=max_depth,
                            max_features=max_features,
                            min_samples_leaf=min_samples_leaf,
                            n_estimators=n_estimators,
                            **kwargs)
    model = ensemble.GradientBoostingRegressor(**model_parameters)

    model.fit(x_train, y_train)

    train_error = mean_absolute_error(y_train, model.predict(x_train))
    test_error = mean_absolute_error(y_test, model.predict(x_test))

    print(f'Training Set Mean Absolute Error: {train_error:.4f}')
    print(f'Test Set Mean Absolute Error: {test_error:.4f}')

    joblib.dump(model, save_path)

    draw.benchmark_graphs(model=model,
                          model_parameters=model_parameters,
                          x_test=x_test,
                          y_test=y_test,
                          train_error=train_error,
                          test_error=test_error)
    return model, train_error, test_error

def prepare_data(path: str,
                 *,
                 output_column: str,
                 test_size: float) -> List[pd.DataFrame]:
    df = pd.read_csv(path)

    features = df.drop(output_column, axis=1)
    output = df[output_column]

    return train_test_split(features,
                            output,
                            test_size=test_size)

if __name__ == '__main__':
    generate_new_model()


The process you're using is better than trying to read and write the same file, which is just asking for a headache. However there is another way, which will particularly help if you need to use this on a larger file. You can read the file line by line, writing the replaced lines to your output file. This is less memory intensive as only a line is read at a time.

with open(resource,'rb') as f, open("output.txt", "w") as outputfile:
    for line in f:
        for i, j in rep.iteritems():
            line = line.replace(i, j)
        outputfile.write(line)

Note: I'd move the rep declaration out before you open either file, and I removed the superfluous print call now that it's running over every line.

Additionally, I don't think you need a dictionary for your mapping. It seems to semantically make sense, but offers no actual advantage to you. Just a tuple of tuple pairs would work fine, and I'd rename it too:

replacements = (
                ("Incoming Call", "Voice (in)"),
                ("Outgoing Call", "Voice (out)"),
                ("Incoming SMS", "SMS (in)"),
                ("Outgoing SMS", "SMS (out)"),
               )

Also a minor improvement for your loop, you can use the unpacking operator to simplify things a little:

for pair in replacements:
    line = line.replace(*pair)

* is the unpacking operator, it unpacks a 2-item tuple into 2 arguments for you. I prefer this as I find it more readable and makes for a better name (pair rather than i, j).


2D model simulating water breaking a floodbank

Downcasting can usually be avoided by using common methods in abstract types.

    if (((DoorbraakWorld)getWorld()).stopped) return;

Is this the same as getWorld().stopped()?

    // The next line looks so incredibly ugly…
    Sandstone sandstone = (Sandstone)getOneObjectAtOffset(dx, dy, Sandstone.class);
    if (sandstone != null) {
        getWorld().removeObject(sandstone);
        getWorld().addObject(new Water(), getX() + dx, getY() + dy);
    }

You can use the Actor type: Actor sandstone = getOneObjectAtOffset(dx, dy, Sandstone.class)

    Sand sand = (Sand)getOneObjectAtOffset(0, 1, Sand.class);

Here too: Actor sand = getOneObjectAtOffset(0, 1, Sand.class);

    ((DoorbraakWorld)getWorld()).stopped = true;

How about greenfoot.stop()?


Checking for memory leaks in data structures

This code

if ((self._isArray(obj) || self._isObject(obj))) {
  if (self._isArray(obj)) {
    self._logTooBig(obj, obj.length)
    for (var i = 0; i < obj.length; i++) {
      self._checkIfNeeded(obj[i])
    }
  }
  else if (self._isObject(obj)) {
    self._logTooBig(obj, self._keys(obj).length)

    for (var key in obj) {
      self._checkIfNeeded(obj[key])
    }
  }
}

should be reduced, remove the outside if statement

  if (self._isArray(obj)) {
    self._logTooBig(obj, obj.length);
    for (var i = 0; i < obj.length; i++) {
      self._checkIfNeeded(obj[i]);
    }
  }
  else if (self._isObject(obj)) {
    self._logTooBig(obj, self._keys(obj).length);

    for (var key in obj) {
      self._checkIfNeeded(obj[key]);
    }
  }

There is no need for it.

Also some of your one liner blocks make use of Curly Brackets and some do not,  this is confusing when put together with your 2-space indenting instead of 4-space indenting.  don't worry about space when writing your JavaScript, use all the characters that you need to be able to maintain the code properly, don't Minify until you are completely finished with the code.

Especially when nesting if statements

if ((self._isArray(obj) || self._isObject(obj))) {
  if(obj.__leaks_checked == self.uniq_id)
    return;
  obj.__leaks_checked = self.uniq_id

  setTimeout(self._partial(self.checkLeaks, obj), 5);
}

you should use brackets and proper indenting to make it clear what is going on

if ((self._isArray(obj) || self._isObject(obj))) {
    if(obj.__leaks_checked == self.uniq_id){
        return;
    }
    obj.__leaks_checked = self.uniq_id;

    setTimeout(self._partial(self.checkLeaks, obj), 5);
}

This is also one that almost confused me as well

_keys: function(obj) {
  var rval = [], prop
  for (prop in obj)
    rval.push(prop)
  return rval;
};

I would write it like this (and don't forget the ;)

_keys: function(obj) {
    var rval = [], prop;
    for (prop in obj){
        rval.push(prop);
    }
    return rval;
};

I just realized how many times you left out the semi-colons after a line of code,  this is a very bad habit to fall into.

Always remember your semi-colons!

There are places where I don't think the code will run correctly because you don't have semi-colons to tell the browser that you have ended the command.


Bugs in PrimeNumberClassic

There are multiple bugs in this class : 2 is not prime, while any number <= to 1 are considered prime :(

Some large number may results in infinite loop !!! (I'm going into more details about that at the end of my post)

Before considering the rest of my reviews, you should :

correct them
make unit tests (check JUnit) for your two classes for some cases (2, multiple even numbers not 2, 3, 5, 7, 31, 277, some really big numbers and a negative number for example)

Consider using bigger number

int aren't that big, if you plan on doing math calculations, you should consider switching to long or BigInteger.

Well now, the real review :

Review of PrimeNumber

I don't really get what this class is about. The name makes it sounds like it's storing a prime number but it's not... it actually looks like a Factory of some sort.

I'd consider removing it unless you want to add more features (in which case that may be the object of a future, follow-up, question ^^).

Review of PrimeAbstract

/**
 * abstract class of prime number object
 */
abstract class PrimeAbstract {

    public abstract boolean isPrime(int number);
}

Why is this an abstract class ? It's clearly an interface, also the javadoc is pretty useless.

The name is not very good... why PrimeAbstract ? Aren't PrimeNumberFinder/ PrimeNumberDetector name closer to the intent ?

Review of PrimeAbstract's childs

The code in the implementation really needs to breathe !

Put some spaces in it ;) it's tiring to read it as of now.

As a rule of thumb, put spaces between the = (as well as things like += ofc) sign, the '?' sign and theirs operands as well as between comparators and their operands.

if (number%2==0) return false;

I'm one of the people that don't really care about using { for very simple cases... however putting the return on the same line makes it harder to read IMO.

As said in others questions, any good IDE have a code formatter included solving all previous points (and auto-indenting your code) ;)

The Sieve is okish... I don't really like the fact that it fails with an exception when you use isPrime with a too big number. Also you should make the field private ;)

I'd probably make the sieve lazy and not compute it until isPrime is called for the first time.

1000 is a magic number and should be turned into a constant.

Finally, storing every results in an array is really space-inefficient. Maybe consider storing only the integers that are prime into an HashSet, the contains method with a HashSet is incredibly fast.

I'd optimize PrimeNumberClassic to :

know the results for some very small primes (reducing the complexity for "common" cases)
go for at most sqrt of number... yeah I know you already do that with i*i but it's less clear, likely less performant and it's buggy (if i grows large it'll overflow and you find yourself with a potentially infinite loop or accessing indexes that aren't in your array... no good)

So in the end this implementation may look like something like :

public boolean isPrime(final int number) {
    if (number == 2) {
        return true;
    } else if (number % 2 == 0) {
        return false;
    } else if (number < 36) {
        return number == 3 || number == 5 || number == 7 || number == 11 || number == 13
                || number == 17 || number == 19 || number == 23 || number == 29 || number == 31;
    }

    final int max = (int) Math.round(Math.sqrt(number));
    for (int i = 3; i <= max; i += 2) {
        if (number % i == 0)
            return false;
    }
    return true;
}


Yay, you use tests!

Darn it, you don't use tests.

Confusing? Allow me to explain. While I totally approve of you using tests, there is a lot more to it than simply putting the @Test annotation above them.

A test is comprised of 3 aspects: Arrange, Act and Assert. Typically a test (whether it's unit, integration, functional, end-to-end, etc) will have these aspects in explicit or implicit form. Personally I like to explicitly separate them with comments (// Arrange).

Why do I mention this? Note the last aspect of AAA: Assert. This tells us that, as the last step in our test, we will verify the result we have and assert that it is what we expected.

Doing this allows us to run the tests and automatically compare the result of each test with the expected outcome. In your situation you have to manually verify that each test works as expected; can you see yourself doing that when you have 300 tests instead of 3?

This brings us to another point: all modern IDE's have integrated test runners. If you have tests, you can just run these using that instead of having to use a main() method as entrypoint for your tests.

By adapting these changes you also won't need those println's anymore which takes away focus from your actual content.

Junit documentation
Junit tutorial


Parsing input

input().strip().split() can be reduced to input().split() as split without parameters has extra logic to remove empty strings in the result. It feels also more idiomatic to unpack the two integers using r, c = map(int, input().split())

Parsing princess position

First of, you could create the grid using a list-comprehension rather than append:

grid = [input() for _ in range(n)]

Note that I dropped 0 from the range parameter as it the default starting point.

But you don't even need to build the whole grid since you’re only interested in knowing the princess position. You could search for it while parsing the input:

def princess_position(grid_size):
    for row in range(grid_size):
        try:
            return row, input().index('p')
        except ValueError:
            # Princess not on this line
            pass
    # Princess not in grid
    return -1, -1

grid_size = int(input())
bot_row, bot_column = map(int, input().split())
princess_row, princess_column = princess_position(grid_size)
print(next_move(bot_row, bot_column, princess_row, princess_column))

Comparing positions

You don't need to put parenthesis around ternary operators. You can also simplify a - b > 0 to a > b; same for other comparisons. Last thing, you can perform less work by comparing a == r first and returning left or right before comparing for up and down:

def next_move(bot_row, bot_column, princess_row, princess_column):
    if bot_row == princess_row:
        return 'LEFT' if bot_column > princess_column else 'RIGHT'
    return 'UP' if bot_row < princess_row else 'DOWN'

Top-level code

It is better practice to wrap your top-level code under an if __name__ == '__main__' statement, as it allows you to import your file without executing the whole thing:

def next_move(bot_row, bot_column, princess_row, princess_column):
    if bot_row == princess_row:
        return 'LEFT' if bot_column > princess_column else 'RIGHT'
    return 'UP' if bot_row < princess_row else 'DOWN'

def princess_position(grid_size):
    for row in range(grid_size):
        try:
            column = input().index('p')
        except ValueError:
            # Princess not on this line
            pass
        else:
            return row, column
    # Princess not in grid
    return -1, -1

if __name__ == '__main__':
    grid_size = int(input())
    print(next_move(
        *map(int, input().split())
        *princess_position(grid_size))

I also changed the way to use unpacking to simplify variable managements.


Tabulate k = 2^n minimizing multiplication

If you use 1 instead of 2 as the number to shift, you won't have to subtract one from n. I.e. you can just define k as (ash 1 n).

Other than that your code looks fine.


Cross-site request forgery defense for code to count Likes

Defending agains CSRF offens happens by creating a token that can only be used once by the client that requested it. For proper protection, that token should ofcourse be linked to a form.

A simple one could be to add a md5 hash or similar to all your forms, store that hash somewhere. And then when the user submits, check or the hash is valid. Depending on the requirements, you can also add a Time to live to the hash (e.g. did it take more then 30minutes to submit the form?)

In your case, it is not a form, but a request being send to the server. Simply adding a token to that request (and validating it) would help you protect agains CSRF atacks.


Find the maximum profit if given an array of daily stock prices and allowed to buy and sell twice

It seems the correctness of doing this to the Maximum Subarray Problem
  is more obvious: the 2 maximum subarrays are just finding the max
  first, and then disregard this region, and find the max of the
  remaining 2 sets of data.

That's actually wrong. Let the array be [2, -1, 4, 2, 3]. Your solution would take the whole array as the maximum during the first step (the sum is 11) and remove it, leaving an empty array, so it would return 11. But that's not correct. Two subarray [0, 1) and [2, 5) add up to 12, yielding an optimal solution.

It also implies that your solution to the stock selling problem is also incorrect (a counter example can be constructed in a similar manner).

You can use dynamic programming to solve the problem correctly. There's a constant number of states in each layer, so the extra space complexity is constant (the code is in python, but it should be easy to implement this algorithm in any other language):

def get_two_max(nums):
    """
    Returns the two maximums in the list.
    The list must contain at least 2 elements.
    """
    max1 = max(nums[0], nums[1])
    max2 = min(nums[0], nums[1])
    for num in nums[2:]:
        if num >= max1:
            max2 = max1
            max1 = num
        elif num > max2:
            max2 = num
    return max1, max2

def get_max_two_subarrays(nums):
    """
    Returns the maximum sum of two non-intersecting non-empty subarrays
    """
    if len(nums) < 2:
        # There're no two non-intersecting non-empty subarrays
        return None
    count_non_neg = sum(1 for num in nums if num >= 0)
    if count_non_neg < 2:
        # There is at most one positive element, so the optimal answer is
        # to take two largest elements of the array
        return sum(get_two_max(nums))
    # The state has the following meaning:
    # 0 - the first subarray hasn't started
    # 1 - the first subarray has started, but it's not over yet
    # 2 - the first subarray is over
    # 3 - the second subarray has started, but it's not over yet
    # 4 - both subarrays are over
    dp = [0] * 5
    for num in nums:
        new_dp = [0] * len(dp)
        for state in range(len(dp)):
            # Doesn't change the state. Adds the current element if one of
            # the subarrays is not over.
            new_dp[state] = max(new_dp[state], dp[state] + (num if state % 2 else 0))
            if state + 1 < len(dp):
                # Goes to the next state by opening/closing a subarray
                new_dp[state + 1] = max(new_dp[state + 1], new_dp[state])
        dp = new_dp
    # The answer is the value of the state when both subarrays are over
    return dp[-1]

If you have a solution and you're not sure if it's correct or not, you can do the following:

Implement a slow but obviously correct solution (in this case, it would just generate all subarrays, compute their sums and choose the best one).
Generate thousands of small test cases and compare the output of your solution and the naive one. It's quite likely that you'll a test case your code fails if it's actually wrong (that's exactly how I found a counterexample to your algorithm).


Fastest fill memory with specified 64-bit value

Unfortunately the answer is CPU-dependent. For example here is Android's memset implementation: it uses rep stosq for some CPUs and a different more complicated implementation (avoiding rep stosq) for others.

For further details, on Intel CPUs, refer to the "Enhanced REP MOVSB and STOSB operation (ERMSB)" section of the Intel® 64 and IA-32
Architectures
Optimization Reference Manual.


Conceptually it is a great solution. I can suggest some changes, but in reality they are minor. It would also be 'fun' to tune it  abit, but in the bigger picture the changes would be miniscule... still...

My biggest observation is that the constructors can be simplified a lot. Instead of having each Enum member create a unique method implementation (and that method builds a String each time - though the compiler will probably fix that), you could simplify it a lot with:

private final int degrees;
private final String message;

private Direction(final int degrees, final String name) {
    this.degrees = degrees;
    this.message = degrees + " degrees due " + name;
}

public int getDegrees() {
    return degrees;
}

public String getMessage() {
    return message;
}

With the change to the constructor, you have:

no abstract methods to implement
simple message which is a constant, instead of re-creating it each time you call getMessage()
Your enums are initialized in a simpler way:

NORTH(0, "North"),
EAST(90, "East"),
SOUTH(180, "South"),
WEST(270, "West")

Apart from this, the code is pretty good, but, there is a way you can 'play' with the lookup system to use the ordinals only.... consider the following code (I'll leave it to you to figure out.... ;-):

public static Direction get(final int degrees) {
    int ordinal = ((degrees % 360) / 90) - ( 4 * (degrees % 90));
    return ordinal < 0 ?  null : values()[ordinal];
}


What am I missing?

Several things.

constructor that takes object of type std::nullptr_t
constructor that takes object of type shared_ptr<U> where U is derived from T
boolean conversion operator.
swap operator
move semantics

Sure there is more. In Smart pointers you always forget something.

  Did I implement this smart pointer right?

YOu implemented the rule of three. So barring any bugs it should be good.

  Your suggestions would be appreciated.

I go into a lot of detail in my articles:

Unique Pointer
Smart Pointer
Constructors

Don't use this.

It is not very normal to see this-> in C++ code (unlike Java).

I actually consider the use of this-> as bad practice. You only need to use this->member if there is some ambiguity between local/parameters and member names.

If you have some ambiguity then you have done a bad job at naming and you are using this-> to cover up the problem. Prefer to fix the problem as some poor maintainer is going to come along later and use the wrong variable because of your laziness.

I normally turn on the compiler warning that tells my if a local variable is shadowing another thus forcing me to have unique (and meaningful names).

One Line One Statement

shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)

To me this looks exactly like multiple assignments packed onto the same line.

varOne = 5; varTwo = 6; theOtherOne = doStuff(5);

I think it is well accepted that one line should have one statement. Why not apply this to your parameter list. It will make reading the code much easier and also validating order of initialization problems.

shared_ptr(const shared_ptr &p)
    : refCount(nullptr)
    , t(nullptr)
{
    /* Stuff */
}

Construct with a null ptr

    shared_ptr(T *p) : refCount(new int(1)), t(p) {}

What happens if you I build with a nullptr?

X*            ptr = nullptr;
shared_ptr<X> data1(ptr);
shared_ptr<X> data2(nullptr); // should have its own constructor.

Double Check of isvalid() is wastefull

If p.isvalid() is true then isvalid() will be true after the copy.

    shared_ptr(const shared_ptr &p) : refCount(nullptr), t(nullptr)
    {
        if(p.isvalid())
        {
            refCount = p.refCount;
            t = p.t;

            if(isvalid())
            (*this->refCount)++;
        }
    }

Also this could be much simplified.

    shared_ptr(const shared_ptr &p)
        : refCount(p.refCount)
        , t(p.t)
    {
        if(isvalid()) {
            (*refCount)++;
        }
    }

Prefer Copy/Swap Idiom for assignment.

    shared_ptr& operator =(const shared_ptr &p)
    {
        if(this != &p)
        {
            /* This LOOKS LIKE A BUG */
            /* Don't think the ! should be there. */
            if(!p.isvalid())
            {
                this->destroy();
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;

                return (*this);
            }

            if(!isvalid())
            {
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;

                return (*this);
            }
            else
            {
                this->destroy();
                this->refCount = p.refCount;
                this->t = p.t;

                if(isvalid())
                (*this->refCount)++;
            }
        }
        return (*this);
    }

Sorry that function is big and clumsy and hard to read. It also does not provide the strong exception guarantee. You modify the content of this object doing exception dangerous work (call destroy) before updating the content of this object.

To do any work in exception safe way you need to follow a three step processes.

Make a copy into temp. -> Dangerious as exceptions can fly.
Swap the temp and current. -> Safe as swap should not throw exceptions.
Destroy then temp. -> Safe as the state of current is now good.

This 3 step process is ipitimized by the copy and swap idiom.

 shared_ptr& operator =(const shared_ptr &p)
 {
     shared_ptr  temp(p);    // Constructor copies. Destructor destoryes.
     temp.swap(*this);       // Perform an exception safe transfer of state.
     return *this;
 }

Lots of people take this one step further. And do the copy in the parameter:

 shared_ptr& operator =(shared_ptr p)  // Notice the pass by value.
 {                                     // this gets your copy.
     p.swap(*this);
     return *this;
 }

Const correctness

These two functions do not mutate the state of the object.

    T* operator ->() {return t;}
    T& operator *() {return *t;}

So they should probably be marked as const.


This mostly seems like a layer of sugar coating that just adds overhead and doesn't add any improved functionality over what a javascript object already has.  The only new functionality I see is keeping track of a length, but this is a lot of extra overhead just for that.  The length could be calculated at any time on a plain javascript object.

Here are the analogs to your methods:

var collection = {};

addItem:
    collection[key] = value;

removeItem:
    delete collection[key]

clear:
    collection = {};

exists:
    if (key in collection)

getItems:
    collection.keys()

getLength:
    collection.keys().length

So, all you're getting out of your implementation is a slightly more efficient length and every other operation is less efficient than just using the native code way of doing it.  Is this collection really useful?

There are some older browsers that don't offer the .keys() method, but there's a pretty simple shim that implements it if not available.

In addition, your implementation loses functionality that a plain javascript object has.  For example, you can't pass your collection to any function that expects a javascript object with the keys and values on it because those are hidden inside, they aren't actually properties of the collection object itself.  Then further, you can't do custom iteration of the keys and values without first creating an array of all the keys because you've hidden the natural ability to iterate the keys of a javascript object.


The main shortcoming of this algorithm is that it relies solely on security through obscurity.

Since you save all information to reconstruct the plain-text string in the encrypted string, the only information keeping that encrypted string safe is the fact that an attacker has to know how to get the decrypted string from it. This is inherently unsafe.

As an attacker (who does not know the algorithm, but can use the encrypt function), one could note the following features:

The encrypted string is always six times longer than the plain-text, so a good guess would be that each block of six characters encodes one character.
The second character of that block is always a number, so it is probably not a function that transforms a single character to six random looking characters.
At this point it becomes a game of finding correlations between the characters in the encrypted string and the plain text. A common strategy would be seeing which offset would be needed to get a certain character in the encrypted string. This would lead to the finding that the offset is actually in the encrypted string and your "encryption" is broken.


Detect the last resolve in an ES6 promise chain

Code in the question is hard to follow but it would appear that you are struggling to do something that's achieved very simply with this pattern, with which detection of "the last resolve in an ES6 promise chain" falls out in the wash. Read and understand that before continuing below.

If I'm correct, then you could write :

function makeAsyncSequence(arr, callback) {
    return arr.reduce((chain, item) => {
        return chain.then(() => callback(item));
    }, Promise.resolve());
}

And you would call :

makeAsyncSequence([1,2,3,4,5], doSomethingAsync).then(finalResult => {
    console.log('complete');
});

This is so simple that, in practice, we would normally choose to write arr.reduce(...) out longhand in our application everywhere it's needed. A special utility function like above is seldom needed.

Now, if you wish to impose a minimum delay that is not already imposed by the callback function :

First a delay function ...

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
};

... and an enhanced version of makeAsyncSequence(), in which callback(item) is aggregated with delay(minimumDelay) :

function makeAsyncSequence(arr, callback, minimumDelay) {
    minimumDelay = +minimumDelay || 0;
    return arr.reduce((chain, item) => {
        return chain.then(() => {
            if (minimumDelay) {
                return Promise.all([callback(item), delay(minimumDelay)]); // the slower of the two async processes determines the timing of the returned promise's success path.
            } else {
                return callback(item); // no minimumDelay required, therefore act as in the simple case.
            }
        });
    }, Promise.resolve());
}

And you would call :

makeAsyncSequence([1,2,3,4,5], doSomethingAsync, 1000).then(finalResult => {
    console.log('complete');
});

demo

Due to the increased complexity we would probably choose to write this as above in our application - ie as pair of special utilities.


Style

You’ve already been told that by @alexwlchan in your previous question but: "whitespace is cheap" and it improves readability a lot. Compare your code to:

def asciiart(text, conf=default_conf):
    """Produces an ascii art representation of text using the conf data"""
    if isinstance(conf, str):
        conf = conf.split('\n')

    height, key, data = int(conf[0]), conf[1], conf[2:]
    figures = dict(map(
        lambda x: (x, data[key.index(x) * height: (key.index(x) + 1) * height]),
        key))
    art = '\n'.join([
        '\n'.join([
            ' '.join([figures[x][i] for x in t.lower() if x in figures])
            for i in range(height)])
        for t in text.split('\n')])
    return art

Again, you should also consider using generator expressions rather than list-comprehensions to feed into your join calls: turn those square brackets into parenthesis.

Handling font configuration

First of, when reading the file, you should remember to close it:

with open('C://Programs//Python35//Lib//asciiart.txt') as configuration_file:
    default_conf = configuration_file.read()

You may also want to name the resulting string DEFAULT_CONF as it is a constant.

Second, why parse this string at each call of asciiart? You should provide a function that will do the parsing and asciiart will only be responsible of using the parsed configuration:

ASCII_ART_CONFIGURATION = {}

def parse_ascii_art_configuration(filename='C://Programs//Python35//Lib//asciiart.txt'):
    with open(filename) as f:
        conf = f.read().split('\n')
    height, key, data = int(conf[0]), conf[1], conf[2:]
    figures = dict(map(
        lambda x: (x, data[key.index(x) * height: (key.index(x) + 1) * height]),
        key))
    ASCII_ART_CONFIGURATION.update(figures)

def asciiart(text):
    if not ASCII_ART_CONFIGURATION:
        parse_ascii_art_configuration()

    art = '\n'.join(
        '\n'.join(
            ' '.join(ASCII_ART_CONFIGURATION[x][i]
                     for x in t.lower() if x in ASCII_ART_CONFIGURATION)
            for i in range(height))
        for t in text.split('\n'))
    return art

The advantage being:

You give your users direct access to the underlying ASCII_ART_CONFIGURATION that they can populate the way they want if need be;
You give your users an easy way to provide their own configuration filepaths;
You parse the configuration only once.

Obviously, this version wont work since asciiart does not have access to height any more. Time to bring our old friend zip (or itertools.zip_longest) back:

from itertools import zip_longest

def asciiart(text):
    if not ASCII_ART_CONFIGURATION:
        parse_ascii_art_configuration()

    art = '\n'.join(
        '\n'.join(
            ' '.join(row)
            for row in zip_longest(
                (ASCII_ART_CONFIGURATION[x]
                 for x in t.lower() if x in ASCII_ART_CONFIGURATION),
                fillvalue=''))
        for t in text.split('\n'))
    return art

Better iterations

Now that we have a better API, let's focus a bit more on the code:

iteration over a file can be made using either the "reading" API or the iterator one, this can help better handle the separation of each part:

with open(filename) as f:
    height = int(next(f))
    keys = next(f)
    data = [line.rstrip('\n') for line in f]

building of the figure dictionary can be made more efficient using the grouper recipe from itertools:

def grouper(iterable, n):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3) --> ABC DEF G"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue='')

def parse_ascii_art_configuration(filename='C://Programs//Python35//Lib//asciiart.txt'):
    with open(filename) as f:
        height = int(next(f))
        keys = next(f)
        data = [line.rstrip('\n') for line in f]

    figures = {
        character: list(group)
        for character, group in zip(keys, grouper(data, height))
    }
    ASCII_ART_CONFIGURATION.update(figures)

now that we use zip_longest to concatenate ascii-art letters, you can simplify handling missing symbols by turning ASCII_ART_CONFIGURATION into a collections.defaultdict:

ASCII_ART_CONFIGURATION = defaultdict(list)

def asciiart(text):
    if not ASCII_ART_CONFIGURATION:
        parse_ascii_art_configuration()

    return '\n'.join(
              '\n'.join(
                  ' '.join(row)
                  for row in zip_longest(
                      (ASCII_ART_CONFIGURATION[x] for x in line_of_text),
                      fillvalue=''))
              for line_of_text in text.lower().splitlines())


Recursive implementation of palindrome string checker

For all practical purposes, recursion is a bad idea for this problem, mainly because String.substring() is an expensive operation, especially since Java 7.  Let's assume that you're doing this just as a fun educational exercise.

Single return statements are overrated.  There's no practical advantage to forcing your code to have just one return for its own sake.

Your base cases are poorly chosen.  A zero-length string will cause a crash.  If you handle empty strings as a base case, then you no longer need to treat two-character strings as a special case.

You take the string length often enough that it's worth assigning it to a variable.

Overall, the function could be written more compactly.

public static boolean isPalindrome(String s) {
    int len = s.length();
    if (len <= 1) {
        return true;
    }
    return (s.charAt(0) == s.charAt(len - 1)) &&
           isPalindrome(s.substring(1, len - 1));
}


Two major suggestions:

First, let's try speeding everything up by taking advantage of the nature of Conway's Game of Life and the way C++ handles pointers. When you evaluate Conway's Game of Life, it's a two part process.  First you copy all of the entries into a new array, then you do your computation referring to that new array, and update the original one. This process takes \$ O \left( n^{2} \right) \$, and involves a major memory copy; for small sizes that shouldn't be a problem, at larger sizes, the cost incurred by the memory copy will become non trivial, so let's reformulate the design a little:

Conway's Game of Life itself is an application of cellular automata, where the state G of the grid at time t is a function of of the state at a time t-1. More specifically, it would be of a form like this: G(t)=R(G(t-1)) where R() is some rule function determining which cells live and which cells die. This direct dependence offers us an interesting solution to the memory copying conundrum--what if we store two grids, one to represent G(t) and one to represent G(t-1)? Then we can get away with reading G(t-1), applying our rule and updating G(t). This however brings us back to the first question--how do we update G(t-1) then? do we just copy G(t)'s memory? C++ offers us a more convenient approach actually, we can swap the pointers instead: as G(t) is fully described by G(t-1) if we simply swap the pointers for the two arrays, so the pointer for G(t-1) refers to G(t)'s memory region, and G(t) refers to G(t-1)'s memory region, then we can apply the update rule, update G(t) to be G(t+1), overwriting the old memory used to store G(t-1), which prevents us from needing to copy the grids ever, which will significantly speed up the simulation in case n>500 in my experience.

The second comment is on code abstraction, cellular automata as a whole is a good place to explore this, because it's such a general field. It's not necessary to make your Conway's Game of Life code work, but it will make it easier if you come up with interesting variations you want to test. Right now you have the update rule, R() represented as a single function, liveOrDie, this can be re-factored into several smaller tasks however, which has the advantage of making the system more modular and easier to tweak. How then can we break down this rule into smaller, more modular components? Let us start by listing the actual procedure performed by the update function:

Iterate over all of the cells and update them
To update a cell, look up it's neighbors (in Conway's Game of Life we use the Moore neighborhood)
Look at a cells neighbors and decide whether it will live or die (apply the rule to a cell)
Update the contents of a cell according to it's rule

This list of tasks lends itself to defining three separate functions

void update(G(t),G(t-1)), which will perform the updating itself
int neighbors(G,x,y), which will return the number of neighbors of a cell indexed at (x,y)
bool rule(neighbors,lod,x,y) which will look at a specific cell and decide whether it lives or dies (lod is the state of the cell, live or dead)

The basic outline could then be something like this:

update(G(t),G(t-1)){
 for(x: 1..size)
  for(y: 1..size){
    G(t-1)[x+y*size] = rule(neighbors(G(t),x,y),G(t)[x+y*size],x,y)
  }
 swap = G(t-1)
 G(t-1) = G(t)
 G(t) = swap
}

The advantage to this model is if you want to change the function of the rule, or the neighborhood, say apply periodic bounding, you can easily change only the definition related to that part of the code. Hope that helps.


A simple command line linear interpolator in C

Program Usage:

Your usage string is a little...aenimic. I didn't read the initial
part of your post about needing to use 0n as a "missing" value, and
had to squint a little bit before I figured out what is was doing.
This sort of information should ideally be printed out (either when
the user doesn't input enough arguments, or if a flag is passed;
generally this would be -h or --help):

void print_usage()
{
    printf("Usage: lin_interp <list of floating point values>\n");
    printf("lin_interp linearly interpolates pairwise. To input "
           "values to be interpolated, use 0n. For example:\n"
           "lin_interp 100 0n 200\n"
           "will produce 100.0 150.0 200.0, where 0n has been "
           "replaced by the interpolated value.");
    exit(1);
}

Initialization:

There's a little trick for array initialization in C that comes in
handy. Instead of having to loop over an array, initializing it
with the same value:

for(j = 0; j < MAXLEN; j++)
    filled[j] = 0.;

You can simply write:

float filled[MAXLEN] = {0.0f};

This will initialize each value of your array to 0.0.

Functions:

When you start writing programs, they're generally quite small, and
a lot of the time everything fits neatly into main. However, when
you start writing slightly larger programs, this starts to become
inconvenient. It makes your program harder to follow, lets variables
live for longer than they should, and means parts of a program cannot
easily be reused (and further along in your programming career, it
makes things harder to test, too). A large part of programming
is breaking things down into small pieces, writing those small
pieces separately, and composing them together into a solution.

Here, there are a few things that should exist as functions. The
first one we've already shown; print_usage(). The code that
performs the interpolation should also be inside its own function:

size_t interpolate(float* filled, size_t len)
{
    // Interpolation Code
}

 Braces:

It's tempting to omit braces when you're only using a single-line
command:

for(i = 1, j = 0; i < argc && strcmp(argv[i], NULLA) == 0; i++)
   filled[j++] = NULLF;

Although this is a point of some contention, it's (generally) not
seen as very good practice, especially in a language like C. It is
all too easy for you (or someone else) to come back to the code to
make a minor modification, and forget that there are no braces:

int starting_nulls = 0;
for(i = 1, j = 0; i < argc && strcmp(argv[i], NULLA) == 0; i++)
    filled[j++] = NULLF;
    ++starting_nulls;    //Uh-oh!

Prefer to wrap even single line statements in { }. It is almost
zero effort, and will stop these kinds of mistakes.

 const vs #define:

Prefer to use const instead of #define whenever you can. Because
of the quirks of C, this is not always possible:

// This has to be a #define to be used in an array length
#define MAXLEN 1000
// These can both be const
const char NULLA[] =  "0n"
const float NULLF = -1000.0f;

#define is a very crude mechanism that can cause a lot of headaches.
A lot of older C code uses it (because there was no other option),
but it is still a good idea to keep its use to a minimum.


Quick review, there are a few things I think you could improve, they are mostly a matter of style though.

Casing

Just pick a casing style and stick to it, you are actually using all 3 casing styles kind of randomly.

Common Table Expression (or, CTE)

In Transact-SQL/ Microsoft SQL Server, there's a syntax sugar type of expression to help reduce sub-queries, the execution plan from the query engine should be the same but they help readability.

For instance, look at this join clause:

from
  uk_registered_companies.dbo.Filed_Accounts
JOIN (
  Select
      companyNumber,
      max(convert(date, CONVERT(varchar(20),file_date),103)) as MaxDate
  from
      uk_registered_companies.dbo.Filed_Accounts
    group by CompanyNumber
) as mostRecentAccounts

You could do something like this:

--Here is the CTE:
with mostRecentAccounts as (
        select
            companyNumber,
            max(convert(date, CONVERT(varchar(20),file_date),103)) as MaxDate
        from
            uk_registered_companies.dbo.Filed_Accounts
        group by CompanyNumber
)
--end of CTE
select
    *
from
    uk_registered_companies.dbo.Filed_Accounts
join
    mostRecentAccounts
  on
    Filed_Accounts.CompanyNumber = mostRecentAccounts.CompanyNumber
  and
    (convert(date, CONVERT(varchar(20),Filed_Accounts.File_Date),103)) = mostRecentAccounts.MaxDate

Indentation

I did a few changes to your formatting to make it easier to read. For indenting, I usually have the following keywords to the left, and indent everything else accordingly, kind of a crapshoot as there is no official style guide:

with Foo as (
    --...
)
select
  --...
from
  --...
join
  --...
    on --...
where
  --...
group by
  --...
having
 --...
order by
 --...


Inserting a DBNull value into a database

The most terse and declarative way to write this is to use C#'s ?? operator. Your line becomes:

new SqlParameter("@Price",  (object)items.Price ?? DbNull.Value),

The expression here will either return the non-null value of the left operand (items.Price), or return the operand to the right instead.

If you hadn't guessed, the ?? operator is basically syntactic sugar for if operl  != null ? operl : operr.


JavaScript module to render and handle a form to add users

Your Concerns/Questions

  Whenever I add an user, it reloads the entire list.

One alternate approach would be to have the handleAddUser() store the newly added user in a property (e.g. recentlyAdded) and then have the render() method look for that property - if it is set (to something other than null) then add the rendered template of the new user and clear that property.

When the page loads, is there an existing list of users that gets added to the list? If so, maybe those could be stored in a different property and the existing code in render() could look for that property for rendering the existing records.

  I could of course just add the new entry to the DOM inside the Users.handleAddUser method but what if later, I also want to delete users.  I would have to delete the entry within Users.handleRemoveUser and would so already have two methods that handle DOM modifications for the same thing.

Going along with the alternate approach above, one could have the handleRemoveUser method also store the key of the recently removed user, and then the render() method can look for that property too and remove such an element associated with that key - perhaps by adding an id or other data attribute to the template.

You didn't include an implementation for handleRemoveUser so I can only guess as to what it would be: some way of removing the user from the list this.user. If this.users is still an array, then looking for the user to remove might require a loop. However if this.users is an associative-array (i.e. object with keys corresponding to the key of each user) (or a Map), then looking for the user to remove can be achieved without a loop.

See this demonstrated in the snippet below.

In revision 2 you had this question, altered in revision 5:

  As you can see I am not getting the input by ID but by form.elements and then referencing the name.

It is fine to do that, but because the form data doesn't get sent to the server-side, you could also use the id attribute on the input instead of the name attribute, and then fetch that element by id.

Other Feedback

The Template.get() function loops over the keys in placeholders:

for (key in placeholders) {

For this loop, key is a global variable, which may or not be intentional. In general it is best to avoid global variables. One reason would be that if code in a separate function makes its own variable with the same name, there would be no chance of overwriting the value if it isn't a global variable. Use const to declare key as local to that loop.

for (const key in placeholders) {

I recently saw this SO answer that offers a solution to interpolating a string literal similar to how a template literal would be interpolated. I compared it with the regular expression approach in your code and found it to be much slower (see this jsPerf test). I was hoping I could offer that suggestion but unfortunately it can be much slower.

// lets you get templates from HTML ( as you can see in the HTML above ).
// This is to avoid writing out HTML inside JavaScript
const Template = {
  cached: {},
  get(templateId, placeholders) {
   let templateHtml = ''
   if (!this.cached[templateId]) {
      templateHtml = document.getElementById(templateId).innerHTML.trim()
      this.cached[templateId] = templateHtml
   }
   else {
      templateHtml = this.cached[templateId]
   }

   for (let key in placeholders) {
     templateHtml = templateHtml.replace(new RegExp("\\${\\s*" + key + "\\s*}", "g"), placeholders[key]);
   }
   return templateHtml
  }
}

const Users = {
  users: {},
  recentlyAdded: null,
  recentlyRemovedKey: null,
  nextKey: 1,
  init() {
    this.cacheDom()
    this.bindEvents()
  },
  cacheDom() {
    this.addUserFormEl = document.getElementById('add-user-form')
    this.userListEl = document.getElementById('user-list')
  },
  bindEvents() {
    this.addUserFormEl.addEventListener('submit', this.handleAddUser.bind(this))
    this.userListEl.addEventListener('click', this.handleListClick.bind(this));
  },
  render() {
    // gets the HTML from ALL users of our user list and replaces the current user list
    /*const userHtml = this.users.map( user => Template.get('user-template', user) ).join('')
    this.userListEl.innerHTML = userHtml*/
    if (this.recentlyAdded) {
     this.userListEl.innerHTML += Template.get('user-template', this.recentlyAdded);
     this.recentlyAdded = null;
    }
    if (this.recentlyRemovedKey) {
     const element = document.getElementById(this.recentlyRemovedKey);
      if (element) {
       element.remove();
      }
     this.recentlyRemoved = null;
    }
    console.log('userlist after render: ',this.users);
  },
  handleAddUser(e) {
    e.preventDefault()

    const username = e.currentTarget.elements['username'].value
    if (!username) return
    e.currentTarget.elements['username'].value = ''

    const key = this.nextKey++;

    this.users[key] = {
      key: key,
      name: username
    };
    this.recentlyAdded = this.users[key];

    this.render();
  },
  handleListClick(e) {
    const target = e.target;
   if (target.classList.contains('remove')) {
     this.handleRemoveUser(target.parentNode.id);
    }
  },
  handleRemoveUser(key) {
   delete this.users[key];
    this.recentlyRemovedKey = key;
    this.render();
  }
}

Users.init()
.remove:before {
  content: 'X';
}
<form id="add-user-form">
  <input type="text" placeholder="username" name="username">
  <button>add User</button>
</form>


Checking for any character common to two strings — Go is 50× slower than Python

This entire answer refers to my rewrite of the asker's code on the Go Playground and is mostly a summary of our discussion on the chat.so Go/Golang room. For reference, I'm reproducing the code below:

package main

import (
    "bufio"
    "io"
    "os"
    "strconv"
)

// charSet is a limited bitset to contain all lowercase latin characters (a-z).
type charSet struct {
    bits uint32
}

// Set switches a bit to 1 for any given character i that is in the range 'a'
// to 'z'. Characters outside this range have undefined behavior.
func (c *charSet) Set(i uint8) {
    c.bits |= 1 << (i - 'a')
}

// Intersects returns whether two charSets intersect (i.e., share one or more
// on bits).
func (c charSet) Intersects(o charSet) bool {
    return c.bits&o.bits != 0
}

// set returns a charSet for all bytes in s. Bytes in s must be in the range of
// 'a' to 'z'. Anything outside that range is regarded as undefined behavior.
func set(s []byte) charSet {
    var c charSet
    for i := 0; i < len(s); i++ {
        c.Set(s[i])
    }
    return c
}

// subst returns whether two strings share any characters. l and r are assumed
// to only contain characters in the range of 'a' to 'z'.
func subst(l, r []byte) bool {
    return set(l).Intersects(set(r))
}

func main() {
    var n int
    r := bufio.NewReader(os.Stdin)

    if l, err := r.ReadString('\n'); err == nil && len(l) > 1 {
        if n, err = strconv.Atoi(l[:len(l)-1]); err != nil {
            panic(err)
        }
    } else if err != nil {
        panic(err)
    }

    for i := 0; i < n; i++ {
        var s1, s2 []byte
        var err error
        s1, err = r.ReadBytes('\n')
        if err == nil {
            s2, err = r.ReadBytes('\n')
        }
        if err != nil && err != io.EOF {
            panic(err)
        }
        if len(s1) > 0 && len(s2) > 0 && subst(s1[:len(s1)-1], s2[:len(s2)-1]) {
            io.WriteString(os.Stdout, "YES\n")
        } else {
            io.WriteString(os.Stdout, "NO\n")
        }
    }
}

There are two major changes here to get this to the point that it at least beats Python in my own test runs on HackerRank:

Replace fmt.Scanf with just reading and parsing where necessary. The only input that requires actual parsing is the first integer, so there's no need for fmt.Scanf beyond that. Even initially we don't need it, however, because we're really only interested in parsing the first line. As such, I just replaced the entire thing with a buffered reader and read up to a delimiter, assuming that all lines end with '\n' (they should for this case). After that, I just run the first line through strconv.Atoi.

This chops off a reasonable amount of time in reading because it avoids parsing a format string and then modifying the input read to conform to the format string, as well as possible time spent in reflection depending on the data. I don't think it'll actually hit the reflect package here, but I haven't looked at the fmt.Fscanf implementation, so take that with a grain of salt.
Use a limited bitset (i.e., just one integer) instead of map[uint8]bool. This is more obvious as to why it's faster: there's no need to allocate more than four bytes on the stack to use an integer, and because the problem constrains the input strings to lowercase characters in the range of 'a' to 'z', we know it'll fit in the bounds of a 32-bit integer.

The charSet type and set function (which is just me being lazy and sort of mimicking the Python code) covers the entire implementation of this. All it does is, given a byte, update the underlying bits integer and test for an intersection using a bitwise and. To get a complete bitset for a string, or byte slice, just iterate over its length and set those bits.

This results in pretty simple code, an acceptable interface for working with a bitset that makes changes to the implementation easier, and it's much faster than allocating memory for a map, creating new cells in the map, and lookups in the map. (I think it's likely that some improvement would be seen by giving the map enough initial capacity for the cardinality of its key, but I doubt if it'd be significant — haven't tested it, so that's something to look into.) These are all fast enough for day to day things, but if we're trying to beat the time on some program, data structures are low-hanging fruit.

With those changes, I get, at worst, 0.01s on HackerRank for test #4 and #5 (possibly both — I'm guessing it's rounding at this point) and 0s for all other tests. This is also fairly easy to benchmark using the testing package, but I don't have a way to compare those results with Python's, so I consider HackerRank's authoritative for now.


Creating a array of custom objects from JSON, sent using PHP from a MySQL database

Let me try to clean it little bit.

1 First of all you made jsonArray global. I think it's not necessary.
You can declare it locally where needed.

2 retrieveData() function looks very messy.
You can abstract that creation of Blog object.

3 You can improve for loop code

So here is what I would propose:

class Blog: NSObject {

  var blogName: String!
  var blogStatus1: String!
  var blogStatus2: String!
  var blogURL: String!
  var blogID: String!
  var blogType: String!
  var blogDate: String!
  var blogPop: String!

  init?(from jsonObject: AnyObject) {
    guard let bID: String = jsonObject.object(forKey: "id") as? String,
        let bName: String = jsonObject.object(forKey: "blogName") as? String,
        let bStatus1: String = jsonObject.object(forKey: "blogStatus1") as? String,
        let bStatus2: String = jsonObject.object(forKey: "blogStatus2") as? String,
        let bURL: String = jsonObject.object(forKey: "blogURL") as? String,
        let bType: String = jsonObject.object(forKey: "blogType") as? String,
        let bDate: String = jsonObject.object(forKey: "blogDate") as? String,
        let bPop: String = jsonObject.object(forKey: "blogPop") as? String else {
            print("Error: (Creating Game Object)")
            return nil
    }
    blogName = bName
    blogStatus1 = bStatus1
    blogStatus2 = bStatus2
    blogURL = bURL
    blogID = bID
    blogType = bType
    blogDate = bDate
    blogPop = bPop
    super.init()
  }
}

So outside world will not have to worry about converting json object into Blog.

Then simply use this abstraction as:

var mainArray = [Blog]()

func retrieveData() {

  let getDataURL = "http://example.com/receiving.php"
  let url: NSURL = NSURL(string: getDataURL)!

  do {
    let data: Data = try Data(contentsOf: url as URL)
    let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

    // Looping through jsonArray
    for jsonObject in jsonArray {
      if let blog = Blog(from: jsonObject as AnyObject) {
        mainArray.append(blog)
      }
    }
  }
  catch {
    print("Error: (Retrieving Data)")
  }
  myTableView.reloadData()
}


Calculate the number of palindrome numbers in the given ranges

Need new algorithm

The current algorithm you are using takes \$O(n \log m)\$ time, where \$n\$ is the size of the range and \$m\$ is the larger end of the range.  For example, if you are trying to find the number of palindromes between 1 and 1000, you iterate through all 1000 numbers (\$n\$) and for each number you do a palindrome check that iterates through the 3 digits of the number (\$\log m\$).  Given a large range, such as 1..1000000000, your program will be iterating for a long time.

Can be done in \$O(\log m)\$ time

This problem can actually be done in logarithmic time.  First, change the problem to finding the number of palindromic numbers between 1 and n.  Then the answer to the actual problem will be num(b) - num(a-1).

Now, to find how many palindromes there are between 1 and n, there is a trick you can use.  You don't have to count/find actual palindromes.  You can just look at the front half of the given number to get an estimate of the number of palindromes.

Example for even number of digits

How many palindromes are there between 1 and 12345678?

If you take the front half ("prefix") of the number, i.e. 1234, you can use that to estimate the number of palindromes.  Each number between 1 and 1234 can "generate" two palindromes: one with the last digit not repeated (making an odd number of digits), and one with all digits repeated (making an even number of digits).

Example: take the number 25.  This number can generate two palindromic numbers:

25 -> 252   (the last digit 5 is not repeated = odd number of digits)
25 -> 2552  (all digits repeated = even number of digits)

If you take all the numbers between 1 and 1234, you can generate 1234*2 palindromes this way.  You can also easily prove that all of the generated palindromes are less than 12345678.

However, there are also some palindromes that are missing.  These are generated by prefixes greater than 1234.  For each of the prefixes from 1235..9999, there is another palindrome that should be counted.  For example, take the number 2345.

2345 -> 2345432  (should be counted)
2345 -> 23455432 (too large)

So in addition to the prefix*2 palindromes already counted, we need to add 10^prefixLength - prefix - 1 extra palindromes.  The final answer is:

number of palindromes = prefix * 2 + 10^prefixLength - prefix - 1

Example for odd number of digits

How many palindromes are there between 1 and 123456789?

The answer for an odd length number is similar for an even length number.  I won't go through the whole proof, but here are the differences:

The prefix length is rounded up.  For the example, the prefix is 12345.
Some of the prefix*2 palindromes generated are not valid because they are larger than the original number.  All of the prefixes from 10000..12345 generate an extra prefix that is too large.  So there is an adjustment to subtract from the count of prefix - 10^(prefixLength-1) + 1.

The final answer for an odd length is:

number of palindromes = prefix * 2 - prefix + 10^(prefixLength-1) - 1

Final adjustment

I skipped one detail in all of the above.  Sometimes you need to subtract one from the prefix because the palindrome it generates is less than the original number.  For example, for 12345678, 1234 is the correct prefix to use because 12344321 is less than 12345678.  But if the original number were 12340000, then 1234 would be too high because 12344321 is greater than 12340000.  So you would use 1233 instead.

Example program

Here is a program that utilizes the method above to solve the problem in \$O(\log m)\$ time:

// Counts the number of palindromic numbers between two given numbers a and b.
//
// 121 is palindromic, 123 is not.
//
// Input is "n", the number of tests, and then n pairs of "a b".

#include <stdio.h>

static int numPalindrome(int num);
static int constructPalindrome(int palPrefix, int numLength);

int main(void)
{
    int a = 0;
    int b = 0;
    int n = 0;

    scanf("%d", &n);
    while (n-- > 0) {
        scanf("%d %d", &a, &b);
        printf("%d\n", numPalindrome(b) - numPalindrome(a-1));
    }
    return 0;
}

// Returns the number of palindromes between 1 and num.  If the input is 0,
// this function will return 0.
static int numPalindrome(int num)
{
    int numLength = 0;
    int palLength = 0;
    int palPrefix = 0;
    int temp      = 0;
    int i         = 0;

    // Example 1: num = 12345678
    // Example 2: num = 123456789

    // Find the length of the number, in digits.  Examples: 8 and 9
    for (numLength=0, temp = num; temp != 0; temp /= 10)
        numLength++;

    // Find the palindrome prefix, which is the front half of the number,
    // rounding up the length.
    //
    // Examples: palLength = 4    and 5
    //           palPrefix = 1234 and 12345
    palLength = (numLength+1) / 2;
    palPrefix = num;
    for (i=0; i < numLength - palLength; i++)
        palPrefix /= 10;

    // Check whether the palindrome formed by palPrefix is greater than num.
    // If it is, we subtract one from palPrefix because the last palindrome
    // is not usable.
    //
    // Example 1: Is 12344321  greater than 12345678?
    // Example 2: Is 123454321 greater than 123456789?
    if (constructPalindrome(palPrefix, numLength) > num)
        palPrefix--;

    // So right now, we have palPrefix being 1234 and 12345 for the two
    // examples.  The number of palindromes less than num is close to
    // palPrefix*2.  The reason is, for each number from 1..palPrefix, you can
    // can construct two palindromes, one of odd length where the last digit
    // is not repeated, and one of even length where all digits are repeated.
    //
    // 25  -> 252    2552
    // 256 -> 25652  256652
    //
    // Starting with all these, palindromes, we adjust the count depending
    // on whether the original number had an even or odd number of digits.
    //
    // For even numLength, we are missing some palindromes, for example:
    //
    // num       = 12345678
    // palPrefix = 1234
    //
    // We can create a palindrome with prefix higher than 1234 that is still
    // less than num.  For example, choose 2345:
    //
    // 2345 -> 2345432
    //
    // So for each number from 1235..9999, we should add one to the count.
    // In other words, add 10^prefixLength - 1 - palPrefix to the count.
    //
    // For odd numLength, we have too many palindromes.  Some of the
    // palindromes already created are not usable.  For example:
    //
    // num       = 12345678
    // palPrefix = 12345
    //
    // 12345 -> 1234554321 (too big, 10 digits)
    //
    // So for all the max digit prefixes, we can only use 1 of the 2
    // palindromes.  So we should subtract some from the count.  The number we
    // need to subtract in this case is: (12345 - 9999).  In other words,
    // subtract palPrefix - (10^(prefixLength-1) - 1) prefixes.
    palPrefix *= 2;
    if (numLength & 1) {
        // Subtract off adjustment for odd length.
        int adjustment = 1;
        for (i=1;i<palLength;i++)
            adjustment *= 10;
        palPrefix -= (palPrefix/2 - adjustment + 1);
    } else {
        // Add adjustment for even length.
        int adjustment = 1;
        for (i=0;i<palLength;i++)
            adjustment *= 10;
        palPrefix += (adjustment - 1 - palPrefix/2);
    }
    return palPrefix;
}

/**
 * Constructs a palindrome from a prefix.  Examples:
 *
 * Prefix = 1234  numLength = 8, returns 12344321
 * Prefix = 12345 numLength = 9, returns 123454321
 */
static int constructPalindrome(int palPrefix, int numLength)
{
    int front = palPrefix; // Starts at 1234, builds to 12340000
    int back  = 0;         // Starts at 0   , builds to 4321

    // If the number length is odd, we do not want to repeat the last digit
    // of the prefix, so skip it here.
    if (numLength & 1)
        palPrefix /= 10;

    // For each digit in the remaining prefix, remove the last digit and
    // place it on the back of "back".  In other words, we are reversing
    // palPrefix into "back".
    while (palPrefix != 0) {
        int digit = palPrefix % 10;

        palPrefix /= 10;
        back       = back * 10 + digit;
        front     *= 10;
    }
    return front + back;
}


Gradient descent for linear regression using numpy/pandas

Without having the insight (or, honestly, time) to verify your actual algorithm, I can say that your Python is pretty good.

Only minor stuff - this kind of comment - # path to read data from - should be turned into a PEP257-style docstring.

You should add a shebang at the top of your file, probably #!/usr/bin/env python3.

Otherwise, you're off to a good start.


I'd contend that State is pure and functional, but I think translating your current code to use State is an excellent exercise so I'll leave that up to you.
The first thing I'd address is making your types do more of the bookkeeping. Well designed types lend themselves to correct-by-construction solutions.
data Player = P1 | P2 deriving Show

data Game = Game { turn :: Player, p1 :: Int, p2 :: Int } deriving Show

Prefer pattern matching to equality testing, it is frequently more terse. Decreased line noise often means increased readability.
changeTurn :: Player -> Player
changeTurn P1 = P2
changeTurn P2 = P1

Your determineWinner function has a (currently unreachable) logic error. If both player's scores are equal then it prefers handing victory to player two. This may not matter in your code as written, but if your code changes or you begin property testing or some other unforeseeable future event comes to pass, it could begin mattering unexpectedly. Handling ties is “morally” the right thing to do.
Also as-is it isn't really determining a winner by the rules of the game, only which player's score is higher.
winner :: Game -> Maybe Player
winner (Game _ p1 p2) =
    case (max p1 p2 >= 10, p1 > p2, p2 > p1) of
      (True, True, False) -> Just P1
      (True, False, True) -> Just P2
      (_, _ , _)          -> Nothing

Don't validate and then parse, parse and allow for failure. If your validation code is separate from your parsing code you risk them drifting out of sync and causing errors. In this case, use Text.Read.readMaybe from base and leave out your isInteger function entirely.
It's a good idea to separate as much of your pure game logic from IO actions as possible. It's easier to test, easier to understand, and enables you to reuse functionality you otherwise couldn't.
updateRound :: Int -> Game -> Game
updateRound n (Game P1 p1 p2) = Game P2 (boundScore $ p1 + n) p2
updateRound n (Game P2 p1 p2) = Game P1 p1 (boundScore $ p2 + n)

clamp :: Ord a => a -> a -> a -> a
clamp lo val hi = lo `max` val `min` hi

boundScore :: Int -> Int
boundScore n = clamp 0 n 10

This also obviates the need for changeTurn.
It's also usually handy to separate your display logic from your control logic, even if both are IO actions. It might be useful to you if you make use of the REPL while developing, your types often shouldn't include multiple copies of the same information (e.g., two numbers and their difference) as that carries a risk of the values getting out of sync. Those derived values might be all you want to see while working though.
displayGame :: Game -> IO ()
displayGame (Game _ p1 p2) = do
    putStrLn $ "P1 Score: " ++ show p1
    putStrLn $ "P2 Score: " ++ show p2

That said, it's good to separate your control logic from your sources of input and output also. It makes your program testable without needing to muck about with piping stdin and stdout. There's also a very elegant transformation when you decide to begin using State, but I'll leave that to you to figure out.
gameRound :: Int -> Int -> Game -> (Maybe Player, Game)
gameRound guess answer game =
  let
    score = calcPointsEarned guess answer
    nextGame = updateRound score game
  in
    (winner nextGame, nextGame)

receiveGuess :: Player -> IO Int
receiveGuess player = do
    putStr $ show player ++ "'s turn. Pick a number between 1 and 10: "
    input <- getLine
    case readMaybe input of
      Nothing -> do
        putStrLn "The input must be an integer"
        receiveGuess player
      Just guess -> pure guess

play :: Game -> IO ()
play game = do
    answer <- randomRIO (1, 10)
    guess <- receiveGuess (turn game)
    putStrLn $ "The answer is " ++ show answer
    let (mPlayer, nextGame) = gameRound guess answer game
    displayGame nextGame
    case mPlayer of
      Just player -> putStrLn $ show player ++ " wins!"
      Nothing -> play nextGame


As for the immediate problem, changing the initial start position, after all the cards have been added, to a random position should remove the bias:

public void SetStart()
{
    int limit = GetNextRandom(_count)
    for (int i = 0; i < limit; i++)
    {
        _current = _current.Next;
    }
}

Use custom classes rather than anonymous classes.  This encapsulates your code better and it is easier to decode what you've done.  Also now if you want to test different shufflers you can re-use a Card class.

public class Card
{
    public enum Suit
    {
        Clubs,
        Diamonds,
        Hearts,
        Spades
    }

    public enum Rank
    {
        Two = 2,
        Three,
        Four,
        Five,
        Six,
        Seven,
        Eight,
        Nine,
        Ten,
        Jack,
        Queen,
        King,
        Ace
    }

    public Rank rank { get; set; }
    public Suit suit { get; set; }

    public Card() { }
    public Card(Suit suit, Rank rank)
    {
        this.rank = rank;
        this.suit = suit;
    }
    public Card(int deckPosition)
    {
        rank = (Rank)((deckPosition % 13) + 2);
        suit = (Suit)(deckPosition / 13);
    }
    public override string ToString()
    {
        return $"{rank} of {suit}";
    }
}


C function delimiates strings using a single character array

Your function seems to do this:

Find the first occurrence of "delimiator" (delimiter?) in some string. For example find the first occurrence of :// in http://example.com.
If found, return the position where it was found
If not found, return the length of the input string

To find if a string is part of another string, you can use the strstr function.
This is equivalent to your code but simpler:

int delimiateString(const char *string, const char *delimiator) {
    char * found = strstr(string, delimiator);
    return found != NULL ? found - string : strlen(string);
}

For the record,
your original code can be simplified,
by eliminating an if around the inner for loop,
and rearranging the nested ifs at the deepest level:

for (buffer = string; *buffer != '\0'; buffer++) {
    for (x = 0; x < len; x++) {
        if (*(delimiator+x) != *(buffer+x)) {
            break;
        }
        if (x+1 == len) {
            return buffer - string;
        }
    }
}


RegExp selecting strings surrounded by brackets

Modify your regexp: {(\w*)} and then replace:

yield return Regex.Replace(element.Value, @"{*}*", "");

with

yield return element.Groups[1].Value;

ps: full code is avaialbe here


Save list over many csv files each with given number of lines

I don't know where outtext comes from, but this seems overly complicated. There's too much nesting, and there's not enough separation of concerns.

Let's back up. We want to (a) chunk our list into sizes of cutoff and (b) write each such chunk into a new file. For each chunk, we create a new file, and write all of the rows. Each of those problems is bite-size and manageable.

First, from How do you split a list into evenly sized chunks?:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

That gives us the first half of the problem:

for chunk in chunks(outtext, cutoff):
    # write chunk

Now for the second half, we just need an index. But rather than keeping our own counter, let's use enumerate(). Additionally, note that csvwriter has a writerows() method - so we don't need a loop for that.

Putting it all together:

for index, chunk in enumerate(chunks(outtext, cutoff)):
    output_file = '{}{}.{}'.format(output_file_tokens[0], index, output_file_tokens[1])
    with open(output_file, 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(chunk)

    print ">>> " + output_file + " successfully saved"

You don't need to del anything. That's going to be pretty slow too - everytime we delete a chunk we have to shift everything in memory. This way, we don't have to do that.


Simple file locking wrapper command in C

Besides reinventing the wheel the things I'm concerned about are:

the warn in attemptLock, because if either creating the lock file
fails, or if you can't get the lock (or the call was interrupted), I
would expect the wrapper to exit instead,
the return value of open, which might very well be negative, so just
check for that separately and give an error message for that,
the return value of flock, where you should handle EINTR in a loop
I believe?


Yes, you understood how MVC works, and you are doing it right. The helper functions such as redirect() are in the correct classes. A few comments on the code itself:

I'd recommend to add an exit; statement after sending headers in redirect(). It will be easier to understand the code, since you can now think of the redirect() as a return, which will help you avoid mistakes.
Don't store your password in plain text.
Symply use return $this->linhas == 1; at the end of your login function.
Your model class simply translates the PDO interface into Portuguese, this is not an interesting layer of abstraction in my book. :)
Declare the variables you use, eg. $this->stm or $this->conn.
You are probably going to want an easier way to make requests when you will have dozens of them, but right now it's OK.


Split a long integer into eight 4-bit values

There are only three issues I take with your code...

The caller of the splitter function has the possibility of trying to access a value outside of the returned array and could cause a memory access violation if they did so. For this reason alone, it would be better to go with the vector approach that @Jamal posted.
You should use the C++ style casting (e.g. static_cast<int>(number & 0XF)) instead of the C style casting (e.g. (int)(number & 0xF)).
You should use std::int32_t instead of long or std::uint32_t instead of unsigned long. long is not gauranteed to be 32 bits, especially on 64 bit platforms. I don't take as big of an issue with this as some do though because on most systems, it will be at least 32 bits.

Here is a solution that only returns one nybble at a time and throws an exception if the caller tries to access an invalid portion of the of number. Since your book hasn't talked about pointers or vectors yet, this might actually be the type of approach it is looking for (possibly minus the exception throwing if it hasn't talked about exceptions yet either). If you take away the exception throwing, the caller still cannot cause a memory access violation though. If they passed something lower than 0 or greater than 7 as the value of part they would just get a return value of 0.

#include <iostream>
#include <stdexcept>
#include <cstdint>

unsigned short get_nybble( std::uint32_t number, const unsigned short part )
{
    if( part > 7 )
        throw std::out_of_range("'part' must be a number between 0 and 7");
    return (number >> (4 * part)) & 0xF;
}

int main( int argc, char* argv[] )
{
    std::uint32_t number = 432214123;
    try {
        for( short i = 7; i >= 0; i-- )
            std::cout << get_nybble(number, i) << " ";
    } catch( std::exception& ex ) {
        std::cerr << "Error: " << ex.what() << std::endl;
    }
    return 0;
}

This may not be the best solution, but another approach I find interesting is an anonymous union combined with a bit field struct. This works with the GNU G++ compiler and should also work with Visual C++. Note that as I understand it this is potentially unsafe on non x86 systems due to the structure packing which I'd bet your book has not talked about yet either.

#include <iostream>
#include <cstdint>

#pragma pack(push, 1)
typedef union
{
    std::uint32_t value;
    struct
    {
        std::uint32_t part1: 4;
        std::uint32_t part2: 4;
        std::uint32_t part3: 4;
        std::uint32_t part4: 4;
        std::uint32_t part5: 4;
        std::uint32_t part6: 4;
        std::uint32_t part7: 4;
        std::uint32_t part8: 4;
    };
} nybbles;
#pragma pack(pop)

int main( int argc, char* argv[] )
{
    nybbles num;
    num.value = 432214123;
    std::cout << "Parts = "
        << num.part8 << ", "
        << num.part7 << ", "
        << num.part6 << ", "
        << num.part5 << ", "
        << num.part4 << ", "
        << num.part3 << ", "
        << num.part2 << ", "
        << num.part1 << std::endl;
    return 0;
}


Simple interface and class for holding text to be analyzed

Your concrete TwitterStatus class would, in a single-threaded application, be OK for the purpose of having a single-set ("lazy set", or "set and freeze") mechanism. Two concurrent threads each setting the value, or one thread setting, and another thread getting the value may cause problems though.

The situation can be relatively easily resolved with an AtomicReference value though...

Consider the following value that replaces both the calculatedMeanSentiment and calculated fields:

private final AtomicReference<Double> calculatedMeanSentiment = new AtomicReference<>(null);

Then, in your methods, you can have:

@Override
public double getCalculatedMeanSentiment() {
    Double val = calculatedMeanSentiment.get();
    if (val == null) {
        throw new IllegalStateException("Mean sentiment has not been calculated yet.");
    }
    return val;
}

@Override
public void setCalculatedMeanSentiment(double calculatedMeanSentiment) {
    if (!this.calculatedMeanSentiment.compareAndSet(null, calculatedMeanSentiment)) {
        throw new IllegalStateException("Mean sentiment has already been calculated.");
    }
}

@Override
public boolean isCalculated() {
    return calculatedMeanSentiment.get() != null;
}

Notice also that when you throw, or return from the 'if' part of an if statement, there is no need to have the 'else' part. Specifically, you have structures like this:

    if (isCalculated()) {
        return calculatedMeanSentiment;
    } else {
        throw new IllegalStateException("Mean sentiment has not been calculated yet.");
    }

that return in the if. They can be easily rewritten as 'guard conditions':

    if (!isCalculated()) {
        throw new IllegalStateException("Mean sentiment has not been calculated yet.");
    }
    return calculatedMeanSentiment;


Only call srand() once in an application:

    srand (time(NULL));

Should be just after main() starts.

This does not generate an evenly distributed the random numbers.

    n= rand();
    n = 1 + n % 6;

This is because rand() returns a number from [0,RAND_MAX) or [0,32767) which is not exactly divisible by 6. So you get:

    1:  1/5462        Notice this is one more than the others.
    2:  1/5461
    3:  1/5461
    4:  1/5461
    5:  1/5461
    6:  1/5461

Probably not an issue for a simple app but worth noting. The proper way to do this is:

int dieRoll() // 1-6 evenly distributed.
{
     static int const max = RAND_MAX/6*6;

     int r = rand();
     while(r >= max) { r = rand();}

     return r%6+1;
}

Probably best not to use goto:

xm:
if (ch=='r'){
system("cls");
call();  }
else
exit (0);
cout<<endl<<endl<<"Press r to roll again q to quit!";
ch = getch();
goto xm;

Prefer (a standard loop):

while (ch=='r') {
    system("cls");
    call();

    cout<<endl<<endl<<"Press r to roll again q to quit!";
    ch = getch();
}

Lets also compress your switch statement:

    switch (n) {
        case 1:   one();break;
        case 2:   two();break;
        case 3: three();break;
        case 4:  four();break;
        case 5:  five();break;
        case 6:   six();break;
        // We know the number will never be anything else
        // so don't need the default.
    }

Don't need to use so many std::endl.

    cout << " ----- \n"
         << "|O   O|\n"
         << "|     |\n"
         << "|O   O|\n"
         <<  " -----" << endl;

std::endl is used to flush the output. If you just want a new line use "\n".


You could try the following which utilizes XPath's XPathSelectElement extension method.

test.xml

<Root>
  <Foo>
      <FooBar>1</FooBar>
    <Bar>
      <FooBar>2</FooBar>
    </Bar>
  </Foo>
</Root>

C#

using System;
using System.Xml.Linq;
using System.Xml.XPath;

...

    static void Main(string[] args)
    {
        XDocument document = XDocument.Load(@"test.xml");
        XElement element = ElementAtPath(document.Root, "Foo/Bar/FooBar");

        Console.WriteLine(element); // Prints <FooBar>2</FooBar>
    }

    private static XElement ElementAtPath(XElement root, string path)
    {
        if (root == null)
        {
            throw new ArgumentNullException(nameof(root));
        }

        if (string.IsNullOrWhiteSpace(path))
        {
            throw new ArgumentException("Invalid path.");
        }

        return root.XPathSelectElement(path);
    }


Producer / Consumer implementation for Parallel Processing in the TPL

As a matter of being thread-safe, you should replace this:

    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        if (BatchAvailable != null)
            BatchAvailable(sender , e);
    }

with this:

    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        var batchAvailable = this.BatchAvailable;

        if (batchAvailable != null)
        {
            batchAvailable(sender, e);
        }
    }

Reason being, accessing the event field "raw", you may wind up with it going null between the if and the invocation itself.


function myMD5(string){

MD5 itself acts on bits or - for most runtimes - bytes. All string manipulation should take place outside any MD5 function.

/*unsigning also works cuts to 32bit words*/

That's not clear to me. Two verbs in a row...

string = unescape(encodeURIComponent(string));

Oh dear, that throws the principle of least surprise in the blender. Do not suddenly change the string without warning the user.

The you first copy the complete message to bytes, and then to words. This uses a lot of unnecessary memory. There is a reason why most implementations (well, outside of those of JavaScript) use multiple update method and a final digest method. It is to handle larger messages, or messages that are actually split over multiple locations.

for(var i = 1; i <= 64; i++)
    K.push(Math.floor(0x100000000 * Math.abs(Math.sin(i))));

This makes the code smaller, of course, but do you really want to perform that calculation for each MD5 invocation?

var A, B, C, D;

When using variable names that are specific to a specification, then please provide a link to the specification. Otherwise other devs are going to wonder about the special variable names (such as shif).

if(rnd < 16){

Branching is relatively slow on modern processors. This is why you see the unrolled loops that you've coiled up again. To get speed, you want to perform operations chunks by buffering a chunk at a time. Then you want to have the code run as fast as possible.

Fortunately you are using else if which makes it ever so slightly more performant. Over a few runs, the branching should become predictable and a good runtime should make it run faster.

You are returning the result as bytes, which is how it should be. Don't forget to test your code against the official test vectors, and add tests for your own edge cases or your MD5 may still result in a wrong value.

Your code looks fine if you just want to get a feel of what MD5 - a relatively simple crypto hash - looks like. It's good practice. But now you may want to proceed and see what it takes to make it efficient - and unroll your own code yourself.


Handle errors. In Go, foo, _ := something() is a big code smell.
Iterating on a string gives you a rune; don't convert it to a one-char string just to compare it to another one-char string. Compare it to another rune instead ('a' instead of "a").
Your functions isVowel and isConsonant are re-building the vowel/consonant map from scratch every time they're called! This is very inefficient: initialize both maps as package variables, and inline these two functions completely. You have two options to do so, I like the second one better because it's slightly more readable.

Option 1:

var (
    vowels = map[rune]bool{
        'a': true,
        'e': true,
        'i': true,
        'o': true,
        'u': true,
    }
    consonants = map[rune]bool{
        // …
    }
)

Option 2:

var (
    vowels = toSet('a', 'e', 'i', 'o', 'u')
    consonants = toSet(/* … */)
)
func toSet(chars ...rune) map[rune]bool {
    m := make(map[rune]bool, len(chars))
    for _, c := range chars {
        m[c] = true
    }
    return m
}

You then check if a rune r is a vowel by just calling vowels[r].
Your s = fmt.Sprintf("%c", x) statement looks a lot like printf debugging. Were you intending to keep it in your code?
countVowels and countConsonants can be inlined as well, and called on each char in the same loop like in Curtis' answer.
Replace foo += 1 by foo++.
I'd say you have needless blank lines in your code (I think each of your functions is simple enough not to have any), but that's a minor style thing.
Your code doesn't support non-ASCII encodings (and it probably should, UTF-8 is everywhere nowadays). It doesn't support uppercase letters, either =)


I assume you are aware of Chrome Canary, which I gather is able to use binary deltas? I don't think it's pure Chromium though.

Your code is pretty clean. You could be using argparse for parsing the command line, currently you are ignoring flags that don't match. You could wrap the exit call around main, like this: exit(main()), and use return / return 2 statements instead. You could replace "C:\\Program Files" with %PROGRAMFILES%, or pick up some defaults from the registry, but that's not necessary unless you plan for a larger audience. You could also reduce the window Chromium is unavailable by unzipping somewhere else, then moving the directories, then clearing the previous one (but I don't think you can make it atomic without something like symlinks or hardlinks).


Encrypting and decrypting strings using Caesar cipher

Docstrings:
If using (and only targeting) python 3.5 or later, you could remove the type hints from the docstring and include them as real type hints.
You could also extend the docstrings to contain a (doctest-conforming) example usage.

Algorithm:
Unicode is HARD. Python3 strings are unicode. The caesar cipher only works for letters that are in ascii range. Example:

>>> rotated_letter("Á", 13)
'L'
>>> rotated_letter("L", -13)
'Y'

So your test by isupper / islower is not enough. You could do 'a' <= letter <= 'z' for an ascii lowercase test.

Variable names:
Just a gut feeling: functions do stuff. So a good name for a function is an imperative: I'd use rotate_letter instead of rotated_letter.
Also, once you name the functions rotate_xxx, the concept of a key is not valid anymore (this belongs into functions like encrypt and decrypt). When speaking of rotation, I'd call the argument offset or something like that.

Memoization / Performance:
The letter encryption function does not do much, so memoization is probably not necessary.
You are concatenating strings for building the result. This is slow. If this slowness doesn't matter to you (because of your small-input use case), then memoization is overkill. If you want better performance, you would (in the general case) append your string parts onto a list, and join the list when the calculation is done. In this special case, I would even opt for a preallocated array, as the output size is known.

PS:
I learned something, too, i.e. that there is setdefault() for dicts. Thanks!


Your code seems to be working. Here are a few things to make it better.

Tuple unpacking

x = point[0]
y = point[1]

can be written :

x, y = point

Remove what is not required

You maintain a count variable but you already know the count : it is TIMES_TO_REPEAT.

Variable name

TIMES_TO_REPEAT does not seem to be such a good name. NB_POINTS would probably be better.

Removing the counting logic

Using iterators and sum, you can remove the logic to count points :

inside_count = sum(1 for i in range(NB_POINTS) if in_circle((random.randint(1,LENGTH),random.randint(1,LENGTH))))

Underscore for throwaway values

In your iteration, you don't really care about the value of i. It is quite a common thing to call it _ (more about this).

Move things to a function

It makes things easier to test

def compute_pi(nb_it):
    inside_count = sum(1 for _ in range(nb_it) if in_circle((random.randint(1,LENGTH),random.randint(1,LENGTH))))
    return (inside_count / nb_it) * 4

Add an if main guard

It is quite common to define functions/values/classes/whatever from your python file but to use them only behind an if main guard to make things easier to reuse via module imports for instance.

Oops

Currently, changing the value of LENGTH seems to be changing the result. This is probably wrong.

At this point, my code looks like :

import random

NB_POINTS = 10**5
LENGTH = 10**5
CENTER = [LENGTH/2,LENGTH/2]

def in_circle(point):
    x,y = point
    center_x, center_y = CENTER
    radius = LENGTH/2
    return (x - center_x)**2 + (y - center_y)**2 < radius**2

def compute_pi(nb_it):
    inside_count = sum(1 for _ in range(nb_it) if in_circle((random.randint(1,LENGTH),random.randint(1,LENGTH))))
    return (inside_count / nb_it) * 4

if __name__ == "__main__":
    print(compute_pi(NB_POINTS))

Using the right type and the right values

In order to solve the problem above and make things easier, you could change a bit the referential you are using.

Instead of using a circle of radius R (equal to length/2) and with center (R, R) and picking integer values in square [1, R] * [1, R] maybe you could consider a circle of radius R and with center 0 and pick floating values in [-R, +R]. Even better, you could focus on the corner of the circle by considering points in [0, R]*[0, R]. Finally, R is not really important here, you could pick 1.

Then the code becomes :

import random

NB_POINTS = 10**5

def in_circle(x, y):
    return x**2 + y**2 < 1

def compute_pi(nb_it):
    inside_count = sum(1 for _ in range(nb_it) if in_circle(random.random(),random.random()))
    return (inside_count / nb_it) * 4

if __name__ == "__main__":
    print(compute_pi(NB_POINTS))

And then, this can be simplified.

import random

NB_POINTS = 10**5

def compute_pi(nb_it):
    return 4 * sum(1 for _ in range(nb_it) if random.random()**2 + random.random()**2 < 1) / nb_it

if __name__ == "__main__":
    print(compute_pi(NB_POINTS))


How to enumerate the internal nodes and leaves of a tree more elegantly?

Here's a more efficient version that avoids copying list elements.  Instead, it creates just two empty lists and appends to them during the traversal.

def leaves_and_internals(self):
    """(BTNode) -> ([object], [object])
    Return a pair of lists: (list of all the items stored in the leaves of
    the subtree rooted at this node, list of all the items stored in the
    internal nodes of the subtree rooted at this node), according to a
    pre-order traversal.
    """
    def helper(self, leaves, internal):
        if self.left is None and self.right is None:
            leaves.append(self.item)
        else:
            internal.append(self.item)
            for child in [self.left, self.right]:
                if child is not None:
                    helper(child, leaves, internal)
        return (leaves, internal)
    return helper(self, [], [])