self.start, self.grid, self.height, self.width = start, grid, height, width

I would not put these all on the same line like that. I think it would be much easier to read spread over multiple lines:
self.start = start
self.grid = grid
self.height = height
self.width = width

I would probably have the Node class as toplevel instead of nested. I don't think you're gaining much by having it inside AStar. You could name it _Node to make it "module-private" so that attempting to import it to another file will potentially raise warnings.
In Node's __lt__ implementation, I wouldn't call the second parameter comparator. A comparator is something that compares, whereas in this case, that's just another node. other_node or something would be more appropriate.

In heuristic, I'd personally make use of an else there:
if (distance == "Manhattan"):
    return abs((x1 - x2) + abs(y1 - y2))
else:
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

It makes it clearer that only one of the lines will be executed. Personally, I only neglect the else in a case like that if the if was an "early exit" precondition check, and I want to avoid nesting the entire rest of the function inside a block. That's not a problem here though.

nodeNeighbors (which should be node_neighbors) would be cleaner broken over several lines:
def nodeNeighbours(self, pos):
    (x, y) = pos
    return [(dx, dy)
            for (dx, dy) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
            if 0 <= dx < self.width and 0 <= dy < self.height and self.grid[dy][dx] == 0]

I think that makes it a lot easier to see what's going on in it.

Again, in many places you're assigning two or more variables on one line:
(x1, y1), (x2, y2) = self.start, end
current, path = endPoint, []
openList, closedList, nodeDict = [], [], {}
x1, y1, y2, x2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]

I would break those up. Especially once you get to 3+ on a line, for the reader to see what variable matches up with what value, they'll need to count from the left instead of just checking what's on each side of a =.

In computePath, it seems like  closedList should be a set. It doesn't appear as though order matters with it, and neighbour in closedList will be faster with a set than it will with a list. It looks though like openList is required to be a list though due to it being passed to heapify.

I don't think I'd reassign stdin and stdout. The reassignment of stdin seems completely unnecessary, and changing stdout will make it harder to debug later using print statements. You don't necessarily want all printed text to be sent to the file.
If need-be, you can specify what file you want printed to when printing:
with open('output.txt', 'w') as out_f:
    print("To file!", file=out_f)


The OdbcConnection is not thread-safe in any way, therefor it needs a locking mechanism.

My observation is that the OdbcConnection does send it's received commands down into the Connector. If this is happening in a multi-threaded environment, the sequence of commands is interrupted and you'll receive an exception with this or a similar message:

  ERROR [HY000] [MySQL][ODBC 3.51 Driver]Commands out of sync; you can't run this command now

The driver is confused because the sequence was interrupted. This can not only happen on a OdbcCommand level, but on a OdbcConnection level. The OdbcConnection needs to be locked.

An additional note is that you should lock the OdbcConnection the moment you start to work with a command:

_cmd.Parameters[0].Value = argument;
lock(_conn)
{
    _cmd.ExecuteNonQuery();
}

This is bad, because it could happen in a multi-threaded environment that the parameter gets overridden by another thread before ExecuteNonQuery can be called.

lock(_conn)
{
    _cmd.Parameters[0].Value = argument;
    _cmd.ExecuteNonQuery();
}

This keeps the execution as one atomic operation which can't be interrupted.

Further investigations revealed that the MySQL Odbc-Connector has a locking mechanism...but only on a statement level:

  MySQL ODBC Connector, 5.1.9, execute.c

 39:    SQLRETURN do_query(STMT FAR *stmt,char *query, SQLULEN query_length)
 40:    {
 ...
 55:        MYLOG_QUERY(stmt, query);
 56:        pthread_mutex_lock(&stmt->dbc->lock);
 ...
 96:        exit:
 97:        pthread_mutex_unlock(&stmt->dbc->lock);
 ...
114:   }

And to make it clear: If you have a non-thread-safe connection, lock the whole connection.

And to make it further clear, using an OdbcDataReader counts as using the connection. As long as you work with an OdbcDataReader, you should keep the lock on the connection.

This includes disposing of the resources, f.e. a DataReader. You should always use using inside the locked parts to make sure that the resources are freed again, otherwise it could happen that a DataReader lingers on and is later destroyed by the Garbage Collector and a rather inconvenient moment, like this:

Thread  Action
     1  Lock Connection
     1  Create Statement
     2  Lock Connection -> Wait
     1  Prepare Statement
     1  Execute Statement
     1  Get Reader
     1  Use Reader
     1  Unlock Connection
     2  Lock Connection
     2  Prepare Statement
     2  Execute Statement
    GC  Destroy Statement from thread #1
    GC  Destroy Reader from thread #1

In code it would like this:

lock (connection)
{
    IDbCommand command = connection.CreateCommand();
    command.CommandText = "SQL";
    IDataReader reader = command.ExecuteReader();
    // Do something the reader
    return valuesFromTheReader;
}

This is bad as it allows resources to linger on and the GC will later destroy them, with possible disastrous results. My tests revealed that from the exception

  Attempted to read or write protected memory.

to a simple deadlock of the application on an arbitrary line1 everything is possible if you fail to correctly synchronize database access.

The best pattern is to always destroy everything while in inside the lock:

lock (connection)
{
    using (IDbCommand command = connection.CreateCommand())
    {
        command.CommandText = "SQL";
        using (IDataReader reader = command.ExecuteReader())
        {
            // Do something the reader
            return valuesFromTheReader;
        }
    }
}

1: I'm not kidding, I could reliable reproduce a hang on the following instruction inside the System.Data.Odbc.OdbcDataReader.NextResult(bool, bool)

IL_0099: ldarg.1
00000099 8B F8 mov edi,eax

when I did not properly dispose of a DataReader.


Null object design pattern in a linked list

The question's classes are node, NullNode, dataNode, and linkedlist. Notice that the naming scheme appears not to be case-aware. It is best to fix this. Let's use camel case and capitalize the first letter. So we'll use Node, NullNode, DataNode, and LinkedList.

A problem is the type of LinkedList::container is NullNode. This means that LinkedList cannot contain DataNode objects!

DataNode -> Node  (-> means implies)

NullNode -> Node

Also, the null object design pattern is not properly used for linked lists. For example, NullNode::setNode() does not set the node. What does this mean? If the caller wants to store a value in a LinkedList object and it only contains a NullNode should the method do nothing?

What if the result of NullNode::getNext() is invoked? For instance,

NullNode x = ...;
NullNode w = x.getNext();
w.getNext(); // Grr, error!

In terms of rewriting this, I'm not sure abstracting nodes (with the null object pattern) is useful for doubly (or singly) linked lists. My gut leads me to believe that using the null object pattern for abstracting the data or elements of the list may work well.

class Data
{
    // interface for getter and setter
};
class BlankData : public Data
{
    // returns 0 for summing, 1 for multiplying, etc.
};
class IntegerData : public Data
{
    // returns value
};
class Node
{
    // typical pointer handling code
    Data element;
};


Given an integer array A and a range, find a subarray within the range with a minimum sum

Introduction
I have come up with a more efficient solution in terms of the time complexity, although it's still not passing all the test cases. Nevertheless, I decided to post the solution, because it may help someone with a similar problem in the future.
Explanation
The idea is to divide an initial array into segments of size √n, and for each segment to pre-calculate 4 helper arrays - sum of elements, minimum sum of elements, minimum prefix sum (minimum sum starting from the first element of the bucket) and minimum suffix sum (minimum sum ending at the last element of the bucket).
In such case, there are 3 possible use cases when calculating the min sum:

Sum range is within the same bucket. Then, to calculate the minimum subsum there, do it brute force.

Sum range starts in one bucket and ends in a neighbouring bucket. Again, do brute force.

Sum range covers more than 2 buckets. That's the hardest case, and that's what for all the additional arrays are built. The minimum sum in the range can happen to be a minimum subsum in some bucket, or a minimum prefix, or a suffix, or a sum of the min suffix and prefix (both buckets are in the range), or a sum of all elements in the current bucket and "special" sum from previous matching buckets. The "special" sum is either a min suffix from the preceding matching bucket or sum of elements starting from some min suffix. Please see the code for more details.

When a value is updated, all 4 helper arrays have to be updated too, and that is done in O(√n) time.
Code
import math
import sys

