To be clear I think Adriano makes a very good point but still I wanted to provide some feedback:

I think you should separate piece of functionality in different classes.

You could abstract the handling of transactions and connections away in e.g

public class SqlHelper
{
    private readonly IDbConnectionFactory _dbConnectionFactory;

    private readonly IExecutionPolicy _executionPolicy;

    public SqlHelper(IDbConnectionFactory dbConnectionFactory, IExecutionPolicy executionPolicy)
    {
        if (dbConnectionFactory == null)
        {
            throw new ArgumentNullException(nameof(dbConnectionFactory));
        }
        if (executionPolicy == null)
        {
            throw new ArgumentNullException(nameof(executionPolicy));
        }
        _dbConnectionFactory = dbConnectionFactory;
        _executionPolicy = executionPolicy;
    }

    public TResult DoInTransaction<TResult>(Func<IDbTransaction, TResult> task,
        IsolationLevel isolation = IsolationLevel.Unspecified)
    {
        using (var conn = CreateConnection())
        {
            conn.Open();
            using (var transaction = conn.BeginTransaction(isolation))
            {
                try
                {
                    var result = task(transaction);
                    transaction.Commit();
                    return result;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}

this helper is now responsible for only handling connections and transactions and if, in the future, you find a new ORM which uses the IDbConnection like Dapper does, you can re-use it.

Next thing you could do is make use of the "repository pattern" in my opinion this should not be a generic interface with CRUD operations, but It could be that.

using Dapper;

public class DapperAccountTable : IAccountTable
{
    private readonly SqlHelper _sqlHelper;

    public DapperAccountTable(SqlHelper sqlHelper)
    {
        _sqlHelper = sqlHelper;
    }

    public AccountData FindAccountRecordByEmail(Username username)
    {
        if (username == null)
        {
            throw new ArgumentNullException(nameof(username));
        }
        return _sqlHelper.DoWithConnection((conn) =>
        {
            var account =
                conn.Query<AccountData>("SELECT * FROM Account WHERE Email = @Email AND Deleted = 0",
                    new {Email = username.ToUnicodeDbString()}).SingleOrDefault();
            if (account != null)
            {
                account.AdvisorId = QueryPartnerId(conn, account);
            }
            return account;
        });
    }

This repository is now the abstraction you are looking for. If you now want to move a way from dapper and use e.g. NHibernate you could create a new implementation of the IAccountTable interface and let this be injected instead of the DapperAccountTable.

Last but certainly not least is that this is only possible when using  Inversion of Control

I think that this is the maximum amount of abstractions that is possible in a DAL. Other ORM's like EF and NHibernate differ so much from Dapper that you always have to re-write your repositories.


The first thing I'd do if I were refactoring this code is get rid of recursion.

You should be able to do it with a variable to keep track of "best row number so far", and a simple "for each row" loop. Inside the loop would be code that compares the current row with the best row so far (and does "best row so far = current row" if the current row is better).

Example:

int maxRow(int a[4][4]) {
    int i,j;
    int bestRow = 0;

    for(i = 1; i < 4; i++) {
        for(j = 0; j < 4; j++) {
            if(a[i][j] !=  a[bestRow][j]) {
                if(a[i][j] > a[bestRow][j]) {
                    bestRow = i;
                }
                break;
            }
        }
    }
    return bestRow;
}


Variable naming

In general, you should follow PEP8, the Python style guide. In particular, it suggests using lowercase for variable names. That is, rows instead of Rows.

User input conditions

while (Rows > 10) or (Columns > 10) or (Rows <= 0) or (Columns <= 0):
    Rows = int(input("Please enter the number of rows you want. \n"))
    Columns = int(input("Please enter the number of columns you want. \n"))

So, if I enter a correct row, but a wrong column, it'll ask again. Without telling me what I did wrong.

I'd suggest

rows = 0
while not (0 < rows <= 10):
    rows = int(input("Please enter the number of rows you want [1-10]."))

And a similar loop for columns. This has one problem: What if the user does not enter a number but something else? 'Pizza' or 'one'. In that case, the int throws an exception, and that should be handled as well.

rows = 0
while not (0 < rows <= 10):
    try:
        rows = int(input("Please enter the number of rows you want [1-10]."))
    except ValueError:
        pass  # Just re-ask the question.

Mixing statements and definitions

The code as given has the form

define function
run some statements
define function
run some statements

In general, you should use

define function
define function
define function
define function main:
    statements
    statements
if __name__ == "__main__":
   main()

Re-using variables

Notice how in create_grid, the variable row has two purposes: It is both a number (due to the for row in range(Rows)), and a list. Please don't do that. Because the number row is unused, we should indicate that to the readers by using the conventional _ as variable name.

def create_grid(Rows, Columns):
    #Creates the 2D Data Grid
    grid = []
    for _ in range(Rows):
        row = []
        for _ in range(Columns):
            row.append(' ')
        grid.append(row)
    return grid

(Note: I myself prefer using a double underscore __ instead, but convention is _.)

Encapsulation

Not sure if you are at the level of classes yet, but I'd suggest learning about them.

Instead of

def create_grid(Rows, Columns):
    #Creates the 2D Data Grid
    grid = []
    for row in range(Rows):
        row = []
        for col in range(Columns):
            row.append(' ')
        grid.append(row)
    return grid

grid = create_grid(Rows,Columns)

You can write

class Grid(object):
    def __init__(self, columns, rows):
        self.columns = columns
        self.rows = rows
        self._grid = []
        for __ in range(rows):
            row = []
            for __ in range(columns):
                row.append(' ')
            self._grid.append(row)

Now, that last part (assigning self._grid) can be done 'nicer' (and faster!).

self._grid = [ [' ' for __ in range(columns)] for __ in range(rows)]

Useless call to .upper.

In display_grid, you've written

    column_names = 'abcdefghijklmnopqrstuvwxyz'[:Columns]
    print('  | ' + ' | '.join(column_names.upper()) + ' |')

Why not

    column_names = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:columns]
    print('  | ' + ' | '.join(column_names) + ' |')

That's a bit nicer, right?

Using enumerate

The builtin enumerate has a second argument: start. You can use it to signal counting should start at 1 instead:

    for number, row in enumerate(grid, 1):
       print(number, '| ' + ' | '.join(row) + ' |')

display_grid as a method on the class

If you follow my suggestion of turning the grid into a class, you can write

def display(self):
    """
    Displays a grid.
    """
    column_names = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:self.columns]
    print('  | ' + ' | '.join(column_names) + ' |')
    for number, row in enumerate(self._grid, 1):
       print(number, '| ' + ' | '.join(row) + ' |')

But that's just a suggestion.

grid = create_grid(Rows, Columns)
display_grid(grid, Columns)

Docstrings

In Python, it is the convention to add the documentation of a method/function in a docstring.

Instead of

def random_row(grid):
    #Makes a random row integer
    return random.randint(1,len(grid))

write

def random_row(grid):
    """
    Makes a random row integer
    """

(There are also a lot of conventions on how to phrase a docstring. I won't get into that for now.)

Parenthesis in conditional

The code says

while (turns != 5):

It could (and should) be

while turns != 5:

That is, you don't need the ( and ) there.

Weird order in the guess loop

Now, the following is just preference. But to me, the final loop is unclear. I've written it as pseudo-code below.

The final part looks like this (pseudocode)

while (turns != 5):
    get_guess
    if hit:
        turns += 1
        notify_success
        break
    else:
        if out_of_bounds:
            # Print out-of-bounds message
        elif already_guessed:
            # Print already guessed message
        else:
            # Update miss
if (turns >= 5):
    # Print 'you lost'

What I notice is that it first checks for hit, before checking if the input is valid (in bounds, and not already guessed).

I'd suggest cleaning it up as follows:

while turns != 5:
    while True:
        get_guess()
        if out_of_bounds:
            # Print out-of-bounds message
        elif already_guessed:
            # Print already guessed message
        else:
            break
    turns += 1
    if hit:
        # Update grit hit.
        # Print hit message.
        break
    else:
        # Update grid miss
        # Print miss message.
    display_grid()


@Ted Brownlow has answered your constructor question, but here's a few other points to consider going forward...
Consider your class interface
Your class needs to present an interface that is functional,usable and focused.  At the moment, your class is responsible for both implementing a LIFO and outputting them to the console.  These are really different concerns.  Consider if instead of writing to the console you wanted to write to a web page / different window.  Building the display logic straight into the class makes it less flexible.  A good exercise might be to remove the show method and decide what method(s) you would need to add to your class in order to allow it to be implemented from outside the class.
Bounds checking
At the moment your class has a fixed maximum size of 5.  However, other than by reading the class there's no way for the client to know (possibly missing a maxSize method or similar).  There's also no way for the client to know how many items are in the list, unless they keep track of it themselves (possibly missing a currentSize method or similar).
Without this size information, there's no way for the client to know if it's safe to call push or pop.  Consider what would happen if you already had 5 items when push was called.  What would happen if 0 items were present and pop was called?  At the moment, you're relying on the framework to handle these scenarios.  This can be ok, if it's a conscious decision, but you probably want to consider  adding some bounds checks and throwing exceptions that more explicitly help the user of your class know what they did wrong.


Whenever I see a module named "utility", it always spells danger. It will almost always suffer bloat because one is easily tempted to put everything that's uncategorized into it and will be forgotten. Consider splitting it off while still early. It appears one is a string formatter, the other a console helper. Split them by that instead, much more meaningful.

Also, function names and variables occupy the same namespace. Defining a variable and assigning a named function is overkill. I prefer a just a function declaration over a function expression due to debugability because the names will appear in the stack trace.

var removeLeadingZero = function removeLeadingZero (strNumber) {
    if (strNumber.charAt(0) === '0') {
        return strNumber.substr(1);
    }else{
        return strNumber;
    }
};

Consider trimming the string prior to checking if the leading character is 0. A leading space could throw this function off. Additionally, this can be shortened to:

function removeLeadingZero(string){
  return string.charAt(0) === '0' ? string.trim().substr(1)
                                  : string;
}

return ((endingPrice - startingPrice) / startingPrice) * 100;

Beware of JavaScript's precision when it comes to numbers. While this works for small applications or where precision isn't really important, it may throw you off when dealing with more complex calculations. You have been warned. 0.1 + 0.2 !== 0.3 in JS :D

var getUri = function getUri (stockObj) {

    return 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo'
        + '.finance.historicaldata%20where%20symbol%20%3D%20%22'
        + stockObj.ticker
        + '%22%20and%20startDate%20%3D%20%22'
        + stockObj.startDate
        + '%22%20and%20endDate%20%3D%20%22'
        + stockObj.endDate
        + '%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
};

Since you said you used jQuery, consider using $.param to build the query portion of your url. It will do the proper escaping for you.

getStockData doesn't look complete, but if you want to be functional and all that, the function must return something. $.getJSON returns a Promise-like object which you can listen to for resolution/rejection. You can also parse and return in a resolve handler to do additional logic before handing it off to the caller. You can use this to restructure the data, do additional computations etc.

var getStockData = function getStockData (stockObj) {

    return $.getJSON(getUri(stockObj)).then(function (priceData) {

        var startDate = utility.formatForConsole(stockObj.startDate);
        var endDate = utility.formatForConsole(stockObj.endDate);
        var pricesArray = priceData.query.results.quote;
        var startingPrice = pricesArray[pricesArray.length - 1].Adj_Close;
        var endingPrice = pricesArray[0].Adj_Close;
        var percentChange = utility.getPercentChange(startingPrice, endingPrice);

       // Return all the needed data
       return {
         startDate: startDate,
         endDate: endDate,
         startingPrice: startingPrice,
         endingPrice: endingPrice,
         percentChange: percentChange
       };

    });
};

// Usage
yahooFinance.getStockData(stock).then(function(results){
  console.log(results.startDate);
});

A good practice is to push off anything UI-related nearer to the caller instead of anywhere in the API (unless the API is for rendering). Most of the time, your API will be just sending/grabbing/computing data and it's good that way. It makes it easy to test with lesser things to stub/mock.

Additionally, it's usually the caller that's nearer the UI. This is more apparent in frameworks like Angular, where API consumers reside in the controller, the last level of JS before the templates. API gets called in the controller, therefore the results should also end up in the controller.


Can this date-validation function can be simplified further or is it the correct approach?

Can this be simplified ? Most certainly.

You can take advantage of the fact that new Date( 'APR 04 1977' ) and new Date( '04 04 1977' ) both work, so you don't need getMonthFromString
You can take more out of regexes with capturing groups
You can get rid of the whole Sandbox construct which does not make a lot of sense to me
You can write it so that the validator can accept but num:true and num:false, it can only make the user happier ;)
Not too excited by YY, we spent billions fixing Y2K, and here you come creating more trouble ;)
You don't need value if you have element ( simply call val() )
isValidDate seems overkill, if you ask for 30 feb 2014, then testDate.getTime() will be NaN

My counter proposal code is about 1/3rd of yours:

function DateHandler(elementId, _mandatory) {
    this.$dateField = $('#' + elementId);
    this.mandatory = _mandatory || false;
    this.$dateField.on('keyup focusout', this.validate.bind(this));
}

DateHandler.prototype.validate = function () {
    this.error('');
    var text = this.$dateField.val().toUpperCase(), matches;
    if (text.length === 0) {
        if (mandatory) {
            this.error('Field should not be empty');
        }
        return;
    } else if (text.length == 6) {
        matches = /([0-3][0-9])([0-1][0-9])(\d\d)/.exec(text);
    } else if (text.length == 7) {
        matches = /([0-3][0-9])(\w\w\w)(\d\d)/.exec(text);
    }
    if (!matches) {
        return this.error('Field should be of format DDMMYY or DDMMMYY');
    }
    value = new Date(matches[2] + ' ' + matches[1] + " " + (matches[3] < 50 ? 20 : 19) + matches[3]);
    if (isNaN(value.getTime())) {
        return this.error('Not a valid date');
    }
    console.log(value);
};

DateHandler.prototype.error = function (message) {
    var label = this.$dateField.siblings('span');
    message ? label.html(message).show() : label.hide();
};

var dateHandler1 = new DateHandler('d1');
var dateHandler2 = new DateHandler('d2');

I tested this fairly well on JsFiddle: http://jsfiddle.net/konijn_gmail_com/985ut/


Find and delete an item from a singly linked list in Python

A few general things:

Use """Doc strings.""" for documentation not # comments
Put a space after each comma
Prefer less indentation. For example, if you have an if blah: return None, then you don't need an else after it, because if the function didn't return then blah must've been false
PEP8 prefers snake_case for methods and variables. setHead should be set_head, although I'm a bit dubious that you should be exposing this to the user. The head should be a private implementation detail. You should expose methods to allow the user to modify the list instead.
Additionally, for parity with builtin collection types, I'd take an optional iterable as the first argument to your constructor. If provided, you populate your collection with the values from it.
I prefer value to data again for parity with python builtins

A warning about equality:

You use cur == self.head. Depending on how equality is implemented for your nodes this may or may not work. In this situation, I think you are lucky to avoid this edge case due to delete removing the first thing, but in general this is dangerous. To test if two things are the exact same object use is. Use == for equality. (1, 2) == (1, 2) but (1, 2) is not (1, 2).

Specifically relating to delete:

I'd rename it to remove for parity with the method on the builtin list
I'd have it raise a ValueError when the value isn't in the list (again for parity with the method on the builtin list)
Despite what @vnp suggests, I wouldn't return the value deleted again for parity with remove on the builtin list. It doesn't really make much sense to return the value since you know it already (you passed it into the method). This is what list.remove does.
Since many operations on the linked list require finding a node with a given value and the previous node (ex. in, find, insert_before), I'd extract find value or raise ValueError into a helper. This will cut down on the complexity of your delete operation (you now just have to stitch the hole in the list)
You have some duplicated logic for setting self.head/prev.next. No matter whether cur.next is None or not you set self.head/prev.next to cur.next. But, I'd solve this another way:
One trick commonly employed to make the linked lists a bit less unwieldy is always having an empty node at the head (with no data). This means that you never have to special case patching the head pointer.

Combining this all:

class Node:
    """Node in SinglyLinkedList."""
    def __init__(self, value, next):
        self.value = value
        self.next = next

class SinglyLinkedList:
    def __init__(self, iterable=None):
        """New list initialized from optional iterable's items."""
        self._head = Node(None, None)

        # Not implemented here, but like list.append,
        # should take ...args and append each. In this
        # way you can do O(n) appends instead of O(n^2)
        self.append(iterable)

    def remove(self, value):
        """Removes value from the list or raises ValueError."""
        previous_node, matched_node = self._find_value(value)
        previous_node.next = matched_node.next

    def _find_value(self, value):
        previous, current = self._head, self._head.next

        while current is not None:
            if current.value == value:
                return previous, current

            previous, current = current, current.next

        raise ValueError(f'value not in list')


I'm reading the 2nd requirement:

  Accepts two single digit numbers† with a "+" or "-" in between them as input

in conjunction with the "12+23" test case. It's a very nice test case, but the double digit numbers are clearly beyond what the spec described. Behavior is unspecified in this case, though your program behaves very sensibly.

In runProgram(), the + and - cases are very similar. Can you break out a helper method that takes + / - as a parameter?

I recommend phrasing the last portion of the function in this way:

else:
    try:
        return 'PUSH ' + int(program)
    except ValueError:
        return 'FAIL'

The in program aproach seems fragile, especially if you have to handle programs like 5 + -3. You might want to tokenize early on, and pass in a list like [5, '+', -3]. Or perhaps define functions like add & subtract, and pass in [5, add, -3].


CoffeeScript is, in the end, just JavaScript with a nicer syntax. So the string-interpreted-as-number behavior is expected and normal. You write:

  This behavior appears wrong to me since a String cannot be multiplied by a Number.

Yet, due to type coercion in JavaScript, a string can be multiplied by a number just fine. And, importantly, the result is correct!

Your options with regard to strict type-checking are:

Using typeof and throwing an exception (or handling it some other way), as you do now.
Doing nothing.

You're still writing JavaScript, so option #2 is a valid solution to most type concerns. For instance, most (all?) the functions in the Math object accept numerical strings just as well as numbers.

For other types, the GIGO principle usually applies: Garbage In, Garbage Out. I.e. if the user of your code passes something completely incompatible, like an object, they'll get NaN back. And that's their problem, really. Same as if you do Math.floor({}) or something.

However, if type-checking is absolutely necessary, you can at least slim your code down a bit:

foo = (x) ->
  throw new TypeError unless typeof x is 'number'
  x * 3

Note that the code throws a TypeError, which is more appropriate for this situation, and that, since it throws, execution of the function is halted just as effectively as writing return. So there's no need for if...else branches.

You can generalize it a bit with a function, if you need to do this more often:

assertNumber = (value) ->
  unless typeof value is 'number'
    throw new TypeError("Expected a Number")

Or, better yet, check whether the value is numeric:

assertNumeric = (value) ->
  if isNaN Number(value)
    throw new TypeError("Expected a numeric value")

And use it like so:

foo = (x) ->
  assertNumeric x
  x * 3


I do not do C# but I can offer another way of approaching the problem:

As our range of numbers is \$[100\cdot100, 999\cdot999] = [10000, 998001]\$, assume a palindromic number on the form \$abccba\$.

The largest \$abccba < 998001\$ is \$k = abccba = 997799\$. We need to determine if \$k\$ can be written as the product of two 3-digit numbers. Using a prime table (or generate one with a sieve at program start) see if any prime number \$p\$ where \$\min\left(\frac{k}{100}, 999\right) \lt p\le k\$ evenly divides \$k\$.

If you can find such a prime then we know that \$\frac{k}{p} \lt 100 \$  and any remaining factors are too small or that \$p \gt 999\$ and we have a factor that is too large. So we can discard \$k\$ and decrement \$c\$ by one to form the next smaller palindrome, eg. \$k=996699\$, and keep trying smaller palindromes.

If you reach \$p\lt \min\left(\frac{k}{100}, 999\right) \$ without finding any prime that evenly divides \$k\$ we need to convince ourselves that the remaining factors can be multiplied into two factors so that both factors are three digits.

There are a few ways to convince ourselves of the above. One way is trial division by simply trying all divisors \$d\$ such that \$100\le d \le \max\left(\frac{k}{100}, 999\right)\$ and checking what the other factor is.

Another more elegant way is to use the fact that we know that there is no prime factor larger than \$p\le\min\left(\frac{k}{100}, 999\right)\$ and find the largest prime factor \$p_{max}\le\min\left(\frac{k}{100}, 999\right)\$ and let \$r_i = \frac{k}{p_{max}}\$.

Let the prime factors of \$r_i\$ be \$p_i\$ and let \$Q=\prod_{\forall i:p_i>\frac{999}{p_{max}}}p_i\$. At this point you have the largest prime factor of \$k\$ as \$p_{max}\$ and all prime factors of \$r_i=\frac{k}{p_{max}}\$ that are too big to be together with \$p_{max}\$ multiplied together as \$Q\$.

Now, factor \$\frac{r_i}{Q}\$ into primes \$P_k\$. Each of the \$P_k\$ primes has to be multiplied into either \$Q\$ or \$p_{max}\$. Iteratively try all combinations (and exit early for impossible branches) until you find one that is satisfactory or retry next smallest palindrome if no combination was found.

Note: This may well be slower than trial multiplication but it's another way to approach the problem and it may give birth to other ideas.


Choosing between Long/Integer and Float/Decimal

I'd let the user choose.
Not because that's the best way, but because I don't see any other way.

Number itself is not reflective on the presence of decimal digits.
It would need an interface Integer and interface Decimal or something like that in order to deal with this in a single signature.
However, the API is not designed this way.

So, if both is needed, I'd have a sumInt and a sumFloat method, or maybe sumInteger and sumDecimal. (I prefer Float over Decimal because Decimal is simply wrong because it means 1/10ths and that's just the wrong name. BigDecimal is the wrong name.)

Simpler usage of Generics

The type parameter U is redundant. You could directly go for this signature:

public static <T extends Number> BigDecimal sum(Collection<T> numbers)

And given that inside you actually don't need T, Number is sufficient, you could go for this signature:

public static BigDecimal sum(Collection<? extends Number> numbers)

Going via String is a bit "far away" from numbers, and unnecessary. You could use Number.longValue() in case of BigInteger and Number.doubleValue() in case of BigDecimal.

Then the code would look like this:

public static BigInteger sumInt(final Collection<? extends Number> numbers) {
    BigInteger sum = BigInteger.ZERO;
    for (final Number number : numbers)
        sum = sum.add(new BigInteger(number.longValue());
    return sum;
}

public static BigDecimal sumFloat(final Collection<? extends Number> numbers) {
    BigDecimal sum = BigDecimal.ZERO;
    for (final Number number : numbers)
        sum = sum.add(new BigDecimal(number.doubleValue());
    return sum;
}

How it looks like with Java 8 Streams

With Java 8 Streams, the code could look like this:

public static BigDecimal sumFloat(final Collection<? extends Number>  numbers) {
    return numbers
            .parallelStream()
            .mapToDouble(Number::doubleValue)
            .mapToObj(BigDecimal::new)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
}

LSP Violation

However, all these implementations violate the LSP - Liskov Substitution Principle. They will not work correctly for all potential Number types. If the Collection numbers contains BigDecimal or BigInteger objects which exceed the range expressible in double or long, the functions would fail to produce the correct result.

Given the signature, which suggests that any Number would do, and given the fact that class BigInteger extends Number and class BigDecimal extends Number, and given the fact that the signature uses BigInteger resp. BigDecimal as a return value, that would be a pretty unexpected behavior.

The following helper function can fix that problem for the known classes BigDecimal and BigInteger:

public static BigInteger toBigInteger(final Number number) {
    return
        Number instanceof BigInteger ? (BigInteger) number :
        Number instanceof BigDecimal ? ((BigDecimal) number).toBigInteger() :
        new BigInteger(number.longValue());
}

However, if someone creates another subclass of Number which exceeds the range of long, there still would be a problem. This problem could only be solved by fixing the API: class Number should have toBigInteger() and toBigDecimal() methods, which in Number, could be implemented with corresponding defaults. Because the root cause for the LSP violation is not in your code, not in my code, but in the API - in the way how class Number actually is defined.

Using the helper function, the code could look like this:

public class Numbers {

    public static BigInteger sumInt(final Collection<? extends Number> numbers) {
        BigInteger sum = BigInteger.ZERO;
        for (final Number number : numbers)
            sum = sum.add(toBigInteger(number);
        return sum;
    }

    public static BigDecimal sumFloat(final Collection<? extends Number>  numbers) {
        return numbers
                .parallelStream()
                .map(Numbers::toBigDecimal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public static BigInteger toBigInteger(final Number number) {
        return
            Number instanceof BigInteger ? (BigInteger) number :
            Number instanceof BigDecimal ? ((BigDecimal) number).toBigInteger() :
            new BigInteger(number.longValue());
    }
    // ...
}


"Sherlock and the Beast" challenge in Java

As Robert pointed out, your code spends a lot of time in getdecentString. A faster way to generate Strings would be to use the StringBuilder class, e.g.:

StringBuilder decentString = new StringBuilder();
...
for ( int j = 1; j <= x; j++ )
{
    decentString.append( "5" );
}
...
return decentString.toString();


1. Comments on your code

You have no guard on the call to main(). This makes it harder to debug the program using the interactive interpreter: as soon as the module is imported, it call main() and starts running. Better to put a guard in place:

if __name__ == '__main__':
    main()

This program consists of persistent state (the board) together with a set of operations on that state. It is therefore crying out to be implemented in the form of a class. See section 3 for how you might do this.
It's horribly tedious to watch the progress of the cellular automaton coming out on the terminal. This is the kind of program that really requires the use of a graphics toolkit like PyGame to draw and animate it. See section 4 for how you might do this.
It's almost never necessary to compare values explicitly against True or False. Instead of:

if cell == True:

you can write:

if cell:

and instead of:

if board[row][cell] == False:

you can write:

if not board[row][cell]:

Giant blocks of values like this are hard to input and hard to check.

board = [[False, False, False, False, False, False, False, False, False],
         [False, False, False, True , False, False, False, False, False],
         [False, True , False, True , False, False, False, False, False],
         [False, False, True , True , False, False, False, False, False],
         [False, False, False, False, False, False, False, False, False],
         [False, False, False, False, False, False, False, False, False],
         [False, False, False, False, False, False, False, False, False],
         [False, False, False, False, False, False, False, False, False],
         [False, False, False, False, False, False, False, False, False]]

It would be better to draw a "picture" and write a bit of code to decode it into the values you want:

glider = '''..o
            o.o
            .oo'''

See the paste method in section 3 below for how to decode this kind of picture.

2. Suggestions

When you have a program like this that operates on a two-dimensional array of cells, it often simplifies matters if you represent the two-dimensional array as a one-dimensional list. Then a cell can be represented by a single number instead of a pair; lookups are of the form array[cell] instead of array[x][y], and adjacent cells may be found by simple arithmetic operations.
It's a feature of the game of Life that, most of the time, very few cells are changing. You can take advantage of this fact to speed up the update operation. Instead of examining all cells to see if they need updating, maintain a set of cells that need to be looked at. Whenever you change a cell from live to dead or vice versa, add it, and all its neighbours, to the set. In the update operation, look only at those cells that were added to the set in the course of the previous update operation.

This means that you don't have to copy out the whole world each update: you only need a copy of the information (liveness and neighbour count) relating to the cells in the set.
Similarly, rather than count the number of live neighbours each time you update a cell, you could maintain an array containing these neighbour counts and update the array whenever a cell changes.

3. Revised code

from itertools import product

class Life(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        cells = (width + 2) * (height + 2)
        self.live = [False] * cells
        self.in_bounds = [True] * cells
        self.neighbours = [0] * cells
        for i in range(width + 2):
            self.in_bounds[i] = self.in_bounds[-i] = False
        for j in range(height):
            k = (j + 1) * (width + 2)
            self.in_bounds[k - 1] = self.in_bounds[k] = False
        self.neighbourhood = [y * (width + 2) + x
                              for x, y in product((-1, 0, 1), repeat=2)
                              if x or y]
        self.needs_update = set()

    def cell(self, x, y):
        """Return the cell number corresponding to the coordinates (x, y)."""
        return (self.width + 2) * (y + 1) + x + 1

    def set(self, p, value):
        """Set cell number 'p' to 'value' (True=live, False=dead)."""
        if value != self.live[p] and self.in_bounds[p]:
            self.live[p] = value
            self.needs_update.add(p)
            adjust = 1 if value else -1
            for n in self.neighbourhood:
                n += p
                if self.in_bounds[n]:
                    self.neighbours[n] += adjust
                    self.needs_update.add(n)

    def update(self, steps=1):
        """Update the world by 'steps' generations (default: 1)."""
        for _ in range(steps):
            u = [(p, self.live[p], self.neighbours[p]) for p in self.needs_update]
            self.needs_update = set()
            for p, live, neighbours in u:
                if live and not 2 <= neighbours <= 3:
                    self.set(p, False)
                elif not live and neighbours == 3:
                    self.set(p, True)

    def paste(self, s, x, y):
        """Decode 's' as a life pattern (o = live, any other character = dead)
        and paste it with top left corner at (x, y).

        """
        for j, line in enumerate(s.strip().splitlines()):
            for i, char in enumerate(line.strip()):
                self.set(self.cell(x + i, y + j), char == 'o')

Note:

It would be possible to combine the live, in_bounds and neighbours arrays into one, perhaps using bit twiddling to combine the values (the neighbour count fits into 4 bits and the other two arrays are one bit each). I've left it as three separate arrays for simplicity here.

4. Animation

Here's a quick implementation in Pygame:

import pygame
from pygame.constants import KEYUP, MOUSEBUTTONDOWN, MOUSEMOTION, QUIT, \
                             K_p, K_q, K_s, K_ESCAPE, K_SPACE

class PygameLife(Life):
    def __init__(self, width, height,
                 background=pygame.Color(240, 240, 255),
                 foreground=pygame.Color('black'),
                 cell_size=4):
        super(PygameLife, self).__init__(width, height)
        self.background = background
        self.foreground = foreground
        self.cell_size = cell_size

    def draw(self):
        screen = pygame.display.get_surface()
        screen.fill(self.background)
        c = self.cell_size
        for x in range(self.width):
            for y in range(self.height):
                if self.live[self.cell(x, y)]:
                    screen.fill(self.foreground, pygame.Rect(x * c, y * c, c, c))
        pygame.display.flip()

    def screen_cell(self, pos):
        """Return the cell number corresponding to screen position 'pos', or
        None if the position is out of bounds.

        """
        x, y = pos
        x //= self.cell_size
        y //= self.cell_size
        if 0 <= x < self.width and 0 <= y < self.height:
            return self.cell(x, y)
        return None

    def run(self):
        pygame.init()
        pygame.display.set_mode((self.width * self.cell_size,
                                 self.height * self.cell_size))
        paused = False
        drawing = False
        running = True
        while running:
            for event in pygame.event.get():
                t = event.type
                if t == QUIT or t == KEYUP and event.key in (K_q, K_ESCAPE):
                    running = False
                elif t == KEYUP and event.key in (K_p, K_SPACE):
                    paused = not paused
                elif t == KEYUP and event.key in (K_s,):
                    self.update()
                elif t == MOUSEBUTTONDOWN and event.button == 1:
                    paused = True
                    p = self.screen_cell(event.pos)
                    drawing = not self.live[p]
                    self.set(p, drawing)
                elif t == MOUSEMOTION and event.buttons[0]:
                    paused = True
                    self.set(self.screen_cell(event.pos), drawing)
            if paused:
                pygame.display.set_caption('Paused (press SPACE to run)')
            else:
                pygame.display.set_caption('Life')
                self.update()
            self.draw()
        pygame.quit()

And here's Bill Gosper's glider gun in action:

>>> glider_gun = '''
........................o...........
......................o.o...........
............oo......oo............oo
...........o...o....oo............oo
oo........o.....o...oo..............
oo........o...o.oo....o.o...........
..........o.....o.......o...........
...........o...o....................
............oo......................'''
>>> p = PygameLife(100, 60)
>>> p.paste(glider_gun, 8, 1)
>>> p.run()

5. Advanced topic

Typical Life patterns contain many repeated objects. For example, the output of a glider gun contains many gliders, all of which behave identically. It would be nice to be able to exploit this repetition so that the evolution of a glider (or any other repeated pattern) could be computed just once, with the result appearing at all the necessary places in the world.

Making this idea precise and turning it into an algorithm leads to Bill Gosper's Hashlife.


I suggest you rename link to next which is a more conventional name for the next linked list node.

struct node {
    int data;
    struct node* link;
};

Currently, you have to write the type of the node as struct node. However, if you do:

typedef struct node {
    int data;
    struct node* link;
} node;

You can allocate a new node simply by writing node my_node;
No, no, no and no. Don't you ever use global variables. As the code base grows, if something goes wrong because of a global variable, debugging will be hell.

struct node *pointerToLinkedList = NULL;

You should not cast the result of malloc:

struct node *newNode = (struct node*) malloc(sizeof(struct node));

What comes to struct node *newNode = (struct node*) malloc(sizeof(struct node)), I suggest you write instead:

malloc(sizeof *newNode)

That way, if you change the type of *newNode to, say, some_funky_struct, you don't have to rewrite malloc(sizeof(struct node)) to malloc(sizeof(struct some_funky_struct)).
There is no pointer to the tail of your list. You define one (called, say, list_tail), you can insertNodeEnd in constant time.
I suggest you rename it to list_head, since that is a conventional name for the first node of a linked list.

struct node *pointerToLinkedList = NULL;

Normally, what you would do when implementing a singly-linked list is creating a following:

typedef struct linked_list_node_t {
    void* datum;
    struct linked_list_node_t* next;
} linked_list_node;

typedef struct linked_list_t {
    linked_list_node_t* head;
    linked_list_node_t* tail;
    size_t size;
} linked_list_t;

linked_list_t* linked_list_t_alloc() {
    linked_list_t* list = malloc(sizeof *list);

    if (!list) {
        abort();
    }

    list->head = NULL;
    list->tail = NULL;
    list->size = 0;
    return list;
}

linked_list_t_operation(linked_list_t* list, ... operands) {
    ... Your implementation.
}

Alternative implementation

You could do:

singly_linked_list.h

#ifndef SINGLY_LINKED_LIST_H
#define SINGLY_LINKED_LIST_H

#include <stdlib.h>

typedef struct singly_linked_list_node_t {
    int datum;
    struct singly_linked_list_node_t* next;
} singly_linked_list_node_t;

typedef struct singly_linked_list_t {
    singly_linked_list_node_t* head;
    singly_linked_list_node_t* tail;
    size_t size;
} singly_linked_list_t;

typedef struct singly_linked_list_iterator_t {
    singly_linked_list_node_t* next_node;
} singly_linked_list_iterator_t;

/******************************************
* Allocates and returns a new empty list. *
******************************************/
singly_linked_list_t* singly_linked_list_alloc();

/**********************
* Initializes a list. *
**********************/
int singly_linked_list_init(singly_linked_list_t* list);

/*************************
* Frees the entire list. *
*************************/
void singly_linked_list_free(singly_linked_list_t* list);

/***************************
* Clears the list content. *
***************************/
void singly_linked_list_clear(singly_linked_list_t* list);

/**********************************************
* Pushes a new datum to the head of the list. *
**********************************************/
int singly_linked_list_push_front(singly_linked_list_t* list, int datum);

/**********************************************
* Pushes a new datum to the tail of the list. *
**********************************************/
int singly_linked_list_push_back(singly_linked_list_t* list, int datum);

/*****************************
* Pops the head of the list. *
*****************************/
int singly_linked_list_pop_front(singly_linked_list_t* list);

/*****************************
* Pops the tail of the list. *
*****************************/
int singly_linked_list_pop_back(singly_linked_list_t* list);

/**********************************************
* Returns the number of elements in the list. *
**********************************************/
size_t singly_linked_list_size(singly_linked_list_t* list);

/**************************************
* Returns the iterator over the list. *
**************************************/
singly_linked_list_iterator_t*
singly_linked_list_get_iterator(singly_linked_list_t* list);

/******************************************************************
* Returns non-zero value if the iterator has something to remove. *
******************************************************************/
int singly_linked_list_iterator_has_next(singly_linked_list_iterator_t* iterator);

/**************************
* Returns the next datum. *
**************************/
int singly_linked_list_iterator_next(singly_linked_list_iterator_t* iterator);

#endif /* SINGLY_LINKED_LIST_H */

singly_linked_list.c

#include "singly_linked_list.h"
#include <stdlib.h>

singly_linked_list_t* singly_linked_list_alloc()
{
    return calloc(1, sizeof(singly_linked_list_t));
}

int singly_linked_list_init(singly_linked_list_t* list)
{
    if (!list)
    {
        return 0;
    }

    list->head = NULL;
    list->tail = NULL;
    list->size = 0;
    return 1;
}

void singly_linked_list_free(singly_linked_list_t* list)
{
    if (list)
    {
        singly_linked_list_clear(list);
        free(list);
    }
}

void singly_linked_list_clear(singly_linked_list_t* list)
{
    singly_linked_list_node_t* current_node;
    singly_linked_list_node_t* next_node;

    if (!list)
    {
        return;
    }

    current_node = list->head;

    while (current_node)
    {
        next_node = current_node->next;
        free(current_node);
        current_node = next_node;
    }

    list->head = NULL;
    list->tail = NULL;
    list->size = 0;
}

int singly_linked_list_push_front(singly_linked_list_t* list, int datum)
{
    singly_linked_list_node_t* new_node;

    if (!list)
    {
        return 0;
    }

    new_node = malloc(sizeof *new_node);

    if (!new_node)
    {
        return 0;
    }

    new_node->datum = datum;

    if (list->size == 0)
    {
        list->head = new_node;
        list->tail = new_node;
    }
    else
    {
        new_node->next = list->head;
        list->head = new_node;
    }

    list->size++;
    return 1;
}

int singly_linked_list_push_back(singly_linked_list_t* list, int datum)
{
    singly_linked_list_node_t* new_node;

    if (!list)
    {
        return 0;
    }

    new_node = malloc(sizeof *new_node);

    if (!new_node)
    {
        return 0;
    }

    new_node->datum = datum;

    if (list->size == 0)
    {
        list->head = new_node;
        list->tail = new_node;
    }
    else
    {
        list->tail->next = new_node;
        list->tail = new_node;
    }

    list->size++;
    return 1;
}

int singly_linked_list_pop_front(singly_linked_list_t* list)
{
    int result;
    singly_linked_list_node_t* node;

    if (!list)
    {
        abort();
    }

    if (list->size == 0)
    {
        abort();
    }

    result = list->head->datum;
    node = list->head;
    list->head = list->head->next;
    list->size--;

    if (!list->head)
    {
        list->tail = NULL;
    }

    free(node);
    return result;
}

int singly_linked_list_pop_back(singly_linked_list_t* list)
{
    int result;
    singly_linked_list_node_t* current_node;
    singly_linked_list_node_t* previous_node;

    if (!list)
    {
        abort();
    }

    if (list->size == 0)
    {
        abort();
    }

    current_node = list->head;
    previous_node = NULL;

    while (current_node->next)
    {
        previous_node = current_node;
        current_node = current_node->next;
    }

    result = current_node->datum;

    if (!previous_node)
    {
        list->head = NULL;
        list->tail = NULL;
    }
    else
    {
        previous_node->next = NULL;
        list->tail = previous_node;
    }

    list->size--;
    free(current_node);
    return result;
}

size_t singly_linked_list_size(singly_linked_list_t* list)
{
    if (!list)
    {
        abort();
    }

    return list->size;
}

singly_linked_list_iterator_t*
singly_linked_list_get_iterator(singly_linked_list_t* list)
{
    singly_linked_list_iterator_t* iterator;

    if (!list)
    {
        return NULL;
    }

    iterator = malloc(sizeof *iterator);

    if (!iterator)
    {
        return NULL;
    }

    iterator->next_node = list->head;
    return iterator;
}

int singly_linked_list_iterator_has_next(singly_linked_list_iterator_t* iterator)
{
    if (!iterator)
    {
        abort();
    }

    return iterator->next_node != NULL;
}

int singly_linked_list_iterator_next(singly_linked_list_iterator_t* iterator)
{
    int result;

    if (!iterator)
    {
        abort();
    }

    if (!singly_linked_list_iterator_has_next(iterator))
    {
        abort();
    }

    result = iterator->next_node->datum;
    iterator->next_node = iterator->next_node->next;
    return result;
}

(Demo driver is here.)
A weakness of a singly-linked list is that we have to scan the entire list whenever popping the back in order to find the second last node. I suggest you use a doubly-linked list after all since it allows popping the back of the list in \$\Theta(1)\$.


Extracting emails from a file and writing them to another file

Working with file handles

You should always close the file handles that you open.
You didn't close any of them.
In addition,
you should use with open(...) as ... syntax when working with files,
so that they will be automatically closed when leaving the scope.

Checking if a list is empty

There is a much simpler way to check if a list is empty, instead of this:

if(len(match_list)>0):

The Pythonic way to write is simply this:

if match_list:

Unnecessary initializations and data storage

There's no need to initialize match_list before the loops.
You reassign it anyway inside.

You don't need to store all the lines from the first file into a list.
You can process the input line by line and write output line by line.
That can save a lot of memory, as you only need to keep one line in memory at a time,
not the entire input file.

Poor naming

The file handles are very poorly named.
handleone and handletwo don't convey that one is for input the other is for output.

ArrayItem doesn't follow the recommended naming convention of snake_case (see PEP8),
and it doesn't describe what it really is.

But f1 wins the trophy of worst name in the posted code.
lines would have been better.

Minor optimization

Instead of re-evaluating regular expressions in every loop,
I use re.compile to compile them first, to make all uses efficient.
However, this might not be necessary,
as it seems recent versions of Python have a caching mechanism.

Suggested implementation

With the above suggestions applied, the code becomes simpler and cleaner:

import re

re_pattern = re.compile(r'[\w\.-]+@[\w\.-]+')

with open("input.txt") as fh_in:
    with open("mailout.txt", "a+") as fh_out:
        for line in fh_in:
            match_list = re_pattern.findall(line)
            if match_list:
                fh_out.write(match_list[0]+"\r\n")


Some of the code seems to be missing - I can't see where you assign @numbers. I'm going to assume that it is set to "//+\n1+2" or the like.

DRY - twice in your code you calculate the delimiter (@numbers[2,1]), either pass it as an argument, or make it a method.

Btw, you seem to have a syntax error there, you might have meant to say supports? ? @numbers... instead.

Be clear, not clever you show good control in ranges, array, chars, etc., but still the following will be much clearer to future readers of your code (you included!)

ValidDelimiters = "!\"\\#$%&'()*+,-.:;<=>?@"

(if you don't like to see escaped sequences, you can use %{!"\#$%&'()*+,-.:;<=>?@} instead)

Be Ruby - when you need to return a boolean, which is returned on a condition, there is no need to explicitly say .. ? true : false, simply return the condition result

Harness the power of regular expressions - when matching strings, captures are set to $n variables - you can use this to check your delimiter more elegantly:

ValidDelimiters = "!\"\\#$%&'()*+,-.:;<=>?@"

def supports?(delim)
   ValidDelimiters.include? delim
end

def delimiter
  return ',' unless @numbers.match(%r{^//(.)})
  delim = $1
  supports?(delim) ? delim  : fail('Unsupported delimiter')
end

Edit - with the new code

Naming - choose names that convey the meaning of the member - @numbers implicitly say it is a group of numbers, although it is actually a string... better name might be input_expression or something like that.

Redundant code with side-effects - your constructor accepts a string as input, which you assign to @numbers. This is not part of the requirements, and you probably don't have tests for that, but it may have serious impact on your result!

Also, for each time you call add, the input is concatenated to the end of the previous result (also not part of the requirements), which will break your code.

Assume nothing - Ruby's to_i method is very liberal - anything that is not a number will be parsed to - 0, so an input like "1,2,goat,3" will give a valid result of 6...

When state is redundant - when assuming each add is supposed to be a separate calculation - no state is needed. You can simply pass the expression around to your helper methods, and return the result. You can even turn your class into a module, with all methods being class methods, and the usage will be `StringCalculator.add('//+\n1+2')


How would you deal with this, through a percentage output?

I don't know a better way. It seems fine the way you did it, using a spinner.

Quoting

The quoting is unnecessary here:

isHardened="false"

You can safely write this simply as:

isHardened=false

Here, on the other hand, you should quote $1:

lineNUM=$(grep -n "$2" $1 | tail -n1 | sed 's/:.*//')

And you could use sed to include what tail does:

lineNUM=$(grep -n "$2" "$1" | sed -ne '$s/:.*//p')

Prefer [[ ... ]] instead of [ ... ]

[ "$lineNUM" ] || lineNUM="$"

[ ... ] is obsoleted, unless you require POSIX compatibility. Using [[ ... ]] is recommended, and it let's you simplify the quoting:

[[ $lineNUM ]] || lineNUM="$"

Don't use echo for non-trivial things

Avoid using echo with any of it's flags, like -e, because it's not portable. You also don't need the trailing ; here:

echo -e '\e[32m'$1'\e[m';

It's better to rewrite using printf:

printf '\e[32m%s\e[m\n' $1

Simplify logic

You evaluate -z "${BIT_SIZE}" twice, unnecessarily:

if [ -z "${BIT_SIZE}" -a "true" == ${isHardened} ]; then
    BIT_SIZE=4096
elif [ -z "${BIT_SIZE}" ]; then
    BIT_SIZE=$DEFAULT_BIT_SIZE
fi

You can simplify the logic, and using [[ ... ]] also helps:

if [[ ! $BIT_SIZE ]]; then
    if [[ $isHardened = true ]]; then
        BIT_SIZE=4096
    else
        BIT_SIZE=$DEFAULT_BIT_SIZE
    fi
fi

Formatting

The formatting is strange here, and it makes your script harder to read:

if [ ! -f $DHEC_path ]; then
  # Generate a 4096 bit random parameter for DH elliptic curves.
  # Generated by OpenSSL with the following command:
  #   openssl dhparam -outform pem -out dhparam.pem 2048
  #   openssl dhparam -outform pem -out dhparam.pem 4096
   ( openssl dhparam -outform pem -out $DHEC_path $BIT_SIZE) &
    spinner $!
fi
        update_config $nginx_ssl_conf ssl_dhparam $DHEC_path';' "#Path to DHEC key"

Write like this instead:

if [[ ! -f $DHEC_path ]]; then
    # Generate a 4096 bit random parameter for DH elliptic curves.
    # Generated by OpenSSL with the following command:
    #   openssl dhparam -outform pem -out dhparam.pem 2048
    #   openssl dhparam -outform pem -out dhparam.pem 4096
    (openssl dhparam -outform pem -out $DHEC_path $BIT_SIZE) &
    spinner $!
fi
update_config $nginx_ssl_conf ssl_dhparam $DHEC_path';' "#Path to DHEC key"


Handling Null values (and equivalents) routinely in Python

Generally I don't think you should have a class for this functionality. There's no state and no particular meaning to MyUtils object here. You can make this into a long function in whatever module you deem appropriate in your codebase.

I think this function as written is a code smell. It 1) doesn't cover a whole lot of types and 2) implies that where you're using it you're not going to have even a rough idea of what type of data you're expecting. In most cases you will have some idea, and even then it's not usually a good idea to do explicit type checking.

Where you're using this for numbers you can replace it with myval if myval is not None else mydefault.

A function like this may be more useful for strings, for which there are a wider range of essentially empty values. Perhaps something like this

def safe_string(s, default="", blacklist=["None"]):
    if s is None or len(s.strip()) == 0:
        return default
    if s.upper() in [b.upper() for b in blacklist]:
        return default
    return s


Increase performance of Bayesian likelihood equation

This is much faster.  I added the seed to better compare results across runs.

import numpy as np

# Define random data with correct shapes.
np.random.seed(0)
N, M = np.random.randint(10, 1000), np.random.randint(10, 1000)
D = np.random.randint(2, 5)
f_N, g_M = np.random.rand(N, D, 2), np.random.rand(M, D, 2)
P_i = np.random.uniform(0., 1., N)

# replace loops with broadcasted array operation, followed by sums
fgsum = f_N[:,None,:,1] + g_M[None,:,:,1]
fgdif = f_N[:,None,:,0] - g_M[None,:,:,0]
print(fgsum.shape)   # e.g. (694, 569, 3)

Dsum = (fgdif**2 / fgsum).sum(axis=-1)
sigma_ijk = np.prod(fgsum, axis=-1)
sum_M_j = np.exp(-0.5 * Dsum) / np.sqrt(sigma_ijk)
sum_Mi = np.sum(sum_M_j, axis=-1)

# as before
sum_Mi_Pi = P_i * sum_Mi
# Remove 0. elements before applying the logarithm below.
sum_N = sum_Mi_Pi[sum_Mi_Pi != 0.]

# Final negative logarithmic likelihood
lik = len(f_N) * np.log(len(g_M)) - sum(np.log(sum_N))
print(lik)


Bugs:

After building your list, you throw it away without printing anything (and if not, please supply all your code)

Minor:

pathlib >>> os. It leads to much better readable code, and less boilerplate.
is_locked=list() should be: is_locked = [] Note spaces and the literal.
pf.close() isn't a reliable statement. Instead, consider using something like with open(full_filename) as pf: pass
"path/to/directory" is a magic variable. Make it a global constant instead.
Use a if __name__ == "__main__": guard. Always.

Are you going to manually unlock all the files?

If not, you can just break after the first error and inform the user.


More efficient way of counting the number of values within an interval?

What you want is a histogram of your values. If you want it to be flexible in the future with different bucket sizes, then you can use a std::vector and calculate how many buckets you need.

If the values are in range [0, 1] and 0 < bucket_size < 1, then the number of buckets you need obviously is ceil(1 / bucket_size).

So what I'd do would probably look something like this:

const float bucket_size = 0.05;
int number_of_buckets = (int)ceil(1 / bucket_size); // requires <cmath>
std::vector<int> histogram(number_of_buckets);

...

while (theFile >> area) {
    int bucket = (int)floor(area / bucket_size);
    histogram[bucket] += 1;
}

No big if-else cascade and easy to adjust for different bucket sizes.


Not sure what that ORDER BY (SELECT new_id from GetNewID), but comparing the following approaches, second is much faster and spends most of the time in COUNT(*), which could be pre-calculated.

SELECT TOP 1 name FROM master.sys.all_objects ORDER BY NEWID()

DECLARE @n int
SELECT @n = RAND() * (SELECT COUNT(*) FROM master.sys.all_objects)

SELECT name FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as n, name
    FROM master.sys.all_objects
) AS names
WHERE n = @n

I guess you could make it even faster by materializing integer sequential id inside your names tables and making a clustered index on that.


Assigning initial value via getter or viewDidLoad

I would recommend to use one common method for initialization of all the variables, constants, NSUserDefaults, etc..

viewDidLoad should not be messy, it should mostly have calls to the methods.
I believe you are all aware with code reusability and code optimization techniques.


Creating valid words on an n-by-n grid of characters using depth-first search

Obfuscation

Tile.empty is a long, verbose way of saying None.  Each time you use it, the Python interpreter must look up Tile in locals(), and then globals(), to find the Tile class object.  Then, it needs to look up empty in the Tile dictionary to find the value None.  If you simply used None, your code would be faster, because None is a keyword; no heroic efforts are needed by the Python interpreter to determine what this value is.

Dictionary of None values

From the minimal code which has been presented, there is no compelling reason to store each direction in self.directionals.  Instead of a direction key returning None (or Tile.empty), that direction could simply not exist in the dictionary.  The top-left corner would only contain directions "e", "se", and "s".  This would simply this code:

        for direction in tile.directionals.values():
            if direction is not Tile.empty and direction not in visited:
                ...

to this:

        for direction in tile.directionals.values():
            if direction not in visited:
                ...

One less check means less work, and faster performance.

Finally, since you keep asking for tile.directional.values(), you might consider storing these values in their own collection:

        tile.valid_directionals = set(tile.directionals.values())

or, if you must store all 8 directions:

        tile.valid_directionals = set(value for value in tile.directionals.values()
                                      if value is not Tile.empty)

and then using:

        for direction in tile.valid_directionals:
            if direction not in visited:
                ...

Using a set instead of a dict_values iterator may not be any faster, but I'll be taking advantage of it later.

List Comprehension

    self.grid = [[] for _ in range(length)]

    for i in range(length):
        for _ in range(length):
            new_tile = Tile(randomchar()) #assume randomchar() returns a random character each time
            self.grid[i].append(new_tile)

is a long, round about way of writing:

    self.grid = [[Tile(randomchar()) for _ in range(length)] for _ in range(length)]

Whenever you create a list, and then append to it in a loop, consider using list comprehension instead.  It is a powerful tool for your tool chest.

Simplify Tests

Consider i - 1 >= 0.  The Python Interpreter must lookup the value i, subtract 1 from it, which involves constructing a new int object, or since all the values are going to be small, looking up an interned version.  Then, the value is compared to zero, and discarded.  Consider the equivalent expression i >= 1, or even i > 0.  Look up the value and compare to a constant.  No subtraction operation required, no new integer object required for the result, and no discarding of the result of the subtraction after being used.  This is still in your executed once initialization code, so performance doesn't matter much, but why be sloppy?

Searching too deep

Your helper function looks approximately like:

    def helper(tile, word):
        if len(word) > max_word_length:
            return

        ...

        for direction in tile.directionals.values():
            if ...:
                helper(direction, word + direction.letter)

Imagine if we've called the helper a few times, and we've just recursed in with word="TRAPS".  We start looping around the tiles around the S, skipping the visited tiles, and call helper(direction, "TRAPS" + direction.letter) with direction.letter taking on the values 'O', 'I', 'M', 'E', 'E' and 'S'.  In each call, the first thing we do is check len(word) > max_word_length, and return if True.  With max_word_length = 5, every one of those calls will immediately return!  There is no point iterating to the len(word) == 6 depth!  If we checked for this earlier, we could eliminate many useless calls, and save time.

    def helper(tile, word):

        ...

        if len(word) < max_word_length:
            for direction in tile.directionals.values():
                if ...:
                    helper(direction, word + direction.letter)

Redundancy

Furthermore:

def helper(tile, word):
    ...
    if tile in visited:
        return
    ...
    for direction in tile.directionals.values():
        if direction not in visited:
            helper(direction, word + direction.letter)

You test direction not in visited, and only if that is true will you call helper(direction, ...).  In that recursive call, the tile in visited test will therefore never be true.  You can remove that redundant check for better performance.

Containment Testing

    #allwords is a list with all the words in the English dictionary
    if word in allwords and len(word) >= min_word_length:
        ...

First of all, English can contain some really long words, like "tetraiodophenolphthalein".  We should shorten this dictionary to words which are max_word_length and less.

possible_words = [word for word in allwords
                  if min_word_length <= len(word) <= max_word_length]

With this, my dictionary size is reduced from 235,886 words down to 17,082.  And a smaller dictionary will speed things up.

But what will speed things up more is getting rid of that list.  Testing if a word is in a list is an \$O(n)\$ operation.  If the words were stored in a set, this reduces search complexity to an \$O(1)\$ operation.

possible_words = set(word for word in allwords
                     if min_word_length <= len(word) <= max_word_length)

Then, containment testing is easy:

    if word in possible_words:
        ...

word in possible_words doesn't look much different from word in allwords, but the speed-up going from x in list to x in set is quite dramatic.

What about the and len(word) >= min_word_length condition?  Where did it go?  possible_words only contains words which are at least min_word_length, so we get that for free!

Pruning the Search Tree

Alright, I'm finally where I actually wanted to be to answer this question.  The fun part.

How many words in the English dictionary start with "RL"?  What about "MS" or "FM" or "TF"?  Plenty of words start with "SM" but no words start with `"SMF".

As you are collecting the tile letters into a candidate word, you test whether you have discovered a word, but not whether you've reached a combination which will not start any word.  Doing so will prune you search tree, and avoid checking around \$6^3\$ candidate words starting with "RL".  Less searching, yields faster performance!

So, how do we prune?

Consider the word "SOME".  If we start with "S", we have a possible word.  If we start with "SO", we have a possible word.  If we start with "SOM", we have a possible word.  And if we start with "SOME" we have a possible word.  So for each word in our possible_words, we just need to collect all the possible prefixes for the word into a set.

valid_prefixes = set(word[:size]
                     for word in possible_words for size in range(1, length(word))

With this set of valid prefixes, if our candidate word fragment is not a valid prefix, we can skip deeper searching of that branch:

    for direction in tile.directionals.values():
        if direction not in visited:
            candidate = word + direction.letter
            if candidate in valid_prefixes:
                helper(direction, candidate)

The tile.valid_directionals set

Almost forgot.  visited is a list.  If we switch this into a set, then we can use set arithmetic to get a set of valid_directionals that haven't been visited with valid_directionals - visited

def dfs(tile, word, min_word_length=2, max_word_length=5):
    visited = set()

    def helper(tile, word):
        if word in possible_words:
            print(word)

        if len(word) < max_word_length:
            visited.add(tile)
            for direction in tile.valid_directionals - visited:
                candidate = word + direction.letter
                if candidate in valid_prefixes:
                    helper(direction, candidate)
            visited.remove(tile)

    helper(tile, word)


I'm not exactly sure what you mean with coding pattern, but there are some things that strike me as odd:

you only log empty messages ... in some of the cases encoding the message in the logger name. This certainly isn't the way log4j is intended to be used.
When ever you call this method basically the same Appender is created added and removed again. This again is a strange way to use log4j. And I'm not even sure what will happen when two threads call this method at the same time.
You are setting the ConsoleAppender and the Pattern over and over again. This at least is superfluous, and might actually be harmful.
The naming is ... suboptimal ... You have two loggers one, is missing a g in its name, the other is abbreviated. None really tells the reader what these loggers are about.
You never ever actually log with loger

So if this doesn't depend on some weird side effect this logs one empty String when it is called and two empty Strings when creating/adding/removing an Appender throws and exception. If this is really what this is supposed to do, it better made it clear in its names and comments.


Solution of class design issue of generic of restricted type

As has been said in the comments, it's unclear why you feel you need this behaviour to restrict the types used.  There's an interesting discussion around constraining types here, which includes a link to example code.
So, there's a couple of questions.  Why do you need to restrict it to double / integer types?  Is it really that you want to do is restrict it to types that support certain operations?  What is the actual downside to using it for Decimal / float?
You've presented an example of IDataType, however suggested that really your goal is to put these items into a set.  So this begs the question, are you planning on creating DescriptiveStatisticalSet<IntegerDataType> or DescriptiveStatisticalSet<IDataType>?  If it's IntegerDataType, what are you gaining over Int32 for example?  If it's IDataType, then are you expecting to have both IntegerDataType  and DoubleDataType both present in the same set?  If so, what are you planning on doing if an Integer has the same value as a Double?  Do you keep both because they are different types, or keep whichever one was there first, or keep the Double because it's more flexible, or the Integer because it's faster?
Looking at your actual code, there's some aspects which are worth mentioning.

object Add(object other);

If we look at IntegerDataType, this method takes in an other of type IntegerDataType, but returns an int.  This it not at all obvious from the method signature.  You are working around this to an extent in your DataType class, which does some recasting by creating a new instance of the returned object, however this seems unnecessarily complex.  Particularly since the implementation of Add relies on casting other to the correct type.  Calling Add with a DoubleDataType for example throws a cast exception.

public int Data { get; set; }

Both your Integer and Double data types declare a Data property that has both public getter and setter.  Since you're implementing an interface to setVal, does it really make sense to declare this public setter?  It feels like it would be better for the set to be private, in order to encourage the client to use the interface method, in case you decide you need to do additional checking in the future.
Your DataType class seems to exist purely to create a new item from the object version of Add.  This seems to add unnecessary complexity over just having the initial Add return the correct datatype.  So, it's a bit unclear to me what advantage your current approach has over simply doing this:
public interface IOtherDataType<T>
{
    T Data { get;}

    IOtherDataType<T> Add(IOtherDataType<T> other);
    void SetVal(T other);
}

public class IntType : IOtherDataType<int>
{
    public IntType(int data)
    {
        Data = data;
    }

    public int Data { get; private set; }

    public IOtherDataType<int> Add(IOtherDataType<int> other)
    {
        return new IntType(Data + other.Data);
    }

    public void SetVal(int other)
    {
        Data = other;
    }
}

Which can be used in a similar way...
IntType five = new IntType(5);
IOtherDataType<int> eleven = five.Add(new IntType(6));


Alien Name Generator (using blocks of consonants and vowels)

All of your code is top-level, there are no functions and the only way to understand this programme is reading it all, also it is not tested so developing it was probably difficult.

Here is how I would go about it, with extensive comments.

"""
Block based alien name generator.
"""

This is a module level docstring, the first thing that gets displayed when the user types help(your_module) it usually describes concisely the purpose of the whole script.

import doctest
import itertools
import random
import string
import time

The Python Standard Library is extensive, many modules make devoloping programs easier.

MIN_BLOCK_LENGTH = 1
MAX_BLOCK_LENGTH = 2
MIN_BLOCKS_NUMBER = 2
MAX_BLOCKS_NUMBER = 3
VOWELS = "aeiou"
CONSONANTS = ''.join(i for i in string.ascii_lowercase if i not in  VOWELS)
TARGET_FILENAME = "nice_alien_names.txt"

These are module level constants, they either contain values that would be meaningless to change such as VOWELS or configuration options such as MAX_BLOCK_LENGTH that I modified as I like best short names. They are written SHOUTCASE and should not be changed (Python won't stop you from doing so though).

def random_string(length, pool):
    """
    >>> random.seed(0)
    >>> random_string(5, "abc")
    'bbabc'
    """
    return ''.join(random.choice(pool) for _ in range(length))

Now we get to the real meat. This is a function, an individual block of code with a name that performs one task and only that, return gives that value back into the programme. You may see the use of a generator expression, it can greatly shorten and simplify code. It is also tested, and the tests serve also as documentation.

def random_vowel_block():
    return random_string(random.randint(MIN_BLOCK_LENGTH, MAX_BLOCK_LENGTH), VOWELS)

def random_consonant_block():
    return random_string(random.randint(MIN_BLOCK_LENGTH, MAX_BLOCK_LENGTH), CONSONANTS)

Two small helper functions, to have function names near to the specification.

def alternate(func_1, func_2, times):
    """
    Returns a list containing `times` results
    of the two functions alternated.

    >>> list(alternate(lambda: 1, lambda: 2, 3))
    [1, 2, 1]
    """
    return list(itertools.chain(
        * zip( (func_1() for _ in range(times)),
               (func_2() for _ in range(times)))))[0:times]

This function is probably more complex than it should be ;P, anyhow docstring and test simplify understanding. As you can see I abstracted the concept of alternation into a higher order function (a function that takes functions as input) that I will use in the main alien_name function.

def alien_name():
    """
    Generates a random alien name by concatenating a random
    number (between MIN_BLOCKS_NUMBER and MAX_BLOCKS_NUMBER)
    of random all-vowel and all-consonant blocks, of which each one
    has a length between MIN_BLOCK_LENGTH and MAX_BLOCK_LENGTH.

    >>> random.seed(0)
    >>> alien_name()
    'aiqmiu'
    >>> alien_name()
    'wtaa'
    """
    name = ''.join(alternate(random_vowel_block, random_consonant_block,
                     random.randint(MIN_BLOCKS_NUMBER, MAX_BLOCKS_NUMBER)))
    return name if random.randint(0, 1) else ''.join(reversed(name))

The most important function, as you can see it is very small, as we have already defined all the building blocks needed. It reads almost as plain English. The last line implies that is a 50% chance of reversal to allow names starting with consonants.

def save_liked_ones():
    print("Enter nothing to ignore, `l` or `like` to save and `end` to terminate and save.\n")
    good_names = []
    while True:
        candidate_name = alien_name()
        choice = input("{}: ".format(candidate_name)).lower()
        if not choice:
            pass
        if choice.startswith('l'):
            good_names.append(candidate_name)
        if choice == 'end':
            with open(TARGET_FILENAME, 'a+') as f:
                f.write('\n'.join(good_names))
            return

I took the liberty of writing a user interface to avoid saving dull or uninteresting names, as you can see the logic is being performed all inside alien_name() this function only handles user interface.

if __name__ == "__main__":
    doctest.testmod()
    random.seed(time.time())
    save_liked_ones()

This runs the tests that you see in the docs and shows the user interface if this file is run as a script, importing it will only cause the functions to be defined. Please note that random.seed is needed as I seeded the Random Number Generator before for ease of testing.

And the full programme, in case you want to play and experiment with it:

"""
Block based alien name generator.
"""

import doctest
import itertools
import random
import string
import time

MIN_BLOCK_LENGTH = 1
MAX_BLOCK_LENGTH = 2
MIN_BLOCKS_NUMBER = 2
MAX_BLOCKS_NUMBER = 3
VOWELS = "aeiou"
CONSONANTS = ''.join(i for i in string.ascii_lowercase if i not in  VOWELS)
TARGET_FILENAME = "nice_alien_names.txt"

def random_string(length, pool):
    """
    >>> random.seed(0)
    >>> random_string(5, "abc")
    'bbabc'
    """
    return ''.join(random.choice(pool) for _ in range(length))

def random_vowel_block():
    return random_string(random.randint(MIN_BLOCK_LENGTH, MAX_BLOCK_LENGTH), VOWELS)

def random_consonant_block():
    return random_string(random.randint(MIN_BLOCK_LENGTH, MAX_BLOCK_LENGTH), CONSONANTS)

def alternate(func_1, func_2, times):
    """
    Returns a list containing `times` results
    of the two functions alternated.

    >>> list(alternate(lambda: 1, lambda: 2, 3))
    [1, 2, 1]
    """
    return list(itertools.chain(
        * zip( (func_1() for _ in range(times)),
               (func_2() for _ in range(times)))))[0:times]

def alien_name():
    """
    Generates a random alien name by concatenating a random
    number (between MIN_BLOCKS_NUMBER and MAX_BLOCKS_NUMBER)
    of random all-vowel and all-consonant blocks, of which each one
    has a length between MIN_BLOCK_LENGTH and MAX_BLOCK_LENGTH.

    >>> random.seed(0)
    >>> alien_name()
    'aiqmiu'
    >>> alien_name()
    'wtaa'
    """
    name = ''.join(alternate(random_vowel_block, random_consonant_block,
                     random.randint(MIN_BLOCKS_NUMBER, MAX_BLOCKS_NUMBER)))
    return name if random.randint(0, 1) else ''.join(reversed(name))

def save_liked_ones():
    print("Enter nothing to ignore, `l` or `like` to save and `end` to terminate and save.\n")
    good_names = []
    while True:
        candidate_name = alien_name()
        choice = input("{}: ".format(candidate_name)).lower()
        if not choice:
            pass
        if choice.startswith('l'):
            good_names.append(candidate_name)
        if choice == 'end':
            with open(TARGET_FILENAME, 'a+') as f:
                f.write('\n'.join(good_names))
            return

if __name__ == "__main__":
    doctest.testmod()
    random.seed(time.time())
    save_liked_ones()


First, a style comment. On the internet, especially in programming, and in particular on this website, English is the lingua franca. So you should avoid mixing other languages and English. This way your code is the most transferable, re-usable and readable.

Second, a comment on the algorithm itself. Your algorithm (and this includes any changes I make to it down below) does not actually find the set of points furthest apart from each other (i.e. the optimal solution). What it does is generate a solution where points tend to be far apart from each other. This is similar to the common strategy for the traveling salesman problem, where you choose to always travel to the closest (unvisited) city next.

This algorithm has the advantage that it does not need to try all combinations, usually quickly leads to a good enough solution, and is very easy to implement. It has the disadvantage that it is on average about a quarter less far apart than the optimal solution and might even return the worst possible solution for some cases.

You might want to look at the other heuristic solutions in that link for different algorithms.

Finally, let's see if the code you have can be improved.

Since you are already using numpy, you should take more advantage of it. It's power lies in using its internal functions, which are implemented and executed in C, independent of the Python interpreter.

As a start, I put your code doing the actual calculations into a function, this way it is re-usable and testable:

@timeit
def op(pts, N, K):
    farthest_pts = [0] * K

    P0 = pts[np.random.randint(0, N)]
    farthest_pts[0] = P0
    ds0 = dist_ponto_cj(P0, pts)

    ds_tmp = ds0
    for i in range(1, K):
        farthest_pts[i] = ponto_mais_longe(ds_tmp)
        ds_tmp2 = dist_ponto_cj(farthest_pts[i], pts)
        ds_tmp = [min(ds_tmp[j], ds_tmp2[j]) for j in range(len(ds_tmp))]
        # print ('P[%d]: %s' % (i, farthest_pts[i]))
    return farthest_pts

if __name__ == "__main__":
    N, K = 80, 40
    pts = np.random.random_sample((N, 2))
    farthest_pts = op(pts, N, K)
    ...

I also used pts = np.random.random_sample((N, 2)) to directly calculate x and y. This means that to plot the points afterwards, you need to use array indexing: plt.scatter(pts[:, 0], pts[:, 1], c='k', s=4).

The @timeit is a decorator*, that prints out the time spent in that particular function whenever it is run. Your code takes about 0.05 seconds on my machine. This is our baseline.

Finally, I put the calling code into a if __name__ == "__main__": guard to allow importing parts of this script from other scripts.

The first thing I would change in your code is the calculation of distances. Here we can use the fact that numpy can operate on the whole array in parallel and just write:

def calc_distances(p0, points):
    return ((p0 - points)**2).sum(axis=1)

Next, here is a way to implement your algorithm using more numpy functions:

@timeit
def graipher(pts, K):
    farthest_pts = np.zeros((K, 2))
    farthest_pts[0] = pts[np.random.randint(len(pts))]
    distances = calc_distances(farthest_pts[0], pts)
    for i in range(1, K):
        farthest_pts[i] = pts[np.argmax(distances)]
        distances = np.minimum(distances, calc_distances(farthest_pts[i], pts))
    return farthest_pts

I also start with pre-assigning an empty array, but using numpy.zeros. I then choose a random point and choose the next furthest point the same way you do.I use numpy.argmax to basically do what your ponto_mais_longe function does, namely return the index of the maximal value. numpy.minimum returns the minimal value for each element in the two given sequences.

This implementation takes about 0.0004 seconds on my machine (so almost 100 times faster).

I don't think this can be sped-up further, because each iteration of the for loop depends on the previous iteration. The only way to speed it up further is to use a different algorithm.

Side note: My timeit decorator looks like this:

from time import clock

def timeit(func):
    def wrapper(*args, **kwargs):
        starting_time = clock()
        result = func(*args, **kwargs)
        ending_time = clock()
        print('Duration: {}'.format(ending_time - starting_time))
        return result
    return wrapper


Merging an overlapping collection of intervals

Some style issues:

Space before {
Spaces around ->
Space after ,
No space before :
Space before else
Indent else blocks 4 characters

Make constructor functions part of the impl:

impl Range {
    fn new(start: i32, end: i32) -> Range {
        Range {
            start: start,
            end: end,
        }
    }
}

Instead of creating a to_string method, implement Display instead. This allows you to automatically get .to_string(), but even better, means you can format the object without extraneous allocation:

impl fmt::Display for Range {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{},{}]", self.start, self.end)
    }
}

No need to use iter() when using a for loop on a slice or Vec, just take a reference:

for range in &self.ranges { ... }

Use pattern matching to avoid all the unwrap calls in RangeStack::add:

fn add(&mut self, range: &Range) {
    if let Some(last) = self.ranges.last_mut() {
        if last.overlaps(range) {
            last.merge(range);
            return;
        }
    }

    self.ranges.push(range.clone());
}

Never take a &Vec<T> as an argument. It needlessly limits what types you can accept. In your case, it also allows you to avoid the allocation of the vector in your main. Use a slice instead:

fn with_ranges(ranges: &[Range]) -> RangeStack { ... }

You probably always want to implement Debug, usually done via derive:

#[derive(Debug, Copy, Clone)]
struct Range { ... }

Consider making your with_ranges constructor more generic by implementing FromIterator:

impl FromIterator<Range> for RangeStack {
    fn from_iter<I>(iterator: I) -> Self
        where I: IntoIterator<Item=Range>
    {
        let mut raw_ranges: Vec<_> = iterator.into_iter().collect();
        // ...
    }
}

All together, this now looks like

use std::{cmp, fmt};
use std::iter::FromIterator;

#[derive(Debug, Copy, Clone)]
struct Range {
    start: i32,
    end: i32,
}

impl Range {
    fn new(start: i32, end: i32) -> Range {
        Range {
            start: start,
            end: end,
        }
    }

    fn overlaps(&self, other: &Range) -> bool {
        (other.start >= self.start && other.start <= self.end)
        || (other.end >= self.start && other.end <= self.end)
    }

    fn merge(&mut self, other: &Range) {
        self.start = cmp::min(self.start, other.start);
        self.end = cmp::max(self.end, other.end);
    }
}

impl fmt::Display for Range {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{},{}]", self.start, self.end)
    }
}

#[derive(Debug, Clone)]
struct RangeStack {
    ranges: Vec<Range>,
}

impl RangeStack {
    fn add(&mut self, range: &Range) {
        if let Some(last) = self.ranges.last_mut() {
            if last.overlaps(range) {
                last.merge(range);
                return;
            }
        }

        self.ranges.push(*range);
    }
}

impl fmt::Display for RangeStack {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for range in &self.ranges {
            try!(write!(f, " {}", range));
        }
        Ok(())
    }
}

impl FromIterator<Range> for RangeStack {
    fn from_iter<I>(iterator: I) -> Self
        where I: IntoIterator<Item=Range>
    {
        let mut raw_ranges: Vec<_> = iterator.into_iter().collect();
        raw_ranges.sort_by(|a,b| a.start.cmp(&b.start));

        let mut range_stack = RangeStack {
            ranges: Vec::new(),
        };

        for range in &raw_ranges {
            range_stack.add(range);
        }

        range_stack
    }
}

impl<'a> FromIterator<&'a Range> for RangeStack {
    fn from_iter<I>(iterator: I) -> Self
        where I: IntoIterator<Item=&'a Range>
    {
        iterator.into_iter().cloned().collect()
    }
}

fn main() {
    let v = [
        Range::new(3, 6),
        Range::new(1, 5),
        Range::new(7, 11),
        Range::new(9, 12),
        Range::new(4, 8),
    ];

    let rs: RangeStack = v.iter().collect();
    print!("Result: {}\n", rs);
}


It looks like you only have one lock, so you can't have deadlock; but for future reference, you can add deadlock detection to the program, see for example this blog post but there are many other options available.
You may want to replace the arraylist with a ConcurrentLinkedQueue, this will let you remove the synchronized block from depositMessage and may let you remove the synchronized block from withdrawMessages and processMessages depending on how responseUpdater.sendReponse is implemented.  In general, try to use lock-free data structures when possible - they generally scale better, and you can't heave deadlock if you don't have any locks.
ConTest is a tool for detecting multithreading problems e.g. race conditions.  Java Pathfinder is a much more heavyweight approach to this.
For a large project, you may want to use a library like Akka or JMS to manage concurrency.


Return correct subclass instance, identified by string

Use all the power of the standard library
In your post on StackOverflow, you mentioned that you couldn't use std::map because you were not allowed to use it. Outside of the classroom, you should not limit yourself this way, and instead use the appropriate functions from the standard library that help you write concise and efficient code. The function func() could look like:
Form *func(std::string_view name)
{
    static const std::unordered_map<std::string_view, std::function<Form*()>> forms = {
        {"triangle",  []{return new Triangle;}},
        {"rectangle", []{return new Rectangle;}},
        ...
    };

    if (auto found = forms.find(name); found != forms.end()) {
        return found->second();
    } else {
        return nullptr;
    }
}

And instead of raw pointers, you should probably return std::unique_ptr<Form>.
In the rest of the review I'm going to assume you are limited to what you can use.
Prefer using = default
It's usually best to let the compiler generate default constructors, destructors and other operators. In some cases, you have to explicitly tell it to add one of those, for example when you want to ensure the destructor of Form is virtual. In that case, use = default instead of {}:
class Form
{
public:
    virtual ~Form() = default;
};

Use \n instead of std::endl
Prefer using \n instead of std::endl, the latter is equivalent to the former but also forces a flush of the output, which might be bad for performance if you are printing a lot.
Avoid unnnecessary parentheses and void
You can simplify the createForm() functions a bit:
static Form *createForm()
{
    return new Square;
}

The unnecessary parentheses and void in the argument list are just unnecessary distractions here.
Move s_makeForms into func()
You can move the definition of struct s_makeForm into func(), so it doesn't clutter the global namespace. In fact, you don't even have to give this struct a name, you can write:
Form *func(std::string &name)
{
    struct {
        std::string name;
        Form *(*createForm)();
    } forms[] = {
        "triangle", Triangle::createForm},
        ...
    }

    ...
}

Prefer const std::string & when passing string arguments
To avoid unnecessary copying of strings, prefer passing strings as const references:
Form *func(const std::string &name)
{
    ...
}

Avoid having to #define NB_FORMS
You can get the size of the array allForms in various ways, the typical trick that works both in C and all versions of C++ is:
struct ... allForms[] = {...};
size_t numForms = sizeof allForms / sizeof *allForms;

for (size_t i = 0; i < numForms; ++i)
{
    ...
}

You can also use a range-based for-loop to iterate over the array:
struct ... allForms[] = {...};

for (auto &form: allForms)
{
    if (name == form.formName)
        return form.makeForm();
}

Memory leak
There is a memory leak in your program, since you forgot to call delete myform. These kinds of errors can be avoided by using smart pointers, such as std::unique_ptr.


Project Euler #14 in Swift - Longest Collatz sequence

collatzSequenceForNumber() returns the length of the Collatz sequence and not a sequence itself, so a better name might be collatzLength():

func collatzLength(var number:Int, inout steps:[Int]) -> Int {
    var numberOfSteps = 0
    let initialNumber = number
    // ...
}

The steps
parameter is an array used as cache. But in longestCollatzSequence(), the same name steps is used for both the caching array and the computed number of steps.
For more consistence, I would suggest to use steps for the number of steps
only and a different name cache for the caching array:

func collatzLength(var number:Int, inout cache:[Int]) -> Int {
    var steps = 0
    let initialNumber = number
    // ...
    return steps
}

The number parameter is declared as a variable
and modified in the function. That is fine generally, but here you need the original value of the parameter at the end of the function. It might be
clearer to treat the  parameter as constant and modify a local copy:

func collatzLength(number:Int, inout cache:[Int]) -> Int {
    var steps = 0
    var n = number
    // ...
    cache[number] = steps
    return steps
}

The expression

found = number < steps.count ? steps[number] > 0 : false

can simpler be written as

found = number < steps.count && steps[number] > 0

and I prefer if (!found) to if (found == false). But you don't need
the found variable at all, as this condition can be put directly into
the while() expression.

So now we have

func collatzLength(number:Int, inout cache:[Int]) -> Int {
    var steps = 0
    var n = number

    while n >= cache.count || cache[n] == 0 {
        if n % 2 == 0 {
            n /= 2
        } else {
            n = (n * 3 + 1) / 2
            steps++
        }
        steps++
    }

    steps += cache[n]
    cache[number] = steps
    return steps
}

Interestingly, this is a tiny bit faster than your original version
(0.027 s instead of 0.032).

You can improve the performance a bit by taking advantage of the fact that
the caching array is filled sequentially. So (in the context of this program)

    while n >= cache.count || cache[n] == 0 {

can be replaced by

   while n >= number {

and this reduces the time to 0.016 s.

In longestCollatzSequence() you are using a tuple with named components
(number:0, steps:0) internally, but return an unnamed tuple (Int, Int).
In the calling function euler14() the return value is assigned to
a named tuple again. I would recommend to stick to one variant, e.g.
the named tuple:

func longestCollatzSequence(maxNumber:Int) -> (number: Int, steps: Int) {
    var collatzSequence = (number:0, steps:0)
    var cache:[Int] = [Int](count: maxNumber, repeatedValue: 0)
    cache[1] = 1

    for var number = 2; number < maxNumber; number++ {
        let steps = collatzLength(number, &cache)
        if steps > collatzSequence.steps {
            collatzSequence = (number, steps)
        }
    }

    return collatzSequence
}

The for loop can equivalently  be written using a Swift range:

for number in 2 ..< maxNumber { ... }

The main function can now be simplified to

func euler14() {
    let result = longestCollatzSequence(999_999)
    println(result.number)
}

or alternatively

func euler14() {
    let (number, steps) = longestCollatzSequence(999_999)
    println(number)
}

Finally note that your longestCollatzSequence() function considers
all number below the given parameter, so you should either call

longestCollatzSequence(1_000_000)

or change the function to include the given upper bound.


Finding minimum steps required to traverse from source to terminal

and welcome!
Things I really like

Using standard Ruby indention (2 spaces)
Using the attr_accessor and attr_reader helpers instead of hand-rolling these methods
Using n.times do to loop.
Using next at the top of a loop body instead of a nested if
Short, focused methods
Great use of functional decomposition (goes along with the focused methods)

There's a lot of nit-picky things to follow, so don't be discouraged.  Many of these things are minor, and I'm mostly pointing out Ruby idioms or practices you have no way to know yet.  Due to time constraints, I am not going to address the algorithm itself, nor look for any major improvements.  I will mostly point out the things that catch my eye as a Ruby programmer.
Naming things
  def _read
    # assign each coord. to a Node-object

Does the comment indicate that "read" could use a better name?
    nodes.each do |x|
      nodes.each do |y|

x and y are frequently used as coordinate names for a Cartesian grid, which a chessboard is.  Here, x and y are nodes, not coordinates.  Better names would be a and b, or perhaps origin and destination.
@adjies = [] # adjacencies

Probably just name the variable @adjacencies so you can lose the comment, and the code will be clearer throughout.  Someone reading the code who hasn't seen this comment yet will be confused.
Formatting
    end
    def add(value)
      @adjies << value
    end
  end

Standard Ruby formatting separates methods with a blank line.  I also prefer a blank line between a method and the end of the class:
    end

    def add(value)
      @adjies << value
    end

  end

but the more common practice is to have no blank line after the last method in a class:
    end

    def add(value)
      @adjies << value
    end
  end

Idiomatic private methods in Ruby
def _jump(nodes)

Standard Ruby does not use the underscore conversion for private methods.  Instead, private methods can follow the private keyword:

private

def jump(nodes)

Note that all methods that follow "private" will be private, so you don't have to use it before every private method.  Standard Ruby practice is to just give the "private" keyword once, and then follow that with all of the private methods.
Omit the "return" keyword in the last expression in a method.
   return -1

The result of a Ruby method is the value of the last expression in the method.  So unless returning early, we usually omit the "return" keyword when it's on the last line:
    -1

You omit the "return" keyword elsewhere, so I assume this is just an oversight.
Don't compare to true or false
if w.disc == false

In Ruby, true and false are a little different than in Java.  Ruby considers anything that is either nil or false to be "falsey", and everything else is "truthy".  Therefore, it is bad practice to compare a value with false, since this comparison will fail if the value is actually nil.
So instead of comparing with false, do this:
if !w.disc

But even better, Ruby has a negating form of "if" called "unless".  Idiomatic Ruby would be:
unless w.disc

Getting the first element of an array or enumeration
root = nodes[0]

This is fine, but this also works:
root = nodes.first

Ruby likes you to have multiple ways to do a thing, a philosophical shift from Python.
Redundant #to_s
     temp = gets.strip.to_s

The result of String#strip is a String, so there's no need for .to_s here.
Use Array instead of Queue (for this application)
q = Queue.new

Queue is intended for multi-threaded applications; it includes locking to prevent race conditions.  For a single-threaded application, you can and should just use Array.  The minor reason is performance (avoid the locking).  The major reason is communication: A Ruby programmer seeing Queue is going to start looking for the threading in your program.
Since the methods you are calling on q (<< and pop) are also implement on Array and have the same meaning, you can do this instead:
q = []

Create empty arrays with []
nodes = Array.new

There's nothing wrong with this, but you will more often see a new, empty array created using the array literal syntax:
nodes = []


Munging select rows in CSV files using Pandas

If you have the Line column in your CSV itself, you can replace what you have with:

df.groupby(['Line', 'KEY']).agg({'AMOUNT': 'sum'}).reset_index()