Don't include unnecessary headers

We're not using <vector> or <stdio.h>, so drop them.  We only need <ostream> rather than <iostream> for the class, and we prefer <cstring> to <string.h> to place the standard functions in their proper namespace.

Avoid importing all of namespace std

It's a bad habit that will cause problems in bigger programs.  Just don't.

Add some compiler warnings

I get some useful diagnostics, worth heeding, with g++ -Weffc++:

165851.cpp:33:39: warning: ‘DynString& DynString::operator+(DynString&)’ should return by value [-Weffc++]
     DynString& operator+ (DynString& y) {
                                       ^
165851.cpp:54:34: warning: ‘DynString& DynString::operator+(char*)’ should return by value [-Weffc++]
     DynString& operator+ (char* x) {
                                  ^
165851.cpp: In constructor ‘DynString::DynString(const char*)’:
165851.cpp:12:5: warning: ‘DynString::c’ should be initialized in the member initialization list [-Weffc++]
     DynString(const char* input) {
     ^~~~~~~~~
165851.cpp: In copy constructor ‘DynString::DynString(const DynString&)’:
165851.cpp:19:5: warning: ‘DynString::c’ should be initialized in the member initialization list [-Weffc++]
     DynString(const DynString& dynstring) {
     ^~~~~~~~~
165851.cpp: In function ‘int main()’:
165851.cpp:95:23: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wpedantic]
     stringD = "The" + stringB + " Wide Web";
                       ^~~~~~~
165851.cpp:95:33: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wpedantic]
     stringD = "The" + stringB + " Wide Web";
                                 ^~~~~~~~~~~

The last two are easily fixed by changing operator+ to accept const char* instead of char*.

The usual way of fixing the warnings on operator+ is to implement operator+ in terms of operator+= (the latter returns a reference, but the former an object).

BUG - be careful using a null pointer as sentinel

What happens if you evaluate DynString() + DynString()?  In both cases, the internal pointer points to NULL, but you happily call strlen on both - that's Undefined Behaviour.  Here's some code that actually checks:

DynString(const DynString& other)
    : c(nullptr)
{
    if (other.c) {
        c = new char[std::strlen(other.c) + 1];
        std::strcpy(c, other.c);
    }
}

But it's probably easier (safer) to always allocate memory:

DynString(const char* input)
    : c(new char[(input ? std::strlen(input) : 0) + 1];)
{
    if (input) {
        std::strcpy(c, input);
    } else {
        *c = '\0';
    }
}

And then all methods can safely assume c isn't null.

Add a move constructor

This one's easy:

DynString(DynString&& other)
    : DynString()
{
    std::swap(c, other.c);
}

Overload operator[]

Allow for both constant and mutable string objects:

char& operator[](size_t i) {
    return c[i];
}

const char& operator[](size_t i) const {
    return c[i];
}

I believe size_t is more appropriate than int as the type of the index.

Eliminate the memory leaks

The example program leaks:

==13517== Memcheck, a memory error detector
==13517== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==13517== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info
==13517== Command: ./165851
==13517==
Hello Worlt
Hello World
The World Wide Web
sh: 1: pause: not found
==13517==
==13517== HEAP SUMMARY:
==13517==     in use at exit: 47 bytes in 3 blocks
==13517==   total heap usage: 12 allocs, 9 frees, 73,860 bytes allocated
==13517==
==13517== 11 bytes in 1 blocks are definitely lost in loss record 1 of 3
==13517==    at 0x4C2C93F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13517==    by 0x108FF3: DynString::operator+(DynString&) (165851.cpp:38)
==13517==    by 0x108C62: main (165851.cpp:90)
==13517==
==13517== 18 bytes in 1 blocks are definitely lost in loss record 2 of 3
==13517==    at 0x4C2C93F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13517==    by 0x10915B: DynString::operator+(char*) (165851.cpp:59)
==13517==    by 0x108CD5: main (165851.cpp:95)
==13517==
==13517== 18 bytes in 1 blocks are definitely lost in loss record 3 of 3
==13517==    at 0x4C2C93F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13517==    by 0x1091EF: DynString::operator=(DynString&) (165851.cpp:69)
==13517==    by 0x108CE7: main (165851.cpp:95)
==13517==
==13517== LEAK SUMMARY:
==13517==    definitely lost: 47 bytes in 3 blocks
==13517==    indirectly lost: 0 bytes in 0 blocks
==13517==      possibly lost: 0 bytes in 0 blocks
==13517==    still reachable: 0 bytes in 0 blocks
==13517==         suppressed: 0 bytes in 0 blocks
==13517==
==13517== For counts of detected and suppressed errors, rerun with: -v
==13517== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 0 from 0)

The main cause is:

    char *newArray = new char[strlen(y.c) + strlen(this->c) + 1];
    strcpy(newArray, this->c);
    strcat(newArray, y.c);
    delete[] c;
    c = new char[strlen(newArray)];
    this->c = newArray;

The error is more visible if you remove the redundant this-> from the last line:

    delete[] c;
    c = new char[strlen(newArray)];
    c = newArray;

The first allocation is obviously leaked, and that line of code should be deleted.  The same error is present in several other methods.

Implementation of operator+:

I would write it like this, starting with the += that the other versions need:

public:
    DynString& operator+=(const DynString& other)
    {
        char *newArray = new char[strlen(c) + strlen(other.c) + 1];
        std::strcpy(newArray, c);
        std::strcat(newArray, other.c);
        delete[] c;
        c =  newArray;
        return *this;
    }

    DynString operator+(const DynString& other) const
    {
        DynString newString(*this);
        return newString += other;
    }

We don't need operator+(const char*), as a C-style string will be promoted to DynString using the (non-explicit) constructor.  We do need an overload to take a C-style string as the first argument - but it doesn't need to be a friend, as it can be an ordinary non-member function instead:

DynString operator+(const char* x, const DynString& other) {
    DynString newString(x);
    return newString += other;
}

Improved version

This code is tested and does not leak:

#include <ostream>
#include <cstring>

class DynString {
private:
    char *c;

public:
    ~DynString()
    {
        delete[] c;
    }

    DynString(const char* input = nullptr)
        : c(new char[(input ? std::strlen(input) : 0) + 1])
    {
        if (input) {
            std::strcpy(c, input);
        } else {
            *c = '\0';
        }
    }

    DynString(const DynString& other)
        : c(new char[std::strlen(other.c) + 1])
    {
        std::strcpy(c, other.c);
    }

    DynString(DynString&& other)
        : DynString()
    {
        std::swap(c, other.c);
    }

    friend std::ostream& operator<<(std::ostream& lhs, const DynString& a)
    {
        return lhs << a.c;
    }

    char& operator[](size_t i)
    {
        return c[i];
    }

    const char& operator[](size_t i) const
    {
        return c[i];
    }

    DynString& operator+=(const DynString& other)
    {
        char *newArray = new char[strlen(c) + strlen(other.c) + 1];
        std::strcpy(newArray, c);
        std::strcat(newArray, other.c);
        delete[] c;
        c =  newArray;
        return *this;
    }

    DynString operator+(const DynString& other) const
    {
        DynString newString(*this);
        return newString += other;
    }

   DynString& operator=(DynString other) {
       std::swap(c, other.c);
       return *this;
   }
};

DynString operator+(const char* x, DynString& other) {
    DynString newString(x);
    return newString += other;
}

#include <iostream>
int main()
{
    DynString stringA("Hello");
    DynString stringB(" Worlt");
    //UNO
    std::cout << stringA << stringB << std::endl;

    //DUO
    stringB[5] = 'd';

    //TRIO
    DynString stringC = stringA + stringB;
    std::cout << stringC << std::endl;

    DynString stringD;
    //QUATRO
    stringD = "The" + stringB + " Wide Web";
    std::cout << stringD << std::endl;
}

Make the concatenation more efficient

Implementing operator+ by copying and appending is inefficient because it allocates memory for the copy that is immediately released during the append.  So we can revisit that method and eliminate the copy step.  I'd do it using an extra constructor:

private:
    DynString(const DynString& a, const DynString& b)
        : c(new char[std::strlen(a.c) + std::strlen(b.c) + 1])
    {
        std::strcpy(c, a.c);
        std::strcat(c, b.c);
    }

public:
    DynString operator+(const DynString& other) const
    {
        return DynString(*this, other);
    }

We can now simplify operator+=, implementing that in terms of our new operator+:

void swap(DynString& other)
{
    std::swap(length, other.length);
    std::swap(c, other.c);
}

DynString& operator+=(const DynString& other)
{
    Dynstring newString(*this, other);
    swap(newString);
    return *this;
}

Remember the string length

We can make every method more efficient, and also allow for embedded NUL characters in strings, if we store the length as a member:

private:
    std::size_t length;         // not including terminator
    char *c;

    DynString(const DynString& a, const DynString& b)
        : length(a.length + b.length),
          c(new char[length + 1])
    {
        std::memcpy(c, a.c, a.length);
        std::memcpy(c+a.length, b.c, b.length+1); // copies terminator
    }

Lean on the standard library for memory management

Instead of managing our own memory, we could make c be a unique pointer:

private:
    std::size_t length;         // not including terminator
    std::unique_ptr<char[]> c;

    DynString(const DynString& a, const DynString& b)
        : length(a.length + b.length),
          c(std::make_unique<char[]>(length + 1))
    {
        std::memcpy(c.get(), a.c.get(), a.length);
        std::memcpy(c.get()+a.length, b.c.get(), b.length+1); // copies terminator
    }

You'll see that we do need to sprinkle calls to get() where we need pointers to the contents

Improved, efficient, smart-pointer version:

(just the class; everything else unchanged from first "Improved version" above, except an additional include)

#include <memory>

class DynString {
private:
    std::size_t length;         // not including terminator
    std::unique_ptr<char[]> c;

    // Helper constructor - allocates but does not initialize
    DynString(size_t length)
        : length(length),
          c(std::make_unique<char[]>(length + 1))
    {}

    DynString(const DynString& a, const DynString& b)
        : DynString(a.length + b.length)
    {
        std::memcpy(c.get(), a.c.get(), a.length);
        std::memcpy(c.get()+a.length, b.c.get(), b.length+1); // copies terminator
    }

public:
    DynString(const char* input = nullptr)
        : DynString(input ? std::strlen(input) : 0)
    {
        if (input) {
            std::memcpy(c.get(), input, length + 1);
        } else {
            c.get()[0] = '\0';
        }
    }

    DynString(const DynString& other)
        : DynString(other.length)
    {
        if (length != other.length)
            c = std::make_unique<char[]>(other.length+1);
        length = other.length;
        std::memcpy(c.get(), other.c.get(), length + 1);
    }

    DynString(DynString&& other) noexcept
        : DynString()
    {
        swap(other);
    }

    void swap(DynString& other) noexcept
    {
        std::swap(length, other.length);
        std::swap(c, other.c);
    }

    friend std::ostream& operator<<(std::ostream& lhs, const DynString& a)
    {
        return lhs << a.c.get();
    }

    char& operator[](size_t i) noexcept
    {
        return c.get()[i];
    }

    const char& operator[](size_t i) const noexcept
    {
        return c.get()[i];
    }

    DynString& operator+=(const DynString& other)
    {
        DynString newString(*this, other);
        swap(newString);
        return *this;
    }

    DynString operator+(const DynString& other) const
    {
        return DynString(*this, other);
    }

    DynString& operator=(DynString other) noexcept
    {
        swap(other);
        return *this;
    }
};


Slow python code that automatically selects k for KNNG

Without thinking too hard about what you are actually doing (i.e., by trying to find a considerable more efficient algorithm), you could get a decent speedup by using list comprehension. Doing appends inside an explicit for loop doesn't usually lead to high performance.
Another observation is that you are doing too much work in sorting the whole row, when you just want the first k elements in sorted order. For that, there's a more suitable function like numpy.argpartition or heapq.nsmallest.

I don't have a test program for correctness, but I wrote a simple check for performance. But even then, I have no idea about your actual use case and parameters, so take it with a grain of salt:

import numpy as np
from sklearn.metrics.pairwise import euclidean_distances
from time import time

def autoselect_K_orig(X, n_neighbors_max, threshold):
    # get the pairwise euclidean distance between every observation
    D = euclidean_distances(X, X)
    chosen_k = n_neighbors_max
    for k in range(2, n_neighbors_max):
        k_avg = []
        # loop over each row in the distance matrix
        for row in D:
            # sort the row from smallest distance to largest distance
            sorted_row = np.sort(row)
            # calculate the mean of the smallest k+1 distances
            k_avg.append(np.mean(sorted_row[0:k]))
        # find the median of the averages
        kmedian_dist = np.median(k_avg)
        if kmedian_dist >= threshold:
            chosen_k = k
            break
    # return the number of nearest neighbors to use
    return chosen_k

def autoselect_K_other(X, n_neighbors_max, threshold):
    D = euclidean_distances(X, X)
    for k in range(2, n_neighbors_max):
        kmedian_dist = np.median([np.mean(row[np.argpartition(row, k)]) for row in D])
        if kmedian_dist >= threshold:
            return k

    return n_neighbors_max

# Rudimentary performance check
X = np.random.randint(5, size=(10000, 10))

start = time()
result = autoselect_K_orig(X, 20, 4)
end = time()
total_orig = end - start
print('Original: ', total_orig)

start = time()
result = autoselect_K_other(X, 20, 4)
end = time()
total_other = end - start
print('Other: ', total_other)

print('Speedup: ', total_orig / total_other)

On my outdated hardware, a typical output is:

Original:  57.56129217147827
Other:  2.257129192352295
Speedup: 25.501992693422242

Meaning speedups of more than 25x. Not surprisingly, this speedup is strongly linked to the value of n_neighbors_max; if you make it very small, the speedup tends to go as low as 2x, but as you can see, it grows quite considerably for larger values, which is probably exactly what you want.

I think further optimization even with your current approach is still possible. For instance, notice that everytime that you increment k, you are essentially duplicating work you have already done by again taking the first (k-1) elements, taking their mean, and so on. Instead, for step k, you should have stored the mean of step (k-1), and then you simply update this mean with a new element that now comes in, reducing the amount of computation you need to do.
Even without such an optimization, you could still get some gains by getting rid of the explicit for loop that goes from 2 to n_neighbors_max by using a suitable generator expression that asks for more elements for as long as we've not extracted an element of at least the threshold.


Script that helps people make better choices

I think your program would be easier to use and create if you rearrange when you ask your questions. (This is mostly to show that I have consciously changed how your program works)
You are correct it would be easier to use your data if you enter it as a dictionary and some lists. I personally would use the following layout:

option_1 = {
    'option': option1,
    'reasons': [option1a, option1b, option1c],
    'weights': [option1aw, option1bw, option1cw],
}

This allows getting the relevant by indexing the objects.
For example to get the entered option you can do:

option_1['option']

To get the first reason you can do:

option_1['option'][0]

It should be noted that lists in Python, and most programming languages, are indexed starting at 0, which is why to get the first value we see the 0 above.
Reduce your workload by using functions, these allow you to define a set of instructions to run which you can then reuse by calling the function.

Take the following function to get an option:
Note: I have changed the questions in this code snippet.

def get_option():
    return {
        'option': input('Enter an option: '),
        'reasons': [
            input(f'Option 1: Why is this a good option? '),
            input(f'Option 2: Why is this a good option? '),
            input(f'Option 3: Why is this a good option? '),
        ],
        'weights': [
            int(input(f'How important is Option 1? (from 1-5) ')),
            int(input(f'How important is Option 2? (from 1-5) ')),
            int(input(f'How important is Option 3? (from 1-5) ')),
        ]
    }

Allowing a user to enter two options is now simple. You make a list with both of them.

options = [
    get_option(),
    get_option(),
]

Before we go any further I'd like to show you my favorite feature of Python - list comprehensions. These allow you to perform a task on a list in a single line. Take the above code snippet to generate two options, we can rewrite that using standard list generation methods exposed in Python and other languages, which would look like:

options = []  # Build an empty list
for _ in range(2):  # Loop twice
    options.append(get_option())  # Add an option to options on each loop

However this pattern is rather messy and it would be more Pythonic to use a comprehension here.

options = [
    get_option()
    for _ in range(2)
]

You should be able to notice we can also use this to simplify our get_option code.

def get_option():
    return {
        'option': input('Enter an option: '),
        'reasons': [
            input(f'Reason {i+1}: Why is this a good option? ')
            for i in range(3)
        ],
        'weights': [
            int(input(f'How important is Reason {i+1}? (from 1-5) '))
            for i in range(3)
        ]
    }

From here we can change your option1result and option2result to:

results = [sum(option['weights']) for option in options]

You can use random.choice to chose from a list.
It is best practice to use an if __name__ == '__main__': guard to prevent your code from running unless it's the main program.
Don't use quit, if you remove it the program will exit successfully.

import random

def get_option():
    return {
        'option': input('Enter an option: '),
        'reasons': [
            input(f'Reason {i+1}: Why is this a good option? ')
            for i in range(3)
        ],
        'weights': [
            int(input(f'How important is Reason {i+1}? (from 1-5) '))
            for i in range(3)
        ]
    }

if __name__ == '__main__':
    print('First, tell me what your options are.')
    options = [
        get_option()
        for _ in range(2)
    ]
    prompt = input('\nWe will calculate now.\n')

    results = [sum(option['weights']) for option in options]
    if results[0] == results[1]:
        input('There are multiple best options.\nThe best will be determined by coinflip.\n')
        best_option = random.choice(options)
    else:
        best_option = options[0] if results[0] > results[1] else results[1]

    print('Your best choice is:')
    print(options[0]['option'])

Additional improvements:

Your code only currently works for two options. To get the top options for any amount of options is fairly simple.

You want a dictionary that holds all the options with a certain total weight. After this you just want to take the max weight, which will give you all the options with that weight.

Once you have have the best options the code is pretty much the same, if there are multiple options then you just use random.choice on them to narrow them down to one.
You should allow your user to enter how many options and reasons they want. This now is just a simple question you can ask before entering either loop.
The way you get user input is error prone, if I enter a as my weight then your code blows up.
You should also take into account that you've told your user that only 1-5 are valid entries, but happily allow -1, and 6.
Not displaying all the best options seems like a poor oversight. Since we know all the best options we can just display them by looping.

Ignoring 3 this can get:

import random

def get_option():
    option = input('Enter an option: ')
    reasons = int(input('How many reasons do you have for this option? '))
    return {
        'option': option,
        'reasons': [
            input(f'Reason {i+1}: Why is this a good option? ')
            for i in range(reasons)
        ],
        'weights': [
            int(input(f'How important is Reason {i+1}? (from 1-5) '))
            for i in range(reasons)
        ]
    }

def get_top_options(options):
    rankings = {}
    for option in options:
        rankings.setdefault(sum(option['weights']), []).append(option)
    return rankings[max(rankings)]

if __name__ == '__main__':
    amount_options = int(input('How many options are there? '))
    options = [
        get_option()
        for _ in range(amount_options)
    ]
    prompt = input('\nWe will calculate now.\n')

    best_options = get_top_options(options)
    if len(best_options) == 1:
        print('Your best choice is:')
    else:
        print('Your best choices are:')
    for option in best_options:
        print(option['option'])


Filtering a recursive directory listing, discarding subfolders

is there an issue with using variables inside anonymous methods that were declared outside?

No, this is what anonymous methods are designed for! It is a very useful trick to keep up your sleeve. Read up on Closures. There are all sorts of things you can do with them.

Obviously there are issues with doing anything when you don't understand it fully, but the way you are using them in your code is what these things are all about!

  any potential issues with nested anonymous methods?

Same thing.

  any other issues or best practices worth mentioning?

Unless you are still using c# 2, the syntax has been simplified to use what is known as a lambda. Instead of using

delegate(string curFolder) { ..code.. }

you can just go :

curFolder => ..code..

As RemoveAll takes a Predicate, you can also lose the return key word. As long as the statement evaluates to True or False, it will take that as the return.

You have some code that is basically going :

if x == true
    return true
return false

This can be simplified to :

return x

With those two things, your code could be simplified to :

 uniqueFolders.RemoveAll(
        curFolder =>

            string.IsNullOrEmpty(curFolder) ||
                   uniqueFolders.Exists( s=>
                        !string.IsNullOrEmpty(s) &&
                        curFolder.StartsWith(s) &&
                        string.Compare(s, curFolder) != 0)

    );

Its a bit of a mouthfull. You may want to factor out a new method.

uniqueFolders.RemoveAll( curFolder => IsNotRootFolder(uniqueFolders, curFolder ) );

bool IsNotRootFolder ( uniqueFolders, curFolder )
{
   return string.IsNullOrEmpty(curFolder) ||
          uniqueFolders.Exists( s=>
            !string.IsNullOrEmpty(s) &&
            curFolder.StartsWith(s) &&
            string.Compare(s, curFolder) != 0)
}


Check if a stack of Integers contains a sequence of consecutive values

Bug 1

Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(isConsecutive(stack));

returns false.

Bug 2

Your method throws EmptyStackException on stack of size 1.

Advice

I suggest you declare your method as static. That way the client programmer does not need to instantiate an object.

Alternative implementation

This is just a slight modification of my answer to your previous stack related question:

public static boolean isConsecutiveV2(Stack<Integer> stack) {
    if (stack.size() <= 1) {
        return true;
    }

    Stack<Integer> aux = new Stack<>();

    aux.push(stack.pop());

    while (!stack.isEmpty() && stack.peek() == aux.peek() - 1) {
        aux.push(stack.pop());
    }

    boolean consecutive = stack.isEmpty();

    // Restore the input stack:
    while (!aux.isEmpty()) {
        stack.push(aux.pop());
    }

    return consecutive;
}


Sorting an int[] array with an Insertion Sort

Your implementation is not quite correct. It is subtle, but what you have is a type of bubble sort in that you do not insert the new value, rather you 'slide' the value in to place.

An insertion sort can be thought of as a 'hole'. You shift all the 'bigger' values to the right by one space, and create a hole at the point where the value should be inserted. Then you insert the value in to the hole.

There should not be a concept of a 'swap' in an insertion sort.

You start at the first unsorted value, and then if the previous values are smaller, you move them up one, until you have the space at the right spot. Then you put the value there.

The example code makes this 'obvious' (but not really), in that it always compares against value and not arr[j+1]. It also has only a single 'assignment' to the array for each time in the loop. Your swap routine does two assignments on each loop.

So, No, your implementation of an insertion sort is not quite correct. It is a correct sort, but not a 'text-book' insertion sort since it slides, rather than inserts the value.


Reading genetic data in VCF and Tabix formats using an asynchronous library

A few painfully obvious edits of my own:

The frivolous for-loop:

for (var a = 0; a < regions.length; a++) {
    d.push([]);
    readers.push(new readBinaryVCF(tabix, vcf, function(x) {x = x;}));
}

Why, why did I think this was a good idea? It's entirely unnecessary.

Omitted.

Callback-waiting:

if (i == regions.length - 1) {

   var finalText = "";

   for (var j = 0; j < d.length; j++) {
       for (var k = 0; k < d[j].length; k++) {
           finalText = finalText + d[j][k] + "<br />";
       }
   }

   $(".text").html(finalText);
}

I thought I could wait until the "last" callback had ended before parsing my data, not realizing that—because they're, again, callbacks—they won't finish in order. This answer inspired me to use a manual counter to determine when they've all finished.

Revised code:

var d = [];
var readers = [];
var callbacksRemaining = regions.length;

regions.forEach(function(item, i) {

    readers[i] = new readBinaryVCF(tabix, vcf, function(tabixReader) {

        reader = readers[i];

        var index = 0;

        for (key in tabixReader.idxContent.namehash) {
            if (key == regions[i][0]) {
                index = tabixReader.idxContent.namehash[key];
            }
        }

        reader.getRecords(index, regions[i][1], regions[i][2], function(data) {;

            d[i] = data;
            callbacksRemaining--;

            if (callbacksRemaining <= 0) {
                processData(d);
            }
        });
    });
});

Summary:

I've made these few minor edits, but my code still isn't running as fast as I'd like. I'm sure there are many more changes I could and should make—I'm still hoping for advice!


Did you know that anyone can set a cookie whenever they like? Imagine someone will set the "user" cookie to "admin".

Use any of popular PHP frameworks instead. They're here for a reason.

I'd also advise to use prepared statement if you absolutely have to write this kind of code yourself.

$query = "SELECT username, password FROM users WHERE username=? AND password=?";
if ($pst = $conn->prepare($query)) {
  $pst->bind_param("ss", $username, $password_hash);
  $pst->execute();
  if ($pst->num_rows) {
    // logged in
  }
}


Array-search algorithm for identical sequences and character distances

1. Improving the code

Here are some ways in which you could improve your code, while leaving the algorithm unchanged:

You can avoid the need to check counts.has_key(j-i) if you use collections.Counter.
You are looping over all pairs of distinct indexes between 0 and len(array)-2. The function itertools.combinations provides a way to cleanly express your intention.
Instead of comparing three pairs of array elements, you can compare one pair of array slices.
Organize the code into a function with a docstring.
Generalize it from 3 to \$k\$.
Python doesn't have an "array" type, but it does have sequences. So your variables could be better named.

Here's the revised code after making the above improvements:

from collections import Counter
from itertools import combinations

def subseq_distance_counts(seq, k=3):
    """Return a dictionary whose keys are distances and whose values
    are the number of identical pairs of `k`-length subsequences
    of `seq` separated by that distance. `k` defaults to 3.

    """
    counts = Counter()
    for i, j in combinations(range(len(seq) - k + 1), 2):
        if seq[i:i + k] == seq[j:j + k]:
            counts[j - i] += 1
    return counts

It's possible to rewrite the body of this function as a single expression:

    return Counter(j - i
                   for i, j in combinations(range(len(seq) - k + 1), 2)
                   if seq[i:i + k] == seq[j:j + k])

Some people prefer this style of coding, and others prefer the explicitness of the first version. It doesn't make much difference to the performance, so comes down to personal taste.

2. Improving the algorithm

Here's an alternative approach (that you could use if the subsequences are hashable). Your original algorithm is \$ O(n^2) \$, where \$n\$ is the length of the sequence. The algorithm below is \$O(n + m)\$, where \$m\$ is the number of repeated triples. This won't make any different in the worst case, where \$m = Θ(n^2)\$, but in cases where \$m = ο(n^2)\$ it should be an improvement.

def subseq_distance_counts(seq, k=3):
    """Return a dictionary whose keys are distances and whose values
    are the number of identical pairs of `k`-length subsequences
    of `seq` separated by that distance. `k` defaults to 3.

    >>> subseq_distance_counts('abcabcabc')
    Counter({3: 4, 6: 1})
    >>> subseq_distance_counts('aaaaaa', 1)
    Counter({1: 5, 2: 4, 3: 3, 4: 2, 5: 1})

    """
    positions = defaultdict(list) # List of positions where each subsequence appears.
    for i in range(len(seq) - k + 1):
        positions[seq[i:i + k]].append(i)
    return Counter(j - i
                   for p in positions.itervalues()
                   for i, j in combinations(p, 2))


Security of login form using prepared statements

I'll point out a few things here:

$pswd = sha1($pswd); is cringeworthy. Please use password_hash() if you can. If you can't update your PHP version to comply, my next best suggestion is to use crypt().
Having all of your DB connection code on the page is generally considered poor coding. Place everything between $servername ... // statement in a separate file and require it.
In your select statement, there is no reason to retrieve the password from the DB alongside the username. The less you deal with the password, most likely will be safer. Also, you're putting the hashed password in the session, which I'm not sure is the best idea. A phishing attempt could potentially reveal this and a malicious user could take advantage of this information.
Your method of creating a session token is weak, and I suggest you check out this StackOverflow post for more info.
Format your code. You're missing a lot of indentation and general style rules aren't 100% met.


Improvements to simple Hangman Game in Python

This is a great start. Let me point out a few things you should consider.
Make it interactive
When I ran the code, it produces some numbers whenever I lose a guess, it took a while to figure out that it was my guess count incrementing. A nice prompt message would be helpful. Also the guess count should reduce for each guess made.
Avoid hardcorded values
What is 5 in the following statement
while lives < 5:. it can be written as follow
MAX_LIVES = 5
while lives <= MAX_LIVES:

Misleading names
character_check is just too misleading, promises one thing(to check a character) and does another thing(recieves input from the user). This can rewritten as user_input
Features worth adding

You could make the game a class,implement a board class to nicely draw the man being hung.
You could also implement a hint package interface, user might want to buy and use hints when they are stuck.


Sending activation email for sqlmembership

I think there is a problem with encapsulation and the single responsibility principle here. The method depends on too many external factors, it makes too many external references, and it includes logic of multiple independent responsibilities that would make sense to extract elsewhere.

These are good and belong to this method:

Creating and filling a MailMessage object
The constant strings for the subject
The SmtpClient object that sends the message

If the method contained only the above,
it would be perfectly reasonable.

But it contains some extra stuff that don't seem to belong:

The construction logic of fullPath. It seems this logic should be somewhere else, for example a centralized router component
The construction logic of the template file path to read
The replacement of the template parameters UserName and ActivationURL would also be good to extract to a component. There should be a component in charge of user templates and the template parameters, which naturally takes a user template and returns properly formatted text. That way, if the template changes, the logic of the template parameters will be closer to the logic that fills those parameters, making the code more cohesive.

Lastly, as a minor remark, the variable naming is not consistent.
Most of the local variables are camelCase, except ActivationUrl:

string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
string ActivationUrl = "/ActivateUser.aspx?ID=" + GetUserID(user.Email);

It would be better to use camelCase consistently.


Test clarity
A sample such as with my_decode(512) deserves a break down of how, as letters, it might be encoded.
Add as a comment, or integrate in test, the expected outputs.
Posting input as well as output is useful.
printf("%u --> result: %u\n", 512, my_decode(512));

Format
Other code and below hints OP is not using an auto formatter as break is not indented.  1) Recommend to use an auto-formatter 2) Prefer { }
    if (input % (i *10) / i == 0)
    break;
    // vs.
    if (input % (i *10) / i == 0) {
        break;
    }