class MinSumRangeQuery:
    size = None
    array = None

    bucket_size = None
    bucket_sums = None
    min_prefix_sums = None
    min_suffix_sums = None
    min_subarray_sums = None

    def __init__(self, array):
        self.size = len(array)
        self.array = array

        self.bucket_size = int(math.sqrt(self.size))
        self.bucket_sums = [None] * (self.bucket_size)
        self.min_prefix_sums = [None] * (self.bucket_size)
        self.min_suffix_sums = [None] * (self.bucket_size)
        self.min_subarray_sums = [None] * (self.bucket_size)

        left = 0
        for i in range(self.bucket_size):
            right = left + self.bucket_size

            # sum of elements in a bucket
            self.bucket_sums[i] = sum(self.array[left:right])
            # calculate a min sum starting from the left position
            self.min_prefix_sums[i] = self.find_min_prefix(left, right)
            # calculate a min sum ending at the right position
            self.min_suffix_sums[i] = self.find_min_suffix(left, right)
            # calculate a min sum within the bucket
            self.min_subarray_sums[i] = self.find_min_subsum(left, right)
            left += self.bucket_size

    def find_min_prefix(self, left, right):
        min_prefix = self.array[left]
        current_prefix = min_prefix
        for i in range(left + 1, right):
            current_prefix += self.array[i]
            if current_prefix < min_prefix:
                min_prefix = current_prefix

        return min_prefix

    def find_min_suffix(self, left, right):
        min_suffix = self.array[right - 1]
        current_suffix = min_suffix
        for i in range(right - 2, left - 1, -1):
            current_suffix += self.array[i]
            if current_suffix < min_suffix:
                min_suffix = current_suffix

        return min_suffix

    def find_min_subsum(self, left, right):
        current_min_subsum = 0
        min_subsum = sys.maxsize

        for i in range(left, right):
            current_min_subsum = min(current_min_subsum + self.array[i],
                                     self.array[i])
            if current_min_subsum < min_subsum:
                min_subsum = current_min_subsum

        return min_subsum

    def find_min_in_range(self, left, right):
        current_bucket_id = int(left / self.bucket_size)
        end_bucket_id = int(right / self.bucket_size)
        current_right = min((current_bucket_id + 1) * self.bucket_size, right)

        current_min_subsum = self.find_min_suffix(left, current_right)
        min_sum = self.find_min_subsum(left, current_right)

        current_bucket_id += 1
        while current_bucket_id < end_bucket_id:
            min_prefix = self.min_prefix_sums[current_bucket_id]
            min_subsum = self.min_subarray_sums[current_bucket_id]
            min_suffix = self.min_suffix_sums[current_bucket_id]

            min_sum = min(min_sum, min_prefix + current_min_subsum)
            min_sum = min(min_subsum, min_sum)

            current_min_subsum = min(current_min_subsum + self.bucket_sums[current_bucket_id],
                                     min_suffix)
            min_sum = min(current_min_subsum, min_sum)

            current_bucket_id += 1

        current_left = current_bucket_id * self.bucket_size
        #if current_left < right:
        min_prefix = self.find_min_prefix(current_left, right)
        min_sum = min(current_min_subsum + min_prefix, min_sum)
        min_sum = min(self.find_min_subsum(current_left, right), min_sum)

        return min_sum

    def update(self, index, value):
        bucket_index = int(index / self.bucket_size)
        if bucket_index < self.bucket_size:
            self.bucket_sums[bucket_index] += (value - self.array[index])
        self.array[index] = value
        if bucket_index < self.bucket_size:
            left = bucket_index * self.bucket_size
            right = left + self.bucket_size
            self.min_suffix_sums[bucket_index] = self.find_min_suffix(left, right)
            self.min_prefix_sums[bucket_index] = self.find_min_prefix(left, right)
            self.min_subarray_sums[bucket_index] = self.find_min_subsum(left, right)

tests = int(input())

for i in range(tests):
    size = int(input())

    array = [int(i) for i in input().split()]

    minSumRangeQuery = MinSumRangeQuery(array)

    queries = int(input())

    for _ in range(queries):
        a, x, y = [int(i) for i in input().split()]
        x -= 1

        if a == 1:
            print(minSumRangeQuery.find_min_in_range(x, y))
        elif a == 0 and array[x] != y:
            minSumRangeQuery.update(x, y)

Algorithm Complexity
Time complexity of the algorithm is O(n√n), and space complexity is O(√n) because 4 arrays for each bucket have to be maintained.


There are a few things I would improve:

Clearly separate the three distinct phases:

Skip until the first index in the set
Copy/delete until we reached the last index
Copy the remainder until the end of the container is reached.

Have an outer loop that loops over the entries of set.
Use *foo++ syntax.
Use auto return type deduction.
Name things after their purpose, not what type they are. So instead of set, name it indices.

With this, the code would look like:
template <class T, class IdxT>
auto remove_indices(std::vector<T>& container, const std::set<IdxT>& indices)
{
    // Exit early if there is nothing to do.
    if (indices.empty())
        return container.end();

    auto destination = container.begin();
    auto source = container.begin();
    auto idx_it = indices.begin();

    // Skip until we reach the first index.
    std::advance(destination, *idx_it);
    std::advance(source, *idx_it + 1);

    // Delete all the elements at the given indices.
    while(++idx_it != indices.end()) {
        auto nextDelete = container.begin() + *idx_it;
        while(source < nextDelete)
            *destination++ = std::move(*source++);
        source++;
    }

    // Copy the remainder until the end of the container.
    while (source != container.end())
        *destination++ = std::move(*source++);

    return destination;
}

Also consider adding a test suite. And you might want to generalize this further to remove elements from other random access container types (for example, std::deque), and have it take the indices in other container types as well, as a std::set is quite an inefficient way to store a few integers.


Is this a good approach to loading JavaScript files asynchronously?

First of all, I would split you problem into 3 parts:

Loading a js-file asynchronously, and calling a callback-function
Loading several js-files an once asynchronously
Using an onload-Handler, which triggers everything

These are 3 independent parts, which might be reused for other purposes, if seperated correctly.

1. Loading a js-file asynchronously

You're using 2 strings to specify a file to be loaded. But instead of writing

["file.js", "cbFunction"]

you can as well also pass the actual function:

["file.js", cbFunction]

This not only ensures that the function actually exists, it also gives you the opportunity to use anonymous functions:

["file.js", function(){ alert("loaded!"); } ]

However, speaking of segregation of responsibilities, you should write a function on its own, without the need of an Array anymore:

function loadScript(path, scriptLoadedCallback){
    var element=document.createElement('script');    //generate <script>-tag
    element.setAttribute("type","text/javascript");
    element.setAttribute("src", path);

    if(typeof(scriptLoadedCallback) == 'function'){  //makes the callback-function optional
        element.onload = function() {
            return scriptLoadedCallback(true, path); //true = successfull; the path is needed later
        };
        element.onerror = function() {               //you might also call the cb on error
            this.parentNode.removeChild(this);       //remove faulty node from DOM
            return scriptLoadedCallback(false, path);      //false = error; the path is needed later
        };
    }
    document.head.appendChild(fileref);              //insert the node in DOM (end of <head>), and load the script
}

This function looks much clearer, and you can see at first glance what it is doing.

Note that I checked the existence of the callback before I append an onload-attribute. This is a bit more efficient than your code, which always calls the onload-Handler and then does nothing.

