Take a list of nums and return max and min

Avoid repeating yourself: use a single input call; it isn't much here, but it is easily error-prone if your "initialization" phase is several steps long. The usual idiom in such case is to use a while True loop and test the condition after the initialization to break if necessary.
Please avoid bare except, this is a bad habit to get into. This will catch all exceptions, including the ones you're not expecting (such as KeyboardInterrupt if the user hits Ctrl+C) and, thus, not ready to handle. In both cases, you’re expecting ValueErrors here.
Use functions, this will make your code much more reusable:

def ask_user_number_list():
    num_list = []
    while True:
        num = input('Please enter a number or 'done' to finish: ')
        if num.lower() == 'done':
            break

        try:
            number = int(num)
        except ValueError:
            print('Invalid input')
        else:
            num_list.append(number)

    return num_list

def search_min_and_max(lst):
    try:
        return min(lst), max(lst)
    except ValueError:
        return None

if __name__ == '__main__':
    bounds = search_min_and_max(ask_user_number_list())
    if bounds is None:
        print('NO INPUT!')
    else:
        print('Maximum number: ', bounds[-1])
        print('Minimum number: ', bounds[0])


Check if two nodes are cousins in a Binary Tree

Two nodes are cousins of each other if they are at same level and have different parents.

Are we cousins? Normally, I'd say "no", but according to your definition, it's quite possible. Never mind, nice to meet you.

What I dislike most is that you're using both a TreeNode and an index-based tree embedded in an array. I guess, the array serves the initialization only, but I'm not very sure. Unless the initialization is part of task, move it to a separate class.

Your TreeNode-based structure is pretty inefficient for this kind of test. You could do much better with a

class MyTreeNode {
    private int item;
    private MyTreeNode parent;
    private int depth;
}

where the depth only allows you to say "NO" fast.

The whole program would be like

areCousins(MyTreeNode a, MyTreeNode b) {
    return a.depth == b.depth && a.parent != b.parent;
}

just like you wrote above. Without the parent pointers, things get much more complicated. It looks like you did it right, although I struggled with your void isCousins for a while. The is prefix suggest a boolean and you're using a List where a two-member container would fit better.

Because of this, your program fails for trees containing a given node twice like

CheckCousins cs1 = new CheckCousins(Arrays.asList(1, 2, 3, 4, 5, 4, 5));
assertTrue(cs1.isCousin(4, -1));

Not tested, but I guess it fills nodeDatas with the two 4s and you're out of luck.


Designing classes for non-standard arithmetics

You might want to define the base type like this

abstract class Primitive
{
    public Primitive OpAccess(Primitive right)
    {
        switch (right)
        {
            case Number number: return OpAccess(number);
            // ... other types
            default: throw new ArgumentOutOfRangeException();
        }
    }
    protected abstract Primitive OpAccess(Number right);
    // ... other OpAccess
}

where there is only one public method and the new C# 7 switch takes care of the dispatch and derived classes need to implement only the concrete protected overloads:

class Sequence : Primitive
{
    protected override Primitive OpAccess(Number right)
    {
        Console.WriteLine("Sequence @ Number");
        return null;
    }
    // ... other OpAccess
}

dynamic is no longer necessary.


Settings the height of rows for multiple screens within a TableViewController

I would split the table into multiple sections and set the number of rows to 0 for those sections I do not want to display and only use the default settings in heightForRowAtIndexPath

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

    switch indexPath.section {
    // hide all cells of teh default methos table
    case 0: return 50.0
    case 1:
        if ((promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize) > 350){
            //print ("the result of this is:  ---------- \(promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize)")
            return 80
        } else { return 50.0 }
    case 2: return 9.0
    case 3:
        if enableNotifications.on {
            return selectedCellHeight
        }
        return unselectedCellHeight
    case 4: return 9.0
    // hide propmt me to modify number cell
    case 5:
        if ((modifyNumbersLabel.intrinsicContentSize().height * modifyNumbersLabel.font.pointSize) > 310){
            //print ("the result of this is:  ---------- \(modifyNumbersLabel.intrinsicContentSize().height * modifyNumbersLabel.font.pointSize)")
            return 90
        } else { return 50.0 }
    case 6: return 9.0
    case 7: return 50.0
    default: break
    }

return 50.0
}

And implement these functions:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 8
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0:
        // Original Rows 0, 1, 2
        switch walkthroughStep {
        case 1,2: return 0
        default: return 3
        }
    case 1:
        // Original Row 3
        switch walkthroughStep {
        case 2: return 0
        default: return 1
        }
    case 2:
        // Original Row 4
        switch walkthroughStep {
        case 2: return 0
        default: return 1
        }
    case 3:
        // Original Rows 5
        switch walkthroughStep {
        case 2: return 0
        default: return 1
        }
    case 4:
        // Original Row 6
        switch walkthroughStep {
        case 1: return 0
        default: return 1
        }
    case 5:
        // Original Row 7
        switch walkthroughStep {
        case 1,2: return 0
        default: return 1
        }
    case 6:
        // Original Row 8
        switch walkthroughStep {
        case 1,2: return 0
        default: return 1
        }
    case 7:
        // Original Rows 9, 10, 11
        switch walkthroughStep {
        case 1,2: return 0
        default: return 5
        }
     default:
         return 0
    }

So most of the display logic is in the numberOfSectionsInTableView method.


Session handling using Python Requests client

Please don't use regexes

Regular expressions are power tools. You can use them for many situations, but they tend to be inherently fragile. They're especially fragile for parsing HTML, in part because of how lenient most browsers will be. I'd recommend using a dedicated parser for it.  If you decided that since this is a page you control you don't need to be that careful that's fine, just be aware.

main

You shouldn't execute any code in the main body of your program - anything that should execute should be inside of an if __name__ == '__main__': block, and that should still be broken up into functions for ease of use.

get_page_data

Don't return a value if nothing was found; this would be very unexpected (and it would be annoying to check for, with a few edge cases). Instead raise an appropriate exception.

You also don't need to do if match != None:, just do if match:

class NoMatchFoundException(Exception): pass

def get_page_data(regex, req):
    match = re.compile(regex).search(req.text)
    if match:
        return match.group(1)
    raise NoMatchFoundException("No match found on {}".format(regex))

Favor good names over comments

Comments are almost always a sin. A necessary sin, but they mean that you haven't been able to sufficiently express yourself in code. Most of your comments would be great function names, e.g.

# get form page, so the cookies are set (form token)
logged_out_req = s.get(form_url, headers=headers)
print_req_data(logged_out_req, 'Logged out request')
title_logout = get_page_data('<title>(.*?)</title>', logged_out_req)

becomes

def get_form_page(session, url, headers):
    return session.get(url, headers=headers)

def get_page_title(page):
    return get_page_data('<title>(.*?)</title>', page)

logged_out_req = get_form_page(s, form_url, headers)
logout_page_title = get_page_title(logged_out_req)

Also you desperately need whitespace - add newlines liberally to group like sections of code. This is also a good way to see where you should create a new function.

I've left out the printing, because...

Don't print willy nilly

Most of the time you have a bunch of print statements they are intended to be debugging output; remove that before you actually use this. Occasionally if you need some sort of admin script or you need to know the status that's fine, but make sure you're printing out the bare minimum of what you need, and a log file is still going to be better.

I ended up with something like this. A lot of the functions end up not doing a whole lot, and if you don't think they're adding a lot of value remove them - the point of them, however, is to make it clear what each step is intended to do.  You'll note that I never do any error handling - I don't know what you actually want to be doing when the match fails.

import requests
import re

class NoMatchFoundException(Exception): pass

def get_page_data(regex, req):
    match = re.compile(regex).search(req.text)
    if match:
        return match.group(1)
    raise NoMatchFoundException("No match found on {}".format(regex))

def get_page_title(page):
    return get_page_data("<title>(.*?)</title>", page)

def get_page(session, url, headers, data=None):
    data = data if data else {}
    return session.get(url, headers=headers, data=data)

def print_req_data(req, req_name):
    print('{} status code: {}'.format(req_name, req.status_code))
    print('{} title: {}'.format(req_name, get_page_title(req)))
    print('{} content:\n{}'.format(req_name, req.text))

def get_form_token(page):
    return get_page_data('<input type="hidden" name="token" value="(.*?)">', page)

def logged_in(logout, logged):
    return get_page_title(logout) != get_page_title(logged)

def same_page(first, second):
    return get_page_title(first) == get_page_title(second)

def test_login(form_url, post_url, headers, username, password):
    with requests.Session() as s:
        logout_page = get_page(s, form_url, headers)

        form_token = get_form_token(logout_page)
        login_data = {'password' : password, 'username' : username 'token': form_token}

        logged_in_page = get_page(s, post_url, headers, login_data)

        if logged_in(logout_page, logged_in_page):
            logged_in_test = get_page(s, form_url, headers)

            if same_page(logged_in_test, logged_in_page):
                print('You are still logged-in')
            else:
                print('Not logged-in anymore')
        else:
            print('FAIL LOGIN')
            print_req_data(post_req, 'Post request (redirect page)')

if __name__ == '__main__':
    form_url = 'http://migueldvl.com/heya/login/'
    post_url = 'http://migueldvl.com/heya/login/process.php'
    headers = {'User-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'}
    username = 'miguel'
    password = 'password'

    test_login(form_url, post_url, headers, username, password)


I created a class to run a certain number of tasks in parallel in the browser.

Unless you're using web workers, in JS, nothing actually runs in parallel. The external processes (file reads, network requests, etc) may be running in parallel after spawning them, but JS still launches and completes in some sequence, asynchronously.

  It runs all the items and resolves if there were no errors, or rejects if there were any errors.

Sounds like you're looking for Promise.all. It takes an array of promises, and resolves if all of them resolve or rejects if any one of them rejects.

Now I've seen code that's eerily similar to this one, and I tell you it's a pain to debug. You have a bunch of functions depending on counters "flag properties" that alter how the functions work. Since async doesn't guarantee order, the values aren't guaranteed, therefore how the function runs is also not guaranteed. This then makes your queue hard to test and you end up doing "hope-driven development" - a project devoid of unit tests.

Hopefully I've scared you, since I don't ever want to see queueing done this way. Makes you lose hair. What I suggest you do is just take in an array of inputs, recursively work on them by chunks, concatenate the results and hand it over. No counters, no flags.

Here's a simple, no-cancel version of the queue. It launches the queue chunkSize at a time. Then it launches the rest of the array, up until the array is exhausted. Then the chunks are concatenated. All you need for inputs are functions that return promises. How you construct them or feed them input is up to you, not the queue. Below shows how to use closures. Alternatively, you can use bind.

