Let's start from the very top.
CHOICE_LIST_TASKS = 1
CHOICE_ADD_TASK = 2
CHOICE_REMOVE_TASK = 3
CHOICE_QUIT = 4

It's clear to me that you want to create variables and assign them certain integers so you don't have to use magic numbers anywhere, kudos to you for this. There is a much better way to implement this idea in python
Enumerations : Enum
Enumerations in Python

An enumeration is a set of symbolic names
(members) bound to unique, constant values

creating an Enum
class Choices(Enum):
    list_task = 1
    add_task = 2
    remove_task = 3
    quit = 4

This already looks much clearer than random global variables. You can also iterate through the enumeration and display its values with names .
print(Choices.add_task.name)

add_task

print(Choices.add_task.value)

1

Use more functions
file = None
if not os.path.exists('tasks'):
    file = open('tasks', 'w+')
else:
    file = open('tasks', 'r+')
tasks = []

for line in file.readlines():
    tasks.append(line.strip())

Why can't we move this into a function called read_task_file()?
This way it is extremely clear to me, you, you after a year reading old projects, and anybody else who will ever read this code that those few lines of code will read the task file. Without that, one must read the code thoroughly and understand its purpose.
def read_task_file():
    file = None
    if not os.path.exists('tasks'):
        file = open('tasks', 'w+')
    else:
        file = open('tasks', 'r+')
    tasks = []
    for line in file.readlines():
        tasks.append(line.strip())
    return tasks

now getting the tasks is
tasks = read_task_file()

This exact same applies to the next set of code, which will let the user enter their choice so we can perform it.
Factoring out the part where we read a choice from the user and perform  into a function would look like
def read_task_choice():
    display_menu()
    choice = read_int()
    if choice not in Choices._value2member_map_:
        print("Invalid input! Please enter a correct choice\n")
        read_task_choice()

Note: Choices._value2member_map_ will be all the values in an enumeration.
This already looks much cleaner! We eliminate the need of having it in a loop where it will check all the cases, the function only returns choice when there is a valid input.
As I said, factor out the work into functions and all them when required. I have done the same for the 4 main jobs ( the 4 choices ).

List tasks
def list_tasks(tasks):
    if len(tasks) == 0:
        print("Task list is empty!")
        return None

    for i in range(len(tasks)):
        print(f"{i} {tasks[i]}")

Add new task
def add_new_task(tasks):
    return input("What task would you like to finish ?: ")
    tasks.append(task)

Remove task
def remove_task(tasks):
    if len(tasks) == 0:
        print("Task list is already empty!")
        return None

    list_tasks(tasks)
    task = int(input(("Which task would you like to remove: ?")))

    if task < 0 or task >= len(tasks):
        print("Invalid input! Please select an appropriate task")
        remove_task(tasks)
    tasks.pop(task)

And finally
Update task file
def update_task_file(tasks):
    file = open('tasks', 'w+')
    for x in tasks:
        file.write(x + '\n')

What is the point of having millions of functions when I can put everything like I have already done?
Now when you have to play the game
tasks = read_task_file()

while True:
    choice = read_task_choice()
    if choice == Choices.list_task.value:
        list_tasks(tasks)

    elif choice == Choices.add_task.value:
        add_new_task(tasks)

    elif choice == Choices.remove_task.value:
        remove_task(tasks)

    else:
        break

    update_task_file(tasks)

This is the main advantage of having strongly typed functions.
Clearing the screen and waiting for input
Due to the absence of Graphics, we can see that after a few choices the terminal looks a little strange
We can improve this by simply clearing the screen after each choice, and then wait for the user to press a key
Clearing the terminal
There are a few ways. A popular way is to use os.system("cls") if you're on windows, but calling this is quite expensive and also makes your program more platform dependant.
You can do
print(chr(27) + "[2J")

And this will also work.
Waiting for input
Adding this line input("Press any key to continue...") will wait for the user's response before displaying all the choices again, making the experience better.
Final
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from enum import Enum

class Choices(Enum):
    list_task = 1
    add_task = 2
    remove_task = 3
    quit = 4

def read_int(prompt='> ', errmsg='Invalid number!'):
    num = None
    while num is None:
        try:
            num = int(input(prompt))
        except ValueError:
            print(errmsg)
    return num

def display_menu():
    print('What do you want to do?')
    print('[1] List all tasks')
    print('[2] Add a new task')
    print('[3] Delete task')
    print('[4] Quit')

def read_task_file():
    file = None
    if not os.path.exists('tasks'):
        file = open('tasks', 'w+')
    else:
        file = open('tasks', 'r+')
    tasks = []
    for line in file.readlines():
        tasks.append(line.strip())
    return tasks

def update_task_file(tasks):
    file = open('tasks', 'w+')
    for x in tasks:
        file.write(x + '\n')

def read_task_choice():
    display_menu()
    choice = read_int()
    if choice not in Choices._value2member_map_:
        print("Invalid input! Please enter a correct choice\n")
        read_task_choice()
    return choice

def add_new_task(tasks):
    task = input("What task would you like to do: ")
    tasks.append(task)

def list_tasks(tasks):
    if len(tasks) == 0:
        print("Task list is empty!")
        return None

    for i in range(len(tasks)):
        print(f"{i} {tasks[i]}")

def remove_task(tasks):
    if len(tasks) == 0:
        print("Task list is already empty!")
        return None

    list_tasks(tasks)
    task = int(input(("Which task would you like to remove: ?")))

    if task < 0 or task >= len(tasks):
        print("Invalid input! Please select an appropriate task")
        remove_task(tasks)
    tasks.pop(task)

def clear_screen():
    print(chr(27) + "[2J")

def pause():
    input("Press any key to continue...")

tasks = read_task_file()

while True:
    clear_screen()
    choice = read_task_choice()
    if choice == Choices.list_task.value:
        list_tasks(tasks)

    elif choice == Choices.add_task.value:
        add_new_task(tasks)

    elif choice == Choices.remove_task.value:
        remove_task(tasks)

    else:
        break

    update_task_file(tasks)
    pause()


A couple of small comments:
Don't call your parameter the same thing as its type string: string. This makes the code needlessly difficult to read - don't make the reader waste time wondering whether this string a type or the variable. Use input, source or something else that makes sense.
Don't shadow outer variables/arguments in arrow functions, again this harms readability rawArray.map((string) => fixProxyString(string));. Note that the parenthesis are optional for one parameter too. Consider instead:
function parse(input: string): Proxy[] {
    const rawArray = stringToArray(input);
    const fixedArray = rawArray.map(raw => fixProxyString(raw));
    const proxyArray = fixedArray.map(fixed => stringToProxy(fixed));
    return proxyArray;
}

I think (although not tested) that you can further simplify:
function parse(input: string): Proxy[] {
    return stringToArray(input)
        .map(fixProxyString)
        .map(stringToProxy);
}

You don't need to replace and then split here return string.trim().replace(/[ ,\n]+/g, ",").split(",");. You can just split by the regex directly.


Optimize narrow phase contact detection for phyiscs simulation code

delete[] sum_rad_;
    sum_rad_ = new double[NbPairs];
    delete[] distance_vector_;
    distance_vector_ = new Vector3d[NbPairs];
    delete[] sq_dist_;
    sq_dist_ = new double[NbPairs];

Why all these bare array-pointers that you have to manage yourself?  You'd have much more maintainable code with std::vector or even just std::unique_ptr<T[]>.


Lacking a good reason to do otherwise, I think I'd use a Vernam cipher instead of a Vigenere. The two offer about the same level of security (none, at least against anybody who knows anything about cryptanalysis), but a Vernam cipher is generally easier to implement, and (probably more importantly, at least for your purposes) with a typical key, a single pass produces output that looks much more random (in particular, it frequently produces a lot of relatively unreadable symbols and such. For example:

#include <iostream>
#include <sstream>

int main() {
    std::istringstream input("This is some input for encryption.");
    std::string key("EncryptionKey");

    unsigned pos = 0;
    char ch;
    while (input.get(ch)) {
        std::cout << char(ch ^ key[pos]);
        ++pos;
        if (pos > key.length())
            pos = 0;
    }
}

Obviously, the code is quite short and simple. The result it produces in this case is:

  ◄♠
  ☺Y↓I∟☺& Yi+▲▬♠Y▬←←O♂%♠♂y5→
  ↔↨^

As already noted, there's little difference in terms of real security--but in terms of producing output that looks strange and off-putting, this seems to me to win by a wide margin.

If you were going to mix two different ciphers, I don't think I'd use the same algorithm, just with two different keys. Rather, I'd use two entirely different types of ciphers. Since Vigenere is a substitution cipher, the obvious choice would be to use a transposition cipher for the second one.


My implementation of the repository pattern

The one thing I am not satisfied about is the dispose method. In every repository I have to add a dispose method that calls the base dispose method.

IDisposable
The IDisposable interface should be impelemented in the base class. By using the default pattern of disposing, you will get this result

public class BaseRepository<TEntityType> : IDisposable where TEntityType : class
{
    private readonly DataClassesDataContext _dataContext;

    protected BaseRepository()
    {
        _dataContext = new DataClassesDataContext();
    }

    protected Table<TEntityType> GetTable()
    {
        return _dataContext.GetTable<TEntityType>();
    }

    protected void SaveChanges()
    {
        _dataContext.SubmitChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~BaseRepository()
    {
        Dispose(false);
    }

    protected void Dispose(Boolean disposing)
    {
        // free unmanaged ressources here
        if (disposing)
        {
            // This method is called from Dispose() so it is safe to
            // free managed ressources here
            if (_dataContext != null)
            {
                _dataContext.Dispose();
            }
        }
    }
}

But wait, what if you also need to dispose ressources of the FirstClassRepository object which descends from that object. Then the FirstClassRepositoryobject also needs to implement the IDisposable interface with the pattern below.

public class FirstClassRepository : BaseRepository<FirstTable>, IRepository<FirstTable>, IDisposable
{
    public FirstTable GetById(int id)
    {
        return GetTable().FirstOrDefault(x => x.Test == id);
    }

    public IQueryable<FirstTable> GetAll()
    {
        return GetTable();
    }

    public void Delete(FirstTable item)
    {
        GetTable().DeleteOnSubmit(item);
    }

    public void Add(FirstTable item)
    {
        GetTable().InsertOnSubmit(item);
    }

    public void Dispose()
    {
        try
        {
            Dispose(true); //true: safe to free managed resources
            GC.SuppressFinalize(this);
        }
        finally
        {
            base.Dispose();
        }
    }

    ~FirstClassRepository()
    {
        Dispose(false);
    }