You might also want to add the onerror-method, otherwise you will never get notified if the loading failed (This usually happens if the js-file doesn't exist).

If you only have to load a single script, you can call this function directly. No need to generate useless Arrays.

2. Loading several js-files an once

If you only want to load several files, and calling a callback after each file, this is an easy task, using your original array (with functions instead of strings):

var filesToLoad = [
    ["file1.js", cbFunctionToCall],
    ["file2.js"]
];
for(var i=0; i<filesToLoad.length; i++){ //I prefer a for-loop because its more readable
    loadScript(filesToLoad[i][0], filesToLoad[i][1];
}

And that's all.

However, if you want to have one callback-function which is called after all files have been loaded, this gets a bit tricky. You don't know which file is the last one, and which file should trigger the actual callback-function.

function loadScriptArray(contentArray, contentLoadedCallback){
    var contentQuantity = contentArray.length;      //Number of Files that needs to be loaded
    var contentCompleted = 0;                       //Number of Files, that have already been loaded
    var returnParamList = {};                       //List with return-Parameters

    if(contentQuantity == 0){                       //We don't have anything to load
        return contentLoadedCallback({});
    }

    for (var i = 0; i < contentQuantity; i++) {
        loadScript(contentArray[i], function(success, path){   //This anonymous function is called everytime a script is finished
                                                               //The only way to know which script finished, is to pass the path as an parameter
            returnParamList[ identifier ] = returnParam;       //store the returnValue (true=success, false=error)
            contentCompleted++;
            if(contentCompleted == contentQuantity){    //this was the last file
                if(typeof contentLoadedCallback== 'function'){
                    contentLoadedCallback(returnParamList);
                }
            }
        });
    }
}

This is how the function is being called:

loadScriptArray(["file1.js", "file2.js"], function(returnParamList){
    alert("All Scripts finished. \n"+
          "File1: "+returnParamList["file1.js"]+"\n"+
          "File2: "+returnParamList["file2.js"]);
});

This function loads 2 files simultaneously, and calls the callback after the last one has been loaded. Afterwards it prints which files have been loaded successfully, and which loading-operation failed.

This only works, if the initial loadScript()-Function always calls the callback-Function - both if it succeeded or failed. And to report the success back to the caller, the callback-function also needs the filePath as an parameter.

Another advantage is, that you can extend this function to also load other files like images, json, xml and so on.

3. Trigger loading with onload

You code looks fine here, with only one very bad issue: Use brackets, they won't kill you.

There's absolutely no reason to omit brackets, it's just a possible source for annoying errors, which are very hard to be found.


Add two numbers represented by linked lists

few notes on your implementation:

if(data>9){
            carry=1;
            Node tempNode = new Node(data%10);
            tempNode.setNext(res);
            res = tempNode;
        }else{
            carry=0;
            Node tempNode = new Node(data);
            tempNode.setNext(res);
            res = tempNode;
        }

can be rewritten as

 carry=data/10;
 Node tempNode = new Node(data%10);
 tempNode.setNext(res);
 res = tempNode;

findSum(Node l1, Node l2, int diff)

you call int length1 = findLength(l1);int length2 = findLength(l2); in every recursive call. It's enough to call it once, before you enter the recursion. The result won't change in the middle. it'll reduce the complexity of your solution from O(N^2) to O(n)
All you need to do afterwards is decrement the value of diff until it becomes 0

I would rewrite the whole method as follows:

private static Node findSum(Node longer, Node shorter, int diff){
    if(diff==0){
         Node res = findSumForListOfSameSize(longer, shorter);
         return res;
    }
        Node res = findSum(longer.getNext(), shorter, diff--);
        int data = longer.getData() + carry;

        carry=data/10;
        Node tempNode = new Node(data%10);
        tempNode.setNext(res);
        res = tempNode;

        return res;
}

and the main would become

...
int length1 = findLength(l1);
int length2 = findLength(l2);
int diff = length1-length2;
if(diff<0){
    diff = diff * -1;
    Node res = findSum(templ21, templ11, diff);
}else{
    Node res = findSum(templ11, templ21, diff);
}
...

you could remove the need for static variable carry by doing this:

Node res = findSum(longer.getNext(), shorter, diff--);
int prevSum = res.getData()
int carry = prevSum / 1;
res.setData(prevSum % 10)

int sum = longer.getData() + carry;
Node tempNode = new Node(sum);

you're 'delegating' the calculation of the carry (and update of the vaue) to the next digit calculation). Also note, I renamed the data variable to be prevSum and sum


Using Python to rename multiple csv files in Windows

Here are my thoughts:

You don't do any error handling if any of the file operation fails. Not to be recommended
Your code will flip the latter two parts, all the time. It does not care if the filename has already been fixed or not!
The code name + [name.pop(0-2)] troubles me. You are concatenating the name list with the popped value, but in order for this work you need for the popping to happen before the first part to be joined. Scary stuff...
Here are some pythonic ways to do stuff with lists:

name[:-2] – Get everything but the two last elements
name[-2:] – Get only the last two elements
name[::-1] – Reverse the element list

Here is some coding displaying the flaw in your original rename code, and two options for how to handle it correctly.

for filename in (
                 'billing.pps-svr01.2014-09-01.csv',
                 'billing.pps-svr02.2014-09-01.csv',
                 'billing.pps-svr01.csv.2015-09-01',
                 'billing.pps-svr02.csv.2015-09-01',
                ):

    print('\nTesting {}:'.format(filename))

    name = filename.split('.')
    name = name + [name.pop(0-2)]
    new_name = '.'.join(name)

    print '    old rename: {} to {}'.format(filename, new_name)

    filename_parts = filename.split('.')
    first_part = filename_parts[:-2]
    last_part = filename_parts[-2:]

    if last_part[-1] != 'csv':
        new_name = '.'.join(first_part + last_part[::-1])
        print '    new rename: {} to {}'.format(filename, new_name)
    else:
        print '    no rename needed'

    if filename_parts[-2] == 'csv':
        new_name = '.'.join(filename_parts[:-2] + filename_parts[-2:][::-1])
        print '    alt rename: {} to {}'.format(filename, new_name)
    else:
        print '    no alternate rename needed'

The output from this are as follows:

Testing billing.pps-svr01.2014-09-01.csv:
    old rename: billing.pps-svr01.2014-09-01.csv to billing.pps-svr01.csv.2014-09-01
    no rename needed
    no alternate rename needed

Testing billing.pps-svr02.2014-09-01.csv:
    old rename: billing.pps-svr02.2014-09-01.csv to billing.pps-svr02.csv.2014-09-01
    no rename needed
    no alternate rename needed

Testing billing.pps-svr01.csv.2015-09-01:
    old rename: billing.pps-svr01.csv.2015-09-01 to billing.pps-svr01.2015-09-01.csv
    new rename: billing.pps-svr01.csv.2015-09-01 to billing.pps-svr01.2015-09-01.csv
    alt rename: billing.pps-svr01.csv.2015-09-01 to billing.pps-svr01.2015-09-01.csv

Testing billing.pps-svr02.csv.2015-09-01:
    old rename: billing.pps-svr02.csv.2015-09-01 to billing.pps-svr02.2015-09-01.csv
    new rename: billing.pps-svr02.csv.2015-09-01 to billing.pps-svr02.2015-09-01.csv
    alt rename: billing.pps-svr02.csv.2015-09-01 to billing.pps-svr02.2015-09-01.csv

Notice how the two first files would have gotten a wrongly rename use your original code.

Code refactor (added)

To accomodate for your question regarding building this into a larger script, and to give example of error handling, I've refactor your code into the following (using the tip from Janne Karila on using rsplit):

import os

def rename_csv_files(directory, required_start):
    """Rename files in <directory> starting with <required_start> to csv files

    Go to <directory> and read through all files, and for those
    starting with <required_start> and ending with something like
    *.csv.YYYY-MM-DD and rename these to *.YYYY-MM-DD.
    """
    try:
       os.chdir(directory)
    except OSError, exception:
       print('IOError when changing directory - {}'.format(exception))
       return

    try:
        for filename in os.listdir('.'):
            if filename.startswith(required_start):

                base, ext, date = filename.rsplit('.', 2)
                new_filename = '.'.join((base, date, ext))
                if ext == 'csv' and not os.path.exists(new_filename):
                    try:
                        os.rename(filename, new_filename)
                        print 'Renamed: {}'.format(new_filename)

                    except OSError, exception:
                        print('Failed renaming file - dir: {}, original file:  {}, new file: {} - {}'.format(
                              directory, filename, new_filename, exception))

                elif ext != 'csv':
                    print('Skipped: {}'.format(filename))

                else:
                    print('Skipped: {} - Renamed version already exists'.format(filename))

    except OSError, exception:
        print('Failed traversing directory - dir: {} - {}'.format(directory, exception))

def main():
    rename_csv_files('./test_data', 'billing.pps-svr')

if __name__ == '__main__':
    main()

Running this script against the following test-data:

$ ls -1d test_data/* | sort -n
test_data/billing.pps-svr01.2014-09-01.csv
test_data/billing.pps-svr01.csv.2015-09-01
test_data/billing.pps-svr02.2014-09-01.csv
test_data/billing.pps-svr02.2015-09-01.csv
test_data/billing.pps-svr02.csv.2015-09-01
test_data/original_files.tar

Gives the following output:

Skipped: billing.pps-svr01.2014-09-01.csv
Renamed: billing.pps-svr01.2015-09-01.csv
Skipped: billing.pps-svr02.2014-09-01.csv
Skipped: billing.pps-svr02.2015-09-01.csv
Skipped: billing.pps-svr02.csv.2015-09-01 - Renamed version already exists

This code now handles error handling for at least the following cases:

Directory not existing, or read or execution permission faults
Errors when traversing directory or renaming files
The logical error of renaming a file into an already existing file


Synchronous and asynchronous behavior for client

Late answer to this question.....

There are a few things which should be considered when implementing a solution like this, and best-practice comes in to play here.

  One nit-pick ... before we go further, your interface the methods
  executeAsynchronous and executeSynchronous, whereas your
  implementation has executeAsync and execute. This is a carelessly
  posted question?

What you have, at the moment, works, but is it the best way? I don't think so.

You code has a few features that are important:

executeSynchronous() - waits until you have a result, returns the result.
executeAsynchronous() - returns a Future immediately which can be processed after other things are done, if needed.
it has a private getHandle() method which does the hard work of creating a Callable, and returning a future.

Now, I have tried to list why there are problems with this, but, it's easier to actually show you a different approach, and explain why it is better.... so, here's a different approach, which reverses the logic.

First thing, we are going to make the interface a generic interface... why does it always have to return a String value for each URL? Also, why is it a Client? It is not really a client, but it is a RemoteCall. This is not the full Client, but a part of what it does when it talks to the server.... so, let's rename the Client interface, and make it generic.... Also, while we are at it, you need to declare that you throw some form of exception... my preference is for a new checked exception type, but maybe you can borrow an existing exception. What you have is not best-practice. Here's a decent exception to throw:

class RemoteCallException extends Exception {

    private static final long serialVersionUID = 1L;

    public RemoteCallException(String message, Throwable cause) {
        super(message, cause);
    }

    public RemoteCallException(String message) {
        super(message);
    }

}

Then, with that exception, we can complete the interface:

public interface RemoteCall<T> {

    // for synchronous
    public T executeSynchronous(final String action) throws RemoteCallException;

    // for asynchronous
    public Future<T> executeAsynchronous(final String action);
}

Right, this interface is now a better representation of the work it is supposed to do.

Now, here's a key feature I want you to consider.... at the moment, you may only have one 'action' you need to execute on the server, the part of translating a userid in to a JSOM response. But, I expect there is, or will be, more. Having to build a new implementation for your Client interface for every type of operation is a real PITA, especially when it requires building a new Callable / Task instance.... so, what we do is we create a convenient abstract class, which will do all the synchronous/asynchronous work for us....

Note, it does not implement executeSynchronous(), and it is still fully generic. It uses an executor service that is passed in.

One of the really huge advantages of reversing the logic (there is no Callable involved in the synchronous call) is that the work is done on the calling thread. In your implementation, you have two threads fully occupied, the calling thread waits for work to be done, and a thread in the ExecutorService is actually doing the work. By making the executeSynchronous() call the way I suggest, only one thread is occupied, and the thread that is busy is the same thread that calls executeSynchronous()

public abstract class AbstractRemoteCall<T> implements RemoteCall<T> {

    private final ExecutorService executor;

    public AbstractRemoteCall(ExecutorService executor) {
        this.executor = executor;
    }

    // note, final so it cannot be overridden in a sub class.
    // note, action is final so it can be passed to the callable.
    public final Future<T> executeAsynchronous(final String action) {

        Callable<T> task = new Callable<T>() {

            @Override
            public T call() throws RemoteCallException {
                return executeSynchronous(action);
            }

        };

        return executor.submit(task);
    }
}

OK, so, the above class deals with any asynchronous method calls, and delegates the synchronous calls to the actual implementations.

Now we get to your actual implementation you want to do, the userid -> JSON transformation. It is now as easy as:

public class SmartClient extends AbstractRemoteCall<String> {

    public SmartClient() {
        super(Executors.newFixedThreadPool(5));
    }

    @Override
    public String executeSynchronous(String userId) throws RemoteCallException {

        String url = createURL(userId);

        // make a HTTP call to the URL
        RestTemplate restTemplate = new RestTemplate();

        return restTemplate.getForObject(url, String.class);

    }

    // create a URL
    private String createURL(String userId) {
        String generateURL = somecode;

        return generateURL;
    }
}

The advantages of all these changes are:

the abstract class is the only place you need to worry about threading
in a synchronous call, the work is done on the calling thread
there is a better mechanism for error handling with the new RemoteCallException.
you can now have many different implementations of the abstract class, each implementation does their own type of restful work, and you don't need to worry about the threading in any of them.
the actual working classes (like SmartClient) do one thing, and one thing only.

There are other advantages.... but, what you have now, though it works, is not nearly as maintainable, extensible, and reliable as what it could be.

EDIT: Some use-cases

How would the code I recommend be used? Two situations.... Synchronous

// set up some system, need the JSON data
SmartClient sc = new SmartClient();
String json = sc.executeSynchronous(userid);

Collecting data asynchronous:

// Set up a number of things, timing can be in parallel.
try {
    SmartClient sc = new SmartClient();
    Future<String> jsonfut = sc.executeAsynchronous(userid);
    // set up some other things.
    // perhaps some thing that gets other data....
    //   this is a different class just like the SmartClient that can be asynchronous
    DataCLient dc = new DataClient();
    Future<String> defautsfut = dc.executeAsynchronous("getdefaults");
    Future<String> messagesfut = dc.executeAsyncrhonous("messages");
    String json = jsonfut.get(500, TimeUnit.MILLISECONDS);
    String defaults = defaultsfut.get(); // no timeout
    String messages = messagesfut.get(); // no timeout
} catch (TimeoutException te) {
    // handle appropriately
}


Assembling a user agent descriptor, implemented using StringBuilder vs String

For a method like this, don't worry about performance until you have evidence that performance is a problem. Either way will almost certainly be fast enough.

I would suggest instead for readability that you separate the data (key-value pairs) from the construction of the string.

If the order of the pairs is not important, you can write

var data = new Dictionary<string, string>
{
    { "device-type", "mobile" },
    { "os", "Windows Phone" },
    ...
};
return string.Join(";", data.Select(kvp => kvp.Key + "=" + kvp.Value));

If order is important, use the slightly more verbose

var data = new[]
{
    new KeyValuePair<string, string>("device-type", "mobile"),
    new KeyValuePair<string, string>("os", "Windows Phone"),
    ...
};
return string.Join(";", data.Select(kvp => kvp.Key + "=" + kvp.Value));


Your class can absolutely be considered like a DDD domain entity.
However, I would suggest some improvements:

DDD likes to use an ObjectValue for the unique identifiers, you could use one instead of a simple integer.
You could separate the validation logic from the entity (not specific to DDD).
You should not have a getPassword() method but a verifyPassword($password) instead. Don't expose the password in plain text.
You could also separate the stringLength() into its own string utility class.
Regarding the use of a Uniw timestamp, keep in mind that DateTime is a better option since it embeds the time zone. Timestamps don't, which is always confusing when handling dates from all over the world...


Select top 2 employees based on Grade and Alphabetical Order

About performance

As a forewords, I'm not sure you should be obsessed with performance as a beginner (actually I'm pretty sure you should not but surely others will disagree).

Consider reading : https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil

With that said...

In the Employee class :

As said by coderodde, your compareTo can't be made faster.

In the EmployeePicker class :

PriorityQueue isn't made with performance in mind.
Seeing your code there is no point in using this class over a TreeSet and I'd really recommend using a TreeSet over anything else.

If you really are obsessed with performance, PriorityQueue may outperform a TreeSet when you have over 20_000 elements for your specific use case.

However, if you are really really obsessed with performance and you know all the employees as soon as the program starts (and then only have to retrieve some of them after that) then you should consider using an array that you sort once... it'll also be the most space-efficient solution of the three.

With less than a hundred elements, I'm pretty sure you can consider all solutions equals in performance.

Conclusion : IMO use TreeSet unless you have good reasons not to :)

About code format

You should make the fields of Employee private and final and create getters for them. When a method have multiple parameters, you should always follow the comma with a space (makes code more readable).

The indentation in compareTo is really confusing.


If these parameters may not always be lowercase,
then I don't think there's a better way.

However, if you have many callers that are guaranteed to use lowercase parameters,
and it's a pity to call .lower() for those,
then you could split this into 2 functions:

One for callers that are guaranteed to use cleaned parameters (lowercased parameters)
One for untrusted callers

For example:

def _get_revenue(self, metric, product, platform):
    # get adjustment for product.platform, multiply by metric
    if product not in self.adjustments:
        raise Exception('Unknown adsense product: {}'.format(product))

def get_revenue(self, metric, product, platform):
    self._get_revenue(metric, product.lower(), platform.lower())

In the examples I used snake_case naming for method names,
as recommended by PEP8.

By the way it seems a bit odd that the function name starts with "get" but it doesn't return anything.

Without seeing the full code,
I don't see a reason to object against the use of self.adjustments.
Whether it's objectionable or not really depends on the rest of the code.

Something to object against though is the platform param which is not used by this method.
Ideally it shouldn't be there at all.


Well, it seems to be ok, a simple unit test prove it works.

However, using such private exceptions is not a good idea because nobody can catch them. You should also use the CamelCase name for those exceptions and maybe provide more context information to those exceptions.


Drawing random smooth lines contained within a square

Random walks "wander all around" by definition. So you have to twist the odds of the walk staying in the area you want.

It would be much simpler if you'd just make an attractor point at the center, that would move each point infinitesimally (some floating point value between 0 to 1 or sqrt(2) pixels) towards itself at each step.

Another option would be to make the edges exponentially hard to reach. I'm thinking of an Exponential_map with a really steep slope at the edges and otherwise near linear curve. also see Gamma curve. So essentially map an "infinite" area to the restricted space.

Third option would be to think about how magnetism works. I mean, a magnet can't be any more magnetized to a certain direction after all it's particles are magnetized towards that direction. And the magnetization takes exponentially stronger field all the way towards that state. I've written a "tape compression" algorithm with Numpy using that idea.


Your regex looks complicated. What's more, it doesn't work:

$ cat fortune | sed -r 's/^[/|\\]\s?([-A-Za-z ()!,?".;'$a']*)[/|\\]?/\1/'
Abou Ben Adhem (may his tribe increase!)
Awoke one night from a deep dream of peace,
And saw, within the moonlight in his room,
Making it rich, and like a lily in bloom,
An angel writing in a book of gold.
Exceeding peace had made Ben Adhem bold,
And to the presence in the room he said,
"What writest thou?"  The vision raised its head,
And with a look made of all sweet accord,
Answered, "The names of those who love the Lord."
"And is mine one?" said Abou. "Nay not so,"
Replied the angel.  Abou spoke more low,
But cheerly still; and said, "I pray thee then,
Write me as one that loves his fellow-men."
The angel wrote, and vanished.  The next night
It came again with a great wakening light,
And showed the names whom love of God had blessed,
And lo!  Ben Adhem's name led all the rest.                 |
                -- James Henry Leigh Hunt, "Abou Ben Adhem"

See this stray | in the second line from the bottom? Honestly, I didn't analyze why your regex doesn't work because, as I said, it looks horribly complicated. But, first of all, cat is not necessary here because most of sed implementations - GNU, busybox, BSD can operate on a file directly and some of them even take i parameter which makes sed modify a file in place. That being said, here's how I would do it:

$ sed -r 's,^(/|\||\\) ,,g' fortune | sed -r 's,(\\|\|)$,,g'

I tested it with GNU sed 4.2.1 and with busybox version of sed on OpenWRT. The only thing that I don't like about it is usage of -r. There may be some basic sed implementations that don't implement extended regular expressions but they should be very rare.

EDIT:
No chaining with perl:

$ perl -pe 's,^(/|\||\\) (.+?)(\\|\|)?$,\2,' fortune


Few things:

You can create a plugin out of it (create divs #slider and #slides - don't use id, but just reference - and add class slider_wrap in code)
You don't put var before nextImg = new Image();
Instead of new Image you can use jQuery:

$('<img/>').attr('src', path).appendTo($("#slides"));
Instead of $('span.next') use elWrap.find('span.next') because it will not work if span.next is somewhere in the html.
Is always better ot use jQuery not native function because they may be different from browser to browser. So use $(window).scroll(function() { }) $(window).innerHeight() and $(window).scrollTop();
Inside newimg you call $("#slides") you can call that before a function and store it's value in variable.


Docstrings

You should include a docstring at the beginning of every method, class, and module you write. This will allow any documentation to identify what your code is supposed to do. Pulling from GeeksforGeeks, this is what a docstring should be:

What should a docstring look like?

The doc string line should begin with a capital letter and end with a period.
The first line should be a short description.
If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
The following lines should be one or more paragraphs describing the object’s calling conventions, its side effects, etc.

ClassNamingShouldBePascalCase

Class names should normally use the CapWords convention. The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable. Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants. [source]

In your case, you have a class named connect4. This does not conform to PEP-8 standards. It should instead be ConnectFour.

Variable Naming

You variable names should be descriptive and thoughtful enough for you to understand what that variable is holding. In your test file, you use b as the variable to hold your connect4 object. If you end up writing a larger program from this, how will you remember b is the game? What if you decide to use c, d, e, etc? Then you end up with variable names spanning the entire alphabet. This is become confusing very fast. Changing b to game makes it very clear that that's the game object.

Accessor Method Naming

Having accessor and mutator (getters and setters) methods aren't really common in python, at least not as much as in java or c#. When dealing with accessor methods, the name should be get_...(). This makes it clear that you're getting the thing from the object you're calling it on. For example, get_board() as opposed to return_board(). Not convinced? Consider this:

...
if b.get_board() is not None:
    do_stuff()
...

...
if b.return_board() is not None:
    do_stuff()
...

In this context, which is what you're using, it seems like return_board is returning a boolean, True or False, if the board was "returned successfully". get_board makes it clear that you're getting a board.

Unnecessary accessor methods

On the subject of get_board(), the whole method is unnecessary. In fact, all of the get_...() are unnecessary, but some of them are there so the code isn't all messy. Which I can appreciate. However, the get_board() is not needed. Just do game.board instead of game.get_board().

enumerate vs range(len())

Many python beginners, whether they be coming from other languages like C, or brand new to programming, inevitably go through a phase where they try to do the same thing.

This results in things like this:

for i in range(len(sequence)):
    print(sequence[i])

This is never the right answer.  In python we have the power and ability to loop directly over the items in a sequence.

We can instead do this:

for item in sequence:
    print(item)

It is simpler to type; simpler to read; and most importantly makes more sense.  As we were never concerned with the index to begin with, we don't need to bother with it.

There are however cases in which one does want the index as well as the item.  In such cases enumerate is the tool of choice.

Our loop becomes:

for i, item in enumerate(sequence):
    print("{} : {}".format(i,item)

In short, if you ever catch yourself writing range(len(...)) rethink your goal and figure out what it really is you are interested in. You can apply this principle to your code.

is not vs !=

This StackOverflow answer explains this amazingly:

== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.

_ for unused loop variables

_ has 4 main conventional uses in Python:

To hold the result of the last executed expression(/statement) in an interactive
interpreter session. This precedent was set by the standard CPython
interpreter, and other interpreters have followed suit
For translation lookup in i18n (see the
gettext
documentation for example), as in code like:
raise forms.ValidationError(_("Please enter a correct username"))
As a general purpose "throwaway" variable name to indicate that part
of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:
label, has_label, _ = text.partition(':').
As part of a function definition (using either def or lambda), where
the signature is fixed (e.g. by a callback or parent class API), but
this particular function implementation doesn't need all of the
parameters, as in code like: callback = lambda _: True

(For a long time this answer only listed the first three use cases, but the fourth case came up often enough, as noted here, to be worth listing explicitly)

The latter "throwaway variable or parameter name" uses cases can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

Use i / j for double loops

This one is my opinion / possibly a common practice. When using two nested for loops, I like to use i and j as the outer and inner loop variables, respectively. i and j have typically been used as subscripts in quite a bit of math for quite some time (e.g., even in papers that predate higher-level languages, you frequently see things like "Xi,j", especially in things like a summation). Most people seem to have seen little reason to change that.

Multiple anonymous array checks

You have this code:

...
for i in range(self.height):  # check rows
    for x in range(self.width - 3):
        if self.get_row(i)[x:x + 4] in [['0', '0','0', '0'], ['1', '1', '1', '1']]:
            return self.board[i][x]
for i in range(self.width):  # check columns
    for x in range(self.height - 3):
        if self.get_column(i)[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
            return self.board[x][i]
for i in self.get_diagonals():
    for x in range(len(i)):
        if i[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
            return i[x]
...

You create the anonymous array [['0', '0', '0', '0'], ['1', '1', '1', '1']] three times! Instead of this repetition, you should assign this array to a variable, and check against that variable. The updated code reflects these changes.

'' => ' ' formatting

You have a couple of formatting problems when outputting the board to the console. When there's a column a couple stacks high in the middle of the board, it does this:

['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '1', '', '', '', '', '']
['0', '1', '', '', '', '', '']
['0', '1', '0', '', '', '', '']

Even after just one input, it gets shifted:

['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['', '', '', '', '', '', '']
['0', '', '', '', '', '', '']

You should allocate this space in the beginning. In __init__, self.board should look like this:

self.board = [[' ' for x in range(width)] for i in range(height)]

and make_move(self, team, col) should now look like this:

def make_move(self, team, col):
    """
    Simulates a move and puts a 0/1 in the specified column
    """
    if ' ' not in self.get_column(col):
        return self.board
    i = self.height - 1
    while self.board[i][col] != ' ':
        i -= 1
    self.board[i][col] = team
    return self.board

Updated Code

"""
Module Docstring
A description of your program/class goes here
"""

class ConnectFour:
    """
    Class for creating a connect four game
    """
    def __init__(self, height=6, width=7):
        self.height = height
        self.width = width
        self.board = [[' ' for x in range(width)] for i in range(height)]

    def get_column(self, index):
        """
        Returns a column at the specified index

        :param index: Index at which column will be returned
        """
        return [i[index] for i in self.board]

    def get_row(self, index):
        """
        Returns a row at the specified index

        :param index: Index at which row will be returned
        """
        return self.board[index]

    def get_diagonals(self):
        """
        Returns all the diagonals in the game
        """

        diagonals = []

        for i in range(self.height + self.width - 1):
            diagonals.append([])
            for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):
                diagonals[i].append(self.board[self.height - i + j - 1][j])

        for i in range(self.height + self.width - 1):
            diagonals.append([])
            for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)):
                diagonals[i].append(self.board[i - j][j])

        return diagonals

    def make_move(self, team, col):
        """
        Simulates a move and puts a 0/1 in the specified column
        """
        if ' ' not in self.get_column(col):
            return self.board
        i = self.height - 1
        while self.board[i][col] != ' ':
            i -= 1
        self.board[i][col] = team
        return self.board

    def check_win(self):
        """
        Checks self.board if either user has four in a row
        """

        four_in_a_row = [['0', '0', '0', '0'], ['1', '1', '1', '1']]

        #Check rows
        for i in range(self.height):
            for j in range(self.width - 3):
                if self.get_row(i)[j:j + 4] in four_in_a_row:
                    return self.board[i][j]

        #Check columns
        for i in range(self.width):
            for j in range(self.height - 3):
                if self.get_column(i)[j:j + 4] in four_in_a_row:
                    return self.board[j][i]

        #Check diagonals
        for i in self.get_diagonals():
            for j, _ in enumerate(i):
                if i[j:j + 4] in four_in_a_row:
                    return i[j]

        return None

def start_game():
    """
    Starts a game of ConnectFour
    """
    game = ConnectFour()

    while True:

        for i in game.board:
            print(i)
        if game.check_win() is not None:
            break

        col = int(input('Team 0 choose column: ')) - 1
        game.make_move('0', col)

        for i in game.board:
            print(i)
        if game.check_win() is not None:
            break

        col = int(input('Team 1 choose column: ')) - 1
        game.make_move('1', col)

    print('Thank you for playing')

if __name__ == '__main__':
    start_game()


Filling A Linked List With Data From File And Handling User Status Messages

The first thing that strikes me is that you're writing error and status messages to the standard output stream, when usually these go to stderr, the standard error stream.

I'm not sure it makes much sense to attempt to create an empty file if the file opening fails - why not leave this until it's time to save?  What if the reason it failed is because the file doesn't have read permission for the process?  And how do you know whether creating a new file succeeded or not?

I'd argue that it's better to return a null pointer if the file opening fails, so that client code can distinguish this from a successful load of an empty list:

if (f == NULL)
{
    /* NULL return signifies nothing could be read */
    return NULL;
}

studentList *list = newList();

I'm assuming newList() is an allocation function that returns a null pointer if the allocation fails; that means we shouldn't attempt to use it until we've checked it's a valid pointer.

while (!eof) is a common anti-pattern; what we want to do instead is more like while (fscanf(...)==2) - and that removes the need to measure the file size before reading the contents.

This line is clearly wrong

    fflush(f);

f is an input stream, so fflush(f) is Undefined Behaviour.  Just remove this call.


You can use a for-each iterator instead of using indexes.
It would be somewhat simpler, like this:

Edge previous = edges.get(nodeList.size() - 1);
for (Edge edge : edges) {
    edge.previous = previous;
    previous.next = edge;
    previous = edge;
}

Suppose the initial list of edges is not in an ArrayList which allows quick random access but another kind of iterable. Then, you could rewrite this way without accessing any element by index:

Iterator<Edge> iter = edges.iterator();

Edge first = iter.next();
Edge previous = first;
Edge edge = null;

while (iter.hasNext()) {
    edge = iter.next();
    edge.previous = previous;
    previous.next = edge;
    previous = edge;
}

if (edge != null) {
    edge.next = first;
    first.previous = edge;
}


Filling text boxes with player names received from an array

We can do better still.

First of all, we're talking about a UITableViewCell to which you've added custom views--or at least modified existing views (hence the tags) as well as adding a gesture recognizer.

What makes most sense is to instead subclass UITableViewCell.  This would help both to clean up the method you have posted here as well as clean up the cellForRowAtIndexPath: which I'm sure is a bit of a mess.

Then, you would no longer need to iterate through all of the content view's subviews.  Instead, best case scenario, you only have a single text field on the cell, and you can access it directly, and switch on its tag, and at worst, you can create a custom IBCollection--an array of text fields--that would be relevant to this method and iterate over just that (which you know would contain only text fields relevant to this method) looking at the tags.

int index = [txtField tag]-offsetIndex;
if (tag >= 6 && tag <= 11)
{
    if (needCustomNames)
        textField.text = [names objectAtIndex:index];
    else
        textField.text = [defaultNames objectAtIndex:index];
}

This chunk of code is confusing.

First of all, tag isn't declared anywhere.

Second of all, presuming the if is supposed to be checking textField.tag, you should either move the int index line inside the if block, or probably better, refactor the if to check the index that was just calculated based on textField.tag and is the value actually used inside the if block.  As it stands, this code might crash if someone unknowingly changes the offsetIndex 7 lines previously and that might be a hard crash to figure out.

I think there's some more cleanup to do, but I'm kind of interested in seeing whether you'd be interested in posting a new question where you've rewritten the code to use a UITableViewCell subclass, which truly would be the best option.


Verifying password strength using JavaScript

Dislcaimer: I'm not a security researcher and the following answer is compiled from my own, humble knowledge. The math is very basic and there are many things to consider, if in doubt, pay Security a visit. Also there are many factors that can kill password security completely, for example the user themselves or social engineering.

In this case I'm not reviewing the code, but I'm reviewing your program logic.

A short talk about password security

Let's first define the rules you use (the term "special chars" here for further on refers to the set !@#$%^&*?_~-()):

Password length > 6: 1 Point
Password length > 12: 1 Point
Password contains at least one lower and one upper case letter: 1 Point
Password contains at least one digit: 1 Point
Password contains at least one of the special chars: 1 Point

Your scale goes from 0 (Very Weak) to 5 (Strongest). That means a password based on length can never go beyond 2 (Better), but a short password can be 4 (Strong). This is bad if we keep in mind that strong passwords do not necessarily use a broad character set.

The following passwords are considered Strong by your algorithm:

abcdE$1
qwert!1
1111Aa@

Now these do not look like strong ones to me, let's have a look at how many possible combinations such a password has. The total character set for these passwords is 26 (lower) + 26 (upper) + 10 (digits) + 14 (special) = 76.

  76^7 = ~1.4 * 10^13 = ~14 trillion

So an attacker which knows the character set and the length of the password, has to search roughly 14 trillion combinations until they find the password. Though, that is the worst case scenario, could be that they find it on the third try, but could be that it is the next to the last. Todays computers can do more then 500 million guesses per second, that's roughly 8 hours...this can not be considered secure in any way.

Let's have a look at the other side of the spectrum, the following password is only considered Better:

  thisisaverylongpasswordbecause (This is a very long password because)

It only has a character set of 26 and a length of 30 (the maximum for your system if I've seen this correctly).

  26^30 = ~ 2.8 * 10^42 = ~2.8 tredecillion

I have no idea what that number is supposed to mean, so let's compare it. Okay, that doesn't help either...maybe if we put it into a timeframe, 500 million guesses per second again:

  ~1.8 * 10^26 years

That's actually good news! That's well before the heat death of the universe.

So, less nonsense, more talk: What's going on here?

The strength of a password can not reliable be defined. But we know two things:

The longer it is, the more combinations you have to go through.
The more different characters it uses, the more combinations you have to go through.

The difference is that one adds to the base, and the other to the exponent. A higher exponent weighs in heavier than a higher base and yields more total combinations. So whenever possible use a passphrase instead of a password.

Despite being, seemingly, vulnerable to dictionary attacks, the Oxford Dicitonary holds 300 thousand main entries, so if we have a passphrase of 4 words, that's:

  300000^4 = 8.1 * 10^21

And that does not take into account possible misspellings, if the words start uppercase, lowercase or mixed and different languages.

Make the users favor passphrases and long, easier to remember passwords then complicated short ones.

Sell it as a feature!

This will make your marketing department happy, you just implemented support for the more secure passphrases into your software! Let your users know about it by simply adding a short information to the password box:

  We support passphrases up to a length of XX characters!

  Passphrases are more secure and easier to remember than ordinary passwords.

And some short information about how to "create" one, and drop any indicator if the password is secure or not.

Who you can and can't help

There are quite many user groups out there, the question is who you want to reach with this help. Let's define three groups:

The "average user", which does not understand why they need to press a button labeled "Delete" to delete something.
The normal user, always ready to learn and looks beyond their own nose.
The technical user, already uses a password manager and/or passphrases.

No matter how hard you try, you will not be able to help the "average user". If you tell them to use a password of minimum length 6, they will use "123456" or "asdfgh". If you tell them to use a password of minimum length 12, they will use "asdfghjkzxcvbn" or "000000000001". They are beyond hope and will actively workaround security measures you implement. Just let 'em be.

The "normal user" on the other hand is ready to learn something new, telling them about passphrases and that you support them will make them want to use passphrases. If your small help text and the rest of the system in that moment is helpful, they will use a passphrase which is not something absolutely stupid.

The "technical user" will be pleased that you support a XX length password and passphrases. They most likely already use a strong and random password and a password manager or passphrases, but that you don't limit them in any way will make them happy.

Secure passwords stored insecure are insecure

It doesn't matter how good the password or passphrase is, if you fail to store in a secure manner, they are insecure.

We will completely leave out social engineering or "harmful" users (there are people after all who have their creditcard PIN on a note in the same wallet), we can't help them.

But what is important that if somebody manages to break into your server and manage to copy the user database, they must not have access to all accounts. This is achieved by simply hashing the passwords with an appropriate method. Even if the attacker now has all the usernames and e-mail addresses, the passwords are still safe.

It will also make the marketing department happy that, despite you've been hacked, they can tell the users that their accounts are still safe (password change advised, obviously).

The great news is, if you hash the passwords there's absolutely no reason to limit password length at all! They will all end up as the same length hash in your database, so you can let me use that sentence from that book as a passphrase.

Ask the right people the right questions

Last but not least, defining what is a strong password depends on many things. If in doubt, pay the people over at Security a visit, that's what they're there for.


LW, MTD, STD, YTD Sales... all in line and looking pretty

I think your problem is do with the amount of cartesian products you are forming. I would approach something like this, as I alluded to in chat:

with salesYTD as (
    SELECT SalesPerson, InvoiceDate, Sum(Amount) As AmountOnDay
    FROM sales
    WHERE InvoiceDate > DATEADD(year, DATEDIFF(year, 0, GETDATE()), 0)
    GROUP By SalesPerson, InvoiceDate
),
calculatedYTD as (
    SELECT SalesPerson, SUM(AmountOnDay)
    FROM salesYTD
    GROUP BY SalesPerson
),
calculatedMTD as (
    SELECT SalesPerson, SUM(AmountOnDay)
    FROM salesYTD
    WHERE InvoiceDate >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
    GROUP BY SalesPerson
)
-- etc
SELECT *
FROM calculatedYTD ytd
LEFT JOIN calculatedMTD mtd ON ytd.SalesPerson = mtd.SalesPerson

I realise the above is not the same code as you posted, trying to show a basic principal, will expand if you want, just shout in comments

But the basic principle is:

Perform the expensive operation once, specifically the one with the biggest date range (YTD)
Perform the rest of the calculation from the result of the first one (its already filtered)

But there are a few things you can do, to which I have made the assumptions above, assuming:

YTD means the beginning of the year
MTD means the beginning of the month... etc...

you can:

Do away with the calculation functions (they are expensive compared to...)
Calculate your YTD as DATEADD(year, DATEDIFF(year, 0, GETDATE()), 0)
Calculate your MTD as DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)

I haven't run it, but I suspect that it will give you far better IO/performance. Let me know if it helps...


Sum of squares of 2 largest numbers out of a list of 3 numbers

Specification

It is helpful to specify the solution before writing code. The mathematics of sorting three values (a b c) means there are six (3!) permutations:

(define abc (a b c))
(define acb (a c b))
(define bac (b a c))
(define bca (b c a))
(define cab (c a b))
(define cba (c b a))

The code must cover all six possibilities.

There are three possible outputs:

(define output-ab (+ (* a a) (* b b)))
(define output-ac (+ (* a a) (* c c)))
(define output-bc (+ (* b b) (* c c)))

The code must map the six permutations to the three outputs.

abc || bac -> output-ab
acb || cab -> output-ac
bca || cba -> output-bc

Now the code can reflect the specification

   (cond

     ((or (and (>= a b)
               (>= b c))
          (and (>= b a))
               (>= a c)))
      output-ab)

     ((or (and (>= a b)
               (>= c b))
          (and (>= a b))
               (>= c a)))
      output-ac)

     ((or (and (>= b a)
               (>= c a))
          (and (>= c b))
               (>= b a)))
      output-bc)

     (else (error "unhandled condition")))

