Add or subtract two numbers depending on dropdown selection

Be sure when you ever have a code that it has the chain of if else there should be an improvement. (even many programmers say you should not use if statement in your code as possible and some others say don't use else statement at all!)

You can use something like this:

First Add a class to manage your actions:

 public class ActionRegistry: Dictionary<string, Func<int, int, int>>
    {
        public ActionRegistry()
        {
            this.Add("Add", (x, y) => x + y);
            this.Add("Subtract", (x, y) => x - y);
        }

    }

Then you can use that class like this:

public class DoStuff
{
    private int Calculate(string sAction)
    {
        var actionRegistry= new ActionRegistry();
        var a = 1;
        var b = 2;
        //var actionResult= actionRegistry[this should come from your drop down].Invoke(a, b);
        var actionResult= actionRegistry[sAction].Invoke(a, b);

        //you can even Register New Action Like this :
        actionRegistry.Add("Multiply",(x,y)=>x*y);

        //then you can use it somewhere else:
        var multiplyResult =  actionRegistry["Multiply"].Invoke(a, b);
        return actionResult;
    }
}

Every time your action has changed you just need to add the new action in your ActionRegistry. With this approach, there is no need for that if-else statement.

By the way, you can even use interface and DI to loosely couple the ActionManager.

UPDATE Here my update using enums:

First Declare an Enum :

enum ActionType
{
 Add,
 Subtract
}

Then use that enum in your ActionRegistry class:

public class ActionRegistry: Dictionary<int, Func<int, int, int>>
{
    public ActionRegistry()
    {
       //it's better to register your actions outside the class
       // and don't use enum inside your class
       // but for simplicity i did that inside the class

       this.Add((int)ActionType.Add, (x, y) => x + y);
       this.Add((int)ActionType.Subtract, (x, y) => x - y);
    }

}

then you should change your calculate method like this :

 private int Calculate(int actionTypeCode)
        {
        var actionRegistry= new ActionRegistry();
        var a = 1;
        var b = 2;
        //var actionResult= actionRegistry[this should come from your drop down].Invoke(a, b);
        var actionResult= actionRegistry[actionTypeCode].Invoke(a, b);

        return actionResult;
    }

Note that you should bind your dropdown list with your enum keys as value.
I prefer to use an integer as my key because I can add more item later without changing my enum but it is not necessary.


Computing sums in some CSV files horizontally and in other CSV files vertically

Where we improve the existing code
First of, let's start by talking a bit about some issues in your code. We'll see if we can factorize some bits latter.
The first thing to note is that you iterate twice over your field_names to construct its final form and initialize self._totals. There is no need for it:
field_names = reader.next()
for i, code in enumerate(field_names):
    code = code.strip(string.punctuation).upper()
    field_names[i] = code
    if (len(code) <= size) and (code not in bad_codes):
        self._totals[code] = 0

Next, we see that you differentiate the behaviours of your sums whether self._totals[code] has been initalized or not. One way to simplify it is to turn it into a collections.defaultdict. To be more precise, you will have to define self._totals = defaultdict(int) instead of self._totals = dict(). This will allow you to write, in compute_totals_v:
for row in reader:
    # get totals
    code = row[code_field].strip(string.punctuation).upper()
    self._totals[code] += string_utils.to_int(row[est_field])

This will also allow you to write, in compute_totals_h:
for row in reader:
    # get totals
    for code, val in zip(field_names, row):
        if (len(code) <= size) and (code not in bad_codes):
            self._totals[code] += string_utils.to_int(val)

eliminating the need to initialize self._totals fields. Also, using zip here is more idiomatic. And since you are using Python 2 (I guess reader.next() would have been next(reader) in Python 3) you can use itertools.izip to avoid building a new list in memory.
We can see here that we're moving the test that initialized self._totals[code] into the “get totals” loop. But it is not efficient since we are re-doing it for each row of data. Time to improve that filtering by getting something closer to the if code in self._totals we had. The easiest way is to turn invalid codes into None and check if code is not None instead:
def compute_totals_h(self, size, bad_codes):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        # initialize reader
        reader = csv.reader(f)
        field_names = [c if (len(c) <= size) and (c not in bad_code)
                       else None
                       for c in (
                           code.strip(string.punctuation).upper()
                           for code in reader.next())]

        for row in reader:
            # get totals
            for code, val in zip(field_names, row):
                if code is not None:
                    self._totals[code] += string_utils.to_int(val)

    self._write_totals()

We now have something closer to compute_totals_v and can start to work on factorizing.
Where we get to do what you ask for
The general layout you extracted for your compute_totals method is quite close to what compute_totals_v and compute_totals_h has become. You should note, however, that compute_totals_h needs to return both reader and field_names for its initialization. So we need to return a dummy value (let's say None) in the initialization function for compute_totals_v as well. And thus, we need to accept a second parameter (the dummy value or field_names) in get_totals for both methods.
We also need to define the helper functions as inner functions of the method so we can capture the parameters of the method once and for all without having to pass them around.
# Somewhere, where you define self._totals:
# self._totals = defaultdict(int)

def compute_totals_h(self, size, bad_codes):
    def _init_reader(file_handler):
        reader = csv.reader(file_handler)
        field_names = [c if (len(c) <= size) and (c not in bad_code)
                       else None
                       for c in (
                           code.strip(string.punctuation).upper()
                           for code in reader.next())]
        return reader, field_names

    def _get_totals(row, field_names):
        for code, val in zip(field_names, row):
            if code is not None:
                self._totals[code] += string_utils.to_int(val)

    self.compute_totals(_init_reader, _get_totals)

def compute_totals_v(self, code_field, est_field):
    def _get_totals(row, *args):
        code = row[code_field].strip(string.punctuation).upper()
        self._totals[code] += string_utils.to_int(row[est_field])

    self.compute_totals(lambda f: (csv.DictReader(f), None), _get_totals)

def compute_totals(self, initialize_reader, get_totals):
    with open(self._in_file_path, self._FILE_READ_MODE) as f:
        reader, field_names = initialize_reader(f)

        for row in reader:
            get_totals(row, field_names)

    self._write_totals()

I'm not convinced, however, of the improvement of this change. Readability seems worse to me. And calling the get_totals function for each row has its slight overhead.


The naming of the class is OK, I think.  It could be better named AdjacentSameCharacterPairsRemover. "Same" is shorter than "duplicate". "Pairs" corrects a misunderstanding that I initially had, which was that "aaa" → "" instead of "aaa" → "a".  The name still wouldn't convey the idea that the elimination is applied repeatedly, but there's only so much information that you can fit into a name.

I don't think that the function name needs to be that long, if the class name is already descriptive.  The parameter name, candidate, is peculiar.  What office is that string running for, or what validation are you performing on it?

I don't recommend marking parameters and local variables as final — it just adds visual clutter.  Functions should be short enough that you can easily keep track of all the variables in your head simultaneously.

You don't need the special case for if (candidate.length() < 2); the algorithm works just fine without it.  The added complexity isn't worth the potential performance benefit.

I would work directly with the char[] and dispense with the Stack and StringBuilder.  By doing so, you would eliminate the need for extra storage, the boxing of chars as Characters, the synchronized behaviour of java.util.Stack, and the semi-deprecated status of java.util.Stack.  You also would't need to push all of the original characters onto the stack and then filter it, since the character array is the input.  You wouldn't need to translate the Stack back to a StringBuilder to make the String.  The code would be simplified so much that you could eliminate the helper function altogether.

public class AdjacentSameCharacterPairsRemover {
    // Suppress the default constructor
    private AdjacentSameCharacterPairsRemover() {}

    public static String process(String s) {
        char[] chars = s.toCharArray();
        int len = 0;      // Length of result (initially empty)

        for (int i = 0; i < chars.length; i++) {
            if (len == 0 || chars[i] != chars[len - 1]) {
                chars[len++] = chars[i];   // Push one char onto "stack"
            } else {
                len--;                     // Pop one char from "stack"
            }
        }
        return new String(chars, 0, len);
    }
}


Finding alternating sequence in a list of numbers

Basically, you approach solves the problem adequately, and I have nothing to say about the existing code in terms of style.

However, I think the general approach might be too costly, in terms of time and space requirements (even though I admit that there is no spec).
But since we should treat it as an interview question, then a potential interviewer could ask you
how to approach the problem more efficiently: for example, how could you process the array in one pass only?

So here is a possible answer.

Algorithm's complexity

As you said, your current implementation requires:

linear storage requirement
quadratic execution time

I have an alternative approach, using constant memory and linear time, which is based on an incremental algorithm: for each element of the array, you can determine the longuest zig-zag subsequence that can be built so-far.

I prototyped the solution using Common Lisp, so here is my version (this could be translated easily as a simple for loop in Java, but this is left as an exercise ;-))

(defun max-zig-zag (sequence)
  (loop
     for last = nil then current
     for current in sequence
     for sign   = 0 then (signum (- current last))
     for match  = t then (or (eql await 0) (eql await sign))
     for await  = 0 then (if match (- sign) await)
     count match))

This approach makes all your test examples pass:

(loop for (expected sequence) in
     '((6 (1 7 4 9 2 5))
       (7 (1 17 5 10 13 15 10 5 16 8))
       (1 (44))
       (2 (1 2 3 4 5 6 7 8 9))
       (8 (70 55 13 2 99 2 80 80 80 80 100 19 7 5 5 5 1000 32 32))
       (36 (374 40 854 203 203 156 362 279 812 955 600 947 978 46 100 953 670 862 568 188 67 669 810 704 52 861 49 640 370 908 477 245 413 109 659 401 483 308 609 120 249 22 176 279 23 22 617 462 459 244)))
     always (eql expected (max-zig-zag sequence)))

=> T

I acknowledge that this might not be easy to follow through, so I'll try to write a step-by-step explanation.

Main idea

The difficulty in your question is that you allow some elements to be deleted (or, ignored). We are looking for sequences with maximum length, however.
The elements that can be ignored are those that do not alternate from previous ones: when you encounter a 2, and then the number 4, you can discard all the following elements that are greater than, or equal to, 4, without reducing the potential length of the subsequence: all numbers above 3 are just intermediate values.

The suggested approach is a greedy count of all the alternations of slopes in the array (*).
It is built around a fixed number of variables that are updated at each element, during a unique iteration of the array; in fact, the input array could be an infinite stream of inputs, whereas the count value could be an infinite stream of integers that is updated for each input (and growing when needed).

Derivative

