99 bottles of beer on the wall in Python 3

You have the wrong version of 99 bottles of beers
Global variables are bad except for constants (and some special cases)
print() is equal to print('') but there are two other amazing solutions.
If you come from another language, forget all you know about loops

1.

Ok the first fix is easy, just add:

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.

to the end

2.

The second is very important for all your future projects. Use arguments instead of global variables. Using globals is only ok if you define constants of if your script is short, but as soon as your project grows, it will become unmanageable. Globals are also less performant than locals because locals can only be modified in the function itself, that permits the compiler to do assumptions which can't be done with globals. Avoid globals as much as possible.

3.

print('hello')
print('')
# is the same as
print('hello', end='\n') # '\n' is a newline which is the default
print()
# which is the same as
print('hello')
print()
# which is the same as
print('hello', end='\n\n')
# which is the same as
print('hello\n')
# which is the same as
print('he', end='llo')
print()
print()

In summary, either use end='\n\n' or append \n to your string.

4.

In Python, there is this concept of iterable, for i in range(start, end, step) is the way you do the classic looping over integers. range(10) is an iterator that will take all the values from 0 to 9, you know what, lists, tuple, dictionaries files, and even strings are iterables for i in 'babar': print(i). That's why while loops are less used in python, it is because iterables are cool, don't use a while.

def bottles():
    for i in range(99, 1, -1):
        print(f"{i} bottles of beer on the wall, {i} bottles of beer.")
        print(f"Take one down, pass it around, {i-1} bottles of beer on the wall\n")
    i -= 1
    print(f"{i} bottle of beer on the wall, {i} bottle of beer.")
    print("Take it down, pass it around, No more bottles of beer on the wall.\n")
    print("No more bottles of beer on the wall, no more bottles of beer.")
    i = 99
    print(f"Go to the store and buy some more, {i} bottles of beer on the wall.\n")
    bottles() # remove this line if you don't like beers

bottles()

Update:

Apparently, OP can't use numbers, this version doesn't contain numbers:

def bottles(count):
    for i in reversed(range(count+True)):
        s='s' if i-True else ''
        print(f"{i} bottle{s} of beer on the wall, {i} bottle{s} of beer.")
        if not i-True: break
        print(f"Take one down, pass it around, {i-1} bottle{s} of beer on the wall\n")
    print("Take one down, pass it around, no more bottles of beer on the wall\n")
    print("No more bottles of beer on the wall, no more bottles of beer.")
    print(f"Go to the store and buy some more, {count} bottles of beer on the wall.\n")
    bottles(count)  # If you don't want to go to the store and buy some more remove this line

bottles(99)
```


LeetCode: Increasing Order Search Tree C#

There isn't much to review. InOrder() is merely a depth-first-search, so maybe I would call it that.

You could though optimize a bit, if you created the new "tree" as you traverse the old one:

  public class InOrderForEach
  {
    TreeNode newRoot = new TreeNode(0);
    TreeNode current = null;

    public TreeNode IncreasingBST(TreeNode root)
    {
      if (root == null)
      {
        return null;
      }
      current = newRoot;
      InOrder(root);
      return newRoot.right;
    }

    private void InOrder(TreeNode root)
    {
      if (root == null)
      {
        return;
      }
      InOrder(root.left);
      current = current.right = new TreeNode(root.val);
      InOrder(root.right);
    }

  }


As with every performance question: run your code through a profiler

That said, your ShouldNotLog method can be simplified.  There is not much reason to check your auto subscribe list prior to checking your suppress list:

_shouldNotLogs is a shorter list
presumably, none of the strings in _shouldNotLogs should exist in _shouldAutoSubscribe

As a result, checking _shouldAutoSubscribe only adds extra work.  The only times you perform fewer operations is if the input name matches one of the first three elements in _shouldAutoSubscribe.  It's a wash at four.  Anything else is extra work.

This leaves us with the following:

    public bool ShouldNotLog(string telemetryName)
    {
        return _shouldNotLogs.Any(s => telemetryName.IndexOf(s, StringComparison.Ordinal) >= 0);
    }

Next, for readability, I would instead use string.Contains.  If you check the .NET source, string.Contains calls string.IndexOf internally with an Ordinal check, so it is effectively the same thing, but it declares your intent far better:

    public bool ShouldNotLog(string telemetryName)
    {
        return _shouldNotLogs.Any(s => telemetryName.Contains(s));
    }

If possible, though, an even better way of doing it would be to extract your telemetry names to some numerical ID and use enums or ints.  Number comparison will be far quicker than string comparison.  However, you state that your input names are superstrings of those appearing in your lists, so I don't know if that is feasible.


Function to return last line's length of a string

It's good that you've used strlen, but there's actually another standard function that could be useful here. Instead of your reverse loop, you can use strrchr to find a pointer to the last occurrence of a character (or NULL if said character is not found). As discussed in the comments, this could be (and likely is) slower in the case when a newline is not found, but unless this function is called very often or is in a very performance critical path, I can't imagine it will be an issue. If you do need to optimize it to your original implementation, I would pull the reverse loop logic out into a function.

Anyway, a bit of a review:

Your string parameter should be a pointer to const since it's not modified.
Personal style thing: I'm not a fan of return (...). If it matters, it also tends to be pretty rare style wise in C.
You should probably explicitly document what happens if a line break is not found in the text. I wouldn't be sure whether strlen(string) or -1 we be returned.


I have never used it before but I think what you are looking for is CHARINDEX I found a StackOverflow Answer that has several upvotes and no downvotes using it like this

WHERE CHARINDEX('
', Body) = 0

So far from what I have seen they are relatively close to the same speed, and is giving the same results as your query.

I would much rather read this than Body not like '%
%'

I think we have found a new "hammer", let's find some nails.

Read more about CHARINDEX Here

There is also a CONTAINS function in T-SQL, but unfortunately it cannot be used on that column of that table because the column is not Full-Text Indexed

Read more about CONTAINS Here


Yes, you have overcomplicated things. But it's nothing dramatic.

First, you defined a two-dimensional table for getting the name of a day. You can replace this with a one-dimensional array.

const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

With this definition, you can just say dayNames[pointer] instead of your current dayNames[pointer][pointer].

The for loop should be of the form for (let i = 0; i < 3; i++) { }, which is the idiomatic form of saying three times.

const today = (new Date()).getDay();
const nextDays = [];
for (let i = 0; i < 3; i++) {
  nextDays.push(dayNames[(today + 1 + i) % dayNames.length]);
}

This counts i from 0 to 2. At first it may feel a bit easier to let i count from 1 to 3 instead, making the + 1 unnecessary. Amongst experienced programmers, almost all loops start at 0 though, so whenever you start a loop at a nonzero number, you will confuse them a little bit.


Grouping a dictionary of lists based on  % key and the first value in the list

1. Review

There's no docstring. What does groupCount do? The text in the post explains it very clearly, so using this would be a good start.
groupCount has two responsibilities: (i) it collates the input into groups, and (ii) it prints the collated results. The trouble with combining responsibilities like this is that it makes it hard to reuse the code. If you need to use the groups in other code, how do you get them? If you want to write automatic test cases, how do you do that? It would be better to split the grouping and printing code into separate functions. (This is the "single responsibility principle".)
This code iterates over the indexes in the sequence counts and then looks up the item using counts[i].

for i in range(len(counts)):
    # code using i and counts[i]

Python provides the function enumerate for simultaneously iterating over items and their indexes:

for i, count in enumerate(counts):
    # code using i and count

For collating items based on their keys, it is handy to use collections.defaultdict, like this:

groups = defaultdict(list)
for i, count in enumerate(counts):
    groups[count].append(i)

To split a sequence into groups of length \$n\$, there's a well-known trick that's described in the documentation for zip, where it says:

  This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

There is no need to pass a key function to sort. Sequences are compared lexicographically by their items, and because we know that all the items are different, the comparison will never have to look past the first item.

2. Revised code

from collections import defaultdict

def group_by_count(counts):
    """Given a sequence of group sizes for each item, return a list of
    groups, each group being a tuple of indexes of items.

    >>> group_by_count([3, 3, 3, 3, 3, 1, 3])
    [(0, 1, 2), (3, 4, 6), (5,)]

    """
    groups = defaultdict(list)
    for i, count in enumerate(counts):
        groups[count].append(i)
    result = []
    for count, group in groups.items():
        result.extend(zip(*[iter(group)] * count))
    return sorted(result)

(Note the example in the docstring: this can be automatically checked using the doctest module.)


Translating sentences with an API wrapper

Dobra robota, tak trzymaj.

Your code is rather good code:

Docstrings, yay;
PEP 8 compliant (except a missing second blank line before if __name__ == '__main__');
Custom exception for the module;
Not executing top-level code on imports;
Sensible defaults;
Readable.

However, it's rather WET and you've got a silly rookie mistake.

Bug

Reading the docstring above, I'm pretty sure if source and target in self.supported_languages: is not checking what you intended to check.

This is parsed as if source and (target in self.supported_languages): which checks for the truth value of source rather than its existence in the self.supported_language dictionary.

Instead you could write:

def _get_translate_direction(self, source, target):
    """Raise an exception if source and target language are not currently
    supported by the Yandex Translate API.
    """
    if target not in self.supported_languages:
        raise YandexException('language target \'{}\' not supported'.format(target))
    if source is None:
        return target

    if source not in self.supported_languages:
        raise YandexException('language source \'{}\' not supported'.format(source))
    return '{}-{}'.format(source, target)

DRY it up

Each of the 3 method communicating with the API reuse the same exact structure and mostly share 7 lines in common. You could extract that to simplify things:

def _get_api_response(self, endpoint, payload):
    try:
        response = self._session.get(self.URL + endpoint, params=payload)
        if response.status_code != 200:
            raise YandexException(response.json())
        return response.json()
    except ConnectionError:
        raise YandexException('API unavailable')

@property
def supported_languages(self):
    payload = {
        'ui': 'en',
        'key': self.api_key
    }
    return self._get_api_response('getLangs', payload).get('langs')

def translate(self, text, target='en', source=None):
    translate_direction = self._get_translate_direction(source, target)
    payload = {
        'text': text,
        'format': 'plain',
        'lang': translate_direction,
        'key': self.api_key
    }
    return self._get_api_response('translate', payload).get('text')[0]

def detect_language(self, text):
    payload = {
        'text': text,
        'format': 'plain',
        'key': self.api_key
    }
    return self._get_api_response('detect', payload).get('lang')

Improvements

I’m not sure why you chose to .get elements out of the JSON response rather than accessing them directly with ['lang'] or ['text']: in case the API doesn't respond with the expected JSON, you won't figure it out. Worse, it will crash on other parts of the code with no obvious reasons.

For instance, if the getLangs call does not return a dictionary with a 'langs' key, response.json().get('langs') will return None. This will make the checks target in self.supported_languages raise TypeError because None is not iterable. This is not ideal. You should either:

access the key directly and catch the KeyError to throw your own exception;
or use a default value in your .get calls that is compatible with what is expected later.

For the second option, I'd use:

return self._get_api_response('getLangs', payload).get('langs', {})
return self._get_api_response('translate', payload).get('text', [None])[0]
return self._get_api_response('detect', payload).get('lang')

For the last two, None seems valid as it convey the "I couldn't detect/translate" meaning.

An other improvement I would make is to cache the returned value of supported_languages as there is very few chances that it changes during the lifespan of the application. I’d use functools.lru_cache for that:

from functools import lru_cache

class Yandex:
    ...
    @property
    @lru_cache(maxsize=1)
    def supported_languages(self):
        payload = {
            'ui': 'en',
            'key': self.api_key
        }
        return self._get_api_response('getLangs', payload).get('langs', {})

I chose a maxsize of 1 because there is little to no chance that more than 1 Yandex object get instanciated in a given application.

Lastly, I’m not aware if Yandex provide a sandboxed environment with some kind of public key that anyone can use with restrictions on the amount of requests, for instance. But if they do, it could be a great addition as a default value for the constructor.


Replace anchor tags with spans, and place the href attribute into the span

One thing to consider is the whole working with HTML as string. In the answer I'll assume you work within the web-browser. The web-browser can parse the HTML for you, this way you'll only have to work with nodes.

Here is an example:

const testHtml = `

