Using `from select`-syntax to pass through elements from a collection unmodified

I don't personally use RX, so my answer may be wrong, but he is it anyway:

I don't know whether “everyone does it this way”, but I doubt it. The code is translated into (after LINQ query transformation and by writing extension method invocation as if it was a normal method):

return Observable.Select(xs, x => x);

Observable.Select does exactly what you would expect it to, if you know LINQ to objects: it creates a new observable, which consumes each item from xs, processes it using the delegate you gave it (which in this case just returns the item unchanged) and then produces the result.

So, using that code does have some overhead, but it will be most likely negligible for you and you shouldn't worry about it much. But it does make the code longer and more confusing (it did confuse you). And “there is a chance it will save you some typing in the future” is not a good reason to sacrifice readability, I think.


Trie implementation for left to right wildcard search

Eclipse says that the second null check in the search method is dead code:

if (current == null) {
    return matches;
}

Furthermore, it could be refactored to the following:

public Set<Trie> search(final String word) {
    count = 0;
    Trie current = this;
    for (final Character c: word.toCharArray()) {
        ++count;
        current = current.children.get(c);
        if (current == null) {
            return Collections.emptySet();
        }
    }
    return current.connections;
}

You should specify the return types:

public Set<Trie> search(final String word) { ... }
public Set<Trie> build() {... }

instead of

public Set search(final String word) { ... }
public Set build() {... }

Consider using

StringUtils.isBlank instead of the (word == null || "".equals(word.trim())) and
StringUtils.isNotEmpty instead of (this.word != null && this.word.length() > 0).

I've found them more readable.
If I'm right you could iterate over the values directly in the build method:

for (final Trie childTrie: children.values()) {
    connections.addAll(childTrie.build());
}

I'd separate the builder logic from the Trie class. Currently clients can easily misuse this class:

t.build();
t.add("can2");

(Effective Java, 2nd Edition, Item 2: Consider a builder when faced with many constructor parameters)
connections does not seem a good name. It took some time to figure out that this set contains the descendant Trie objects which has a word. I might call it descendantsWithWord. Furthermore, it could contain only the words (strings), not the Trie objects, so it could be simply Set<String> descendantWords.
The static count field does not smells well. It is used for two different purposes. I'd create a createdTrieObjects field:

private int createdTrieObjects = 1;

and increment it in the add method:

t.children.put(c, new Trie());
createdTrieObjects++;

On the other hand, in the search method you could return a SearchResult object which contains the search depth (it's the count currently) and the result strings:

public class SearchResult {

    private final Set<String> words;
    private final int searchDepth;

    ...

}

It contains only a set of string instead of the Set<Trie> collection. I think clients should not know about the internal Trie objects. If you don't need the search depth return with Set<String> only:

public Set<String> search(final String wordStart) {
    Trie current = this;
    for (final Character c: wordStart.toCharArray()) {
        current = current.children.get(c);
        if (current == null) {
            return Collections.emptySet();
        }
    }
    return Collections.unmodifiableSet(current.descendantWords);
}

Please note the Collections.unmodifiableSet call. It prohibits malicious clients to modify the Trie's internal structure. (Effective Java, 2nd Edition, Item 39: Make defensive copies when needed)
You could eliminate the build method and the word field if you fill the descendantWords in the add method:

 public void add(final String word) {
    checkArgument(StringUtils.isNotBlank(word), "word can not be blank");
    Trie current = this;
    descendantWords.add(word);
    for (final Character c: word.toCharArray()) {
        if (!current.children.containsKey(c)) {
            current.children.put(c, new Trie());
            createdTrieObjects++;
        }
        current = current.children.get(c);
        current.descendantWords.add(word);
    }
}

Some small notes about the edit:

Instead of the checked IllegalAccessException I'd throw runtime IllegalStateException. It's rather a programming error if a client tries to add new element to a built trie.  (Effective Java, 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors)
About the s variable in the search method: Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (Effective Java, Second Edition, Item 45: Minimize the scope of local variables)
You could copy the descendantsWithWord set with the HashSet's constructor instead of the for loop in the search method:

return new HashSet<String>(current.descendantWords);

The isBuilt flag should be at the beginning of the class with the other fields.

Here is the refactored version:

import java.util.Collections;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import static com.google.common.base.Preconditions.*;

public class Trie {

    private final Map<Character, Trie> children = new HashMap<Character, Trie>();
    private final Set<String> descendantWords = new HashSet<String>();

    public Trie() {
    }

    public void add(final String word) {
        checkArgument(StringUtils.isNotBlank(word), "word can not be blank");
        Trie current = this;
        descendantWords.add(word);
        for (final Character c: word.toCharArray()) {
            if (!current.children.containsKey(c)) {
                current.children.put(c, new Trie());
            }
            current = current.children.get(c);
            current.descendantWords.add(word);
        }
    }

    public Set<String> search(final String wordStart) {
        checkNotNull(wordStart, "wordStart cannot be null");
        Trie current = this;
        for (final Character c: wordStart.toCharArray()) {
            current = current.children.get(c);
            if (current == null) {
                return Collections.emptySet();
            }
        }
        return Collections.unmodifiableSet(current.descendantWords);
    }
}

Edit for the comment:

In your original implementation there is a set (descendantsWithWord) in every node which refers to Trie objects. In this answer there is a set (descendantWords) in every level which refers to String objects.

The size of the sets are the same, Strings (as well as other objects, like Tries) are on the heap, the set contains only references to objects, so it does not count if they are Strings, Tries or other Objects, there is no difference in memory consumption and there is no duplication. The only difference is the method where the trie builds the set and the generic type of the set (references in the set).

I'm not too familiar with tries and articles on the Wikipedia do not mention that trie nodes should or should not store each descendants (not just references to the nodes of the next level), so I'm not sure that this is "officially" a trie or not.

Anyway, if I'm right you need fast search, so memory consumption looks is secondary here. Precalculating and storing the result in a cache (i.e. descendantWords) seems a better solution that traversing a subtree and building strings from characters on every search request as you did it too.

Furthermore, I'd consider using a Map<String, Set<String>> structure:

c,      [can, cancel, cancer]
ca,     [can, cancel, cancer]
can,    [can, cancel, cancer]
canc,   [cancel, cancer]
cance,  [cancel, cancer]
cancel, [cancel]
cancer, [cancel]
...

It's very similar to the trie above since (1) the trie's nodes are the same as the keys in this map and (2) the values of the map are the same as the descendantWords set in the trie. An advantage could be a simpler implementation, especially with a Multimap from Guava:

public class AutoSuggestCache {

    private final SetMultimap<String, String> words = HashMultimap.create();

    public AutoSuggestCache() {
    }

    public void add(final String word) {
        checkArgument(StringUtils.isNotBlank(word), "word can not be blank");
        for (int endIndex = 0; endIndex < word.length(); endIndex++) {
            final String wordStart = word.substring(0, endIndex);
            words.put(wordStart, word);
        }
    }

    public Set<String> search(final String wordStart) {
        checkNotNull(wordStart, "wordStart cannot be null");
        return Collections.unmodifiableSet(words.get(wordStart));
    }
}


Turning my comment on your question into an answer:

On a Mac, when the Caps Lock key is engaged, the Shift key doesn't change the case to lower. So in the event that the Caps Lock key has already been engaged, before your page even loads, this code won't work as intended. I believe this jQuery plugin has already solved this problem - github.com/nosilleg/capslockstate-jquery-plugin

As for your code itself:

I like that you've got named variables, that makes the final if statement super easy to read. You could name the event variable as such too, so it's clearer what e contains.
You can refactor this var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase

to:

var isUp = (kc >= 65 && kc <= 90) // uppercase

because (kc >= 65 && kc <= 90) evaluates to a boolean value. The conditional operator is redundant.

Similarly, you can refactor: var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false );

to:

var isShift = ( e.shiftKey ) || (kc == 16);

The interesting thing about the statement above is that it takes advantage of a mechanism called short-circuit evaluation that boolean operators, like OR (||) and AND (&&), use.

Basically, in an OR statement, if the first expression evaluates to true, the second expression is never evaluated, because true || anything will always evaluate to true.

Similarly for an AND statement, if the first expression evaluates to false, the second expression is never evaluated, because false && anything will always evaluate to false.


Your code is incorrect. See the following case:

print replace_inside("[tag]abc[/tag]abc[tag]abc[/tag]")

You can indeed use regular expressions

pattern = re.compile(r"\[tag\].*?\[/tag\]")
return pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)


I'm not convinced that there is much value in combining the results of three separate problems into one data structure, but I'll play along.

Note that the standard indentation for Ruby is two spaces.

Fibonacci

I don't think it's a good idea to have Fibonacci objects that differ only in their max.  What is the point of the max, anyway?  It just introduces a possible failure if you try to request an entry beyond the max.  Why not have a "smart" singleton that extends itself as necessary?

The get_nth method is a natural candidate for overloading the [] operator, so that you can write Fibonacci[3].

Opinions may differ as to the convention, but I would consider 0 to be the zeroth Fibonacci number, followed by 1, 1, 2, 3, 5, …

class Fibonacci
  @list = [0, 1]

  def self.[](nth)
    while @list.size <= nth
      @list << @list[-2] + @list[-1]
    end
    @list[nth]
  end
end

FizzBuzz

It would probably be a good idea to make FizzBuzz adhere to the same interface as Fibonacci.

Your results are sometimes numbers and sometimes strings.  That's allowable, but not a practice that I would recommend.

The conditions can be written a bit more succinctly using the value if condition syntax and implicit return.

class FizzBuzz
  def self.[](n)
    output = ''
    output += 'Fizz' if n % 3 == 0
    output += 'Buzz' if n % 5 == 0
    output = n.to_s if output.empty?
    output
  end
end

numbers

Instead of appending to an empty array, build it "all at once" using Range#collect.

numbers = (1..100).collect do |n|
  {
    :Number => n,
    :FizzBuzz => FizzBuzz[n],
    :Prime => Prime.instance.prime?(n),
    :Fibonacci => Fibonacci[n]
  }
end


UNIX cp multithreaded implementation in C