So, the main idea is to look at the shape, or the derivative of your numbers: you take the current value, and the last value, when iterating over the array, and you compute the difference: that gives you the slope.

However, what is interesting is only the sign of this slope: the sign variable always contains the sign of the difference between current and last element, so that a 1 means that current value is higher, and -1 mean that is is lower than the last one.

Matching zig-zags

Initially, you await for any of those sign, either -1 or 1 (which is encoded by zero in the await variable).
This first time that sign differs from zero you have a match: you encountered a positive or negative variation of value; so, the new value of await is now the opposite of the current sign: if we saw a positive slope, like 1, we must read until there is a negative one.

The match variable is initially true, and is otherwise true only when the sign variable equals the await variable (or, if await is zero, during the initialization phase).

When match is false, we skip entries and let await keep its previous value.
When true, await takes the opposite of current sign, which means that we await for a change in the slope.

Then, match is true whenever we go up after having gone down, and respectively down after having gone up, discarding all continuous sequences of decreasing (or increasing) elements.

Finally, we count the number of matches to have the longuest subsequence.

(*) It is based on a data-flow approach (see Lustre, Signal, ...). In fact, the Common Lisp code above could probably easily be rewritten using the SERIES package.


How do I avoid over-using the garbage collector?

For the Garbage Collector, it doesn't matter at all. You don't create the object. You just use an object reference to it in the above code.

The String object itself is still stored in the Person class and is therefore not garbage-collected until it is changed inside the Person object, or the Person object itself is garbage collected (which will happen when the Person does not have any more references to it).

Normally, you don't need to worry about "over-using" the Garbage Collector.

However, for the sake of readability it is a good practice to declare the variable in the smallest scope as possible. Therefore, I would go with the inside the for-loop approach.


Replace every letter in the string with the letter following it in the alphabet and capitalize vowels

isVowel()

The first thing to say about isVowel() is that it should return bool, not int. And the logic should really be flipped so that it returns true or 1 if it's a vowel... not false or 0.

You are correct that there is a more elegant way to do a check like isVowel(). What you'd probably want to do is make an array of all the vowels, like this:

static constexpr auto vowels = std::array{ 'a', 'e', 'i', 'o', 'u' };

If you're not using C++17, you need to specify the type and size of the array:

static constexpr auto vowels = std::array<char, 5>{ 'a', 'e', 'i', 'o', 'u' };

Don't forget to #include <array>.

Then to find if a character is a vowel, you'd search for it in the array:

std::find(vowels.begin(), vowels.end(), element);

If the element is not in the array, std::find() will return the end iterator. So all you need to do is check for that. Putting it all together:

bool isVowel(char element) noexcept
{
    static constexpr auto vowels = std::array{ 'a', 'e', 'i', 'o', 'u' };

    return std::find(vowels.begin(), vowels.end(), element) != vowels.end();
}

Note that you can also make the function noexcept. And as of C++20, you can even make it constexpr, because std::find() is constexpr in C++20.

LetterChanges()

If your goal is efficiency, then it must be pointed out that you're doing a lot of unnecessary shuffling around of your data. You get a std::string argument, then you copy it all into a std::vector, then you copy it all again into another std::string.

There's no need for all those acrobatics. Rather than creating a vector, you can simply make cstr a std::string, and return that when you're done. Even better, rather than taking str as a std::string const&, just take it as a std::string and use that. You don't need to copy the data, not even once!

But let's go through the function line-by-line first.

std::vector<char>cstr(str.c_str(),str.c_str()+str.size());

You don't need to go through all that hassle to copy a string's characters into a vector. You can just do:

std::vector<char> cstr{str.begin(), str.end()};

In the loop:

if((element >= 'A' && element < 'Z')||(element >='a' && element <   'z'))