Macro vs. code
Consider a helper function
bool alph_in_range(unsigned num) {
  return num >= MIN_ALPH && num <= MAX_ALPH;
}

Function
my_decode(102) is 2 and my_decode(1002) is 1.  I'd expect 2 for the first is allowed, 10,2 and 1,02 then 10,02 and 1,002 allowed for the 2nd.

Not much else to say.
Minor: _MAX
...._MAX more common in C such as INT_MAX
// #define MIN_ALPH 1
// #define MAX_ALPH 26

#define ALPH_MIN 1
#define ALPH_MAX 26

Minor: unsigned vs. unsigned int
Either works.  unsigned is shorter.
As with such style issues, code to your group's coding standard.
Minor: Mixed types
Some coding standards dislike  unsigned % int.
Could use input % 100u vs. input % 100.


Your algorithm is correct. There is no way to reduce time or space complexity, so I will give some less important suggestions.

because you know that there will only be latin letters, we can use an array instead of a hashtable and avoid the overhead. You can decide for yourself if this approach is explicit enough.

int[] counts = new int[26];
counts[ch - 'a'] += 1

firstNonRepNum() has an argument size, that it does not use.
Your indentation, while mostly consistent, is very odd. It ends up with 8 chars of indent each level. Read some style guides for other ways of indenting. In java most people indent like this.