Use ftw() to crawl directories
ftw() is a POSIX function that will recursively crawl directories, and calls a callback function for every directory entry found.
Consider using strdup() and asprintf()
Instead of copying strings using some kind of strlen()+malloc()+strcpy(), use the POSIX function strdup() if possible, which takes care of all this for you.
Linux and most BSDs also implement asprintf(), which takes care of allocating a correctly sized buffer for you. Be aware that this is definitely not cross-platform.
Don't throw away threads
While thread creation and destruction is quite fast on Linux, it still has an overhead. If you are copying many small files, that overhead might start dominating. It would be much better to have a fixed number of threads that are waiting for work to do.
A typical implementation would use a thread-safe queue for this. Have the directory crawler fill a queue of filenames to copy. The queue is guarded by a mutex, and has an associated condition variable. Whenever it pushes an item to the queue, it signals the condition variable. The threads wait for elements to be pushed, and when woken up, they will pop one entry from the queue and start copying it.
However, assuming the directory crawler is much faster than files can be copied, it would be a waste of memory to fill a queue with all filenames encountered, especially if the directory tree is large. You only need a few entries in the queue for worker threads to pick up work. You can make the crawler block itself if the queue gets too large. You should add a second condition variable then that gets signalled whenever a worker dequeues a filename to copy.
Find the right number of threads to use
It's hard to predict how many threads will be optimal. It could be that one thread is optimal, depending on how fast the storage is compared to the overhead of having multiple threads. Having as many threads as files to copy might also not be ideal; even if they don't use much CPU time, performing I/O on multiple files at the same time might result in more disk seeks (which is mostly an issue on harddisks, but some solid state drives also have some performance penalty for doing non-sequential access). You could benchmark your code and optimize the number of threads for your system, but the performance might be different on other systems.
Alternatives for threads
Threads are a solution to the problem that there is some implicit serialization when doing regular I/O operations on files in a single thread. However, there are also other techniques to have multiple I/O operations submitted to the kernel simultaneously. POSIX AIO is one way to do this, however it has its limitations. In particular, I don't think you can easily hand off a file copy operation to it. What is more promising is Linux's io_uring, although this is of course not a cross-platform solution to your problem. If you are interested in the latter, then also see this LWN article and this excellent guide. Most BSD flavors have something similar called kqueue.


If you know what the named matches are up front (ie if you know what the pattern looks like, you can simply use array_intersect_key to extract only the values that have a specific key from the $matches array:

$names = ['foo' => null];

$pattern = '#^(?<foo>.*)$#';//changed ^ to $ at the end ;)
$str = '123';
if (preg_match($pattern, $str, $matches))
{//or return here
    $matches = array_intersect_key($matches, $names);
}
return $matches;

Of course, if you are not in control of the names that will be used in the pattern, you'll have to either iterate over the $matches array like you're doing now. However, I'd recommend you don't use unset on the $matches array, but rather copy the relevant values to a new one and return that array instead:

$returnValue = [];//new array
foreach ($matches as $k => $v) {
    if (!is_int($k)) {
        $returnValue[$k] = $v;
    }
}

There are a couple of reasons for this:

It's considered bad practice to change the array you're iterating over inside the loop. It can cause issues in certain cases, and it will definitely bite you if you decide to pick up another language
PHP's memory management and copy-on-write mechanisms work well with code like the loop above: the new array will be assigned a reference to the value in $matches, but once the function returns, $matches is GC'ed. The values not referenced by $returnValue will be GC'ed, the other values are then "owned" by the return array (that's not 100% accurate, but it's true enough for now)
It's probably the most efficient (in terms of readability and execution time) approach.

Time to get silly

Just for the fun of it: you can opt for an inception-style preg_match_all call on the regex you're passing to preg_match (regex matching on a regex... let's be honest, that sounds a tad absurd). It's silly, but it can be done:

$pattern = '#^(?<foo>.*)$#';//changed ^ to $ at the end ;)
$str = '123';
$names = null;
if (preg_match_all('/(?<=\?<)([^>]+)/', $pattern, $matches))
{//create an assoc array containing the match names
    $names = array_fill_keys($matches[0], null);
}

$matches = null;
if (preg_match($pattern, $str, $matches))
{
    if ($names) {
        //gets only the named keys
        $matches = array_intersect_key($matches, $names);
    }
    return $matches;
}
//throw exception, return null, or do something else here

Now, this is not exactly the way to go, but in some cases it might happen that you're processing a string, but what regex you apply to it can change depending on any number of reasons. In that case, array_intersect_key is definitely worth a look, seeing as it only returns the keys that exist in all of the arguments you pass to it:

class Foo
{
    const DOMAIN_PATTERN = '/(?<=@)(?<domain>[^@\.]+)(?=\.)/';//or something
    const EXTENSION = '/\.(?<extension>[a-z]{3,4})$/';

    protected static $names = [
        'domain'     => null,
        'extension'  => null,
    ];

    protected $mode = null;

    public function setValidationOptions(array $options)
    {//based on these options, one or more specific regex's will be applied to the data
        $this->mode = $options;
        return $this;
    }
    public function validateString($string)
    {
        $regex = $this->getPatterns();
        $result = [];
        foreach ($regex as $pattern) {
            if (preg_match($string, $pattern, $matches)) {
                $result = array_merge(
                    $result,
                    array_intersect_keys(
                        $matches,
                        static::$names
                    )
                );
            }
        }
        return $result;
    }
}

This is just a crude example of how you could use array_intersect_key to handle regex matches with named sub-patterns


Break text into letters (regular Unicode graphemes+language specific digraphs)

For starter, you do not need to create you digraphs list each time the function is called: they won't change, so better create them once as a global constant. You also forgot to add capitalized versions in the list so that 'HELLO' is split into ['H', 'E', 'LL', 'O'] instead of the current ['H', 'E', 'L', 'L', 'O'].

Second, your linear research in the digraphs list can be time consuming when all you want to know is if characters at position i-1 (if any) and i forms a digraph present in your list. I’d rather write it as yield 0 if s[i-1:i+1] in digraphs else breakable. Of course, for this to work efficiently, you will need digraphs to be a set instead of a list where lookups are \$\mathcal{O}(1)\$ instead of \$\mathcal{O}(n)\$.

Lastly, I would only consider lowercase variants and turn the selected two characters lowercase before checking:

from uniseg.graphemecluster import grapheme_clusters

DIGRAPHS = {"dh", "gj", "ll", "nj", "rr", "sh", "th", "xh", "zh"}

def albanian_digraphs(s, breakables):
    for i, breakable in enumerate(breakables):
        yield 0 if s[i-1:i+1].lower() in DIGRAPHS else breakable

if __name__ == '__main__':
    # from https://sq.wiktionary.org/wiki/Speciale:PrefixIndex?prefix=dh
    for text in ('dhallanik', 'dhelpëror', 'dhembshurisht', 'dhevështrues', 'dhimbshëm', 'dhjamosje', 'dhjetëballësh', 'dhjetëminutësh', 'dhogaç', 'dhogiç', 'dhomë-muze', 'dhuratë', 'dhëmbinxhi', 'dhëmbçoj', 'dhëmbëkatarosh'):
        print(list(grapheme_clusters(text, albanian_digraphs)))

Also note the use of if __name__ == '__main__' to separate the actual code from the tests.


SETLOCAL ensures that any environment variables you set don't affect the calling process's environment. It's like a sandbox for variables, directory changes, and other shell settings.

I usually use @ECHO instead of plain ECHOs so that if the @ECHO OFF is ever temporarily disabled (say, for debugging purposes), the echo statements don't produce needless noise in the output.

I also suggest using a loop to repeat the nearly-duplicate statements:

@ECHO OFF
SETLOCAL
:: variables
@ECHO This script takes the backup of file SwiftALM Important folders
SET /P source=Enter source folder Example D:\jboss6.1\server\swift:
SET /P destination=Enter Destination folder:
SET /P folder=Enter Folder name:

@ECHO folder=%folder%

MKDIR %destination%\%folder%
SET xcopy=xcopy /E/V/Q/F/H/I

FOR /F %%s IN (conf lib deploy deployers) DO (
    echo %%s folder will be copied
    %xcopy% %source%\%%s %destination%\%folder%\%%s
    IF NOT ERRORLEVEL 1 @ECHO %%s folder has been copied.
)

@ECHO Files have been copied. Press enter to proceed.
PAUSE


Parse a formatted string, which may have duplicate keys, into a map

You can not get it much more efficient that this. It could be more readable and there are some code smells.

Remarks:

The input string "zoo=ooz=10" has a map with 1 entry that has "ooz" as value. Is this what you want? Maybe not limit the split and check that it is 2?
"catch (Exception ex)" is considered bad practice. You are basically saying that you do not care about any Exceptions. Also any possible exceptions in all the methods you call. This is never a good idea.
No argument checking. The cases where the argument is null or the empty string you can leave the method early. This improves readability. Now the massive catch also does the argument checking. Having a dedicated piece of code for every thing is easier to read.
You are transforming one iterable (result of payload.split) into another dynamic sized iterable. Usually it is better to then set the initial capacity for the HashMap to prevent rehashes during insertion which is O(n). But in this case the end size does not have to be equal to the input size. It is a border case.

My proposal:

public static Map<String, String> parseStringToMap(String payload) {
  Map<String, String> map = new HashMap<>();

  if (payload == null || payload.isEmpty()) {
    return map;
  }

  for (String part : payload.split("\\|")) {
      String[] subparts = part.split("=");
      if (subparts.length == 2) {
        map.put(subparts[0], subparts[1]);
      }
  }

  return map;
}


Deleting large folders on remote machines

I decide to write my own function(using native process) to delete the files(tested on windows), no external dependencies on jars.

Implementation details for windows:

I am using robocopy because rmdir fails for complex or deeply nested file paths.
The logic to delete files on windows works like Collections.retainsAll().

import java.io.File;

import java.io.IOException;

public class RecursiveDelete {

    public static void main(String[] args) throws IOException {
        String dirPath = "C:" + File.separator + "dev_tools" + File.separator + "dir_to_delete";
        System.out.println("Delete folder path=" + dirPath);
        execute(dirPath);
    }