This is a test paragraph

  Google is here
  Msn is here

This is a heading

`;

function transformLinksToTextOnly(htmlString) {
  const root     = document.createElement('root');
  root.innerHTML = htmlString;
  const anchors  = root.querySelectorAll('a');

  anchors.forEach(anchor => {
    const span = document.createElement('span');

    span.innerHTML = anchor.innerHTML;
    if (anchor.href)
      span.innerHTML += ` (${anchor.href})`;

    anchor
      .getAttributeNames()
      .forEach(attrName => {
        const attrValue = anchor.getAttribute(attrName);
        span.setAttribute(attrName, attrValue);
      });

    anchor.parentNode.replaceChild(span, anchor);
  });

  return root.innerHTML;
}

const result = transformLinksToTextOnly(testHtml);

document.body.innerHTML += testHtml;
document.body.innerHTML += '
';
document.body.innerHTML += result;


You could just go:

export CXXFLAGS=-std=c++14 -Wall -Wextra -Werror -Wpedantic -pedantic-errors

Then at any point you want to compile:

make plop.cpp

This will build the executable plop. Use the CXXFLAGS and does NOT need a makefile.

If you want to keep your function, I would allow people to override the defaults using the environment:

function compile-cpp {

    if [ -z "$1" ]
    then
    {
        echo "Need a file to compile as argument."
    }
    else
    {
        # extract file name from path
        filename=$(basename "$1")

        # cut the extension
        filename="${filename%.*}"

        # compile
        if [ -z "${VERBOSE}" ]
        then
        {
            # Normally just want to see the file that is being compiled.
            echo ${CXX:-g++} $1 -o ${filename}
        }
        else
        {
            # But if things are going wrong then you want to see the full command LINE.
            echo ${CXX:-g++} $1 ${CXXFLAGS:-'-std=c++14 -Wall -Wextra -Werror -Wpedantic -pedantic-errors'} -o "$filename"
        }
        fi
        ${CXX:-g++} $1 ${CXXFLAGS:-'-std=c++14 -Wall -Wextra -Werror -Wpedantic -pedantic-errors'} -o "$filename"
    }
    fi

}

Here:

${CXX:-g++} means if the environment variable is empty or null use `g++`
            otherwise use the value of `${CXX}`.

Same for the `${CXXFLAGS}`

I would prefer using the make technique, as this provides you all the facilities of Make in addition to the compiler (so it checks file date stamps) and other stuff.

## Use the fortran compiler for shits and giggles
CXX=fortran compile-cpp plop.cpp
VERBOSE=1 compile-cpp plop.cpp


Reading transactions from a file and writing them to a database table

Connection

You get your connection with the standard mysql.createConnection method. OK, but you also use bare JSON sub-fields to initialise it. What if they're not there? You're going to get a ReferenceError whent the call tries to access it. I'd advise checking that and logging the mistake.

function createDatabaseConnection(properties) {
    if(properties.host && properties.user && properties.pass && properties.database) {
        return mysql.createConnection({
            host: properties.host,
            user: properties.user,
            password: properties.password,
            database: properties.database
        });
    }
    else {
        console.log("Could not retrieve all required details to connect to the database.");
    }
}

var connection = createDatabaseConnection(connectionProps);

Naming

There are a few - not many - places where your naming could be better.

checkErr - you could name this handleErrors, which would reflect slightly better what it does.
Table names - are your tables really called TRANSACTION_TYPES, all caps? If they are, OK, there's no standard, but if you're only doing it to match the SQL caps style, you shouldn't be.
typeNameToId- that reads like a method name. Perhaps call thistypeIds`?

Magic arguments

process.argv[2] - how do you know that what you want is always argument number 3? This might be a good point to look at implementing switches on the command line. You seem to be getting a file name here, perhaps you should use -f filename as the switch.

You've also got a number of array accesses which are done with magic numbers, though that's more common and not a massive issue.

Query errors

In your second query:

connection.query(
  'INSERT INTO TRANSACTION (DESCRIPTION, AMOUNT, TRANSACTION_TYPE_ID, TRANSACTION_DATE) VALUES ?',
  [data],
  function(err) {
    connection.end();

    if (err) {
      throw err;
    }
  }
);

You're redefining how you handle errors. If you simply pass a reference to checkErr (or whatever you've called it, by then) as the third argument instead of the function, you get consistent error handling. I notice your method definition here is different to that in checkErr - is there a reason you're closing the connection before checking if the error actually exists this time?


Monitor webserver accessibility inconsistencies

The concept in your code is fundamentally good, but there are a few things I would recommend you change.
Static initializers
First up, I like static initializer functions when the static component is non-trivial. So, for example, this code:

private static final Logger logger = Logger.getLogger("MonitoringLogger");

public static void main(String[] args) throws MalformedURLException, IOException, InterruptedException {
    configureLogger();
    ......
}

private static void configureLogger() throws IOException {
    FileHandler fh;
    fh = new FileHandler("logfile.log");
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.info("Logger initialized");
}

I would replace with:
private static final Logger logger = configureLogger();

private static Logger configureLogger() {

    try {
        Logger logger = Logger.getLogger("MonitoringLogger");
        FileHandler fh;
        fh = new FileHandler("logfile.log");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
        logger.info("Logger initialized");
        return logger;
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not get logger up.", ioe);
    }
}

That's a 'trivial' change, but it puts the initialization sequence of the code in to a much more structured system.
What to log.
You don't really want to be logging what the sites are showing, you want to be logging their response times. I suggest pulling different metrics than the ones you are getting..... How long it took for the repsonse to come, and whether it was successful, or not. A log that looks like:

2015-07-22 12:23:34 [INFO] 3ms response from http://alpha:11480/AlphaApplication-war/
2015-07-22 12:26:12 [INFO] 3984ms response from http://alpha:11480/AlphaApplication-war/
2015-07-22 12:29:49 [ERROR] 5000ms TIME OUT FROM http://alpha:11480/AlphaApplication-war/

That would be much easier to process.
To do that, you will want to measure the actual times, not the responses... and you will pick up slow-to-respond servers too (perhaps a big garbage collection, over-congested network handler, or something).
So, create a function that has a response, which should be an Object:
private static final class ServerStat {
    private final boolean success;
    private final long milliseconds;

    ServerStat(boolean success, long milliseconds) {
        .....
    }
}

and then a function that tests an HTTP URL:
public static ServerStat pingServer(URL host) {
    long start = System.currentTimeMillis();

    boolean ok = false;
    try {

        URLConnection connection = url.openConnection();
        try (InputStream stream = connection.getInputStream()) {

            byte[] buffer = new byte[4096];
            while (stream.read(buffer) >= 0) {
                // throw the data away
            }
        }
        // no exceptions
        ok = true;
    } catch (Exception e) {
        // swallow any exception
    }
    return new ServerStat(ok, System.currentTimeMillis() - start);
}

Now, you have a function which times how long it takes to get a complete response (or fail) from a server.
Now, instead of having an infinite while-loop, have a non-daemon scheduled thread executor instead. Something like:
    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
    ses.scheduleAtFixedRate(() -> pingServerList(totest), 0, 5, TimeUnit.SECONDS);

That runs a function every 5 seconds.
I put it all together like this:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PingServer {

    private static final class ServerStat {
        private final boolean success;
        private final long milliseconds;
        private final String message;

        ServerStat(boolean success, long milliseconds, String message) {
            this.success = success;
            this.milliseconds = milliseconds;
            this.message = message;
        }
    }

    public static ServerStat pingServer(URL url) {
        long start = System.currentTimeMillis();

        boolean ok = false;
        String message = "OK";
        try {

            URLConnection connection = url.openConnection();
            connection.setReadTimeout(3000);
            try (InputStream stream = connection.getInputStream()) {

                byte[] buffer = new byte[4096];
                while (stream.read(buffer) >= 0) {
                    // throw the data away
                }
            }
            // no exceptions
            ok = true;
        } catch (Exception e) {
            message = e.getClass().getName() + ": " + e.getMessage();
        }
        return new ServerStat(ok, System.currentTimeMillis() - start, message);
    }

    public static void main(String[] args) throws IOException {
        List<URL> totest = Arrays.asList(new URL("http://localhost:3000"));
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        ses.scheduleAtFixedRate(() -> pingServerList(totest), 0, 5, TimeUnit.SECONDS);

    }

    private static void pingServerList(List<URL> totest) {
        for(URL url : totest) {
            ServerStat ss = pingServer(url);
            System.out.printf("%tc [%s] %dms %s %s\n", System.currentTimeMillis(),
                    ss.success ? "INFO" : "ERROR",
                    ss.milliseconds, url.toString(), ss.message);
        }
    }

}