    protected void Dispose(Boolean disposing)
    {
        // free unmanaged ressources here
        if (disposing)
        {
            // This method is called from Dispose() so it is safe to
            // free managed ressources here
        }
    }
}

If the FirstClassRepository obect doesn't need to dispose ressources you can omit the implementation of IDisposable.

EDIT based on comment:

The ~FirstClassRepository() method is what the compiler takes as beeing the Finalize() method of the object. If you forget to call the Dispose() method of that object, this method will be called at the time your object is destructed.
So as the method is implemented by calling the overloaded Dispose(Boolean) method with the parameter == false, only unmanaged ressources will be freed (where the comment is written) as the GC takes care of the managed objects.

Otherwise your implementation looks fine for me.

Some SO links
proper-use-of-the-idisposable-interface
when-should-i-use-gc-suppressfinalize


The last three libraries should be removed as they're not being used.  There's no need to keep a library around if you're long longer using it or have never used even it.

You may also consider organizing them in some way, such as alphabetically.
You don't really need these:

using std::vector;
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::ostream_iterator;
using std::istream_iterator;

Just use std:: where needed, otherwise it'll just get longer if you add more.  Also, you have listed using std::vector twice, but it should just be there once.
print() isn't modifying any data members (it just prints something):

print( std::vector<float> &data )

so data should be passed by const& to avoid an unnecessary copy:

print(std::vector<float> const& data)

There's no need to provide your own swap() function; just use std::swap:

std::swap(lit, rit);

This is not a very common nor maintainable style in my_qsort():

if( lit > rit ) { break; }
else { lit++; }

Put each bracketed statement on its own line, in case you ever need to add to them:

if (lit > rit) {
    break;
}
else {
    lit++;
}

Why is there a "pause" in my_qsort()?

char c;
cin >> c;

Just let the function works without such interruptions.  But if you must keep it anyway, then at least make the user aware that it's a pause, and tell them to input a character in order to continue.
Using parentheses for a simple return is not really needed:

return ( 0 );

Just keep it simple and omit them:

return 0;

Moreover, you don't really need this.  Reaching the end of main() already implies success, so the compiler will insert the return itself.


Is catching null pointer exception to handle it instead of null check beforehand always a bad practice or it depends?

The correct behavior of your code depends on the related code around it.

If that code doesn't expect nullvalues in strings, you should not even check for null. And, to be consistent, you should not return null either but throw an exception instead. Therefore, you should remove the whole catch clause.

On the other hand, if you follow the Apache Commons style of expecting null everywhere and passing it through unmodified, your first code is the way to go. Since null is an expected value, it should not throw exceptions, for performance reasons. The second code is nicer to read, but it will be slower unless the optimizer were really fancy and would transform the second code into the first.


you select the pen in, but don't select out before delete.

SelectObject(memDC, hp353535);
// snip
DeleteObject(hp353535)

should be:

hOldPen = SelectObject(memDC, hp353535);
// snip
SelectObject( memDC, hOldPen );
DeleteObject(hp353535)

SelectObject(memDC, hBMP); should really be hOldBMP = SelectObject(memDC, hBMP);

For some other comments:

I recommend that you split the WM_PAINT (and all other messages) processing into its own function. It'll be easier to read/debug.
Are rMainClntNoBorder (and rTile, rClnt) globals, or declared and initialised before the code supplied?
Only declare one variable per line. It's easier to read and find where it's declared rather than searching. It also avoids an issue with pointers that you may come across.
Use proper names for the brushes if you can - hbDarkOrange (or even hbCurrentActiveTile) means more than hb984921.
Unless you have hundreds of colours, it may be better to create them at the start of the program and delete them at the end, and store their values in a struct in the 'user-area' of the window structure - You may want to avoid creating and deleting them continually.
If you don't do the above, keep the creation and deletion as close together as possible.

hbDarkGrey = CreateSolidBrush(RGB(33, 33, 33));
FillRect(memDC, &rMainClntNoBorder, hbDarkGrey);
DeleteObject( hbDarkGrey );

Similarly, your switch statement could be simplified. Rather than creating three brushes and using one, just pick the one you want.

setTileRect(); // implies that rTile is a global??
switch(tiles)
{
    case 1:
        tile_colour = RGB( 73, 73, 73 );
        break;
    case 2:
        tile_colour = RGB( 152, 73, 33 );
        break;
    case 7: // allow fallthrough
    default: // you need a default!!
        tile_colour = RGB( 0, 0, 0 );
        break;
}
hbTile = CreateSolidBrush( tile_colour );
FillRect( memDC, &rTile, hbTile );
DeleteObject( hbTile );

Instead of 1 and 2 etc in the case statement, create some meaningful constants for them with enum.


Using a singleton class to get and set program wide settings

There should be something about a Singleton class that requires that it allow and present a single, globally available, instance.  Otherwise, the pattern is being misused.

The way your class is built, there's not really such a reason.  You could have any number of instances, and they'd all work (though they'd all look like the same instance anyway).

As for recommendations to make things less weird...?

Use instance variables.

Everything is essentially global.  (Make no mistake; hiding it in a class doesn't do much at all to change that.  static is just how a lot of OO languages spell "global".  :P)  Your "instance" is just an interface to get and set that global stuff.  Every "instance" has the same ability, since it gets and sets the same variables -- and in fact, any update through one "instance" will be reflected in every other.  So new Config and Config::getInstance() really differ only in whether another instance is created.  The caller could say one or the other, and get the exact same results.

If you insist on a singleton, moving the static variables into the instance would legitimize the existence of an instance at all, and provide a less dodgy reason to require exactly one authoritative instance.  (Though it'd also prompt the question, "Why can't i create a separate configuration for testing?".  Among others.)
Lose the public setter, or provide a way to disable it.

There's next to no encapsulation or data hiding going on here; the only thing that even remotely counts is your path stuff.  Any caller can change global settings at will.  This kind of "action at a distance" can cause all kinds of weirdness.  It is the very reason mutable global state is discouraged, and set makes it even easier to abuse.

You should consider either getting rid of the setter, making it private (and thus disabling outside modification altogteher), or adding some way for your setup code to disable it -- effectively "freezing" the instance -- once the configuration is established.
Use self::, not static::.

static (when used in place of a class name) uses PHP's "late static binding" to look up variables through the name of the called class rather than the one where the method lives.  It's there to allow subclasses to override static members.  But you've explicitly disallowed inheritance...so values will only ever be looked up in this class.  static is thus wasteful, and a bit of a mixed message.
As for the autoloader, it's not exactly a mortal sin or anything to put that in the same file as the config class.  Unless the classes are going to be moving around, though, their current location isn't really part of the config settings, is it?

I'd suggest making the autoloader a part of the startup code, unless the class files are going to move around (thus making the current location a part of the configuration).


Project Euler problem 14 (longest Collatz sequence) in Swift 3

The main performance bottleneck of your code was already pointed out in the other answers: building lots of arrays (without need).
I'll like to point out how some Swift techniques can be used to achieve
the goal in a functional (and fast) way.
First, I would separate the computation of the next Collatz number into
a separate function:
func collatzFunc(n: Int64) -> Int64? {
    if n == 1 {
        return nil
    } else if n % 2 == 0 {
        return n/2
    } else {
        return 3*n + 1
    }
}

or, using the conditional operator:
func collatzFunc(n: Int64) -> Int64? {
    return n == 1 ? nil : n % 2 == 0 ? n/2 : 3*n + 1
}

(As already pointed out in other answers, we must operate on Int64
here). For reasons which become apparent shortly, this function returns nil
when called with 1, i.e. when the sequence "ends".
Now, instead of building an array with all elements, we build a
sequence, using sequence(first:next:)
from the Swift Standard Library:

Returns a sequence formed from first and repeated lazy applications of next.
func sequence<T>(first: T, next: @escaping (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>

Our collatzFunc is exactly what is needed as the next parameter.
For example,
let seq = sequence(first: 13, next: collatzFunc)

creates the Collatz sequence starting at 13. But in contrast to your
function, all elements are evaluated lazily, i.e. on demand when
the sequence is enumerated.
for n in seq { print(n) }

would print that Collatz sequence. But we need only the length,
so we define a collatzLength function. A straightforward
implementation would be
func collatzLength(n: Int) -> Int {
    var count = 0
    for _ in sequence(first: Int64(n), next: collatzFunc) {
        count += 1
    }
    return count
}

The for-loop enumerates the sequence and increments a count for
each element. Since the sequence element itself is not needed,
the "wildcard pattern" _ is used as the loop variable.
This can be written more concisely/functionally using
reduce():
func collatzLength(n: Int) -> Int {
    return sequence(first: Int64(n), next: collatzFunc)
        .reduce(0, { (count, _) in count + 1 })
}

Finally, we have to find the number (under one million) which has the
longest Collatz length. This can be done with a for-loop, as you did.
Alternatively, one can consider that as the maximum of all
(n, collatzLength(n)) pairs with respect to the second component:
let (maxN, maxLength) = (1...999_999)
    .map { ($0, collatzLength(n: $0)) }
    .max { $0.1 < $1.1 }!

This code, compiled with Xcode with optimization ("Release" configuration)
runs in about 0.8 seconds on my 1.2 GHz Intel Core m5 MacBook.

EBrown demonstrated
how to use caching/memoization to increase the performance.
Here is a similar but slightly different approach. Instead of
caching all computed values in a dictionary, cache only the
computed values for n up to a maximum value in an array.
With the cache array size equal to the maximal needed n (1 million
in our case), this turned out to be very fast.
let cacheSize = 1_000_000

var cache = [Int](repeating: 0, count: cacheSize)
cache[1] = 1

func collatzLengthCached(n: Int64) -> Int {
    if let smallN = Int(exactly: n), smallN < cacheSize {
        if cache[smallN] > 0 {
            return cache[smallN]
        }
        let len = 1 + collatzLengthCached(n: collatzFunc(n: n)!)
        cache[smallN] = len
        return len
    }
    return 1 + collatzLengthCached(n: collatzFunc(n: n)!)
}

let (maxN, maxLength) = (1...999_999)
    .map { ($0, collatzLengthCached(n: $0)) }
    .max { $0.1 < $1.1 }!

This code, compiled with Xcode with optimization ("Release" configuration)
runs in about 0.08 seconds on my 1.2 GHz Intel Core m5 MacBook.


Arduino based ultrasonic sensor program, output HIGH to control electric motor

As per C++ naming convention, only user-defined types and macros in C++ are capitalized.  Your constants, global variable, and functions should start with a lowercase letter.
Since your constants are similar, you can group them into an enum instead:

enum Pin { Motor=7, Trigger, Echo };

With the first one set to 7, the following ones will be set to 8 and 9 respectively.

This could also help with code maintenance.  If you ever need to add another Pin, you just need to insert it into the enum appropriately, as opposed to creating another constant.
Duration is only used in loop(), so just initialize and use it there.  Having it as a global variable could invite bugs, and is otherwise bad practice.  This applies to global variables in general because they're accessible throughout the entire program, meaning they can be changed anywhere.
You're using "magic numbers" (hard-coded numbers) in places.  You should either make them variables or constants, or provide comments to specify their meaning.
Your indentation is quite inconsistent.  You indent a different number of spaces in different functions, but you should stick to one (most common is four spaces).  You especially should have indentation within functions, otherwise it may appear that the code isn't contained within that function.
This isn't syntactically correct:

if  (dist_avg < 600 && dist_avg > 400);
digitalWrite(MotorPin,HIGH);
else
digitalWrite(MotorPin,LOW);

There shouldn't be a semicolon after the if condition, otherwise the following statements won't work with it.  The second and fourth lines should also be indented.


abstract class CookieBase{

Might be just a coding style nitpick, but in C# the scope-opening brace goes on the next line, like this:

abstract class CookieBase
{

Also (and this is possibly just a personal preference), when an access modifier isn't specified, it's public by default. This may or may not be what's intended - the intent is always clearer when the access modifiers are explicit:

public abstract class CookieBase
{

I like that you're using the Base suffix to denote a base/abstract class - seeing FooBase immediately tells me that the class cannot be instantiated directly.

   protected HttpRequestBase request;
   protected HttpCookie cookie;
   protected string name;

protected members should follow the same casing convention as public members - PascalCase:

protected HttpRequestBase Request;
protected HttpCookie Cookie;
protected string Name;

Now, exposing fields is never a recommended approach. You should expose properties, not fields. Hence:

protected HttpRequestBase Request { get; set; }
protected HttpCookie Cookie { get; set; }
protected string Name { get; set; }

Now this causes a naming clash with some other public members:

   public HttpCookie Cookie { }
   public string Name { get; }

The solution would be to make the properties public, with a protected setter (and remove the clashing public members):

public HttpRequestBase Request { get; protected set; }
public HttpCookie Cookie { get; protected set; }
public string Name { get; protected set; }

Having a method called Get is basically a code smell all by itself. I'd get rid of it, its functionality seems to be already implemented in the Cookie property:

  public HttpCookie Get(){ ... }

The rest of your code is not quite reviewable, I'd suggest you first implement it before your post it for peer review:

   protected string GetValue(string key){ ... }

   public bool IsSet(){ ... }

   protected void SetValue(string key, string value){ ... }
}

Is this a good approach? Not sure. abstract classes define abstractions, but your abstract class has nothing that actually warrants being abstract - you have no virtual or abstract members, not even a protected constructor, which leads me to believe that your derived classes might look like this:

public class SomeCookie : CookieBase
{
}

public class AnotherCookie : CookieBase
{
}

...if that's the case, then the base class is probably a bad design and you're probably better off just calling it Cookie and making it a normal class.

If your goal was to define an abstraction, @Malachi's answer is probably accurate - you'd be better off defining these members in some ICookie interface (which the "normal" Cookie class described above could very well be implementing).


Exit
There should never be a call to exit() in a library. If for example this code was included in a daemon or some other part of an operating system you would be shutting down the system without meaning to. The best you could do here is to require that a setjmp() command is used in the linking program and do a longjump() from the assert function. This allows the calling program to clean up and perform the correct actions in this case. A library will never know what other actions are necessary.

Incorrect Usage of Header Files
Header files should generally not have executable functions in them. Part of the reason is that if multiple files include the header then at link time the linker will complain about multiple definitions of the functions.

You seem to have worked around the multiple definition problem with complex #ifdef statements. It would be much simpler to have both a utl.h and and a utl.c. The utl.c file contains the executable functions and the utl.h file contains the function prototypes. This is a very common practice and could be
considered a standard. This would also remove the requirement for most of the header files included by this header file.

If you are creating a library that may be used by multiple programs you should probably turn utl.c into either an archive library (libmylog.a) or a dynamically linked library (libmylog.so or libmylog.dll based on the operating system).


It's a pretty nice script! (You should open-source it, I would use it.)

Prepared statements

You should use prepared statements in your queries. It's not only easier to write, it's also more efficient. For example:

def get(self, search_query, page_number):
    with self.get_conn() as conn:
        c = conn.cursor()
        query = """SELECT search_results FROM movies
                   WHERE search_query = ?
                   AND page_number = ?
                   AND strftime('%s', 'now') - timestamp < ?; """

        c.execute(query, (search_query, page_number, cache_expiration))
        return c.fetchone()

Notice that you don't need to worry about quoting anymore.

You can do the same thing to your Cache.put method too:

def put(self, search_query, page_number, search_results):
    timestamp = int(time.time())
    with self.get_conn() as conn:
        c = conn.cursor()
        insert = """INSERT OR REPLACE INTO movies
                    (search_query, page_number, timestamp, search_results)
                    VALUES (?, ?, ?, ?); """

        c.execute(insert, (search_query, page_number, timestamp, search_results,))
        conn.commit()

Statements can be simplified

Instead of this:

results = ""
for a in c.execute(query):
    results = a
return results

It would be simpler and cleaner like this:

c.execute(query)
return c.fetchone()

Unless, you really want to iterate over multiple results and return only the last one, as it was in your original code.

Python classes

Modern classes should extend object, for example:

class Cache(object):
    ...

class Movie(object):
    ...

Coding style

You can simplify this:

if result != "":
    ...

like this:

if result:
    ...

And it's good to follow PEP8, the official Python style guide.


Parameter list too long in initialize method

An in-between solution for you might be:

def initialize(site:, name:, **options)
  @site          = site
  @name          = name
  @date_online   = options[:date_online]   || '-'
  @date_offline  = options[:date_offline]  || '-'
  @date_modified = options[:date_modified] || '-'
  @date_tagged   = options[:date_tagged]   || '-'
  @tags          = options[:tags]          || []
end

You would probably want to raise an error if an unexpected key was passed in as part of options.


Note: this post gets extremely side tracked, but the two ideas are pretty closely related, so hopefully my rambling ends up being helpful.

new in a constructor is an anti-pattern. It immediately creates very high coupling, and it murders any form of coding to interface.

Rather than passing what you need to construct the object, you should pass the actual object. This idea (or at least, an idea very closely related to it) is called dependency injection.

This is all a bit abstract, so I'll give an example. Imagine that you have a simple database-backed logger. I'm more familiar with PDO than MySQLi, so I'll use it.

class DbLogger
{
    private $_db;

    const WARNING = 1;
    const ERROR = 2;

    public function __construct()
    {
        $this->_db = new PDO("sqlite:log.sqlite", null, null, array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ));
    }

    public function log($message, $severity)
    {
        $stmt = $this->_db->prepare("INSERT INTO log (message, serverity) VALUES (?, ?)");
        $stmt->execute(array($message, $severity));
    }

}

Seems simple enough, right? And quite easy to use. No matter where you are in code, you can just do $log = new DbLogger(); $log->log('...'); and you're done.

There's a major problem though. What if you want to use a different database? What if you want a users_log.sqlite and a financials_log.sqlite? Well, simple... You could just pass the name of the log to the constructor.

And yes, that would work, but how manageable is it? Do you really want to find all the places that the name is used every time you want to change it?

Consider if instead of creating the PDO instance, the constructor accepted it. This allows an important difference to happen: DbLogger no longer has to care about how to create a PDO object; it only has to care about using it. Now if you want to use two different databases, you just construct two different loggers based on two different PDO objects. "But," you might say, "don't I then have to pass around the details of my log database?"

Nope. Instead of passing around the details, you just pass around the object.

Any object that needs a logger, you just construct it with a logger. Or, if only a certain method needs logging, you only have to pass that method the logger. It's a bit hard to get used to this pattern, but once you've done it a bit, the way the object graph fits together becomes a lot more clear.

Basically, the idea is to never create your own dependencies. That creates extreme coupling and makes providing alternate implementations impossible. To steal an example from a Google code talk, imagine that you have a bit of code that's responsible for charging a credit card. Now, imagine that you want to test that code. So, you go, you add three items, and you go to run the transaction. Oops, you just actually charged yourself. So... how do you fake it? Do you comment out the actual request and just echo out the variables? Sure, that works once, but how do you make sure you don't accidentally break the code later? You need the test to be rerunnable. You need it to be able to go through the normal process, but instead of actually running the credit card, you need it to just pretend. This is a perfect example of why dependency injection is necessary. If you instead pass in a credit card charging object, a real implementation can be used during production, but for tests, you can just use a mock that just verifies what's passed to it.

Anyway, I'm rambling a bit, so here's a real example:

interface Logger
{
    const INFO = 1;
    const WARNING = 2;
    const ERROR = 3;
    public function log($message, $severity);
}

class NullLogger implements Logger
{
    public function log($message, $severity)
    { }
}

class DbLogger implements Logger
{
    private $_db;
    public function __construct(PDO $db)
    {
        $this->_db = $db;
    }

    public function log($message, $severity)
    {
        $this->_db->prepare("...");
        $this->_db->execute(...);
    }

}

class FileLogger implements Logger
{
    private $_fh;

    public function __construct($file)
    {
        if (!is_resource($file) && is_string($file)) {
            $file = fopen($file, 'a');
        }
        if (!is_resource($file)) {
            throw new InvalidArgumentException("A valid file handle or path must be provided: " . $file);
        }
        $this->_fh = $file;
    }

    public function log($message, $severity = self::WARNING)
    {
        fputs($this->_fh, "...");
    }

}

Now, imagine you have some class that needs a logger. It no longer is tied specifically to a specified DbLogger. In fact, it's no longer tied to a DbLogger at all. All the object has to care about is that it has an object on which it can call log. It's not tied to a specific logger. If we need to change the logger, we just pass it a different logger on construction. No magic to it. No need to edit a bunch of files. Just one config.php (or config.ini/config.json/etc) has to be changed. All we need is a very top layer that knows how to kick off the chain of object creation ("a User needs a DBAL which needs a DatabaseConnection which needs a PDO" for example) and this can all be done with fairly little effort (and lots of different approaches/tools exist to do that).

Hopefully this answer has been at least semi-useful. It's super rambling, and it's not exactly what you were asking about, but I'm guessing that dependency injection and coding to interface are not two things that you're familiar with. It's a bit odd in a situation with database connections since they're so low level (relatively). There's not exactly a RDBMS interface that MySQLi and other connection classes extend. This makes the interface thing a pretty unrelated topic. When the question is extended to a higher level concept though, hopefully it makes sense.

Anyway, please let me know if you have any questions as I fear that this explanation is pretty bad.


The code duplication is easily eliminated by passing an additional parameter:

    public int solution(Tree T)
    {
        return Math.Max(
            turn(T.l, 0, false),
            turn(T.r, 0, true)
        );
    }

    private int turn(Tree T, int turns, bool it_was_right) {
        if (T == null) {
            return 0;
        }
        return turns += Math.Max(
            turn(T.l, it_was_right, !it_was_right),
            turn(T.r, !it_was_right, it_was_right)
        );
    }

Now it is obvious that for the recursive calls an additional parameter is redundant. Making a helper function with only two parameters is a good exercise.

Recursion seems to be necessary. I cannot imagine a strictly iterative approach. At the end of the day you must check every path.

A small nitpick. You don't compute angels in the path (that would be quite hard indeed); you compute angles. Sorry, can't resist.


Inorder, Preorder, and Postorder traversal of a binary tree in C++

I can see a few changes that at least might be worth considering.

Minimize Requirements

All else being equal, you typically want to minimize the requirements you place on the type contained in a container like this. For example, where you need to do comparisons, you can use the same operator (typically <) to do all the comparisons. For example, in your Find, we can do just a little rearranging to get this:

template<typename T>
T BTree<T>::Find(T key)
{
    Node<T>* current = this->root;

    while (current!= nullptr)
    {
        if (current->data < key)
            current = current->right;
        else if (key < current->data)
            current = current->left;
        else // Neither is less than the other, so they must be equal
            return current->data;
    }
}

With this, T only needs to define "less than" for our code to work (where it previously required <, > and ==).

Check recursion

Your PrintInOrder looks broken:

template<typename T>
void BTree<T>::PrintInorder(Node<T>* ptr)
{
    PrintPreOrder(ptr->left);
    cout<<ptr->data<<endl;
    PrintPreOrder(ptr->right);
}

This seems to do a pre-order traversal of the left sub-tree, prints the current, then a pre-order traversal of the right sub-tree. For in-order, you want an in-order traversal of the left-subtree, process the current node, then in-order traversal of the right subtree. With only a few nodes (so the tree is never very deep) this probably may not be visible, but it's clearly wrong.

The same applies to your PrintPostOrder.

Simplify where possible

At least to me, your PrintPreOrder seems unnecessarily complex. I'd do something like:

template <class T>
void PrintPreOrder(Node<T> *ptr) {
    if (ptr == nullptr)
        return;

    std::cout << ptr->data << "\n";
    PrintPreOrder(ptr->left);
    PrintPreOrder(ptr->right);
}

With this we only do one check for a null pointer in one place.

Likewise, your Add currently looks like this:

template<typename T>
void BTree<T>:: Add(T val)
{
    if (root==nullptr)
    {
        root = Add(val, nullptr);
    }
    else
    {
        root = Add(val,root);
    }
}

This checks whether root is a null pointer, and if it is it explicitly passes a null pointer. Otherwise, it pass root. If we just pass root, (whether it's a null pointer or not) we get exactly the same effect.

template<typename T>
void BTree<T>:: Add(T val)
{
    Add(val, root);
}

Avoid std::endl

When people use std::endl, they typically just want to write a new-line to a stream. Unfortunately, that's not quite all that std::endl actually does--in addition to writing the new-line, it flushes the stream. Flushing the stream unnecessarily can lead to a dramatic speed loss (e.g., 10x is pretty common).

On the rare occasion that you actually do want to both write a new-line and flush the stream, I think it's better to do that explicitly:

std::cout << "\n" << std::flush;

At least in my experience, actual uses for this are fairly rare though.

Prefer enum's to magic numbers

Your Print currently sorts out the order for the printing like this:

if (o==1)       // ...
else if (o==2) // ...
else if(o==3)  // ...

Rather than 1, 2 and 3, I'd rather use an enumeration:

enum order { PRE_ORDER, IN_ORDER, POST_ORDER };

Then Print would look something like this:

template<typename T>
void BTree<T>::Print(order o)
{
    switch (o) {
        case PRE_ORDER:  PrintPreOrder(root);    break;
        case IN_ORDER:   PrintInOrder(root);     break;
        case POST_ORDER: PrintPostOrder(root);   break;
    }
}

At least to me, this seems considerably clearer and more readable (also note the use of a switch statement to directly express the intent of choosing one of multiple alternatives).

Don't Repeat Yourself

Right now, you have code in both Add and Find to find a node (if any) with a particular value. Oddly, the two use entirely different approaches to this problem. Rather than having two copies of code to find a node based on a key, I'd rather have one piece of code that's used from both:

Node *&find_key(T key) {
    Node *current = root;

    for (Node *current = root; current != nullptr;) {
        if (key < current->data)
            current = current->left;
        else if (current->data < key)
            current = current->right;
        else
           break;
    }
    return current;
}

With this, we can rewrite Find to look something like:

T Find(T key) {
    Node *pos = find_key(key);
    if (pos != nullptr)
        return pos->data;
}

Likewise, Add would look something like this:

void Add(T key) {
    Node *&pos = find_key(key);
    if (pos == nullptr)
        pos = new Node(key);
}

Avoid Undefined Behavior

As currently defined, if you call Find for a key that isn't present in the tree, execution flows off the end of the function without returning a value, leading to undefined behavior. There are various ways to deal with this, such as a Maybe or Optional type that carries both the return value itself and an indication whether a value is actually present. Another possibility (probably not as nice, but at least it does work) is to use an approach about like the find_key shown above, returning a null pointer if a value isn't present.


Moving a cursor with the keyboard in assembly

Eventually you're going to want to handle other key-presses, correct? You might also want to handle other encoding styles, like EBCDIC, correct?

So, I've never done Assembly before, but these are pretty simple things to design for, and I hope the implementation is correct. First, we want to build a (very large) jump table for ASCII. Essentially, a jump table eliminates all of your comparisons down to exactly one comparison. It's pretty easy to set up:

        goto ascii(al) ; Jump to the line of the character code
ascii:  goto nulInput  ; This would be `0` code input
        goto sohInput  ; This would be `1` code input / Start of Heading
        goto stxInput  ; This would be `2` code input / Start of Text
        ; Add End of Text (3), End of Transmission (4), Enquiry (5)
        ; Acknowledgement (6), Bell (7)
        goto bsInput   ; This would be `8` code input / Backspace
        goto htInput   ; This would be `9` code input / Horizontal Tab
        goto lfInput   ; This would be `A` code input / Line Feed
        ; Add Vertical Tab (B), Form Feed (C)
        goto crInput   ; This would be `D` code input / Carriage return
        ; Shift Out (E), Shift In (F), Data Link Escape (10)
        ; Device Control 1 / XON (11), Device Control 2 (12)
        ; Device Control 3 / XOFF (13), Device Control 4 (14)
        ; Negative Acknowledgement (15), Synchronous Idle (16)
        ; End of Transmission Block (17), Cancel (18), End of Medium (19)
        ; Substitute (1A)
        goto escInput   ; This would be `1B` code input / Escape
        ; File Separator (1C), Group Separator (1D), Record Separator (1E)
        ; Unit Separator (1F)
        goto spacInput  ; This would be `20` code input / Space
        goto exclInput  ; This would be `21` code input / Exclamation Point
        ; In Order:
        ; " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
        ; @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
        ; ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~
        goto delInput   ; This would be `7F` code input / Delete

So you should get the point, go through the ASCII spec line-by-line and put a line for each record in the spec, then a label for each of those lines. For the ones you don't wish to implement yet, simply have a restart label or badCode label that ignores the input.

Once that's done we now know how to implement EBCDIC, just build an EBCDIC jump table.

What you might not realize is that having 128 (because eventually you want to support all codes/keys, right?) cmp statements will cause negative performance because al is compared up to 128 times for each key press, that's a lot. So we build a jump table that might be more work to implement initially, but in the end we'll end up with a much easier to maintain setup, and performance will not degrade. When we call jmp ascii(al), it jumps to the ascii label, then to the line identified by al. Easy stuff.

Regarding your indentation and such, from what I've seen usually assembly is spaced fairly far from the left (8-12 spaces) then all labels go at position 0. This helps keep them in plain sight, since assembly doesn't have 'functions' and such, and there's not a real concept of 'nesting' (you can nest labels, but any label can be accessed from any other location/scope so it doesn't always do any good).


SPOJ problem - The last digit of a number to a power (follow up)

It really isn't that hard to bring your code under 700 bytes.  Just replacing base and exponent with a and b, respectively, would do the trick.  Normally, such renaming would hurt readability.  But here, you are just matching the terminology in the question, which arguably improves intelligibility.

You can also trim obvious fat, such as

eliminating the implicit return 0
long instead of long long int
switching to a more efficient brace style

The cases at the end can all be collapsed using a bit of modulo arithmetic.

There is plenty of room within 700 bytes for writing nice code.  You can expand dig into digit.  You can add customary spaces around operators for readability.  You can even write a long explanatory comment.

#include <stdio.h>

/*
The last digit of pow(a, b) cycles with b modulo 4.

0, 0, 0, 0, 0, ...
1, 1, 1, 1, 1, ...
2, 4, 8, 6, 2, ...
3, 9, 7, 1, 3, ...
4, 6, 4, 6, 4, ...
5, 5, 5, 5, 5, ...
6, 6, 6, 6, 6, ...
7, 9, 3, 1, 7, ...
8, 4, 2, 6, 8, ...
9, 1, 9, 1, 9, ...
*/
int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        long a, b;
        scanf("%ld%ld", &a, &b);
        if (b == 0) {
            printf("1\n");
        } else {
            int i;
            int digit[4];
            digit[0] = 1;
            for (i = 1; i <= 4; i++) {
                digit[i % 4] = (a * digit[i - 1]) % 10;
            }
            printf("%d\n", digit[b % 4]);
        }
    }
}

And we haven't even touched truly nefarious tricks like replacing spaces with tabs, which would save another hundred bytes!


You don't need the constructor, as it's empty.

You're taking red as the low bits and blue as the high bits, which is backwards.

You appear to be using System.Drawing and not System.Windows.Media, judging by the overloads. If so, there is an overload that takes an int:

public class UniqueColorGenerator
{
    private int _colorIndex;

    public Color Next()
    {
        return Color.FromArgb(++_colorIndex);
    }
}

You also wouldn't need to use &, as casting to a byte will cut off the upper bits.

return Color.FromArgb(
    (byte)(_colorIndex >> 24),
    (byte)(_colorIndex >> 16),
    (byte)(_colorIndex >> 8),
    (byte)_colorIndex);


Sending email notifications, each to a different set of subscribers

Is there any reason for this to be a concrete class/method?

You only seem to be considering happy path.

What happens in DB connection failure occurs?  Have you considered passing the DB connection/object as a dependency to this class or method such that this class/method is guaranteed it gets a connection in a proper state?

Have you considered using a join to get notification/subscriber information in a single query and not have to query in loops?

Email::getMailer()->send(...)

Do you really need to instantiate mailer here every time? Should mailer be a passed dependency?

Do you not need a unique key for performing your update? Right now it looks like you are updating every record on the table.

Do you really want to be updating unix timestamps into the table as opposed to using appropriate MySQL datetime or timestamp fields?


Google Code Jam: Store Credit Java Solution

Performance is bad. List.contains() runs in linear time, driving it to quadratic. Recommendation: prepare the list of {price, index} pairs, and stable sort it by prices. The solution is then found in a single scan, along the lines of

    while (head < tail) {
        total = head->price + tail->price;
        if (total < credit) {
            ++head;
        else if total > credit) {
            --tail;
        else {
            return {head->index, tail->index};
        }
    }


I can't think of anything faster than:

a <- matrix(diag(-1, n2), nrow = n2, ncol = n1 * n2)

The n2 * n2 values inside diag(-1L, n2) will be recycled n1 times to fill the final matrix of dimensions n2-by-n1*n2.


Change architecture of Ruby app to be more object oriented, readable

Your code is not very clear indeed, as you said the name of the classes don't reflect what they do.

GetUserId sends the message to the user, I can't infer that just by the name of the class.

You know the steps of your program, which is good, but you haven't separated them in your program, so, the first step would be to create each of these steps in an independent way and then create a class that coordinates what has to be called. I think the handle method can do this coordination, it doesn't need to be as clean as you did.

Also, try to create classes that have states and operations, this way it is more object-oriented IMO. In terms of DDD, you are creating Service classes, you can try to create Entity classes.

For example (just a draft):

slack_api = SlackAPI.new

user = ::Slack::User.new(reporter_email, reporter_name, ticket_number, slack_api.user_id)
message = ::Slack::Message.new(user)

slack_api.send_message!(message)

(I've introduced here a class that will handle the communication with the Slack API.)

User:

class Slack::User
  def initialize(email, name, ticket_number, id)
    @id = id
    @email = email
    @name = name
    @ticket_number = ticket_number
  end
end

Message:

class Slack::Message
  def initialize(user_id, name, ticket_number)
    @user_id = user_id
    @name = name
    @ticket_number = ticket_number
  end
end


tic tac toe code in c++ with two players

You can address both of the your problems using "struct".
By making something like this:
struct myBorad
{
    char board[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
    bool bMyBoardStatus[9] = { false };
};
myBorad g_myBoard;

You then need to change each of the fields as "taken" by setting them to "true".
after each player play.
g_myBoard.bMyBoardStatus[0] = true;

Now that you have this in place you can add two ifs:

Check if the status of selected by player place is "taken" aka not false.
Check if all the array aka all nine of them are true and you didn't meet the win condition yet that means its draw.

there are more elegant solutions but this will help you get what you need, and this does not have to be in struct. i prefer this way.


Approximating the square root using an iterative method

Do not rely on a fixed number of iterations. Stop when reaching a desired discrepancy (e.g. fabs(x*x - n) < epsilon)
I do not see any reason for not simplifying the calculations into x = (x + n/x)/2.0.
Assure that the input is positive.


Setting new values in array based on query results

array_filter  removes elements from an array
array_map changes
each element of an array to something else
array_walk steps
through each element of an array (usually to create side effects)
(does not return anything)
array_reduce create something new from
an existing array

Every traditional loop (that does one thing) is one of the above.

<?php
// Inside your object.
$data = array_reduce($grid_fields, add_grid_fields_to_data($cloned, $this), $data);

// Outside your object.
function add_grid_fields_to_data($cloned, $object) : array {
    return (function (array $data, array $grid_field) use ($cloned) {

        $grid_entry = $this->fetchGridEntry($grid_field['field_id'], $data['entry_id']);
        $grid_field_str = 'field_id_' . $grid_field_id;

        $data[$grid_field_str] = array();
        $data[$grid_field_str]['entry_id'] = $cloned;

        $no_grid_entry = sizeOf($grid_entry) == 0;
        $no_grid_entry ?: $data = array_reduce(array_keys($grid_entry), add_grid_entry_values_to_data($grid_entry, $grid_field_str), $data);

        return $data;
    })->bindTo($object);
}

function add_grid_entry_values_to_data(array $grid_entry, $grid_field_str) : Closure {
  return function (array $data, string $gridEntryKey) use ($grid_entry, $grid_field_str) : array {
    $gridEntryValue = $grid_entry[$gridEntryKey];
    $grid_row = 'new_row_' . $gridEntryKey;

    $data[$grid_field_str]['rows'][$grid_row] = array();

    $data = array_reduce(array_keys($gridEntryValue), add_grid_row_to_data($grid_row, $gridEntryValue), $data);
    return $data;
  };
}

function add_grid_row_to_data(string $grid_row, array $gridEntryValue) : Closure {
    return function (array $data, $geK) use ($grid_row, $gridEntryValue) : data {
        $geV = $gridEntryvalue[$geK];

        $row_col_id_exists = strpos($geK, 'col_id_') !== FALSE || strpos($geK, 'row_id') !== FALSE;
        $row_col_id_exists ? $data[$grid_field_str]['rows'][$grid_row][$geK] = $geV : NULL;

        return $data;
    };
}


Reach to the last index starting at index 0

Default Parameters

When can compare the method signatures of the iterative approach and the functional one, we can see, that for the functional one we have to append the 0 on the first call.

If you want to avoid this - and in this case I think it makes sense - you can add a default parameter into the method signature: const reachLastIndexOf = (arr, start = 0)

Long Condition & Pattern Matching

The condition start === next || next >= arr.length is currently in on if-statement. The ||-operator operates short-circuit - that means if the first operation is true, the compiler don't validates the second condition. When we split the disjuncture into to two if-statements, we can keep the same short-circuit behavior and create a more pattern-matching look and feel:

if (start === next) return false
if (next >= arr.length) return false

The advantage is that you have a less logical operator. The less code, the fewer errors and at the same time the readability is increased.
Please note that I have meant this more generally for conditions, even if in this context only a Boolean operator is avoided, the code is still more readable in my view than before.

Readable Method Names

For this algorithm we need to check if:

an index exists (arr[start] === undefined)
an index stays on the same place (start === next)
an index is out of the array bound (next >= arr.length)
an index reached the end (next === arr.length - 1)

We all now what these checks are meaning but it would be much better if we wrap these into their own functions

const reachLastIndexOf = (arr, start = 0) => {
    if (isIndexDefined(arr, start)) return false;

    const next = start + arr[start];

    if (isStayingInTheSamePosition(start, next)) return false
    if (isOverArrayBound(next, arr)) return false
    if (isReachingTheEnd(next, arr)) return true
    return reachLastIndexOf(arr, next)
}

const reachLastIndexOf = (arr, start = 0) => {
  if (isIndexDefined(arr, start)) return false;

  const next = start + arr[start];

  if (isStayingInTheSamePosition(start, next)) return false
  if (isOverArrayBound(next, arr)) return false
  if (isReachingTheEnd(next, arr)) return true
  return reachLastIndexOf(arr, next)
}

const isIndexDefined = (array, index) => array[index] === undefined
const isStayingInTheSamePosition = (start, next) => start === next
const isOverArrayBound = (next, array) => next >= array.length
const isReachingTheEnd = (next, array) => next === array.length - 1

console.log(reachLastIndexOf([2, 0, 1, 0], 0));


Converting unsigned integer value into byte array

Observations

Your code is beautiful (proper naming conventions followed, proper whitespace usage, very readable. I particularly like the type-aliasing, which helps make the whole thing that much more readable than a typedef or #define). I cannot personally think of any more ways to make your code more readable, however, I do have 1 suggestion.

The algorithm you currently follow is standard and ideal (you even have proper masking of higher-order bits); and in my honest opinion any other algorithm would be tantamount to obfuscation; but if you assume that the code will only ever run on a particular architecture, you could probably unroll the loop.

Suggestion

Make your function parameter const. Although C++ is call-by-value, making it explicitly const and mutating a local copy of the variable is never a bad idea, and it does make your function contract that much clearer.
On the performance side, since on any reasonable computer unsigned will have maximally 16 bytes (64 bits of 8 bytes is the case for all common architectures, except for probably some microcontrollers which will have less, even as less as 1 byte) (note that the upcoming RISCV architecture does have a native 16-byte (128-bit) integral data type, but the 64-bit one is the default), you can easily make this function a template, such that the computation of the byte vector can be done at compile time without much overhead and incur no runtime overhead.

You can probably even pre-set the capacity of your std::vector utilising sizeof(unsigned).

Although I'm not sure if this suggestion will work in the constraints of your application.


1-D intersection of lines given begin and end points

Using explicit booleans is a common antipattern:

check = False
if condition:
    check = True
return check

is equivalent to much more transparent (and preferable)

return condition

Segments do not intersect if a lies completely to the left, or completely to the right of b. Assuming that segments are themselves sorted:

def is_intersect_3(a, b):
    return not (a[1] < b[0] or a[0] > b[1])

is_intersect_2 fails badly on floats


Getting all the dates in a month that do not coincide with a project's dates

My attempt to make this code as clean as possible.
Note that i have not changed almost any of the logic you provided.

<?php

class ProjectDays {
    private $projectDays;

    public function __construct(array $projectDays, $month, $year) {
        $this->projectDays = $projectDays;
        $this->month = $month;
        $this->year = $year;
    }

    public function getNonProjectDays() {
        $monthDays = array();
        $projectDays = array();
        $daysInMonth = $this->getDaysInMonth();
        foreach ($this->projectDays as $projectDay) {
            for ($day = 1; $day <= $daysInMonth; $day++) {
                $date = $this->formatDate($day);
                $monthDays[$day] = $date;
                $weekDay = $this->getWeekDay($date);
                if($weekDay == $projectDay){
                    $projectDays[] = $date;
                }
            }
        }
        return array_diff($monthDays, $projectDays);
    }

    private function getWeekDay($date) {
        return date('N', strtotime($date));
    }

    private function getDaysInMonth() {
        return cal_days_in_month(CAL_GREGORIAN, $this->month, $this->year);
    }

    private function formatDate($day) {
        return "{$this->year}-{$this->month}-{$day}";
    }
}

$excludedDays = new ProjectDays([1, 6], date('n'), date('Y'));

print_r($excludedDays->getNonProjectDays());


It's often simpler to have a fixed frame rate in a game. Then you don't have to multiply everything by a time factor. In this case, you do not have to lower the frame rate to the lowest value that all computers can handle. You can for example let the position updates run at 200Hz and update the graphics at the highest speed the computer can handle (which may be lower than 200Hz).

If the updates can easily run at a fixed speed on all hardware you want it to run on, this can work well. It is a good way to get consistent behaviour in physics simulations, and for simple games, updating at a much higher speed than needed for the graphics is not a problem.

On the other hand, if the position updates are complicated, you may not be able to run them at top speed, and you'll have to handle varying time deltas (as in your code). This is often more difficult. The "jumping around in case of lag" problem has a simple (but not perfect) solution: just put a cap on the time delta, so you'll never do calculations on a time delta bigger than say 50 ms.

I guess this part of the question would fit better at gamedev.stackexchange.com, where there probably already are discussions about it.

EDIT: Sure is, have a look at https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step


Algo for generating a fake, but feasable, dataset

You didn't include any specific request, so here are some general comments.

comments / documentation

You say it's been a while since you wrote it.  When you look at the code now, are there places you ask yourself "why did I do that?" or where it takes time to figure out what is going on?  If so, those are good places to add comments.

Also docstrings could be added to the file and the functions.

random_hour(start, end)

The writeup says it returns a random time between start and end.  However, it actually returns a random timedelta between start and end + 59 minutes.  Also, similar python functions tend to include the start and exclude the end (e.g. randrange), so it would be good to document this.

random_weight(total_working_hours)

dicts() are not guaranteed to be ordered until Python 3.7.  So i==0 may not correspond to in_orc.  It would be better to iterate over the keys and check if the key=='in_orc'.

min_hour is calculated but never used.  I think it is supposed to be area.

module level code

It is common to put the top level code in a function such as main().  And the call main() from code such as

if __name__ == '__main__':
    main()

csv module

The standard library includes the csv module for reading a writting csv and other kinfs of delimited text files.  It takes care of escaping characters or enclosing strings in quotes if needed.

unpacking

Instead of using for i in range(0,6) to iterate over the employees, use something like:

for employee_code, employee_name in employees:
    ...

locals()

The python documentation says the dictionary returned by locals() should NOT be modified.  The changes may not be picked up by the interpreter.

That's enough for now.


Scala app to transpose columns into rows

Immediately I'd ask if there's any specific style guide that allows
these vastly different names, otherwise I'd suggest following IDE hints
and/or a linter and rename the variables and methods to be more
consistent (e.g. [cC]amelCase for everything).

Also, "stuff" is not a great name for anything ... what stuff are we
talking about?  In fact the first line of CreateStuff already shows
that there's a better name, tableName for the parameter, probably
createTable for the method.  yrmnth is especially bad too, three
vowels saved from yearMonth and in the process made the name
unreadable for the casual observer.

Seems like the spark session is created twice and the comment even says
so - I'd suggest passing the variable into the method, that's fairly
straightforward by either passing it as a parameter, or extending App
with a member variable.

The SQL queries are created by concatenating strings and there's usually
better ways, here probably a query builder.

columnCount is unused, selectColumns2 has 2 as the suffix, even
though there's no 1, that can just be selectColumns.

The loop for columnStack could be in its own method so it's a little
small section that could be tested on its own too, returning what is now
collist, formatColumnsList(columns: Seq[String]): String perhaps.
Again, if a query builder could do all this it would be a bit cleaner
than concatenating strings.

The construction for yrmnth is pretty convoluted for what it does, I'd
suggest finding a more succinct approach, e.g.

val yearMonth = DateTimeFormatter.ofPattern("yyyyMM").format(LocalDateTime.now())

That would require a recent Java for java.time.LocalDateTime and
java.time.format.DateTimeFormatter.  But even without there should be
better ways.  If everything fails the whole section should at least be
in its own method, e.g. formatDate(calendar Calendar): String.

The bottom part of unPivotDF uses a temporary table - is that the best
way to go, or could the data be inserted directly?


Check if the jQuery library is present locally

Well, you could set this up to use additional methods. You don't have to throw everything into the constructor. This would be a big step in the right direction, at least in as far as OOP and best practice is concerned. This will help you to understand what is going on much easier while also helping you to avoid violating basic OOP principles. For instance:

Single Responsibility

The first principle you are violating, or so it seems, is the Single Responsibility Principle. As the name implies, your classes and methods should be responsible for just one thing, to the exclusion of all others. They can request information from others if necessary, but they should not be aware of how those others work. This principle is typically demonstrated with a function/method, but should also be applied to the classes themselves.

It's hard to tell in this context, because all you provided were the guts, but, judging by the static properties, I would assume you are handling these loading failures for another class. If you are not able to modify the class in question, such as if this were a library, then this functionality should be added to an intermediary, such as a controller, otherwise this really belongs in the JQuery class. Let's continue under the assumption that this is being constructed in said intermediary.

Don't Repeat Yourself

The "Don't Repeat Yourself" (DRY) Principle is another of the principles you are violating. As the name implies, your code should not repeat. Typically this is done through functions/methods, but it can also be done with variables/properties and loops, though it is not just confined to this. Keeping your code DRY takes a lot of foresight, but really helps in the long run. So let's take a look at how your code is repeating itself and try to fix this.

This should be fairly obvious. There are two files that are being verifyed and the same things are being done to both files. To paraphrase someone important to DRY (can't remember who, only that it was similar to the Rule of Three): we can either do something once, or do something many times; There is no such thing as doing something only twice. To follow this pearl of wisdom, we can create a method, and then use that method each time we need it. This also follows the Single Responsibility principle because it abstracts the task away from the constructor, whose only job is to instantiate initial values.

public function verifyVersion( $file, $version ) {
    //generalized verification code
}

As the comment says, this method should be generalized for a single file, which can either have a boolean return value or a boolean property it manipulates to show whether verification was a success. It seems like you already have such a property in $versionLoaded so we can use that. Its not exactly a boolean, but it can be used as one so long as its default value is FALSE or NULL.

if( ! $this->versionLoaded ) {
    throw new Exception(
        "Neither the version $version nor the default version "
        . JQuery::DEFAULT_VERSION
        . " could be found or downloaded"
    );
}

BTW: I slightly edited your exception because the grammar was bothering me. "Nor" is the negative connotation of "or" and "neither" prefixes a list of negatives. Though I'm not an English major, so you can take that with a grain of salt.

How do we generalize our check? And equally important, how do we do it just once? In your code you were checking if these files exist not once, but twice. If we check it once, and assume that if the version is loaded then the file exists, then we wont need to check it a second time.

if( file_exists( $file ) || self::installVersion( $version ) ) {
    $this->versionLoaded = $version;
}

That should leave us with one final task. How to check each file. Well, I mentioned that loops were sometimes used in DRY. Here's a pretty good time to use one.

$header  = __DIR__ . '/versions/jquery-';
$default = JQuery::DEFAULT_VERSION;

$files = array(
    $header . $version . '.js',
    $header . $version . '.min.js',
    $header . $default . '.js',
    $header . $default . '.min.js'
);

foreach( $files AS $file ) {
    $this->verifyVersion( $file, $version );
    if( $this->versionLoaded ) {
        return;
    }
}

throw new Exception(
    "Neither the version $version nor the default version "
    . JQuery::DEFAULT_VERSION
    . " could be found or downloaded"
);

Of course, this is still violating the Single Responsibility Principle. This constructor is still doing too much, but I'll leave that up to you to refactor. If you use everything I posted above it should be pretty simple. I'll give you a couple of hints though:

Those files are not violating DRY. You might be thinking that using $header and '.js' repeatedly is a violation, but that is to ensure that our method is as reusable as possible. The only way they might be is by their similar structure, which I can't see refactoring without confusing the issue. Though you might want to try that for yourself.
I think a pretty good name for this new method might be loadJQuery().

I hope this helps!

Edit

I forgot about the isset( $versionList->$version ); bit, so the above code will need to be refactored for that as well, but I think the solution should be obvious once that last method is implemented. If you need clarification, let me know.


import string, time, math, webbrowser

def timefunc(function, *args):
    start = time.time()
    data = function(*args)
    end = time.time()
    timetaken = end - start

I'd recommend calling this time_taken as its slightly easier to read.

    print "Function: "+function.__name__+"\nTime taken:",timetaken

Print already introduces newlines and combines different pieces. Take advantage of that.

   print "Function: ", function.__name__
   print "Time Taken: ", time_taken

That's easier to follow

    return data

def process_text(filename):

You never use filename in here, but you do use fin which is the same thing. typo?

    t = []

Not a very descriptive name. I suggest coming up with something clearer

    for line in fin:
        for i in line.split():

i usually means index which its not here

            word = i.lower()
            word = word.strip(string.punctuation)
            if word != '':
                t.append(word)
    return t

I'd do this as

 words = fin.read().lower().split()
 words = [word.strip() for word in words]
 words = [word for word in words if word]
 return words

I think its easier to follow and probably more efficient

def create_freq_dict(wordlist):
    d = dict()

d is not a very good name. Usually dicts are created with {} not dict(). No difference, but the first is generally preffered

    for word in wordlist:
        if word not in d.keys():
            d[word] = 1
        else:
            d[word] += 1

Use d = collections.defaultdict(int) or d = collections.Counter(). Both will make it easier to count up like this. See the python documentation for collections. You should actually be able to write this function in one line

    return d

def sort_dict(in_dict):
    t = []
    for key,value in in_dict.items():
        t.append((value, key))

in_dict.items() is a list already, there is no reason to copy the elements into the list. (NOTE: in Python 3.x in_dict.items() is no longer a list). Even if it wasn't a list you could do:

    t = list(in_dict.items())

Which would do the same thing your code does

    t.sort(reverse=True)
    return t

I'd implement this function as

return sorted(in_dict.items())

The sorted function takes anything sufficiently list-like and produces a sorted list from it.

def write_results(sorted_list):

sorted_list isn't a great name. It would be better to give an indication of what's in the list.

    fout = open('wordfreq.txt','w')
    fout.write('Word Frequency List\n\n')
    r = 0
    for i in sorted_list:
        r += 1

Use for r, (key, value) in enumerate(sortedlist): That way you don't need to manage r yourself, and you can refer the value as value rather then the harder to read i[1].

        fillamount = 20 - (len(i[1]) + len(str(r)))

Some of the those parens are unnecessary.

        write_str = str(r)+': '+i[1]+' '+('-' * (fillamount-2))+' '+str(i[0])+'\n'

Multiplication has precedence, you don't need the parens to make that happen. Also, python has a method ljust which does this for you

        write_str = (str(r) + ': ' + i[1]).ljust('-', 20) + str(i[0]) + '\n'

You may also want to consider using string formatting rather then adding strings

 write_str = ('%d: %s' % (r, i[1])).just('-', 20) + '%d\n' % i[0]

I think its easier to follow, although I'd probably split across several lines

        fout.write(write_str)
    fout.close()

## The Brothers Grimm
## This file can be obtained from Project Gutenberg:
## http://www.gutenberg.org/cache/epub/5314/pg5314.txt
fin = open('c:\Python27\My Programs\wx\grimm.txt')

fin presumable stands for file in. Give a name that indicates what's actually in it ike grim_text

wordlist = timefunc(process_text,fin)
freqdict = timefunc(create_freq_dict,wordlist)
sorted_list = timefunc(sort_dict,freqdict)
results = timefunc(write_results,sorted_list)

Very nice

webbrowser.open('wordfreq.txt')

That's a slightly unusual use of a webbrowser

print "END"


Is the way I'm handling deck (card) generation the wisest way to do it?

I would agree that your implementation is quite readable. Indentation and white space are consistent. The variables and operations are named clearly and concisely, with the exception of 'getNextCard' as noted by '200_success'. This allows us to focus much more at the low level nuts and bolts of your code.

    private static Random random = new Random();

Use caution in assigning an instance of the Random class as a static member as concurrent access to its operations can cause contention and consequent poor performance. A pattern I like to follow to ensure random instances are seeded uniquely is to have a package level static random member for seeding instances. This still risks contention, but limits the surface area for it to occur in. For simple gaming purposes the 48-bit seed of Random will suffice, but using java.security.SecureRandom will provide a better source of entropy:

    private static final SecureRandom SEEDER = new SecureRandom();
    private static final int ENTROPY = 256; // 2048-bit is good enough for banking
    private SecureRandom random = new SecureRandom(SEEDER.generateSeed(ENTROPY));

-

    this.shuffle();
    this.shuffle();
    this.shuffle();

If your shuffle method and random source are fair, than one shuffle is actually better than more -- you're skipping over entropy and risk introducing bias. If either is not fair shuffling more will not make them fair.

public void shuffle() {
    List<Card> temp = new ArrayList<Card>();
    while(!cards.isEmpty()) {
        int randInt = random.nextInt(cards.size());
        temp.add(cards.remove(randInt));
    }
    cards = temp;
}

While I would argue with mjolka that your implementation of shuffle is a non-in-place implementation of the Fisher-Yates shuffle, I would prefer to be more concise and use the base library utility method:

public void shuffle() {
    java.util.Collections.shuffle(cards, random);
}

I would join both mjolka and 200_success in recommending to guard your getNextCard implementation and throw an appropriate error as well as exposing an external status check method such as size() or isEmpty(). Also I agree the card should be popped from the end of the list when using an ArrayList as the backing collection.

Finally, you have a very well formed class with clear and concise public members. Be sure to add just enough javadoc comments to allow a the class to be consumed without needing to open the code.


PHP Status class : pattern or anti-pattern

I want to abstract some code...

What is it that you actually want to abstract?
Unless you are going to pass an instance of ContactCanBeContactedCheck class to someone who expects a callable, you shouldn't implement it through __invoke method.
My first though was, why not make it a method of the Contact class?
class Contact
{
  public const NOT_CONTACTABLE_REASON_DECEASED = 1;
  public const NOT_CONTACTABLE_REASON_OPTED_OUT = 2;

  // ...

  public function getNotContactableReason(): ?int
  {
        if ($this->is_deceased) {
            return static::NOT_CONTACTABLE_REASON_DECEASED;
        }

        if ($this->opt_out) {
            return static::NOT_CONTACTABLE_REASON_OPTED_OUT;
        }

        return null;
  }
}

Now it is contained in the class that actualy has the data to tell the reason. Encapsulation is one of the fundamental principles of OOP.
Still, if you need a callable, you can now do just
$callback = fn (Contact $contact): ?int => $contact->getNotContactableReason();

Also your method is trying to do 2 things

tell if the contact is contactable
tell the reason why it is not contactable

My method only tells the reason why it is not contactable, and null if there is no reason, because the contact is contactable. Using this approach you are actually able to tell both those things using just this one method as well. But it is not intent to do two things like in your method. It's just a side effect. And that makes a big difference.
You could add another method that would just tell whether it is contactable regardless of reason, but it is now easy enough to tell from the first method as well, so the second method would be just sugar for $this->getNotContactableReason() === null.
Notice I started the constants at 1, not 0. Zero is falsey, just like null.
And using zero could then easily lead to mistakes if you use weak comparision.
if ($reason) {...}

vs.
if ($reason !== null) {...}

I am wondering though, what you are actually doing with the class and the resulting reason. If the reason ends up in a switch or an if, then the entire method is useless and you should branch your code based directly on the $is_deceased and $opt_out properties.
Those 3 lines of usage are far from enough to tell what you really need. If I had more, I could target my review much better.


Speeding up the generation all bit strings with Hamming distance one

To start with, here is a trivial optimization you can perform: in the most inner loop, you store u, then have k = u - 1, then compare k + 1 to u, which corresponds to comparing k to u - 1. Basically your inner loop performs unneeded work; just set directly u to (i ^ j) - 1 and you will save some work. Here is the most inner loop once changed:

const int u = (i ^ j) - 1;

// https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
int k = u;
k |= k >> 1;
k |= k >> 2;
k |= k >> 4;
k |= k >> 8;
k |= k >> 16;

if (k == u)
{
    edges.emplace_back(j);
    edges.emplace_back(i);
}

It timed it on my computer and it was consistently a bit faster, which means that the compiler wasn't able to make this simple transformation.

On the other hand, we can notice an interesting pattern with your original code: k + 1 can only be equal to u when u is a power of \$2\$. Checking whether a number is a power of \$2\$ or (or \$0\$, but the formula you use already has a special case of \$0\$) is easily done: a power of \$2\$ has exactly one bit set, so you only have to check whether removing a set bit from an integer returns \$0\$ to check whether an integer is \$0\$ or a power of \$2\$. This comparison is so cheap that you can perform it first and perform your current check only when it is true:

const int u = (i ^ j);

if (not (u & (u - 1))) // check whether u is 0 or a power of 2
{
    int k = u - 1;
    k |= k >> 1;
    k |= k >> 2;
    k |= k >> 4;
    k |= k >> 8;
    k |= k >> 16;

    if (k + 1 == u)
    {
        edges.emplace_back(j);
        edges.emplace_back(i);
    }
}

Now, correct me if I'm wrong, but if u is a power of two, you don't actually need to check anything else after (you don't need to round up to a power of \$2\$ since you know it's already one). You can simply remove all the k stuff. I mean, it was a wild guess, but the result were exactly the same on my computer. You can just check that u is a power of \$2\$ then emplace_back your values directly.


Converting PHP defined constant values to multiple languages

In all honesty, that seems a bit redundant... But since you can't change the constant values here it goes:

define('ACTION_ACCOUNT_NEW', 1024);
define('ACTION_ACCOUNT_DELETE', 1025);

function ActionToString($action)
{
    $actions_map = array();
    $defined_constants = get_defined_constants(true); // use true to get "user" key

    if (isset($defined_constants['user']))
    {
        $defined_constants = $defined_constants['user'];

        // only process constants that start with "ACTION_"
        $defined_constants = array_intersect_key($defined_constants, array_flip(preg_grep('~^ACTION_~i', array_keys($defined_constants))));

        foreach ($defined_constants as $key => $value)
        {
            $actions_map[$value] = Language::_($key);
        }

        return isset($actions_map[$action]) ? $actions_map[$action] : Language::_('Unknown');
    }

    return Language::_('Unknown');
}

It assumes you only want to parse constants that start with ACTION_, other than that it should work just fine (although, a bit slower due to the looping - still, you could probably fix it with static variables).

One other alternative would be to use class constants but I'm not sure if that option is available to you.


Recursive Fibonacci with Generic delegates

I like to say T1 T2 instead of TArg1, it just makes it more clear to me what is going on. Your code would look more like this.

delegate Func<T1, T2, T3, T4> Recursive<T1, T2, T3, T4>( Recursive<T1, T2, T3, T4> r);

private static Func<T, T, T, T> AnonRecursiveFiboFunc<T>(Func<Func<T, T, T, T>, Func<T, T, T, T>> function)
{
    Recursive<T, T, T, T> recursive = rec => (step, fibo1, fibo2) => function(rec(rec))(step, fibo1, fibo2);
    return recursive(recursive);
}

Other than that... this code seems pretty solid, except for the crazy lack of immediate readability :D and like mentioned in the comments the fact that you are using delegates at all here.


The title of your post is

  Compare ZIP codes, disregarding leading zeros

The solution is simple -- just drop the leading zeros.  Then you can compare the strings directly.

This leads us to something like this:

def compareZip(first: String, second: String): Boolean = {
  first.dropWhile(c => c == '0') == second.dropWhile(c => c =='0')
}

If you want, you can factor out the common lambdas.

There's no need to do anything more complicated than that.  "Fixing" the zipcode only makes things more complicated.  And, since the result never leaves the comparison function anyway, all that work is wasted.


Copying from sheet to sheet if column headings match

Okay. So, let's start with this gigantic array of arrays you've got there. I don't mean to be rude, but what exactly are you doing here?! Each and every one of the inner arrays simply duplicates itself. For the life of me I can't figure out why you have it duplicated. This would work just as well by adding each of these strings to a collection. I would create a single function that intializes and returns this collection.

Private Function GetHeaders() As Collection
    Dim result As New Collection
    With result
        .Add "Account_ID"
        .Add "Claim_ID"
        .Add "Account_Name"
        ' ...
    End With

    Set GetHeaders = result
End Function

And call it at the beginning of Standardization like this.

Dim headers As Collection
Set headers = GetHeaders

Which turns your loop into this.

Dim header As Variant
For Each header In myHeaders
    Set r = wsImport.Cells.Find(header, , , xlWhole)

    If Not r Is Nothing Then
        Set c = wsMain.Cells.Find(header, , , xlWhole)

        If Not c Is Nothing Then
            wsImport.Range(r.Offset(1), wsImport.Cells(Rows.Count, r.Column).End(xlUp)).Copy _
            wsMain.Cells(Rows.Count, c.Column).End(xlUp)(2)
        Else
            msg = msg & vbLf & header & " " & wsMain.Name
        End If
    Else
        msg = msg & vbLf & header & " " & wsImport.Name
    End If

Next

Note that I added a level of indentation inside of the loop, and replaced the cryptic e variable with the more sensible and descriptive header variable.

Now the duplication becomes so obvious that it's painful, so let's extract a couple more functions.

Private Function FindHeaderRange(ByVal ws As Worksheet, ByVal header As String) As Range
    Set FindHeaderRange = ws.Cells.Find(header, , , xlWhole)
End Function

and

Private Function BuildMessage(ByVal currentMessage As String, ByVal ws As Worksheet, ByVal header As String) As String
    BuildMessage = currentMessage & vbLf & header & Space(1) & ws.Name
End Function

Note that I replaced the literal space with a call to Space(1). This is just for readability. It's much easier to parse the function call than a " ".

Also, you never defined msg in your original code. Turn Option Explicit on so this doesn't happen in the future. It helps turn runtime errors into compile time errors. It's kind of magical. You should always be using it.

Anyway, I took the liberty of renaming some more cryptic variables, and now it looks like this.

Dim header As Variant
Dim source As Range
Dim dest As Range
For Each header In headers
    Set source = FindHeaderRange(wsImport, header)

    If Not source Is Nothing Then
        Set dest = FindHeaderRange(wsMain, header)

        If Not dest Is Nothing Then
            wsImport.Range(source.Offset(1), wsImport.Cells(Rows.Count, source.Column).End(xlUp)).Copy _
                wsMain.Cells(Rows.Count, dest.Column).End(xlUp)(2)
        Else
            msg = BuildMessage(msg, wsMain, header)
        End If
    Else
        msg = BuildMessage(msg, wsImport, header)
    End If

Next

Which is better, but I'd prefer to take a happy path whenever possible. It's easier to reason about positive statements than double negatives.

For Each header In headers

    Set source = FindHeaderRange(wsImport, header)
    If source Is Nothing Then
        msg = BuildMessage(msg, wsImport, header)
    Else

        Set dest = FindHeaderRange(wsMain, header)
        If dest Is Nothing Then
            msg = BuildMessage(msg, wsMain, header)
        Else
            wsImport.Range(source.Offset(1), wsImport.Cells(Rows.Count, source.Column).End(xlUp)).Copy _
                wsMain.Cells(Rows.Count, dest.Column).End(xlUp)(2)
        End If
    End If
Next

You don't ever use the variable x. Get rid of it entirely.
You turn screen updating off three times without ever turning it back on. Once is enough.
Speaking of screen updating, anytime you turn it off, you need an error handler to ensure it always gets turned back on no matter what happens while the code is executing.
Don't activate and select. Use object references/variables instead.

wsMain.Columns("A:AO").Select
Selection.EntireColumn.AutoFit
Selection.ClearFormats

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)

Should be

   Dim cols As Range
   Set cols = wsMain.Columns("A:AO")
   cols.EntireColumn.AutoFit
   cols.ClearFormats

   Dim tbl As ListObject
   Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, cols, , xlYes)
   tbl.TableStyle = "TableStyleMedium9"

Always be explicit about scope. Procedures defined as just plain Sub are public. It's better to write that down instead of relying on a developer's knowledge (or lack there of).

Here's the resulting code. I apologize that I never got around to performance. There were a number of issues to work through first. If I get time, I'll take a look at the performance later.

Public Sub Standardization()
On Error GoTo ExitSub

    Dim headers As Collection
    Set headers = GetHeaders

    Dim msg As String

    Dim wsImport As Worksheet, wsMain As Worksheet

    Set wsImport = ThisWorkbook.Sheets(2)
    Set wsMain = ThisWorkbook.Sheets(3)

    Application.ScreenUpdating = False

    Dim header As Variant
    Dim source As Range
    Dim dest As Range
    For Each header In headers

        Set source = FindHeaderRange(wsImport, header)
        If source Is Nothing Then
            msg = BuildMessage(msg, wsImport, header)
        Else

            Set dest = FindHeaderRange(wsMain, header)
            If dest Is Nothing Then
                msg = BuildMessage(msg, wsMain, header)
            Else
                wsImport.Range(source.Offset(1), wsImport.Cells(Rows.Count, source.Column).End(xlUp)).Copy _
                    wsMain.Cells(Rows.Count, dest.Column).End(xlUp)(2)
            End If
        End If
    Next

    Dim cols As Range
    Set cols = wsMain.Columns("A:AO")
    cols.EntireColumn.AutoFit
    cols.ClearFormats

    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, cols, , xlYes)
    tbl.TableStyle = "TableStyleMedium9"

ExitSub:
    Application.ScreenUpdating = True

End Sub


Some of your declared variables aren't used in your posted code - ws3, foundMatches, sDate.  Maybe they are used in code that you haven't included.  Even if you think your code may be too long to post in full, it would be helpful for us to be able to see everything between Sub and End Sub.

Your With ws2 End With is ineffective in so far as you continue to use ws2 explicitly in your code.  For example, lastRowWs2 = ws2.UsedRange.Rows.Count should be lastRowWs2 = .UsedRange.Rows.Count.

I'm not sure why you are looping through a single element array strSearch.  In fact, you could do away with strSearch and check by simply testing If ws1.Cells(i, searchColumnWs1).Value = "john" Then.

Looping through cells is inefficient.  So is copying entire rows.  I'm assuming that you actually want to paste into column C of lastRowWs2 + 1 which is why you insert new columns A:B.

While I haven't time tested filtering column J = "john" and copying/pasting the resulting list into .Cells(lasrRowWs2 + 1, 3) I'm confident that it would be much faster.

Avoid declaring variables as Variant because they have an overhead in terms of size and time taken for VBA to work out what sub-type they are.

.UsedRange.Rows.Count can return unexpected results if the last cell on the sheet is not where you think it is.  I've seen cases where Excel thinks the UsedRange extends down to row 1048576.


Review

There are a few things that can be improved upon here,

  def letterNumberSwap(x):

is reinventing the wheel of str.index()
and str[index]

  randomStart = str(letterNumberSwap(randint(1,8)))+str(randint(1,8))

random.choice() might be better choice :)

  It's just implementation details. randint delegates to randrange, so it has another layer of function call overhead, and randrange goes through a lot of argument checking and other crud. In contrast, choice is a really simple one-liner. source

moveList = [] # list of moves in matrix connotation
possibleMoves = [] # list of moves in chess connotation

Stick to the scope.

Do not make these globals,.. either return or yield them from the function

if (0 < (c - 2) <= 8):
    if (0 < (r - 1) <= 8):
        moveList.append([c - 2, r - 1])
    if (0 < (r + 1) <= 8):
        moveList.append([c - 2, r + 1])

Stick to DRY, you can avoid the repetition by saving all possible directions in a list
Don't do string + string but use .format() or use the fancy f"{string}" if you use python 3.6+
in range(x) is alot faster in python3 instead of x <= !! and x >= !! @Graipher
Naming

In chess a row is called a rank, and a collumn is called a file
Avoid magic numbers

Make the WIDTH and HEIGHT constant so that they can easily be changed

Alternative

from string import ascii_uppercase
from random import choice

BOARD_HEIGHT = 5
BOARD_WIDTH = 13
CHESS_FILES = ascii_uppercase[:BOARD_WIDTH]
CHESS_RANKS = range(1, BOARD_HEIGHT+1)

def knight_moves(file, rank):
    position = (CHESS_FILES.index(file), rank)
    directions = ((1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1))

    for direction in directions:
        file, rank = (d + p for d, p in zip(direction, position))
        if  file in range(BOARD_WIDTH) and rank in CHESS_RANKS:
            yield f"{CHESS_FILES[file]}{rank}"

if __name__ == '__main__':
    file = choice(CHESS_FILES)
    rank = choice(CHESS_RANKS)

    print(f"With BOARD({BOARD_WIDTH}, {BOARD_HEIGHT})")
    print(f"A knight on {file}{rank} can go to:")
    print(", ".join(knight_moves(file, rank)))


As per my comments, I've not sure SE.CodeReview is the right place to get the help you are looking for.

However, as I didn't read your question properly at first, I had a look at your code and changed a few things (please note that it's not exactly the same behavior as it used to be):

extract the display logic in a method on its own
reuse update in start and finish (little changes here : this method now updates the object instead of just doing some display)
removed self._seen because it didn't seem useful

Here the code :

class Progress(object):
    def __init__(self, maxval):
        self._pct = 0
        self.maxval = maxval

    def update(self, value):
        pct = int((value / self.maxval) * 100.0)
        if self._pct != pct:
            self._pct = pct
            self.display()

    def start(self):
        self.update(0)

    def finish(self):
        self.update(self.maxval)

    def display(self):
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*self._pct, self._pct) + '\n')
        sys.stdout.flush()


Checking if two strings are anagrams in Python

You can change your if to just be return.
You should change your while to an if, as it makes no sense for it to be while.
You shouldn't return a string on invalid input, instead you could raise a ValueError.

This can get:

def is_anagram(string1, string2):
    if len(string1) == len(string2):
        return sorted(string1) == sorted(string2)
    raise ValueError('The strings are not anagrams they have differing lengths')

However I wouldn't raise, and so you can just use:

def is_anagram(string1, string2):
    return sorted(string1) == sorted(string2)

To answer your questions:

The \$O\$ complexity for your function is not \$O(1)\$. Lets take the different aspects of your function:

len(n) is \$O(1)\$
int == int is \$O(1)\$
sorted(n) is \$n\log{n}\$
str == str is \$O(n)\$
len(a) == len(b) is \$O(1)\$
sorted(a) == sorted(b) is \$O(\min(a, b) + a\log{a} + b\log{b})\$

Since the function will short circuit if len(a) == len(b) we know that \$a = b = n\$.
And so the complexity becomes \$O(n + n\log{n})\$. This may be ok to simplify to \$O(n\log{n})\$, as \$O(n + n\log{n}) = O(n(1 + \log{n}))\$

You can however use collections.Counter to reduce your sorted complexity to \$O(n)\$. And so keeping the short circuiting your function would be \$O(n)\$, otherwise it would be \$O(a + b)\$. And so to use this you can use:

from collections import Counter

def is_anagram(string1, string2):
    return Counter(string1) == Counter(string2)

I would prefer you use the builtin functions, as it should lead to less code to maintain.