    public static void execute(String folderToDelete) throws IOException {
        String os = System.getProperty("os.name").toLowerCase();
        File emptyFolder = createEmptyDirectory();
        if (isWindows(os)) {
            Runtime.getRuntime().exec("cmd /c robocopy " + emptyFolder + " " + folderToDelete + " /purge & rmdir " + folderToDelete);
        } else if (isUnix(os) || isMac(os) || isSolaris(os)) {
            Runtime.getRuntime().exec("rm -r -f  " + folderToDelete);
        }
    }

    private static File createEmptyDirectory() {
        File emptyFolder = new File("EmptyFolder");
        if (!emptyFolder.exists()) {
            boolean isCreated = emptyFolder.mkdir();
            System.out.println("Is empty folder created ?" + isCreated);
            System.out.println("EmptyFolder path" + emptyFolder.getAbsolutePath());
        }

        return emptyFolder;
    }

    public static boolean isWindows(String os) {
        return (os.contains("win"));
    }

    public static boolean isUnix(String os) {
        return (os.contains("nix") || os.contains("aix") || os.contains("nux"));
    }

    public static boolean isSolaris(String os) {
        return (os.contains("sunos"));
    }

    public static boolean isMac(String os) {
        return (os.contains("mac"));
    }
}


Remove all trailing blanks and spaces from a string

When working with strings, always try to avoid copying/duplicating/moving them, if possible. This would be a perfect example to do so.

When you think about strings in memory, they may be described as a specific number of characters (i.e. length or determined by a terminator) at a specific offset in memory. So all you'll have to do is move both, the starting offset as well as the end indicator (whether it's another pointer or some specific value, i.e. terminator, doesn't matter).

Both these tasks can easily be achieved using a loop in a single line each.

Here's what I'd do (simplified; try it on Ideone.com):

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

char *trim(char *text) {
    char *start = text; // points to the first character
    char *end = text + strlen(text); // points past the last character

    // Let's start with the left side.
    // Move the pointer as long as there's a whitespace
    for (; isspace(*start); ++start);

    // In a similar way, let's get the right end.
    // Again, move the pointer as long as there's a whitespace right before it
    for (;end > start && isspace(end[-1]); --end);

    // Insert the new terminator
    *end = '\0';

    // Return the new starting pointer
    return start;
}

int main(int argc, char **argv) {
    char string[] = "  \t  Hello World\t\t\n";
    printf("result: '%s'\n", trim(string));
    return 0;
}

Note that I'm removing line breaks as whitespaces as well. In this example you'd add it after trimming the line.

Other points regarding your code:

If this is no contest to write code that's as short as possible (like code golf), try to use telling names. len is good, arr is good as well, but pc and nl aren't (nl is obviously "new line", but how about pc?).
The same applies to your preprocessor constants. This is even more important, since you might unintentionally rewrite code. As such never define F or T. If you want a TRUE and FALSE, call them like that or simply use 0 or 1.
In a similar way, use white spaces to make your code more readable.

For example, the line:

while(pc==' '||pc=='\t'||pc=='\n')

could be reformatted to this:

while (pc == ' ' || pc == '\t' || pc == '\n')

This way it's easier to see where single expressions start or end, especially combined with syntax highlighting colors.
I'd also rewrite the contents of your append() function. Since there's nothing happening inside the loop other than the increments, you could use a for() instead:

void append(char to[], char from[], int pos)
{
    int i;

    for (i = 0; pos < STORELEN - 1 && from[i]; to[pos++] = from[i++]);

    to[pos] = '\0'; // Only required in case you run out of space
}

As long as your target string isn't too long already and there's still a character left in your source string it will copy the contents and then move both offsets every iteration. Also note the - 1 when checking for the maximum length. Otherwise pos would point one past the maximum length (see below).
There's a buffer overrun in your code:

If you define char string[1000], your last valid offset would be 999, since the index starts at 0.
When checking pos < STORELEN and this check fails, the value of pos would be 1000 already. Once you hit the line to[pos] = '\0' you're essentially writing past the allocated memory at string[1000].


Monkey patching extra events in Node.js HTTP/Express

I did the following for something similar.  This uses the closure to create a chain-of-command pattern.

function (req, res, next) {
  var realEnd = res.end;
  res.end = function () {
    var realEndArgs = arguments;
    req.log.info ("HTTP RESPONSE CODE " + res.statusCode);
    realEnd.apply (res, realEndArguments);
  }
  next();
}

You could instead of logging the status code, do res.emit('end') as you described, or anything else, before returning control to the original res.end (which may itself be a replacement).  Or, you could do directly in this function whatever you want to do in response to the end event.

Note: I explicitly store res.end's arguments in realEndArguments in case I later add anything asynchronous, because arguments would then refer to the asynchronous action's callback's arguments instead of res.end's arguments.  A subtle bug I ran into at first.


Opening comments

I'm not a Haskell expert, but I hope I can offer some helpful comments and critiques.

Overall, I think this is mostly good and idiomatic code. You make good use of pattern matching and have pretty clean definitions of your code.

I'm going to first address style and your questions. I'll then address the performance issue, since it actually isn't that hard to fix.

Style

I think most of your style is fine. I just personally prefer to nest where clauses like so

foo x y = x' + y'
  where
    x' = 2*x
    y' = 2*y

How you do it is up to you.

Using Num

I don't think there's much wrong with using Num for FibNum to make things easier. I would just go ahead and implement abs and signum if you do, since they aren't too difficult, although you don't have to since you don't export FibNum (which I think is good). However, Num is just an interface and doesn't officially make any promises about how its operations behave (i.e. it doesn't have any laws).

The data type you've defined is the Ring* Z[√5]. I found a library that has a Ring type class which you could implement for your datatype. You could then use this type class's implementation of (^) instead of pow for a speedup (see my comments regarding performance).

Whether you want to be more precise like this is up to you. Num unofficially is a ring, too, and is the more common type class.

As an addendum, since you are using division, you may wish to consider changing your Integers to Rationals, which would make your type the Quadratic Field Q[√5]. There is also a Field typeclass.

* Don't worry too much about the abstract algebra here if you aren't familiar. What's more important is understanding the interfaces and the promises they make/laws they obey. For example, the order of operation of addition can be rearranged (known as commutativity) in a Ring and Field. You don't need to know anything more than how to implement the functions required, make sure they satisfy the laws, and how to use the interface (I don't really remember my rings and fields anyway, I just googled around a bit).

Using fromJust

I think that the usage of fromJust is unnecessary and serves to undermine the fact that divR5 returns a Maybe. Below, I offer two alternative options.

I would also consider either renaming divR5 to indicate that it doesn't actually divide an arbitrary FibNum by √5, leaving a comment to that effect, or defining it in the where clause of fibo (which is what I would do). If you define it in the where clause, you can't accidentally misuse it elsewhere.

Return a Maybe

fiboMaybe :: Integer -> Maybe Integer
fiboMaybe n = (`div` p2) <$> divR5 nom
  where
    nom = pow fphi n - pow fpsi n
    p2  = 2^n

I like to use the infix form of fmap (and also I prefer to use div in infix), but you can also explicitly case on the result or use do notation.

Give a better error message

If you aren't going to return a Maybe, then you might as well provide a more informative error message than fromJust's.

fiboError :: Integer -> Integer
fiboError n = divR5 nom `div` p2
  where
    nom = pow fphi n - pow fpsi n
    p2  = 2^n
    divR5 (FibNum 0 n) = n
    divR5 _            = error "fiboError: got nonzero integer part in divR5 (this shouldn't happen)"

Improving efficiency

It turns out that it's not too hard to improve your efficiency. If you implement the Ring or Field type class and use the functions provided there, you should see a major speedup. But if you don't want to, we can fix the speed in only a couple lines of code.

The inefficiency in your code comes from your implementation of pow, which, while correct, takes linear time. You can reduce this significantly. Here's how we can fix it. We're going to use the Product Monoid and the function mtimesDefault from Data.Semigroup.

If you aren't familiar with the abstract algebra terminology here, ignore that junk for a second. Here's the lowdown: we're going to take advantage of the fact that for your datatype, multiplication is associative. What does that mean? It means that

(x * y) * z == x * (y * z)

i.e. we can move around parentheses in a product without changing its value. If you can do that, you have something known as a Semigroup. That's all a Semigroup is! A Monoid is a Semigroup where you know there's some element that does nothing when you multiply it. In this case, that element is 1:

1 * x == x * 1 == x

If you have a Monoid (which FibNum is with respect to the multiplication operation) and want to multiply a number by its self n times, mtimesDefault :: (Integral b, Monoid a) => b -> a -> a does this more efficiently than the naive solution.

The Product wrapper type takes a Num a and uses its multiplication operation as the Monoid operation. So to get a faster pow, here's all the code we have to write:

import Data.Monoid    (Product(..))
import Data.Semigroup (mtimesDefault)

powFast :: Integral a => FibNum -> a -> FibNum
powFast n exp = getProduct $ mtimesDefault exp (Product n)

If we replace pow with powFast, your implementation becomes much faster than the "standard" approach too!

Of course, it isn't too hard to write a faster pow function by hand. It's just neat that Haskell has built-in machinery that lets you avoid doing so. If you wanted to figure out how to do it faster by hand, I would hint you to think about exponentiation of regular numbers.

Say I asked you to compute 2^50 by hand. I claim you don't need to take 50 multiplications to give me an answer. Try and think about how you would do it efficiently, taking advantage of the fact that you're only ever multiplying by 2 and that you multiplication is associative.

Here's a hint:

   Think about multiplying exponents with the same base. 2^x * 2^y = 2^(x+y). What about 2^x * 2^x?

and another:

   For example, suppose you get to 2^4 = 16. From here, if you multiply 16 by itself, you'll get 16 * 16 = (2^4) * (2^4) = 2^(2*4) = 2^8. That saved 3 multiplications compared to the naive method of multiplying by 2!

You can find the answer in the implementation of stimesDefault.


Copying contents between BufferedStreams in Java

Instead of reading the buffered stream byte-by-byte inputStream.read() you might use the advantage of buffering. This will speed up the large content copy.

private boolean copyToStream(BufferedInputStream inputStream, BufferedOutputStream fileStream) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    int n;
    while ((n = inputStream.read(buffer)) != -1) {
        fileStream.write(buffer, 0, n);
    }
}

Also, consider java.nio.FileChannel transferTo() which may allow using DMA.


Your main() function desperately needs to be busted up, for multiple reasons:

You use a lot of variables, all of them declared at the top of main().  A human mind is only good at keeping track of about 7 things at a time, so this code is hard to follow.
It violates the Single Responsibility Principle, by parsing the command line, throwing the dice, keeping the statistics, and printing the report.  That's a lot of work for one function!
Object-oriented code is preferred in Java.  A static function avoids object-oriented thinking.
It's unclear what you're simulating: what constitutes a trial, and what you mean by biggest/smallest sum.

A quick win in readability can be obtained by defining a Die class: die.toss() reads like English, whereas 1 + (int) ((Math.random() * (6 - 1)) + 1) doesn't.

class Die {
    // Since "throw" is a Java keyword, we use "toss"
    int toss() {
        return 1 + (int)(6 * Math.random());
    }
}

A good start to taming the variables would be to declare each of them in the tightest scope possible.  For example, theSum, and diceSum are only relevant inside the loop.  count is a loop counter, and it's much easier to recognize if you rewrite the loop as a for-loop.  dice1 and dice2 are only relevant inside the inner loop, which is better expressed as a do-while loop.

for (int count = 0; count < Integer.parseInt(args[0]); count++) {
    int theSum = 0, diceSum;
    do {
        int dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
        int dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
        diceSum = dice1 + dice2;
        if (diceSum != 7) {
            theSum = theSum + diceSum;
        }
        //System.out.println("the sum is "+theSum);
    } while (diceSum != 7);
    …
}

Now a picture is beginning to emerge.  The inner loop is what you would call a simulation trial.  Based on that, I would define a DiceSimulation class with a runTrial() method.  Everything else just falls into place around that core function.  ☺

public class DiceSimulation {
    private int trials = 0,                 // Formerly count
                min = Integer.MAX_VALUE,    // Formerly lowest
                max = 0,                    // Formerly finalSum
                sum = 0;                    // Formerly totalSum

    private Die die1 = new Die(),
                die2 = new Die();

    /**
     * One trial consists of tossing a pair of dice until a sum of 7 is obtained.
     * The result of the trial is the sum of all tosses up to, but not including,
     * the toss that resulted in 7.
     */
    public int runTrial() {
        int trialSum = 0, pairSum;           // Formerly theSum and diceSum
        while (7 != (pairSum = die1.toss() + die2.toss())) {
            trialSum += pairSum;
        }

        if (trialSum > max) {
            max = trialSum;
        }
        if (trialSum < min) {
            min = trialSum;
        }
        sum += trialSum;
        trials++;
        return trialSum;
    }

    public void report() {
        System.out.println("After " + trials + " simulations: ");
        System.out.println("Biggest sum: " + max);
        System.out.println("Smallest sum: " + min);
        System.out.println("The average is: " + (double)sum / trials);
    }

    public static void main(String[] args) {
        int trials = Integer.parseInt(args[0]);

        DiceSimulation sim = new DiceSimulation();
        for (int count = 0; count < trials; count++) {
            sim.runTrial();
        }
        sim.report();
    }
}


N.b. the current GitHub source already has some of these fixed.

Firstly, all lines are indented one level more than I would expect (the
first comment is also indented in the GitHub source); that seems to
break the user script annotation, as at the moment I don't see either
the description, the name, or the @match restrictions applied after
installation.

Otherwise formatting is fine, though the naming convention (upper camel
case for top level definitions) is unusual.  My editor also marks a few
lines with missing semicolon; that could be fixed just for consistency.

Even though it might not happen usually I'd ensure that all referenced
functions are defined before calling them, in this case ReplaceAll is
run from the callback, when it's only defined a few lines later.

The function ReplaceAll also returns false in a couple of cases, but
firstly, the return value isn't used anywhere and secondly, the function
doesn't return a value in one case.  I'd suggest to either always return
a value, or not at all.

The left over console.log should likely be deleted as it doesn't give
the reader much information.

In SelectBadgeProperties the regex match is done twice; it would make
more sense to only do the match and distinguish between the null
value and an actual match.

A minor gripe with ColourTransforms is that the starting # is left
out of the colour definition - this means that some external editors,
plugins, etc. won't recognize it as a colour.  I'd leave it in, in the
interest of compatibility and readability, even if it takes three
additional characters in the source.

And lastly, inserting many copies of the SVG image doesn't sound
performant, but I can't back that up with data obviously; I also doubt
that people will insert a massive number of badges and therefore this
point is kinda moot.

Otherwise looks great to complement the chat functionality.


Solving "Quadruple sum" problem using dynamic programming

Just reviewing solution 2.

1. Bugs

Some inputs cause the code to raise an exception:

>>> quadruple_sum([1, 2, 3, 4, 5], 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr185635.py", line 21, in quadruple_sum
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))
  File "cr185635.py", line 21, in <genexpr>
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))
  File "cr185635.py", line 14, in iquadruple_sum
    for s, positions in sums.items():