and when I run it on my machine, with a test server running (then not running), I get the output:

Wed Jul 22 16:20:51 EDT 2015 [ERROR] 22ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:20:56 EDT 2015 [ERROR] 1ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:21:01 EDT 2015 [ERROR] 2ms http://localhost:3000 java.net.ConnectException: Connection refused
Wed Jul 22 16:21:06 EDT 2015 [INFO] 21ms http://localhost:3000 OK
Wed Jul 22 16:21:11 EDT 2015 [INFO] 8ms http://localhost:3000 OK
Wed Jul 22 16:21:16 EDT 2015 [INFO] 5ms http://localhost:3000 OK
Wed Jul 22 16:21:21 EDT 2015 [INFO] 4ms http://localhost:3000 OK
Wed Jul 22 16:21:26 EDT 2015 [ERROR] 4ms http://localhost:3000 java.net.ConnectException: Connection refused


Check if current time is within the timeframe using Joda-Time

to me it looks like a simple check of number between range of numbers.
do I would do like this

turn hour and minute into one number that is hhmm to simplify the comparison
now its a simple check between range of numbers, taking into account the case of cross-date boundary

complete code:

private static void checkTimeframe(int startHour, int startMinute, int endHour, int endMinute) {
    // "concatanate" hour and minute into one number
    int startHourMinute = startHour * 100 + startMinute;
    int endHourMinute = endHour * 100 + endMinute;
    LocalDateTime now = LocalDateTime.now();
    int nowHourMinute = now.getHour() * 100 + now.getMinute();

    // if range within date - simple between boundaries check
    if (startHourMinute <= endHourMinute) {
        if (nowHourMinute >= startHourMinute && nowHourMinute <= endHourMinute) {
            System.out.println("Ok, we're within start/end");
        } else {
            System.out.println("Outside start/end");
        }
    // else (cross date boundary range) - check if now date is either within range of yesterday or within range tomorrow
    } else {
        if (nowHourMinute >= startHourMinute || nowHourMinute <= endHourMinute) {
            System.out.println("Ok, we're within start/end");
        } else {
            System.out.println("Outside start/end");
        }
    }
}


Banking application - Optimizing java multi-threading code

This code is broken.

Imagine an Account with $100, two threads, one depositing $1, the other withdrawing $50.

Thread one acquired lock1, and begins executing:

this.balance = getBalance() + amount;

and reads $100 ...

Thread two acquired lock2, reads the balance (still $100), subtracts $50, stores the new balance ($50) and releases lock2.

... (back to thread one) ... adds $1, for a total of $101, which it stores in balance.

Free money!  The withdrawal of $50 was forgotten.

You must lock all read-modify-write operations of an object's member with the same lock.


To reduce memory usage you can exploit the mechanics of zip and iter / iterator / generator expression.

Make tmp an iterator.

You can achieve this by changing the brackets from [] to (); changing it from a list comprehension to a generator expression.

You can alternately wrap the list comprehension in an iter call. However that would still be using \$O(n)\$ memory.
In case you don't know what an iterator is, than it's a very useful design pattern.

In short the iterator contains in it some data, and a single method to get the next bit of information. In Python the next function calls this method.

Take the iterator a list provides:

>>> my_data = iter([1, 2, 3, 4])
>>> next(my_data)
1
>>> next(my_data)
2

If you think of zip in terms of iterators, then you'll notice that with two input it works something like:

def zip(a, b):
    while True:
        yield next(a), next(b)

This means if a and b are the same then zip will get the first value and second value in a tuple. Then it will get the third and fourth, until it gets all values.

And so to improve memory usage you can change your code to:

tmp = (int(i) for i in x.split(','))
y = zip(tmp, tmp)

Note: this still runs in \$O(n)\$ space, as x.split() also makes an intermediary list. However it has cut the code from four intermediary lists to just one.

This is a common pattern, as provided in the itertools docs.

  def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

y = grouper((int(i) for i in x.split(',')), 2)


Reusable Unit Of Work Interface / Factory

Leaky Abstractions

public interface IUnitOfWork : IDisposable
{
    void Commit();
}

I like that there's only a Commit method here - it makes the IUnitOfWork interface very well segregated/focused. However the interface specifying that all implementations must also implement IDisposable, is a leaky abstraction - you have a specific implementation in mind, and that implementation is leaking into the abstraction: what if I wanted a mock-up implementation that doesn't need to be disposed?

public interface IUnitOfWorkFactory
{
    IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel);
}

GetUnitOfWork makes it sound like the "factory" is hiding a Singleton or something (the name is reminiscent of "GetInstance") - I like my abstract factories when they expose a single parameterless Create method, and intake their dependencies from the constructor; IsolationLevel is also an implementation detail that's leaking into an abstraction - one specific implementation requires an "isolation level", and that implementation detail is leaked into the abstraction.
I would move : IDisposable to TransactionScopeUnitOfWork, because that specific implementation must implement IDisposable.
Then I'd change the abstract factory interface to look something like this:
public interface IUnitOfWorkFactory
{
    IUnitOfWork Create();
}

And the specific implementation that creates a TransactionScopeUnitOfWork would be responsible for specifying an IsolationLevel:
public class TransactionScopeUnitOfWorkFactory : IUnitOfWorkFactory
{
    private readonly IsolationLevel _isolationLevel;

    public TransactionScopeUnitOfWorkFactory(IsolationLevel isolationLevel)
    {
        _isolationLevel = isolationLevel;
    }

    public IUnitOfWork Create()
    {
        return new TransactionScopeUnitOfWork(_isolationLevel);
    }
}

With IoC Containers such as Ninject, you can easily specify IsolationLevel.Serializable or IsolationLevel.ReadCommitted as needed, depending on whether the factory dependency is being injected into a Smurf or into a FooBar's constructor.
That said I've noticed I seldom need to actually implement an abstract factory with Ninject: you can easily configure DI to inject the result of an anonymous method whenever a class has an IUnitOfWork dependency to be constructor-injected: you just do the binding with .ToFactory and let Ninject do the hard work.
The client code shouldn't be bothered with configuring a transaction isolation level if all it needs to care for is that it's depending on an IUnitOfWork that provides a Commit method; if the client code needs to know about an isolation level, then it knows more than it should about the implementation behind the interface it's presented.


Is brute force the accepted best practice for handling Excel COM 'busy' exceptions?

You're missing the Thread.Sleep(500); call from the linked post's solution, which is much, much better than what you've posted here:

private void TryUntilSuccess(Action action)
{
    bool success = false;
    while (!success)
    {
        try
        {
            action();
            success = true;
        }

        catch (System.Runtime.InteropServices.COMException e)
        {
            if ((e.ErrorCode & 0xFFFF) == 0xC472)
            {   // Excel is busy
                Thread.Sleep(500); // Wait, and...
                success = false;  // ...try again
            }
            else
            {   // Re-throw!
                throw e;
            }
        }
    }
}