public void func(int[] arg) {
    for (int i; arg) {
        if (i % 2) {
            even();
        } else {
            odd();
        }
    }
}

if a variable is only used in a certain scope, declare it in that scope. This helps people who are reading your code because they dont have to search for what count does.

{
    int occurs = count.get(ch);
    count.put(ch, occurs+1);
}

You call firstNonRepNum() twice. Once to check if there is a solution and once to get the result. Call it once and put the result in a variable.
Remove any unused variable declarations (i.e. String line2) or commented out code as soon as you are sure you don't need it.


Factory for constructing directed graphs in C++

Don't use using namespace std; it pollutes the namespace and creates name collisions. Only do this with concrete classes and only within a namespace or cpp file.

new without delete => leaks. Instead use smart pointers or store them by value where it makes sense.

There is no need to create a class hierarchy for the edges, instead use a enum to differentiate: enum{BIDIR, FROM_1_TO_2, FROM_2_TO_1} and a self referential edge is a BIDIR and nodes 1 and 2 are equal.

unordered_set is far from the best data structure, it's slow to iterate over, access is very often a cache miss or two. Instead prefer data structures like std::vector where it is very fast to iterate over.

The best data structure depends a lot on what operations you will be doing on it, which you didn't mention so I can't really judge beyond saying that unordered_set is most likely a bad choice.


