#include<iostream>
#include<vector>
#include<random>
#include<chrono>

Leave some space between the #includes and the rest of your code, that's easier to read. Besides, I really like <chrono> myself too, but you don't seem to use it afterwards.

using namespace std;
using namespace std::chrono;

using directives for a whole namespace is a bad idea. You risk conflicts between the names defined in std (and there's quite a lot of them) and those you define yourself. Safety is worth a few more keystrokes.

vector<int> merge(vector<int> a,vector<int> b){

That function signature means you're passing a and b by value, that is to say you copy the argument vectors. It might be the good move sometimes, but here it isn't, because you only read them. So const std::vector<int>& a, const std::vector<int>& b is better.

    int i=0;
    int j=0;

i, j, why not? but it doesn't scream what you'll be using those variables for.

    vector<int> result;
    while(i<a.size()&&j<b.size()){

I would rather use iterators in the first place (I mean, in the function's signature), because:

it avoids comparison issues (vector.size() is unsigned, whereas i and j are signed)
it makes it easier to write and use generic code
it allows you to merge sequences which are only a part of a container, or even inside the same container.

if(a[i]<b[j]){

There's a trick here: if a[i] == b[j] you'll insert b[j] first. It might be innocuous -it is for an int- but programmers expect that min(a, b) will return a if a == b. Since a sorting algorithm is a good candidate for abstraction (a vector of strings is sorted the same way as a vector of ints or floats), you should respect that rule.

        result.push_back(a[i]);
        i++;

Unless you need to keep track of the old value, use pre-incrementation (++i) since i++ creates and returns a temporary value.

        }
        else{
            result.push_back(b[j]);
            j++;
        }
    }
    while(i<a.size()){
        result.push_back(a[i]);
        i++;
    }
    while(j<b.size()){
        result.push_back(b[j]);
        j++;
    }

copy and paste is an anti-pattern. Standard algorithms will provide what you need in a more elegant way, especially if you use iterators: std::copy(current_a, a.end(), std::back_inserter(result));

    return result;
}

vector<int> mergesort(vector<int> a,int low,int hi){
    vector<int> b,c,result;
    if(low==hi)
        return {a[hi]};
    b=mergesort(a,low,(low+hi)/2);
    c=mergesort(a,(hi+low)/2+1,hi);
    result=merge(b,c);
    return result;
}

This part is all right, even if I believe you should try to reduce the place you need to merge-sort or at least the number of allocations.

int main(){

    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0,90); // define the range
    vector <int> num;
    for(int i=0;i<30;i++)
        num.push_back(distr(eng));
    vector<int> a=mergesort(num,0,num.size()-1);
    for(auto &i:a)

You generally don't take integers by reference (a reference is the size of or bigger than an int, and you don't take non-const references when you don't modify the variable, which you don't.

        cout<<i<<" ";
}


How to efficiently (fast) calculate the transpose of a *permutation matrix* in Python3?

Perhaps only marginally, but the readability of your code can be improved by using enumerate and the reverse=True flag in sorted.

def transpose_r(ls):
    return [len(ls)-1-k
            for k, Pk in sorted(enumerate(ls),
                                reverse=True,
                                key=itemgetter(1))]

If we index starting from the left, then this is further simplified.

def transpose_l(ls):
    return [x for x, Px in sorted(enumerate(ls), key=itemgetter(1))]

The transpose has the funny property that transpose(ls)[ls[j]] == j. We can use this to build the transpose without sorting.

def transpose_l(ls):
    tr_ls = [0]*len(ls)

    for l in ls:
        tr_ls[ls[l]] = l

    return tr_ls

def transpose_r(ls):
    n = len(ls)
    tr_ls = [0]*n

    for l in ls:
        tr_ls[n - 1 - ls[l]] = n - 1 - l

    return tr_ls

Alternatively, we can use enumerate again.

def transpose_l(ls):
    tr_ls = [0]*len(ls)

    for ix, l in enumerate(ls):
        tr_ls[l] = ix

    return tr_ls

def transpose_r(ls):
    n = len(ls)
    tr_ls = [0]*n

    for ix, l in enumerate(ls):
        tr_ls[n - 1 - l] = n - 1 - ix

    return tr_ls


There isn't really any great performance improvement to be made here in my opinion.  You original structure is going to require nested loop approach to generate your desired structure regardless.

My only suggestion would be building an array of objects in your result rather than an array of associative arrays, as I think what you have shown in your example is more meaningful as objects (i.e. items that have a set of properties) vs. as an associative array (which I typically like to use more for hashmap type of use cases).


WPF Extension to directly inject dependencies in the Window constructor

Constructor injection is indeed preferable, but it's not the only way to inject dependencies - property injection is just as valid, and in the case of a WPF Window, the only dependency that should be injected, is the ViewModel - and Window already has a property exposed for that: DataContext.

Assuming a Model-View-ViewModel architecture, I cannot think of a single valid reason to constructor-inject anything into a View. The role of the View in MVVM is to be nothing more than a simple I/O device presenting data to the user, and exposing means for that user to provide inputs.

That means a View needing dependencies injected is highly suspicious, because it suggests that the View is at least partly doing the ViewModel's job, and this is going to make that logic much more difficult to test than if it were done elsewhere: the idea behind separating the View from the ViewModel isn't just to leverage the powerful XAML data bindings, it's also to get as much of the not-stricly-presentation concerns out of the View so that they can be unit-tested without popping up a UI.

Now, as I said in an earlier comment, maybe I'm doing this wrong, but I've never had issues with this approach: I remove the StartupUri in the App.xaml markup, and then edit App.xaml.cs to override OnStartup as follows:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup();
    // if you're using an IoC container, this is where you set it up:
    // ...

    // if you're using an IoC container, this is where you resolve your VM's dependencies:
    // ...
    // otherwise, just new it up:
    var vm = new MainWindowViewModel(/*ctor-inject dependencies manually here*/);
    var window = new MainWindow { DataContext = vm };
    window.ShowDialog();
}

The IoC configuration code should go into its own method (could be in App.xaml.cs, or in some static helper), of course. But the point remains: the view doesn't have any dependencies, other than its view model.

The MainWindow.xaml.cs code-behind might look like this:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContextChanged += MainWindow_DataContextChanged;
    }

    MainWindowViewModel ViewModel => DataContext as MainWindowViewModel;

    private void MainWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var vm = ViewModel;
        if (vm != null)
        {
            vm.Close += HandleViewModelCloseCommand;
        }
    }

    private void HandleViewModelCloseCommand(object sender, EventArgs e)
    {
        Close();
    }
}

Everything else belongs in the ViewModel: any ICommand you might want to inject, any service, unit-of-work/repository, "business logic" worker objects - none of these are dependencies of the window itself.

Since a WPF window needs no dependencies, the base premise falls apart, and all that code can be deleted.


Get argument as unicode string from argparse in Python 2 and 3

You can define unicode for Python3 when you get a NameError.
You should make a small note that explains unicode is not defined in Python3, rather than having the user guess, what #py3 means.

try:
    unicode
except NameError:
    # Define `unicode` for Python3
    def unicode(s, *_):
        return s

You should use the type parameter to add_argument, to change the type returned.
And so if you don't want to have unicode in the global scope in your Python3 environment you can bind it to that functions scope.

def build_to_unicode():
    try:
        unicode
    except NameError:
        def unicode(s, *_):
            return s

    def inner(s):
        return unicode(s, "utf-8")

    return inner

to_unicode = build_to_unicode()

Also your lack of a definitive style to pass variables to the parser made it harder for me to read your code.

try:
    unicode
except NameError:
    # Define `unicode` for Python3
    def unicode(s, *_):
        return s

def to_unicode(s):
    return unicode(s, "utf-8")

parser = argparse.ArgumentParser(
    description='Organize your movie collection using symbolic links')
parser.add_argument(
    'media_src',
    metavar='FILE|DIR',
    help='Media file or directory',
    type=to_unicode)

args = parser.parse_args(args=argv[1:])
# If you really want to.
args = vars(args)


Function to copy characters from one buffer to another given the maximum size

The function copy_max() is mis-named, No one maintaining this code would know from the name of the function that the from string is being shortened by the from.erase(from.begin(), prev_pos). Copy does not imply destruction of the source, move might be more appropriate.

You may also want to consider the Single Responsibility Principle and break copy_max() into multiple functions. I see at least 2 functions there. This loop is complex enough to be it's own function and can be called from
copy_max()

    while(pos != from.end() && index <= limit)
    {
        prev_pos = pos;
        pos = std::find(pos + 1, from.end(), delim);
        index = std::distance(from.begin(), pos);
    }

Doing so makes the logic of copy_max() clearer.

I'm fairly sure that you can calculate index only once. I'm not sure why it's being calculated in 3 different places in copy_max().

The title is miss leading as well, since this will copy more than just characters.


There's a number of issues with your code. I'll walk through your class pointing out several issues as I go along:

class Timer {