This is a bit of an advanced technical point, but... you are assuming that the letters A-Z and a-z have contiguous code points. (In other words, you are assuming that if you take 'A' and add 25, you'll get 'Z'.) That's true in the most common character sets these days (ASCII and Unicode), but it's not always true.

The correct thing to do would be to have a function that works similarly to isVowel(), with an array. Something like this:

char transformLetter(char c) noexcept
{
    static constexpr auto uppercase = std::array{ 'A', 'B', 'C', /* rest of the letters */ };
    static constexpr auto lowercase = std::array{ 'a', 'b', 'c', /* rest of the letters */ };

    auto const p_uppercase = std::find(uppercase.begin(), uppercase.end(), c);
    if (p_uppercase != uppercase.end())
    {
        // c is an uppercase letter... but is it Z?
        if (++p_uppercase == uppercase.end())
            return 'Z';
        return *p_uppercase;
    }

    // c wasn't uppercase, so check lowercase.
    auto const p_lowercase = std::find(lowercase.begin(), lowercase.end(), c);
    if (p_lowercase != lowercase.end())
    {
        // c is an lowercase letter... but is it z?
        if (++p_lowercase == lowercase.end())
            return 'z';

        // Not z, but is it a vowel?
        if (isVowel(*p_lowercase))
        {
            // Since we already have upper and lowercase arrays,
            // let's just use them to do toupper cheaply.
            return uppercase[std::distance(lowercase.begin(), p_lowercase)];
        }

        return *p_lowercase;
    }

    // Not a letter at all, so just return it unchanged.
    return c;
}

This could be simplified quite a bit, of course.

Anyway, if you don't care about exotic character encodings, and will only be using Unicode or ASCII, what you have is fine.

So if the function is simplified to remove the unnecessary copies, it should look something like:

std::string LetterChanges(std::string str)
{
    for (auto& element : str)
    {
        if ((element >= 'A' && element < 'Z') || (element >='a' && element <   'z'))
        {
            element = element+1;

            if (isVowel(element))
            {
                element = std::toupper(element);
            }
        }
    }

    return str;
}

Since you're not doing any copying or allocation at all, you can even make this function noexcept.

Summary

Use proper and consistent spacing and indentation. It makes code much easier to read and understand, and helps highlight errors.

Use bool for true/false, not int. And don't invert logic. This is not shell scripting; 0 is false, 1 is true.
Don't copy unnecessarily. Whenever someone complains that C++ is slow, at least 70% of the time it's because they're doing a lot of unnecessary copying. If you have a value that you want to modify, why copy it when you can modify it in place?


There should be some function definitions. is_power_of_2, powers_of_2_below and a main.
It's good practice to use an if __name__ == '__main__' guard.
Please stop putting lots of spaces at the end of lines.
Many of the imports are not used.
Always indent with 4 spaces.

import time

def is_power_of_2(X):
    binary = "{0:b}".format(int(X))
    return binary.count(str(1)) == 1

def powers_of_2_below(X):
    binary = "{0:b}".format(int(X))
    l = len(binary)
    count = 0
    result = [];
    for j in range(0, l):
        count = count + 1
        # create list of factors called result
        result.append(int(binary[0:l-count], 2))
        if len(result) == l-1:
            # I don't want to forget X itself is a factor
            result.append(X)
            break
    return result

def main(X):
    print('Find the factors of a power of 2')
    print('This input number must be a power of 2')
    if is_power_of_2(X):
        print('yes, this is a power of two')
    else:
        print('no, this is not a power of 2')
        quit()
    start = (round(time.time() * 1000000))
    result = factors_of_power_of_2(X)
    end = (round(time.time() * 1000000))
    print(result)
    print('Factoring took', end - start, 'microseconds')

if __name__ == '__main__':
    main(X)

You can now use return rather than quit to exit main.
The code in is_power_of_2 is fine. There are a couple other ways you can implement it but they're all pretty underwhelming.
By replacing count with (j + 1) we can remove the need for that variable.
By using j rather than (j + 1) we can remove the need for the if in the for.
To get l in powers_of_2_below we can use X.bit_length().
We can instead use 1 << j to build the value from j alone. This however will invert the output.

import time

def is_power_of_2(x):
    binary = "{0:b}".format(int(x))
    return binary.count(str(1)) == 1

def powers_of_2_below(x):
    result = []
    for j in range(0, x.bit_length()):
        result.append(1 << j)
    return result

def main(x):
    print('Find the factors of a power of 2')
    print('This input number must be a power of 2')
    if is_power_of_2(x):
        print('yes, this is a power of two')
    else:
        print('no, this is not a power of 2')
        return
    start = (round(time.time() * 1000000))
    result = factors_of_power_of_2(x)
    end = (round(time.time() * 1000000))
    print(result)
    print('Factoring took', end - start, 'microseconds')

if __name__ == '__main__':
    main(32)

We can use a list comprehension instead of a for loop in powers_of_2_below.

def powers_of_2_below(x):
    return [1 << j for j in range(x.bit_length())]

Alternate solutions to is_power_of_2:

We can use powers_of_2_below with & and any.

def is_power_of_2(x):
    x = abs(x)
    if x == 0:
        return False
    return not any(x & i for i in powers_of_2_below(x - 1))

We can replace the any with just x & x - 1. This is because \$1000 - 1 = 0111\$. Logically this is doing exactly the same as 13.

def is_power_of_2(x):
    x = abs(x)
    if x == 0:
        return False
    return not x & x - 1

We can instead use x.bit_length() to construct the power of 2 it should be and check they are the same.

def is_power_of_2(x):
    if x == 0:
        return False
    return abs(x) == 1 << x.bit_length() - 1

Overall is_power_of_2 just doesn't look nice.


Program to check if heap order is correct or not

Avoid flag variables if you don't need them

The hasOrder flag variable is unnecessary.
When you set this variable to false,
you could return false instead.
If the end of the loop is reached, you can return true.

Avoid unnecessary special handling

The special treatment for the case list.size() < 2 is unnecessary.
The rest of the implementation handles that case naturally.

Don't repeat yourself

The computation logic of the left and right child indexes is duplicated twice.
You could eliminate that by changing the loop to while (true), and making this computation the first step of the loop instead of last:

while (true) {
  int leftChild = 2 * parent + 1;
  int rightChild = 2 * parent + 2;

  if (leftChild >= list.size()) {
    break;
  }

  // ...

Test using a unit test framework

Testing by printing stuff is not very useful.
You have to read the output to verify it's correct,
which takes mental effort, and error-prone.
It's better to use a proper unit testing framework,
where test cases will give you simple yes-no answers per test case;
no need to re-interpret passing results.

Test all corner cases

Only one case is "tested".
You need more tests to verify that hasHeapOrder correctly returns true or false depending on the input.
I suppose you have an implementation of Heap such that heap.copy() returns a correctly heap-ordered list, and so hasHeapOrder returns true.
At the minimum,
you should verify that hasHeapOrder returns false for lists like 4, 1, 2 and 4, 5, 2.


Lock-free multiple producer single consumer message queue

As far as thread safety goes, your code is fine. But there's a couple of things I want to point out:

The meaning of your variables (previousQueue, newQueue and currentQueue) isn't very clear, at least not to me. And when writing multi-threaded code, readability becomes extremely important.

Also, for CAS-loops, I always find a "while(true) - break" loop a lot easier on the eyes, but that's my personal opinion.

Here's my suggestion for improving readability:

while(true)
{
    var expectedOldQueue = queue;
    var newQueue = expectedOldQueue + message;
    var actualOldQueue = Interlocked.CompareExchange(ref queue, newQueue, expectedOldQueue);

    if(expectedOldQueue == actualOldQueue)
        break;
}

Also, I'm a bit concerned about the design you chose to achieve a multiple producer/single consumer queue, or maybe I'm just not understanding something...

If I understood correctly, producers will enqueue actions, instead of items that need to be consumed, and producers will simply call Process to trigger those actions, correct?

So, instead of this:

//producer
queue.EnqueueItem(item);

//consumer
var item = queue.Dequeue();
Console.WriteLine(item);

You're proposing this:

//producer
queue.Enqueue(() => Console.WriteLine(item));

//consumer
queue.Process();

If so, this worries me because it goes against the main vein of a consumer/producer architecture, where the consumers are detached from the producers, and have no idea how items will be consumed.

With your proposal, producers will be in charge of producing work items and define how they are going to be consumed.


Format an integer with thousands separator (recursive implementation)

ArtemyVysotsky has provided you with a improved solution, so I am just going to give some general advice:

Do not use using namespace std; since it not only lowers readability of your code (things that belong to the standard library are no longer easily discernible) but also opens the door for subtle name resolution bugs.
n is of type long long, but mod is only of type int. Since mod grows until n % mod == n, you are running into the risk of overflow here, so mod should also be of type long long. However, since mod should never be negative, it would be even better to have it be a unsigned long long/
Keep your spacing consistent. For example, why do you sometimes leave space around == and other times don't? There is no right coding style that everyone agrees on, so you are free do choose any option that fits you, but you should at the very least stick to the style you choose throughout your code (also, keep in mind that most programmers consider more space better than less space, so leaving a space around operators is generally better received than not doing so).
Consider wrapping your recursive function in a helper function. Anyone who doesn't know about your code would assume that all three parameters your function takes can and should be passed by the caller when the last two arguments aren't actually supposed to take anything but their default value.
Don't treat single characters as strings when treating them as chars would work fine. In particular, prefer std::cout << ... << ','; over std::cout << ... << "," since this is (likely to be) faster and more efficient.
Having a function output do std::cout directly severely harms its uses. For example, what if I want to send the formatted number to a file? Currently, your function doesn't help much with that. There are several possible improvements here, for example building and returning a std::string or taking an std::ostream as a parameter and output to that instead.
You don't actually need return 0; in main, the compiler is nice enough to add that automatically (Beware, however, as this only happens in main!).


Print which CPU flags are set at the start of the program

You have a bit of code duplication that could and should be removed to avoid mistakes. FASM supports macros that you can use to remove duplicated parts.

One can define a check_flag macro:

macro check_flag op1, op2
{
   local flag_not_set
   test eax, op1
   jz flag_not_set
   push eax
   push op2
   call [printf]
   pop eax
   pop eax
flag_not_set:
}

A bit of explanation. This macro will do all the work that is required to check if a specific flag is set (specified as operand op1) and if so print the message specified by operand op2. We need to specify also our label as local so that there is no label duplication when macro is placed in code multiple times. We also keep the flags to be restored after printing.

Having this we can simplify the code a bit to basically this:

    check_flag 1h, carry_flag
    check_flag 4h, parity_flag
    check_flag 10h, aux_flag
    check_flag 40h, zero_flag
    check_flag 80h, sign_flag
    check_flag 400h, dir_flag
    check_flag 800h, OF_flag

Which such approach it is easy to add new ones, just by writing:

    check_flag 200h, interrupt_flag

You could also add a new line to those strings so that, they are a bit separated from each other when printing like this:

  aux_flag db 'Aux flag set', 13, 10, 0

The whole program:

format PE console
entry start

include 'win32a.inc'

section '.text' code executable

macro check_flag op1, op2
{
   local flag_not_set
   test eax, op1
   jz flag_not_set
   push eax
   push op2
   call [printf]
   pop eax
   pop eax
flag_not_set:
}

start:  pushf
    push hello
    call [printf]
    pop ecx
    pop eax

    check_flag 1h, carry_flag
    check_flag 4h, parity_flag
    check_flag 10h, aux_flag
    check_flag 40h, zero_flag
    check_flag 80h, sign_flag
    check_flag 400h, dir_flag
    check_flag 800h, OF_flag

    push p
    call [system]
    pop ecx

    push 0
    call [ExitProcess]

section '.rdata' data readable
    hello db 'The flags are: %X', 10, 0
    p db 'pause>nul'
    carry_flag db 'Carry flag set', 13,10,0
    parity_flag db 'Parity flag set',13,10, 0
    zero_flag db 'Zero flag set',13,10, 0
    sign_flag db 'Sign flag set',13,10, 0
    dir_flag db 'Direction flag set',13,10, 0
    OF_flag db 'Overflow flag set',13,10, 0
    aux_flag db 'Aux flag set',13,10, 0

section '.idata' data readable import
    library kernel32, 'kernel32.dll', \
            msvcrt,   'msvcrt.dll'
    import kernel32, ExitProcess, 'ExitProcess'
    import msvcrt, printf, 'printf', \
    system, 'system'


Warning: I am far from an expert with Sass!

I'll list a few things I think could use some re-factoring.

We can DRY out your code. In the main function, I see $each-column + $each-gutter three times. Create a variable and assign the variable the sum.

This line: if ($function == 'offset' and $first-child == false) and ($responsive == false) can all be in one pair of parentheses. Breaking it apart actually reduces clarity.

I find that this line:

if ($function == 'push' or $function == 'pull') and ($responsive == false) or ($function == 'offset' and $first-child == true)

is difficult to read. Note my changes in the code below.

A couple instances, things seem mistaken. For example, this line:

if ($function == 'offset' or 'push' or 'pull')

doesn't seem to be correct. I tried to copy this conditional, and I'm surprised you haven't noticed the error.

This statement says: If $function is equal to 'offset', or either 'push' is non-null or 'pull' is non-null. I believe it should be:

if ($function == 'offset' or $function == 'push' or $function == 'pull') and ($responsive == true) {

I've written your code to take into account all of these modifications. I think it looks neater, however it's not meant to be completely superficial. Since my Sass isn't very strong I hope someone else will be able to help break down your code with you more thoroughly.

@function calculate-function($function, $size, $first-child: false, $responsive: false) {
    $each-column: calculate-one-column() * $size;
    $each-gutter: calculate-each-gutter() * ($size - 1);

    $sum-width: $each-column + $each-gutter;

    $push-or-pull: ($function == 'push' or $function == 'pull');
    $offsetting: $function == 'offset';

    @if ($function == 'size') {
        @return $sum-width;

    } @else if ($offsetting and $first-child == false and $responsive == false) {
        @return $sum-width + ($gutter-width-percent * 1.5);

    } @else if $push-or-pull and ($responsive == false) or ($offsetting and $first-child) {
        @return $sum-width + $gutter-width-percent;

    } @else if ($offsetting or $push-or-pull) and $responsive {
        @return auto !important;
    }
}

Also, you misspelled percent as procent. I suggest you change that in all occurrences.


Testing the performance of a loop for a vector of unique_ptr

Most of your loops are executing in no time at all because the optimizer is eliminating them since they have no side effects.  You need to do something observable with them, like summing all elements and returning that sum from the function.  Declare a new variable int sum = 0 before the loops, replace the int num = lines with sum +=, then return sum; at the end of the function.  This will require changing the return type for all of them to int, and changing the type of pointer passed to TestLoop.

std::vector::max_size returns a theoretical maximum, not one determined on your current system specs.  In your case, it returns 0x3FFFFFFF, which is the maximum number of 32 bit pointers that can be stored in a 32 bit address program.  This max size also doesn't consider any additional storage space required by objects stored within the vector.  Every element you have is a unique_ptr, which when allocated will take 4 bytes for the int, plus additional overhead for the memory management system (so at least 12 or more likely 16 bytes).

Your program crashes with more then 70 million elements because it runs out of memory.


False optimization (and makes it hard to read).

template <typename T>
constexpr unsigned num_bits(T = 0) {
  return sizeof(T) << 3;
}

This should be sizeof(T) * 8 that's so much easier to read. And if it quicker to shift that is what the compiler will actually do. Don't try and outsmart the compiler the only thing that will is happen is that you will outsmart yourself.

Also its not actually 8. TO be compliant and accurate use CHAR_BIT.

This is a bit inefficient.

template <typename T>
unsigned num_bits_set(T x) {
  unsigned cnt = 0;
  // behavior of signed type underflow is unspecified
  std::make_unsigned_t<T> v = x;
  while (v) {
    ++cnt;
    v &= v - 1;
  }
  return cnt;
}

You are using a runtime loop (over each bit). You could use a compile time loop over each byte. Because the number of bits set for each specific value for a byte it is easy to pre-calculate.

Note: For each byte there are only CHAR_BIT number of bits (usually 8). Which is 256 values. So you can swap space for time here for a single byte.

unsigned num_bits_set_count_value[] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,  // 000-015
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,  // 016-031
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,  // 032-047
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 048-063
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,  // 064-079
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 080-095
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 096-111
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,  // 112-127
// ---
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,  // 128-143
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 144-159
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 160-175
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,  // 176-191
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,  // 192-207
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,  // 208-223
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,  // 224-239
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; // 240-255

// Use compile time meta program
// to unwind a multi byte value into a set of adds
// these will all be inlined.
template <int x>
unsigned num_bits_set_count(char const* byteStream) {
    return num_bits_set_count_value[*byteStream]
         + num_bits_set_count<x - 1>(byteStream + 1);
}
template<> unsigned num_bits_set_count<0>(char const*) {return 0;}

template <typename T>
unsigned num_bits_set(T x) {
   return num_bits_set_count<sizeof(T)>(reinterpret_cast<char const*>(&x));
}

Overall its fine. But you can get the same functionality from using std::bitset and its more readable.

 int a {86};
 std::bitset<sizeof(a) * CHAR_BIT>   x(a);
 // test bit 5
 x[5]

 // set bit 5
 x[5] |= 1;

 // reset bit 5
 x[5] ^= 1;


Log monitoring with pythonic tail -f and process killing

Using regex for such a simple task as finding if a line contains a string is not worth it. The built-in str.__contains__, being called by the keyword in is faster in this case.

Here are some worst case (i.e. a string that does not contain the string "ERROR") timings for the two functions:

import re

def using_in(s):
    return "ERROR" in s

def using_re(s):
    return bool(re.search('.*ERROR.*', s))

Using re is always slower in this case. It does, of course, have its uses for more complex patterns. Note that the re module also compiles the regex automatically (and caches it), so that is not a way to make it faster in this case, since it is always the same regex being used.

Let's just hope your lines are less than 10,000 characters long.

In general, I think you still have to find a good balance between not having enough functions and having too many. IMO, instead of having a increase_base_time function, I would have a global constant and inline the call:

INCREMENT = datetime.timedelta(minutes=1)

...

for line in log:
    ...
    if line_time > base_time:
        base_time = line_time + INCREMENT
        ...

If read_log is a tail -f equivalent, you could just call it tail_f. In any case, I would make the sleep time an optional parameter.

Note that your function does not ensure that the file is properly closed, which might cause issues. You should always use the with keyword to avoid this.

def read_log(f, sleep=0.1):
    """
    Basically tail -f with a configurable sleep
    """
    with open(f) as logfile:
        logfile.seek(0, os.SEEK_END)
        while True:
            new_line = logfile.readline()
            if new_line:
                yield new_line
            else:
                time.sleep(sleep)

This way the file is closed even if the user presses Ctrl+C.

You should only call your function under a if __name__ == "__main__": guard to allow importing from this script without it (trying and failing to) run:

if __name__ == "__main__":
    monitor(sys.argv[1])


You can avoid modifying the input parameter num_list and the memcopy by returning the sorted list pointer. All relevant changes to your code are marked with // (1) in the code below.

You also have a memory leak in counting_sort since you don't release count_list. The fix is marked // (2).

Same for the lists in main // (3)

Note : The program also seg faults when negative data is entered. You either have to guard against that, or also find the minimum data value,  allocate count_list big enough and fix the indices when accessing it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int* counting_sort(int *, int, int); // (1)
int find_max(int *, int);

int main(void)
{
    int l_size;
    int i;

    scanf("%d", &l_size);

    int *num_list = calloc(l_size, sizeof(int));

    for (i = 0; i < l_size; i++)
        scanf("%d", &num_list[i]);

    int max = find_max(num_list, l_size);
    int* sorted = counting_sort(num_list, l_size, max); // (1)

    puts("Sorted:");
    for (i = 0; i < l_size; i++)
        printf("%d ", sorted[i]); // (1)

    printf("\n");

    free(sorted); // (3)
    free(num_list); // (3)

   return 0;
}

int* counting_sort(int *num_list, int l_size, int max) // (1)
{
  int i, j;

  int *count_list = calloc(max + 1, sizeof(int)); // auxiliary array C
  int *sorted_list = calloc(l_size, sizeof(int));

  for (i = 0; i < l_size; i++)
    count_list[num_list[i]]++;

  for (i = 1; i < max + 1; i++)
    count_list[i] += count_list[i - 1];

  for (i = l_size - 1; i >= 0; i--)
    {
      sorted_list[count_list[num_list[i]] - 1] = num_list[i];
      count_list[num_list[i]]--;
    }

  free(count_list);  // (2)

  return sorted_list;  // (1)
}

int find_max(int *num_list, int l_size)
{
    int i;
    int max = num_list[0];

    for (i = 1; i < l_size; i++)
    {
        if (num_list[i] > max)
            max = num_list[i];
    }

    return max;
}


Main method

You want your code to tell the story of how you are solving the problem, starting with the general picture and then working down to the details.

Your main method is find_triangle_number_with_500_factors. I suggest you change the name slightly:

drop "find" as being useless.
don't hardwire "500".

Not hardwiring "500" makes the method more general, facilitates testing and helps explain what the method does. In general, hardwiring is bad and doesn't buy you anything.

Perhaps we might call the method smallest_triangle_number(nbr_factors).

Make the main method simple, showing how the calculation is made is the simplest of terms:

def smallest_triangle_number(nbr_factors)
  n = 0
  nfacs = 0
  while nfacs < nbr_factors
    n += 1
    tnbr = triangle_number(n)
    nfacs = nbr_factors(tnbr)
  end
  tnbr
end

To my way of thinking, the shorter the method, the shorter the variable names can be.  If a method is short, and you understand what value a variable holds, you don't have to remember its name very long, so it can be short. Here I used n (and nbr) for "number" because I always use that convention. triangle_number(n) obviously is a method that calculates n's triangle number. I can use something short like tnbr because the expression says what it is.  Same with nbr_factors and nfacs.

If you want to get fancy you don't have to begin with the number 1. Instead, you could calculate a lower bound on numbers that have triangle numbers with the given number of factors.

Calculate triangle numbers

Next, in order, the method triangle_number(n). Your method is fine, except "generator" doesn't add anything to the name and there is no need for an instance variable. Just return the triangle number, which also helps with the self-documentation of the method:

def triangle_number(nbr)
  nbr * (nbr + 1) / 2
end

I suggest that you only introduce instance variables when you really need them.  For this problem, I don't think you need any.

This problem concerns natural numbers, so I think nbr is enough. (Nobody will ask, "What if nbr is negative, a float, a complex number or a Roman numeral"?) You could instead calculate each triangle number from the previous one, but this is a quick calculation relative to the other work that must be done, and stands alone, so I think that's fine.

Calculate factors

Next up, nbr_factors. You are doing that calculation in two steps, so again, keep the method short to give the reader the big picture:

def nbr_factors(nbr)
  pfacs = prime_factors(nbr)
  prime_factors_to_nbr_factors(pfacs)
end

Again, this is pretty much self-documenting. Notice that I've written the argument as nbr, rather than some variation of triangle_number. That's because the method applies to natural numbers generally, even though we will only use it for triangle numbers. You could of course also write this as:

def nbr_factors(nbr)
  prime_factors_to_nbr_factors(prime_factors(nbr))
end

That's up to you, but you probably want to use the first form at least while you are debugging and testing.

Calculate number of factors from prime factors

Now let's go out of order and look at the method     prime_factors_to_nbr_factors. This one is actually quite easy, as we can employ a version of the Tau function.

Suppose we have constructed prime_factors(n) to return the array:

pfacs = [[f1,n1], [f2,n2],..., [fm, nm]],

where:

fi is the ith prime factor
ni is the number of times fi is a factor

and:

n = f1**n1 * f2**n2 *...* fm**nm

The Tau function tells us the number of factors is:

(n1+1)*(n2+1)*...*(nm+1)

which in Ruby-speak is:

def prime_factors_to_nbr_factors(prime_factors)
  prime_factors.reduce(1) { |tot,(_,n)| tot *= (n+1) }
end

It makes sense that the number of factors should not depend on what the particular prime factors are, just how many there are and the number of times each occurs.

(Note that if you don't care about displaying the prime factors, you could have prime_factors--probably renamed--return only [n1, n2,..., nm].)

Suppose, for example:

tnbr = triangle_number(7)
  #=> 28

Then

pfacs = prime_factors(28)
  #=> [[2,2], [7,1]]

so

prime_factors_to_nbr_factors([[2,2], [7,1]])
  #=> (2+1)*(1+1) => 6

It remains to construct the method prime_factors to return an array similar to pfacs above. As I've rambled on awhile, I'll leave it to others to cover that.


SafeBox StateMachine implemented with Enums

Make fields immutable when possible

The setPass method is never used in the posted code.
As such, you can make the password field immutable:

private final String password;

Reuse Scanner

ACCEPT.askPassword will recreate the Scanner scan field from System.in every time it's called. This is unnecessary, it would be better to create the scanner only once.
That also means that you can make scan a final field.

Use boolean expressions directly

Instead of code like this:

if (res == false)
// ...

if (res == true)
// ...

Use boolean expressions directly like this:

if (!res)
// ...

if (res)
// ...

Do this everywhere where you used something == true or false.

Combine related if statements

In this code there are two conditions on the value of res:

if (res == false)
    System.out.println("try number:" + safebox.counter);

if (safebox.counter == 3){

    safebox.state = SafeBox.PENELTY;
}

if (res == true)
{
    safebox.state = SafeBox.SUCCESS;
}

The code could be reorganized to make it clearer and to avoid one unnecessary condition:

if (safebox.counter == 3) {
    safebox.state = SafeBox.PENELTY;
}

if (res) {
    safebox.state = SafeBox.SUCCESS;
} else {
    System.out.println("try number:" + safebox.counter);
}

And since safebox.counter is only incremented in case of failure,
the penalty condition can be moved inside the else branch of the second if statement:

if (askPassword(safebox)) {
    safebox.state = SafeBox.SUCCESS;
} else {
    System.out.println("try number:" + safebox.counter);
    if (safebox.counter == 3) {
        safebox.state = SafeBox.PENELTY;
    }
}


Speeding up Parallel.ForEach iterating through datatable and rendering report

The first thing here, you shouldn't be using directly the DataTable to read the results, use the method CreateDataReaderto create a Data Reader from it.

The difference is that a DataTable will check back on the database server on each iteration, while the DataReader will get a snapshot of your data and not check back anymore. That saves lots of time when dealing with a big number of records.

In this same channel, don't make the INSERT directly, but create it on memory, like an array or something (I think there is too something in the DataBase class that manages it in memory and commits later, but don't remember its name). If you stop dealing with the database one-at-a-time and doing in chunks, the speed of your code will improve.


You can import and use datetime rather than validating date yourself.
>>> import datetime
>>> datetime.date(2020, 9, 9)
datetime.date(2020, 9, 9)
>>> datetime.date(1990, 2, 29)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

As such we can just change all your checks to a call to datetime.date in a try except block.
for groups in dateRegex.findall(text):
    try:
        datetime.date(int(groups[2]), int(groups[1]), int(groups[0]))
        matches.append('/'.join(groups))
    except ValueError:
        pass

Rather than using '/'.join(groups) if we use finditer we can just use groups[0].
And we'd need to increment the other indexes by one too.
for groups in dateRegex.finditer(text):
    try:
        datetime.date(int(groups[3]), int(groups[2]), int(groups[1]))
        matches.append(groups[0])
    except ValueError:
        pass

We can also change the creation of datetime.date to use a comprehension.
We need to use * to map all the values of the built list to arguments to the function.
for group in dateRegex.finditer(text):
    try:
        datetime.date(*(int(part) for part in group.groups()[::-1]))
        yield group[0]
    except ValueError:
        pass

You should also use an if __name__ == '__main__': guard to prevent your code from running on import.
And I'd define more functions.
import pyperclip
import datetime
import re

DATE_MATCHER = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)')

def find_dates(text):
    for group in DATE_MATCHER.finditer(text):
        try:
            datetime.date(*(int(part) for part in group.groups()[::-1]))
            yield group[0]
        except ValueError:
            pass

def main():
    text = 'Hello. Your birthday is on 29/02/1990. His birthday is on 40/09/1992 and her birthday is on 09/09/2000.'
    dates = list(find_dates(text))
    if not dates:
        print('No dates found.')
    else:
        pyperclip.copy('\n'.join(matches))
        print('Copied to clipboard:')
        print('\n'.join(dates))

if __name__ == "__main__":
    main()


I would use map to replace all the data.query.pages[key]. into a single variable. Also ES6 template string is very useful, if you are not using ES6, just change it into one line string like you did in your original solution. map return an array, so I have to join('') them into a single string. Then I can just use it to pass to the jquery html() function and replace the content. Also, ? : shorthand for if else statement can produce less code in one line.

$('.sec-result .row').html(
    data.query.pages.map(page => (
        `

${page.title}

${page.extract}

`
    )).join('')
);

My solution is just for readability, it may not increase the speed though.


Creating a ES6 class for every API endpoint's response

Hard coding outside data source should be avoided.
Hard coding outside data sources will present an ongoing workload. This will be compounded by the fact there is no validation of data.
At anytime the data source may change, add, or remove properties. You will not know about the change (if you don't personally follow the source doc feed) until it fails or a customer/consumer reports the problem, or worse just stops using it.
Testing for a valid response will not protect against modified data.
Even if you validate the data it will just improve response time for the fix / update but not the underlying problem.
The cost.
Every change will require an update, test, documentation, deploy, monitor, release, and pray cycle for the life of the service. As a business I would have to pass this cost/ risk on to the client or revenue source, and having a programmer on call is very expensive. In other words this type of design can kill a service.
For the sake of auto complete it is not worth it.
You are best of generating something that Vs2017 can read (I don't use it so you will have to look in the docs) and hard coding as little as possible that is outside your direct control.


Copy object properties without using many if statements

I think Apache commons BeanUtils might help you there. It uses reflection. Take this into consideration if performance is an issue...

We need 2 Steps:

1st create a method that copies a property if a condition is met

2nd create a copy method that passes all fields to the first method

Here we go...

public class InputForm {
    [...]

    private void copyProperty(InputForm srcForm, String field, boolean condition) {
        if(condition) {
            PropertyUtils.setProperty(this, field, PropertyUtils.getProperty(srcForm, field));
        }
    }

    public void copyFromOtherForm(InputForm srcForm, CopyForm conditions) {
        copyProperty(srcForm, "brandCode", conditions.isBrandCodeChecked());
        copyProperty(srcForm, "caution", conditions.isCautionChecked());
        [...]
    }
}

if you're still not pleased with that you could use reflection to invoke "is"+field+"Checked" on your CopyForm instance and change the calls to:

copyProperty(srcForm, conditions, "field");


Python function to strip inline repr'd unicode strings

Yes, regexps were my first thought:

re.sub(r"u'([^']*)'?", r'\1', string)

Dissected:

A literal u'.
Then anything that is not a ' zero or more times: [^']*.
Store that for later retrieval: ([^']*).
End with an optional '.


Creating a user via social auth, merging and modifying appropriately

You can organize better your asynchronous code.

Turn something like this:

Promisse.then(function() {
    Promisse.then(function() {
        promisse.then(function()) {
        }, function() { error })
    }, function() { error })
}, function() { error })

Into something like:

Promisse.then(function() {
}).then(function() {
}).then(function(){
}).catch(function () { failure && failure(); })

Another tip would be creating a function User.create and other called User.merge (this will make debugging easier; read about the Single-responsiblity principle to know more in depth why).


Partition array in at most k subarrays that minimize a function

Yes there is a better way.

The key observation is that since the array is sorted, the size of partition [p,q] is \$a_q - a_p\$, and the sum of sizes is almost \$a_N - a_1\$. Missing are gaps between right end of one partition and left end of the next one.

So the solution is to compute the set of sequential differences, and select \$K-1\$ largest. These are optimal partition points.

Otherwise, the code is clean and understandable.


Encrypt and backup folder to email daily, when online

I would make the following changes, in order to make it more robust, and simpler:

Do not use openssl and symmetric encryption.  Use gpg and public key encryption.  The advantage is that you do not have to store any passwords, anywhere (keep the secret key away from the backup script).  Public key encryption is great for backups (you only need to access your secret key when you have to restore a backup, which happens rarely).
Do not mess around with timestamp files.  Instead, keep the last archive around, and inspect the datestamp of the archive (you can use find <path> -ctime 1 to see if the archive is older than 24 hours).  If your last backup is too old, make a new one.  Keeping one old backup around is another safety line for you, even though it's only stored locally.
Do not use a cron job.  Instead, invoke your script from a DHCP exit hook, which is run whenever your computer acquires an IP address.  You can then check if you have Internet access, and mail your backup straight away.  This also works if you're only online for a short while (and your cron job might miss that window of opportunity).
Check exit codes of everything and make sure your script alerts you somehow if things went wrong.  You might need to find a way to interface with your desktop environment in order to do that (notify-send works in Ubuntu).


In python it is usually frowned upon iterating with:

l = [1, 2, 3]
for i in range(len(l)):
    print l[i]

and it is preferred to iterate over the iterable directly:

l = [1, 2, 3]
for x in l:
    print x

Similarly, it is a lot easier to use random.sample (or random.choice if you don't care if a word is asked multiple times) to choose a random word to test now.

Also, it is easier to leave the word and its definition bundled in a tuple, because most of the time you need both of them.

Your choices included sometimes multiple times the same words, because you check only once whether the random answer is already included (if it is, you choose randint - 1, which might also already be included). You should keep on polling until you find a word not included in answers yet (This assumes your dictionary to have more words than CHOICES).

Similar for your user choice. It is nicer (to the user) to keep on asking for an answer until he answers with a possible choice.

I made you enumeration of the choices to be numbers rather than letters because it makes it easier to validate the correct answer.

You should in general use python's str.format methods rather then string addition. It is usually faster and also more readable (and extendable, you can add text justification, padding, etc).

I also added random.shuffle(answers) instead of answer.sort() just so it does not get too boring.

Final code:

import csv
import random

WORDS = 5    # Number of words
CHOICES = 5    # Number of choices

with open("wordlist.csv") as csvfile:
    words = list(csv.reader(csvfile))

score = 0
count = 1

while count <= WORDS:
    print("\nQuestion {}".format(count))
    word, correct_answer = random.choice(words)
    print("Word: {}".format(word))

    answers = [correct_answer]
    while len(answers) < CHOICES:
        _, random_answer = random.choice(words)
        if random_answer not in answers:
            answers.append(random_answer)
    random.shuffle(answers)
    correct_index = answers.index(correct_answer) + 1

    for choice, answer in enumerate(answers, start=1):
        print("{}: {}".format(choice, answer))

    userinput = 0
    while not 0 < userinput <= CHOICES:
        try:
            userinput = int(input("Answer: "))
        except ValueError:
            continue
    if userinput == correct_index:
        score += 1
        print("Correct")
    else:
        print("Wrong: {}".format(correct_answer))
    count += 1

print("{}/{}".format(score, WORDS))


Tidying up jquery code for linking inputs

It's not so horrible. You managed to cache your jQuery selectors, which is more than a lot of people can say. Good job there.

automatic and pager are not super great names in this context. I suggest renaming them to autoSlug/autoMenu or manualSlug/manualMenu.

You are caching toSlug, but really, it's not complex enough to warrant caching. I did some quick and dirty testing and found that you save about 10ms per 1,000 executions. That is not worth anything here. So, to reduce code size and bug potential, I suggest removing all caching.

Variables and parameters should not be capitalized unless they represent a class. As such, the Text parameter in toSlug should be text.

Finally, and this is more of a personal preference, but I find that code is easier to read and follow when reading functions and not event handlers. By that I mean this: instead of calling menu.change(), why not move that code to a function and call updateMenu()?

Here is the final result:

$(function(){
var autoSlug = true;
var autoMenu = true;

var slug = $('#slug');
var menu = $('#menu_title');
var page = $('#page_title');

page.on('change', function() {
    if (autoMenu) {
        updateMenu()
    }
});

menu.on('change', function() {
    autoMenu = (menu.val() == '');
    updateMenu()
});

slug.on('change', function() {
    autoSlug = (slug.val() == '');
    updateSlug();
});

function updateMenu(){
    if(autoMenu){
        menu.val(page.val())
    }
    if(autoSlug){
        updateSlug()
    }
}

function updateSlug(){
    var text = autoSlug ? menu.val() : slug.val();
    slug.val(toSlug(text));
}

function toSlug(text) {
    return text.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-');
}
});


Add multiples of 3 or 5 below 1000, Can this code be optimised. Project Euler #1

The main problem

The main issue here is that you define i in function of it being a "factor of 3", and then also try to use this number as a "factor of 5". This doesn't make any sense - as there is no inherent relationship between being a threefold and a fivefold number.

It would've made sense if you were doing it for 3 and 6, for example, because 3 and 6 are related:

//i*3 is obviously always a multiple of 3
sum += 3 * i;

if ((3*i) % 2 == 0)
{
    //Now we know that i*3 is also a multiple of 6
}

But that is not the case here.

The for loop's readability

I understand your idea, you wanted to only iterate over factors of three which keep the multiple under 1000. While I will suggest to change this approach (later in the answer), your approach could've been written in a much more readable manner:

for( int i = 0 ; i < 1000 ; i+=3 )

This will iterate over i values of 0,3,6,9,12,15,... and will skip all values inbetween.

The benefit here is that you don't need to work with i*3 all the time, you can just use i itself.

You will need to iterate over the multiple of 5 separately. However, should you keep using this approach, I would always suggest splitting these loops anyway.

The algorithm

Your approach works, but it's not the easiest approach. If I put your approach into words:

  Add every multiple of 3 to the sum.

  Also add the multiple of 5, but only if it's still below 1000, and it's not already divisble by 3.

The issue here is in how you handle the multiples of five. You're working with an i that is defined as the allowed values for threefolds. For any i > 200, you're effectively having to manually exclude this value. You're using a different approach for the 5 than you are using for the 3, even though the logic is exactly the same. That's not a reusable approach.

Secondly, there is a readability problem. Your code should be trivially readable, and I simply wasn't able to understand your intention. I had to google what the question was before I could understand what your code was trying to achieve.

So let me offer a better approach, first putting it into words:

  Check every number from 0 to 1000 (not including 1000)
  If it is divisible by 3 or it is divisible by 5, then add it to the sum.

This can be put into code, step by step:

// Check every number from 0 to 1000 (not including 1000)
for(int i = 0; i < 1000; i++)
{
    var isDivisibleBy3 = i % 3 == 0;
    var isDivisibleBy5 = i % 5 == 0;

    //If it is divisible by 3 or it is divisible by 5
    if(isDivisibleBy3 || isDivisibleBy5)
    {
        //then add it to the sum
        sum += i;
    }
}

Note how the code exactly mirrors my algorithm description.

You don't need to use the booleans. I simply added them to simplify the example. if(i % 3 == 0 || i % 5 == 0) would be equally okay to use because it's still reasonably readable.

If the calculations become more complex, I suggest always using the booleans so you neatly break your algorithm down to small and manageable steps. It will do wonders for your code readability, and it does not impact performance (the compiler will optimize this in a release build).

A LINQ variation

This can be further shortened using LINQ:

var sum = Enumerable.Range(0,1000)
              .Where(i => i % 3 == 0 || i % 5 == 0)
              .Sum();

LINQ is just a nicer syntaxt, but it uses a for/foreach iteration in the background, so I suspect it won't be much more performant than the previous example. But I do consider this highly readable.

Maximizing performance

The previous suggestion maximizes readability, but it does so at the cost of performance, as it now has to loop over 1000 values and evaluate them all. You already linked several other answer that clearly dive deeper into the code in order to maximize the performance, I hope you can see that this dramatically impacts the readability.

For example:

public void Solve(){
    result = SumDivisbleBy(3,999)+SumDivisbleBy(5,999)-SumDivisbleBy(15,999);
}

private int SumDivisbleBy(int n, int p){
    return n*(p/n)*((p/n)+1)/2;
}

By itself, I would have no idea what this code does. I can sort of understand the intention of Solve(), but it's not quite apparent how SumDivisbleBy() works.

SumDivisbleBy() has effectively become impossible to maintain. If you needed to introduce a change, you would effectively have to reverse engineer it before you can alter it. This means that starting from scratch is the better option, which is clearly not a good thing.

However, when performance is the main focus, this is acceptable. I would, however, strongly urge you to document the algorithm in comments specifically to help future readers in understanding how/why this works.

Note that AlanT's answer contains a more readable variant of the SumDivisbleBy() method, which already helps a lot with understanding the algorithm. The clear naming used clarifies what the algorithm does, which is the main goal of writing readable code (explaining why something works is only a secondary goal and not always required).


Implementing SOLID Principles with C# Asp.net

When you say I have a form that initiates import process on a button's click event, you've coupled your UI with some "business logic". Let's look at that Click handler:

private void btnStart_Click(object sender, EventArgs e)
   {
       IReader _reader = new DBReader();
       Interfaces.IWriter _writer = new Classes.DBWriter();

       Interfaces.IExternalSystemInteraction _externalSystem = new Classes.JSonExternalSystem(_writer);

       Classes.Client _client = new PxImportApplication.Classes.Client(_reader, _externalSystem);
       _client.Invoke();
   }

Naming

This method handles the click of a button, I'd infer a button named btnStart and say that the naming convention you're using for control names is breaking the naming convention for method names - how about naming the button StartButton and handle the Click event in a StartButton_Click, or OnStartButtonClick method? In my opinion the reasons why btnStart is a bad name would be something like:

Hungarian Notation is used, "btn" being a short for Button, which is a type.
Disemvoweling turned "button" into "btn".
camelCase breaks the PascalCase convention for naming methods, because the convention for event handlers is void [objectName]_[eventName](object sender, EventArgs e).

Type qualification

If, at the top of your code file, you added the following:

using PxImportApplication.Classes;
using PxImportApplication.Interfaces;

Your handler code could read like this:

private void btnStart_Click(object sender, EventArgs e)
   {
       var reader = new DBReader();
       var writer = new DBWriter();

       var externalSystem = new JSonExternalSystem(writer);

       var client = new Client(reader, externalSystem);
       client.Invoke();
   }

Fully-qualified types make the code harder to read. I noticed you used _ in front of local variables; I prefer to use the underscore for private fields, if at all.

Dependencies

The problem with this approach, is that by instantiating that form you automatically get a new DBReader and a new DBWriter, with absolutely no way of swapping these two with a mock implementation - actually you don't really have another way of testing this piece of logic, other than F5 and run the thing and click the button and see how it goes.

In fact, the UI is tightly coupled with the DBReader, DBWriter (which should be DbReader and DbWriter), Client and JSonExternalSystem. Whenever you new up something, you've identified a dependency. Most classes of the .net framework are ok to instantiate on the fly like this, other dependencies should be clearly stated, in the form's constructor. Keep the parameterless default constructor so that you won't break the designer, but make another that takes all other dependencies. Too many (4? 5? 6? Your call!) constructor parameters (/dependencies) is a sign that your class is starting to break the Single Responsibility Principle.

I think the form is doing much more than just being a UI here, and the dependencies really are, is dependencies of another type, namely PxImportApplication.Classes.Client.

What the button really needs to do, is instantiate a Client and call the Invoke() method (a confusing name that breaks POLS, Invoke is .net lingo for synchroneously calling a delegate). All this newing up is covering-up the real intent. How about having a click handler doing this:

private void btnStart_Click(object sender, EventArgs e)
{
       var client = _clientFactory.Create();
       client.Invoke(); // todo: rename this method
}

This code means the handler now only depends on a _clientFactory private field:

private readonly IFactory _clientFactory;

And this field can be instantiated from the form's parameterized constructor:

public Form1(IFactory clientFactory) : this()
{
    _clientFactory = clientFactory;
}

The factory class has its own dependencies:

private readonly IReader _reader;
private readonly IExternalSystemInteraction _externalSystem;

public ClientFactory(IReader reader, IExternalSystemInteraction externalSystem)
{
    _reader = reader;
    _externalSystem = externalSystem;
}

public IClient Create()
{
    return new Client(_reader, _externalSystem);
}

The ClientFactory class implements the IFactory interface, which simply exposes a parameterless Create() method - and that's everything the form needs to know.

Your constructor-injected private fields can be made readonly in both Client and JSonExternalSystem classes (should be JsonExternalSystem). You're doing it right in these classes - don't do DI halfway though, do it all the way. Creating instances of types is the role of factory/infrastructure classes and of the application's composition root. If you're using an IoC container you don't have to resolve the dependencies yourself. This means if the IReader that the factory class takes has dependencies of its own, you don't need to bother with them; by letting go of the control you have over the types that a type can instantiate, your code becomes very focused, cohesive. High cohesion, low coupling is what you want to achieve.


You're finding all solutions, but because the code overwrites the <span> for every solution found you only see the last one. Try this:

sp.innerHTML += 'solved in ' + h.length + ' steps<br/>';

You're performing a breadth-first search of all possible paths through the maze which is what I ended up going with. By scheduling timer events you're essentially queueing up cells. I did the same but with an actual queue of cells to visit.

This is the core of my Scala version.

// pathTo tracks the best path to each point
// moves(Point) returns the number in that cell

val queue = new Queue[Point]
queue enqueue new Point(0, 0)  // start from top-left
while (!queue.isEmpty) {
    val start = queue dequeue
    val path = pathTo(start)
    (UP, DOWN, LEFT, RIGHT) foreach { direction =>
        val end = start.move(direction, moves(start))
        if (end != None && !pathTo.contains(end)) {
            pathTo(end) = path + end
            queue enqueue end
        }
    }
}


Python Console App | Is there a better way to go back a page?

I'm thinking there are a few different approaches you could take here.
The stack was inside you all along
It may not be the most flexible of approaches, but the way things are right now, your pages are just functions. And guess what? Your program already has a stack of functions -- you navigate it by calling functions and returning from them! You don't get a whole lot of information about where you'll end up if you return, but if that's not a problem, you might be able to just get rid of menu_checker and menu_stack altogether -- if the user wants to go back, you just return.
For example, your page_one could simply look like
def page_one():
    while True:
        clear_terminal()

        print('Page One\n')

        option = input('Page 2, back\n')

        if option in ['2', 'two']:
            page_two()
        elif option in ['b', 'back']:
            return
        else:
            print('Invalid input, please try again\n')
            sleep(1)

It's not the fanciest-looking perhaps, but it's easy to implement, easy to understand and does the job just fine.
Where do you want to go?
But maybe that isn't good enough. It might be nice if the "back" option could say something like "Back (to page 1)" depending on what the stack looks like, for example. Or maybe you'd like to also have a "forward" option in case the user accidentally presses "back" too many times. Or maybe there's another reason you don't want to use the call stack for this. That's fine too.
Another option could be to move the navigation logic from the individual menus into a single core loop. Each menu then returns which menu it thinks you should go to next.
For example, we might be looking at something like this:
def main():
    menu_stack = [main_menu]

    while menu_stack:
        current_menu = menu_stack[-1]

        next = current_menu(option)

        if next:
            menu_stack.append(next)
        else:
            menu_stack.pop()

With menus looking a lot like the previous ones, but instead of calling the next menu like page_two() they return it like return page_two. Or perhaps return None if we should go back.
Classy
Personally, though, I think there are some tasks (like asking for input) that should be the responsiblity of the app itself rather than the menus. The menu can know what it looks like and how to navigate based on input, but the core loop asks it for help and then handles those things on its own terms.
def main():
    menu_stack = [main_menu]

    while menu_stack:
        current_menu = menu_stack[-1]

        clear_terminal()

        print(current_menu.text)

        option = input(current_menu.prompt)

        try:
            next = current_menu.get_next_menu(option)

            if next:
                menu_stack.append(next)
            else:
                menu_stack.pop()
        except ValueError as e:
            print("Invalid input, please try again")
            sleep(1)

Defining a nice Menu class is left as an exercise for the reader.


I think the main issue here is that you are trying to reuse snippets from Google without trying to understand what is doing what.

Magic numbers

This might be purely personal but I find 60*60*24 much easier to understand than 86400.

Do not repeat yourself

What is the point of having fmt = '%Y-%m-%d %H:%M:%S' if later on you rewrite strftime('%Y-%m-%d %H:%M:%S') ? You could write it : d1 = datetime.date.today().strftime(fmt) making obvious to everyone that the same format is used.

Useless conversion between strings and dates

You are converting dates to string and string to date in a convoluted and probably not required way.

Usess conversion to int

You are using int(expr_date)) but expr_date is defined as int(t) * 86400 which is an integer anyway. Also, I am not sure you would need the conversion of t as an int.

Taking into account the different comments, my resulting not-tested code looks like :

def convUnixTime(t):
        return (datetime.datetime.fromtimestamp(t*60*60*24)
              - datetime.datetime.today()).days

Edit : I was using datetime.date.today() instead of datetime.datetime.today(). Also fixed the sign issue.


Arithmetic

Project Euler questions are meant to educate you about both mathematics and programming.  It would be a good idea to understand what these triangular, pentagonal, and hexagonal numbers actually are, rather than blindly applying the given formulas.

One performance improvement would be to find a way to generate successive elements of each sequence without plugging \$n\$ into the formulas, which involve division.  (Division tends to be slow.  Floating-point division, using the / instead of the // operator, is even slower, and it also causes you to have to cast the result back to an int.)

If you take the formula for pentagonal numbers \$P_n\$, you can figure out another formula for the difference between successive elements in the sequence.

$$
\begin{align}
P_n &= \frac{n(3n-1)}{2} = \frac{3n^2-n}{2} \\
P_{n+1} &= \frac{(n+1)(3(n+1)-1)}{2} = \frac{(n+1)(3n+2)}{2} = \frac{3n^2+5n+2}{2} \\
P_{n+1} - P_n &= \frac{(3n^2+5n+2)-(3n^2-n)}{2} = \frac{6n+2}{2} = 3n + 1
\end{align}
$$

If you do the same for triangular, square, and hexagonal numbers, you'll find:

$$
\begin{align}
T_{n+1} - T_n &= n+1 \\
P_{n+1} - P_n &= 3n+1 \\
H_{n+1} - H_n &= 4n+1
\end{align}
$$

Considering that square numbers would be \$S_{n+1} - S_n = 2n+1\$, you can see a pattern to produce polygonal numbers in general.

Algorithm

Your strategy is to generate a million elements of each sequence and find the elements that exist in common.

First of all, one million is an arbitrary limit.  You might need fewer than a million to find the next element in common (in which case you've wasted execution time), or you might need more than a million (in which case you would have to raise the limit and run your code again).  It would be nice if your algorithm did not have to rely on a guess.

Secondly, the millionth hexagonal number is certainly going to be much larger than the millionth triangular number.  There is no way that the millionth hexagonal number is going to coincide with anything, so that's wasted work.

Thirdly, you store the sequences as lists.  Searching a list (e.g. terms in triangle) involves inspecting every element in that list (a so-called O(n) operation).  Searching a set takes only O(1) time.  Therefore, simply changing

triangle = []
pentagonal = []
hexagonal = []

and

        triangle.append(product.triangle())
        pentagonal.append(product.pentagonal())
        hexagonal.append(product.hexagonal())

to

triangle = set()
pentagonal = set()
hexagonal = set()

and

        triangle.add(product.triangle())
        pentagonal.add(product.pentagonal())
        hexagonal.add(product.hexagonal())

brings the execution time down from hundreds of seconds down to about 2 seconds.  Better yet, your main() function could be simplified using the set intersection operator &:

def main():
    generate()
    triangle_number = triangle & pentagonal & hexagonal
    print(sorted(triangle_number))
    print(time.time() - startTime, "seconds")

Pythonicity

Be consistent with your naming.  If you write "pentagonal" and "hexagonal", then use "triangular" rather than "triangle".

The Shape class shouldn't exist at all.  It's just a very weird and cryptic way to call three functions that take a numerical parameter.

for _, terms in enumerate(hexagonal) is a nonsensical use of enumerate.  If you're going to throw away the index anyway, why not just write for terms in hexagonal?  And why is your iteration variable pluralized (terms rather than term)?

Your code would be much more expressive if you could say "give me the next pentagonal number".  A good way to do that in Python is to define a generator, so that you can write next(pentagonal_numbers).

Suggested solution

from itertools import count

def polygonal_numbers(sides):
    result = 0
    for n in count():
        yield result
        result += (sides - 2) * n + 1

tt, pp, hh = polygonal_numbers(3), polygonal_numbers(5), polygonal_numbers(6)
t = p = 0
for h in hh:
    while p < h: p = next(pp)
    while t < h: t = next(tt)
    if t == p == h > 40755:
        print(h)
        break

If you take into account that every hexagonal number is also a triangular number, you can ignore the triangular numbers altogether:

from itertools import count

def polygonal_numbers(sides):
    result = 0
    for n in count():
        yield result
        result += (sides - 2) * n + 1

pentagonal_numbers = polygonal_numbers(5)
p = 0
for h in polygonal_numbers(6):
    while p < h: p = next(pentagonal_numbers)
    if p == h > 40755:
        print(h)
        break

My last solution takes about 50 milliseconds to run on my machine.


Overall, fairly good.

  Am I doing anything dangerous in this?

Lack of comments

I'd expect at least some commentary about the roll of the functions and how to use them near the function declaration section.

Assume a user will read the header and not delve into implementation.

Unexpected type change

The stored ellement is a void *, changing the return type to const is not good.

// const void* vv_read_index(void_vector *vv, size_t index)
void* vv_read_index(void_vector *vv, size_t index)

Overuse of NULL

vv_pop(), vv_read_index() return NULL as an error indicator and can return NULL as a valid return.  If NULL is not to be allowed (which I think is a bad idea) as a storable void *, vv_push(&vv, NULL) should error.

I'd re-work calls to return an error code on vv_pop(), like vv_err vv_pop(void_vector **vv, void **el).

It seems odd to have 2 forms of error signaling: error codes and NULL.

"default size"

I see no real value in a default size of 16.  Suggest setting aside size == 0 as something special and allow an initial vector size of 0.  Add code to handle doubling array size when size is 0.

Create a VV_DEFAULT_SIZE 16u if desired for the user to call with new_void_vector(VV_DEFAULT_SIZE).

Overflow

I'd detect overflow in size computations.

Tolerate freeing NULL

free(NULL) is well defined.  I'd expect the same with delete_void_vector(NULL, foo).  Currently code dies on this.

  Is the code clear, what can I do to make it easier to follow?

Naming convention

Recommend to use the same one prefix with all external types, names and functions.

// void_vector.h
vv.h

// VOID_VECTOR_H
VV_H

// void_vector* new_void_vector(size_t size);
void_vector* vv_new(size_t size);

Or use void_vector instead of vv throughout, not both.

Allocate to the size of the object, not type

Allocating to the size of the referenced object is 1) less error prone, 2) easier to review 3) easier to maintain than allocating to the type.

// void_vector* vv = malloc(sizeof(void_vector) + sizeof(void*) * size);
void_vector* vv = malloc(sizeof *vv + sizeof *vv->data * size);

Avoid unnecessary suffixes

An L, l, LL, ll is needed a lot less than one thinks.  In the following case, L certainty not needed.  The u is useful though.  I am curios as to why OP thought is was needed - what issue was of concern?

/// #define defualt_size 16ul
#define defualt_size 16u

Use const

const would help convey that the function is not altering *vv

// vv_read_index(void_vector *vv ...
vv_read_index(const void_vector *vv ...

  Is there an obvious way to greatly improve the efficiency?

Allocations only increase as vv_pop() does not reduce things. This can make for an inefficiency of memory usage.

IMO, a more advanced  scheme could decrease by 1/2 when size needed falls below 25% or 33%.

  General style comments

Spell check

// #define defualt_size 16ul
#define default_size 16ul

! vs. >

Minor: With arithmetic concerns, > is more readily understood that ! negation.

// if (!size)
if (size > 0)

  I'm not overly concerned about the contents of void_vector_tb.c.

Avoid naked magic numbers

Replace 10 with #define VV_STR_N 10,  32 with #define VV_STR_SZ 32,

Cast not needed

// while(s = (char*) vv_pop(vv)) {
while(s = vv_pop(vv)) {


Munging data off the World Atlas of Language Structures website

There are a few efficiency improvements I can see:

Don't continually do an operation on data if that data doesn't change. Take your headerline variable. Each time you loop through your data, you do headerline.split('\t')[1:]. This is fairly inefficient since headerline never changes after you assign its value and thus you only need to do the operation once instead of \$n\$ times.

To fix this, save the result to a variable before your loop:

relevant_headers = headerline.split()[1:]
for line in data.split():
    . . .

Akin to the point above: don't do more work than you have to. You call split twice on line in your first for loop: first you split line and grab the language, then split it again to get the rest of the data. Instead of doing that, take advantage of unpacking in Python 3 or use pop() in Python 2:

# Python 3
language, *language_data = line.split()

# Python 2
language_data = line.split()
language = language_data.pop(0)

You can combine your final three for loops into one loop:

self.genus = defaultdict(list)
self.family = defaultdict(list)
self.related_languages = defaultdict(list)
for language, data in self.items():
    genus = self.genus[data['genus']]
    family = self.family[data['family']]

    genus.append(language)
    family.append(language)

    self.related_languages[language] = genus + family

Yes, we are reassigning self.related_languages[language] each iteration. However, this is an \$O(1)\$ operation, so it can be thought of as another basic operation. Since we now only have one for loop, only \$n\$ operations are done instead of \$3n\$. In terms of Big-O notation, the two versions perform the same; however, in terms of operation count and practical processing time, the above is better.

There are also a couple of style pointers I want to make:

Only use ALL_CAPS when dealing with constants. Because we cannot syntactically define constants in Python, convention is all we have to tell whether a variable is constant or not. So, unless a variable is actually supposed to be constant, do not use ALL_CAPS.

To go along with this point, when dealing with multiple words in a variable name, use underscores to separate the words:

# No
self.LANGUAGEFAMILY

# Yes
self.language_family

  NOTE: One exception to the rule ALL_CAPS rule is if you are using an acronym in a class name. So if WALS is an acronym, then MiniWALS is a slightly ambiguous, yet OK, name. Otherwise, I would suggest MiniWals.

Technically you indentation is fine. However, conventional Python uses 4 spaces to define code blocks.
Use format instead of string concatenation. This is in the style section because the performance benefits are debatable. However, using the format notation is much more readable and is more Pythonic:

# Instead of this...
WALS_TXT = currentdirectory()+"/data/wals/wals.txt"

# ... do this.
wals_text = '{}/data/wals/wals.txt'.format(currentdirectory())

Aside from these pointers and a few spacing issues and a not-needed +, your code stylistically looks fine.

Here is my version of your code:

from collections import defaultdict
from utils import sync_and_read, currentdirectory

class MiniWALS(dict):
    def __init__(self, toupdate=True):
        # Unless unfeasible, I always put instance variables at the top.
        self.genus = defaultdict(list)
        self.family = defaultdict(list)
        self.related_languages = defaultdict(list)

        wals_url = 'http://wals.info/languoid.tab?sEcho=1&iSortingCols=1'\
                   '&iSortCol_0=0&sSortDir_0=asc'
        wals_text = '{}/data/wals/wals.txt'.format(currentdirectory())

        wals_tsv = sync_and_read(wals_url, wals_text, toupdate=toupdate)
        headerline, _, data = wals_tsv.partition('\n')

        relevant_headers = headerline.split()[1:]
        for line in data.split():
            # I'm assuming Python 3.
            language, *language_data = line.split()
            for key, value in zip(relevant_headers, language_data):
                self.setdefault(language,{})[key] = value

        for language, data in self.items():
            genus = self.genus[data['genus']]
            family = self.family[data['family']]

            genus.append(language)
            family.append(language)

            self.related_languages[language] = genus + family


IMDB website query to find actors by time period

I see some of the same problems as in your last query
Do not use single-letter aliases
a, m1, c1... How about an alias that helps you write the query, instead of one that saves a few characters? That's what they are for, after all.
Old style JOIN
I think you would benefit from reading about explicit JOIN syntax instead of using the pre-ANSI-92 syntax.
Vertical white space
I personally find queries much easier to read if you use line breaks between lists of columns/values/conditions, instead of writing them inline.
Column aliases
It's good practice to rename short/ambiguous/ugly column names to something more human-friendly while presenting the result set. To you it may not matter much, but if you were presenting this report to your boss, they may scratch their head at fname and lname. The syntax for column aliases is the same as table aliases.
That Devil BETWEEN
BETWEEN is ambiguous. You should instead use logical operators.
This is about Microsoft T-SQL, but some problems apply pretty much across the board in SQL.

What do BETWEEN and the devil have in common?
I'll make no bones about it: BETWEEN is evil. For one, the meaning of the word in English does not always match the meaning of the operator in T-SQL. In T-SQL, BETWEEN is an inclusive range - not everyone gets that. Sure, in casual conversation when someone says "between 3 and 6" the answer really could be 3, 4, 5 or 6; but other times, they really mean to restrict the set to only 4 or 5 (an exclusive range).

The reviewed script
SELECT DISTINCT
    Actor.fname AS ActorFirstName,
    Actor.lname AS ActorLastName,
FROM
    Actor -- look no alias needed
    INNER JOIN Cast AS OlderCast ON OlderCast.pid = Actor.id
    INNER JOIN Movie AS OlderMovie ON OlderCast.mid = OlderMovie.id
    INNER JOIN Cast AS NewerCast ON NewerCast.pid = Actor.id
    INNER JOIN Movie AS NewerMovie ON NewerCast.mid = NewerMovie.id
WHERE
    AND OlderMovie.year >= 1850
    AND OlderMovie.year <= 1900
    AND NewerMovie.year >= 1901
    AND NewerMovie.year <= 1950;


Asking for Fibonacci numbers, up till 50

A few minor tips on making the code more compact:

Remove unneeded variables/initializations.  In particular your t variable doesn't need to be initialized outside the loop since its value is always set within the loop before it's used.
The run variable can also be eliminated; make the loop while True and use a break to escape it when you're done.
Instead of doing text.isdigit() just do the int conversion inside a try block.
Combine your two "Try again" cases into a single block of code rather than repeating yourself.

With those changes the code looks like:

# Init previous two values of Fibonacci sequence
prev_2 = 1
prev_1 = 0

# Run while loop to prompt user enter Fibonacci number
while True:
    try:
        t = int(input('Enter the next Fibonacci number >'))
        if t != prev_2 + prev_1:
            raise ValueError('not the next Fibonacci number!')
        if t > 50:
            print('Well done')
            break
        # move to next value in the sequence
        prev_2, prev_1 = prev_1, t
    except ValueError:
        print('Try again')
        break

A larger tip on improving the code would be to separate the two distinct tasks the code is doing: computing the Fibonacci sequence up to 50, and quizzing the user on it.  Here's how I might write that:

# Init Fibonacci sequence up to first value past 50 (shfifty-five)
fib = [0, 1]
while fib[-1] <= 50:
    fib.append(fib[-2] + fib[-1])

# Prompt the user for all those values (after the initial 0, 1)
for n in fib[2:]:
    try:
        if int(input('Enter the next Fibonacci number >')) != n:
            raise ValueError('not the next Fibonacci number!')
    except ValueError:
        print('Try again')
        break
else:
    print('Well done')

Now the code is in two smaller parts that are each a lot simpler than the previous version -- the first few lines compute the Fibonacci sequence in a very straightforward way, and the rest of the code simply iterates over the sequence and checks the input against it.

In a larger project you'd probably take these two "chunks" of code and define them as functions (you'd have one function that generates the sequence and another that handles the quizzing), but even within a function it's valuable to think about how you can break a problem does into distinct simple parts (and once you've done that, the next step of refactoring it into smaller functions becomes easy).


Backing up two tables using SQL transactions

First of all, you don't check @@ERROR after deleting which is not a good idea.

Second, you don't need to name transactions, but you can if you want to. Although, I'd recommend to avoid the same naming as you use for tables. For example, Table1_Backup is preferable in this case.

Let's make it more readable and compact. We have two ways.

1. XACT_ABORT

If you SET XACT_ABORT ON, transaction will automatically roll back on every run-time error.

SET XACT_ABORT ON

BEGIN TRANSACTION
    INSERT INTO [Table1_BU] SELECT * FROM [Table1] ORDER BY ID
    DELETE FROM Table1
COMMIT TRANSACTION

BEGIN TRANSACTION
    INSERT INTO [Table2_BU] SELECT * FROM [Table2] ORDER BY ID
    DELETE FROM Table2
COMMIT TRANSACTION

SET XACT_ABORT OFF

2. TRY ... CATCH

Second approach is to get it under control.

BEGIN TRY
    BEGIN TRANSACTION
        INSERT INTO [Table1_BU] SELECT * FROM [Table1] ORDER BY ID
        DELETE FROM Table1
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH

-- and, of course, the very same for the second table


Composing functionality of sealed class with interfaces

It depends on the actual class requirements along with the overall code factors.
For instance,

Do you think that Client class can be extended in the future? (not by inheritance surely since it's sealed).
How often this class is going to be called?
How simple you need to simplify the initiation of this class? (as a way to automate handling of its dependencies)
Are these interfaces going to be recalled or extended in any other way except this class ?
Do interfaces have many unneeded members? (say you only need some members and not all of them).

You must investigate that, and decide the best approach that would be feasible to your current project.
As kick-starter that would give you some ideas after looking at your class, and interfaces, without knowing your actual implementations, I could say the safest way is to create ClientHandler and pass it to the constructor instead. something like this :
public class ClientHandler : ITickProvider, ICommandReceiver
{
    private readonly Simulation _simulation;
    public ClientHandler(Simulation simulation)
    {
        if(simulation == null)
        {
            throw new ArgumentNullExecption(nameof(simulation));
        }
        _simulation = simulation;
    }

    // ITickProvider implementation
    // Do the handeling here
    public void Tick() { ... }

    // ICommandReceiver implementation
    // Do the handeling here
    public void CommandReceived() { ... }
}

public sealed class Client
{
    private readonly ClientHandler _handler;

    public Client(ClientHandler clientHandler)
    {
        if(clientHandler == null)
        {
            throw new ArgumentNullExecption(nameof(clientHandler));
        }

        _handler = clientHandler;
    }
}

This is better, because you'll have more room in your code to be able to control the handler and the client side-by-side, with a benefit of extending the handler as per requirement. Also, Implementing interfaces would ease your work, especially if your work includes Reflection. You can also keep the handler as abstract class and inherit it to have more customizable handlers.


Weather application data structures and design

About the HTML

You shouldn’t use heading elements (h1-h6) like that. These elements give the heading for the section they create. Don’t use them for the name in simple name-value items, nor for stand-alone content (where no other content in the section exists).

You could represent each day as a section:

A section should ideally have a heading (and it’s the only one needed in this case). I think it makes the most sense to use the day+date as heading. The time element can be used to mark up the date in a machine-readable way. The abbr element can be used to give the full name of the day.

Sun <time datetime="2017-12-31">Dec. 31</time>

The forecast can be given in a p. As the img seems to convey the same content, it’s correct to keep the alt attribute empty.

clear sky

While you could use a list for the temperatures, I think three p elements are sufficient in this simple case.

14 °C

High: 20 °C

Low: 6 °C

When using a label for the first temperature, too, I would go with a dl element instead:

Current

14 °C

High

20 °C

Low

6 °C

So, an entry for a day could look like this:

Sun <time datetime="2017-12-31">Dec. 31</time>

clear sky

14 °C

High: 20 °C

Low: 6 °C

or with dl:

Sun <time datetime="2017-12-31">Dec. 31</time>

clear sky

Current

14 °C

High

20 °C

Low

6 °C


Finding the number of integers between 1 and K, who's sum of the digits is a multiple of D

There's probably a more efficient method, but I can't think of one at the moment. A few suggestions, though:

Why do you have a badly-named variable hello that is only used once? I'd recommend inlining it.
There's no need for parentheses around the condition for the if statement.
There's no need to convert the map to a list before finding the sum.
You could convert the loop into the sum of a generator expression.
It's probably a good idea to convert your code to have a main function and an if __name__ == '__main__' guard.

Result (not tested):

def perform_calculation(k, d):
    return sum(sum(map(int, str(i))) % d == 0 for i in range(1, k+1))

def main():
    k = int(input())
    d = int(input())

    print(perform_calculation(k, d))

if __name__ == '__main__':
    main()


Python has a number of templating options, but the simplest to start is probably the string.Template one described in https://docs.python.org/3/library/string.html#template-strings

This supports targets such as $StockId and is used as below

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

If you need more output options, look at the string.format functionality, but this is probably best for starting with.