const launchQueue = (q, chunkSize) => {
  // No more items, resolve with an empty array
  if (!q.length) return Promise.resolve([]);

  // Slice the array
  const chunk = q.slice(0, chunkSize);
  const remain = q.slice(chunkSize);

  // Call each function and store the promises returned to an array.
  // Promise.all fails fast. Catch errors and resolve with those.
  const chunkPromises = chunk.map(f => f.call().then(r => r, e => e));

  // Wait for all to resolve
  return Promise.all(chunkPromises).then(r => {

    // Run the remaining items
    return launchQueue(remain, chunkSize).then(s => {

      // Concat results.
      return r.concat(s);
    });
  });
}

// For each input, create a function that returns a promise that
// that resolves when the operation completes.
const queue = [9000, 7000, 4000, 5000, 8000, 1000, 3000, 2000, 4000, 6000].map(n => {
  return () => new Promise(r => {
    console.log(`fn with ${n} requested`);
    setTimeout(() => {
      console.log(`fn with ${n} resolved`);

      // Prove that whatever we resolve here ends up in the
      // call below.
      r(-n);
    }, n);
  });
});

// Hand over the functions to the queueing function and wait for
// the results.
launchQueue(queue, 2).then(r => console.log(r));

An async-await version is much more readable:

const launchQueue = async (q, chunkSize) => {
  if (!q.length) return [];

  const chunk = q.slice(0, chunkSize);
  const remain = q.slice(chunkSize);
  // The then is much more concise than a try-catch.
  const chunkPromises = chunk.map(f => f.call().then(r => r, e => e));
  const chunkResults = await Promise.all(chunkPromises);
  const remainResults = await launchQueue(remain, chunkSize);
  return chunkResults.concat(remainResults);
}

// For each input, create a function that returns a promise that
// that resolves when the operation completes.
const queue = [9000, 7000, 4000, 5000, 8000, 1000, 3000, 2000, 4000, 6000].map(n => {
  return () => new Promise(r => {
    console.log(`fn with ${n} requested`);
    setTimeout(() => {
      console.log(`fn with ${n} resolved`);

      // Prove that whatever we resolve here ends up in the
      // call below.
      r(-n);
    }, n);
  });
});

// Hand over the functions to the queueing function and wait for
// the results.
launchQueue(queue, 2).then(r => console.log(r));


Your calculations are all off by a factor of 10: one minute is 60000 milliseconds, not 6000.  Instead of explaining your 6000 using a comment, write it out in the code, and the compiler will figure it out for you. That calculation will not cost you any runtime performance at all.

I don't recommend that design, defining one function per type of note.  One function should cover everything, I think.

Since you use printf() and scanf(), you should #include <stdio.h>.

It is customary to put main() at the end, so that you don't have to declare the functions it uses in advance.

#include <stdio.h>

#define SEMIBREVE       (1.0)
#define MINIM           (1.0/2)
#define CROTCHET        (1.0/4)
#define QUAVER          (1.0/8)
#define SEMIQUAVER      (1.0/16)
#define DEMISEMIQUAVER  (1.0/32)

int millisec(int bpm, double note) {
    return (int)(
        60      /* seconds */
        * 1000  /* milliseconds per second */
        * 4     /* crotchets per semibreve */
        * note
        / bpm
    );
}

int main() {
    int bpm;
    printf("Enter tempo (crotchets per minute): ");
    scanf("%d", &bpm);

    printf("Semibreve would last for... %d milliseconds!\n", millisec(bpm, SEMIBREVE));
    printf("Dotted crotchet would last for... %d milliseconds!\n", millisec(bpm, 1.5 * CROTCHET));
    printf("Demisemiquaver would last for... %d milliseconds!\n", millisec(bpm, DEMISEMIQUAVER));
}


You are saying

  I want to merge the dictionary present

but what makes your task a bit difficult is that you are not handling dictonnaries but lists. Among other things, if you keep that idea that way, you'll have to iterate over n*m pairs (ta, tb) (where n and m are respective size of a and b).

A probably better idea would be to reorganise data in a and b to have them as an actual dict mapping id to some additional information. Then, merging will go through maximum n + m elements.


The code looks good, however, some point I like to mention about readability..

I can see there are multiple try-catch blocks. Every catch block does same thing. You can easily terminate duplicate code.

public static void LogThisCode(Action action)
{
    try
    {
        action();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        Debug.Print(ex.ToString());
    }
}

Call it like this:

public void Open()
{
    LogThisCode(() => {

        oConnection.ConnectionString = oConString;
        oConnection.Open();
        Console.WriteLine("Oracle DB Connection Established");

    });
}

You don't need all the variables to be global. Avoid using them. They aren't easy to track and create confusion when code grows.
I've moved oConnection.ConnectionString = oConString; inside constructor to avoid global variable.
Instead of comments on methods, use XML Documentation Comments
Always check and remove any unused code
You can use String.Format instead of concatenate strings
I would suggest you to eliminate all hard coded strings by introducing a class having constants.

After all above changes code will look like this:

class Oracle
{
    private OracleConnection oConnection;
    private OracleDataAdapter oCommand;

    public static void LogThisCode(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }

    public Oracle()
    {
        LogThisCode(() =>
        {
            oConnection = new OracleConnection();
            var oXML = new XmlDocument();
            oXML.Load(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\Test.xml");

            string oDb = oXML.SelectSingleNode("/Connections/Oracle/Database").InnerText;
            string oUID = oXML.SelectSingleNode("/Connections/Oracle/UId").InnerText;
            string oPassword = Encrypt.DecryptString(oXML.SelectSingleNode("/Connections/Oracle/Pwd").InnerText, oUID);
            string oConString = string.Format("Data Source={0};User Id={1};Password={2};", oDb, oUID, oPassword);
            oConnection.ConnectionString = oConString;
        });
    }

    /// <summary>
    /// Method that handles opening the connection to the  database
    /// </summary>
    public void Open()
    {
        LogThisCode(() =>
        {
            oConnection.Open();
            Console.WriteLine("Oracle DB Connection Established");
        });
    }

    /// <summary>
    /// Method that handles closing the connection to the database
    /// </summary>
    public void Close()
    {
        LogThisCode(() =>
        {
            oConnection.Close();
            Console.WriteLine("Oracle DB Connection Closed");
        });
    }

    /// <summary>
    /// Method that handles pulling the data from a table
    /// </summary>
    /// <returns></returns>
    public DataTable Pull()
    {
        DataTable oTable = new DataTable();

        LogThisCode(() =>
        {
            string oScript = System.IO.File.ReadAllText(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\CASE_SELECT.sql");
            oCommand.SelectCommand = new OracleCommand(oScript, oConnection);

            DataSet oData = new DataSet();
            oCommand.Fill(oData, "uds9");
            oTable = oData.Tables["uds9"];
        });

        return oTable;
    }
}


You could wrap your whole file in a namespace, as described here.

Of all the possibilities, this is the one I like the most:

var YourNamespace = (function () {
   var Message = function (div) {
      ...
   }
   var aPrivateFunction = function () { ... }
   ...
   return {
      'Message': Message
   };
})();

This lets you define private functions, like aPrivateFunction, not visible outside YourNamespace. You can access Message as YourNamespace.Message.


I'm not sure if there really is a better way to do this. The best I could come up with is:

import itertools
from collections import Counter

def convDict(inDict):
    inDict['a'] = inDict['a'] * inDict['n']
    return Counter(inDict)

average = sum(itertools.imap(convDict, inData), Counter())
average['a'] = average['a'] / average['n']

But I'm still not sure if that is better than what you originally had.

Counter is a subclass of dict. You can get items from them the same way you get items from a normal dict. One of the most important differences is that the Counter will not raise an Exception if you try to select a non-existant item, it will instead return 0.


Compile-time-fixed templated integer range

IMO, your test cases would be vastly more readable if you wrote them simply in terms of std::is_same. If you were going to write a lot of test cases, you could wrap all that boilerplate up in a macro such as

#define TEST(type, start, end, ...) \
    static_assert(std::is_same< \
        polder::integer_range<type, start, end>, \
        std::integer_sequence<type ,##__VA_ARGS__ > >::value)

which reduces your test cases to the tiny amount of code they actually are.

TEST(int, 8,8);
TEST(int, 0,5, 0,1,2,3,4);
TEST(int, 5,0, 5,4,3,2,1);
TEST(int, -3,2, -3,-2,-1,0,1);
TEST(int, -1,-4, -1,-2,-3);
TEST(int, 3,-8, 3,2,1,0,-1,-2,-3,-4,-5,-6,-7);

This shorter formulation incidentally makes it more obvious that you didn't test any corner cases or types other than int — which is why I'm a strong proponent of "shorter code is better code." We've now made the code short enough that we can see where the bugs are.

Okay, let's move on to looking at the actual code. It actually looks very clean and simple. Admittedly I did think at first that you were doing the bad O(n) approach where integer_range<N> inherits from integer_range<N-1>; it took me a moment to see that you were in fact doing the right thing. I see only two issues with

template<typename Int, Int... N, Int Begin>
struct increasing_integer_range<Int, std::integer_sequence<Int, N...>, Begin>:
    std::integer_sequence<Int, N+Begin...>
{};

The first problem is that our new test cases don't pass, because your increasing_integer_range is not actually a synonym for std::integer_sequence; instead it's merely derived from std::integer_sequence. This is good enough for the average codebase, but for a library implementation we'd want to make sure that the two types are actually equal. Fortunately, C++11 template typedefs make this easy. Rewrite it as

namespace details
{
    template<typename Int, typename, Int Begin, bool Increasing>
    struct integer_range_impl;

    template<typename Int, Int... N, Int Begin>
    struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, true> {
        using type = std::integer_sequence<Int, N+Begin...>;
    };

    template<typename Int, Int... N, Int Begin>
    struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, false> {
        using type = std::integer_sequence<Int, Begin-N...>;
    };
}

template<typename Int, Int Begin, Int End>
using integer_range = typename details::integer_range_impl<
    Int,
    std::make_integer_sequence<Int, (Begin<End) ? End-Begin : Begin-End>,
    Begin,
    (Begin<End) >::type;

template<std::size_t Begin, std::size_t End>
using index_range = integer_range<std::size_t, Begin, End>;

The second problem is that this implementation does not work for some obvious corner cases, such as integer_range<int, INT_MIN, INT_MAX>, because in general the result of End-Begin is not guaranteed to be representable in Int.

Fixing the second problem is left as an exercise for the reader, because I believe it's pretty darn hard. I think you might have to abandon the (really clever) idea of using std::integer_sequence to do your heavy lifting, and resign yourself to reimplementing integer_sequence something like Xeo did here except harder.

EDIT TO ADD a third "problem" I just thought of: The name integer_range could be considered misleading. If I were proposing this for the standard library, I'd name it make_integer_range, by analogy with make_integer_sequence.


How can I speed up my calculations with loops? Python

The code is very hard to follow. Here's a possible refactor to make its intent
clearer. Some key ideas in the simplification: (1) use loops to manage counters
rather than manually incrementing/decrementing; (2) use more
meaningful variable names when context isn't clear; and (3) delegate some of
the complexity to a helper function. The third idea is the most impactful: the
helper function is simple because it does so little; and the main function,
having been relieved of a burden, is simpler as well -- so simple, in
fact, that it boils down to computing a sum over two loops.
def math_count(inv, trials = 10000):
    total_attempts = sum(
        attempts_to_get_lte(x)
        for _ in range(trials, 0, -1)
        for x in range(inv, 0, -1)
    )
    return total_attempts / trials

def attempts_to_get_lte(x):
    attempts = 0
    while True:
        attempts += 1
        if random.randint(1, 45) <= x:
            return attempts

But attempts_to_get_lte() is an easily solved probability problem: rather
than have Python simulate the manual flipping of coins, we can just do a little
math. If you prefer that approach, I believe the following is correct
(probability experts should chime in if I've gone astray):
def math_count_exact(inv):
    return sum(45 / x for x in range(inv, 0, -1))


Like @Gareth mentioned in his comment it would be perfect to use the ConcurrentQueue<T>.

You answered @Gareth the queue needs to be bounded in size but where is the problem. We can just add a check to the Add() method and if the queue's size is equal to the bounded size we will just dequeue one item.

If the passed in size parameter of the constructor is 0 you will get a DivideByZeroException at _i = (_i + 1)%_size; and it doesn't really make sense to have a CircularBuffer with size == 0, does it ?

As you will notice in the adjusted code, I have placed the _lock.EnterWriteLock(); outside of the try..finally because what happens if the call to EnterWriteLock() fails ?

public class CircularBuffer<T>
{
    private readonly ConcurrentQueue<T> _data;
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private readonly int _size;

    public CircularBuffer(int size)
    {
        if (size < 1)
        {
            throw new ArgumentException($"{nameof(size)} cannot be negative or zero");
        }
        _data = new ConcurrentQueue<T>();
        _size = size;
    }

    public IEnumerable<T> Latest()
    {
        return _data.ToArray();
    }

    public void Add(T t)
    {
        _lock.EnterWriteLock();
        try
        {
            if (_data.Count == _size)
            {
                T value;
                _data.TryDequeue(out value);
            }

            _data.Enqueue(t);
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }
}

although using a ConcurrentQueue is IMO the cleaner way I will post a solution using a generic array as well like so

public class CircularBuffer<T>
{
    private readonly ReaderWriterLockSlim slimLock = new ReaderWriterLockSlim();
    private readonly int capacity;
    private readonly T[] buffer;
    private readonly int upperBound;

    private int currentIndex = -1;
    private int currentStart = 0;

    public CircularBuffer(int size)
    {
        if (size < 1)
        {
            throw new ArgumentException($"{nameof(size)} cannot be negative nor zero");
        }

        buffer = new T[size];
        capacity = size;
        upperBound = size - 1;
    }

    public void Add(T value)
    {
        slimLock.EnterWriteLock();
        try
        {

            if (IsFull || currentIndex == upperBound)
            {
                currentStart = FetchNextSlot(currentStart);
                IsFull = true;
            }

            currentIndex = FetchNextSlot(currentIndex);
            buffer[currentIndex] = value;

        }
        finally
        {
            slimLock.ExitWriteLock();
        }

    }

    public bool IsFull { get; private set; }

    private int FetchNextSlot(int value)
    {
        return (value + 1) % capacity;
    }

    public IEnumerable<T> Latest()
    {
        slimLock.EnterReadLock();
        try
        {
            return FetchItems().ToArray();
        }
        finally
        {
            slimLock.ExitReadLock();
        }
    }

    private IEnumerable<T> FetchItems()
    {
        IEnumerable<T> fetchedItems = Enumerable.Empty<T>();
        if (IsFull)
        {
            return FetchItems(currentStart, upperBound);
        }
        return fetchedItems.Concat(FetchItems(0, currentIndex));
    }
    private IEnumerable<T> FetchItems(int start, int end)
    {
        for (int i = start; i <= end; i++)
        {
            yield return buffer[i];
        }
    }
}


Java merge sort implementation efficiency

First of all your indentation is really bad. This makes the code hard to read and not so fun to review.

The easiest solution to this is to get yourself a nice IDE (most popular ones are eclipse and IntelliJ) and have that IDE auto format your code.

Then to properly put the code in the textbox on this site just paste it, select it entirely and press the {} button at the top.

As for your algorith I don't fully understand why you keep creating new arrays. The usual implementation for sorting an array does so in place. So I would expect the method signature to look like this:

public static void sort(int[] array) {

Which then calls a helper method that also uses indicates which part of the array has to be sorted:

public static void sort(int[] array) {
    sort(array, 0, array.lenght-1);
}

public static void sort(int[] array, int start, int end) {

This method now doesn't physically split the array, but just looks at half the range, get's both sides sorted and then merges both halves in place into sorted order.

public static void sort(int[] array, int start, int end) {
    if(end == start) {
        return;
    }
    int middle = (end-start)/2;
    sort(array, start, middle);
    sort(array, middle+1, end);

    //TODO merge array[start:middle] with array[middle+1:end]
}

Before going into the merge implementation let's take a look at the space complexity of your current one.

Since the array get's split into 2 each time, the method recursively call's itself up to O(log N) steps (with N the size of the array and log meaning the 2-log). At each step you copy the given array into 2 new variables. And call the recursion with half the array. So the total needed memory for storing your arrays is I think O(N+(log N)²).

Now notice that the part of the algorithm I have given does not reserve any extra space for arrays. So up till now it's still running O(1) space. And this is including the recursive steps already.

As for actually merging, although possible to do in place, I would now take a temp copy of the array. This makes merging a lot easier at the cost of O(N) space. We do have to be careful at which one we actually put the result in though. Because we want our input array to remain sorted even after returning from this method.

For this reason we can never reassign the array variable. We have to do array[index]=newValue to achieve this.

Here's an idea about how to implement this:

int leftIndex = 0;
int rightIndex = middle;
int currentIndex = 0;
int[] partialSorted = Arrays.copyOf(array, array.length);
while(both parts not finished){
    if(partialSorted[leftIndex] < partialSorted[rightIndex]){
        array[currentIndex++] = partialSorted[leftIndex++];
    } else {
        //similar for right side
    }
}
//copy remainder of left side
//copy remainder of right side

The parts I left out shouldn't be too hard to figure out yourself. I didn't want to just give you the entire solution as that would take out all the fun.

EDIT 2: You can further reduce the space requirement in half if you only store the left half into a temporary copy. This also saves you from copying the remainder of the right hand side after the while loop.

EDIT: Technically this last step of copying the array to a temp and putting it back into the original in the correct place makes this implementation no longer in-place. The true in place implementation is a lot harder than I expected :)

A final optimisation you should consider is before actually merging to first see if it is already sorted: (last element of left half is smaller than first element of right half). Because then you can just return without copying anything at that iteration. This is a serious improvement in space complexity when the input is already a sorted array (turning it into O(1)).


Find the number closest to 0, breaking ties in favor of positive numbers

A bad example

Perl is a language in which the shortest code is usually not the best code.  For example, this short program accomplishes the task:

print((sort {abs($a)<=>abs($b) || $b<=>$a} (split ' ',<>)[0..<>-1])[0] // 0)

Not only is it hard to read, it's also algorithmically inefficient (because sorting is O(n log n) rather than O(n)).  I don't recommend writing code like that.

Critique

You should use more whitespace.  It won't make your code look any less clever, nor will it make your code run any slower.

You can safely dispense with chomp(), as Perl will naturally disregard the trailing newline when interpreting the string as a number.  You could probably write <> instead of <STDIN>, unless you insist on reading only from standard input.

Counting loops are clumsy in Perl.  When possible, opt for higher-level list-processing techniques.  In this case, I recommend List::Util::reduce.

A possible solution

In Perl, there are usually many possible ways to solve a problem.  Here's one short solution that is O(n), but avoids being the shortest possible solution.  I'll let you figure out how it takes advantage of the <=> operator.

use List::Util qw(max reduce);
use strict;

my $n = <>;
my @temps = (split ' ', <>)[0 .. $n - 1];
print((reduce { ($a, max($a, $b), $b)[1 + (abs($a) <=> abs($b))] } @temps)
       // 0);

The special case of $n == 0 can be handled using a // logical defined-or operator.  A || logical or operator would also happen to work, but it wouldn't be as appropriate.

Since the @t is meant to represent temperatures, renaming it to @temps would make the code less cryptic.


RUST: How can I optimize this password cracking algorithm?

First, I would change the approach fundamentally: I'd consider the plaintext as a 17-digit number in "base 11" (because there are 11 "letters" in the alphabeth). Then the loop becomes a simple iteration through a range from 0 to 1117-1. On top of that, threading will be easy to add using rayon.
As you were told, we should re-use memory for strings and not generate the wordlist in advance.
To re-use memory for strings, we treat them as long-living containers and call .clear() whenever we need to reuse them for another purpose.
This part in your code
for letter in alphabet.iter() {
    let new_word = format!("{}{}", word, letter);

    temp.push(new_word);
}

is very inefficient as it's calling format!, which is complex machinery, just to append a letter. It would be better to have at least String::push there, but we will take another approach below.

On 4 cores, the all-in-one is roughly as fast as just your non-parallelized first pass. For parallelism, I did parallel fold after Range<u64>. So each thread has a little bit of its own state there.
Make sure you add rayon = "0.6" in the Cargo manifest.
Here is the code:
#[cfg(debug_assertions)]
use num_format::{Locale, ToFormattedString};
use std::str;
use std::io::Write;
use rayon::prelude::*;

static PASS_LENGTH: u32 = 17;

#[derive(Default)]
struct State {
    plaintext: Vec<u8>,
    intermediate: Vec<u8>,
}

impl State {
    fn new() -> Self {
        let mut result = State::default();
        for _ in 0 .. PASS_LENGTH {
            result.plaintext.push(b"x"[0]);
        }
        result.plaintext.extend(b"........................................................!1".iter().copied());
        result
    }
}

fn main() {
    let goal_hash = "dbba1bfe930d953cabcc03d7b6ab05e";

    let num_of_md5 = 4;
    let alphabet = "bdeilmostu-";
    let alphabet_len = alphabet.len() as u64;

    let total = alphabet_len.pow(PASS_LENGTH);

    (0 .. total).into_par_iter().fold(
        || State::new(),
        |mut state, num| {
            for i in 0 .. PASS_LENGTH {
                let letter = ((num / alphabet_len.pow(i)) % alphabet_len) as usize;
                state.plaintext[i as usize] = alphabet.as_bytes()[letter];
            }

            state.intermediate.clear();
            write!(&mut state.intermediate, "{:x}", md5::compute(&state.plaintext[..]));
            for _ in 1 .. num_of_md5 {
                let digest = md5::compute(&state.intermediate[..]);
                state.intermediate.clear();
                write!(&mut state.intermediate, "{:x}", digest);
            }
            let result = &state.intermediate[..];

            if result == goal_hash.as_bytes() {
                println!("We found the password: {}", str::from_utf8(&state.plaintext[..]).unwrap());
            }

            if num % 1_000_000 == 0 && num != 0 {
                #[cfg(debug_assertions)]
                println!(
                    "Attempts: {}/{}, Text: {}",
                    num, total, str::from_utf8(&state.plaintext[..]).unwrap()
                );
            }

            state
        }
    ).for_each(|_| {});
}
```


Memory alignment requirements is something often forgotten when implementing custom memory allocation strategies. Each native type has a minimum alignment required for its starting memory address, consequently, structured types will inherit the requirement from its members. std::aligned_storage and std::aligned_union are a good example on that. Also refer to: How to allocate aligned memory only using the standard library?

Operator new and malloc are guaranteed to always return a starting address that is aligned for the most demanding type available (like 16 bytes for a __m128 vector type), so memory returned by those system allocators will be suitable to store such objects and homogeneous arrays of them. The problem with mixing objects with different alignment requirements in the same memory block is that if one item or chunk of items in this mixed array breaks the alignment, whatever follows will be misaligned, so you run the risk of getting memory access errors at the CPU level when touching that memory.

Your block allocator has that problem, since it accepts generic types, so you need to fix it in order to have a robust implementation that can allocate anything. To do that, you just have to increment each pointer to an aligned address, and also add an extra overhead to the parent block, in account of that. Something like the following:

void * aligned_ptr(void * ptr, std::size_t alignment)
{
    // Cast to integer and align the address:
    std::uintptr_t uintPtr = reinterpret_cast<std::uintptr_t>(ptr);
    std::uintptr_t alignedPtr = (uintPtr + (alignment - 1)) & ~(alignment - 1); // Power-of-two alignment assumed!

    // Re-cast to void*, validate and return:
    void * userPtr = reinterpret_cast<void *>(alignedPtr);
    assert(is_aligned_ptr(userPtr, alignment));
    return userPtr;
}

std::size_t aligned_size(std::size_t size, std::size_t alignment)
{
    // Add the minimum extra needed to the size for pointer alignment.
    // This size can then be used to malloc() some memory
    // and then have the pointer aligned with aligned_ptr().
    return size + (alignment - 1);
};

block block_allocate(A*& pA, std::size_t nA, B*& pB, std::size_t nB, C*& pC, std::size_t nC)
{
    auto sizeBlockA = aligned_size(nA * sizeof(A), alignof(A));
    auto sizeBlockB = aligned_size(nB * sizeof(B), alignof(B));
    auto sizeBlockC = aligned_size(nC * sizeof(C), alignof(C));

    block blk = alloc_bytes(sizeBlockA + sizeBlockB + sizeBlockC);

    pA = reinterpret_cast<A*>(aligned_ptr(blk.ptr, alignof(A))); // if allocated with new, already aligned, but doesn't harm checking either...
    pB = reinterpret_cast<B*>(aligned_ptr(blk.ptr + sizeBlockA, alignof(B)));
    pC = reinterpret_cast<C*>(aligned_ptr(blk.ptr + sizeBlockA + sizeBlockB, alignof(C)));

    return blk;
}

Please note that the above example was not tested, but hopefully gives you a good idea of the procedure.

Other little things:

Instead of returning a plain unique_ptr to the memory, I'd suggest augmenting the pointer with a small structure that has some extra context, like the total size of the memory. This is oftentimes useful for debugging and profiling (the block type I invented above):

struct block
{
    std::unique_ptr<std::uint8_t[]> ptr;
    std::size_t size;
};

Or you might modify it to use of a std::vector. It is certainly possible, but might be overkill, since the block is not meant to be resized.

Very minor nitpicking, but notice that I use the std:: prefix in the extended integer types like size_t? That's the correct usage, since they are members of the standard namespace in C++. It works without because shared C headers expose them globally, but a pure C++ compiler is not required to provide that.


Warshall's algorithm for transitive closure

Arrays are 0-indexed

In C, arrays are 0-indexed. Not 1-indexed. So you're skipping the first element and running off the back in these loops. You want:

for(i=0;i<n;i++)
  for(j=0;j<n;j++)
    for(k=0;k<n;k++)

Use braces

Nested logic is crying for braces to make it easer to read:

for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
    }
  }
}

That'll also future proof anything else you add into these loops. What if you added logging? You'd have to go back and add braces then anyway. It's a good habit to get into. Always braces.

maximum()

There's actually no reason for this function. The logic you want is:

R(k)[i, j] = R(k-1)[i, j] or (R(k-1)[i,k] and R(k-1)[k,j])

We can just do that directly using bitwise math:

for(i=0;i<n;i++) {
  for(j=0;j<n;j++) {
    for(k=0;k<n;k++) {
      p[i][j] = p[i][j] | (p[i][k] & p[k][j]);
    }
  }
}


I still find the string creation awful. If you cannot use C# 6 the I suggest the StringBuilder:

var consoleTitle = new StringBuilder()
    .Append(projectName).Append(" / ")
    .Append(serverUptime.Days).Append(" day".Pluralize(serverUptime.Days))
    .Append(serverUptime.Hours).Append(" hour".Pluralize(serverUptime.Hours))
    // ...
    .ToString();

and an extension method to get rid of conditionals:

static class StringExtensions
{
    public static string Pluralize(this string text, int value)
    {
        return (value != 1 ? text + "s" : text)
    }
}


I do, however insist on making everything explicit. I'm not a huge fan of implicit anything... Maybe that's something I need to get over?

No, that is very good practice and a good habit. Particularly, there are many dangerous, implicit type promotions going on in C, that explicit type casts can prevent.

However, if you want to be explicit, you must actually have quite a deep understanding of what's going on between the C lines. Until you do, you will end up causing more problems than you solve with this coding practice. Also, you do a couple of pointless things that only clutter down the code.

Here are my comments on your code:

Do not define your own bool type. Instead use the standard bool type in stdint.h.
(int) 0 This cast is pointless and adds nothing of value. Integer literals are always of the type int. Enumeration constants are also always of the type int.
register is an obsolete keyword from the dark ages, when compilers were worthless at optimizing code. Today, a modern compiler does a much better job at optimizing the code than you do, so let it do its job. Also, the register keyword causes various side-effects: for example you can't take the address of a register variable. So never use register, because there is never a reason to do so. That keyword just remains in the language for backwards compatibility.
Similarly, it is often best to let the compiler handle inlining in most cases. Because while inlining makes the code faster, it also makes the executable much larger. The compiler is likely better than you at determining when to optimize for size and when to optimize for speed.
Always use {} after each statement, even if there is only one line of code following it. Skipping {} is dangerous practice that almost certainly leads to bugs sooner or later.
You want to be explicit but miss a few cases where it actually matters.

1 << offset means that you do left shift on a signed integer. Assuming 32 bit integers, the case of 1 << 31 leads to undefined behavior. Generally, in 99.9% of the cases it doesn't make any sense whatsoever to use bitwise operators on signed integers. If you wish to write safe code, be explicit and type 1u << offset.
Because of the above, *x |= (1 << offset); implicitly stores an int into an unsigned int, which is potentially dangerous in some cases.
And also because of the above, you apply ~ to a signed int, which is always dangerous practice.
You have no function declarations, only definitions. You also don't declare the local functions as static, which is proper practice for functions that are private to the specific module.

As others have commented, naming a bool "value" and using it to store values is confusing. uint8_t would have been a more suitable type to use in this case.
In general, it is always better to use the types from stdint.h when you do bit manipulations.


Replacing DOM elements that have no attributes

Some thoughts about your code:

1) You work with the serialized form of the HTML, i.e. with innerHTML and outerHTML. In some (rare) occurrences, it may be acceptable to do so, but most of the time working with the provided API is cleaner. I don't think that the serialized representation is guaranteed to be the same across user agents (attribute ordering, legacy uppercasing of HTML...) - plus what if some inline script declares some '<span>' text... like yours?

2) Re-running the method is a bit dubious, you should be able to remove all spans in a single pass. In your case, the DOM collection is live, so each time you replace a span element, the current index must be shifted back. In itself, manually updating the index of a loop is a bad practice, but Javascript has limited iteration mechanisms, so you have to live with it. It's actually not that unusual in DOM manipulation.

3) Removing the spans without attributes is well and good, but even an empty span may be styled, as part of another selector (e.g. .foo > span). Your fix may bring new problems.

4) Comments should not repeat the code, but bring enlightenment to the reader. Indicating "find all <span> elements" aside a getElementsByTagName is probably unneeded. Indicating why you shift a loop index, if you decide to do it, is necessary.

function fixSpan(doc) {
    var spans = doc.getElementsByTagName("span");
    for (var index = 0; index < spans.length; index++) {
        var span = spans[index];
        if (span.attributes.length == 0) {
            span.parentNode.replaceChild(document.createTextNode(span.textContent), span);
            index--; // Tree is live; removing one span requires shifting the index.
        }
    }
}


Reading lines from a file and processing them concurrently

The general approach seems fine. You may want to benchmark your application based on the type of inputs you'll receive and the type of computation that's done. If the computation is CPU intensive, it may not make sense to have too many goroutines running in parallel since they can't all use the CPU at the same time.

If you find that's the case, it could be better to have a channel into which you send the lines that are being read and have a bunch of worker goroutines that read a line from the channel, process it, read another line and so on. Benchmarking should give you a good idea about the right approach.

If each goroutine makes a request to an external resource (such as a web service or a database) you'll have to think about ways to limit the rate of such requests.

Some general comments about the code which I think you should fix before putting it into production:

The code doesn't have any error checking or a way to report errors from the processing of each input line. You'll have to add those in.
You're also using a global variable to share the WaitGroup, which I think you should avoid. Either pass it in as a function parameter or use an anonymous function that calls processLine() and then wg.Done() (instead of calling wg.Done() in processLine())
As I mentioned above you may want to consider limiting the number of concurrent goroutines depending on your use case.


High CPU utilisation for Logs Manager shell script

If your CPU is rising to 75% and staying there (not bouncing up and down), then it suggest that your script is spinning and not hitting any of your sleep statements.  There's a few things that may be worth looking into.

The while loop in logmgr_run keeps going until enough files have been cleared out.  If this doesn't happen, then it'll never get to the 60 second sleep.
logmgr_delete_oldest will only sleep if it deletes a file, which only happens if the file isn't in use.

I haven't tested it, and it has been a while since I did script programming, but it looks to me like your algorithm breaks down if the oldest file in either folder is being used at the same time that you breach the usage threshold.  It can't delete the oldest file, so it just keeps trying over and over again without succeeding or sleeping.

Rather than having a loop that keeps trying to remove the last file when the threshold is breached it might be better to calculate the amount of files that need to be removed in order to come back under the threshold and try to remove several files in one go / or to skip files if they are in use and move on to the next file rather than stopping and trying the same file again next time.

It may also be worthwhile extending the cleanup to clear a bit more than you need, so that you don't immediately trigger another cleanup next time you go through the loop.  So, for example if you breach 70% usage, clear down the files to 65% or 60% so that there is some growth space.

Your script also has some declared an unused variable, which you should probably either be using (or remove):

max_file_safe=100


I think for the given task, the code is fine.

If you want to do some architecting, here are some thoughts

I'd say the class does two things, timing and updating console
I'd create a worker class that would do the timer stuff
Inject (using dependency injection) an interface that can output stuff
Create an interface that defines "outputting stuff"
Create a console version of that interface
Feed it to the concrete one

It's just refactoring so that you can use the same stuff to write output to different places such as disk, web service etc..


Efficiency of this constantly running time processor for an HTML5 video control bar

If you're worried about performance, this should raise a red flag:

someJQueryObject = $("#some-id");
...
someJQueryObject.html(aPlainOldString);

.html(foo) is almost certainly slower than .innerHTML = foo, because .html() does a bunch of extra stuff, like checking if it can use innerHTML, trying to use innerHTML, catching errors if that fails and using a fallback, etc. Also, using innerHTML is probably slower than simply creating a Text node and updating its data property.

I'd suggest replacing timeProgress = $("#time-progress") with something like this:

var timeProgress = document.createTextNode('');

document.getElementById('time-progress').appendChild(timeProgress);

And replacing timeProgress.html(progressHMS); with this:

timeProgress.data = progressHMS;

This will be a significant performance improvement and will also eliminate the jQuery dependency. Using a large GP library like jQuery to select two elements and update their text content seems like overkill anyway.

Here's a jsPerf demonstrating the performance difference.


Looks fine to me but one way to write a lot less code for these relatively simple ajax calls is to use the Jquery Form plugin that converts a form tag to an ajax call. I believe you'll find it a huge time save going forward.


The good thing about this code is your bracing style which is applied consistently and is visually appealing.  Now on to some improvements:

This code does not implement a Database.  (You have called the class Database, but it does not resemble something that looks like a database).  This class does not really have a good purpose.  If you are going to write a database class it should handle database type things.  Like transactions or methods for select, insert and delete statements etc.

Some other things:

It is not easy to re-use the code.
It contains hard coded values.
It breaks up a logical separation of concerns for your program.
Don't use eval - it is not good for your application security:
eval("\$query = \"$query\";");
oneDatabase::$_database can be replaced by $this->_database as you
are extending that class.
mysqli is mixed in with PDO.  Just use PDO.
databaseCopy is not required
method access should be specified (public, protected, private)

In summary, I think you should re-think your design.


You can get the results with a single query like this one:

var result = await
    (from u in context.Users
     join ui in context.UserInfos on u.Id equals ui.UserId
     where u.AccountName.Contains(query) && ui.HasPicture
     select new UserProfileDTO
     {
         Id = u.Id,
         DisplayName = u.DisplayName,
     }
    ).ToListAsync().ConfigureAwait(false);

This would select all users with a picture in their user-info.

I assumed the UserInfo table has a foreign-key UserId that you can use for joining both tables.

This by the way

user.HasPicture = entity.HasPicture == true ? true : false;

is the same as:

user.HasPicture = entity.HasPicture;


I would use a dictionary to store the choices, and pass the input through capitalize() so, the user doesn't have to write the capitalized word(i am doing this only because you have it that way, but unless you are printing the word as it is, i recommend you to use only lowercase or uppercase to avoid unmatching), also, the while loop is unnecesary because you are calling play() if the user wants to play again.

def play():
    p_choice = input("What do you choose?").capitalize()
    choices = {1 : 'Rock', 2 : 'Paper', 3 : 'Scissors'}
    cpu_choice = choices[random.randint(1,3)]

then, you can do the same thing for all cases, instead of all those conditionals, you can build a dictionary for all cases and then let the compare function return True if its a win or False if its a lose, although i wouldn't recommend you to define the function inside play()

def compare(playerChoice,cpuChoice):
    results = {('Paper','Rock') : True,
               ('Paper','Scissors') : False,
               ('Rock','Paper') : False,
               ('Rock','Scissors') : True,
               ('Scissors','Paper') : True,
               ('Scissors','Rock') : False}
    return results[(playerChoice,cpuChoice)]

and this is my version of game_start()

def game_start():
    begin = input("Would you like to play Rock, Paper, Scissors? ").capitalize()
    while begin != "Yes":
        if begin == "No":
            print("Game Over")
            return sys.exit()
        else:
            print("Please try again")
            begin = input("Would you like to play Rock, Paper, Scissors? ").capitalize()
    play()
    while True:
        begin = input('Play again?').capitalize()
        while begin != "Yes":
            if begin == "No":
                print("Game Over")
                sys.exit()
            else:
                print("Please try again")
                begin = input("Play again? ").capitalize()
        play()

the whole code looks now like this:

import random
import sys

def play():
    p_choice = input("What do you choose?").capitalize()
    choices = {1 : 'Rock', 2 : 'Paper', 3 : 'Scissors'}
    cpu_choice = choices[random.randint(1,3)]
    if p_choice == cpu_choice:
        return print('Tie!')
    if compare(p_choice,cpu_choice):
        return print('You Win!')
    else:
        return print('You Lose!')

def compare(playerChoice,cpuChoice):
    results = {('Paper','Rock') : True,
               ('Paper','Scissors') : False,
               ('Rock','Paper') : False,
               ('Rock','Scissors') : True,
               ('Scissors','Paper') : True,
               ('Scissors','Rock') : False}
    return results[(playerChoice,cpuChoice)]

def game_start():
    begin = input("Would you like to play Rock, Paper, Scissors? ").capitalize()
    while begin != "Yes":
        if begin == "No":
            print("Game Over")
            sys.exit()
        else:
            print("Please try again")
            begin = input("Would you like to play Rock, Paper, Scissors? ").capitalize()
    play()
    while True:
        begin = input('Play again?').capitalize()
        while begin != "Yes":
            if begin == "No":
                print("Game Over")
                sys.exit()
            else:
                print("Please try again")
                begin = input("Play again? ").capitalize()
        play()

game_start()


Performing a special multiplication on two square matrices

From what I can tell, you could combine all of the for loops into only 2 distinct loops:

A loop to setup the matrices used for later calculations
A loop to do the rest of the calculations

Instead of performing list comprehension to create an array to pass to each numpy matrix, you could simply multiply a base array by the len(a) to create said array:

base_list = [[0.0]]*len(a)  # Creates [[0.0], [0.0], [0.0], ... ]

This way you do not temporarily store each element in the xrange object without needing to.

Use more descriptive variable names. What is a, b? Using more descriptive variable names helps improve comprehension and readability.

Here is my version of mult2():

def mult2(a, b):

    AB = a*b
    API, BPI, PITA, PITB = [],[],[],[]

    # Base list used to seed each np.matrix()
    base_list= [[0.0]]*len(a)

    C = np.sum((a*b)**2, axis=1)
    CE1 = np.matrix(base_list)
    CE2 = np.matrix(base_list)
    CE3 = np.matrix(base_list)
    CE1E2 = np.matrix(base_list)
    CE2E3 = np.matrix(base_list)
    CE1E3 = np.matrix(base_list)
    CE1E2E3 = np.matrix(base_list)

    # Create arrays used in later matrix calculations
    for index in xrange(len(a)):
        API.append(np.diag(np.diag(a*PI[index])))
        PITB.append(np.diag(np.diag(PIT[index]*b)))
        BPI.append(np.diag(np.diag(b*PI[index])))
        PITA.append(np.diag(np.diag(PIT[index]*a)))

    # Do matrix calculations
    for index in xrange(len(a)):
        CE1 += np.sum(API[index]*PITB[index]*AB, axis=1)
        CE2 += np.sum(a*BPI[index]*PITA[index]*b, axis=1)
        CE3 += np.sum(AB*API[index]*PITB[index], axis=1)
        CE1E2 += np.sum(API[index]*PITB[index]*API[index]*PIT[index]*b, axis=1)
        CE2E3 += np.sum(a*BPI[index]*PITA[index]*BPI[index]*PIT[index], axis=1)
        CE1E2E3 += np.sum(np.matrix((API[index]*PITB[index])**2), axis=1)

        for pos in xrange(len(a)):
            CE1E3 += np.sum(
              np.matrix(API[index]*PITB[index]*API[pos]*PITB[pos]), axis=1)

    return C - (CE1 + CE2 + CE3 - CE1E2 - CE1E3 - CE2E3 + CE1E2E3)

Remember, good code is readable code: group like statements together.

Also, PEP8 is the Python standard style convention. It provides a very nice style guide for code and helps code look as Pythonic as possible.


Your code is indeed sub-optimal.

When looking at a task do not start writing some loops, but think about it is made up of simpler tasks.

A word is in a two-dimensional crossword grid if any of the below is True:

The word is in any of the rows.
The word is in any of the columns.
The word is in any of the diagonals.

So, the general outline of the method may be:

class WordGrid {
  public contains(String word) {
    return any(word in row for row in getRows())                ||
           any(word in column for column in getColumns())       ||
           any(word in diagonal for diagonal in getDiagonals())
   }
}

Now you just have to translate this pseudocode to real code and implement the three get methods and the problem will be solved.

This is my suggestion because:

The general idea can be understood at a glance, if the reader wants more details he can read the helper methods.
It is made of many small pieces, that may be reused and are simpler to write on their own.
It is general working, for any grid and word size.


Generate points for smooth movement between two given points

Dividor

dividor is ill-defined. It acts as a factor for quantization:

 xi = xi / divider;

But also as threshold for yielding smoothed results:

for (int i = 0; i < divider; i++)

While this seems fine if dividor is \$integer >= 2\$, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.

Usability

GeneratePointsForSmoothMovement is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on IEnumerable<Tuple<Double,Double>> and preferrably also on IDictionary<Double,Double> for faster lookup.

In pseudo code:

public static Func<Double, Double> ToContinuousFunction(
    this IDictionary<Double,Double> points)
{
    return new Func<Double, Double>(x =>
    {
        if (points.TryGetValue(x, out var y))
        {
            return y;
        }

        // .. perform lineair interpolation or extrapolation based on nearby points
    });
}

Let's say we have points (x: 1, y: 10) and (x: 2, y: 20):

var f = points.ToContiniousFunction();
var yValues = new []
{
    f(1)    // 10  (from cache)
   ,f(1.5)  // 15  (interpolation)
   ,f(2)    // 20  (from cache)
   ,f(3)    // 30  (extrapolation)
};


Some notes:

I assume that, for some reason, you want to write your own function/method instead of the existing Date#leap? that @Flambino linked above.
kabisat? We all love our mother tongue, but in computing English is the lingua franca, specially when you share your code with people around the world. It's a nice word to learn, though :-)
This is a personal advice, not all Ruby programmers agree: don't use inline returns. Use the good old full-fledged conditionals, it's much more clear. In general, use expressions instead of statements.

Let's see the standard algorithm. Ok, I'll just translate it to Ruby (if I felt fancy I'd even add Integer#divisible_by?(n) for a fully declarative code):

def is_leap_year?(year)
  if year % 400 == 0
    true
  elsif year % 100 == 0
    false
  elsif year % 4 == 0
    true
  else
    false
  end
end

Too verbose? use boolean logic:

def is_leap_year?(year)
  (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)
end


This is quite a decent implementation of a C++ container! Some minor improvements are possible though:
Prefer using default member initialization
Especially when you have multiple constructors, default member initialization saves typing and reduces the chance of accidentily not initializing a variable. So:
class Queue {
public:
    Queue() = default;

    Queue(const Queue &rhs)
    {
        ...
    }

    ...
private:
    T* data = nullptr; // or {} works as well
    size_t len = 0;
    size_t cap = 0;
    size_t front = 0;
};

Use bitwise AND instead of modulo operations
Calculating the modulus of an integer is very slow compared to doing a bitwise AND (tens of CPU cycles vs. a fraction of a cycle). Since your capacity is always a power of two, you can use bitwise AND, like so:
data[(front + len) & (cap - 1)] = val;

You can get rid of the - 1 if you really want, that means storing the capacity minus one in cap. This will speed up the common case where you don't need to reallocate a tiny bit.
Note that the compiler probably won't be able to optimize the modulo to a bitwise AND by itself, because cap is not a constant.
Consider following the naming conventions of the standard library
It would be nice if your container has the same interface as other STL containers. That makes it easier for a programmer to remember the names of the member functions, but also makes it more likely that your container can be used as a drop-in replacement for other STL containers, and that algorithms that work with a std::queue can also work with your container. So consider renaming these member functions:

GetLength() -> size()
GetFront() -> front()
Enqueue() -> push()
Dequeue() -> pop() (althought the STL's pop() doesn't return any value)
Clear() -> clear()

The reason the STL doesn't return a value for pop() is so that it doesn't require T to be movable, instead you use front() to read the value, then pop() to discard it.
Unnecessary use of this->
There are a few places where you use this-> where it isn't necessary. In the copy constructor it makes a bit of sense since this emphasizes the contrast with rhs., but in ~Queue() and Clear() you don't need it.


It's easy to write very ugly Perl code,
but this is pretty nicely written, so congrats.

Using barewords for file handles like this is discouraged:

open(FILE, "<$srcfile") or die "Couldn't open file: $!\n";
my @lines = <FILE>;
# ...
close FILE;

The recommended way:

open(my $fh, "<$srcfile") or die "Couldn't open file: $!\n";
my @lines = <$fh>;
# ...
close $fh;

Some simplifications are possible.
For example instead of this:

my @srcext = ("*.cpp", "*.c");

I find this way a lot easier to type:

my @srcext = qw/*.cpp *.c/;

Another, bigger simplification is in the loops.
Instead of this:

my @lines = <FILE>;
for($b = 0; $b < scalar(@lines); $b++){
    $srcBytes += length($lines[$b]);
    $totLines++;
    if($lines[$b] =~ /^\s$/){ # is only whitespace ==> newLine
        $newLines++;
        next;
    }
    if(($lines[$b] =~ /^\s*\/\//) || # comments only lines
       ($lines[$b] =~ /^\s*\/\*/) ||
       ($lines[$b] =~ /^\s*\*/)){

You can iterate using for (<$fh>) { ... },
and instead of $lines[$b], benefit from the auto-variable $_,
which can be omitted from $lines[$b] =~ /.../ statements,
like this:

for (<$fh>) {
    $srcBytes += length($_);
    $totLines++;
    if(/^\s$/){ # is only whitespace ==> newLine
        $newLines++;
        next;
    }
    if(/^\s*\/\// || # comments only lines
       /^\s*\/\*/ ||
       /^\s*\*/){


The main improvement you can get is separating your concerns. Currently parsing the commandline, parsing the config file and actually truncating the columns is all mashed up together. Instead write short functions for each of these things:

import configparser
import csv
import sys

USAGE = """
Usage: %s [inputfile] [output file]
This program requires 2 arguments to function properly.
[input file] is the file to clean
[output file] is the name of the file that will be created as a result of this program
"""

def read_config(file_name):
    config = configparser.ConfigParser()
    config.read(file_name)
    return config['CONFIG']

def detect_dialect_from_file(csv_file):
    dialect = csv.Sniffer().sniff(csv_file.read(2048))
    dialect.escapechar = '\\'
    # return to beginning of file
    csv_file.seek(0)
    return dialect

def truncate_row(row, size):
    return [col if len(col) <= size else col[:size - 2] + ".." for col in row]

def truncate_cells(csv_file_name, output_file_name, encoding, size,\
                   output_delimiter, detect_dialect, **kwargs):
    # opens target file and creates the receiving one
    with open(csv_file_name, 'r', newline='', encoding=encoding) as csv_file,\
         open(output_file_name, 'x', newline='', encoding=encoding) as output_file:
        # helps with parsing
        dialect = (detect_dialect_from_file(csv_file)
                   if detect_dialect
                   else "excel")
        reader = csv.reader(csv_file, dialect)
        dialect.delimiter = output_delimiter
        writer = csv.writer(output_file, dialect)
        # loops through file's lines
        for row in reader:
            # writes in new file
            writer.writerow(truncate_row(row, size))

def main():
    print(len(sys.argv))
    if len(sys.argv) < 3:
        print(usage % (sys.argv[0]))
        sys.exit(1)
    # reads the config file
    config = read_config('csv_cleaner.ini')
    config['size'] = int(config['truncation_size'])
    config['detect_dialect'] = bool(config['detect_dialect'])

    truncate_cells(sys.argv[1], sys.argv[2], **config)

if __name__ == "__main__":
    main()

Here I made the following additional changes:

According to Python's official style-guide, PEP8, lines should be indented by 4 spaces. Also spaces should surround operators and keywords. Imports should also be on separate lines.
While [col[:(size-2)]+(col[(size-2):]and'..')for col in row] works, I find [col if len(col) <= size else col[:size - 2] + ".." for col in row] a bit more readable.
When detect_dialect is false in your case, the script should not run (since it is all nested under that if). But since the value is a string, it is truthy, regardless of whether or not you put True or False there.
When using a multiple line string using triple-quotes, there is no need to use explicit line-breaks and line-continuation characters. I made it a global constant here to avoid indentation issues.

Note that I (or rather my linter) think that 'x' is not a valid file mode.


I'm not completely sure about the requirements, but what about the following?

public static String findWord2(final String text) {
    for (int i = text.length() - 1; i > 0 ; i--) {
        final String first = text.substring(0, i);
        final String last = text.substring(text.length() - i);
        if (first.equals(last)) {
            return first;
        }
    }
    return text;
}

Here are my tests:

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class FindWords2Test {

    private final String expected;
    private final String input;

    public FindWords2Test(final String expected, final String input) {
        this.expected = expected;
        this.input = input;
    }

    @Parameters
    public static Collection<String[]> data() {
        //@formatter:off
        final String[][] data = new String[][] {
                {"file", "file = new JarFile(new File()\nSystem.out.println(file"},
                {"file ", "file = new JarFile(new File()\nSystem.out.println(file "},
                {"file = new JarFile(new File()\nSystem.out.println(",
                    "file = new JarFile(new File()\nSystem.out.println("},
                {"args", "args"},
                {"", ""},
                {"a", "a"},
                {"a", "aa"}};
        //@formatter:on
        return Arrays.asList(data);
    }

    @Test
    public void testFindWords() throws Exception {
        assertEquals(expected, FindWords2.findWord2(input));
    }
}


Recursively listing the content of an FTP server

Seems good except for a few small improvements:

path_+"/"+name is better perceived with f-string formatting: f'{path_}/{name}
user if user else default_user is a verbose version of user or default_user


C++ Data-Oriented Modules using namespaces and extern

Your header file is missing include guards. Either put #pragma once at the start, or use the more portable:

#ifndef MESH_H_
#define MESH_H_

// ... rest of header

#endif

MESH_H_ has to be unique for the file.

namespace OpenGL{

If you don't own OpenGL, I'd recommend not naming your namespace after it. If they release OpenGL in a namespace, your code wouldn't be compatible. Try to use a namespace for your project. Similarly, I'd recommend not naming your header OpenGL.h, unless you put the header in a directory.

extern vector<Vertex> allVertices;
extern vector<unsigned int> allIndices;
extern vector<Material> allMaterials;
extern vector<Mesh> allMeshes;

extern string MESH_DIR;
extern vector<string> meshNames; //find mesh index by name

I'm assuming that in OpenGL.h, you have using namespace std;. Don't do this. It is especially bad in a header.

Also, if you find yourself using extern globals, you are almost certainly doing it wrong. These should either not exist at all (as in the calling code takes care of it), or they should be wrapped in a class that the calling code passes around.

These globals and the following point out that you really need to define a class. Maybe something like this:

class MeshManager { // this name is suspicious; "Manager" in a name is usually bad.
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;
    std::vector<Material> materials;
    std::vector<Mesh> meshes;

    std::string meshDirectory;
    std::vector<std::string> meshNames;

public:
    void setMeshDirectory(std::string directory);
    void loadAllMeshes();

    Mesh loadMesh(std::string filename);
    void addMesh(std::string filename);
};

Note that this design isn't the best. You still need a constructor, and possibly accessors on the member variables. Also, setMeshDirectory and loadAllMeshes might be better as a constructor to MeshManager, or a static factory function if you prefer that style.


Looks ... great?  Not a lot to complain about really.

The semaphore doesn't do anything though used like this, it should be
passed in from the top to protect the get/aiohttp.request.  You can
see that if you print something right before the HTTP request.

Also, the result of asyncio.as_completed will be in random order, so
be sure to sort the resulting chapters somehow, e.g. by returning both
the URL and the collected text from extract_text.

A couple of small things as well:

List comprehensions are okay, but with just a single argument it can
be shorter and equally performant just to use map.
The URL constants should ideally be defined on the top level; at least
base_url can also be defined by concatenating with start_url.
Alternatively they could be passed in to generate_links.  Then
again, it's unlikely that another blog has the exact same layout?
The manual append in run seems unnecessary, I'd rewrite it into a
list of generators and use a list comprehension instead.
At the moment generate_links is called from run; I think it makes
more sense to call it from the main function: it doesn't need to run
concurrently and you could think of a situation where you'd pass in
the result of a different function to be fetched and collected.

All in all, I'd maybe change things to the code below.  Of course if you
were to add things to it, I'd recommend looking into command line
arguments and configuration files, ...

import aiohttp
import asyncio
import requests
from lxml import etree

@asyncio.coroutine
def get(*args, **kwargs):
    """
    A wrapper method for aiohttp's get method. Taken from Georges Dubus' article at
    http://compiletoi.net/fast-scraping-in-python-with-asyncio.html
    """
    response = yield from aiohttp.request('GET', *args, **kwargs)
    return (yield from response.read_and_close())

@asyncio.coroutine
def extract_text(url, sem):
    """
    Given the url for a chapter, extract the relevant text from it
    :param url: the url for the chapter to scrape
    :return: a string containing the chapter's text
    """
    with (yield from sem):
        page = yield from get(url)

    tree = etree.HTML(page)
    paragraphs = tree.findall('.//*/div[@class="entry-content"]/p')[1:-1]
    return url, b'\n'.join(map(etree.tostring, paragraphs))

def generate_links():
    """
    Generate the links to each of the chapters
    :return: A list of strings containing every url to visit
    """
    start_url = 'https://twigserial.wordpress.com/'
    base_url = start_url + 'category/story/'
    tree = etree.HTML(requests.get(start_url).text)
    xpath = './/*/option[@class="level-2"]/text()'
    return [base_url + suffix.strip() for suffix in tree.xpath(xpath)]

@asyncio.coroutine
def run(links):
    sem = asyncio.Semaphore(5)
    fetchers = [extract_text(link, sem) for link in links]
    return [(yield from f) for f in asyncio.as_completed(fetchers)]

def main():
    loop = asyncio.get_event_loop()
    chapters = loop.run_until_complete(run(generate_links()))
    print(len(chapters))

if __name__ == '__main__':
    main()


Using nullable properties in a base class for record selection in Table per Hierarchy

It's hard to answer your question with a definitive answer as so much information is missing and a lot, depends also on the other UI screens data that you need to fill or that other may have opened. You’re going to get issues when performing aggregates on the same table that you provide row data on as you might end-up in a deadlock, even with yourself. I'm going to give some basic data that goes through my mind, if you already know this, no harm done, just skip over it.

1 Transaction scope:
Say you have a transaction summing over the charges and payments to get a balance, you also would like to return the last 10 charges as well as the last 10 payments. We all know that there is no guarantee that charges and payments sum-up you will get into partial payments.

Then users will use a invoice reference number in the payments so you need to book a payment to that reference even if there are older charges that would incur late fees (this may actually be a business case for some companies as they charge more).

You're may not be able to guarantee that the table is partitioned in a way that would facilitate transactional isolation levels to that detail so you will likely need to set your connections to allow for a snapshot isolation level (this will hit your tempdb with snapshot data so size for that) as you have no or little control over the TSQL generated by EF. If you can think of the data that you your using as  ViewModel class in MVC that that would help, you do not need take the whole table into memory when you a limited subset. You will have less issues when you’re updating the data that another user might also be updating

public class FooViewConfiguration : EntityTypeConfiguration<FooView>
{
   public FooViewConfiguration()
   {
    this.HasKey(t => t.Id);
    this.ToTable("dbo.myView");
   }
  …
}

You will find that you’re users are getting optimistic concurrency exceptions (you never get them as you’re the only one changing the data in your database) so you’re data scope needs to deal with that. Have a look at

using (var context = new PaymentTransactionContext())
{
    var payment = context.Payments.Find(1);
    payment.PayedByName = "client Name";
    payment.PaymentDate = UTCNow;

    bool saveFailed;
    do
    {
        saveFailed = false;

        try
        {
            context.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            saveFailed = true;

            // Update the values of the entity that failed to save from the store
            ex.Entries.Single().Reload();
        }

    } while (saveFailed);
}

And only save that where you have a change.

using (var context = new MyContext())
{
    context.ChangeTracker.TrackGraph(customer, e =>
    {
        e.Entry.State = EntityState.Unchanged;

        if((e.Entry.Entity as Invoice) != null)
        {
            if (e.Entry.IsKeySet)
            {
                e.Entry.State = EntityState.Modified;
            }
            else
            {
                e.Entry.State = EntityState.Added;
            }
        }
    });

    foreach (var entry in context.ChangeTracker.Entries())
    {
        Console.WriteLine("Entity: {0}, State: {1}", entry.Entity.GetType().Name, entry.State.ToString());
    }
    context.SaveChanges();
}

You limit this by using an (indexed) view and control the locking using TSQL, you can update data in a view either direct if only one table is involved or by using "instead of" triggers when you join several tables.

2 Indexing and locks: You might have some and you might find that your indexes are disabled (they get broken on ETL import errors) or those that you need are missing you will usually end-up with table locks as the dbms has alternative as the only option is a table scan or index scan (yes, both are bad).

Adding to many indexes will really slow down the inserts as they need to be maintained as well. Depending on the size and quantity of an index that might get out of hand. (once worked on a project where I had to drop all indexes, then do a backup and re-create the indexes in order to backup and maintain the recovery time objectives).

Also indexes, and covering indexes will widen the scope of the data as this needs to be locked as well.

What one ends-up doing is design a database that has indexes on join fields first. The way you limit the scope and speed up your table is by "removing unrelated data" as early as possible, the smaller the scope the smaller the lock the less disk I.O. SQL server executes the plan after a given time, might not be the best plan, but you do not want to wait 2 seconds for him to figure it out (that's why you can pre-compile plans and attach them). Usually what I end-up doing is make 2 connections/ contexts. I normally have a database connection with a read-only intend. And one with a read-write intend. This way will save yourself quite a few locking issues and note that this is what makes working with large databases so slow, you quickly end up locking too much and read too much. The read-only will do most of the heavy lifting and cause little or no issues as the intend and transaction levels help.

3 Database are for storing data, they are not OO: Sql server does support graph, and you would get some kick-ass performance however EF doesn’t as far as I know.  So, if getting a bigger database I advice to not use OO design from the class as a mirror on the SQL tables, it’s not going to perform, go to the 6th nominal form and start duplicating data. Or create a physical table for all 3  using a 1-1 optional relationship (a foreign key that is disabled for query plans) and a trigger for data integrity
Also, I think that Proposal is a perhaps a ChargeTrasnaction that has a flag of being accepted… could this be

I think, try having a customer with relationships on "view model"/"unit of work" scoped data using ICollection for all relations and really limit what you load using the above mentioned option.

You can always use EF and SqlCommand and use the best of both worlds when ever you need.


Return true if the elements of an array do not contain one or the other

In JDK there's nothing, but with Guava you could do

List<Integer> list com.google.common.primitives.Ints.asList(nums);
return !(list.contains(1) && list.contains(4));

Obviously, converting int[] to something like ArrayList<Integer> would be a performance disaster. Fortunately, there's nothing like this, instead there's a class implementing the List interface by accessing the primitive array. Bulk-methods like contains are optimized and lead to a simple loop with no boxing inside.

But seriously, feel free to stick with your loop, as there's not always such a trick available. What you could improve:

You need no xxxCount, a simple boolean containsXxx would do. But this is no problem, having the count may be useful sometimes.
You could use an early return. Whenever you find a 1, you can check if you have already a 4 and return false if so.

The only part I dislike is

if (oneCount > 0 && fourCount > 0) {
    return false;
}
return true;

You surely mean

return oneCount == 0 || fourCount == 0;

If performance was very important (which it rarely is), I'd try this

int i = 0;
int missing;
for (; ; i++) {
    if (i == nums.length) {
        return true;
    } else if (num[i] == 1) {
        missing = 4;
        break;
    } else if (num[i] == 4) {
        missing = 1;
        break;
    }
}
for (; i < nums.length; i++) {
    if (nums[i] == missing) {
        return false;
    }
}
return true;

But as you can see, it's terribly long and not very readable. When embedded in a real code it may also be slower (due to inlining limit or whatever).


Typeahead autocomplete functionality challenge

Organisation of the function

You are doing many things in the same function which make the whole thing a bit confusing. First thing to do is to split the two main parts of the functions : one does preprocessing on usernames, one handles queries. One this is done, your code looks like :

def typeahead(usernames, queries):
    # Pre-processing on usernames
    username_lower = [item.lower() for item in usernames]
    username_lower = sorted(username_lower)

    alphabet = [[] for x in xrange(26)]
    myDict = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}

    [alphabet[myDict[username[0]]].append(username) for username in username_lower]

    # Handling the queries
    matches=[]
    amount_of_queries = len(queries)
    results = [-1]*amount_of_queries
    queries_lower = [query.lower() for query in queries]
    querylen = [len(query) for query in queries]
    for q in xrange(amount_of_queries):
        matches[:] = []
        quer = queries_lower[q]

        if querylen[q]==1:
            results[q] = alphabet[myDict[quer[0]]][0]
        else:
            matches = [item  for item in alphabet[myDict[quer[0]]] if quer==item[:querylen[q]]]
            if len(matches)>=1:
                results[q]= matches[0]

    print '\n'.join(map(str, results))

Before we go any further, something to keep in mind

I am not quite sure that this is an issue but in your example, your print lower-case usernames even though usernames with their original case is printed on this original problem.

Making your map from letters to username a bit cleaner

At the moment, you always use alphabet and myDict together. This is a good sign that something is wrong. (Also, if you really want to map letters to their index, you don't need dictionnary with hardcoded value, you just need arithmetic, ord/chr). If what you want is just to match letters with the list of corresponding usernames, you can use normal dictionnary and check if items are already present, normal dictionnary and fill with empty list from the very beginning or you could play it smart and use Python good stuff as defaultdict and setdefault :

from collections import defaultdict
mapping = defaultdict(list)
mapping2 = dict()
for username in usernames:
    low = username.lower()
    mapping[low[0]].append(low)
    mapping2.setdefault(low[0], []).append(low)

I'll assume we are using the defaultdict option from now.

In order to integrate this part of the solution in your code, let's remove the duplicated code from what we have in the part handling the queries :

for q in xrange(amount_of_queries):
    matches[:] = []
    quer = queries_lower[q]

    candidates = alphabet[myDict[quer[0]]] ### THIS IS WHAT IS HAVE ADDED
    if querylen[q]==1:
        results[q] = candidates[0]
    else:
        matches = [item  for item in candidates if quer==item[:querylen[q]]]
        if len(matches)>=1:
            results[q]= matches[0]

Replacing this with our defaultdict logic, we get :

def typeahead(usernames, queries):
    # Pre-processing on usernames
    mapping = defaultdict(list)
    for username in usernames:
        mapping[username.lower()[0]].append(username.lower())

    # Handling the queries
    matches=[]
    amount_of_queries = len(queries)
    results = [-1]*amount_of_queries
    queries_lower = [query.lower() for query in queries]
    querylen = [len(query) for query in queries]
    for q in xrange(amount_of_queries):
        matches[:] = []
        quer = queries_lower[q]

        candidates = mapping[quer[0]]
        if querylen[q]==1:
            results[q] = candidates[0]
        else:
            matches = [item  for item in candidates if quer==item[:querylen[q]]]
            if len(matches)>=1:
                results[q]= matches[0]

    print '\n'.join(map(str, results))

Please note that I took this chance to remove the list you were building with a useless list-comprehension.

Handling the queries

As you are about to iterate on queries anyway, there's no real need to build lists with information you will need. You can just iterate over queries and that will do the trick.

Also, you can initialise matches inside the loop and use enumerate if you really need the index. At this point, the part of the code looks like :

# Handling the queries
results = [-1]*len(queries)
for i,q in enumerate(queries):
    matches=[]
    low_quer = q.lower()
    l = len(low_quer)

    candidates = mapping[low_quer[0]]
    if l==1:
        results[i] = candidates[0]
    else:
        matches = [item  for item in candidates if low_quer==item[:l]]
        if len(matches)>=1:
            results[i]= matches[0]

Finally, we don't even need the indices as we can build results as we go. Also, we don't need matches in that part of the function. Things get even more concise :

# Handling the queries
results = []
for q in queries:
    low_quer = q.lower()
    l = len(low_quer)

    candidates = mapping[low_quer[0]]
    if l==1:
        results.append(candidates[0])
    else:
        matches = [item  for item in candidates if low_quer==item[:l]]
        if len(matches)>=1:
            results.append(matches[0])
        else:
            results.append('-1')

Another issue found

What if we look for "c" ? At the moment, we'll do results.append(candidates[0]) with an empty list of candidates : this will crash. This should be handled much the same way we do for longer strings : check if we do have a match. Also, this removes some unrequired logic :

# Handling the queries
results = []
for q in queries:
    low_quer = q.lower()
    l = len(low_quer)

    matches = [item for item in mapping[low_quer[0]] if low_quer==item[:l]]
    if len(matches)>=1:
        results.append(matches[0])
    else:
        results.append('-1')

If we want to play it cool, we can use the fact that in a boolean context, an empty list is considered False while a non-empty list is considered True. Also, we can use the ternary operator. Finally, because I am now using the string -1 and not the integer, we don't need the conversion to string at the end. We get :

# Handling the queries
results = []
for q in queries:
    low_quer = q.lower()
    l = len(low_quer)

    matches = [item for item in mapping[low_quer[0]] if low_quer==item[:l]]
    results.append(matches[0] if matches else '-1')

print '\n'.join(results)

Using the right function

Using startswith you don't need to do some tricky string handling :

# Handling the queries
results = []
for q in queries:
    q = q.lower()
    matches = [item for item in mapping[q[0]] if item.startswith(q)]
    results.append(matches[0] if matches else '-1')

Your final code becomes :

def typeahead(usernames, queries):
    # Pre-processing on usernames
    mapping = defaultdict(list)
    for username in usernames:
        low = username.lower()
        mapping[low[0]].append(low)
    print mapping

    # Handling the queries
    results = []
    for q in queries:
        q = q.lower()
        matches = [item for item in mapping[q[0]] if item.startswith(q)]
        results.append(matches[0] if matches else '-1')

    print '\n'.join(results)

A few things are not perfect yet : the fact that we get the lower-case name, the fact that we haven't sorted the values but I'll let your play with this.

And now for something different

The trick you have used to map first letter to potential candidates makes things at most 26 times faster. In real life, this performance boost will not be that huge because usernames are not uniform over the alphabet. You might want to generalise this trick over all letters of the words. Here are a few pages that you might find interesting :

http://en.wikipedia.org/wiki/Suffix_tree
http://en.wikipedia.org/wiki/Suffix_array
http://en.wikipedia.org/wiki/Trie


One hurdle is that I can't send and receive simultaneously in the same thread. Thus, I'm forced to send and receive in separate threads.

Naturally. This is because "send" and "receive" for a chat server behave asynchronously, and block on different events. Haskell's threads are lightweight, so you can write your code using blocking calls and multiple threads, and rest assured that behind the scenes Haskell is using epoll.

You could modify the chat server so that the client is required to give a special command in order to read new messages, in that case only one thread would be needed, since all messages from you to the client would depend directly on that particular client's input. But then it wouldn't feel much like a chat program.

  [Haskell] so hard to reason about, especially when exceptions come into the picture.

Exceptions are best avoided in Haskell, but you seem to have been able to reason about them fairly well. Did you have any specific issues reasoning about your code? I think it might be fair to replace [Haskell] with [Concurrent programming]; exceptions and concurrency are inherently at odds, in any language.

  Is this a good approach? Is there a better way to organize network code like this?

I think it's pretty good. I don't do much networking code so take my opinion with a grain of salt.

Clearly this is just some simple example code, but you might want to consider allowing the client to send a special message to stop interacting with the server, so that disconnecting is not entirely dependent on exceptions.


Creating method to use one foreach instead multiple

First step is to look at the repeated code then copy an single into a method.
In this case a could method name would seem to be CreateDataTable.

What are the commonalities?

A ComboBox that has checked items.
Get an IQueryable or IEnumerable depending on which is returned by the where clause
Creates a list of the text value from each checked item
Creates a DataTable using ToStringDataTable(parameters

Since the type in and type out is all the same, this makes it much easier to refactor out into a method. The question then is what input and what output?

Input = ComboBox, output = `DataTable'. This give the method signature needed:

DataTable CreateDataTable(ComboBox cbo) {
}

Now put in those lines that are repeated and change the *Status to cbo and instead of assigning the DataTable just return the result of ToStringDataTable(parameters).

DataTable CreateDataTable(ComboBox cbo) {

    var checkedItems = cbo.CheckBoxItems.Where(x => x.Checked);
    List<string> parameterList = new List<string>();
    foreach (var i in checkedItms) {
        parameter.Add(i.Text);
    }

    return ToStringDataTable(parameters);
}

Now clean up the original method:

public class Refactor {
  private void BtnLoadReport_Click(object sender, EventArgs e)
    {
        var db = new SQLDataMgr();

        var designStatusParameters = CreateDataTable(cboDesignStatus);
        var shopStatusParameters = CreateDataTable(cboShopStatus);
        var customerTypeParameters = CreateDataTable(cboCustomerType);
        var customerParameters = CreateDataTable(cboCustomer);
        var resellerParameters = CreateDataTable(cboReseller);
        var stateParameters = CreateDataTable(cboState);
        var projectManagerParameters = CreateDataTable(cboProjectManager);
        var salesRepresentativeParameters = CreateDataTable(cboSalesRepresentative);
        //Rest of the method
    }
}

This could be further improved by using some additional LINQ chains if the items returned by the where clause supports them.

Example:

List<String> parameters = cbo.CheckBoxItems.Where(x => x.Checked).Select(x => x.Text).ToList();

which would simplifying the method even further:

DataTable CreateDataTable(ComboBox cbo) {

    List<string> parameterList = List<String> parameters = cbo.CheckBoxItems.Where(x => x.Checked).Select(x => x.Text).ToList();

    return ToStringDataTable(parameters);
}


Let’s refactor it a little bit for clarity and symmetry. We could have this class shared:

class NamedTokenSource : CancellationTokenSource
{
    const string Namespace = "4978406A-A7C0-4DE7-93C8-6BDB1145ED32";

    public static implicit operator NamedTokenSource(string name) =>
        new NamedTokenSource(name);

    public NamedTokenSource(string name)
        : this(new EventWaitHandle(false, EventResetMode.ManualReset, name + Namespace))
    {
    }

    public NamedTokenSource(EventWaitHandle handle)
    {
        Handle = handle;
        ThreadPool.RegisterWaitForSingleObject(handle, (s, to) => Cancel(), null, -1, true);
        Token.Register(() => handle.Set());
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        if (disposing)
            Handle.Dispose();
    }

    EventWaitHandle Handle { get; }
}

Now Controller looks like:

NamedTokenSource cts = "WorkerTokenSource";
Console.WriteLine("Press ENTER to cancel...");
Console.ReadLine();
cts.Cancel();

when Worker is:

NamedTokenSource cts = "WorkerTokenSource";
Console.WriteLine("Waiting for cancellation...");
cts.Token.WaitHandle.WaitOne();