    private $_db;
    public $user_id;

I'll just mention the same point as chervand mentioned here, but it applies to the entire class: coding standards matter, Please follow the PSR standards as much as possible: brackets go on a new line, private or protected property names needn't start with an underscore (that's something that stems from the old PHP4 days).
Also try to add doc-blocks, documenting what arguments should be passed, and what the value/type of each property is:

class Timer
{
    /**
     * @var PDO
     */
    protected $db = null;//protected, in case you'll extend this class
    /**
     * @var int
     */
    public $userId = null;//I'm assuming int, and I prefer camelCase

Next: your constructor: you're expecting the user to pass a "db". You don't specify what that variable must be. Use type-hints to prevent users from passing invalid things to methods. Especially when you're dealing with dependencies.

The userId argument is also required to be passed to the constructor. If it is that important to have this value, then why is it public? There's nothing stopping me from doing something like this:

$timer = new Timer($pdo, 123);
$timer->userId = 'Some invalid value';

It's probably best to make the property protected here, or require the caller to pass the userId as an argument to the methods that require this value. Anyway...

Here's how I'd write the constructor:

    public function __construct(PDO $db, $userId)
    {//PSR

        $this->db = $db;
        $this->userId = (int) $userId;//cast to int, so we're sure we're not dealing with a string
    }

Moving on:

    public function checkActiveTimer()
    {//PSR

        $db = $this->db;

        $query = $db->prepare("SELECT * FROM qrm_logs WHERE `active` = :active");
        $query->execute(array(

            ':active'   =>  1

        ));

        $result = $query->fetchAll(PDO::FETCH_OBJ);

        if (count($result) > 0) {

            return true;

        }

        return false;

    }

your methods, almost all of them, have the same problem: they don't take any arguments, they contain hard-coded (and sometimes bad) queries. They don't handle possible exceptions, you're using prepared statements (which generally is a good thing), even if you don't (in which case, prepared statements are just overhead).
The biggest problem with your using prepared statements, though, is that you're missing out on the best part about them. Prepared statements allow you to re-use a query. You're preparing the same query string over and over again... pointlessly. Here's what my method would look like:

public function getActiveTimerCount()
{
    $stmt = $this->db->query(
        "SELECT COUNT(`active`) as cnt FROM qrm_logs WHERE `active` = 1"
    );
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return (int) $row['cnt']
}

Now this method is a lot shorter. I know that active will be 1, so I'm not at risk of SQL injection attacks here. Instead of fetching all rows, I'm asking the DB to return me the row count, and I'm returning the count. This is more informative to the caller. 0 is still a fasly value, other values are truthy. The caller can still use this method as though it returned a boolean. However, because I'm returning the actual count, the caller can use the same method to work out how many active timers there are.

I also got rid of that reassignment ($db = $this->_db). It's personal preference mainly, but in this case, I think $this->db->query is just as easy to read.
The same basic comments apply for the getTimerTypes method

First, slightly late update

Ok, I promised to revisit this review when I had the time, it took some patience, but I found a free 15min, which I'll spend reviewing this code:

public function getTime() {

    $db = $this->_db;
    $user_id = $this->user_id;

    $query = $db->prepare("SELECT `started_at` FROM qrm_logs WHERE `active` = :active AND `user_id` = :user_id");
    $query->execute(array(

        ':active'   =>  1,
        ':user_id'  =>  $user_id

    ));

    $result = $query->fetchAll(PDO::FETCH_OBJ);

    if (count($result) > 0) {

        foreach ($result as $time) {

            $date = new Datetime($time->started_at);
            $date2 = new Datetime();

            $difference = $date2->getTimestamp() - $date->getTimestamp();

            return $difference;

        }

    }

    return false;

}

As before, the comments about PSR coding standards, and there being no real need to reassign the properties to local variables still apply.

You are using prepared statements, and you're using them to use the userId value (which is provided by the caller, and therefore not to be trusted) safely. This of course makes perfect sense. You're also binding a hard-coded 1 which really doesn't make that much sense at all. For starters, if this value is something only of interest to your class, you'd probably want to define it as a constant. If the value ever needs to change, it's easier to change the value assigned to a constant once, then going through the code and changing all occurrences of 1 to their new value. Especially if the value, like 1, can be used for things other than the active value.
More importantly here, though, is that there is no real reason to bind a known integer value. You can just make that part of the WHERE clause part of the prepared statement. It's an immutable part anyway. Here's what I'd do:

//at the top of the class:
const TIMER_ACTIVE = 1;

public function getTime()
{
    //makes query easier to read IMO
    $stmt = $this->db->prepare(
        'SELECT started_at
        FROM qrm_logs
        WHERE `active` = ' . self::TIMER_ACTIVE .
        ' AND `user_id` = :uid'
    );
    $stmt->execute([':uid' => $this->userId]);

The next thing I notice about your code is that you're using fetchAll, then iterate over the results, and return inside the loop. This suggests that all you're really after is a single result. Using LIMT 1 in your query would make this clearer to whoever ends up maintaining this code. If a query can return multiple results, but I'm only after one row, I'd never ever use fetchAll. Personally, I'd use fetch, to get a single row. Your call to fetchAll implies that all results are being fetched and loaded into memory. That's extremely wasteful considering you're never ever processing more than a single row.
You're also using count to check whether or not there are any results to process. There's no reason for that function call, though. If you use fetch, the return value is null if there aren't any results, or the row (as an object, or array, or whichever fetch mode you use).
even if you use fetchAll, though, an empty array in PHP is a falsy value, so you could just as well write if (count($result) > 0) { like so:

if ($result) {
    //$result is NOT empty
}
//or:
if (!$result) {//in PHP, !array() is true
    return false;//
}
//process $results here

So what does that mean for the code we've discussed so far, and how would I write it?

public function getTime()
{
    //makes query easier to read IMO
    $stmt = $this->db->prepare(
        'SELECT started_at
        FROM qrm_logs
        WHERE `active` = ' . self::TIMER_ACTIVE .
        ' AND `user_id` = :uid'
    );
    $stmt->execute([':uid' => $this->userId]);

    $row = $stmt->fetch(PDO::FETCH_OBJ);
    if (!$row) {
        return false;//no active records found for user
    }

Now all that's left for us to do is to return the interval in seconds. I personally advocate the use of the DateTimeInterface objects as much as possible. However, in this particular case, I don't think it's worth it. You want to subtract a date (in timestamp format) from the current timestamp. You can do that as a one-liner by calling 2 simple functions: time() and strtotime(). The first just returns the current timestamp, the second returns the timestamp for the string representation of a date. Seeing as started_at is coming from the DB, I'm assuming it's a MySQL DATETIME or TIMESTAMP field, and its values can be handled by strtotime just fine. Here's how I'd write your function in full:

public function getTime()
{
    $stmt = $this->db->prepare(
        'SELECT started_at
        FROM qrm_logs
        WHERE `active` = ' . self::TIMER_ACTIVE .
        ' AND `user_id` = :uid'
    );
    $stmt->execute([':uid' => $this->userId]);

    $row = $stmt->fetch(PDO::FETCH_OBJ);
    if (!$row) {
        return false;
    }

    return time() - strtotime($row->started_at);
}

This looks simple, clean and easy.
A Final not, instead of passing those PDO::FETCH_* constant every time you're fetching, you might want to consider setting the default fetch mode on the PDO instance ($this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);), provided no other piece of code has access to the same PDO instance, or that other piece of code doesn't change the default fetch mode, you don't have to bother passing the fetch mode every time again...

I'll look into the rest of the code a bit later on, and update this answer as I go along. This is all I have time for for now.


Prime generator program SPOJ time limit exceed

Re-organising the code

A quite easy thing to start with is to split the logic into a part collecting the input and a part performing computation from this input. This makes things clearer but also this might make testing easier and make some optimisations possible later on.

You can also take this chance to remove whatever is not needed :

i is not needed, the usage is to use _ for throw-away values in Python.
final is not needed : you populate it one element at a time and then you iterate on it to display the elements.
You don't need to recreate a new string to call join, you can use generator expressions.

Here's what I have at this stage :

#!/usr/bin/python

import sys

if False :
    # Test from standard input
    inputs = []
    for _ in xrange(int(sys.stdin.readline())):
        start,end=[int(x) for x in sys.stdin.readline().split()]
        if start==1:
            start=2
        inputs.append((start,end))
else:
    # Hardcoded test
    inputs = [(2,10),(5,7)]

for start,end in inputs:
    # sieve of eras** algorithm
    primes = (list(sorted(set(xrange(start,end+1)).difference(set((p * f) for p in xrange(2, int(end ** 0.5) + 2) for f in xrange(2, int(end/p) + 1))))))
    print("\n".join(str(p) for p in primes)+"\n")

Now, I can use inputs = [(2,10),(5,7),(9999985,10000000),(9999937,9999987)] for performance testing.

Computing things once

At the moment, you re-compute your sieve multiple times. You might as well juste do it once with the biggest max you can find.

def sieve_of_era(n):
    primes = [True]*(n+1)
    primes[0] = primes[1] = False
    for i in range(2, int(n**0.5)+1):
        if primes[i]:
            for j in range(i*i, n+1, i):
                primes[j] = False
    return primes

sieve = sieve_of_era(max(end for _,end in inputs))

Then, it's only a matter of collecting the information and printing it :

print "\n\n".join("\n".join(str(p) for p in xrange(start,end+1) if sieve[p]) for start,end in inputs)

A last remark

Your "sieve" considers 1 as a prime number and for that number, you added a hack to change 1 into 2 in the inputs. This is not required anymore and once it's removed, everything can be included in a single list comprehension.

The code becomes :

#!/usr/bin/python

import sys

inputs = [[int(x) for x in sys.stdin.readline().split()] for _ in xrange(int(sys.stdin.readline()))] if False else [(2,10),(5,7),(9999985,10000000),(9999937,9999987)]

def sieve_of_era(n):
    primes = [True]*(n+1)
    primes[0] = primes[1] = False
    for i in range(2, int(n**0.5)+1):
        if primes[i]:
            for j in range(i*i, n+1, i):
                primes[j] = False
    return primes

sieve = sieve_of_era(max(end for _,end in inputs))

print "\n\n".join("\n".join(str(p) for p in xrange(start,end+1) if sieve[p]) for start,end in inputs)

I haven't tried edge cases for the sieve function but it looks ok.


While trying to add an easter egg on my framework, I saw this answer : Stack Overflow returning HTTP error code 418 (I'm a teapot)?.

Since it looks like there is no "correct" way to handle CSRF, I thought it could be a fun thing to do. Upon detecting a CSRF attack, my framework now sends a HTTP 418 header with a nice ASCII art of a trolly teapot.

So I mark this question as answered, because there's no real best practice (yet ?) and anything would be OK.


Your code is not finished.

I could not say this is a finished bit of code as it simply does not work. A simple test, a random set of integers and comparing it to the result of the standard sort showed that more often than not the function just failed.

Read this Gramma and types

3 rules of coding:

There is no code without testing.
There is no code without testing.
There is no code without testing.

When creating a function such as this it is important that you have a reliable means of testing the code over all possible inputs. One test case just does not cut it. Having a full test at the start makes writing the code a lot easier. You can make a change and instantly test all possible inputs, it also helps you optimise the code once you have the basics worked out.

Example test function

This is the function that I used to test your code. It creates a random  list of numbers of different lengths, different numbers of digits, and different ranges of digits. If it fails any test then it stops displaying the failed array and the correct array.

function test() {
    function log (data) {console.log(data); }
    function createRandomArray (maxItems, maxDigits, digitRange) {
        var numSize, num;
        var numbers = [];
        var count = Math.random() * maxItems;
        while (count-- > 0) {
            numSize = Math.random() * maxDigits;
            num = 0;
            while (numSize-- > 0) {
                num *= 10;
                num += Math.floor(Math.random() * digitRange);
            }
            numbers.push(num);
        }
        return numbers;
    }
    var items, digits, range, array;
    for (items = 0; items <= 20; items += 1) {
        for (digits = 1; digits <= 9; digits += 1) {
            for (range = 1; range <= 9; range += 1) {
                array = createRandomArray(items, digits, range);
                length = array.length;
                numbers = [...array];
                RadixSort();
                array.sort((a, b) => a - b);
                if (array.join(",") !== numbers.join(",")) {
                    log("==============================");
                    log("Test failed.");
                    log("Items = "+length)
                    log("Max digits = "+digits)
                    log("Digit range = "+range)
                    log("- Result --------------------")
                    numbers.forEach(n => log(n))
                    log("- Expected ------------------")
                    array.forEach(n => log(n) )
                    return
                }
            }
        }
    }
    log("All passed")
}
test();

Style and syntax.

Only capitalise variables if they are functions that are intended to be instantiated via the new token. Note the syntax highlighting.

function MyObj(){}   // good
var obj = new MyObj();

function myObj(){}   // bad
var obj = new myObj();

function doSomething(){} // good

function DoSomething(){} // bad

var myData = []; // good

var MyData = []; // bad.

Don't take shortcuts when it comes to syntax, especial concerning curly braces when defining blocks, it is a major source of syntax related bugs that are very hard to find when you are staring at thousands of lines of code.

for(i = 0; i < 10; i+= 1)
    doSomethif();            // bad

for(i = 0; i < 10; i+= 1) doSomethif();  // better but still bad

for(i = 0; i < 10; i+= 1) {  doSomethif(); }  // OK

for(i = 0; i < 10; i+= 1) {    // Good
    doSomethif();
}

Same for if, while, do statement blocks.
Layout. Don't spread out initialization code throughout the source. You are making calls to clear and radixSort intermixed within the source. Ok maybe for a short bit of code but when your code gets over a few pages it can be very hard to see what is going on.

The general layout is Function declarations first, then variables, and then functional source. I personally use bottom up layout style. The deepest level function first, top of the page, then down the page to the highest level function. So in most cases you know that to locate a function being called from within another is to look above the current functions location.

You can also use top down, it does not matter which direction, just as long as you are consistent.
Naming. Use clear descriptive words or phrases for the functions. You have Clear. Clear what, maybe resetBuckets would be a better name for the function.
Use ES6. There is no reason not to use Javascript latest and best incarnation. Using ES5 because it has more browsers that support it is only shooting your self in the foot. Time moves along and ES6 will soon be ES7. As a programmer you can not afford to not learn the latest and best, by the time you know it back to front, it will be obsolete.
Use const for any variables the will not change. (not a must, but it makes you look more professional) The general accepted reasoning between the use of constants const, block scope let, and function scope var variables is mostly about reducing bugs by protecting state. You cant mess up the state of the code if it is a protected 'const' or inaccessible (out of scope), which makes sense, well kind of, if you feel that you need the training wheels down that is.

Understand what the differences are and use them correctly. Really it is a joke that const was added to ES6, as it is borrowed from the compiled language world, where consts are there to improve speed and access, not to protect state. Don't get me started on let. End rant.

I use const because I hope one day the browsers will give a performance boost for const (sadly not yet) and as it does not decrease performance it is a bit of future optimization. I never use let because it is just wrong in Javascript.

Code

Keep the global name-space (scope) clean. You have polluted the global name-space with some nasty variable names that are going to clash, length, numbers, clear are very common variable names and if you are on a page that shares Javascript and any of that code is slack your code will stop working. Finding out why your code suddenly stops working is next to impossible, so expose only what you must and hide the rest behind your functions scope.

Example of clean namespace code:

// pass to the function data
function radixSort(numArray){
    // define required functions within the function
    function Clear() {
        for (var i = 0; i < 10; i++)
            buckets[i] = [];
    }
    // declare inside the function
    var length = numArray.length;
    var buckets = new Array(10);

    // return the processed information
    return sorted

    // Or leave in place but still return the array
    return numArray
 }

Don't use new Array() and new Object() when creating objects and arrays, they are not quite the same as using literals [] for array and {} for object. The same applies to strings (if you're ever tempted) don't use = new String("my string"); use = "my string";

I know that there is no easy way to create an array of predetermined size easily when using literal declaration, but the little bit of extra code is usually needed anyway.
Don't delete or dereference if it can be avoided. Javascript runs in a managed environment, if you don't need something you just throw it way and it will be cleaned up for you. When you need memory it is there (well within limits). But all that cleaning up the managed code does for you does not come for free. If you are a messy coder there is a lot more work for the GC (garbage collector) to do. If you want some new memory, and it is a mess, then you don't get it until it is been cleaned up. This can become very noticeable as GC is blocking.

So always keep that in mind when coding in any managed environment.

Example:

// bad
function clear() {
    for (var i = 0; i < 10; i++) {
        buckets[i] = []; // dereferences the array held in [i] and creates a brand new one
    }
}

// good
function clear() {
    for (var i = 0; i < 10; i++) {
        buckets[i].length = 0; // reduces the array size but does not create a new one
    }
}

// great by hard work
// first array item is the current number of usable items in the array
function clear() {
    for (var i = 0; i < 11; i++) {
        buckets[i][0] = 0; // totally clean nothing created, nothing deleted, and very fast
                       // but you can no longer use bucket[i].length.
    }
}

Don't repeat code. You have the function copyToArray and at the bottom of radixSort the very same code, done twice. If you want to change something you have to do it twice, and if it is a long bit of code, you may forget one.
Don't repeat calculations. You have:

// Bad
for (var index = 0; index < length; index++) {
    var tenIndex = Math.pow(10, count); // recalculating the same number for each array item. Bad
    //... blah blah
}
count++

// Good
var tenIndex = Math.pow(10, count); // only once
for (var index = 0; index < length; index++) {
    //... blah blah
}
count++

Use the correct function appropriately. parseInt is for parsing integer values into Javascript's floating point numbers. It IS NOT how you remove the fractional part of a number. Use Math.floor, Math.ceil or Math.round. Some may suggest using bitwise operators to trim of the fraction var num = myNum | 0; Don't unless you understand the difference between a double and a signed int 32 and why that will make the the test runs fail.

The radixSort

Part of its beauty is that it is a very quick sort as you only need to iterate the numbers array once for each digit in the biggest number. But there is also another optimisation you missed. Numbers that are smaller than the current digit are already sorted and thus do not need to be iterated over again and can be removed from the array of values to be sorted. This give a huge performance boost.

Note that I expect that the numbers are correctly formatted as unsigned integers and no exponent notation (e.g. 127e10).

Thus the rewrite:

// One  function name so no global scope pollution.
// lower-case as this is a function rather than an object
// Pass the array of numbers rather than use a global.
// Returns a new array of numbers sorted.
function radixSort (numbers) {
    function emptyBuckets () {          // empties buckets and adds contents back to workArray
        workArray.length = 0;
        for (i = 0; i < 10; i += 1) {   // could have used buckets forEach but this is quicker on average
            if(buckets[i].length > 0){
                workArray.push(...buckets[i]);
                buckets[i].length = 0;
            }
        }
    }
    var i;                  // hoist declarations
    const results = [];     // array that holds the finnal sorted numbers
    const buckets = [[], [], [], [], [], [], [], [], [], []];  // buckets
    const workArray = [...numbers]; // copy the numbers
    var power = 0;                  // current digit as a power of ten
    var tenPow = 1;                 // ten to the power of power
    if(numbers.length <= 1){        // if one or no items then dont sort
        return workArray;           // dont sort if there is no need.
    }
    // as numbers are sorted and moved to the result array the numbers
    while (workArray.length > 0) {
        for (i = 0; i < workArray.length; i += 1) { // for all numbers still being sorted
            if (workArray[i] < tenPow) {            // is the number samller than the current digit
                results.push(workArray[i]);         //Yes it is sorted then remove a put o nthe result array
            } else {
                // add to bucket. Use Math.floor and save complexity doing it in one statement line
                buckets[Math.floor(workArray[i] / tenPow) % 10].push(workArray[i]);
            }
        }
        power += 1;
        tenPow = Math.pow(10, power);
        emptyBuckets();
    }
    return results;
}


Every time you feel obliged to put a comment like

    // Start filling up left array

you really deal with a potentially important algorithm, which deserves a name, and a method of its own. In this case the algorithm is known as partial product. Consider factoring it out, and see the comments disappear.

Ditto for the second loop.

Regarding space complexity,

You don't need left: accumulate the partial products directly into output.
You don't need right as well: instead of accumulating the partial products, use it immediately:

    temp = 1;

    for (int i = size - 1; i >= 0; i--) {
        output[i] *= temp;
        temp = temp * nums[i];
    }


Finding the profile name for a join in my Facebook auth backend

You can use django.contrib.auth.get_user_model() instead of importing User directly. Note that I also explicitly included the ObjectDoesNotExist exception.

https://docs.djangoproject.com/en/2.2/topics/auth/customizing/

from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from better_facebook.models import FacebookUser

class FacebookBackend(object):
    """
    Authenticate against a facebook_user object.
    """
    def authenticate(self, facebook_user):
        assert(isinstance(facebook_user, FacebookUser))
        try:
            UserModel = get_user_model()
            return UserModel.objects.get(userprofile__facebook=facebook_user)
        except ObjectDoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            UserModel = get_user_model()
            return UserModel.objects.get(pk=user_id)
        except ObjectDoesNotExist:
            return None
```


Group a list of `dict` by all keys except one

Your code is pretty good, there is one thing that I would add,
the for-else keyword, as this gets rid of the found variable.
Which honestly is just noise.
This is as if a for loop runs completely without breaking then the else will run too. But if it breaks then it won't run the else.
This can leave you with:

def group_by_excluding_key(list_of_dicts, key_field):
    """
    Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.
    :param list_of_dicts: List of dicts to group
    :param key_field: key field in dict which should be excluded from the grouping
    """
    output = []
    for item in list_of_dicts:
        item_key = item.pop(key_field)
        for existing_group, found_keys in output:
            if existing_group.viewitems() == item.viewitems():
                found_keys.append(item_key)
                break
        else:
            output.append((item, [item_key]))
    return output

Other than that your code is good.

But if I were to were to write this, I'd prefer a very small solution.
Lets say dicts are hash able, what you want is a dictionary that has the modified item as the key, and the popped item_key as the value.
This obviously has two down-sides, it's not ordered, and dicts aren't hash able.
Both easily solved with collections.OrderedDict and tuple(dict.items()).
And so can result in:

from collections import OrderedDict

def group_by_excluding_key(list_of_dicts, key_field):
    """
    Takes a list of `dict` items and groups by ALL KEYS in the dict EXCEPT the key_field.
    :param list_of_dicts: List of dicts to group
    :param key_field: key field in dict which should be excluded from the grouping
    """
    output = OrderedDict()
    for item in list_of_dicts:
        key = item.pop(key_field)
        output.setdefault(tuple(item.items()), []).append(key)
    return [(dict(key), value) for key, value in output.items()]

This has the benefit of moving the for loop into the OrderedDict, and possibly getting \$O(1)\$ key lookup, but requires you to change the type of all the keys, twice.

I know you didn't ask for a performance review, but the performance difference between my code and your code can be tested with the following. The comments are my functions run time over yours as a percentage, so if mine took 0.8s and yours 3.3s then it'll be 24%, followed by how long it took my function to run.

from timeit import timeit
from itertools import count

# 240%, 0.1s
c = count(1)
l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(10)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 25%, 0.8s
c = count(1)
l = [{'status': 1, 'product': i, 'id': next(c)} for i in range(100)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 28%, 0.8s
c = count(1)
l = [{'status': i, 'product': j, 'id': next(c)} for i in range(10) for j in range(10)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=1000))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=1000))

# 0.4%, 0.9s
c = count(1)
l = [{'status': i, 'product': j, 'id': next(c)} for i in range(100) for j in range(100)]
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key_dict as fn', number=10))
print(timeit('fn({!r}, "id")'.format(l), 'from __main__ import group_by_excluding_key as fn', number=10))


C++ std::vector with always valid iterator/pointer/index/key

Quick review (in anticipation of more code).

The main issue I have with the code is that is not encapsulate in a class.

std::vector<Element> data;       // usual continious vector, no magic here
std::vector<int> key_indices;    // point to data[]. these values changes when erase/insert to data
std::vector<int> free_indices;

These are basically global variables and anybody can access an mutate them (not just maliciously but accidently). C++ has the ability to encapsulate all the parts of a class and protect it from accidental misuse by only allowing certain functions (methods) to access the raw underlying data.

class MultiIndexToElement
{
    private:
        std::vector<Element> data;         // usual continious vector, no magic here
        std::vector<int>     key_indices;  // point to data[]. these values changes when erase/insert to data
        std::vector<int>     free_indices;
    public:
        void emplace_back();
        Key get_key(std::vector<Element>::iterator iter);

        Value& operator[](Key key);
        Value& operator[](int index);

        void erase(std::vector<Element>::iterator iter);

     private:
        template<class iter>
        void update_indices(iter from, iter to, int shift);
};

Now that we can see the interface clearly there are a couple of things you should watch for.

Const correctness.

A method that does not change the state of the object should be marked const. This tells the compiler that calling this method does not change the object.

      Key get_key(std::vector<Element>::iterator iter) const;
                                                  //   ^^^^^

This is important because objects get passed to functions by const reference a lot in C++ to avoid the cost of copying the object.

Element Access

Usually containers allow tow forms of element accesses. Mutating access and const accesses.

        Value&       operator[](int index);       // This allows mutating access.
        Value const& operator[](int index) const; // This allows const accesses.

Emplace Back.

Usually emplace back (a new form of push back). Creates the Element in place using one of Elements constructors. Your version only allows for Element to have zero parameter constructor.

It is usually written like this:

 template<Args... args>
 void emplace_back(Args&& args...) {
     data.emplace_back(std::forward<Args>(args)...);     // pass arguments to constructor
     .... /* Other stuff you need */
 }

The Args... part is a new part of C++14 so you will need to tell your compiler to use the newer version of the standard (that's not a default yet). But usually this means adding -std=c++14 to the command line.

Templatization

Your code does not allow for easy templatization. In fact you don't define Value in the code sample above. This is more easily solved using templates around a class.

template<typename Value>
class MultiIndexToElement
{
     /* STUFF */
};


Do you plan to replace the Joystick object?

Joystick *leftStick;
Joystick *rightStick;

If not then declare them as

Joystick  leftStick;
Joystick  rightStick;

If you are going to replace them then you should be using smart pointers rather than a RAW pointer (if you want to do it manually then learn the rule of three) But I would go with smart pointers (but that is a second option to normal objects).

If you must have pointer use smart pointers:

std::unique_ptr<Joystick>  leftStick;
std::unique_ptr<Joystick>  rightStick;

There is no need declare these as static (unless you want to get the address or something) so just use enum:

// Motor ports (hardware)
static const UINT32 kLeftFrontMotor = kPWMPort_1;
static const UINT32 kRightFrontMotor = kPWMPort_2;
static const UINT32 kLeftBackMotor = kPWMPort_3;
static const UINT32 kRightBackMotor = kPWMPort_4;

Prefer:

enum { kLeftFrontMotor = kPWMPort_1, kRightFrontMotor = kPWMPort_2, kLeftBackMotor = kPWMPort_3, kRightBackMotor = kPWMPort_4};

No need to explicitly return from a constructor:

MainRobot::MainRobot(void)
{
    ...

    return;  // No need
}

There is nothing wrong with prefixing functions with the class name but personally I would not.

while(MainRobot::IsAutonomous()) {
    MainRobot::GetWatchdog().Feed();
    Wait(kDelayValue);
    // Do nothing.
}

Easier to write:

while(IsAutonomous())
{
    GetWatchdog().Feed();
    Wait(kDelayValue);
    // Do nothing.
}

The file name "typedefs.h" is relatively common. You may want to avoid it.


Generally it looks good, at least to an Haskell beginner like me.
I find the use of dropWhile to be a bit confusing. I admit I had to read your comment to understand why you used it.

I think it could also have introduced a bug. What is the expected behaviour for split ',' ",,"?
Your code returns [""] but I would expect ["","",""]. Was your behaviour intended?

This solution fixed the issue.

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split separator ys = f : (split separator (dropSeparator separator rest))
  where (f, rest) = break (== separator) ys

dropSeparator :: Eq a => a ->  [a] -> [a]
dropSeparator _ [] = []
dropSeparator separator (x:xs) = if x == separator then xs else x:xs

I prefer using meaningful variable names, such as separator, even if I'm not sure if it is idiomatic Haskell. Ditto for the parentheses and the introduction of the helper function.


Leetcode: Longest substring without repeating characters

You have exploited the space complexity.

def findLongestSubstring(inputString)
    hashMap = Hash.new
    longestSubstringLength = 0
    jIndex = 0
    iIndex = 0
    while(jIndex < inputString.length)
        if(hashMap[inputString[jIndex]])
            iIndex = [iIndex, hashMap[inputString[jIndex]]].max
        end
        longestSubstringLength = [longestSubstringLength, jIndex-iIndex+1].max
        hashMap[inputString[jIndex]] = jIndex + 1
        jIndex = jIndex + 1
    end
    longestSubstringLength
end

This method makes use of HashMap which works efficiently in terms of complexity. Searching the element in HashMap works in O(1) and same goes for insertion. This way  you can reduce the complexity of your program


Restricting user to one open tab in browser

I can't think of a better approach than a session cookie. It feels safe in that you have three potential ways of leaving the page:

Navigate away
Close browser/tab
Browser crashes

So you're either going to have the option to remove the cookie on the unload event or the session cookie will expire anyway.

I would structure the code a little differently:

// Wrap in an IIFE accepting jQuery as a parameter.
(function ($) {
    var setCookie,
        removeCookie,
        // Create constants for things instead of having same string
        // in multiple places in code.
        COOKIE_NAME = 'TabOpen',
        SITE_WIDE_PATH = { path : '/' };

    setCookie = function () {
        $.cookie(COOKIE_NAME, '1', SITE_WIDE_PATH);
    };

    removeCookie = function () {
        $.removeCookie(COOKIE_NAME, SITE_WIDE_PATH);
    };

    // We don't need to wait for DOM ready to check the cookie
    if ($.cookie(COOKIE_NAME) === undefined) {
        setCookie();
        $(window).unload(removeCookie);
    } else {
        // Replace the whole body with an error message when the DOM is ready.
        $(function () {
            $('body').html('
' +
                '
Sorry!
' +
                '
You can only have one instance of this web page open at a time.
' +
                '
');
            });
    }
}(jQuery));

(code untested).


Can I avoid nested for loop in this case?

I've seen, that you made up this code as an example, so I hope, that this is not your production code:

public static ArrayList<String> getNamesCorrespondingtoUser(String userName)
        throws Exception {
    ArrayList<String> names = new ArrayList<String>();
    if (userName.equals("user101")) {
        names.add("UBSC1");
        names.add("HDBG1");
        names.add("GHYU1");
    }
    if (userName.equals("adminuser")) {
        names.add("UBSC1");
        names.add("HDBG1");
        names.add("GHYU1");
    }
    return names;

}

If you take a look at both blocks, they are the same, aren't they?
But for further improvement, I would suggest working with a Map where you have usernames as the key and the according List of Names as the result.

Second: I would reccomend you to take a look at Google's Guava Library esp. the section about predicates .

Third: I am wondering, how you could retrieve any correct item. As far as I can see your names have to be unique to resolve the correct items. The collision rate for (nick-)names is generally high. So it would be better to switch to some ID-mechanism.

Fourth: The task is in itself nested; you need to iterate over a list of items and over a list of users. So you couldn't "avoid" a nested loop. Okay: If you let a database do the magic, you didn't loop at all - the database does. But I think, that is not the answer you wanted.


Helper class for accessing blobs and mmap memory

BlobRef details

You should provide a default constructor.
safeAccessMemory contains a bug. If you have an empty BlobRef and you call safeAccessMemory(0, 0) you will deference a nullptr (the guard fails).
Don't use c-style casts. In your cases you should use reinterpret_cast. This helps readability, search-ability and signals clear intent.
as can invoke undefined behaviour if called on certain types. The gritty details are in 3.10.10 of the C++ spec.

  If a program attempts to access the stored value of an object through
  a glvalue of other than one of the following types the behavior is
  undefined:

  the dynamic type of the object.

  a cv-qualified version of the dynamic type of the object.

  a type similar (as defined in 4.4) to the dynamic type of the object.

  a type that is the signed or unsigned type corresponding to the dynamic type of the object.

  a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object.

  an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union), a type that is a (possibly cv-qualified) base class type of the dynamic type of the object.

  a char or unsigned char type.

My understand is that there's no easy way to make this work (the gsl folks removed theirs)

Unfortunately this would remove the entire essence of this class. One approach you could take to remedy this would be to use type-traits to restrict the function to types for which it will be well defined.

template <class T, typename = std::enable_if_t<std::is_integral<T>::value>>
const T *as(size_t const pos = 0, size_t const elements = 1) const noexcept{
    return (const T *) safeAccessMemory(pos, elements * sizeof(T));
}


The Java standard dictates the use of the "Egyptian braces" style:

if (something) {
    // something...
}

In AvarageCalc():

int avarage = sum / population;
return avarage;

you can just return the calculation:

return sum / population;

Also, it should be spelled average. ;-)
In Output(), you don't need to declare text and then assign it later.  Instead, initialize it where it's first used.  Always try to keep variables as close in scope as possible, which can help keep your code cleaner and easier to maintain.

String text = messageText[0]+ "\n" + listOfNums;


TwoFish implementation with Bouncy Castle

static vs instance

public BCEngine()
{

}

BCEngine(IBlockCipher blockCipher, Encoding encoding)
{
    _blockCipher = blockCipher;
    _encoding = encoding;
}

Default constructors should provide reasonable default values for the two fields initialized by the other constructor but wait... both constructors are useless because all public APIs are static. The only instance members are private methods. I can create an instance of BCEngine but I cannot do anything with it.

BCEngine bcEngine = new BCEngine(new TwofishEngine(), Encoding.UTF8);
bcEngine.SetPadding(new Pkcs7Padding());
return bcEngine.Encrypt(TextPlain, param);

But wait again.. you instantiate it to call the private instance methods. This is very inconsistent and chaotic.
You should either make everything static or everything instance.
It's ok if an instance uses private static methods as helpers but the other way around is kind of weird. At least the default constructor should be private too.
However your implementation uses private fields where two of them are not readonly so you use them to store some state but fortunately they are not static. You should remove these fields and pass the required arguments from method to method. Then you won't need any instances and the methods would be pure <-- LINK.

using and disposables
You should check your code for disposable types. I'm pretty sure there are plenty of them. Encryption usually requires to dispose something.

#region
Regions are rarely necessary and for member grouping virtually never. It's easier to read the code without them.


Complex class polymorphism and lazy-loaded components

I ended up side-stepping the issue entirely by extending the Complex class with ES5 prototype chaining instead of ES6 extends:

class Complex {
  constructor(real = 0, imag = 0, abs = Math.sqrt(real * real + imag * imag), arg = Math.atan2(imag, real)) {
    this.real = real;
    this.imag = imag;
    this.abs  = abs >= 0 ? abs : -abs;
    this.arg  = arg ? -((-arg + (abs >= 0 ? Math.PI : 0)) % (Math.PI * 2) - Math.PI) : abs < 0 ? Math.PI : 0;
  }

  // ...
};

const Cartesian = Complex.Cartesian = function Cartesian(real = 0, imag = 0) {
  this.real = real;
  this.imag = imag;
};

Cartesian.prototype = Object.create(Complex.prototype, {
  constructor: {
    configurable: true,
    enumerable: false,
    value: Cartesian,
    writable: true,
  },
  abs: {
    configurable: true,
    enumerable: true,
    get() {
      const value = Math.sqrt(this.real * this.real + this.imag * this.imag);

      Object.defineProperty(this, 'abs', {
        configurable: true,
        enumerable: true,
        value,
        writable: true
      });

      return value;
    },
    set(value) {
      Object.defineProperty(this, 'abs', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
  },
  arg: {
    configurable: true,
    enumerable: true,
    get() {
      const arg = Math.atan2(this.imag, this.real);
      const value = arg ? -((-arg + Math.PI) % (Math.PI * 2) - Math.PI) : 0;

      Object.defineProperty(this, 'arg', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
    set(value) {
      Object.defineProperty(this, 'arg', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
  },
});

const Polar = Complex.Polar = function Polar(abs = 0, arg = 0) {
  this.abs = abs >= 0 ? abs : -abs;
  this.arg = arg ? -((-arg + (abs >= 0 ? Math.PI : 0)) % (Math.PI * 2) - Math.PI) : abs < 0 ? Math.PI : 0;
};

Polar.prototype = Object.create(Complex.prototype, {
  constructor: {
    configurable: true,
    enumerable: false,
    value: Polar,
    writable: true,
  },
  real: {
    configurable: true,
    enumerable: true,
    get() {
      const value = this.abs * Math.cos(this.arg);

      Object.defineProperty(this, 'real', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
    set(value) {
      Object.defineProperty(this, 'real', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
  },
  imag: {
    configurable: true,
    enumerable: true,
    get() {
      const value = this.abs * Math.sin(this.arg);

      Object.defineProperty(this, 'imag', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
    set(value) {
      Object.defineProperty(this, 'imag', {
        configurable: true,
        enumerable: true,
        value,
        writable: true,
      });

      return value;
    },
  },
});

This allowed me to write the constructors without requiring the call to super(), which was what created the issue in the first place.


Middlewares with Route definition or Routes with Middleware definition

I personally prefer Approach 2 since it will increase readability and you can easily find out which middle-ware are applied to a route rather than to go to each excepted middle-ware and calculate. That is a lot of work for future purpose.


Automata theory, state reachability in Haskell

This is neat, methinks.

A couple of questions/points:

Is the || any (== s') rs part of canReachExcluding necessary?
In the same definition, the part rs = reach1From s au \\ ex takes time linear in the size of ex. Using a set (or hash) instead of a list for ex would probably improve your running time significantly in practice. But of course, that'd likely be at the expense of the clarity of your beautiful program.
You are of course right that your program checks "states excluded in other branches". What you are "really" implementing is depth-first search (DFS) on the graph defined by the automaton, and so you might want to look for a more efficient (functional) implementation of DFS. In that case, you could either look at the Haskell Library implementation, or maybe just this quick-and-dirty approach.


Removing list of words from a text file in Ruby

Some notes:

I guess you come from imperative languages. Try to write in a more functional style (more expressions, less statements).
Use libraries (File) to manipulate paths.
This double each_line is bad news for performance: O(n*m). Avoid it by building a data structure that has O(1) checks for inclusion. I'd create a set of the prepositions (it's the smaller set). The overall performance is now O(n).

I'd write:

prepositions = open(File.join(path, "prepositions.txt")).lines.to_a
words = open(File.join(path, "dictionary.txt")).lines.to_a
filtered_words = words - prepositions
File.write("dictionary_without_prepositions.txt", filtered_words.join)

If the input file dictionary.txt is very, very large, this is a more lazy aproach:

require 'set'
prepositions = open(File.join(path, "prepositions.txt")).lines.to_set

open("dictionary_without_prepositions.txt", "w") do |output|
  open(File.join(path, "dictionary.txt")).lines.each do |line|
    unless prepositions.include?(line)
      output.write(line)
    end
  end
end


PHP Script - Converting string of calculations to result

I really should be discussing your code here, but ones I got started I took it a bit too far. So before I do that, let's talk about your code.

names

Names of variables and functions give meaning to your code. They should tell the reader exactly what is in them, or what they do. A name like $string or $Arr clearly doesn't do that. Most names are good, but they all need to be good for the code to be easily read. You'll notice that readability is very important to me.

functions

You've clearly mastered the usage of functions, but you're not using them effectively. Functions allow you to write code with another level of abstraction and meaning, making it easier to understand. Functions also isolate variables from the global scope, which will become important when your application grows.

don't repeat yourself (DRY)

See: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself

I've noticed the following structure in your code:

if ($char == "+") {
    .....
    $lastOperator = "+";
} else if ($char == "-") {
    .....
    $lastOperator = "-";
} else {
    $cache1 = $cache1.$char;
}

the ..... represent two pieces of code that are exactly the same. Why not write:

if (($char == "+") || ($char == "-")) {
    .....
    $lastOperator = $char;
} else {
    $cache1 = $cache1.$char;
}

that way you don't have to repeat the same code twice.

choice of algorithm

You process input characters one by one. This is hard. No really, it is. Would this really be the best algorithm? I don't think so. How would a person do the calculation? They would split the string like this: 1,+,41,-,3,+,5,-,12,+,5,+,10, and then simply perform the operations sequentially. Why don't you? With explode() you could split the string like this:

function splitQuestion($question)
// split a math question into numbers, plus and minus
{
  return explode('#',str_replace(['+','-'],['#+#','#-#'],$question));
}

// example code
$question = '1+41-3+5-12+5+10';
echo '<pre>'.print_r(splitQuestion($question),TRUE).'</pre>';

The trick here is to first insert the hashes and only then explode on that. After this writing an algorithm to do the calculation will be much easier because you don't need to cache any characters.

error checking

Your code almost seems to assume the input is valid. There's little checking of, and tolerance for, syntax errors in the input. A programmer should always think about possible errors in the input. They will always occur, and in my experience unexpected input is the most common 'cause' of bugs.

playtime

I couldn't resist to write a very short calculator for you:

// user input
$question = '1+41-3+5-12+5+10';
// get the answer
eval('$answer = '.$question.';');
// show question and answer
echo $question.' = '.$answer;

There are several reasons to be scared of the eval() function in PHP, read the warning here: http://php.net/manual/en/function.eval.php

This warning is appropriate and should be taken notice of. So, normally you really shouldn't use it, but in the case of a calculator it can be very powerful. You can basically do everything which PHP can do, and that's a lot (hence the danger).

As long as you hardcode the math question in PHP there's no problem, but that's not the point of a calculator, you want user input. So instead of working hard on deciphering the question, why not restrict and validate the user input and use eval() to calculate the result?

For instance if only the characters 1234567890+- are allowed in the question string nothing damaging can happen. This would only add one line to the code:

// user input
$question = '1+41-3+5-12+5+10';
// filter everything except numbers, plus and minus
$question = filter_var($question,FILTER_SANITIZE_NUMBER_INT);
// get the answer
eval('$answer = '.$question.';');
// show question and answer
echo $question.' = '.$answer;

You would want to put this code in a function for two reasons: It isolates the eval() even more, and it makes your code easier to read. Like so:

function calculate($question)
// perform a calculation with numbers, plus and minus
{
  return eval('return '.filter_var($question,FILTER_SANITIZE_NUMBER_INT).';');
}

// user input
$question = '1+41-3+5-12+5+10';
// show question and answer
echo $question.' = '.calculate($question);

This can be easily extended to multiplications and devision, or the use of brackets. Do with it what you want.


I've got a few small points about this code and then I have some other points regarding your design. I'll try to discuss your design in perspective to game-development (where I am completely inexperienced) and in perspective to (the more common Java area) business applications.

Names and Design choices

Your class (and interface) names seem to come from a C# dominated development perspective to me. Prefixing I to interfaces smells .NET to me. Whenever I am developing Java I try to keep interfaces without clutter and then usually suffix the implementation classes if that is required.

Next thing that somewhat bit me was the A prefix for your abstract class. I am not a great friend of abstract classes anyways. I try to avoid them wherever I can and prefer interfaces and "Default[...]"-implementations. I have been going better with that since abstract classes often end up constraining the use of the "Interface" too much.

I'd rather write a little duplicate code than creating a central abstract class that limits my possibilities when using the interface. Instead I'll create a simple, if not "minimalistic" interface. Multiple minimalistic interfaces can be combined to allow more complex uses, but since your use-case is clear ....

Anyways this is enough of abstract talk about personal preferences in regards to language constructs. Let's give your code a thorough examination.

Code Analysis:

What instantly struck me when I first saw your code was the lack of explicit visibility modifiers on your AEventPublisher and your IEventListener. Neither of these needs the other for context so much that you'd have to put them into the same classfile.

The next thing I saw was your incredibly long generics specification:

AEventPublisher<Model, Publisher extends AEventPublisher<Model, ?>>

This seems to be a lot of unnecessary work to me. Also you're needlessly restricting the possibilities you have, when using your publishing mechanism. IMO the following would be sufficient:

AEventPublisher<Model, P extends Publisher>

Then I saw how you store listeners. You have a private List<...>

You have two choices when creating an abstract class like this. Either you allow "full" access to your fields (by making them protected) or you close yourself off completely.

Following the Open/Closed principle (Open to extension, Closed to modification) I definitely suggest the latter. You did that not even bad, but I have two small nitpicks to make.

Make your "immutable" fields really immutable:

private final List<...>

is better than just a private list.
Make use of "common" language features:
You're currently initializing your List in the constructor, and (again) repeat the clunky generics definition. Save yourself from that and use the Java 7 feature: the diamond operator. It makes overly clunky generics (as java has them) easier by shortcircuiting redundancy:

private final List<IEventListener<Model, Publisher>> listeners = new ArrayList<>();

Next up is how you handle publishing. The problem you're describing when you implemented your publish method is rooted in how you restricted yourself when starting directly with an abstract class, instead of taking yourself the room of creating an interface for a Publisher. Consider the following:

public interface Publisher<E> {
    public void subscribe(IEventListener<E, Publisher<E>> listener);
    public void unsubscribe(IEventListener<E, Publisher<E>> listener);
    public void publish(E sender);
}

This greatly simplifies your generics declarations and nestings and additionally resolves the conflict you had internally.

If you'd sacrifice a little "flexibility" (which you problably won't need anyways, more later), you could even make your IEventListener much simpler and completely get rid of the second type-parameter you introduced.

In general your solution seems overengineered for the problem. Which brings me to my next point.

Design Discussion:

In general your design is somewhat over the top. You try to keep flexibility and allow substitions (which is in principle a good thing) in places where it's overly complicating your source-code and detrimental to code-readability and hurtful to your actual flexibility.

Coming from a "GameDevelopment-Perspective"

You will never need a Listener, which can listen to multiple different model classes, and if against all odds you need it, an abstract class or interface to group these model-classes is the simplest call to make. You went too far in your idealistic approach to be "open to everything". This is something you should strive to do, but not at the cost of simplicity and effectiveness.

This is true to both gamedevelopment and business applications.

In addition to that, gamedevelopment is a often heavily performance-reliant environment, and let me tell you, overcomplicated generics and backreferencing interfaces are not something to make the JVM run faster.

I also have no idea why you'd need or want the Listener to obtain a reference to the publisher. From what I see with my nonexistant experience you could "directly" subscribe to your model, which would then pass a reference to itself to it's listener. But that makes the whole Model-circus in your code moot, and defeats the point of a separate Publisher (which I don't see in the first place).

In general, separating the Publisher from the "published" is somewhat overkill and most probably sign of an underlying design mistake. I can not imagine a situation where I'd have to get a reference to a Publisher, before publishing something. You're again: overly complicating a simple matter.

Because in the end, what is this all about?

You want to bring data from one end to another, depending on certain conditions. And there's already a lot of existing solutions (beginning with Observable and ending god knows where) in the Java world for that.

Which is also what makes this model somewhat problematic from a business perspective. The simplicity of existing solutions beats your idea easily. The practical use-case is from my point of view missing.

Overall you reinvented the wheel, but not as wheel, but as a polygon. Your solution to "Get data from A to B on demand" suffers from clunkyness in use. It's a bumpy ride and I don't know how I'd make it better without landing at some place that's already polished for use.

Final overview:

When I reviewed your code I copied it to a local project in my IDE. A few changes and a little headscratching later I was at the state of code that follows.

From what your use-case seems to be, that should be completely sufficient:

public interface Publisher<E> {
    public void subscribe(IEventListener<E> listener);
    public void unsubscribe(IEventListener<E> listener);
    public void publish(E sender);
}

public interface IEventListener<E> {
    public void actionPerformed(Publisher<E> publisher, E sender);
}

public class DefaultEventPublisher<Model> implements Publisher<Model> {
    private final ArrayList<IEventListener<Model>> listeners = new ArrayList<>();

    @Override
    public void subscribe(IEventListener<Model> listener) {
        listeners.add(listener);
    }

    @Override
    public void unsubscribe(IEventListener<Model> listener) {
        listeners.remove(listener);
    }

    @Override
    public void publish(Model sender) {
        for (IEventListener listener : listeners) {
            listener.actionPerformed(this, sender);
        }
    }
}

And since you also had an example of a usecase:

public class ButtonEventPublisher
       extends DefaultEventPublisher<ButtonEventPublisher.ButtonEvent> {
    public static class ButtonEvent {}
}

This code should in essence be able to do the same things that your code can do, but is IMO much simpler. Let me know what you think ;)


Implementing an asynchronous mutex in C#

A better alternative to the busy wait loop would be to use a Semaphore - in this case a SemaphoreSlim would probably be the most appropriate. Semaphores are not reentrant. This would simplify the implementation to:

struct DumbAsyncMutex
{
    private SemaphoreSlim _Semaphore = new SemaphoreSlim(1, 1);

    public async Task WithMutexAsync(Func<Task> t)
    {
        await _Semaphore.WaitAsync();

        try
        {
            await t();
        }
        finally
        {
            _Semaphore.Release(1);
        }
    }
}

The advantage is that it has async support and you can abandon the waiting by using cancellation tokens.


There's a few points you can improve on:

throw:

throw "Object is not an Array";

You should use throw new Error instead of throw as throw new Error contains a stack trace as well.

for in:

for in is a bit weird and can cause issues as it iterates over prototypes as well.

Considering you're testing that the properties are array items anyway, you can just use forEach instead.

if(ob instanceof Array){
    for(r in ob){
        if(ob.hasOwnProperty(r)){
            row = ob[r];

into:

if(ob instanceof Array){
    ob.forEach(function(row, index){
        //...

Declaring globals:

You shouldn't be declaring globals like:

var str = "", row, a, i, o, c, r;

Use them at their respective levels, don't have left over variables.


Extract numerics from matrix A with logical matrix B

While rowSums(A*B) looks pretty nice for me, you can also try

A[which(t(B) == 1, arr.ind = T)[,2:1]]


I don't know about the performance, but readability-wise, cramming that double-nested ternary on a single line of code isn't, well, ideal.

Give it some [vertical] air:

const rot13 = (str) => str
   ? (code(str) < 65 || code(str) > 90)
       ? head(str).concat(rot13(tail(str)))
       : String.fromCharCode((((code(str) - 65)) + 13) % 26 + 65).concat(rot13(tail(str)))
   : '';

Ah, already better.

I'm no javascript expert, but being all inline, it probably performs better than if you further improved readability by introducing a function for each of the two outcomes of the inner condition... on the other hand, that could just as well be premature optimization - so I'd still go for readability and extract the logic into its own function.


Overall, I see the following issues with your code

It's coupled way to tightly to the markup
It's overly complex
You call $(this) again and again without ever caching the result
It's repetitive

I won't be posting fully revised code, as there's a lot I'd do differently. Instead, I'll try to explain the steps you could take.

Right now, you're relying on the markup never, ever changing. For instance, you're using $(this).parent().prev().find('input') to find the other password field, but if the markup changes just slightly, your code will no longer find the right input. You'd have to change your code each time you change your markup. Obviously, that's not very maintainable.

You're doing a similar thing to find all other inputs/selects in the form - again, this will break if the markup changes.

Instead, do something like

$("form").each(function () {
  var form = $(this),
      fields = form.find("input, select");

  // ... everything here has access to the form and fields variables
});

Or at the very least use $(this).closest("form").find("input, select")

In either case, you greatly reduce the coupling between markup and code.

Also, do not rely an input's name to tell you its intended type. A name can be anything. For instance, you could have a field called "recipient" which should be an email-address, but then you'd have to update your code to look for that.

In the case of email-addresses specifically, HTML5 has a type-attribute value you can use:

<input name="whatever" type="email">

Your other checks seem to be about checking presence of any value - i.e. required fields. Again, HTML5 has an attribute for that:

<input name="whatever" type="email" required>

So now, your code can check the input's type to determine it's intended type, and check for the required attribute to determine if it's required (seems logical, right?)

Depending on the browser, it might actually "help out" should your validation fail. For instance, Chrome respects and enforces the email type, and so requires the user to type an email-address.

Incidentally, it makes more sense to use an empty string "" as the nothing-selected value in the select element. -1 is a value, whereas an empty string is, well, an empty string; no value at all. JavaScript itself considers "" == false but considers -1 == true.

Last up is the password and password repeat. Instead of the complex jQuery selector chain to find the other password field, use HTML5's data-* attributes to say what you should check against. For instance:

<input id="password" type="password" data-match="password_confirmation">

<input id="password_confirmation" type="password" data-match="password">

Now each element can tell you what its counterpart is, regardless of how your markup is put together.

As for structure and repetition: Don't use the switch statement for big blocks of code. It's hard to read, and hard to maintain. Instead, DRY (Don't Repeat Yourself) you code, by breaking it into functions. For instance, you could have functions like checkEmail and checkSelection that you can pass an element to, and they'll report true or false, depending on element's value.

Do the same for the bit of code that adds the error class: Have a function, like, say

function markElement(element, valid) {
  if(valid) {
    $(element).removeClass("error");
  } else {
    $(element).addClass("error");
  }
}

Now you have some more generic building blocks.

Lastly, don't do all the validation logic in the event handlers themselves. The validation logic is the same regardless of how/why something needs to be validated. Instead, write the validation code separately and use the event handlers to call it.


Implementation of a queue for digicode-like system

Some PEP8 guidance:

class MyQueue(): here, you can remove the redundant parentheses as you're not passing any parameter to it. So you will have class MyQueue.

When inside of a class, it's recommended to have one space between your methods:

def addItem:
    ....

def printQueue:
    ....

It's also specified in PEP8 the following (methods naming):

  Use the function naming rules: lowercase with words separated by
  underscores as necessary to improve readability.

That said, addItem would become add_item.

More

Don't use <> operator. It's not usual. I strongly recommend you using != operator (which is the common way of doing this) when you're trying to say not equal. Later on, you might want to use this with a more recent Python version (say Python 3.5). This way, you won't have any issues.

Related to portability, you might also want to add parentheses when using print(). It's not necessary since you're using Python 2.7, but it might help you in the future.

Classes and methods inside them usually have docstrings. To quote the documentation:

  A docstring is a string literal that occurs as the first statement in
  a module, function, class, or method definition. Such a docstring
  becomes the doc special attribute of that object.

  All modules should normally have docstrings, and all functions and
  classes exported by a module should also have docstrings.

That said:

class MyQueue:
    """Some text to describe what you're class does"""
    ....

    def add_item(self, value):
        """ what this method does """
        ...

In a perfect world, which obviously we're not living in, I would've expect to see some push / pop methods or queue / dequeue ones since we're talking about a queue implementation and it's way of handling things (FIFO). Perhaps add_item might be push_item.

More to come


This is almost right, but it has two flaws:

First, you can improve type safety by passing char(&)[4] instead of char*:

int32_t Char4ToInt(char (&pChar4)[4]);

void StuffIntIntoChar4(char (&pIntoChar4)[4], int32_t val);

Second, you are running into undefined behavior. In the C++11 standard (section [expr.shift]), it says

  The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated
  bits are zero-filled. If E1 has an unsigned type, the value of the
  result is \$E1 × 2^{E2}\$, reduced modulo one more than the maximum value
  representable in the result type. Otherwise, if E1 has a signed type
  and non-negative value, and \$E1 × 2^{E2}\$ is representable in the result
  type, then that is the resulting value; otherwise, the behavior is
  undefined.

The last part is what you're running into -- you're left-shifting a negative value in some cases, which is undefined behavior.

You have a couple of choices, depending on your portability requirements.

If you will always run this on the same architecture (or in any case only on architectures with the same byte ordering), you can store like this:

void SerializeInt32(char (&buf)[4], int32_t val)
{
  std::memcpy(buf, &val, 4);
}

int32_t ParseInt32(const char (&buf)[4])
{
  int32_t val;
  std::memcpy(&val, buf, 4);
  return val;
}

If you would like instead to be able to store with a program built on one platform and load on a program built on a different platform (as long as its implementation-defined unsigned int -> int conversion uses two's complement, which is almost all modern platforms), you can write it like this:

void SerializeInt32(char (&buf)[4], int32_t val)
{
    uint32_t uval = val;
    buf[0] = uval;
    buf[1] = uval >> 8;
    buf[2] = uval >> 16;
    buf[3] = uval >> 24;
}

int32_t ParseInt32(const char (&buf)[4])
{
    // This prevents buf[i] from being promoted to a signed int.
    uint32_t u0 = buf[0], u1 = buf[1], u2 = buf[2], u3 = buf[3];
    uint32_t uval = u0 | (u1 << 8) | (u2 << 16) | (u3 << 24);
    return uval;
}


Optimizations

You should think of your algorithm as a black box. As long as input and output match, internally the function has not to reproduce the textual representation of the problem.

With this in mind you can simplify your code. You also have an approach already in the charToObj function. I would use this to solve the whole problem:

create a map
store values in that map and increase their amount, when they reappear
decrease amount, if necessary
test the map for given frequencies

This has a few advantages:

shorter code, easier to follow
no helper function necessary
no need to call splice
no inner loops anymore
no need to build obj over and over again

The new functions could look like this:

function freqQuery(queries) {
    const frequencies = [];
    const result = [];

    for (const query of queries) {
        const action = query[0];
        const value = query[1];

        if (action === 1) {
            if (typeof frequencies[value] === 'undefined') {
                frequencies[value] = 1;
            } else {
                ++frequencies[value];
            }
        }

        if (action === 2) {
            if (frequencies[value]) {
                --frequencies[value];
            }
        }

        if (action === 3) {
            result.push(frequencies.indexOf(value) === -1 ? 0 : 1);
        }
    }

    return result;
}

console.log(
    freqQuery([[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]]),
    freqQuery([[3, 4], [2, 1003], [1, 16], [3, 1]]),
    freqQuery([[1, 3], [2, 3], [3, 2], [1, 4], [1, 5], [1, 5], [1, 4], [3, 2], [2, 4], [3, 2]]),
    freqQuery([[1, 5], [1, 6], [3, 2], [1, 10], [1, 10], [1, 6], [2, 5], [3, 2]]),
    freqQuery([[1, 3], [1, 38], [2, 1], [1, 16], [2, 1], [2, 2], [1, 64], [1, 84], [3, 1], [1, 100], [1, 10], [2, 2], [2, 1], [1, 67], [2, 2], [3, 1], [1, 99], [1, 32], [1, 58], [3, 2]]),
);

Instead of the three if-statements you could also use switch:

switch(action) {
    case 1: …
    case 2: …
    case 3: …
}

Small improvements

The bottleneck in this functions is indexOf. An alternative is using .includes():

if (action === 3) {
   result.push(frequencies.includes(value) ? 1 : 0);
}

This is faster for all test cases I ran in Chrome and Node.js. It is sometimes faster but can be slower depending highly on the input in Safari and Firefox.

Here's a test on jsfiddle.

Taking it one step further

So, the bottleneck is still the expensive test in case 3:

frequencies.includes(value)

Let's get rid of this by keeping track of the current frequencies ourselves. The main improvement is, that we finally will only have to check whether a given index evaluates to true:

if (action === 3) {
    result.push(frequencyTracker[value] > 0 ? 1 : 0);
}

We introduce a second array frequencyTracker, which is filled with the amount each frequency occurs. I've used the ternary operator simply to shorten the code.

function freqQuery(queries) {
    const frequencies = [];
    const frequencyTracker = [];
    const result = [];

    for (const query of queries) {
        const action = query[0];
        const value = query[1];
        let index;

        if (action === 1 || action === 2) {
            index = frequencies[value];
            frequencyTracker[index] ? --frequencyTracker[index] : null;
        }

        if (action === 1) {
            typeof frequencies[value] === 'undefined' ? frequencies[value] = 1 : ++frequencies[value];
        }

        if (action === 2 && frequencies[value]) {
            --frequencies[value];
        }

        if (action === 1 || action === 2) {
            index = frequencies[value];
            frequencyTracker[index] ? ++frequencyTracker[index] : frequencyTracker[index] = 1;
        }

        if (action === 3) {
            result.push(frequencyTracker[value] > 0 ? 1 : 0);
        }
    }

    return result;
}

console.log(
    freqQuery([[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]]),
    freqQuery([[3, 4], [2, 1003], [1, 16], [3, 1]]),
    freqQuery([[1, 3], [2, 3], [3, 2], [1, 4], [1, 5], [1, 5], [1, 4], [3, 2], [2, 4], [3, 2]]),
    freqQuery([[1, 5], [1, 6], [3, 2], [1, 10], [1, 10], [1, 6], [2, 5], [3, 2]]),
    freqQuery([[1, 3], [1, 38], [2, 1], [1, 16], [2, 1], [2, 2], [1, 64], [1, 84], [3, 1], [1, 100], [1, 10], [2, 2], [2, 1], [1, 67], [2, 2], [3, 1], [1, 99], [1, 32], [1, 58], [3, 2]]),
);

This doesn't look as elegant as the naive solution, but it's way faster. It passes all test cases on HackerRank as well.

Explanation

As requested in the comments, here's a an example to explain how this works in detail:

Before we begin, we create an empty array, which we will become a sparse array later.

Now we run through all queries:

If the action is 1 we set or increase our counter at the given index.

[1, 2] → [undefined, undefined, 1] + [undefined, 1]
[1, 4] → [undefined, undefined, 1, undefined, 1] + [undefined, 2]
[1, 4] → [undefined, undefined, 1, undefined, 2] + [undefined, 1, 1]

If the action is 2 we decrease our counter at the given index.

[2, 2] → [undefined, undefined, 0, undefined, 2] + [1, 0, 1]

If the action is 3 we check whether the value in our frequencyTracker is "true" or "not 0" or "nor undefined".

[3, 1] → [1, 0, 1] → 0
[3, 2] → [1, 0, 1] → 1

Naming

Some variable names are good, others are ambiguous, like:

charToObj()
obj

This should be improved.


Checking if an array of dates are within a date range

To me it looks fine, other than it makes me scroll the code to read it. On this ground I agree with Sam, that line ought to be shortened. To do so I would

use the fact that you don't need to convert mysql format dates to compare them
remove excessive bracing
use De Morgan's law to invert the condition

and get this
function dates_in_range( string $start_date, string $end_date, array $dates ): bool
{
    foreach ( $dates as $date ) {
        if ( $date < $start_date || $date > $end_date ) {
            return false;
        }
    }
    return true;
}

Also, I removed the default value for the $dates as I don't see any use in calling this function with only two parameters.
I am not sure about empty arrays though. Your function will return true for one, but it's hard to tell whether it's correct or not. It's like division by zero, and may be an exception must be thrown.


As I suspected, there's already a thing for this - a TreeView. Strongly prefer built-in widgets that get the job done, leaving the construction of individual elements as a last resort if the built-in widget doesn't at all meet your needs.
There's plenty of examples on how to use this as a table, but if I were you I'd start with the reference documentation.
Remove the first row of your values and use it as a dedicated heading, instead. Break your i/j loop into two halves - a heading half, and a body half.


Algorithm

I find one problem here, you create len(nums)-2  times copy of array by calling nums[i+1:]. It's fast but not necessary. In general helps islice iterator to avoid copies of sub-arrays.

Iterators

Lines index_of_list_element += constant in loop strongly suggest rewrite code to use proper iterators to get more python way code. In your code i, first, second are indexes for unique numbers in nums. two_pointer() function also can be iterator to avoid create temporary list inside main loop.

Code

Idea of code with iterators

def three_sum(nums):
    def uniques(nums_sorted, start, stop, step):
        prev = None
        for idx in range(start, stop, step):  # xrange() in python2
            value = nums_sorted[idx]
            if value != prev:
                prev = value
                yield idx, value

    def two_pointer(nums_sorted, neg_a, start):
        biter = uniques(nums_sorted, start, len(nums_sorted), 1)
        citer = uniques(nums_sorted, len(nums_sorted) - 1, start, -1)
        (bidx, b), (cidx, c) = next(biter), next(citer)
        while bidx < cidx:
            two_sum = b + c
            if two_sum == neg_a:
                yield b, c
            if two_sum <= neg_a:
                bidx, b = next(biter)
            if two_sum >= neg_a:
                cidx, c = next(citer)

    nums = sorted(nums)
    return [[a, b, c] for aidx, a in uniques(nums, 0, len(nums) - 2, 1)
                      for b, c in two_pointer(nums, -a, aidx + 1)]


Architecture

stdin is usually line buffered.  So nothing is given to fgetc() until the user hits Enter.  OP code will give multiple error messages with input like "Hello 123".  Better to separate user input from input validation.  Read the line of user input with fgets() or some version of your own as fgets() does have some weaknesses.  Then validate the input.

char *input;
while ((input = my_gets()) != NULL) {
  if (valid_phrase(input)) {
    foo(input);
  } else {
    fprintf(stderr, "Invalid input\n");
  }
  free(input);
}

Concerning "I would love to get rid of the outer while loop".  That loop exists to silently consume '\n'.  If you want a loop to do that, just preceded inner loop with

int ch;
while ((ch = fgetc()) == '\n')
  ;
ungetc(ch, stdin);

char ch

The ch is not the best type.  fgetc() returns typically 257 different values [0-255] and EOF.  To properly distinguish them, save the result in an int.

// bad
char ch;
..
while (string == NULL && ch != EOF) {
while (EOF != (ch = fgetc(in_stream)) && ch != '\n') {

// better
int ch;
..
while (string == NULL && ch != EOF) {
  while (EOF != (ch = fgetc(in_stream)) && ch != '\n') {

Same for char tmp;

realloc()

Cast not need.
Modify for out of memory to free string - not needed if code will simply exits, yet good practice to put your toys (code's pointer) away.

// string  = (char*) realloc(string, len+2);
char * new_string  = realloc(string, len+2);
if (new_string == NULL) {
  free(string);
  bail_out(EXIT_FAILURE, "Out of memory");
}
string = new_string;

Good use of of sizeof(*strings) below.  Recommend simplification.

strings = (char**) realloc(strings, (index+1)*sizeof(*strings));
strings = realloc(strings, sizeof *strings * (index+1));

size_t len

Good use of size_t to represent an array size.  Curiously code does not do  the same with int index;.  Recommend size_t index;

is...()

With using int ch, no need for cast.  Since this is a logical test, recommend using ! rather than arithmetic == 0.

// if (ch != ' ' && isalpha((int)ch) == 0) {
if (ch != ' ' && !isalpha(ch)) {

The following may be easier to understand - fewer negations.  (Style issue)

if (!(ch == ' ' || isalpha(ch))) {

ferror()

Nice check of if (ferror(in_stream))

Variable names

string, strings is as useful as calling an integer integer.  Maybe phrase, dictionary instead.

// OK
/** @brief Contains the dictionary */
static char **strings = NULL;

// Better
// comment not truly needed
static char **dictionary = NULL;

get_strings() is mis-named.  It sounds general, yet code restricts input to letters and space.  Maybe get_words()?


Right, there's two parts to this review:

Is what you are doing 'good'?
Is there a better way?

The answer to the second question is 'yes', but we'll have to explore your current code to understand why....

Current code, is it good?

Your code, for the most part, is neat, well-named, and generally understandable. Great. But, there are some significant problems too:

your 'default' constructor creates the Rational 1/2 .... why? What's special about that....? Remove it.
It is better to have one 'core' constructor, and then have the other constructors call it.... :

public Rational(int num, int den){
    numer = num;
    denom = den;
    reduce();
}

public Rational(Rational x){
    this(x.numer, x.demon);
}

The equals(...) and hashCode() contract. If you override one of equals() or hashCode() you should always also override the other.
your equals() method is oddly broken because it should take an Object as an argument. You have a situation where you may compare two rationals in a context where Java will call the equals(Rational) in one situation, but in a different situation (if Java does not know that the value really is a Rational) it may call equals(Object)... and that may return false. This will lead to some interesting confusion..... hmmm.
you implement the method compareTo(Rational) but your class does not implement the Comparable interface. If you implement the Comparable interface you can do things like put your values in an array and then sort them using the native Java mechanisms, etc.
your public interface methods should have comprehensive names, even if your variables do not: setNumer(int) and setDemon(int) should be setNumerator(int) and setDenominator(int) respectively. The same is true for the get* versions. Just because you were a bit lazy and used the auto-generated getter/setter mechanism in your IDE to create these methods, does not mean they are good names.
you are not validating your denominator for division-by-zero.
if your numerator is 0 you should have a special case for it.
you should check for nulls for all input Rationals

OK, that's enough about the style.... let's go through the bugs... ;-)

you do integer division a lot, and you are getting wrong answers (note that this equals() method is broken for other reasons too):

public boolean equals(Rational x){
    if (numer / denom == x.numer / x.denom){
        return(true);
    } else {
        return(false);
    }
}

This is broken, because, consider two Rationals 1/1 and 99/50 ... when you do your math, you are doing integer division, so both of them have the result 1, and 1 == 1 so your code will declare that 1 == 1.5, which is only off by nearly 100%....

This same type of logic is used in the compareTo() method.

Since you reduce() your Rational after every operation, your equals method could be as simple as return numer == x.numer && denom == x.denom;

OK, that's enough about the general issues....

The better way.

Storing your Rational numbers is an important part of many programs. The underlying problem with your class is that it is Mutable. .... you can change the value of a Rational. This is unfortunate for a few reasons:

you cannot use it as a Key in a java.util.Map<Rational,...> because, if the value changes, it will break the internal hashing in the map.
similarly, you cannot store these rationals in a java.util.Set<Rational>().
If you sort your data, the order will change if you change a Rational's value.
The instances are not thread safe.
serializing the instances is a problem.

This problem is well understood, and all the Java number-type classes are Immutable (Integer, Long, Double, BigInteger, BigDecimal, ......).

BigDecimal is a really good example of what you should be doing here. Have a look at it's Javadoc. Notice how all the mathematical methods do not modify the BigDecimal, but return a new BigDecimal with the right value.

Putting all of this together, your class should really look something like:

public final Rational implements Comparable<Rational> {

    private static final int getGCD(int a, int b) {
        .....
        return divisor;
    }

    private static final Rational checkRational(rat) {
        if (rational == null) {
            throw new NullPoiterException("Must supply a non-null Rational value");
        }
        return rat;
    }

    private final int numer, denom;

    public Rational(int numerator, denominator) {
        if (denominator == 0) {
            throw new IllegalArgumentException("Denominator cannot be 0");
        }
        // reduce the value at construct time....
        int div = numerator == 0 ? 1 : getGCD(numerator, denominator);
        // div is guaranteed to be a divisor, so integer division is safe
        this.numer = numerator/div;
        this.denom = numerator == 0 ? 1 : denominator/div;
    }

    public Rational(Rational other) {
        this(other.numer, other.denom);
    }

    @Override
    public int hashCode() {
        // somewhat convenient hashcode ... it's a bitwise trick...
        // could be improved...
        return numer * 31 ^ denom * 31;
    }

    @Override
    public boolean equals(Object other) {
        return other instanceof Rational
              && ((Rational)other).numer == numer
              && ((Rational)other).denom == denom;
    }

    @Override
    public int compareTo(Rational other) {
        checkRational(other);
        Rational difference = subtract(other);
        if (difference.numer > 0) {
            return 1;
        }
        if (difference.numer < 0) {
            return -1;
        }
        return 0;
    }

    // return a new instance instead of updating ourselves...
    public Rational add(Rational addend) {
        checkRational(other);
        return new Rational(addend.numer * denom + numer * other.denom, denom * other.denom);
    }

    ....... Lots more .....

}


Merging Two Sorted Lists in Python In Linear Time

Correctness

First of all, your merging code is not correct. If you have list1 = [1, 2, 3] and list2 = [4, 5, 6], the result would be [6, 5, 4, 1, 2, 3].

Assuming, you are up to [1, 2, 3, 4, 5, 6], you should be comparing the first elements of the lists. The problem with that is that "pop" from the left is an expensive operation for a regular Python list. Switching to the collections.deque double-ended queue would solve it - popleft() is O(1).

Fixed version:

from collections import deque

def merge_sorted_lists(left, right):
    """
    Merge sort merging function.
    TODO: Improve, add examples."""
    result = deque()

    left = deque(left)
    right = deque(right)

    while left and right:
        if left[0] > right[0]:
            result.append(right.popleft())
        else:
            result.append(left.popleft())
    return result + left + right

Time Complexity Analysis (for your "incorrect" version)

You are operating Python lists, according to the Time Complexity page:

the "get length" operation is O(1) (even though you can use -1 in place of len(list1) - 1 and len(list2) - 1)
the "pop from the right" operation is O(1)
the "append to the right" operation is O(1)

Which leads to overall complexity as O(N + M) where N is the length of the list1 and M - the length of the list list2.

Stylistic issues:

as per PEP8 guide, use 4 spaces for indentation
the function name should be merge_sorted_lists according to PEP8 variable naming guidelines
list1 should be better called left, list2 - right, list3  - result for clarity purposes
missing docstring explaining what function does