Review

Style

Scheme has formatting conventions. The code does better with indentation than with parenthesis.

Logic

The lack of a specification and tests based upon it leads to an incorrect implementation and poorly organized code. There is a branch which returns the same value on both paths:

 (else (cond ((> b c)
                (+ (square b) (square c)))
              (else (+ (square b) (square c))))

Efficiency

Correct code is the first order objective. Writing clear code facilitates that because it makes debugging and testing and maintenance easier.

Speed of execution matters only when it matters. That is always after the code is correct and after there is an objective performance issue, not just a theoretical one. Getting a wrong answer fast may be worse than no answer at all if we mistakenly believe the wrong answer is correct.


1. Review

There doesn't seem to be any iterative deepening going on. The code just implements an ordinary depth-first search for all simple paths in the graph. Iterative deepening would require calling enumerateAllPaths first with depthLimit=1, then with depthLimit=2 and so on.
The docstring should explain what the parameters mean.
Imports are best done once at the top level of a module, not every time a function is called.
The comment for paths says "pqueue" which I don't understand (is it an abbreviation for "priority queue"?). It would be better to be explicit, for example I would write something like "heap of (cost, length, path) tuples for paths that reach the goal".
The code for getting the best path out of the heap is needlessly long-winded, and has a bug (if the best path has cost \$2^{63}-1\$ it will not be found). Better to write:

if paths:
    cost, _, _ = heapq.heappop(paths)
    return cost
else:
    return -1

If you need a number that's larger than any possible cost, use infinity, that is, float('inf') instead of an arbitrary number.
The goal of the problem is to find just one path to the destination (the cheapest one), so it is wasteful to maintain a collections of all paths to the destination. Better just to remember the best path found so far.
There is no need to pass the variables goal and visited and path into the enumerateAllPaths function. These do not change during the search.
These lines of code are repeated:

path.pop()
visited[u] = False

By testing depthLimit != 0 instead of depthLimit == 0 you could avoid this repetition.
Instead of implementing visited as a dictionary mapping nodes to True or False, use a set of nodes instead.
The path list is not needed: this is only used to find the length of the path, but that is redundant as len(path) is always equal to K + 1 - depthLimit. And since you don't care about the actual length of the path, only its relative length compared with other paths, you can drop the K + 1 (since this is the same for all paths) and just use -depthLimit.

2. Revised code

from collections import defaultdict

def cheapest_path_cost(edges, src, dst, k):
    """Return the cost of the cheapest path in the graph from src to dst
    visiting no more than k other nodes. The graph is specified as a
    sequence of tuples (u, v, c) meaning that there is an edge from u
    to v with cost c. If there is no path, return infinity.

    """
    graph = defaultdict(list)  # {u: (v, cost)}
    for u, v, c in edges:
        graph[u].append((v, c))
    infinity = float('inf')
    best = infinity, 0         # (cost, -depth) of best path found.
    visited = set()            # Set of nodes visited on current path.

    def enumerate_paths(u, cost, depth):
        # Enumerate simple paths of length up to depth, starting at u.
        nonlocal best
        visited.add(u)
        if u == dst:
            best = min((cost, -depth), best)
        elif depth:
            for v, c in graph[u]:
                if v not in visited:
                    enumerate_paths(v, cost + c, depth - 1)
        visited.remove(u)

    enumerate_paths(src, 0, k + 1)
    return best[0]

3. Testing

You write in the post:

  Since it fails on runtime, I don't know if my code is 100% valid from an implementation standpoint.

This suggests to me that you have not tested your code. Is that right? You say in comments that you "already solved this problem with Bellman–Ford" in which case you could use your other solution as a test oracle.

Here's the kind of test that you might quickly implement using a test oracle. Here I'm using the compressed sparse graph routines in scipy.sparse.csgraph, but any other graph library would do.

import numpy as np
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra
from unittest import TestCase

class TestCheapestPathCost(TestCase):
    def test_cheapest_path_cost(self):
        # Random graph on n nodes with given density and costs up to maxcost.
        n = 10
        density = 0.3
        maxcost = 5
        graph = np.random.randint(1, maxcost + 1, (n, n))
        graph[np.random.random((n, n)) > density] = 0

        # Convert to array of edges.
        i, j = np.mgrid[:n, :n]
        edges = np.dstack((i, j, graph))
        edges = edges[edges[..., 2] != 0]

        # Find shortest paths and compare.
        shortest = np.dstack((i, j, dijkstra(graph))).reshape(-1, 3)
        for src, dst, expected in shortest:
            self.assertEqual(cheapest_path_cost(edges, src, dst, n), expected)

4. Performance

There are a couple of easy optimizations you can make in depth-first searches.

First, prune paths that are no better than the best path so far, like this:

def enumerate_paths(u, cost, depth):
    # Enumerate simple paths of length up to depth, starting at u.
    nonlocal best
    visited.add(u)
    if u == dst:
        best = cost, -depth
    elif depth:
        for v, c in graph[u]:
            if v not in visited and (cost + c, 1 - depth) < best:
                enumerate_paths(v, cost + c, depth - 1)
    visited.remove(u)

Note that we don't need the call to min in this version of the code because we already tested that the cost was an improvement, before visiting this search node.

Second, when constructing the adjacency list representation of the graph, sort the edges at each vertex by their cost. This means that lower-cost paths are visited sooner in the search, and this makes it more likely that the pruning will be effective.


Shorter way to write list-as-dict-value in Python?

You can use collections.defaultdict:

from collections import defaultdict

mydict = defaultdict(list)

Now you just need:

mydict[color].append(path)

defaultdict is a subclass of dict that can be initialized to a list, integer...

btw, the use of has_key is discouraged, and in fact has_key has been removed from  python 3.2.
When needed, use this by far more pythonic idiom instead:

if color in a:
    ........


You can access the data element via dataset property and camelCase data name

const data = element.dataset.classToggle;

You can add a click event to the document as follows that will only do something if the target is class js_class_toggle

const togClass = `.js_class_toggle`;

addEventListener("click", e => {
    if (e.target.classList.contains(togClass)) {
        /* ...do stuff... */
    }
}

Or you can add a click to each element containing the class.

document.querySelectorAll(togClass).forEach(el => el.addEventListener("click", toggleClick));

By the looks you are toggling the class on the element that is clicked so there is no need to add the reference

    This element will have a class toggled

making the function to toggle very simple

function toggleClick(e) {
     e.target.classList.toggle(e.target.dataset.classToggle);
}

To include the reference id you can make the data JSON like

    This element will have a class toggled

Then the function becomes

function toggleClick(e) {
     const data = JSON.parse(e.target.dataset.classToggle);
     const el = document.querySelector(data.query);
     if (el) { el.classList.toggle(data.toggleClass) }
}


Avoid globals. consecutivo is particularly confusing. It is too easy to miss the fact that it is reset to 0 at each iteration. Always prefer returning a value:
int suma_elementos(int elemento)
{
    int proporcion = n;
    int consecutivo = 0;
    while (proporcion >= elemento)
    {
        proporcion--;
        consecutivo++;
    }
    return consecutivo;
}

and use it in your loop as
    int consecutivo = suma_elementos(consecutivos[i]);

Now it is obvious that suma_elementos does not really need to loop. You have an invariant proporcion + consecutivo == n. At the end of the last iteration you also have proporcion == elemento, which means that consecutivo = n - elemento. In other words,
int suma_elementos(int elemento)
{
    return n - elemento;
}

Now I would rather not bother to have suma_elementos at all (besides, with my poor Spanish I have an impression that the name is rather misleading). The loop would become
    for (int j = 0; j < n - consecutivos[i]; j++)

Honestly, it is much easier to understand.

final = 99999999; is very fragile. Consider a ramp-up loop:
  final = 0;
  for (int j = 0; j < consecutivos[i]; j++) {
      total += elementos[j];
  }

Your code complexity is \$O(n*k)\$ (k being a width of the window). Notice that after the ramp-up you don't need to recompute the sums of k elements: as the window shifts, one element enters, another leaves:
  final = total;
  for (int leave = 0, enter = base[i]; enter < n; leave++, enter++) {
      total += elementos[enter] - elementos[leave];
      if (total < final) {
          final = total;
      }
  }

obtaining \$O(n + k)\$ complexity.


public static double returnLogisticEquation(double x, double r) {

The name is not quite correct, as it does return the result of equation, not the equation itself, so more like calculateLogisticEquation.

    public static double returnLogisticEquation(double x, double r) {
        return r * x * (1 - x);
    }

I'm torn on this one. Normally, I say that you are only allowed to use single-letter variables when dealing with dimensions (yes, that disallows "i", "j", "k" too). However, when implementing mathematical functions there might be a reason to use them. However, using the long names might still be an improvement:
    public static double returnLogisticEquation(double populationRatio, double reproductionate) {
        return reproductionRate * populationRatio * (1 - populationRatio);
    }

for (int i = 0; i < numberOfIterations; i++) {

That's what I meant:
for (int counter = 0; counter < numberOfIterations; counter++) {

public static double ignoreFirstIterations(int numberOfIterations, double x, double r) {

I'm not sure about the name here, maybe forward(int numberOfIterations, ...) would be a better name, as normally, I'd not assume a function that ignores something to return something.

    public static double ignoreFirstIterations(int numberOfIterations, double x, double r) {
        for (int i = 0; i < numberOfIterations; i++) {
            x = returnLogisticEquation(x, r);
        }
        return x;
    }

Assigning to a parameter is bad style. Even though you can treat it as just another declaration, it might lead to confusion down the line. For example if you have an object as parameter and the following line:
thisIsAParameter.setValue("value");

If you have the habit of assigning parameters, you now need to check whether there was a different object assigned to the parameter before that function call. Ideally, parameters would be final, but that is quite noisy, though. Threat them as final.

int numberOfIterations = 1000;

It's not the number of iterations, it's the number of ignored iterations.

r += subintervalLength

For the record: += and other shorthand operators are not short for a = a + b, but for a = (TYPE_A)(a+b), which might yield unexpected results. For example, intA = intA + 5.5d will yield an error that a double is truncated to an int. intA += 5.5d will yield no such error.

    public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {
        StdDraw.setYscale(0, 1);
        StdDraw.enableDoubleBuffering();
        double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints;
        int numberOfIterations = 1000;
        for (double r = leftOfRInterval; r < rightOfRInterval; r += subintervalLength) {
            x = ignoreFirstIterations(numberOfIterations, x, r);
            for (int p = 0; p < numberOfVerticalPoints; p++) {
                x = returnLogisticEquation(x, r);
                StdDraw.point(r, x);
            }
        }
        StdDraw.show();
    }

A few more empty lines to group logic would be nice (like you've done in other functions).
    public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {
        StdDraw.setYscale(0, 1);
        StdDraw.enableDoubleBuffering();

        double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints;
        int numberOfIterations = 1000;

        for (double r = leftOfRInterval; r < rightOfRInterval; r += subintervalLength) {
            x = ignoreFirstIterations(numberOfIterations, x, r);

            for (int p = 0; p < numberOfVerticalPoints; p++) {
                x = returnLogisticEquation(x, r);

                StdDraw.point(r, x);
            }
        }

        StdDraw.show();
    }

while (true) {

If you can include a dynamic break condition, do so (like listening for ESC).

        double r = 0;
        double y = 0;

Declare variables where they are used, to limit the scope in which they exist to limit possible errors.
                double r = StdDraw.mouseX();
                double y = StdDraw.mouseY();

double scale = 0.05;

Seems more like this should either be a parameter, or a class-level constant.

I haven't tested your code or verified the mathematical correctness, but looks good so far.


@Snowbody has addressed many important points.  I'll just talk about the std::map.

The function initializes daysInMonth each time, which is just unnecessary.  You should have it initialized only once elsewhere, and it should also be const since it's not to be modified within the code.

If you have C++11 (which you should), you can initialize the map with an initializer list:

const std::map<int, int> daysInMonth = { {1, 31},
                                         {2, 28},
                                         {3, 31},
                                         {4, 30},
                                         {5, 31},
                                         {6, 30},
                                         {7, 31},
                                         {8, 31},
                                         {9, 30},
                                         {10, 31},
                                         {11, 30},
                                         {12, 31} };

(it can be formatted in any way you'd like)

You should also use an unsigned type for dates since they cannot be negative.


The composition root is just the place in your code where you'll compose the application and resolve the entire dependency graph at once. You'll want that as close as possible to the application's entry point - the Main method is perfect for this in a console application.

Regardless of your IoC container, the first thing you need to do, is to configure it - to tell it what implementation to supply for the constructor-requested interfaces.

That's the key right here: constructor injection. Your IoC container is the object responsible for owning the instances of everything under its wing. The resolution phase resolves services, with their own dependencies; you don't resolve a string, you resolve an interface that presents a string.

Your entire program lives and dies inside the Main method - your example is too trivial to demonstrate the benefits of DI/IoC, I don't think it's a good example.

Imagine you have a data layer, a business layer and a presentation layer. In a non-IoC code base the BLL will have a dependency on the DAL, and will consume its API; the presentation layer will probably run the show, and have a dependency on the BLL.

With IoC you revert the dependencies. The BLL doesn't need to know about a DAL. Instead the DAL has a dependency on the BLL, and it implements the interfaces that the BLL is coded against.

The presentation layer is the logical place to compose the application, if your application's entry point is typically right there.

The composer assembly needs to have references to all the assemblies that basically provide the implementations - nothing forbids creating a separate assembly just for wiring up the application and starting it.

If the composition root is in its own assembly, it's all you need to recompile. I like defining my mappings with code, because I get IntelliSense and compile-time validity.

Unfortunately there's not much code to review in your question, ...we can't review what you haven't written yet! Good luck!

Please come back when you've implemented a functionality, right now I don't think your project isn't ready for peer review.

(cough) that was too long for a comment ;)


Determine number of times an id was used with a domain IP

First, I would ask if you really need the percentage calculation to happen in the query result set (vs. being able to calculate this in application layer).  This is really what is causing complexity in your use case, as being able to get row-level data and summary data (the percentage) in a single query is a bit of a challenge in most relational databases.

If you don't require this in your actual query, then you can greatly simplify this query to something like:

SELECT
    id,
    domainIP,
    COUNT(domainIP) AS times
FROM log
GROUP BY id, domainIP
ORDER BY id ASC, times DESC

This would eliminate your subselect and the resulting filesort that is happening because of it. Of course, the query above would require an index on domainIP to be optimized.

This would give a result set like:

| id     | domainIP        | times
| foo    | 158.132.34.5    | 1
| bob    | 128.12.244.3    | 2
| bob    | 19.152.134.4    | 1
| bob    | 168.152.34.9    | 1
| alice  | 178.132.64.10   | 1
| alice  | 188.152.214.200 | 1
| peter  | 208.162.36.153  | 3
| peter  | 198.168.94.201  | 1

This may or may not be trivial to compile this into your percentage results in your application layer depending on how many unique id values you have.

You could potentially make it even easier by using WITH ROLLUP clause in your GROUP BY (see https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html for more info).

That query might look like this:

SELECT
    id,
    domainIP,
    COUNT(domainIP) AS times
FROM log
GROUP BY id ASC, domainIP ASC WITH ROLLUP

This would yield a result set like:

| id     | domainIP        | times
| foo    | 158.132.34.5    | 1
| foo    | NULL            | 1
| bob    | 128.12.244.3    | 2
| bob    | 19.152.134.4    | 1
| bob    | 168.152.34.9    | 1
| bob    | NULL            | 4
| alice  | 178.132.64.10   | 1
| alice  | 188.152.214.200 | 1
| alice  | NULL            | 2
| peter  | 208.162.36.153  | 3
| peter  | 198.168.94.201  | 1
| peter  | NULL            | 4
| NULL   | NULL            | 11

Note here that there are added rows where the NULL values represent case where you have subtotal for the preceding aggregation set (i.e. for each of you id values).  This could make it even easier for application logic to pick up you group-level totals.

Now, if you truly need to get percentages totals in the result set, then I would first take a step back and really understand what the use case is. Do you really need to make this query on an ad hoc basis with a need for exact real-time results?  If so, you may just have to live with the fact that your query may take a long time to run, as you will always have to calculate the totals as aggregated at id level and at id/domainIP level.

If however you can live with periodically updating the aggregations (like scheduled via cron, or simlar), then your options open up greatly to deliver better performance.  Perhaps you runs a query like I have shown above and place the results into a temporary table every X minutes and then use that table as the basis for your query.  Perhaps you look at wholly separate summary tables (as suggested in the answer by @Siegen), with trigger-based updates.  Perhaps you have a wholly separate ETL process which takes this data and populates in into a data store more geared towards data reporting (i.e. a data warehouse). Whatever the case may be, I would suggest that you might need to take a step back and think about what you use case really requires, and my guess is that you will find it does not require ad-hoc, real-time, query results like what you are trying to get here.

With regards to your table schema:

Your id and event index are totally unnecessary and are likely hurting insert performance on this table.  event is an exact duplicate of logUnique (just withut the uniqueness constraint, which makes no sense). id index use cases can be satisfied via the logUnique index as well, as the first two fields in the index are exactly the same and in the same order.
You might consider doing away with camelCasing of any database object identifiers (table names, field names, etc.) as case-sensitivity is typically quite meaningless in MySQL and may lead to some problems when applied across different operating systems..  Many MySQL admin folks consider it best practice to simply use snake_case for naming all database object identifiers to keep things simple.  Read https://dev.mysql.com/doc/refman/5.7/en/identifier-case-sensitivity.html for more on this.


in-nest-sequence: sequence generator in Racket

For cases where the the user follows the syntax and the function returns and receives the correct number of values, this works fine.

It is a good principle to catch errors as early as possible.

Consider this example:

(in-iterate add1)

Here the user supplies a function add1 that has arity 1, but supplies no arguments. This will eventually lead to an "result arity mismatch;" error, when add1. This error can be caught earlier in using procedure-arity to check that enough init values are supplied. The error message presented to the user can be "expected 1 initial value, but received 0".

In the *in-iterate consider: [(x ...) (_ func init ...)] .
Here the number of bound identifiers (the xs)  must be the same as the number of init expressions. If they are not, a raise-syntax-error with stx as the source of the error can be used.

An example that should be a syntax-error (and not a runtime error):

(define (add1/2 x y) (values (+ x 1) (+ y 2)))
(for/list ([n     10]
           [(x y) (in-iterate add1/2 0)])
  (list x y))

The name of the construct is a bit off. In in-list and in-sequence we have the pattern in-noun, so that suggest in-iteration might be better. However iteration is a bit vague. Maybe one in-nested-sequence or in-nest-sequence based on the name used in Mathematica? http://reference.wolfram.com/language/ref/NestList.html


Sorting email address according to occurrences of each domain

I suggest you get a linter such as Prospector or flake8, this can tell if your code is un-Pythonic. Some people prefer hinters like black.

Your code doesn't conform to PEP 8 which is the standard when it comes to Python. Your comprehension is hard to read because it doesn't conform to best practices.
I'd recommend moving your code into a main function and use an if __name__ == '__main__': guard. This reduces global pollution and prevents your code from running accidentally.
When you see something like:

if key in my_dict:
    my_dict[key] += value
else:
    my_dict[key] = default + value

Then you should probably use dict.get which can get the following code:

my_dict[key] = my_dict.get(key, default) + value

In this case you can add more sugar by using collections.defaultdict, as it will default missing keys to 0.

import collections

my_dict = collections.defaultdict(int)
my_dict[key] += 1

Don't use comprehensions with side effects, they're hard to understand and are better expressed as standard for loops. This is as the list you're making is absolutely pointless.
You can use dict.items() rather than your comprehension with dict.keys().

import re
import collections

def main():
    with open('mailbox.txt') as mbox:
        ndict = collections.defaultdict(int)
        for line in mbox:
            domain = re.findall('From [^ ].*@([^ ]*)', line)
            if domain:
                ndict[domain[0]] += 1

        for item in sorted(ndict.items(), key=lambda x: x[1], reverse=True):
            print(item)

if __name__ == '__main__':
    main()

You can replace the majority of your code with collections.Counter.

import re
import collections

def main():
    with open('mailbox.txt') as mbox:
        counts = collections.Counter(
            domain[0]
            for domain in re.findall('From [^ ].*@([^ ]*)', line)
            if domain
        )
        for item in counts.most_common():
            print(item)

if __name__ == '__main__':
    main()