RuntimeError: dictionary changed size during iteration

The problem is with the line:

for (i,j) in sums[target - s]:

sums is a collections.defaultdict, and this means that if target - s is not already in the dictionary, then merely looking up the value causes the dictionary to be updated. There needs to be a guard like the one you have in solution 1:

if target - s in sums:
    for i, j in sums[target - s]:

(In practice you'd want to move the guard outside the loop over k, l as well.)
The code constructs the quadruple like this:

yield sorted((xs[i],xs[j],xs[k],xs[l]))

This means that the quadruple is sorted in order by its elements, but in the problem description it says, "Each quadruplet must have elements (input[i], input[j], input[k], input[l]), such that \$i<j<k<l\$", in other words, the quadruples must be sorted in order by their indices.

>>> quadruple_sum([4, 3, 2, 1], 10)
[(1, 2, 3, 4)] # expected [(4, 3, 2, 1)]

This also causes some quadruples to be missed:

>>> quadruple_sum([2, 1, 1, 2, 2], 6)
[(1, 1, 2, 2)] # expected [(1, 1, 2, 2), (2, 1, 1, 2)]

This problem is easy to miss if you only ever test with the input in sorted order. The correct code needs to look something like this:

yield tuple(xs[m] for m in sorted((i, j, k, l)))

2. Testing

How could you have found these bugs? By testing, of course! It's easy to spot that the problem can be solved like this:

list(set(q for q in combinations(xs, 4) if sum(q) == target))

This is inefficient (takes \$Θ(n^4)\$ in all cases) but is clearly correct, so we can use it as a test oracle together with randomized test case generation. For example,

import random
import unittest

class TestQuadupleSum(unittest.TestCase):
    def test_quadruple_sum(self):
        for _ in range(100):
            n = random.randrange(10)
            xs = [random.randrange(10) for _ in range(n)]
            if len(xs) >= 4 and random.random() < .9:
                target = sum(random.sample(xs, 4))
            else:
                target = random.randrange(sum(xs) + 1)
            expected = list(set(q for q in combinations(xs, 4)
                                if sum(q) == target))
            found = quadruple_sum(xs, target)
            self.assertCountEqual(expected, found,
                                  "xs={}, target={}: expected {} but found {}"
                                  .format(xs, target, expected, found))

This soon fails with one of the bugs in §1 above:

======================================================================
FAIL: test_quadruple_sum (cr185635.TestQuadupleSum)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr185635.py", line 59, in test_quadruple_sum
    .format(xs, target, expected, found))
AssertionError: Element counts were not equal:
First has 1, Second has 0:  (1, 5, 8, 3)
First has 0, Second has 1:  (1, 3, 5, 8) :
xs=[1, 5, 8, 7, 3], target=17: expected [(1, 5, 8, 3)] but found [(1, 3, 5, 8)]
----------------------------------------------------------------------

3. Review

The term "dynamic programming" is normally used to describe the technique in which you build up the solution for a large problem instance by combining the solutions for smaller instances of the same problem. For example, in the well-known "change-making problem" you have to count the number of ways of making change for an amount \$a\$, and in the dynamic programming approach you count the number of ways of making change for various amounts \$b < a\$ and then add them. (The name "dynamic programming" is a bit obscure and I wrote a piece about this on my blog.)

What you have here is not "dynamic programming" in the usual sense of the term, since the code does not work by finding solutions to smaller instances of the "quadruple sums" problem and then combining them.
Solution 2 makes a list of pairs of distinct indexes like this:

pairs = ((i,j) for (i,x),(j,y) in product(enumerate(xs), enumerate(xs)) if i<j)

When you want to generate distinct subsets of a collection without repetition, you need itertools.combinations. In this case you would write:

pairs = ((i,j) for (i,x),(j,y) in combinations(enumerate(xs), 2))

The code then looks up the elements at these pairs of indices, like this:

for i,j in pairs: d[xs[i]+xs[j]].add((i,j))

But in fact xs[i] and xs[j] were the values x and y that you got out of the enumeration on the previous line but then discarded! Instead of discarding these elements and then looking them up again, hang on to them and use them:

for (i, x), (j, y) in combinations(enumerate(xs), 2):
    d[x + y].add((i, j))

The value of target - s does not change in any of the inner loops, so you could cache it in a local variable and avoid recomputing it.
The two loops over positions and target - s:

for (k,l) in positions:
    for (i,j) in sums[target - s]:

can be combined into one using itertools.product:

for (i, j), (k, l) in product(positions, sums[target - s]):

The functions all_sums and iquadruple_sum are short and each is called from just one place, so it might make sense to inline them at their single point of use.

4. Revised code

def quadruple_sum(xs, target):
    "Return list of unique quadruples of xs that add up to target."
    # Map from sum to set of pairs of indexes with that sum.
    sums = defaultdict(set)
    for (i, x), (j, y) in combinations(enumerate(xs), 2):
        sums[x + y].add((i, j))
    result = set()
    for s, pairs in sums.items():
        t = target - s
        if t in sums:
            for (i, j), (k, l) in product(pairs, sums[t]):
                indexes = {i, j, k, l}
                if len(indexes) == 4:
                    result.add(tuple(xs[m] for m in sorted(indexes)))
    return list(result)


Fastest way to count non-zero pixels using Python and Pillow

Here's your implementation using Pillow:

def count_nonblack_pil(img):
    """Return the number of pixels in img that are not black.
    img must be a PIL.Image object in mode RGB.

    """
    bbox = img.getbbox()
    if not bbox: return 0
    return sum(img.crop(bbox)
               .point(lambda x: 255 if x else 0)
               .convert("L")
               .point(bool)
               .getdata())