Averaging outputs of each execution of a file

I think the short answer to your question is "what you're doing is fine, but there are other approaches depending on what you want to do." However, first:

When posting on CodeReview, try to post the most complete, compilable code that you can. This is often less work for you (because you can just paste straight from your source file with no editing), and less work for the reviewers (because they can just paste it straight into a source file and compile it). What you've posted here seems to be just the body of main.
Please indent your code consistently. This is good(ish):

if(file.is_open())
{
    while (!file.eof()) {
        file >> x;
        times.push_back(x);
    }
}

but this is bad:

if(write.is_open()) {
write << counter << endl;
};

You can use a tool like clang-format, astyle, or indent to format your code automatically until you acquire the muscle memory to do it yourself.

However, both of those snippets I just pasted have formatting "bugs" besides the indentation:  In the second one, you have a trailing ; that shouldn't be there.  In the first one, you mix brace styles:

if (x)
{

and

while(x) {

(Notice the mix of pre-parenthesis-spacing styles as well.)  Pick one style for a given program and stick with it.

Lastly, try to structure your program by breaking it down into subroutines. For this program, I'd probably have subroutines

// Generate a random number and return the number of tries for the user to guess it.
int guess_the_number();

// Append a number to the named file.
void append_to_file(const char *filename, int value);

// Retrieve the contents of the named file.
std::vector<int> load_ints_from_file(const char *filename);

And then I'd strongly consider refactoring the program along the lines suggested by symmetry: namely, would it make more sense to provide a function

// Retrieve the contents of the named file.
void save_ints_to_file(const char *filename, const std::vector<int>& values);

instead of the append_to_file function?  There are valid reasons you might not want to in production code (for example, the append-only version has better efficiency and atomicity, if you do it right — which is not to say that you have), but if your goal is just to make a readable and sensible toy guess-the-number program, personally I'd go with the load/save dichotomy in place of the load/append dichotomy.

As for your question about "how to keep a running average": if all you care about is the average number of guesses (i.e. total number of guesses divided by total number of games played), then you don't need to keep a record of how the total number of guesses happened to divide up into individual games-played. Just store those two numbers in your file:

std::vector<int> values = load_ints_from_file("times.txt");
if (values.empty()) values = std::vector<int>{0, 0};
values[0] += guess_the_number();
values[1] += 1;
std::cout << "Average is " << values[0] / values[1] << std::endl;
save_ints_in_file("times.txt", values);


SOXXY: a daemon stated IRC client project

I believe enc = enc() is considered an anti-pattern, because the semantics of enc changes. I'd suggest renaming the variable to encoding.

Rather than a long if..elif..else block you could use a simple handle_operation(op) call.

Since there's effectively no exception handling it will be difficult to diagnose errors.

Using argparse would make it possible to understand how to use the code without reading it. As a bonus it adds -h/--help support by default so users can see what the expected call structure is.

sleeping to wait for an end point to be available is an anti-pattern. To guarantee that an end point is up and that you get started processing as quickly as possible it's common to poll the end point until it responds correctly or fail if there's a timeout.


ArrayBlockingQueue - blocking drainTo() method

Your problem is easily solved without having to delve in to the internals of ArrayBlockingQueue, and without needing a new ReEntrantLock either. SImply use the methods that are currently available, and combine them....

public int drainAtLeastOneTo(Collection<? super E> c)
        throws InterruptedException {
    c.add(take());
    return 1 + drainTo(c);
}


This won't be a very in-depth review since I don't know angular.js, and I will focus only on some superficial issues.

You have "magic" classes.

These should be declared at the top, to avoid any kind of problem.

An example:

var classes = {
    open: 'slide-content-open',
    slide: 'slide-content'
};

This could help a lot with any future class change.
You repeat $element.next() 3 times.

This shows a little of misuse of the library, and you should be careful with this since it kills performance.

Try to save it into a variable or chain it's methods, if possible.
You have a "magic" number there!

Imagine that now you want to change the width that the class it removed from 990 to, say, 1020. You can argue and say "I just edit it manually, duh!". Now imagine you have 300 lines of code and you don't know where it is and it's previous value.

I recommend storing that value in a variable by itself.
You can eliminate a lot of bloat by reducing duplicated conditions.

You have the following code:

if($element.hasClass('slide-content')){
    if(($element).next().height > 0) {
        $element.next().toggleClass('slide-content-open');
    }
    else {
        $element.next().toggleClass('slide-content-open');
    }
}

So, no matter what you do, it will toggle the class? Why have this whole condition?

Eliminating most of the code:

if($element.hasClass('slide-content')){
    $element.next().toggleClass('slide-content-open');
}

For some reason, this code seems to look a little like jQuery to me. If you have jQuery, this fits in 1 single line:

$element.filter('.slide-content').next().toggleClass('slide-content-open');

You don't use the variable w anywhere, besides in 1 method a few lines below.

Instead of all that, you can chain the methods and spare a dangling reference later on.

Something like this:

angular
    .element($window, $element)
    .bind('resize load', function(){
       scope.toggleClass();
    });

For the final code:

Without jQuery:

angular
    .module('app')
    .directive('ngContentToggle', function($window) {

        var classes = {
            open: 'slide-content-open',
            slide: 'slide-content'
        };

        var minWidth = 990;

        return {
            link: function(scope, $element) {
                angular
                    .element($window, $element)
                    .bind('resize load', function(){
                       scope.toggleClass();
                    });

                scope.toggleClass = function(){
                    if($window.outerWidth < minWidth) {
                        $element.addClass(classes.slide);
                    }
                    else {
                        $element.removeClass(classes.slide);
                    }
                };
                $element.bind('click', function(){
                    if($element.hasClass(classes.slide)){
                        $element.next().toggleClass(classes.open);
                    }
                });
            }
        };
    });

With jQuery:

angular
    .module('app')
    .directive('ngContentToggle', function($window) {

        var classes = {
            open: 'slide-content-open',
            slide: 'slide-content'
        };

        var minWidth = 990;

        return {
            link: function(scope, $element) {
                angular
                    .element($window, $element)
                    .bind('resize load', function(){
                       scope.toggleClass();
                    });

                scope.toggleClass = function(){
                    if($window.outerWidth < minWidth) {
                        $element.addClass(classes.slide);
                    }
                    else {
                        $element.removeClass(classes.slide);
                    }
                };
                $element.bind('click', function(){
                    $element.filter('.' + classes.slide).next().toggleClass(classes.open);
                });
            }
        };
    });


A binary search implementation for any datatype in C (continuation)

Code does not handle an array size of 0 (count == 0). Simple to fix

//size_t lo = 0, hi = count - 1, mid;
//while (lo <= hi) {

size_t lo = 0, hi = count, mid;
while (lo < hi) {
  hi--;

Potential UB.  Consider the below if mid == 0.  IMO, better to use a variable hi_plus_1 instead of hi and adjust code accordingly to avoid size_t underflow.

        hi = mid - 1;  // hi could become SIZE_MAX

Avoid losing const-ness.

const void *base
// char *base_ptr = (char *) base;
const char *base_ptr = (const char *) base;

binary_search.c is missing the include of binary_search.h.  This is important to maintain the consistency of the declaration and definition.

binary_search.h should include <stdlib.h> for size_t.

#include "binary_search.h"

void *binary_search(const void *x, const void *base, size_t count, size_t size,
    int (*compare)(const void *, const void *)) {
  const char *base_ptr = (const char *) base;
  size_t lo = 0, hi_plus1 = count;
  while (lo < hi) {
    size_t mid = lo + (hi_plus1 - lo)/2;
    int result = (*compare)(base_ptr + mid * size, x);
    if (result == 0) {
      return base_ptr + mid * size;
    } else if (result < 0) {
      lo = mid + 1;
    } else {
      hi_plus1 = mid;
    }
  }
  return NULL;
}

Test code

Problem specifier.  Use "%zu" for size_t.  The 2 below hint OP is not compiling with all warnings enabled.  Double-check that all warnings are enabled for prompt automatic feedback.

 size_t count, i;
 // scanf("%llu", &count);
 scanf("%zu", &count);

 for (i = 0; i < count; i++) {
    // printf("%u : ", (i + 1));
    printf("%zu : ", (i + 1));

A size of 0 may cause for malloc() to return NULL and that is not an out-of-memory.

 a = malloc(count * size);
 // if (a == NULL) {
 if (a == NULL && count > 0) {
   printf("Error while trying to allocate memory.\n");

size = sizeof(double); lacks context.  Why sizeof(double)?  Certainly that is because that is the type a points to.  Then code that directly:

// size = sizeof(double);
size = sizeof *a;

For testing, useful to print the value sought and the value found.  Recommend %e for detail.

printf("Value sought %e\n", x);
printf("Value found  %e\n", x, *result);
// or for sufficient detail
printf("Value sought %.*e\n", DBL_DECIMAL_DIG - 1, x);
printf("Value found  %.*e\n", DBL_DECIMAL_DIG - 1, *result);

With compare(), note that 0.0 will match -0.0.  If that is not desired, perhaps below.  Simplifications may be possible.

int compare(const void *a, const void *b) {
    const double *p = a;
    const double *q = b;
    if (*a > *b) return 1;
    if (*a < *b) return -1;
    if (isnan(*p)) return +1;
    if (isnan(*q)) return -1;

    // values are equal and not NaNs
    if (!signbit(*a) == !signbit(*b)) return 0;
    if (signbit(*a)) return -1;
    return 1;
}


Assuming that each post has exactly one submitter, this is a more natural formulation of the query.

SELECT posts.*
     , users.username
     , users.firstname
     , users.lastname
     , users.avatar
    FROM posts
        JOIN users
            ON posts.submitter = users.username
    WHERE
        posts.id < $lastpost
        AND posts.position = posts.submitter
    ORDER BY posts.id DESC
    LIMIT 5

However, its performance is likely to be similar to your original query.  To investigate performance issues, run EXPLAIN SELECT to help you verify that the necessary indexes are in place.


Your code could be improved by using a guard clause which reduces horizontal spacing.

Names of variables shouldn't be shortened. Tabpanel tp could be easily refactored to a more meaningful Tabpanel tabPanel. Increasing readability helps Sam the Maintainer to the maintaining job.

You should catch specific exceptions, not just Exception. Also you should enclose only the code which can throw an exception.

Object target = fe.getOrigin().getTarget();

if (!(target instanceof Tab)) { return; }

Tab tab = (Tab) target ;

Tabpanel tabPanel = tab.getLinkedPanel();

tabPanel.invalidate();

if ((tabPanel.getId().equals("stbvc") && (Sessions.getCurrent()
        .getAttribute("subscriber") == null))) {

    Messagebox.show(
            "Create Subscriber first,then assign STB/VC!",
            "Warning", Messagebox.OK, Messagebox.INFORMATION);

    tabPanel.setSelectedPanel(basic);

} else {

    inc2.setSrc("stbvc.zul");

    System.out.println("Subscriber ID set in session...");
}


C# to Access SQL query based on UI controls

My initial thought is that since view models are only (or should only be) concerned with presentation logic, it shouldn't know how to construct an SQL string. I would move the code which builds up the query into a separate Query Object. Also I would have some helper methods (e.g. extension methods) to try and get rid of the repetitive null/empty/whitespace checks. For example:

public class GetRecordsQuery
{
    // If there's a lot of parameters, maybe refactor this to accept an object
    public void Execute(string recordNumber, string employeeId, string location,
                        string firstName, string lastName)
    {
        var query = new StringBuilder();

        query
            .Eq("Record_Number", recordNumber).And()
            .Like("Employee_ID", employeeId).And()
            .Like("Location", location).And()
            .Like("First_Name", firstName).And()
            .Like("Last_Name", lastName)
            .EndQuery();

        // or however AccessWorker members are invoked
        return AccessWorker.GetRecords(String.Format("WHERE {0}", query));
    }
}

public static class StringBuilderExtensions
{
    private const string AndOp = " AND ";

    public static StringBuilder And(this StringBuilder sb)
    {
        var str = sb.ToString();

        if (String.IsNullOrWhiteSpace(str))
            return sb;

        if (str.EndsWith(AndOp))
            return sb;

        return sb.Append(AndOp);
    }

    public static StringBuilder EndQuery(this StringBuilder sb)
    {
        var str = sb.ToString();

        if (String.IsNullOrWhiteSpace(str))
            return sb;

        if (!str.EndsWith(AndOp))
            return sb;

        var length = AndOp.Length;
        var start = sb.Length - length;

        return sb.Remove(start, length);
    }

    public static StringBuilder Eq(this StringBuilder sb, string column, string value)
    {
        if (String.IsNullOrWhiteSpace(value))
            return sb;

        return sb.AppendFormat("{0} = '{1}'", column, value);
    }

    public static StringBuilder Like(this StringBuilder sb, string column, string value)
    {
        if (String.IsNullOrWhiteSpace(value))
            return sb;

        return sb.AppendFormat("{0} LIKE '%{1}%'", column, value);
    }
}

EDIT 1: Corrected code to prevent AND operators being appended when one already exists.

EDIT 2: Added an EndQuery method to trim off any trailing AND operators.


Rewriting file names according to the available screen space

In general case I would to get text_width and container_width, then calculate new_string_length=container_width/text_width*length, than setup increase or decrease text, depending on result_text_width > container_width  and do the loop like yours.

This is really needed only if strings have a very big size.


You can use Set::Functional to make the code very short:

use Set::Functional 'difference';
for(difference [@ipfw_ip], [@bill_ip]) {
    `/sbin/ipfw table 11 add $ip`;
    print "$ip blocked\n";
}

Another advantage of the approach above is that you don't have to worry about duplicate entries in the two arrays.


Handling a spinner for multiple REST calls

It is in theory not necessary to unsubscribe all subscriptions. For example if you call the backend with the Angular HttpClient then you will get an observable, that will automaticly complete after it emits the first result. As soon as it is completed, the observable is gone and does not strain your ressources anymore.
That means, if the Observable will complete itself in a timely manner, then you do not have to unsubscribe.
BUT: In most cases you have to dig a bit deeper to see that an observable will complete itself. That means the reader of your code will not easily know if you forgot the unsubscribe or if it could be skipped. Therefore i personaly decided for safety (but more code) and unsubscribe always.
Not unsubscribing will result in unnecessary memory consumption and/or can create unexpected sideeffects. The function that should be executed at emits, is stored at the Subject. That means even when your component is long ago destroyed, the function will still "live" at the Subject. And will be executed at each emit...
But you could make unsubscribing a bit nicer with a Subscription Object
private subscriptions: Subscription = new Subscription();
...
this.subscriptions.add( myOberservable.subscribe(value => doMagic(value)) );
this.subscriptions.add( myOtherOberservable.subscribe(value => doMoreMagic(value)) );
...
this.subscriptions.unsubribe() // will unsubscribe all added subscriptions at once

About the general question of implementing the spinner. If you always want a spinner, you could attach it in an interceptor, activating the spinner before the call is fired and deactivated as soon as you get a respond.
Or using a central method for backend calls and doing the the toggle there.
In both cases you would need a spinner service that needs to remember how often it was "activated", so that if 3 calls are triggered at once, the first response does not deactivate the trigger.
May ways are possible, it depends a bit on your use case and your general architecture.
But your specific example i would write in the following way:
export class MyComponent implements OnInit, OnDestroy {

  private subscriptions: Subscription = new Subscription();
  private filterLoading$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);

  ngOnInit(){
      this.subscriptions.add(this.callAll().subscribe(() => this.toggleSpinner()));
  }

  ngOnDestroy(){
      this.subscriptions.unsubscribe();
  }

  private callAll():Observable[]{
    const listOfCalls: Observable[] = [
          remoteService.getFirst(),
          remoteService.getSecond(),
          remoteService.getThird(),
    ];
    return forkJoin(listOfCalls);
  }

  private toggleSpinner():void{
      this.filterLoading.next(false)
  }
}

Its nearly the same way you used. Only a few changes.

If there is no need to declare something public, then its private.
I make use of the "Subscription" Object, even if in this example there is just one subscription to be stored. I try to be consisten with solutions. Also it makes it easier to extend the component when a second subscription is needed.
I like to hide code behind methods. That way someone reads the methodname and then can decide if he/she is interested in the details or not.

All in all its more code. But i think its easier to understand. And in my experience, code is read quite more often then writen. And "read" really means "reading and understanding". And thats an very expensive task. :-)
As always, the solution totaly depends on the context. So, choose the things that suit you well and skip the rest. :-)


Rule of Three for non-circular singly linked list

Putting member variables in a protected block is a worry.

 protected:
    node *mFirst;
    size_t mSize;

I would put them into a private block and give limited accesses via members in the protected block that prevents derived classes from breaking the invariant on your members.

Personal preference here:

linked_list():
    mFirst(NULL),
    mSize(0) {}

I like to write it like this:

// Take it or leave it.
// Nobody should complain about your style just looks slightly different.
linked_list()
    : mFirst(NULL)
    , mSize(0)
{}

I would also change mFirst to mRoot. The use of m to mark member variables is an indicator that you are using bad member Vs local names and need a rule to allow people to distinguish between the two. I would prefer you improve the naming convention of your variables so that it si obvious from context the meaning.

Modify the array constructor to use members to do the real work and make the code more readable and thus self documenting.

linked_list(T* others, size_t n) {
    for (int i = 0; i < n; i++) {
        mFirst = new node(*others, mFirst);
        others++;
    }
}

// More Self documenting
linked_list(T* others, size_t n) {
    for (int i = 0; i < n; i++) {
        append(others[n]);         // Note this is inefficient with only
                                   // mFirst (you would need an mLast
                                   // to make it efficient. But alternatively
                                   // you could insert at the beginning and insert
                                   // in reverse order.
    }
}

Copy constructor

linked_list(const linked_list &other)
    : mFirst(NULL),
    , mSize(0)
{
    for(Node* tmp = other.mFirst; tmp; tmp = tmp->next) {
        append(tmp->data);   // Same comment as above.
    }
}

Copy  and Swap Idiom

linked_list& operator=(linked_list const& rhs)
{
     linked_list  copy(rhs);   // use copy constructor to copy.
     swap(copy);               // swap the content of this and copy.
     return *this;
}
// The object copy goes out of scope calling its destructor and
// thus cleaning up the original content of this object.


Generating (presumably) unique `nonce` fields for Twitter OAuth

If I understand the requirements correctly, Guid.NewGuid().ToString("N") would work for generating a nonce.

  A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

The "N" format specifier will return the GUID as 32 (lowercase) hexadecimal digits.


In the object initializer syntax you're using here:

return new StatementLineResult()
{
    ErrorMessages = errorMessage,
    Data = BankLineData(delimitedRecord),
    IsValid = errorMessage.Count==0
};

The parentheses are redundant; object initializer calls the parameterless constructor by default, so you don't need to call it explicitly.

However there's a design smell here; using this syntax tells me your StatementLineResult class looks something like this:

public class StatementLineResult
{
    public Dictionary<string,string> ErrorMessages { get; set; }
    public SomeType Data { get; set; }
    public bool IsValid { get; set; }
}

Notice how everything could be set from the outside, even with invalid state? What if IsValid is set to false when there are items in ErrorMessages? Nonsensical isn't it!

The type is crying to be immutable. Make the properties get-only, and assign their values from the constructor. If the logic for IsValid is "has no error messages", then it's probably redundant. In any case, it should be get-only and return ErrorMessages.Count == 0, not an arbitrary bool value.

Don't expose a Dictionary (or a List, for that matter) like that. Expose an IEnumerable<T> - your client code needs only to iterate the values, and doesn't care about the Key and Value concepts. What's the type of T then?

How about a tiny little class?

public class FieldValidationError
{
    public FieldValidationError(string fieldName, string message)
    {
        _fieldName = fieldName;
        _message = message;
    }

    private readonly string _fieldName;
    public string FieldName { get { return _fieldName; } }

    private readonly string _message;
    public string Message { get { return _message; } }
}

Then instead of exposing a Dictionary<string,string>, you can expose a much more expressive IEnumerable<FieldValidationError>, and not worry about the possibility that client code could tamper with the results.

Random thoughts:

Don't compare strings to null or "" - use string.IsNullOrEmpty instead... which you are using.. just not consistently.
Don't throw System.Exception. Use the most appropriate existing exception type, or make one if none fits the bill appropriately. But don't throw the base exception type; it forces client code to catch (Exception), which makes it catch all kinds of nasties that you would probably rather see bubble up the call stack and crash your app. In this case, throwing an ArgumentException would probably be fine; deriving an InvalidFieldCountException from it could work too.

Spot the issue:

if (!int.TryParse(items[1], out sortCode) || items[1].Length > 6)
    errorMessage.Add("Sort Code", "Invalid sort code");

if (string.IsNullOrEmpty(items[2]) || items[1].Length > 34)
    errorMessage.Add("Account Number", "Invalid account number");

if (string.IsNullOrEmpty(items[3]) || items[1].Length > 35)
    errorMessage.Add("Account Alias", "Invalid account alias");

if (string.IsNullOrEmpty(items[4]) || items[1].Length > 35)
    errorMessage.Add("Account Name", "Invalid account name");

if(string.IsNullOrEmpty(items[5]) || items[5].Length != 3)
    errorMessage.Add("Account Currency", "Invalid account currency");

Looks like a copy-pasta bug. I think the part after the || operator is actually intended to use the same index as the part before.

This is clearly a bug:

if(_transactionTypes.First(item=>item.TransactionType==items[16]) == null)

First does not return null when there's no item: it throws an InvalidOperationException instead. You probably meant to use FirstOrDefault:

if(_transactionTypes.FirstOrDefault(item => item.TransactionType == items[16]) == null)

...but that's sub-optimal, too; if that's meant to say "if there's no _transactionTypes item for items[16]", then it can be expressed more concisely like this:

if(!_transactionTypes.Any(item => item.TransactionType == items[16]))


Running SSH commands on multiple servers

Looks like Fabric is what you need.

Fabric is a pretty simple deploy tool (comparing to Ansible/Puppet/etc), that lets you execute simple shell commands over SSH (Paramiko inside).

Features you will get from it:

You can specify SSH key path using command line:

fab command -i /path/to/key.pem

or parse it from command line:

import sys
from fabric.api import *
...
env.key_filename = sys.argv[2] or '/path/to/keyfile.pem'

Describe local/remote tasks in pythonic way:
    from fabric.api import *

def local_test():
    local('nosetests .')

def remote_pull():
    run('git pull')

And chain/group/do-anything-you want to them.
You can describe host list:

hosts = [<your_hosts_list>]
env.hosts = ['disc{}.{}'.format(host, index) for host in hosts for index in xrange(1,3)]

or you can describe roles:

env.roledefs['group1'] = ['host.name.com']
env.roledefs['group2'] = ['host1.name.com', 'host2.name.com']

and use this roles/hosts in your tasks configuration then:

@roles('group1')
@runs_once
def add_tag(version):
    run('git tag -f {}'.format(version))

And many more features out of the box!


Mapping object values from one object to another

jQuery has extend, which seems to be what you are looking for:

http://api.jquery.com/jquery.extend/

Otherwise, if you don't want to use jQuery at all, you can make a for loop:

var first  = { value: 1, string: "two" };
var second = { value: 2 };

for ( var i in second )
  if ( first.hasOwnProperty( i ) )
    first[i] = second[i];

first.value == 2; // true

As a side, your if statement isn't doing anything because both cases assign the value to configOptions.


Is it possible to remove variable repetition here?

This class looks like a utility class, and you could use static functions: you then wouldn't need to instantiate it:

class StringHelperK {

    public static function normalizeStringK($string) {
        return static::removeAccents(
            static::replaceSpacesWithSlashes($string)
        );
    }

    public static function removeAccents($string){
        return strtr($string,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    }

    public static function replaceSpacesWithSlashes($string) {
        return strtolower(str_replace(" ", "-",$string));
    }
}

To normalize a string, you would then do: StringHelperK::normalizeStringK("blabla").

And no, $string should definitely not be a property, and I see nothing wrong with passing is as an argument to each function.


There is a bug in your Matrix destructor. delete array is not correct. It was allocated using an array form of the new operator, so it must be deleted using an array form of delete(that is, delete[]). The current version of your code invokes undefined behavior. But simply changing it to delete[] array is not enough to fix it. There is still a memory leak here. A correct version of the destructor should look this way:

~Matrix() {
    for (int row = 0; row < n; row++)
        delete[] array[row];
    delete[] array;
}

It is necessary because deleting an array of pointers does not delete the objects pointed by this pointers.
It looks like the size of the array is not correct, either. You allocate an array of pointers of size n, but then you use it as if it had a size m.

array = new int*[n];
for (int i = 0; i < n; i++)
    array[i] = new int[m];
...
for (int i = 0; i < res->m; i++) {
    for (int j = 0; j < res->n; j++) {
        res->array[i][j] = m1->array[i][j] + m2->array[i][j];
    }
}

This code invokes undefined behavior in case n != m.
You should probably implement a copy constructor and a copy-assignment operator. A default copy constrcutor(and assignment operator) just copies the pointer, not the content of the Matrix(I'm not sure if you it is what you want).
A good way to get rid of many bugs in your code is to use standard containers instead of dynamic memory allocation with raw pointers. For example, you can use a std::vector to store the elements of the Matrix:

 class Matrix {
     std::vector<std::vector<int>> array;
     ...
 };

It allows you to avoid manual memory management issues.
Using raw pointers and the new operator is not common in modern C++ in general.
C++ has operator overloading, and it is usually used in C++ programs. For example, matrix addition is a good candidate for overloading the + operator.

class Matrix {
    ...
public:
    Matrix operator+(const Matrix& rhs) const {
        // Check the validity of input parameters.
        Matrix res(n, m);
        // Addition goes here.
        return res;
    }

    ...
};

This example also shows a conventional way to pass arguments without copying them: by const reference(passing a pointer to them is not common in modern C++).
Member-functions that do not change the instance should have a const qualifier.
It is a good practice to write unit tests instead of ad-hoc testing(it is not C++ specific, of course).


Channels vs. "for loop" prime number generator

yes it can be improved.

first, Golang is supposed to be big on concurrency. Your version is not concurrent. It will probably run on just one core.

Channels are supposed to give us concurrency for free. Here, we have a cascade of filtering channels, and while a number makes its way through a later channel, another, bigger number can well enter the earlier channel, concurrently. On multi-core, I'd expect to see high CPU utilization for this code.

The channel version can be drastically improved. Filtering by 7, say, should only be done for numbers from 49 up. There's no need to check 28 by 7—it'll be caught earlier, by a lower prime factor, 2. So the filtering channels should only be started up at primes' squares. This will radically reduce the number of channels working largely for nothing right now. The time complexity should improve from about quadratic to about n1.5, give or take.

I call it the postponement technique. I described it in this SO answer as well as many others. I first thought it up when I worked through the SICP book many years ago and tried re-writing its primes code in Haskell for fun. I thought then it must be widely known... but it turns out, it wasn't.

And of course, there's no need to enumerate any even number above 2. Here's the code:

func Sieve(out chan<- int) {   // 2,000 primes:
  out <- 2                     //  was: 1.32s now: 0.06s
  out <- 3
  q := 9
  ps := make(chan int)
  go Sieve(ps)                 // separate primes supply
  p := <-ps   // p=2, ps@3
  p = <-ps    // p=3, ps@5
  nums := make(chan int)
  go NumsFromBy(5,2,nums)
  for i := 0; ; i++ {
    n := <-nums
    if n < q {
        out <- n   // n is prime
    } else {
        ch1 := make(chan int)
        go Filter(nums, ch1, p)  // p=3
        nums = ch1
        p = <-ps  // 5
        q = p*p   // 25 !
    }
  }
}


Implementing a very simple memory block for quick allocation and memory alignment. C++

Use C++17 aligned new or aligned_malloc()
_aligned_malloc() is a Windows-specific, non-portable function. Luckily, C++17 added the portable aligned_malloc() without an underscore. It also introduces a variant of new that allows aligned allocation. The latter would look like so:
#include <new>
...
MemoryBlock::MemoryBlock(size_t size, size_t alignment):
    p_rawMem((void *)new(std::align_val_t(alignemnt)) char[size]),
    ...
{
}

Unnecessary special case for p_remainingMemSize == 0
Why is this a special case in p_addCurrentMemLocation? Just adding delta to the current pointer is perfectly fine. A pointer that points just beyond the end of an array or an allocated memory region is still a valid pointer.
Consider avoiding the check for delta == 0
An if-statement is not free, especially not if the branch predictor cannot correctly predict the result of the condition. If delta is zero, then the rest of the code still works correctly, and it's just two additions and a subtraction.
Don't use floating point math
You should not need to use floating point math to calculate how much to advance p_currentMemLocationOffset inside getMemoryWith(). Depending on which processor your code is running on, converting to double and back to size_t can be an expensive operation. Furthermore, double has less precision than size_t on 64-bits machines, so the result might be wrong if very large memory blocks are used.
Instead of ceil(p_CurrentMemLocationOffset / (double)alignment), use the fact that integer division rounds down, and compensate for this by adding alignment - 1 first:
p_addCurrentMemLocation((((p_currentMemLocationOffset + alignment - 1) / alignment) * alignment) - p_currentMemLocationOffset);

Alternatively, use the modulo operation to determine how much to add:
p_addCurrentMemLocation((alignment - p_currentMemLocationOffset % alignment) % alignment);

The latter will be especially fast if the compiler can deduce that alignment is always a power of two.
char * vs. void *
It's probably easier to use char * internally for the pointers, since you are doing arithmetic on them. And if you do that, the only time you need to cast is when returning from getMemoryWith().


TL;DR: use {k: v for k, v in zip(names, data)} where names is a list of names for your values, or dict(zip(names, data)) (which I personally find less readable).

There are two sources of complexity in your code (and I mean human-percieved complexity, not computational complexity):

details, which hide the big picture of what's going on;
the fact that the values in data have names, and those names depend on the order of the data list.

The 1st is easy to solve, just split everything into functions, each of which does one thing only, on the appropriate level of abstraction.

The 2nd is more tricky, since even if you define a tuple of names for your values, there's still an implicit relationship left between the order of values in the frame['data'] string, and the order of values in your tuple. Those kinds of implicit relations are not obvious to someone who doesn't know as much as you do about your code (i.e. to everyone else).

Imagine that the structure of the string in frame['data'] changes. Then, your code will be broken, probably in a very unobvious way, and in a totally unrelated place. It's stuff like this that creates spaghetti code.

I don't know where the frame comes from, so it's hard to give a good advice here. In general, you can pack the frame and the tuple of names into another data structure where you create the frame, and never use the frame alone. Or, make the tuple of names a part of frame. In any case, you want to keep them bound together.

Or, you may encapsulate frame's contents in a  class. This class can have a method which returns data in the appropriate dictionary form. The order of the names can be a private variable, encapsulated inside the class.

If I had to stay with frame as it is, I'd do something like this (the names of the functions can be chosen much better, I don't know enough context to come up with good names):

NAMES = (
    'state',
    'flow_rate',
    'operating_hours',
)
def get_cat_data(frame):
    data = _get_data(frame)
    base = _data_to_dict(data, NAMES)
    base.update(_get_xbee_address(frame))
    return base

def _get_data(frame):
    return frame['data'].split(';')

def _data_to_dict(data, names):
     return {k: v for k, v in zip(names, data)}

def _get_xbee_address(frame):
     return {'xbee_address': '\x00' + frame['source_addr']} #consider naming the string literal and using a constant instead

I hope this helps.


I guess the Python interpreter will optimise most or all of this on its own, but you could try a list comprehension and removing an intermediate variable:

new_app = [(title, region, class_dct['Classif_%s'% region].classify(features(title))) for title in df.booktitle]


OOP, FP and IMP condensed in Rock, Paper and Scissors

I'm almost sorry to say, that it feels like you are naming things just because you can name them according to some coding principle.

Calling a named tuple OOP, is stretching it very thin. Yes, it encapsulates something but it doesn't have any options to do actions on the object, and it's not a very good use of it. Could possibly use OOP if you used inheritance for the human player and the computer player incorporating the choice logic.

But then again, that would ruin your so-called FP approach with lambdas and storing of functions. Which again is stretching it rather thin, as you don't use a functional approach avoiding state handling and mathemical functions on lists.

So in the end it is mostly imperative programming, which most paradigms ends up with at some level deep within. And it's imperative programming with a very slight touch of OOP, and a very slight touch of FP.

As this however is Code Review, lets add some review issues as well:

User interface is almost non-existent – You don't provide the user with any information on what to enter, nor do you have error handling of any sort. Only after studying the code intensely I see that you enter either "rock", "paper" or "scissors", which is looked up, incremented, and finally decremented to be displayed back within rock_paper_scissors(). Slightly confusing...
Not the best of variable names – The names RPS, a and b are not according to style guidelines, nor very descriptive.
Neat version to select winner – Simple in code, although undescribed, version to select the winner
Add vertical spacing to rock_paper_scissors() – Instead of everything jammed together, I would love to have a little vertical space to help me distinguish the statements of this function.

To summarize, your script does implement a function to play rock, paper or scissors, but it is, in my opinion, too condensed and should be expanded upon rather than simplified any more.


your code is fine but I would go with some thing like this, i have commented the changes

#include <SFML/Graphics.hpp>
#include <cstdint>

// for eliminating magic numbers
enum class Players
{
    PlayerOne,
    PlayerTow
};

enum class ScreenSize
{
    Width = 800,
    Height = 600
};

// SFML has tiny class for rendering purpose, it has only a one virtual fucntion
class Paddel : public sf::Drawable
{
    // for member data perfered tobe started with m prefix
    float mSpeed; // here is an optional you may use integer value
    sf::Vector2f mBorder;
    sf::Vector2f mPosition;
    sf::Vector2u mScreenSize;
    sf::RectangleShape mShape; // <-- now it's private
public:

    Paddel(sf::Vector2u screenSize, Players player)
        // member data perfered be initilaized as contructor's initilaized list
        : mScreenSize(screenSize)
        , mBorder(8, 6)
        , mSpeed(3.f)
    {
        sf::Vector2f size = sf::Vector2f(20, 100);

        switch (player)
        {
        case Players::PlayerOne:
            mPosition = mBorder;
            break;
        default:
            mPosition.x = (mScreenSize.x - size.x) - mBorder.x;
            mPosition.y = mBorder.y;
        }

        mShape.setSize(size);
        mShape.setPosition(mPosition);
    }

    void moveUp()
    {
        mPosition.y -= mSpeed;
        if (mPosition.y < mBorder.y)
            mPosition.y += mSpeed;
        mShape.setPosition(mPosition);
    }

    void moveDown()
    {
        mPosition.y += mSpeed;
        //100 - (600 + 5)
        if (mPosition.y >(mScreenSize.y - mBorder.y) - mShape.getSize().y)
            mPosition.y -= mSpeed;
        mShape.setPosition(mPosition);
    }

    // sf::Drawable has singe virtual fucntion for rendering, override it
    void draw(sf::RenderTarget& target, sf::RenderStates states) const override
    {
        // sf::RectangleShape has its own defualt RenderStates
        target.draw(mShape, states);
    }
};

int main()
{
    // unfortunately strong type enumeration doesn't decay to integer value, so that we need to static cast it to integer type
    // here we don't want to have a negative value for size, we should use unsigned int or use std::uint32_t which is declared
    // in <cstdint> header file if you considered C++11 features.
    sf::Vector2u screenSize(static_cast<std::uint32_t>(ScreenSize::Width), static_cast<std::uint32_t>(ScreenSize::Height));
    sf::RenderWindow Window(sf::VideoMode(screenSize.x, screenSize.y), "Ping Pong");

    Window.setFramerateLimit(60);
    Window.setVerticalSyncEnabled(true);

    Paddel playerOne(screenSize, Players::PlayerOne);
    Paddel playerTwo(screenSize, Players::PlayerTow);

    const sf::Time TimePerFrame = sf::seconds(1.f / 60.f);
    sf::Clock clock;
    sf::Time timeSinceLastUpdate = sf::Time::Zero;
    sf::Time elapsedTime;

    bool play = true;

    while (Window.isOpen())
    {
        Window.clear();
        sf::Event Event;

        while (Window.pollEvent(Event))
        {
            if (Event.type == sf::Event::Closed)
                Window.close();
        }

        elapsedTime = clock.restart();
        timeSinceLastUpdate += elapsedTime;

        if (play)
        {
            if (timeSinceLastUpdate > TimePerFrame)
            {
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
                {
                    playerOne.moveUp();
                }
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
                {
                    playerOne.moveDown();
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                {
                    playerTwo.moveUp();
                }
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                {
                    playerTwo.moveDown();
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
                    play = false;
            }

            Window.draw(playerOne); // <-- we can draw Paddel object directly
            Window.draw(playerTwo);

            Window.display();
        }
    }
}


Revised: ...I wonder if this could replace those two loops? Here are the results with the test vector offered in your comments:

set.seed(100);  m=rnorm(15); std_d <- sd(m)
Reduce(function(y,xx){ if( abs(tail(y[!is.na(y)], 1) - xx) > std_d ) {c(y,NA)}else{
                                                                        c(y,xx)} },
          m )
 [1] -0.50219235          NA -0.07891709          NA  0.11697127  0.31863009          NA  0.71453271
 [9]          NA          NA          NA          NA          NA  0.73984050          NA

Here's original test case with revised results. It is now comparing the last non-NA value to the current one and making NA if it exceeds the standard value. That other solution looked at the running sd() but your code did not do that so I just used a global sd value:

> z <- read.zoo(text=' "timestamp" "mesured_distance" "IFC_Code" "from_sensor_to_river_bottom"
 "1" "2012-06-03 12:30:07-05" 3188 1005 3500
 "2" "2012-06-03 12:15:16-05" 3189 1005 3500
 "3" "2012-06-03 12:00:08-05" 3185 1005 3500
 "4" "2012-06-03 11:45:11-05" 3191 1005 3500
 "5" "2012-06-03 11:30:15-05" 3188 1005 3500', tz = "")
 std_d <- sd(coredata(z[,1]) )
 zx <- as.numeric(coredata(z[,1]))
 coredata(z[,1]) <- Reduce(function(y,xx){
                              if( abs(tail(y[!is.na(y)], 1) - xx) > std_d ) {
                                        c(y,NA)} else {
                                        c(y,xx)} },
                                  zx )
 z
                    mesured_distance IFC_Code from_sensor_to_river_bottom
2012-06-03 11:30:15             3188     1005                        3500
2012-06-03 11:45:11               NA     1005                        3500
2012-06-03 12:00:08               NA     1005                        3500
2012-06-03 12:15:16             3189     1005                        3500
2012-06-03 12:30:07             3188     1005                        3500


Convert a list of dictionaries to a dictionary of dictionaries

While using methods with side effects in list- or dict-comprehensions is generally frowned upon, in this case you could make use of dict.pop to get the id and at the same time remove it from the dictionary.

>>> a = [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {d.pop("id"): d for d in a}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}

Keep in mind, though, that this will alter the dictionary in-place, i.e. afterwards:

>>> a
[{'bar': 'baz'}, {'bar': 'baz'}]

If you do not want to alter the original dictionaries, use map(dict, a) to create copies before poping elements from those, leaving the original dicts in a as they were.

>>> {d.pop("id"): d for d in map(dict, a)}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}


This

        while ( str[pos] != '\n' ):
            length = "%s%s" % (length, str[pos])
            pos = pos + 1

could be just

        length = string.split(str[pos:], '\n')[0]


I spent a ton of time on this;

The choice to replicate Date but not the other 50+ built-ins is interesting
I would write isObject as const isObject = x => (typeof x === 'object' && x !== null)
A question to ask yourself, what about functions, do you want to clone those as well?
 if (Object.keys(obj).length < 1) { return obj; } is interesting, this means you will allow for modifications in the original object to impact the new object
The poor man's deep clone for non-cyclic structures is JSON.parse(JSON.stringify(o))
After the construction here: newObj[key] = new value.constructor(value); I would still copy over the properties as well
Still mulling over a counter example..


Ad 1. Yes, it's reasonable to refactor it the way you did. It's consistent with Single Responsibility Principle, and as such it makes it easy to eg. add some new formats without having to meddle with the base routine.

Ad 2. It's questionable in some places.

a) No exception handling. You may prefer it to be caller's responsibility, but at the very least you should ensure that the file stream always gets closed, even if an exception is thrown (with a try-finally or using).

b) The names IFile and its derivatives are misleading. It's a IFileProcessor (HtmlFileProcessor etc.). It's obvious that it doesn't represent a file itself, it represents a way of dealing with a file whose contents are passed from outside.

Ad 3. Your new implementation lacks the part that associated appropriate file processing method with a given FileType. This could be implemented with a FileProcessorFactory class taking a FileType instance and returning an IFileProcessor instance. Calling code doesn't need to know whether it's HtmlFileProcessor etc., that's the point: such nuts and bolts are something left for the factory to worry about, and caller is only concerned whether the factory returns something that matches the interface.

EDIT:

Here's a suggested improvement.

public class FileProcessor
{
    public void ProcessFile(string fileName, IFileProcessorBehavior file)
    {
        // using ensures we won't leave the method without closing the fileStream
        // even if an exception is thrown. this prevents resource leaks.
        using (var fileStream = new StreamReader(File.OpenRead(fileName)))
        {
            string fileContent = fileStream.ReadToEnd();
            file.ProcessFooFile(fileContent);
        }
    }
}

// Behavior, or Strategy.
// we need to differentiate file processor the general facade
// from format-specific file processor.
// in any case, this is not a "file", it's a way of dealing with a file.
// if I knew more about the context of this code,
// I could probably come up with a more natural naming scheme
public interface IFileProcessorBehavior
{
    void ProcessFooFile(string fileContent);
}

public class FileBehaviorFactory
{
    public IFileProcessorBehavior Create(FileType fileType)
    {
        switch(fileType)
        {
            case FileType.Html:
                return new HtmlBehavior();
            case FileType.Text:
                return new TextFileBehavior();
            default:
                // don't use the most generic Exception - use a meaningful exception type
                throw new NotSupportedException("Unknown file format: " + fileType);
                // ^ and quote the value that was not recognized -
                // it will help to track the cause of an error
        }
    }
}

public class HtmlBehavior : IFileProcessorBehavior
{
    public void ProcessFooFile(string fileContent)
    {
        // ...
    }
}

public class TextFileBehavior : IFileProcessorBehavior
{
    public void ProcessFooFile(string fileContent)
    {
        // ...
    }
}

And now you would just:

var factory = new FileBehaviorFactory();
IFileProcessorBehavior behavior = factory.Create(fileType);
// at this point we don't know and we don't care of what type this behavior thing is
var processor = new FileProcessor("some file", behavior);

Thanks to this pattern any new formats can be added as separate classes (supporting the interface), so the system is open for extension, and they can be registered within the factory. The base routine (FileProcessor) is closed, which is what we want. The factory only carries one responsibility, which is to match any given file type to respective behavior, or file processing strategy. This means there is only one ever one reason to modify the factory: when this logic needs to be enhanced, or modified.


Coding style

There is a well-established coding style for Python, the PEP8 coding style, and conformance to that style can be checked online at PEP8 online.

In your case it reports “missing space around operator” in almost every
code line. Fixing those issues increases the legibility of your code.

Program structure

It is better to separate the I/O from the actual computation. With a function to compute the number of common divisors you make your code more readable and reusable. In addition you can document each function and add test cases easily.

A check for main allows to run the script directly, or import it as a module.

So the overall program structure should be

def num_common_factors(a, b):
    """ Return the number of common factors of a and b. """
    # ... TODO ...

if __name__ == "__main__":
    a, b = map(int, input().split())
    print(num_common_factors(a, b))

Note also that reading the input line and the mapping to integers can be combined into a single statement.

Simplify (and fix) your code

Your solution is the “brute-force” approach: Test every possible number (in a suitable range) if it is a divisor of both numbers. That can be improved considerably (see below), but let's first discuss how your solution can simplified. First, the limit can be computed using the built-in min() function:

lim = min(a, b)

Then note that a range() excludes the upper bound, so you probably want

for num in range(1, lim + 1):

I would also avoid abbreviations, i.e. limit instead of lim. Finally the code can be written more concisely by summing a generator expression:

def num_common_factors(a, b):
    """ Return the number of common factors of a and b. """
    limit = min(a, b)
    return sum(1 for i in range(1, limit + 1) if a % i == 0 and b % i == 0)

Mathematics helps!

The problem can be solved more efficiently using some maths. Every common divisor of a and b is a divisor of the “greatest common divisor” of a and b, and vice versa. So the task can be split into two separate problems:

Determine the greatest common divisor \$ g = \gcd(a, b) \$. This can be done efficiently using the Euclidian algorithm, but even better, Python has a built-in function math.gcd for that.
Count the number of divisors of \$ g \$.

So our function would be

from math import gcd

def num_common_factors(a, b):
    """ Return the number of common factors of a and b.

    Example 1: 10 and 25 have the 2 common factors 1, 5.
    >>> num_common_factors(10, 25)
    2

    Example 2: 720 and 24 have the 8 common factors 1, 2, 3, 4, 6, 8, 12, 24.
    >>> num_common_factors(720, 24)
    8
    """
    g = gcd(a, b)
    return num_divisors(g)

where I also have added two test cases as examples.

Now we are left with the second task: counting the number of divisors. A simple implementation would be

def num_divisors(n):
    """Return the number of divisors of n."""

    count = 0
    for i in range(1, n+1):
        if n % i == 0:
            count += 1
    return count

which again can be done by summing a generator expression:

def num_divisors(n):
    """Return the number of divisors of n."""

    return sum(1 for i in range(1, n+1) if n % i == 0)

But this can be done far more efficiently using the prime number factorization: If
$$
 n = p_1^{e_1} \, p_2^{e_2} \cdots p_k^{e_k}
$$
is the factorization of \$ n \$ into prime numbers \$ p_i \$
with exponents \$ e_i \$, then
$$
 \sigma_0(n) = (e_1+1)(e_2+1) \cdots (e_k+1)
$$
is the number of divisors of \$ n \$, see for example
Wikipedia: Divisor function. Example:
$$
 720 = 2^4 \cdot 3^2 \cdot 5^1 \Longrightarrow
  \sigma_0(720) = (4+1)(2+1)(1+1) = 30 \, .
$$

Here is a possible implementation (translated from the JavaScript here to Python):

def num_divisors(n):
    """Return the number of divisors of n."""

    count = 1   # Number of divisors
    factor = 2  # Candidate for prime factor of n

    # If n is not a prime number then it must have one factor
    # which is <= sqrt(n), so we try these first:
    while factor * factor <= n:
        if n % factor == 0:
            # factor is a prime factor of n, determine the exponent:
            exponent = 1
            n /= factor
            while n % factor == 0:
                exponent += 1
                n /= factor

            # factor^exponent is one term in the prime factorization of n,
            # this contributes as factor exponent + 1:
            count *= exponent + 1

        # Next possible prime factor:
        factor = 3 if factor == 2 else factor + 2

    # Now n is either 1 or a prime number. In the latter case,
    # it contributes a factor 2:
    if n > 1:
        count *= 2

    return count

Testing

As already mentioned above, test cases can be added to each function, and verified with the doctest module. Running the tests after each modification of the code helps to find programming errors.

We already added two test cases to the num_common_factors() function. Now we'll do this for the num_divisors() divisors function, which is essential to the program, and where a programming error can easily lead to wrong results.

One option is to compute a bunch of values using an alternative program and use the results as test cases. I chose PARI/GP to compute the number of divisors of \$ 1, \ldots, 20 \$, \$ 100, \ldots, 119\$, and \$ 10000, \ldots, 10019 \$:

? vector(20, n, numdiv(n))
%1 = [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6]
? vector(20, n, numdiv(99+n))
%2 = [9, 2, 8, 2, 8, 8, 4, 2, 12, 2, 8, 4, 10, 2, 8, 4, 6, 6, 4, 4]
? vector(20, n, numdiv(9999+n))
%3 = [25, 4, 8, 4, 12, 16, 4, 2, 24, 2, 32, 8, 6, 8, 8, 4, 12, 16, 4, 4]

and added these as test cases to the num_divisors() function:

def num_divisors(n):
    """Return the number of divisors of n.

    >>> [num_divisors(n) for n in range(1, 21)]
    [1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6]

    >>> [num_divisors(n) for n in range(100, 120)]
    [9, 2, 8, 2, 8, 8, 4, 2, 12, 2, 8, 4, 10, 2, 8, 4, 6, 6, 4, 4]

    >>> [num_divisors(n) for n in range(10000, 10020)]
    [25, 4, 8, 4, 12, 16, 4, 2, 24, 2, 32, 8, 6, 8, 8, 4, 12, 16, 4, 4]
    """
    ... remaining function omitted ...

Testing is done by running

python -m doctest -v countcommonfactors.py

on the command line (assuming that “countcommonfactors.py” is the name of your Python script).


Performance Improvement for Subtree for another tree

I was just about to post on your previous version of this question when you pulled it. As you have changed the code my old answer is mute apart from a few points;

The 100% memory efficient is the default value when leetcode has not collect the required minimum stats to provide comparative memory use.

The performance result can vary significantly submitting the very same code. Submit the code several times and you may get a much better score.

The snippet below completed in 62ms and was rated above 99.78% of JavaScript submissions. And got the bogus 100% memory score.

var isNodeEqual = function(a, b) {
    const leftA = a.left !== null, leftB = b.left !== null;
    const rightA = a.right !== null, rightB = b.right !== null;
    if (leftA !== leftB || rightA !== rightB) { return false }
    if ((leftA && a.left.val !== b.left.val) ||
        (rightA && a.right.val !== b.right.val)) { return false }
    return (leftA ? isNodeEqual(a.left, b.left) : true) &&
           (rightA ? isNodeEqual(a.right, b.right) : true);
}
var isSubtree = function(s, t) {
    const stack = [s];
    while (stack.length) {
        const node = stack.pop();
        if (node.val === t.val && isNodeEqual(node, t)) { return true }
        node.left !== null && stack.push(node.left);
        node.right !== null &&  stack.push(node.right);
    }
    return false;
}

Rather than full recursion I used a stack to iterate the main tree, and recursion to test for matching sub tree.

I also avoided truthy and falsey statements as they introduced coercion overhead when testing for null or Object    eg if(node.left) { is slower than if(node.left !== null) {


Finding an element in multiple sorted lists efficiently

I think you have some misguided assumptions here.

For a start, what you have now is not \$O(k \log(n))\$, it first scans and sorts all the data in to the tree, which is a \$O(N \log(N))\$ operation, where \$N\$ is the cumulative data size (sum of input-array sizes). Then, the check on it, is a \$O(\log(N))\$ check, so, your algorithm is in the order of \$O(N\log(N))\$.

The complexity you are worried about \$O(k\log(n))\$ is really quite trivial. \$k\$ is a small number (5), and log(n) is always small... in many ways, after n = 128 it is effectively a constant....

So, I would do the following:

binary search each List
keep the 'min' value

with the code:

Integer result = null;
for (List<Integer> data : lists) {
    int pos = Collections.binarySearch(data, input);
    if (pos >= 0) {
        //exact match, return
        return data.get(pos);
    }
    pos = -pos - 1;
    if (pos < data.size()) {
        Integer found = data.get(pos);
        if (result == null || result.compareTo(found) > 0) {
            result = found;
        }
    }
}
return result;

Now, if you wanted to be fancy, and you wanted the fastest response times, you could put each binary search in to a Callable<Integer>, and run them in parallel....

Then rank the results, and teturn it all in time complexity \$O(\log(n))\$ assuming \$k\$ is less than your hardware CPU count.