(above code from sepp2k's answer here)

  is it not vulnerable to hanging if for some reason it keeps being rejected?

Given that this code is meant to address a COM exception thrown when Excel is busy, it remaining in the loop would mean, well, that Excel is still busy - and possibly hung... in which case, the user will probably lose their patience and kill the application anyway.

The difference between sepp2k's code and the code you're having here, is that you're swallowing all COM exceptions - which is bad. I really don't see a reason not to use the code provided in the post you're following-up on, which filters the error code (if ((e.ErrorCode & 0xFFFF) == 0xC472)) and re-throws all other exceptions, leaving you with a way to exit the loop if you get a COM exception that's saying anything other than Excel is busy.


Separating logic per class and being able to use dependency injection

Without knowing exactly what those classes are supposed to do, I assume it's supposed to work something like (new UserNewState( $this->userRepository ))->handle( $user );. That doesn't look that bad to me.

What other dependencies do you envision your separate State classes are going to need besides the repository?

But perhaps something like a UserStateHandlerFactory is something you could be looking for?

class UserStateHandlerFactory
{
  private $userRepository;

  public function __construct( UserRepository $userRepository ) {
    $this->userRepository = $userRepository;
  }

  public function create( User $user ) {
    switch ($user->state) {
        case 'new':
            return new UserNewState( $this->userRepository );
            break;
        case 'banned':
            return new UserBannedState( $this->userRepository );
            break;
        // ...
    }
  }
}

class UserStateManager
{
  private $userRepository;
  private $handlerFactory;

  public function __construct( UserRepository $userRepository, UserStateHandlerFactory $handlerFactory )
  {
    $this->userRepository = $userRepository;
    $this->handlerFactory = $handlerFactory;
  }

  public function handle()
  {
    $user = $this->userRepository->find(1);
    $this->handlerFactory->create( $user )
                         ->handle( $user );
  }
}

However, I don't know if that makes things much cleaner though. It just looks like another layer of indirection; hiding away, what ultimately has to be done anyway: pass dependencies into the handlers.


Extracting spreadsheet cells using Apache POI

You could extract the content of inner loops to methods with speaking names.

E.g. You could introduce a method like

public static void processSheet(Sheet sheet)
{
  if (sheet.getLastRowNum() > 24) {
      Iterator<Row> rowIterator = sheet.iterator();
      while (rowIterator.hasNext()) {
        row = rowIterator.next();
  ...

}

Within this method you can extract another method e.g.

public static void processRow(Row row){
  for (int j = 23; j < sheet.getLastRowNum(); j++) {
    if (row.getRowNum() == j) {
      if (row.getCell(1) == null || row.getCell(1).getCellType() == Cell.CELL_TYPE_BLANK) {
        break;
    ...

}

And so on until you have only short methods with speaking names. This makes the code easier to read and understand.


Normally I wouldn't recommend creating a class with almost exactly the same name as a framework class (your StopWatch vs the existing Stopwatch), but you mentioned that this is an exercise, so let's ignore that for now.

The basic approach here seems fine: Start stores the start time, Stop stores the end time, and GetTime returns the difference. But there's a bug: GetTime does not work correctly if the stopwatch is still running. In that case, instead of looking at the (incorrect) stop time, it should look at the current time.
Why do Start and Stop take a DateTime as argument? That's something that the stopwatch itself should be doing. If, for some reason, you really must allow calling code to pass in their own times, then your stopwatch class should probably verify that the stop time is not earlier than the start time.
Why does Start throw an exception if the stopwatch is already running? Is that really something that should not be allowed? If so, why is it allowed to call Stop on a stopped stopwatch? I see no real reason for this inconsistency.
If starting a running stopwatch is not allowed, why can't a caller determine whether a stopwatch is running? A read-only IsRunning property that returns _timeRunning would be useful.
As you know, there's already a Stopwatch class in System.Diagnostics, so I would encourage you to look at its source code. You'll see several differences. One in particular is that it remembers the total elapsed time across multiple start/stop calls. Related to that are the Reset and Restart methods, and there's a convenient static StartNew method. It also uses lower-level methods for more accurate timing.


Performance:

if start_list in list_of_existing_nodes:
    point_index=list_of_existing_nodes.index(start_list)
    nodes_list[point_index][1].append(feature["FID"])

This is not an efficient way to update an existing element. The fact that you want to lookup a node based on it's coordinates means that you are using the wrong data structure. A dictionary is explicitly designed to make key-based lookups fast, making this type of manipulation easy. This way you can have the point object as the key and the value would be the data object that might have a FID value.

What you have now will cause each look to iterate over the entire list to see if the node exists. Then when it does, iterate again to find the index. As the number of nodes increase, the lookup will take longer and longer. Using a dictionary will take a constant amount of time independent of how many nodes are in the collection.

def iterate_features(self):
    feature_set = arcpy.SearchCursor(self.Address)
    for feature in feature_set:
        yield feature

def create_new_dict(self):
    iterator = self.iterate_features()
    for item in iterator:
        # ...

This is not providing any benefit. If SearchCursor creates a list, then the list has already been allocated containing all of the values. This means your generator method is just adding additional iteration overhead when switching back and forth between contexts. If SearchCursor is already a generator (which I suspect is the case based on the name cursor), you are just wrapping it without adding any additional values.

Other Points:

coordinates_list is never used, so remove it. Additionally, this is the only case where you use list() instead of [], you should be consistent and use [].

Don't suffix your variables with _list, making the name plural should be sufficient to convey that the value is a collection.

A list is not a great data structure for when each index has specific meaning. If you just need a simple data store object, namedtuple is great for that.

The data you are pulling values from has X and Y attributes. Is there a reason you don't just use that object directly?

Creation of the start and stop point can be cleaned up a lot, even if you stick with lists.

shape = feature["Shape"]
start = [shape.firstPoint.X, shape.firstPoint.Y]
end = [shape.lastPoint.X, shape.lastPoint.Y]

if nodes_list.__len__() is not 0:

should be

if len(nodes_list) == 0:

The built-in function is much cleaner and doesn't depend in the internal implementation.

is is an identity comparison and == is an equivalence comparison. The fact that an identity comparison works is an implementation detail and is not guaranteed to always be true.

Edit:
Since we are dealing with a list, this check is also equivalent to

if not nodes_list:

This is the recommended style by the style guide.

You are performing the same operation for the start and end points. you can create a single function that does the operation instead of repeating the code. When you change to using a dictionary, write the generic function first, then you can call it once for each point.

The naming convention for instance variables is lower_case. Address will make other people think it is a class.


def ackermann(m,n):
    ...
    else:
        print "The Value Doesn't Go into the Domain!"

Printing the error message to standard output looks like a bad design choice (if you code is run automatically and no one is checking the output, it would just silently return None. I don't think you want it). It would more reasonable to throw an exception in this case (I'd throw an instance of the ValueError) because a situation is exceptional (the input is invalid and there's no meaningful way for this function to handle it). Moreover, one function should be responsible for one thing. Your code computes the value of the ackermann's function and does the logging at the same time. It's another reason to handle invalid inputs using exceptions.

You can also simplify the code in the collection function by parsing the input as an integer. There's no point in parsing it as a float and then checking if it's an integer. You could rely on a standard int function to do this job for you. This way, it would be enough to check that both numbers are non-negative.

Now let's talk about variable naming:

collection is a strange name for a function. It's name doesn't give any clue about what it actually does.  Even something simple and generic like read_input would be better.
It's a bad practice to use one variable for two different things. n_val and m_val stand for the user's input as a string and then they turn into integers. I'd rather create two separate variables for each of them (one for the input and the other one for it's integral value).

You use of whitespace is inconsistent. For instance, there's a space after the name of the collection function, but there's none after the name of the ackermann function. Whatever style you choose, you should always be consistent with it (according to the PEP standard, there should be no space after the function name, but there should be one after the comma. I would stick to it unless I have compelling reasons not to).

It's also a good practice to write doc comments for all your functions and classes. The comments inside the code should be more about telling why the code does what it does or why a specific design decision was made. Redundant comments that just tell what the code does create noise and actually make it less readable. For instance, this comment is self-evident:

# Check equivalence to 0 first
if m_val == 0:
    pass

You can just remove it (and all other similar comments). Moreover, if you need to make a comment about what the piece of code does (like "# Then check if the value is nonintegral"), it's a hint that it should probably be implemented as another function with a descriptive name. You should strive for a self-documenting code.


Calling multiple functions in image upload form

Yes, there's room for a lot of improvement here!

First of all, you can "break early" to avoid excessive indentation. Since die terminates the script, you can check if the file is not valid.

Secondly, instead of echoing first and die later, you can call die with a parameter.

This code works in the same way, but is cleaner:

if (!checkvalidfile("img",$ext)) {
    die("Not a valid file");
}
if (!checksize($size, 524288)) {
    die ("File size is too big!");
}

if (!checkdimensions($tmp, 300)) {
    die("Your image can't be bigger than 300 x 300px");
}

$newfilename = renamefile($ext);
recordfileindb($brand_id, $newfilename, $mysqli);
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
header('Location: ./message.php?action=newlogo');


javascript - create an object containing objects based on JSON data

You could dry up this code by adding some helper functions.

For example instead of this:

$scope.gamesSchedule.forEach(function(gameData) {
  var homeTeam = gameData.team1;
  var awayTeam = gameData.team2;
    if (homeTeam) {
        if (!$scope.homeVsAwaySchedules[homeTeam]) {
            $scope.homeVsAwaySchedules[homeTeam] = {
                "Home Games": 0,
                "Away Games": 0
            };
        }
    }
    if (awayTeam) {
        if (!$scope.homeVsAwaySchedules[awayTeam]) {
            $scope.homeVsAwaySchedules[awayTeam] = {
                "Home Games": 0,
                "Away Games": 0
            };
        }
    }
})

You could write using a helper function:

$scope.gamesSchedule.forEach(function(gameData) {
    function checkTeam(team) {
        if (team) {
            if (!$scope.homeVsAwaySchedules[team]) {
                $scope.homeVsAwaySchedules[team] = {
                    "Home Games": 0,
                    "Away Games": 0
                };
            }
        }
    }
    checkTeam(gameData.team1);
    checkTeam(gameData.team2);
})

Similarly, instead of this:

$scope.gamesSchedule.forEach(function(gameData) {
  var homeTeam = gameData.team1;
  var awayTeam = gameData.team2;
    if (homeTeam) {
        if ($scope.homeVsAwaySchedules[homeTeam]) {
            $scope.homeVsAwaySchedules[homeTeam]["Home Games"]++;
        }
    }
    if (awayTeam) {
        if ($scope.homeVsAwaySchedules[awayTeam]) {
            $scope.homeVsAwaySchedules[awayTeam]["Away Games"]++;
        }
    }
})

You could write using a helper function:

$scope.gamesSchedule.forEach(function(gameData) {
    function updateTeamSchedule(team, games) {
        if (team) {
            if ($scope.homeVsAwaySchedules[team]) {
                $scope.homeVsAwaySchedules[team][games]++;
            }
        }
    }
    updateTeamSchedule(gameData.team1);
    updateTeamSchedule(gameData.team2);
})


You can go further by not processing multiples of 3 together with multiples of 2 (even numbers, which you already not process). For stepping on numbers not multiple of 2 and 3, you should take steps of size 2 and 4 alternatively. 5 (+2) 7 (+4) 11 (+2) 13 (+4) 17 ...

This way you will also save space (from n/2 to n/3). You can change your loops like below:

for (int i = 5, t = 2; i < n; i += t, t = 6 - t) {

    if (isPrime [i / 3]) {

        cout<< i << "\n";

        for (int j = i * i, v = t; j < n; j += v * i, v = 6 - v)
            isPrime [j / 3] = false;
    }
}

a little hint is that if don't want to print the prime numbers and want just to generate isPrime array, you can change your outer loop condition to i*i<n, because composite numbers are turned to false by their factor less than their square root.

Another good optimization is that you can use a single bit for storing isPrime flag of each number. This way you can save space by a factor of 1/8, and what is great about this method is that you are increasing your locality of reference and your code will use cache better (when I first wrote sieve by this optimization, amazingly I achieved about 20% speed improvement).


Functionality

Why 31?  Why not 15 or 63 or 42?  If code is to handle 32-bit integers, then use long as that type is at least 32-bit, rather than int, which can be as small as 16.  Alternatives int32_t, int_least32_t.  Even better: re-code for the largest integer type intmax_t.

// Why 31?
for (int i = 31; i >= 0; i--)

Right shifting a negative number leads to implementation defined behavior.  Consider unsigned instead.

// ... (int number)
... (unsigned number)
...
if (number >> i & 1 == 1)

Good that code allows a leading '+'.
Pedantic point.  int overflow is undefined behavior and that is the result of the following with argv[1] == "-2147483648", a string that should "work".

*num = 10* *num + param[i] - '0';

Avoid using printf(some_string).  Should some_string contain a %, maybe due to a code update, that will invoke UB as printf() expects the first arg to be a format string.

// printf(": ");
fputs(": ", stdout);
// or (2nd choice)
printf("%s", ": ");

Do not use argv[1] unless it  is valid

int main(int argc, char *argv[]) {
  if (argc > 1) return handleProgram(argv[1]);
  else ...

Prefer terminating error messages to go to stderr

// printf("\ttoInt()::No number detected, ...
fprintf(stderr, "\ttoInt()::No number detected, ...

Overflow not detected in toInt().

Style

Avoid naked magic numbers.  Consider

// for (int i = 31; i >= 0; i--)
#define INT_WIDTH  32
for (int i = INT_WIDTH - 1; i >= 0; i--)

int toInt() returns only 2 different int.  Consider bool.

Minor

See little value in excessive in vertical spacing throughout code.  Example: The need for a blank line between buys little clarity for the price of a line.

printBinary(number);

state = 0;

Consider parens ()

// if (number >> i & 1 == 1)
if ((number >> i) & 1 == 1)
// or simply
if ((number >> i) & 1)


C# Multiple ASYNC requests single response (Promise like)

Bug
You have a pretty big multithreading issue in your code. When this method can be called from different threads, the MemoryCache doesn't necessarily contain an already created task. Consider the following execution:
Thread 1                     | Thread 2
string cacheKey = ...        |  -
var cachedRequest = ..       |  -
if (cachedRequest != null)   |  -
if (cachedRequest != null)   |  string cacheKey = ...
if (cachedRequest != null)   |  var cachedRequest = ...
TaskCompletionSource tcs =   |  var cachedRequest = ...
TaskCompletionSource tcs =   |  if (cachedRequest != null)
TaskCompletionSource tcs =   |  TaskCompletionSource tcs =
...                          |  ...

The result should be pretty obvious: This way two tasks for the same key can be started. Depending on how strict you need that semantic, that's a problem.
Fixing this is not trivial, but should be simple enough with a lock (_lock) block onto a private static const Object _lock = new Object();
How to Task
In general I'd expect a method that returns a Task<bool> to not actually do the work, as is suggested by //do something long here. Instead the code should submit the work as an Action or something along these lines. Something like that:
Task<bool> result = new Task<bool>(() =>
{
    try
    {
         // do something long here
         return true;
    }
    catch (Exception e)
    {
         return false;
    }
});

this shows an additional problem. The return value of that Task is basically just a flag for successful completion. But you know what? Task already has that: Task.IsFaulted
This makes for a pretty different return value. Use Task instead of Task<bool>, because it removes redundancy.
Back to the code: We're still not quite there with the lookup and caching mechanics.
CacheItemPolicy cip = new CacheItemPolicy()
...
MemoryCache.Default.Set(cacheKey, result, cip);

This is for the caching, now we just need to clean the cache when we're finished:
result.ContinueWith(() => MemoryCache.Default.Remove(cacheKey));
result.Start(); // actually start doing work
return result;


Creating ShortCut (RightClick) Menus in Access

As you already noticed, all the CreateSomething methods have the same repeating pattern. We can extract this pattern and encapsulate it in a method for reuse :

Private Sub CreateCommandBar(name As String, ParamArray buttonIDs() As Variant)
    Dim menu As Office.CommandBar
    Set menu = CommandBars.Add(name, msoBarPopup, False)

    For Each ID In buttonIDs
        menu.Controls.Add msoControlButton, i
    Next

    Set menu = Nothing
End Sub

And, CreateFormDataSheetRowClipboardOnly could be written as :

Private Sub CreateFormDataSheetRowClipboardOnly()
    CreateCommandBar "asd", bcCut, bcCopy, bcPaste
End Sub


Is there a better way of showing multiple NSDictionaries?

«Two or more, use a for»
  — Edsger W. Dijkstra

Okay, I am not using a for-loop, but an enumeration

NSArray *itemArray = @[
    @[@"item1",@"item1-Icon",@"item1"],
    @[@"item2",@"item2-Icon",@"item2"],
    @[@"item3",@"item3-Icon",@"item3"],
    @[@"item4",@"item4-Icon",@"item4"]
];

NSMutableArray *items = [NSMutableArray array];
[itemArray enumerateObjectsUsingBlock:^(NSArray *itemProperties, NSUInteger idx, BOOL *stop) {
    [items addObject: @{ @"label":  itemProperties[0],
                         @"icon":  [UIImage imageNamed:itemProperties[1]],
                         @"identifier":  itemProperties[2]
      }];
}];


Unit testing

Hi again @Legato, I'll probably bug you with unit testing until you start writing them ;-)

@Test
public void test_ABbCcc() {
    assertEquals(152, computeMaxBeauty("ABbCcc"));
}

@Test
public void test_This_is_from_Facebook_Hacker_Cup_2013_() {
    assertEquals(551, computeMaxBeauty("This is from Facebook Hacker Cup 2013."));
}

@Test
public void test_Ignore_punctuation__please___() {
    assertEquals(491, computeMaxBeauty("Ignore punctuation, please :)"));
}

@Test
public void test_Sometimes_test_cases_are_hard_to_make_up_() {
    assertEquals(729, computeMaxBeauty("Sometimes, test cases are hard to make up."));
}

@Test
public void test_CodeReview_is_love__CodeReview_is_life_() {
    assertEquals(724, computeMaxBeauty("CodeReview is love. CodeReview is life."));
}

The first implementation

It's good that the logic is decomposed to 2 methods (as opposed to not decomposed at all).

The printMaximumBeauty method converts the input string to char[].
I think it would be better to pass the string to computeMaximumBeauty and let it do whatever it wants with it.
For the record, there's a trade-off when converting to a char[] as opposed to accessing characters with .charAt(index):

Converting to char[] creates a new array, so doubles the space
Accessing characters with .charAt(index) incurs a boundary check every time

The computeMaximumBeauty method is very inefficient:

It iterates over the characters once to find unique ones
For each unique character it iterates over the characters again to count

You could combine these two steps.

You also incur some performance penalty due to autoboxing / unboxing, but that may be negligible.

Lastly, don't declare variables at the top. Java is not C.
Declare variables the latest possible, and in the smallest scope possible.
For example count could be declared in the for loop where it's used,
and then you wouldn't need to reset it in every cycle.

The second implementation

This method counts the appearances better, by doing it one pass.
Note that this line will do two map lookups when c is already in the map:

beautyMap.containsKey(c) ? beautyMap.get(c) + 1 : 1

First in .containsKey, then again in .get.
To reduce the lookups, you can do one .get and a null-check.

When calculating the beauty, you iterate over entries, but use only the values:

for (Map.Entry<Character, Integer> e : valueSorted.entrySet()) {
    beauty += e.getValue() * beautyVal++;
}

If you don't need the keys, then it would be better to iterate over the values instead of the entries.
And if you don't need the keys here, then probably you don't need them at all.
So instead of a map, a list would have been enough, and probably simplify your logic.

This implementation also declares variables at the top, which is not so good.
And it also incurs some performance penalties due to autoboxing / unboxing.

Suggested implementation

Here's an alternative implementation that's simpler.
It uses the fact that there can be at most 26 unique values,
so the appearance counts can be stored in a simple int[].

private int computeMaxBeauty(String text) {
    String sanitized = text.replaceAll("[^a-zA-Z]", "").toLowerCase();

    int[] counts = new int[26];
    for (int i = 0; i < sanitized.length(); ++i) {
        ++counts[sanitized.charAt(i) - 'a'];
    }

    Arrays.sort(counts);

    int sum = 0;
    for (int i = 25; i >= 0 && counts[i] > 0; --i) {
        sum += counts[i] * (i + 1);
    }
    return sum;
}


Better string copy
You are over-complicating your string duplication. There is an easier way to do it using memcpy. First, simply copy the string:
memcpy(s3, s2, len2);

Then, simply copy the string again (this time, with an offset):
memcpy(s3 + len2, s2, len2);

Notice how the second copy doesn't have - in the last argument. With it like this, you do not have to manually copy the null character over afterwards as it will use the null character from s2.
Note that you can not do this as easily with strcpy as this function will copy the entire string, including the null character.

Not true substring
Your isSubstring function doesn't actually find the substring of a string very well. Take these two strings as an example:

abec abc

Your function would return true to these if these were passed in in this order. A simple fix to this would be to reset j to 0 every time a character is encountered that is not the right one.
while(s1[i] != '\0')
{
    if(s2[j] == s1[i]) {
        j++;
    } else {
        j = 0;
    }

    i++;
}

Misc

Returning bool

return 0;

Why are you returning a number from a bool-returning method?

Clear up the for loop

int j = 0;
...
for(size_t i = 0; i < (2*len2); i++)
{
    ...
    j++;
}

This is somewhat confusing. You should move the j declaration right above the for loop, and move the incrementing into the signature.

Refactor
The string duplication logic should be moved into an external function as to spread out the logic and make sure that every function is only doing what it needs to do and nothing else.

Braces
Always use them, even around single-line statements. They make your code more maintainable and less error-prone.

While to for loop
This:

int j = 0;
int i = 0;
while(s1[i] != '\0')
{
    if(s2[j] == s1[i])
        j++;

    i++;
}

Can be written more cleanly as a for loop:
for(int i = 0, j = 0; s1[i] != '\0'; i++) {
    if(s2[j] == s1[i])
        j++;
}


First of all, I think there is an off-by-one error in your code. From my understanding of the question, the correct output for

var tweetsPerSecond = new[] { 1, 3, 2 };
var windowSize = 1;

would be { 1, 3, 3 }, while your code gives the answer { 1, 3, 2 }.

Also a window size of 0 throws a NullReferenceException.

While there are minor stylistic complaints I would focus on in a normal code review, I believe the bigger picture is that you are using the wrong data structures for this problem.

You are duplicating the information stored in tweetsPerSecond, an array, in a linked list. You don't need this duplication, you can just index into the array.

Second, to find the maximum in a range in the array, you are iterating through the entire range. Using a skip list would change this from an \$O(n)\$ operation to an \$O(1)\$ operation, with adding and removing elements being \$O(\log n)\$.

Assuming an implementation of a SkipList<T> class, the algorithm would look like this:

public static IEnumerable<int> TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    var size = windowSize + 1;
    var skipList = new SkipList<int>(size);
    for (var i = 0; i < tweetsPerSecond.Length; i++)
    {
        if (skipList.Count == size)
        {
            skipList.Remove(tweetsPerSecond[i - size]);
        }

        skipList.Add(tweetsPerSecond[i]);
        yield return skipList.Last;
    }
}

If you don't want to go to the trouble of implementing a skip list, I think you can fake it with a combination of SortedSet<T> and Dictionary<TKey, TValue>. I couldn't find guarantees of the run time of the relevant operations on MSDN, but it runs much faster on this test input:

var tweetsPerSecond = Enumerable.Range(0, 100000).Reverse().ToArray();
var windowSize = 10000;

Here is the sample code (possibly buggy):

public static IEnumerable<int> TweetsPerSecond(int[] tweetsPerSecond, int windowSize)
{
    var size = windowSize + 1;
    var bag = new SortedBag<int>();
    for (var i = 0; i < tweetsPerSecond.Length; i++)
    {
        if (i > windowSize)
        {
            bag.Remove(tweetsPerSecond[i - size]);
        }

        bag.Add(tweetsPerSecond[i]);
        yield return bag.Max;
    }
}

private class SortedBag<T>
{
    private readonly Dictionary<T, int> count = new Dictionary<T, int>();
    private readonly SortedSet<T> set = new SortedSet<T>();

    public void Remove(T value)
    {
        count[value] = count[value] - 1;
        if (count[value] == 0)
        {
            this.set.Remove(value);
            this.count.Remove(value);
        }
    }

    public void Add(T value)
    {
        int occurrences;
        if (this.count.TryGetValue(value, out occurrences))
        {
            this.count[value] = occurrences + 1;
            return;
        }

        this.count[value] = 1;
        this.set.Add(value);
    }

    public T Max
    {
        get { return this.set.Max; }
    }
}

Edit: there's a better solution with \$O(n)\$ complexity. I had great fun thinking about this problem, and would recommend anyone reading this post to think it through further before clicking that link.


Click handlers for edit and save buttons

A few notes:

Always use .slice over .substring (Yes .slice works on strings.), it will support negative selection af strings, eg "abc".slice(0, -1) // "ab"
Storing reused values / objects in variables cleans up the code a lot, eg:

var a = $(this).find('.element').attr('a');
var b = $(this).find('.element').attr('b');
// The above can be written as:
var $element = $(this).find('.element');
var a = $element.attr('a');
var b = $element.attr('b');
// This is faster and is IMO easier to read.

Meaningful variable names, dont use names like seira when you are referring to an index in an array call it index or list_index etc. (I assume its meaningful in another language but IMO all code should be written in english with english comments, and english variable names.)

Code:

$(document.body).on('click', '.edit', function() {
    var $a = $(this).closest('a');
    var list_id = $a.data('list');
    var index = $a.data('order');

    var current_value = navbar_edit[list][index];
    var new_value = prompt('Change Property', current_value);

    navbar_edit[list][index] = new_value;

    exportLists();
});
$(document.body).on('click', '.edit-save', function() {
    var $a = $(this).closest('a');
    var $listGroup = $(this).closest('.list-group');

    var value = $a.text().slice(0, -4);
    var list_id = $listGroup.attr('id').slice(0, -1); // remove last char

    navbar_edit[list_id].push(value);

    exportLists();
});


flag as boolean
If you change the flags from 'Y' and 'N' to True and False You can use boolean indexing. This should speed up a lot of things already
set
You check for each combination word in dest_words for word in source_words on a list of words. If the check matches, you convert to a set. The containment check would be sped up by checking against a list, but using set comparisons would speed this up a lot.
import typing

def partial_match(
    source_words: typing.Set[str], dest_words: typing.Set[str], index=None
) -> typing.Tuple[typing.Any, typing.Optional[str]]:
    intersection = source_words & dest_words
    if intersection:
        return index, ", ".join(intersection)
    return index, None

def exact_match(
    source_words: typing.Set[str], dest_words: typing.Set[str], index=None
) -> typing.Tuple[typing.Any, typing.Optional[str]]:
    if source_words == dest_words:
        return index, ", ".join(source_words)
    return index, None

The reason I chose to return the index along with it is to be able to reconstruct the series easier when reassembling everything.
Don't touch the original data
You change your source data inplace (by adding columns). Better would be to leave this untouched, and keep the destination words etc in separate series.
Series.where
You can replace calls like this
if x['remove_bus_ending'] == 'Y':
        x['dest_words'] = x['dest_words_2']
    else:
        x['dest_words'] = x['dest_words_1']

with Series.where
a = pd.Series(list("abcd"))
b = pd.Series(list("efgh"))
c = pd.Series([True, True, False, True])
b.where(c, other=a)

0    e
1    f
2    c
3    h
dtype: object

If your data looks like this:
from io import StringIO

import pandas as pd

def setify(s):
    return s.str.strip("[]").str.split(", ").apply(set)

df = pd.read_csv(StringIO(data_str), sep="\s\s+", index_col=False, engine='python')
df["source_words"] = setify(df["source_words"])
df["dest_words_1"] = setify(df["dest_words_1"])
df["dest_word_2"] = setify(df["dest_word_2"])
df["remove_bus_ending"] = df["remove_bus_ending"] == "Y"
df["partial_match_flag"] = df["partial_match_flag"] == "Y"
df["exact_match_flag"] = df["exact_match_flag"] == "Y"

intermediate dataframe
If you want to split the dataframe with arraysplit, you'll need to provide an intermediate form with the info you need:
df_intermediate = pd.concat(
    [
        df["dest_word_2"]
        .where(df["remove_bus_ending"], other=df["dest_words_1"])
        .rename("dest_words"),
        df["source_words"],
    ],
    axis=1,
)

You can even split it immediately according to what matching is needed
df_intermediate_partial = df_intermediate.loc[df["partial_match_flag"]]
df_intermediate_exact = df_intermediate.loc[df["exact_match_flag"]]

applying the function
not parallel:
result_partial = list(
    map(
        partial_match,
        df_intermediate_partial["source_words"],
        df_intermediate_partial["dest_words"],
        df_intermediate_partial.index,
    )
)

results_exact = list(
    map(
        exact_match,
        df_intermediate_exact["source_words"],
        df_intermediate_exact["dest_words"],
        df_intermediate_exact.index,
    )
)

result = pd.Series(result_partial + results_exact)

This should be easy to parallelize. Since I'm no expert on that, I'll leave that to others.
context manager
Most of the examples I found in the multiprocessing documantation work with a context manager that takes care of the closing of the pool
with Pool(processes=4) as pool:
    ... # parallel part of the code


Looping through selected cells to indent text

Interesting question,

there is clearly a lack in the Google Script API to indent cells..

Still, I find the CONCAT approach ugly, if one wants to indent 2 times, the formula will be:

=CONCAT(REPT( CHAR( 160 ), 5),"=CONCAT(REPT( CHAR( 160 ), 5),"'Hello World'")")

Which is ugly, I would simply pre-calculate the prefix and concatenate in the script and not let the formula do the work. This will also make un-indenting much easier.


There are quite a few issues here:

In switch statement, you don’t need/want break statements. Unlike C languages, Swift switch statements don’t fallthrough by default. To use break where it is not needed is very unswifty.
I’d make toggleItem an instance method.
The properties of the ViewController should not be static.
This table view controller should not be reaching into ViewController to update its properties, which tightly couples these two classes. We should strive for far looser coupling in our code.

Admittedly, because ViewController is presenting TableViewController, the presenting view controller might go ahead and update properties in the presented view controller, in order to pass data to down the chain. But TableViewController should never be reaching back up the chain. That makes them too tightly coupled and only allows TableViewController to be called from that one view controller, whereas as your app grows, you might want to call it from elsewhere.

The typical solution to achieve loose coupling is the delegate-protocol pattern. Presented view controllers should not updating properties in the presenting view controller, but rather it should only communicate back via its protocol. This allows us to use this presented view controller from wherever we want.
If you’re going to have an early exit in didSelectRowAt (if section ≠ 0), all things being equal, you should prefer guard over if, as it makes the intent more clear (you see guard keyword and you immediately know “oh, this is an early exit for some edge case”). The compiler will also warn us if we accidentally forget to call return.
In if statements, the use of parentheses around the test clause feels a bit unswifty. Consider:

if (state == PastState.UNSELECTED) {
    ...
} else {
    ...
}

Instead, I’d suggest:

if state == PastState.UNSELECTED {
    ...
} else {
    ...
}

In the case of an enumeration, I’d favor switch over if. Thus, instead of the above, I’d suggest:

switch state {
case PastState.UNSELECTED:
    ...

case PastState.SELECTED:
    ...
}

This ensures that the test is exhaustive. It makes it easier to reason about the code at a glance. Plus, if you, for example, later add a .NOTDETERMINED enumeration, the compiler can warn you of all of the non-exhaustive switch statements, but if you use if-else, you have to manually pour through all of your code looking for this yourself.
Because PastState is an enumeration, you can eliminate all of those redundant references to the enumeration name. E.g., using the previous example, you can say:

switch state {
case .UNSELECTED:
    ...

case .SELECTED:
    ...
}

In your enumerations, you should use camelCase (start with lower case letter, only capitalize start of new word within the case name):

switch state {
case .unselected:
    ...

case .selected:
    ...
}

Alternatively, just retire this enumeration altogether and just use a [Bool] property. Or, as shown at the end of this answer, if you use a view model, you might refactor this out completely.
The blacklisted property is using an enumeration, which is good. But flags is using strings with values buried in the code. They both should be enumerations.
The done method is subtracting blacklisted from the ViewController’s allowed. But what if you unselected a blacklisted item and needed to add it back to the allowed? The existing code won’t do that.

The same issue applies for ViewController.flags, where you’re adding flags. But what if one was removed?
You are setting the accessoryView based upon which flags/blacklisted values exist in these sets and toggle this based upon selecting a row. But you then have this UISwitch, too. You’d generally use either a UISwitch or the accessoryView, but not both. Pick one or the other. (In my demo, I’m going to retire UISwitch.)
The references to self.dismiss(...) can be simplified to just dismiss(...).
The didSelectRowAt is:

toggling the indicatorView based upon the old state;
updating the blacklist/flags properties; and
toggling the state.

I would suggest that you simply want to toggle the state and then reload that row. Not only does it make this less fragile (you don’t have three different operations that you need to carefully coordinate), but it affords the opportunity to animate the change of the indicatorView.
I would suggest grouping your view controller methods into extensions. For example, I find it nice to put UITableViewDataSource methods in one extension, UITableViewDelegate methods in another, @IBAction methods in another, etc. This makes it easy to visually identify/find relevant methods. This also allows you to collapse sections (e.g. ⌘+option+◀) sections that you’re not currently working on, making it easy to focus on the work at hand. This, combined with use of the MARK: - designator makes navigation through your view controller easier.
You’ve got an enumeration called PastState. But this is not the “past state”, but rather the current state as updated as the user proceeds with selecting/unselecting various options. So I might rename that SelectedState or something like that.

Likewise, I might give TableViewController a name that indicates its purpose. E.g. maybe AllowedContentViewController.
I find it confusing that the main view controller uses allowed, but the TableViewController uses blacklisted (which is presumably an inverted set of the aforementioned). I’d suggest using the same model in both view controllers. If TableViewController wants to invert it as part of its determination of what’s checked and what’s not, then it should do that.
The most radical change I’m going to suggest is that you should completely remove the business logic from the view controller. The view controller should be handling the interface with the UIKit controls (the table view, the buttons, etc.), but all the logic about which flags and Category values is represented by which row, how you toggle them, etc., doesn’t belong here. You often put it in what I will call a “view model” (though this entity goes by different names)

The virtue of this is two fold. First the view controller suddenly becomes something very concise and easy to understand. Second, when you get around to writing unit tests, you want to be able to test your business logic without worrying about UIKit stuff (which should be part of the UI tests, not the unit tests).

So, pulling this all together, we end up with a view controller like this:

class AllowedContentViewController: UITableViewController {

    // properties set by presenting view controller

    weak var delegate: AllowedContentViewControllerDelegate?
    var allowed: Set<Category>!
    var flags: Set<Flag>!

    // properties used by this view controller

    private var viewModel: AllowedContentViewModel!

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel = AllowedContentViewModel(allowed: allowed, flags: flags)
    }

}

// MARK: - Actions

extension AllowedContentViewController {
    @IBAction func cancel(_ sender: UIBarButtonItem) {
        dismiss(animated: true)
    }

    @IBAction func done(_ sender: UIBarButtonItem) {
        delegate?.allowedContentViewController(self, didUpdateAllowed: viewModel.allowed, flags: viewModel.flags)
        dismiss(animated: true)
    }
}

// MARK: - UITableViewDataSource

extension AllowedContentViewController {
    // you didn't provide the following two, so I'll take a guess what that looked like

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = viewModel.text(for: indexPath.row)
        cell.accessoryType = viewModel.isSelected(row: indexPath.row) ? .checkmark : .none

        return cell
    }
}

// MARK: - UITableViewDelegate

extension AllowedContentViewController {
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 0 else {
            return
        }

        viewModel.toggle(row: indexPath.row)
        tableView.reloadRows(at: [indexPath], with: .fade)
    }
}

That references a protocol to which our presenting view controller will conform:

protocol AllowedContentViewControllerDelegate: class {
    func allowedContentViewController(_ viewController: AllowedContentViewController, didUpdateAllowed allowed: Set<Category>, flags: Set<Flag>)
}

The presenting view controller would then do something like so:

class ViewController: UIViewController {

    var allowed = Set<Category>()
    var flags = Set<Flag>()

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = (segue.destination as? UINavigationController)?.topViewController as? AllowedContentViewController {
            destination.flags = flags
            destination.allowed = allowed
            destination.delegate = self
        }
    }
}

extension ViewController: AllowedContentViewControllerDelegate {
    func allowedContentViewController(_ viewController: AllowedContentViewController, didUpdateAllowed allowed: Set<Category>, flags: Set<Flag>) {
        self.allowed = allowed
        self.flags = flags
    }
}

I obviously made an assumption here of how you presented this AllowedContentViewController (namely that you must have embedded it in a UINavigationController, based upon the presence of dismiss but that you also had @IBActions with UIBarButton). Clearly, adjust the prepare(for:sender:) according to how you actually presented this table view controller.

Anyway, above, the presenting view controller is responsible for passing data to this presented AllowedContentViewController and for responding to AllowedContentViewControllerDelegate delegate method that supplies the updated user preferences for what is allowed and what isn’t. This gets the AllowedContentViewController from ever having to reach into ViewController to retrieve/update properties itself. Now AllowedContentViewController can be used in any context you want.

Finally, our view model has all the business logic that used to be in the TableViewController:

struct AllowedContentViewModel {
    var allowed: Set<Category>
    var flags: Set<Flag>

    func numberOfRows() -> Int {
        return 4
    }

    func isSelected(row: Int) -> Bool {
        switch row {
        case 0:  return flags.contains(.nsfw)
        case 1:  return flags.contains(.religious) && flags.contains(.political)
        case 2:  return !allowed.contains(.programming)
        case 3:  return !allowed.contains(.dark)
        default: fatalError("Unexpected row number")
        }
    }

    private mutating func select(row: Int) {
        switch row {
        case 0:  flags.insert(.nsfw)
        case 1:  flags.insert(.religious); flags.insert(.political)
        case 2:  allowed.remove(.programming)
        case 3:  allowed.remove(.dark)
        default: fatalError("Unexpected row number")
        }
    }

    private mutating func unselect(row: Int) {
        switch row {
        case 0:  flags.remove(.nsfw)
        case 1:  flags.remove(.religious); flags.remove(.political)
        case 2:  allowed.insert(.programming)
        case 3:  allowed.insert(.dark)
        default: fatalError("Unexpected row number")
        }
    }

    mutating func toggle(row: Int) {
        if isSelected(row: row) {
            unselect(row: row)
        } else {
            select(row: row)
        }
    }

    func text(for row: Int) -> String {
        switch row {
        case 0: return NSLocalizedString("NSFW", comment: "Label")
        case 1: return NSLocalizedString("Religious/political", comment: "Label")
        case 2: return NSLocalizedString("Blacklisted Programming", comment: "Label")
        case 3: return NSLocalizedString("Blacklisted Dark", comment: "Label")
        default: fatalError("Unexpected row number")
        }
    }
}

We can, if we want, then write unit tests for this view model. For example:

class AllowedContentViewModelTests: XCTestCase {

    func testDefaultState() {
        let viewModel = AllowedContentViewModel(allowed: [], flags: [])

        XCTAssert(!viewModel.isSelected(row: 0))
        XCTAssert(!viewModel.isSelected(row: 1))
        XCTAssert(viewModel.isSelected(row: 2))
        XCTAssert(viewModel.isSelected(row: 3))
    }

    func testTogglingNsfw() {
        var viewModel = AllowedContentViewModel(allowed: [], flags: [.nsfw])

        XCTAssert(viewModel.isSelected(row: 0))

        viewModel.toggle(row: 0)

        XCTAssert(!viewModel.isSelected(row: 0))
    }

}

See example at https://github.com/robertmryan/RefactoredViewController.


Don't use explicit returns in CoffeeScript unless you have to (and you don't here)
CoffeeScript may do automatic comma insertion, but I certainly didn't right away (i.e. add a comma yourself, right before reject - anything to make it easier to read)

Anyway: You can't get this code

monitor.getServerInfo().then().printDetails()

because that would be synchronous, not asynchronous. The interpreter would have to wait in the middle of the chain before it could call printDetails. And it doesn't wait - that's the point of asynchronicity.

And that's why then() always returns a promise object (and nothing else), because it can return that right away without any waiting.

So your current code

monitor.getServerInfo().then((monitor) -> monitor.printDetails())

is the way to do it. Of course, it doesn't make much sense to have a printDetails method in your Monitor, if it doesn't always work. Right now, you can just call

(new Monitor(api)).printDetails()

and get

undefined, undefined, undefined

printed. Or, if you just happened to call it after the API query has run, printDetails will suddenly print actual values. The method is almost random at that point because there's nothing guaranteeing that things happen in the right order.

I'd just skip the Monitor class entirely, since it's not really contributing much - at least not right now. But, given the name "monitor", I imagine the point is to get the server info, so you can then set up a polling system of some kind.

In that case, you could make a factory method that returns its product via a promise:

Promise = require "bluebird"

class Monitor
  constructor: (@server, @key, @ts) ->
    # I don't know if a Monitor instance needs an api object
    # for anything. If it does, add it as an argument to
    # this constructor

  startPolling: ->
    # ... or something

  stopPolling: ->
    # ... or something

  printDetails: ->
    console.log @server, @key, @ts

# factory function
Monitor.create = (api) ->
  # internal function that actually runs the query
  createMonitor = (resolveCallback, rejectCallback) ->
    success = (data) ->
      {server, key, ts} = data.response # CoffeeScript destructuring
      resolveCallback new Monitor(server, key, ts) # also pass in the api obj, if needed

    api.query("messages.getLongPollServer", use_ssl: 1).then success, rejectCallback

  # return a promise that'll resolve with
  # a new Monitor instance (or fail,
  # presumably with an error of some sort)
  new Promise createMonitor

module.exports = Monitor

If you already have the server, key and ts values from somewhere, then great; just call new Monitor(server, key, ts) and you're done.

But if you don't, you can do this:

Api     = require("./api")
Monitor = require("./monitor")

api = new Api("6de61....")

success = (monitor) -> monitor.printDetails() # or whatever else you need
failure = (args...) -> console.warn args...

Monitor.create(api).then success, failure

This is basically turning the process inside out: Instead of instantiating a Monitor object, and making it fetch the data it needs, the factory method is doing the fetching, and only creating the instance when it's time to do so.


Count characters, words, and lines in files (wc in rust)

InputFile doesn't appear to be a file — a better name might be Statistics.
usize is conventionally used for indexes and sizes instead of u32.
Don't take an argument by &String.  Since the algorithm works for not only files but other streams of characters as well, consider taking a BufRead argument.
Reading the whole file into memory isn't efficient — an alternative is to use the utf8-chars crate to identify characters.
c as u8 != 0 is just c != '\0'.
It took me a while to figure out what spaced does — in_word might be a better name.
char::is_whitespace checks for all kinds of whitespace.
In main, Iterator::skip allows you to skip one argument without allocating a Vec.

Here's my version:
use {
    anyhow::Result,
    parse_display::Display,
    std::{
        env,
        fs::File,
        io::{BufRead, BufReader},
    },
    utf8_chars::BufReadCharsExt,
};

#[derive(Clone, Debug, Display)]
#[display("{characters} {words} {lines}")]
struct Stats {
    characters: usize,
    words: usize,
    lines: usize,
}

impl Stats {
    fn new<R: BufRead>(mut reader: R) -> Result<Self> {
        let mut stats = Stats {
            characters: 0,
            words: 0,
            lines: 0,
        };
        let mut in_word = false;

        for c in reader.chars_raw() {
            let c = c?;

            if c != '\0' {
                stats.characters += 1;
            }

            if !c.is_whitespace() {
                in_word = true;
            } else if in_word {
                stats.words += 1;
                in_word = false;
            }

            if c == '\n' {
                stats.lines += 1;
            }
        }

        Ok(stats)
    }
}

fn main() -> Result<()> {
    for path in env::args().skip(1) {
        let file = BufReader::new(File::open(&path)?);
        let stats = Stats::new(file)?;
        println!("{} {}", stats, path);
    }

    Ok(())
}


How can this python regex file finder be improved?

I think a regex is overkill here. There comes a point where evaluating all these or'ed exceptions becomes just too slow. I would instead use a simple glob and a blacklist:
from pathlib import Path

IGNORE = {"absolute", "abstract", ...}

root = Path("/ROOTDIRECTORY")
for file in root.glob("**/*.php"):
    if len(file.stem) == 8 and file.stem not in IGNORE:
        print(file)

Note that I used a set for a fast check with in.
You could also use the glob "**/????????.php", as suggested by @RootTwo in the comments, then you wouldn't have to do the length check, although that is quite fast.
Indeed, what you should ideally do is not take my or anyone else's word for it, but measure. Measure how fast your approach is, how fast an optimized regex is, how fast mine is and how fast using a different glob is. Maybe it matters, or maybe all of this is premature optimization and it doesn't actually matter that one takes a millisecond and the other a second (or whatever the actual results are). That depends entirely on your use case.


SHA256 password hash generation and verification

How about the following:

if (!$salt) {
    $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} elseif (strlen($salt) !== 64)  {
    log_message('info', 'Supplied password to process_password() was not the correct 64-byte length.');
    return false;
}
// if we're here, we have a valid salt

Improvements

Removed $salt from second condition (already known to be TRUE)
Flipped length logic, moved else code into second block
Removed empty condition block


Distinct nearest pixels for floating-point coordinates

I'm not sure what you are doing, exactly, but looping over range(len(...)) is never very pythonic. Since you only use the index to look up values, you should just take the pairs using zip.

Also, that round() + 0.1 thing is unnecessary. Floats represent all integers in their accurate area exactly. If you are outside the accurate area (i.e. an exponent larger than the number of mantissa bits), that addition will not change the value of the float either. Thus, you can simply cast the result of round() to an integer.

If you need to take the unique items of something, the best way is to not use a dict, but a set.

int_rows = map(lambda x: int(round(x)), dem_rows)
int_cols = map(lambda x: int(round(x)), dem_cols)
s = set(zip(int_rows, int_cols))

Then iterate over the set, or unzip it into two sequences for constructing the arrays.

Note: In python 2.x map and zip create lists, so you may want to use itertools.izip and imap. In python 3.x they are fine as is.


Subtract first and last nodes of linked list

More functions, please.

Every time you feel compelled to comment a block of code, consider factoring it out into a properly named function. For example,

def subtract(A):
    start = reach_till_half(A)
    prev = reverse(start)
    modify(A, prev)
    reverse(prev)

Of course names could (and should) be better.


DELAY V DEBOUNCE
What you have implemented is a delay not a debounce. You delay the firing of the event until after a set time. Events during this time further delay the final event.
Design
Debouncing should respond to the first event immediately and then hold any response during the debouncing period after the listener has been called.
It would be better to clearly identify the event argument passed to the listener.
You do not provide a way of passing additional arguments to the event. By adding them to the outer function, you get better control. (see example)
General points

Inconsistent use of semicolon. Either use it (recommended) or not. Don't mix styles.
var is function scoped, let os block scope. It is better to use var when a variable is declared in function scope.
timeoutHandler is a poor name. The timeout function returns and Id (AKA a handle). The name you used implies that the variable is a function. A better name could be timeoutHandle, or in context just id or handle will do.
The is no need to assign null to the variable timeoutHandler. undefined variable are undefined and making it null is just noise and semantically incorrect
The handle returned by setTimeout (and setInterval) are unique to the context and the call. It is never reused. clearTimeout ignores invalid handles so there is no need check if the handle is valid, nor change its value inside the timeout function.
You can reduce the call stack depth by using the trailing arguments of setTimeout to pass the arguments.
window is the default object. Inconsistent use is poor style. You do not use it for clearTimeout, setTimeout, and console so why for addEventListener?
addEventListener('oninput'... is incorrect, there is no event called oninput. Should be addEventListener('input'...

Examples
Covering the general points and comparing debounce, delay, and immediate event responses. The delay is also used to clear the displays 2sec after the last event.
It also shows when to use window. In the example emoticons can not be used as direct references to elements, thus I use window bracket notation to access the names.

const DELAY_MS = 250;
const CLEAR_DELAY_MS = 2000;
const CLEAR_SPEED_MS = 17;
const DISPLAYS = ["","","⚡"];

const logger = (event, ...args) =>  log(args[0]);

const delay = (callback, delay, ...args) => {
    var handle;
    return event => {
        clearTimeout(handle);
        handle = setTimeout(callback, delay, event, ...args);
    }
}

const debounce = (callback, delay, ...args) => {
    const timerClear = () => clear = true;
    var clear = true;
    return event => {
        if (clear) {
            clear = false;
            setTimeout(timerClear, delay);
            callback(event, ...args);
        }
    }
}

addEventListener('input', debounce(logger, DELAY_MS, DISPLAYS[0]));
addEventListener('input', delay(logger, DELAY_MS, DISPLAYS[1]));
addEventListener('input', event => logger(event, DISPLAYS[2]));
addEventListener('input', delay(clear, CLEAR_DELAY_MS));
gun.focus();

/* Helper functions unrelated to question */
function clear() {
    var allClear = "";
    DISPLAYS.forEach(name => {
        var text = window["log" + name].textContent;
        allClear += window["log" + name].textContent = text.substring(1);
    })
    if (allClear !== "") {
       setTimeout(clear, CLEAR_SPEED_MS);
    } else {
       gun.value = "";
    }
}

function log(which) { window["log" + which].textContent += which }
b { font-size : large }

Rumble!! Debounce V Delay V Immediate. With a 2 second delayed clear.

Debounced 250ms:

Delayed.. 250ms:

Immediate.. 0ms:

<input type="text" placeholder="Rapid fire key strokes" size="50" id="gun">


Checking whether a user is on the donors list

The final parameter here is misnamed:

$conn = mysqli_connect(host, user, pass, table);

It denotes name of MySQL database (e.g. "test") rather than name of a table (e.g. "test.donors" or "donors.donors").

The _res suffix is superfluous and may be safely elided:

mysqli_stmt_bind_result($stmt, $username_res, $activated_res, $expiration_res);

  want to make sure it is secure against SQL injection.

Yes, you are using the API as recommended, in secure fashion.


This comment lies.

$sql = "SELECT * FROM $table"; // get a list of all fields and datatypes (ignore the latter)

You copy pasted the whole line and then neglected to update/remove the comment.
It's traditional to use a simple i for loop counter variables. I see no reason to use a triple iii or jjj. However, in this case it makes much more sense to use more verbose (and hence, descriptive) names like $row and $col.


Json type-safe builders using jackson-annotations

Your code is overall pretty nice. A few things I noted:

Upon first reading, I did a double-take at reading the withFoo methods that your fluent API uses. This is because there's an idiom where withFoo is sometimes a "setter" for an immutable object (which creates a new version with the update info). But after that, I read the contents of the methods and it made sense.
This is not the best way to rethrow exceptions:

public String asJson() {
    try {
        return new ObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Could not create json: " + e.getMessage());
    }
}

Notice that RuntimeException has a constructor which takes a throwable reason as well. Thus it would be much better to implement this like so:

public String asJson() {
    try {
        return new ObjectMapper().writeValueAsString(this);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Could not create json.", e);
    }
}

Don't worry; it still has the message from e. Note that your other classes also have this problem.
What's with the name of this method?

public static HolidayBuilder aHoliday() {
    return new HolidayBuilder().withDuration("1d");
}

What does aHoliday mean? Your other classes have similarly named methods, and I don't understand what they are supposed to do. You should give them proper names.


So first things first, your code looks terrible.

Use real names for your variables that are understandable without any further reading, e.g. instead of fu you could use fatique.
Your variable success is a boolean so make it one.
You should introduce a factor for the fatique rather than subtracting it. That would make the code simpler. Also your failure is most likely because the snail takes so much time to slide back down. So rather than checking for snailHeight > 0 check for heightSlid > fatique * heightClimbed

size_t numDays = 0;
double snailHeight = 0.0;
double fatique = 1.0;
bool fail = false;
while (true) {
    numDays++;
    snailHeight += fatique * heightClimbed;
    fatique *= 0.9;
    if (heightSlid > fatique * heightClimbed) {
        fail = true;
        break;
    } else if (snailHeight > heightWell) {
        break;
    }

    snailHeight -= heightSlid;
}

if (fail) {
    std::cout << "failure\n";
} else {
    std::cout << "success on day " << numDays << "\n";
}


php highlight search keywords [working solution]!

Use of deprecated functions

Both split() and eregi_replace() are deprecated since PHP 5.3. Don't use them.

Use preg_replace() instead of eregi_replace() and explode() instead of split() Other alternatives are str_replace() and preg_split().

Unexpected results

When the search string is lowercase, all replaced words will be lowercase too. The case of the original word is not preserved.

Unused variables

The $key variable is assigned but never used. In fact, the entire while loop is odd. Use a foreach loop instead, like so:

foreach($kt as $val) {
    ...

Missing function

The code should be in a function. The function would require two parameters, the string and an array of words to highlight, and return the result string. The function should not echo anything (but I presume the echo statements are debugging things).

Old HTML

Although valid, the use of <b> tags is outdated. It describes formatting in a document layout, without specifying the need for the format. You should use html for layout and css for styling. Then you can replace the <b> with a <span class="highlight> (or any other sensible class name).