And here's an implementation using Numpy:

def count_nonblack_np(img):
    """Return the number of pixels in img that are not black.
    img must be a Numpy array with colour values along the last axis.

    """
    return img.any(axis=-1).sum()

(We will need scipy.ndimage.imread to load the image.)

Here's a quick performance comparison using timeit.timeit:

>>> from PIL import Image
>>> import scipy.ndimage
>>> from timeit import timeit
>>> img1 = Image.open(filename)
>>> timeit(lambda:count_nonblack_pil(img1), number=10)
5.4229461060022
>>> img2 = scipy.ndimage.imread(filename)
>>> timeit(lambda:count_nonblack_np(img2), number=10)
2.3291947869875003

So Numpy is about two and a half times as fast on my example.


First of all, you should probably create lettersMap from your constructor. You don't need to create it again every time you want to get score for a word.

There are various ways to make the code shorter. The simplest method is to define the scores as an array, in the same order as the letters:

int[] letterScore = {1, 3, 3, 2 ... 4, 10};

Then your whole for-cycle gets reduced to

for (int i = 0; i < lettersCap.length(); i++) {
    lettersMap.put(lettersCap.charAt(i), letterScore[i]);
    lettersMap.put(lettersCap.toLowerCase().charAt(i), letterScore[i]);
}

However, it will also make the code less readable.

You could also define every part separately:

char[] score1letters = {'A', 'E', 'I', 'O', … 'T'};
char[] score2letters = {'D', 'G'};
...
char[] score10letters = {'Q', 'Z'}

and for every such array:

for (int i = 0; i < score1letters.length; i++) {
    lettersMap.put(lettersCap.charAt(i), 1);
    lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
}

To be honest, the most readable version will probably be:

private static final Map<Character, Integer> lettersMap;
static {
    lettersMap = new HashMap<Character, Integer>();
    lettersMap.put('A', 1);
    lettersMap.put('B', 3);
    lettersMap.put('C', 3);
    lettersMap.put('D', 2);
    ...
    lettersMap.put('Y', 4);
    lettersMap.put('Z', 10);
}

To put lowercase chars, you can either get all the keys at the end and copy their values with lowercased key, or, you can leave only uppercase letters there and instead convert the word to uppercase before calculating its score.


You don't need to make additional save method since save method already exist.

public void saveToLibrary(GooglePlayGame googlePlayGame) {
        googlePlayGameRepository.save(googlePlayGame);
    }

You have two methods one called findByTitle(String title) and findByTitleContainsIgnoreCase

To make other programmer understand whats going on maybe renaming findByTitleContainsIgnoreCase to findListOfGamesByTitlesince you are returning List and also it can be optional since games might not be there at all.
In your service call findListOfGamesByTitle just pass String (title.equalsIgnoreCase())

Why are you throwing exception at method level and also inside the body in getGameByTitle , do you want to pass that exception further ? there is no point doing it.

Yes, you should handle optional in the service layer because next layer is the constructor.

The sentence and the place you mentioned is not understood so please fix it a bit
i am referring to the following -> Maybe I should just check it in code like this (not in the service):


Can this code utilizing promises be written more succinctly?

This is Bluebird, but it's very similar to Q in syntax. Note the automatic promisification and utility methods:

var Promise= require("bluebird");
var fs = Promise.promisify(require("fs"));
var path = require("path");

var dir = "stuff";

var analyseFile = function(fileData, callback) { ... }; // Not important.

var deleteFile = function(filePath, callback) { ... }; // Not important.

var fileOps = {
    analyse: Promise.promisify(analyseFile), // do this _once_
    delete: Promise.promisify(deleteFile)
}

var processStuffDir = function() {
  return fs.readDirAsync(dir).filter(function(files) {
        return path.extname(file) === ".txt";
  }).map(function(file){
        return path.join(dir, file)
  }).map(function(file) {
      return fs.readFileAsync(file).then(function(data) {
          return fileOps.analyse(data.toString());
      }).then(function() {
          return fileOps.delete(filePath);
      });
  }).delay(15000).then(processStuffDir);
};

processStuffDir();


Multiple target method invocation wrapper

Why not expose a lambda expression like this (assuming that _subscribers is a field of type List<ICallback>):

private void InvokeCallbacks(Action<ICallback> callbackFunc)
{
    _subscribers.ForEach(callbackFunc);
}

and usage would be:

public void Method1(int a)
{
    InvokeCallbacks(callback => callback.Method1(a));
}

public void Method2(Foo foo, List<Bar> bars)
{
    InvokeCallbacks(callback => callback.Method2(foo, bars));
}

public void Method3(Bar bar, Baz baz)
{
    InvokeCallbacks(callback => callback.Method3(bar, baz));
}


First you may improve your regexps a bit using classes: replace [0-9] by \d.

In the other hand, you may strongly improve performance by:

defining an object with the unit values: units: {h: 3600, m: 60, s: 1};
modifying the 2nd regexp to directly provide the current unit:
timeStamp.replace(/(\d+)(\w)/g, function(match, value, unit) {
(note that \w is enough since your previous test eliminated any wrong value)
then using a unique computation in the function: timeInSeconds += value * units[unit];

So the entire snippet becomes:

function calculateInSeconds(timeStamp) {
  var timeInSeconds = 0,
    units = {
    h: 3600,
    m: 60,
    s: 1,
  };
  if (timeStamp.match(/t=\d*h?\d*m?\d*s?/g).toString() == timeStamp){
    timeStamp.replace(/(\d+)(\w)/g, function(match, value, unit) {
      timeInSeconds += value * units[unit];
    });
  }
  console.log(timeStamp + ' -> ' + timeInSeconds + ' seconds');
}

calculateInSeconds("t=3m59s1h"); //invalid
calculateInSeconds("t=1m59s"); //valid
calculateInSeconds("t=1h"); //valid

BTW I like the idea of your first test to isolate valid timeStamps.


1. Bugs

No use is made of the last observation. For example, if we have this model:

A = 'A', None
B = 'B', None
states = [A, B]
initial = {A:.75, B:.25}
transition = {}
emission = {A:dict(a=1), B:dict(b=1)}

And then we give it the single observation b:

>>> print(HMM(states, initial, transition, emission).best_parse('b'))
b => A  -0.12493873660829995

The conclusion is that the most likely path was to start in state A. But this is impossible, because state A can't emit the observation b!

If you look at the Wikipedia description of the Viterbi algorithm, you'll see that the initial state probabilities have to take the first observation into account. So where the code in the post has:

trellis[0][state] = start_probability.get(state, 0.0)

it should instead be:

trellis[0][state] = (start_probability.get(state, 0.0)
    * emission_probability.get(state, {}).get(observations[0], 0.0))

and then the loop over observations[0:-1] should be over observations[1:].
If the emission table has no entry for an observation, then the probability defaults to \$−∞\$:

get(observations[i], float('-inf'))

But probabilities must be between 0 and 1, so \$−∞\$ is not a probability. This leads to wrong answers because the multiplication \$0 × −∞\$ is likely to turn up somewhere in the computation, and \$0 × −∞\$ is not a number:

>>> 0 * float('-inf')
nan

(Probably you were thinking "log-likelihood" when you wrote float('-inf'). See §2.5 below.)

2. Review

There are no docstrings. What do these methods do? What should I pass? What do they return?
When you have a "class with basically a single method" then what you are looking for is a function. Not everything needs to be a class!
The result of the best_parse method is returned as a formatted string. This is not likely to be useful for anything other than development and debugging. It would be more useful to return the highest probability path as a list.
It seems very limiting that states are required to be pairs whose first element is a string.
The code computes probabilities by multiplying. But over the course of a lengthy sequence of observations this is likely to underflow the range of double-precision floating-point numbers. To avoid this, it would be better to work with the logarithms of probabilities, and add them instead of multiplying.
Just as you only need to keep two copies of the path dictionary (one for the previous observation, one for the current observation), you only need to keep two copies of the trellis dictionary.
The paths are extended by concatenatation: path[candidate_state] + [state]. But this requires copying out the whole of path[candidate_state], and as the paths get longer this takes more and more time. It would be better to represent the paths as linked lists, so that they can be constructed in constant time. Then the best path can be reconstructed by following the links.
The code requires observations to be a sequence so that it can be sliced. This means that all observations have to be acquired before you can start running the Viterbi algorithm. But since observations may take time to acquire, it would be nice if the Viterbi algorithm could be interleaved with the acquisition of the observations. This would be easy to do in Python by iterating over observations instead of slicing it.
Every time around the inner loop, this code:

max((trellis[i - 1][s] *
    transitionable.get(s, {}).get(state, 0.0) *
    emission_probability.get(state, {}).get(observations[i], float('-inf')), s)
for s in states)

has to construct two empty dictionaries (that will most likely not be needed and just get discarded), do four dictionary lookups, and build a tuple. All of this work could be avoided if you pre-processed the data so that (i) states are represented by consecutive integers starting at zero; (ii) observables are also represented by consecutive integers starting at zero; (iii) transitionable and emission_probability are represented by NumPy arrays of logarithms of probabilities (instead of dictionaries of dictionaries of probabilities).

Now, the multiplications become additions, and using NumPy we can do all the additions simultaneously like this:

logprob[:, np.newaxis] + transition + emission[:, event]

3. Revised code

import numpy as np

def likeliest_path(initial, transition, emission, events):
    """Find the likeliest path in a hidden Markov Model resulting in the
    given events.

    Arguments:
    initial: arraylike(n) --- probability of starting in each state
    transition: arraylike(n, n) -- probability of transition between states
    emission: arraylike(n, e) -- probability of emitting each event in
        each state
    events -- iterable of events

    Returns:
    path: list(int) -- list of states in the most probable path
    p: float -- log-likelihood of that path

    """
    # Use log-likelihoods to avoid floating-point underflow. Note that
    # we want -inf for the log of zero, so suppress warnings here.
    with np.errstate(divide='ignore'):
        initial = np.log10(initial)
        transition = np.log10(transition)
        emission = np.log10(emission)

    # List of arrays giving most likely previous state for each state.
    prev = []

    events = iter(events)
    logprob = initial + emission[:, next(events)]
    for event in events:
        # p[i, j] is log-likelihood of being in state j, having come from i.
        p = logprob[:, np.newaxis] + transition + emission[:, event]
        prev.append(np.argmax(p, axis=0))
        logprob = np.max(p, axis=0)

    # Most likely final state.
    best_state = np.argmax(logprob)

    # Reconstruct path by following links and then reversing.
    state = best_state
    path = [state]
    for p in reversed(prev):
        state = p[state]
        path.append(state)
    return path[::-1], logprob[best_state]


Creating a Tkinter window that generates seven numbers from 1 - 49 and sorts them

Don't use wildcard imports

Instead of doing from tkinter import *, use import tkinter as tk and then prefix your use of tkinter objects with tk. (eg: tk.Tk(), tk.Label(...), etc)

Use an array to keep track of multiple identical widgets.

Whenever you have a number as part of a variable name, that's a code smell telling you there's probably a better way. Instead of Lab1, Lab2, etc, put the labels in a  list:

labels = []
for column in range(7):
    label = tk.Label(win , relief = 'groove' , width = 2)
    label.grid(row = 1 , column = column+1 , padx = 10
    labels.append(label)

Later, when you need to reconfigure the widget you can use the global labels like so:

for i in range(5):
    labels[i].configure(text=picks[i])

Follow PEP8

You should follow the naming conventions of PEP8. Specifically, don't use an uppercase character as the first letter of a variable name.

Don't turn off the ability of the user to resize the window

Don't do win.resizable(False,False). Users should be able to control their window size.

Use sticky appropriately

When using grid, you should almost always explicitly set the sticky attribute. It's rate to need to put something in a grid cell and not have it expand or contract to fit that cell.

Set row and column weights

When using grid, you should always give at least one row and one column a non-zero weight. If you don't want your rows and columns to grow and shrink when the user resizes the window, give the weight to an empty column to the right of all other columns, and to the row below all other rows. This will explicitly tell tkinter to allocate extra space to the edges.

Don't include unnecessary imports

It doesn't look like you're using the turtle module, so remove the import.


I'm familiar with RxSwift, not RAC. :-( That said, I think I can say something constructive about this code...

sig0 and sig1 need more descriptive names.

I would be inclined to break up the combined.subscribeNext function. Something more like:

let buttonEnabled = RACSignal.combineLatest([sig0, sig1])
    .map { obj in
        let tup = obj as! RACTuple // Wow RAC doesn't return type safe values?
        return (tup.first as! Bool) && (tup.second as! Bool)
    }

buttonEnabled.subscribeNext { obj in
    let valid = obj as! Bool
    self.button.enabled = valid
}

I strongly suspect that there is a function for mapping the buttonEnabled signal directly to the button though, maybe with an Action? You should look into that.


Python - Knight's tour recursive function

I don't have much to say about this, only a few small nitpicks.

self.height might be a better name, (width and height) make more sense to me. But this might be subjective.
At is_ligit_move() you could use, elem in range(), because range is special. See this excellent description by @Graipher for more details.
At available_moves you could use list comprehension instead of the res variable

So your res would be this:

return [elem for elem in possible_moves if self.is_legit_move(elem)]

It does the same but looks a little cleaner. See PEP202 for more information.

Overall I think you have crafted a nice piece of code!


Prompting for confirmation

The way you're doing the prompt is overly complicated. Consider this:

[CmdletBinding(SupportsShouldProcess=$true)]
param()

$switchTitle = "Terminate User"
$confirmMessage = "Are you sure that " + $fullName + " is the user that you want to terminate?"

if ($PSCmdlet.ShouldContinue($confirmMessage, $switchTitle)) {
    # She said yes!
} else {
    # nope
}

I sometimes wrap this up into a small function that allows for quicker usage if it's always for a single purpose within a script and I need it a lot:

function Get-Confirmation {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
    [Parameter(Mandatory=$true)]
    [String]
    $User
)

    $confirmMessage = 'Are you sure that {0} is the user that you want to terminate?' -f $User

    $PSCmdlet.ShouldContinue($confirmMessage, 'Terminate User?')
}

Then just use it like so:

# code that populates $fullName
if (Get-Confirmation -User $fullName) {
    # terminate
} else {
    # don't terminate
}

Referencing files

Copy-Item -Path "Microsoft.PowerShell.Core\FileSystem::\\Path\To\UserFolder" `
-Destination "Microsoft.PowerShell.Core\FileSystem::\\path\To\TermFolder" -Recurse -Force

You don't have to use the full provider name to reference a file, even for a UNC path.

It would be fine to just do this:

Copy-Item -Path "\\Path\To\UserFolder" `
-Destination "\\path\To\TermFolder" -Recurse -Force


I think you just can get rid of getAll() function as it is just a special case of searchID().

 function searchID() {
     var id = document.getElementById("search").value;
     $("#customers").html("");

     $.getJSON("http://localhost:8080/customer/" + id,
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $('#customers').append("
ID: " + customer.userId + "
");
                     $('#customers').append("
First name: " + customer.fName + "
");
                     $('#customers').append("
Last name: " + customer.lName + "

");
                 });
       });
  }

If the id value is empty then the results it's exactly the same as getAll().

Another important thing to change is the url, if your server is the same, you can just remove the initial part:

$.getJSON("/customer/"...);

This helps to avoid bugs in the future or need of refactoring if you just simply add https.

Cache the jQuery search to avoid the repeat:

 function searchID() {
     var $customers = $("#customers");
     var id = document.getElementById("search").value;
     $customers.html("");

     $.getJSON("http://localhost:8080/customer/" + id,
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $customers.append("
ID: " + customer.userId + "
");
                     $customers.append("
First name: " + customer.fName + "
");
                     $customers.append("
Last name: " + customer.lName + "

");
                 });
       });
  }

Here is an example inside the searchID() function, if you use in all the module, you should save as a module variable.

Another thing is that is not responsability of searchID() to know how to get the id:

 function searchID(id) {
     var $customers = $("#customers");
     $customers.html("");

     $.getJSON("http://localhost:8080/customer/" + id,
       function(data) {
                 ([].concat(data)).forEach(function(customer) {
                     $customers.append("
ID: " + customer.userId + "
");
                     $customers.append("
First name: " + customer.fName + "
");
                     $customers.append("
Last name: " + customer.lName + "

");
                 });
       });
  }

Instead you should add a new function:

function performSearch() {
    var id = document.getElementById("search").value;
    searchID(id);
}

And the same for the draw of the customers on the page:

function displayCustomers($el, customers) {
    $el.html("");

    customers.forEach(function(customer) {
           $el.append("
ID: " + customer.userId + "
");
           $el.append("
First name: " + customer.fName + "
");
           $el.append("
Last name: " + customer.lName + "

");
    });
}

And then:

function performSearch() {
    var id = document.getElementById("search").value;
    searchID(id, function(customersToDisplay) {
        displayCustomers($("#customers"), customersToDisplay);
    });
}

And the new searchID():

 function searchID(id, callback) {
     $.getJSON("/customer/" + id,
       function(data) {
           callback(([].concat(data));
       });
  }

In this way you separate the different aspects:

handle the dom event and launch a command accordingly;
perform an ajax request and handle the harmonization of the response.
use a callback to handle the ajax response
update the DOM


Using a List<int> instead of int[] allows your code to not only be more dynamic but also to leverage the GetRange method of the List.  This simplifies your code to only 2 loops.

Creating the list would look something like this:

int number;
List<int> Numbers = new List<int>();
for(int i = 0; i <= 4; i++)
{
    number = 0;
    bool good = false;
    while(!good)
    {
        Console.WriteLine("Input number {0}", i + 1);
        if(int.TryParse(Console.ReadLine(), out number))
        {
            Numbers.Add(number);
            good = true;
        }
        else
            Console.WriteLine("Invalid input, try again");
    }

}

The sub routine to get the subsets could look something like this:

public static List<List<int>> AllSubsets2(List<int> mainset, int targetsum)
{
    List<List<int>> outval = new List<List<int>>();
    for(int num2 = 0; num2 < mainset.Count; num2++)
    {
        if(mainset[num2] == 0)
            outval.Add(new List<int>{mainset[num2]});
        int sum = mainset[num2];
        for(int num = num2+1; num < mainset.Count; num++)
        {
            sum += mainset[num];
            if(sum == 0)
                outval.Add(mainset.GetRange(num2, num - num2));
        }
    }

    return outval;
}

This will return a list of all the subsets that add up to the target sum.


Two things could be improved, otherwise it looks good:

_.isEqual alone should be enough for an equality check, i.e. the
check for object equality is implied.
console.log might not be available.


You have the right idea, I just want to make a few remarks:

You could have used _ in the first and the last clause of your function in place of the ignored arguments. It might help readability to know right away that an argument is being ignored.
You're explicitly throwing an error on invalid input which is fine. A good error message could be more helpful to the caller than just getting a pattern match fail. However it wouldn't have shocked me if you had omitted that last line. An even safer solution is having the function return Just a when the input is valid and Nothing when it's not, but for performance/convenience's sake many partial functions out there don't do that.

EDIT: To elaborate more on the safer solution point I mentioned earlier: lastButOne has type lastButOne :: [a] -> a. However this type fails to convey that lastButOne is a partial function, and therefore may fail on certain inputs. It's very easy for a caller to overlook that he needs to watch out for invalid inputs. However, had you defined lastButOne as lastButOne :: [a] -> Maybe a instead, then the fact that it might not produce a result for some inputs, is directly encoded in the type of the function, thus making it type safer. Any caller of lastButOne couldn't possibly overlook that he needs to handle failure.

In case you haven't heard of Maybe yet, it's a data structure that is used to elegantly express a computation that may fail. Examples:

my_div :: Integer -> Integer -> Maybe Integer
my_div _ 0 = Nothing
my_div a b = Just (div a b)

lastButOne :: [a] -> Maybe a
lastButOne [a, _] = Just a
lastButOne (_:xs) = lastButOne xs
lastButOne _ = Nothing


Implementing the merge sort with only arrays, out of place

Try not to use using namespace std.
Code within a function should be indented as well.  You already do this with other code blocks, and the same applies to functions.
Just avoid Hungarian notation:

int iArray;

We already know it's an int array.
Prefer not to pass C arrays to functions in C++.  This causes them to decay to a pointer; it does not actually pass the array itself.

Instead, pass in a storage container, such as an std::vector.  Storage containers will not decay to a pointer, and they're more idiomatic C++.

If you have C++11, initialize the vector using list initialization:

std::vector<int> values { 2, 5, 6, 4, 7, 2, 8, 3, 9, 10 };

If you don't have C++11, declare it and call push_back() for each value:

std::vector<int> values;

values.push_back(2);
values.push_back(5);
// ...

Pass it to a function with such parameters:

void merge_sort(std::vector<int> values, int startIndex, int endIndex) {}

As its implementation is that of an array, you can still access its elements with [].  You can also use its iterators (more preferred).

Storage containers do the memory allocation for you, so you will not need new/delete.  It's best to do as little manual memory allocation as possible in C++.


Your code is good, but there's a few things you can improve on:

            $(this).data("resizable-alsoresize-reverse", {
                width: parseInt($(this).width(), 10),
                height: parseInt($(this).height(), 10),
                left: parseInt($(this).css('left'), 10),
                top: parseInt($(this).css('top'), 10)
            });

You can use an unary instead of parseInt:

            $(this).data("resizable-alsoresize-reverse", {
                width: +$(this).width(),
                height: +$(this).height(),
                left: +$(this).css('left'),
                top: +$(this).css('top')
            });

This doesn't really look like you're storing anything.

var _store = function (exp)

It looks more like you're setting up css rules and what is exp?

You should be more descriptive with your function and variable names.

I would avoid omitting the var keyword as it makes the code harder to maintain in future.

    var self = $(this).data("resizable"),
        o = self.options,
        os = self.originalSize,
        op = self.originalPosition;

Imagine you're a contractor coming in to improve this plugin and you accidentally remove the , after self's assignment. All of a sudden you've got a bunch of troublesome globals.

Sticking to adding the var keyword on every line is a practise best kept early.

Your choice of variable assignment is strange:

Here, you assign os and op,

    var self = $(this).data("resizable"),
        o = self.options,
        os = self.originalSize,
        op = self.originalPosition;

But in the following block, you don't bother assigning self.size.* variables.

    var delta = {
        height: (self.size.height - os.height) || 0,
        width: (self.size.width - os.width) || 0,
        top: (self.position.top - op.top) || 0,
        left: (self.position.left - op.left) || 0
    },

Don't assign variables you don't need to.

Making o a shorthand accessor for your options variable is unclear, o can represent many other things. Try to be a little more clear with your variable assignment, and additionally try to avoid abbreviations.

event and ui are passed in as parameters into your three parent functions of start, resize and stop, yet they're never actually used. Remove unnecessary parameters.

You have a lot of extraneous lines, I would try to avoid that, really only leaving lines when necessary.

In your data strings, you have the following resizable-alsoresize-reverse, you should be adding a space (-) between also and resize.


Parsing financials from a YAML file. Is this normal/idiomatic in Rust?

Structure your data
The reason you need nested matches is that even after parsing the YAML document into a Yaml object, it's still essentially unstructured data. Not every YAML object will have the right shape, so you have to validate it piece by piece as you traverse it. Worse, you'll have to validate it all over again next time you try to traverse it. This is inefficient and ugly.
Define some data structures that will hold the information currently held in a YAML document. How you define these depends on how rigid the data format is and what you plan to do with it. Here's one way to do it. You'll need to add chrono to your dependencies.
use chrono::NaiveDate as Date;

struct Document {
    by_date: HashMap<Date, Expenses>,
}

struct Expenses {
    by_category: HashMap<String, Vec<Entry>>,
}

struct Entry {
    payee: String,
    payments: Vec<f32>,
}

Define what it means to total up the whole Document by deferring to its contents:
impl Document {
    fn total(&self) -> f32 {
        // the total of a Document is the sum of the total expenses on each date
        self.by_date.values().map(|expenses| expenses.total()).sum()
    }
}

impl Expenses {
    fn total(&self) -> f32 {
        // the total is the sum of the totals of each Entry in each category
        self.by_category.values().flat_map(|entries| entries.iter().map(Entry::total)).sum()
    }
}

impl Entry {
    fn total(&self) -> f32 {
        // the total is the sum of all the individual payments
        self.payments.iter().sum()
    }
}

Note 1: I am completely ignoring the printing part of unwrap_value. You could add that to the above code relatively easily, but it would be noisy and not super instructive, so I'm just going to focus on the totaling.
Note 2: It might sometimes be useful to write a Total trait and implement it for Entry, Document and Expenses, instead of having three unrelated functions. But it doesn't seem useful here, so I didn't.

Deserialize with Serde
Now, the only problem that remains is how to turn a YAML document into a Document. You could write code to convert from a Yaml object, but the bulk of the work has been done for you already by the Serde library. Serde is an extremely versatile library for serialization and deserialization of just about any Rust data structure from just about any data format. Any time you're considering serialization, unless you know you need something specific, it's a good idea to start with Serde. You'll need to add serde, serde-yaml and serde-derive to your dependencies.
When the data format is flexible, you might just add #[derive(Deserialize)] on all your structs to get the default behavior. In this case, since there's a particular YAML format we're trying to match, we need to add some annotations to explain to Serde just how to put things together. I used chrono::NaiveDate in part because it already implements Deserialize, which makes this task easier by half.
#[derive(Deserialize)]
#[serde(transparent)]
struct Document {
    by_date: HashMap<Date, Expenses>,
}

#[derive(Deserialize)]
#[serde(transparent)]
struct Expenses {
    by_category: HashMap<String, Vec<Entry>>,
}

#[derive(Deserialize)]
#[serde(try_from = "HashMap<String, String>")]
struct Entry {
    payee: String,
    payments: Vec<f32>,
}

impl TryFrom<HashMap<String, String>> for Entry {
    type Error = String;
    fn try_from(value: HashMap<String, String>) -> Result<Self, Self::Error> {
        for (payee, etc) in value {
            let payments = etc.split('+')
                .map(|s| s.trim().parse::<f32>())
                .collect::<Result<_, _>>()
                .map_err(|e| e.to_string())?;
            return Ok(Entry { payee, payments });
        }
        Err("Empty map".to_owned())
    }
}

I didn't have to actually write any code for Document and Expenses; I just used the serde(transparent) attribute to tell Serde to treat those structs exactly the same as their contained types. For Entry, since Serde's YAML deserializer can already parse a string like rent: 2750 into a HashMap<String, String>, I just implemented TryFrom<HashMap<String, String>> and told Serde to use that. This handy trick requires less code and is easier to wrap your head around than a full Deserialize implementation, but may be slightly slower.
Now all we have to do is use it:
let doc: Document = serde_yaml::from_str(&doc).unwrap();
println!("total: {}", doc.total());

For a small initial investment in code, your data is now made of meaningful, Rusty types like Date and HashMap instead of all different Yaml values. You can add a little bit more code to also support serialization, and because Serde is a general purpose (de)serialization library and not a particular data format, switching to another format like JSON or bincode (should you want to) is just a couple lines of code.
And another thing
Floating-point numbers are bad for money because they have variable precision. Use a decimal library, or fixed-point arithmetic (i.e. store an integer number of the smallest possible amount of money – cents instead of dollars.) If you absolutely must use floating-point numbers, at least use f64, and don't say I didn't warn you not to.


Counting points on a given irregular grid that are inside or outside a circle

Well, you are manually testing every point \$(X_i, Y_j)\$ to see where it falls. You shouldn't, really.
Remember the sage advice: If in doubt, sort.

A better algorithm goes:

Read all X-coordinates.
Change them to squared distance from center-line.
Sort them.
Read an Y-coordinate.
Calculate the squared-distance from center-line for X-coordinates leading to the point sitting on the circle. \$\Delta x^2 = r^2 - (y - r)^2\$
Use binary search to determine how many elements from point 3 are smaller/equal/greater than the target.
Repeat at 4 until done.

Your algorithm was \$O(n \cdot m)\$. This one is \$O((n + m) \cdot \log(n))\$.

As an aside, if you simply double the given coordinates before processing them, you don't have to insist on the largest being even.

Now let's take a look at your code:

unsigned only has a minimal maximum of \$2^{16}-1\$, less than \$10^7\$. Even if it had 32 value-bits as on most desktops, \$2^{32}-1\$ is still below \$10^{14}\$. So, use long long which has a guaranteed 64 value-bits.
Why do you use double as the result of distance_squared()? If you did the calculation with double it would be accurate, though slow, but you only convert implicitly on return, which is far too late to help.
An unsigned is cheaply copied. Passing it by constant reference is actually a pessimization, luckily the optimizer will inline it so no harm done.
return 0; is implicit for main().
You should always finish your output with a newline. Not doing so means the prompt after calling the program won't be on a new line, and on ancient systems could have even less desirable outcomes.
The one time you use continue; it doesn't actually have any effect.
Some people like putting single-statements on the same line as the corresponding if, else if or else. I would desist as it impairs readability.
All else being equal, try to define any variable in the smallest scope you can, so a reader doesn't have to trace it all over the place. Concentration is a resource best preserved where possible.
inline only has the effect of allowing multiple equivalent definitions left. If it's only used in the current TU, better mark it static to get internal linkage.
Also consider defining a function before its use so you don't have to add a separate declaration. Remember, don't repeat yourself (DRY).
Restrict line-length so there's no horizontal scrolling. Horizontal scrolling, especially couple with vertical scrolling, is the bane of readability.


Program follows sequence of instructions to arrive at destination

Take a look at Bruce Hauman's answer to the question: https://github.com/bhauman/advent-of-clojure-2016/blob/master/src/advent_of_clojure_2016/day1.clj

One thing that was an eye-opener to me is how we all (my answer had :east and :west etc) fall into the trap of having of describing reality rather than just solving the problem with as simple as possible data structures. You can see how little code he had to write - no need for State, no need for functions describing which way was turned. Albeit his advantage was knowing about reductions, which give a path back for every step taken.


Showing a message when the column is true

There's a lot of great work here, I have a few suggestions, I'll start with a few recommended changes, and finish with some suggestions for improvements.

Let's firstly take a look at your migration.

Do not set a default on a foreign key column. Your user_id defaults to 0, which could be an actual user record, so if a record was ever (somehow) created or modified to without a user_id, it would suddenly belong to that user.

You can take this opportunity to add an index on the user_id for the posts table, it will make certain requests significantly faster, such as looking up all of the posts belonging to one user.

Moving on to your view.

You can add a method to your Post model to indicate if the post has no tags. Rather than using !post.tag_1 && !post.tag_2 && !post.tag_3 && !post.tag_4 in the view, we can make a method to handle that logic for us.

Imagine something like this in your Post model:

def no_tags?
  !tag_1 && !tag_2 && !tag_3 && !tag_4
end

This would mean you could change your view from:

<% if !post.tag_1 && !post.tag_2 && !post.tag_3 && !post.tag_4 %>

none

<% end %>

to:

<% if post.no_tags? %>

none

<% end %>

which I think reads a lot more easily. This kind of method, where you're not modifying data but simply reading it, is sometimes refactored (tidied up) using design patterns like decorators or presenters. It's common to have methods that are really only used for the presentation of data, rather than manipulation, and those design patterns can help keep them away from the business logic of the model.

Those are the first minor changes I'd make to this code, without significantly changing the architecture. If you wanted to take it further, however, I would suggest the following.

It's clear from what you've said in your post that you can see there's something not quite right. Those conditionals in the view are probably the obvious 'smell'.

Think through a moment, and consider what you would do if you needed to add another tag.

You'd first need to add a column in the posts table, to store the boolean value. You'd need to modify our new no_tags? method to include tag_5, and you'd need to change the view to add another conditional, checking to see if tag_5 was present.

I think you'll be much better off if you define a many-to-many relationship between the Post model and a new Tag model. Each tag model can have a name, and your post model will has_and_belongs_to_many tags, allowing you to change your view code to something like:

<% post.tags.each do |tag| %>

<%= tag.name %>

<% end %>

I recommend you read the rails guide on relationships, specifically: https://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference


Member names

The code is confusing because it involves neither event dispatch nor event handling - therefore is nothing to do with events - yet there are member names evt and events, where :

the evt vars are actually uids used as object keys
the events object contains references to methods.

The loose-coupled nature of Pub/Sub does indeed tempt you into believing that it involves events. But no, it does not (at least typically not, and certainly not here). Whereas a Pub and its corresponding Subs can be in completely diffferent parts of the code base, when a Pub fires it informs the subscribers synchronously, in the same event thread.

Similarly, the subscriptions object is not well named. It receives objects which can themselves be subscribed to, not subscriptions directly. If anything was to be named "subscriptions" it would be SubscriptionsBag's self.handlers - each handler is effectively a subscription.

Leveraging jQuery.Callbacks

You are already using jQuery - great!

The jQuery documentation includes a really neat example under jQuery.Callbacks(), showing how Callbacks() instances can be exploited for Pub/Sub.

If you were to adopt this approach, it would :

take all the pain out of having to write/test your own .add(), .cancel() and fire() methods
replace your SubscriptionsBag() with a Topic() constructor
replace your subscriptions repository with a topics repository
give you nice monads that will method-chain.

You need do little more than adopt jQuery's code and assign the Topic constructor to your chosen namespace in lieu of jQuery, and trap the topics repository in a closure (or otherwise avoid the global namespace).

(function (lib, topics) {
    lib.Topic = function Topic (id) {
        var callbacks,
            topic = id && topics[id];
        if (!topic) {
            callbacks = jQuery.Callbacks();
            topic = {
                publish: callbacks.fire,
                subscribe: callbacks.add,
                unsubscribe: callbacks.remove
            };
            if (id) {
                topics[id] = topic;
            }
        }
        return topic;
    };
})(window.mylib, {});

Thus, your versions of the usage examples in the jQuery documentation would be :

// Subscribers
window.mylib.Topic( "mailArrived" ).subscribe( fn1 );
window.mylib.Topic( "mailArrived" ).subscribe( fn2 );
window.mylib.Topic( "mailSent" ).subscribe( fn1 );

// Publishers
window.mylib.Topic( "mailArrived" ).publish( "hello world!" );
window.mylib.Topic( "mailSent" ).publish( "woo! mail!" );

And an example involving asynchronously derived data :

// Subscriber
var mailArrivedTopic = window.mylib.Topic("mailArrived").subscribe(fn1); // Note how the subscribe() method returns the Topic instance (monadic behaviour).

// Publisher
$.ajax({...}).then(mailArrivedTopic.publish);


Replacing letters with numbers with its position in alphabet

First of all, you don't need to hardcode the letters and their positions in the alphabet - you can use the string.ascii_lowercase.

Also, you don't have to call list() on a new_text - you can just iterate over it character by character.

Then, what if we would construct a mapping between letters and letter indexes in the alphabet (with the help of enumerate()). Then, use a list comprehension to create an array of numbers which we then join to produce a result:

from string import ascii_lowercase

LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)}

def alphabet_position(text):
    text = text.lower()

    numbers = [LETTERS[character] for character in text if character in LETTERS]

    return ' '.join(numbers)


Ultimate functor class which can read/write to l-values/r-values

Assuming C++20, we can constrain the template (similar to your attempt at static_assert).  The key is that Args... can contain rvalue-references, but we need to convert those to lvalue types, because that's what we present to the function:
#include <concepts>

    template<typename... Args>
    inline auto operator()(Args&&... args)
        requires std::invocable<Functor, std::add_lvalue_reference_t<Args>...>

I don't see anything else I would propose improving.


A bitwise common prefix algorithm in Python

Is my algorithm slow because it has problems?

Yes. The fundamental problem is that it always processes every character of the input.

There are some obvious improvements which don't address this fundamental problem:

Since the common prefix can't be more than min_len, truncate both strings to min_len before encoding them.
bin returns a string, so str(bin(...)) is overkill.
bin(int(a[::-1].encode('hex'), 16) ^ int(b[::-1].encode('hex'), 16)) is also overkill: what you care about is the position of the lowest set bit of int(a[::-1].encode('hex'), 16) ^ int(b[::-1].encode('hex'), 16). You can extract the lowest set bit directly from the integer as

differences = int(a[::-1].encode('hex'), 16) ^ int(b[::-1].encode('hex'), 16)
least_significant_difference = differences ^ (differences - 1)

(That actually gives a binary number which is all 1s from the lowest set bit to the least significant bit).

Then you can either convert to string and find the length, or take the logarithm base 2.

But the fundamental problem is still there: the fastest code is the code which isn't executed, and when the prefix is very short then a simple loop from the start which compares characters is hard to beat. If you really have to beat it, I think you're probably looking at writing some C which coerces a pointer to (16-bit?) characters into a pointer to 64-bit integers and uses that to compare a block of characters at a time. Beware endianness.


Is there a way to eliminate the repetition in this linq query?

Apply the common refactoring used for repeated code: extracting a method. In your case, creating the method won't be trivial, because you want to create a different Expression each time. That is, unless you use LINQKit:

public static IQueryable<T> WhereEqualsByPatIndex<T>(
    this IQueryable<T> query, string value, Expression<Func<T, string>> propertyExpression)
{
    if (string.IsNullOrEmpty(value))
        return query;

   return query.Where(
       ex => SqlFunctions.PatIndex(
           value.Trim(), propertyExpression.Invoke(ex, propertyExpression).Trim()) > 0);
}

Usage would be like this (that call to AsExpandable() is important):

dc.Retailers
  .AsExpandable()
  .WhereEqualsByPatIndex(firstName, ex => ex.FirstName)
  .WhereEqualsByPatIndex(lastName, ex => ex.LastName)


Validating and saving a user profile, using fat model vs. view code

Yes, using MVC frameworks, or in case of Django modified term MTV (Model-Template-View) you will often hear the expression "Fat models, thin controllers". I do think it is a good idea and the business logic should be put into the model.

In your case the method create_candidate_profile is performing a database operation. More important it changes the database and persists data to it.

Data persistence should be done in the model. So, yes, I'd say the second version is definitely the way to go.

In future you might want to add another possibility for creating candidate profile, maybe through a custom command. Then you can make use of this model method:

User.create_candidate_profile(
    name, mobile_phone, notification_type, password
)

The only line in the code I'd slightly change is the following:

activation_key = self.kwargs['activation_key']

should become:

activation_key = self.kwargs.get('activation_key', 'deafult value')

That is just for the case that self.kwargs doesn't have the key activation_key, so you can pass some default value, maybe an empty string ''.


Optimize strcmp chains
Some of your functions use strcmp() repeatedly.  You could make those functions faster by eliminating the multiple calls to strcmp() and using switch statements instead.  This function:

static bool is_operator(char *token)
{
    return (strcmp(token, "/") == 0 || strcmp(token, "*") == 0 ||
            strcmp(token, "%") == 0 || strcmp(token, "+") == 0 ||
            strcmp(token, "-") == 0);
}

would become:
static bool is_operator(const char *token)
{
    if (token[1] != '\0')
        return false;

    switch (token[0]) {
        case '/':
        case '*':
        case '%':
        case '+':
        case '-':
            return true;
        default:
            return false;
    }
}

This function:

static int eval(int a, int b, char *op)
{
    if (strcmp(op, "/") == 0)
        return a / b;
    if (strcmp(op, "*") == 0)
        return a * b;
    if (strcmp(op, "%") == 0)
        return a % b;
    if (strcmp(op, "+") == 0)
        return a + b;
    if (strcmp(op, "-") == 0)
        return a - b;

    return 0;
}

could become:
static int eval(int a, int b, const char *op)
{
    switch (*op) {
        case '/':
            return a / b;
        case '*':
            return a * b;
        case '%':
            return a % b;
        case '+':
            return a + b;
        case '-':
            return a - b;
        default:
            return 0;
    }
}

Notice I also added a const to your string arguments because they aren't modified by your functions.
Confusing variable names
This code confused me a little:

        int operand1 = stack_pop(s);
        int operand2 = stack_pop(s);
        stack_push(s, eval(operand2, operand1, token));

Here, operand1 is actually the second operand, and operand2 is actually the first operand, as you can see from the call to eval().  I would have rewritten it like this, because otherwise it would get confusing if someone were stepping through it with a debugger and examining variable values:
        int operand2 = stack_pop(s);
        int operand1 = stack_pop(s);
        stack_push(s, eval(operand1, operand2, token));