Your code seems good to me. It's readable, well structured and formatted. So just a couple of minor points:

When implementing a list, it's always a good idea to implement the List interface, as it's well thought out.

The main differences to your interface I am seeing:

naming: your method names contain an xIndex at the end. This isn't really needed, as the argument name index already suggests this.
extra methods: you have a lot of methods which deal with the corner cases of other methods. So eg you have deleteFromBeginning, deleteFromEnd, and deleteFromIndex (same for add and get). This doesn't really seem necessary. List for example only has this for add, as adding happens quite often. It doesn't happen so often to want to delete from the beginning/end though.
extra public methods: you also have some methods which are just not needed. decrementCount isn't needed and will cause problems when used, as the size will be wrong then. getHead is also not needed, it just exposes Node, which isn't really needed outside of the list context. Just make these private.
you are missing some useful methods and your list is not generic, I'm assuming that both are on purpose as this is just for practice.

Misc

Node should be a private class of LinkedList, as it's not needed outside of the list at all.
I would use this for fields. It's a question of preference, but I prefer it as it makes it explicit where the variable comes from.
initialize size explicitly to 0 in the constructor.


Search for the longest sequence of toggled consecutive bits in an integer

Before we make any changes, let's add some tests to the end, so we have confidence that we don't break anything that worked:

#include <stdio.h>
static int test(unsigned int value, unsigned int expected)
{
    unsigned int actual = findsaw(value);
    if (actual == expected)
        return 0;
    printf("findsaw(%#x) = %u\n", value, actual);
    return 1;
}

int main()
{
    return test(0x0, 0)
        +  test(0xAA, 0)
        +  test(0x585, 0)
        +  test(0xA0F, 8)
        +  test(0xF0A, 0)
        +  test(0xFA0, 4)
        +  test(0xEAEA476Bu, 23);
}

This all passes (the program returns 0).  I made test take the value as an unsigned int, because 0xEAEA476B is too big for a plain int on my system.

Now let's look at your code.

#include <stdio.h>
#define YES 1 /* inside a sequence */
#define NO 0 /* outside a sequence */

We're not using anything from <stdio.h>, so that's not required.  Also, instead of defining YES and NO in the preprocessor, we could include <stdbool.h>, and then use true and false instead.

unsigned int findsaw(int value) {
    unsigned int sequence = value;

Are you required to accept input as a signed integer?  If not, then declare findsaw() to take an unsigned int.  As it is, the last test case (from the question's code) produced a compilation warning, as 0xEAEA476BL is larger than INT_MAX on my system.

unsigned char idx = 0;
unsigned char sequenceIdx = 0;
unsigned char currentIdx = 0;
unsigned char size = 0;
unsigned char sequenceSize = 0;
unsigned char bit = value & 1;
unsigned char nextBit;

None of these really need to be char.  It's probably better to let them be int (or uint_fast8_t if you're really keen).

These names aren't immediately obvious to me (or to you in six months' time).  It might be worth grouping them so that idx and size, which represent the best match so far, are placed together, with a comment explaining that.  Similarly, sequenceIdx and sequenceSize seem to represent the current in-progress match, and should go together.

Some of the naming was alien to me: I'd have considered what you call the "next" bit to be "current", and what you call just "bit" to be "last_bit".  That might be just me, though.

    if (bit ^ nextBit) {

A comment would be nice here: this is true when we're matching the sawtooth pattern.  Also, the else branch contains actions that are only needed immediately at the end of a sequence, and do nothing for extended runs such as 0x00 or 0xFF, so that can be else if (insideSequence).

We can save a bit of work here:

        /* matched a transition */
        if (insideSequence) { /* just add to the size */
            sequenceSize++;
        } else {
            /* initialize for inside a sequence */
            sequenceSize = 2;
            sequenceIdx = currentIdx;
            insideSequence = true;
        }

If we initialise sequenceSize to 1 instead of 0, then we can simply increment it in both cases (i.e. outside the if).  We can use sequenceSize == 1 to determine whether we're in a sequence, and we no longer need the insideSequence variable (nor <stdbool.h>):

unsigned int findsaw(unsigned int value) {
    unsigned int sequence = value;

    /* best match so far */
    unsigned int best_start = 0; /* this is what we're looking for */
    unsigned int best_size = 0;

    unsigned int sequenceIdx = 0;
    unsigned int currentIdx = 0;
    unsigned int sequenceSize = 1;

    while (sequence) {
        const int last_bit = sequence & 1;
        sequence >>= 1;
        const int current_bit = sequence & 1;
        if (last_bit ^ current_bit) {
            /* matched a transition */
            if (sequenceSize++ == 1) {
                /* the start of a new sequence */
                sequenceIdx = currentIdx;
            }
        } else if (sequenceSize != 1) {
            /* not matched - did we just finish a sequence? */
            if (best_size < sequenceSize) {
                best_size = sequenceSize;
                best_start = sequenceIdx;
            }
            sequenceSize = 1;
        }
        ++currentIdx;
    }
    if (best_size < sequenceSize) {
        best_start = sequenceIdx;
    }
    return best_start;
}

Let's see if we can do anything about the duplication of if (best_size < sequenceSize) when we reach the last bit.  I'll add a couple of extra tests:

    +  test(0x50000005u, 27)
    +  test(0xA0000005u, 0)

The last one fails (returns 28), because we are zero-extending the left of the value, but not the right.  If we simply take out the test, then other test cases fail (0xa0f and 0x50000005).  It seems that the while (sequence) returns too early in those cases.

At this point, I give up fixing this and look at a different approach.  We don't need to check last_bit ^ current_bit every time around the loop - we can compute them all at the same time like this:

unsigned int sequence = value;
unsigned int mask = sequence ^ (sequence >> 1);

This produces a 1 everywhere we have a bit preceded by its complement.  We still have the problem that the high bit might be set, but we can fix this by writing mask = sequence ^ (sequence << 1) to make the low bit the stray one, and we can just shift that out.  Now, all we have to do is find the longest run of 1s:

unsigned int findsaw(unsigned int value)
{
    unsigned int sequence = value;
    unsigned int mask = sequence ^ (sequence << 1);

    /* best match so far */
    unsigned int best_start = 0; /* this is what we're looking for */
    unsigned int best_size = 0;

    /* current run */
    unsigned int current_start = 0;
    unsigned int current_size = 0;

    /* current position */
    for (unsigned int i = 0;  mask >>= 1;  ++i) {
        if (mask & 1) {
            if (!current_size++)
                /* the start of a new run */
                current_start = i;
        } else if (current_size) {
            current_size = 0;
        }

        if (current_size > best_size) {
            best_size = current_size;
            best_start = current_start;
        }
    }

    return best_start;
}

#include <stdio.h>
static int test(unsigned int value, unsigned int expected)
{
    unsigned int actual = findsaw(value);
    if (actual == expected)
        return 0;
    printf("findsaw(%#x) = %u\n", value, actual);
    return 1;
}

int main()
{
    return test(0x0, 0)
        +  test(0xAA, 0)
        +  test(0x585, 0)
        +  test(0xA0F, 8)
        +  test(0xF0A, 0)
        +  test(0xFA0, 4)
        +  test(0xEAEA476Bu, 23)
        +  test(0x50000005u, 27)
        +  test(0xA0000005u, 0);
}

All the tests pass; time to go home.


Append table cells to select boxes in indexed order

First little thing: var names are important. So

var option = '<option value="'+text+'">'+text+'</option>';

Second and main. When we are making webapps with JS, the main perfomance rule is:

Reduce access to DOM

I tried you code with 15000 tr's in Firefox and Chrome. I wrapped you code with

console.time('DOM');
...
console.timeEnd('DOM');

Results was:

Chrome - about 5000ms
Firefox - about 20000ms

Then i replaced $.append() with just strings concatenation

console.time('String');
var itemOptions = '', valueOptions = '', propOptions = '';
$('tr td').each(function() {
    var $this = $(this);
    var text = $this.text();
    var option = '<option value="'+text+'">'+text+'</option>';
    switch($this.index()){
        case 0:
            itemOptions += option;
          break;
        case 1:
            valueOptions += option;
          break;
        case 2:
            propOptions += option;
          break;
        default:
          alert('Unexpected Error.');
     }
});
$('#item').append(itemOptions);
$('#value').append(valueOptions);
$('#prop').append(propOptions);
console.timeEnd('String');

Results:

Chrome - about 1100ms (bravo, Chrome :))
Firefox - about 4000ms

If you will change your data source to a JSON or something, next optimisation will not need, but you can set first argument of .each() method (index of all td elements) to avoid using .index(). I noticed about 300-500ms of speed increase. So the last version is

console.time('String');
var itemOptions = '', valueOptions = '', propOptions = '';
$('tr td').each(function(index) {
    var $this = $(this);
    var text = $this.text();
    var option = '<option value="'+text+'">'+text+'</option>';
    var modulo = index % 3;
    switch(modulo){
        case 0 :
            itemOptions += option;
          break;
        case 1:
            valueOptions += option;
          break;
        case 2:
            propOptions += option;
          break;
        default:
          alert('Unexpected Error.');
     }
});
$('#item').append(itemOptions);
$('#value').append(valueOptions);
$('#prop').append(propOptions);
console.timeEnd('String');

Results:

Chrome - about 850ms
Firefox - about 3500ms


A pattern to destructively extract items from an array

Array.partition returns an array of two arrays - one where the elements returned true to the condition, and one that returned false.

So, a single liner for your need would be:

odds, ary = (0..9).to_a.partition(&:odd?)
=> [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]

(&:odd?) acts exactly like writing { |x| x.odd? } which will return true if the number is, well, odd...


It's method extraction time!

But before that, I have to comment on your Player enum:

str is a bad name, name would be better.
Speaking of name, all enums have a name() method by default. You don't need your str variable, return name(); instead.
Speaking of return name();, that's exactly what the default implementation of toString() already does for enums. Absolutely no need to override it.

And therefore, we've reduced your Player enum to:

public enum Player {
    X, O;
}

Ain't it lovely with enums? :)

Now, back to your getWinner() method:

You have a whole bunch of duplicated code there indeed. It would be handy if you could get a Collection of some kind (or an array), add some elements to it and check: Is there a winner given by these Player values?

This is just one version of doing it, it's not the optimal one but it should get you started. This code will add a bunch of Player objects to a list and then we check if those objects match to find if there's a winner.

List<Player> players = new ArrayList<>();
for (int x = 0; x < fields.length; x++) {
    for (int y = 0; y < fields[x].length; y++) {
        players.add(fields[x][y]);
    }
    Player winner = findWinner(players);
    if (winner != null)
        return winner;
}

Player findWinner(List<Player> players) {
    Player win = players.get(0);
    for (Player pl : players) {
        // it's fine that we loop through index 0 again,
        // even though we've already processed it.
        // It's a fast operation and it won't change the result
        if (pl != win)
            return null;
    }
    return pl;
}

Please note that there are even more improvements possible for the getWinner method, I don't want to reveal all my secrets for now though ;) And also, this is just one way of doing it, which will reduce your code duplication a bit at least. There are other possible approaches here as well.


New Year Chaos (HackerRank problem) - find minimum swap count

Some minor stuff:
This if:
    if simulated[i] == q[i]:
        continue

is redundant and can be removed, due to the predicate on your while. The while would execute zero times and have the same effect as if you continued.
The while itself:
    while(simulated[i] != q[i]):

should drop the outer parens.
The range here:
for i in range(0, len(simulated)):

should drop the 0,  because that's the default.
Since you use both i and simulated[i], you should iterate using enumerate instead of range (though this won't be the case if you delete the if; continue). Getting a value from enumerate won't be helpful during the value swaps that you do later.
About the value swaps, this block:
        if i + 3 == q[i]:
            simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]
            simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
            bribeCount += 2
        # do 1 bribe
        else:
            simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
            bribeCount += 1

should collapse to
        if i + 3 == q[i]:
            simulated[i + 2], simulated[i + 1] = simulated[i + 1], simulated[i + 2]
            bribeCount += 1

        simulated[i + 1], simulated[i] = simulated[i], simulated[i + 1]
        bribeCount += 1


It seems to me that the ListNode type is part of the SinglyLinkedList. So there's no reason for that to be visible outside the SLL. I suggest making it a nested/private/hidden/secret class. (There are many ways to hide it, pick the one you like.)
Your method names are confusing. The std namespace has any number of collections defined. Pick one of them, and model your naming on that. For example: std::vector has a size method that returns the size. It also defines push_back and pop_back. Alternatively, std::list also defines push_front and pop_front. You need to pick a usage model for your SLL, and then choose method names compatible with it.
What, no iterators?


It is actually a terribly inefficient implementation... Some things to keep in mind:

Do not use the __getslice__ method explicitly.  It is a relic of a time long gone, and you only need to know about it if subclassing objects written in CPython. Not your case. And your code can be written in an infinitely more readable form as:

def sort(some_list):
    if len(some_list) > 1:
       return merge(sort(some_list[:len(some_list)/2],
                     sort(some_list[len(some_list)/2:]))
    else:
        return some_list

Slicing a Python list creates a copy of the list. This is not what you typically want in a merge sort.  To avoid this, you can leave your original list unsliced, and pass around indices to the intervals being sorted and merged.  Such an in-place merge sort could be written as:

def sort(list_, lo=None, hi=None):
    if lo is None:
        lo = 0
    if hi is None:
        hi = len(list_)
    if hi - lo <= 1:
        return
    mid = lo + (hi - lo) // 2
    sort(list_, lo, mid)
    sort(list_, mid, hi)
    merge(list_, lo, mid, hi)

def merge(list_, lo, mid, hi):
    temp = list_[lo:mid]
    left = 0
    right = mid
    write = 0
    while left < mid - lo and right < hi:
        if list_[right] < temp[left]:
            list_[write] = list_[right]
            right += 1
        else:
            list_[write] = temp[left]
            left += 1
        write += 1
    if left < mid - lo
        list_[write:] = temp[left:]

This is not a very Pythonic implementation.  It actually looks like C or Java translated line by line into Python.  But there is not much way around it.  Unless you simply do sort(list_), which is the Pythonic way of getting a listy sorted.


Text-based menu to manipulate a database text file

I'd do Maybe FilePath -> IO ():

menu :: IO ()
menu = do
    (mapM_ putStrLn . map showChoice) choices
    c <- get "Enter the letter corresonding to the action of choice:"
    case filter ((== c) . fst3) choices of
    [] -> back "Not a valid choice. Try again"
    (_, _, f) : _ -> maybeName >>= maybe menu (maybeFile >=> f)

createdb :: Maybe FilePath -> IO ()
createdb (Just file) = back $ "Error: \"" ++ file ++ "\" already exists."
createdb Nothing = do
  cols <- get "Enter unique column names in the form n1,n2,...,n (No spaces):"
  let spl = splitOnComma $ toLower' cols
  if hasDuplicates spl || any (elem ' ') spl
    then back "Error: Column names must be unique and have no spaces."
    else writeFile (name ++ ".txt") (cols ++ "\n")

deletedb :: Maybe FilePath -> IO ()
deletedb Nothing = back $ "Error: Could not find that database."
deletedb (Just file) = removeFile file


This class is too basic to be useful. You can only add nodes to it, but you don't provide a way to access those nodes. As such this is something incomplete.

Make it testable

At the minimum, make it testable. For example by implementing a toString method:

@Override
public String toString() {
    return toString(root);
}

private String toString(TreeNode node) {
    if (node == null) {
        return null;
    }
    return "[" + toString(node.left) + "," + node.item + "," + toString(node.right) + "]";
}

Now we can write some tests to verify it's actually working:

@Test
public void test345() {
    CreateBinarySearchTree tree = new CreateBinarySearchTree();
    tree.add(3);
    tree.add(4);
    tree.add(5);
    assertEquals("[null,3,[null,4,[null,5,null]]]", tree.toString());
}

@Test
public void test453() {
    CreateBinarySearchTree tree = new CreateBinarySearchTree();
    tree.add(4);
    tree.add(5);
    tree.add(3);
    assertEquals("[[null,3,null],4,[null,5,null]]", tree.toString());
}

NOT a Binary Search Tree

The implementation violates a requirement of a Binary Search Tree: it will add duplicate elements. Let's expose this bug by adding a unit test:

@Test
public void testNoDups() {
    CreateBinarySearchTree tree = new CreateBinarySearchTree();
    tree.add(4, 4);
    tree.add(4);
    assertEquals("[null,4,null]", tree.toString());
}

Easy enough to fix, by adding an else in the main loop:

    while (true) {
        if (item < node.item) {
            if (node.left == null) {
                node.left = new TreeNode(null, item, null);
                break;
            }
            node = node.left;
        } else if (item > node.item) {
            if (node.right == null) {
                node.right = new TreeNode(null, item, null);
                break;
            }
            node = node.right;
        } else {
            break;
        }
    }

Recursive add

Instead of a while loop, it would be more elegant to implement adding a node using recursion:

public void add(int item) {
    if (root == null) {
        root = new TreeNode(null, item, null);
    } else {
        add(root, item);
    }
}

public void add(TreeNode node, int item) {
    if (item < node.item) {
        if (node.left == null) {
            node.left = new TreeNode(null, item, null);
        } else {
            add(node.left, item);
        }
    } else if (item > node.item) {
        if (node.right == null) {
            node.right = new TreeNode(null, item, null);
        } else {
            add(node.right, item);
        }
    }
}

Minor things

public CreateBinarySearchTree() {}

public CreateBinarySearchTree(int[] a) {
    this();
    for (int i : a) {
        add(i);
    }
}

The constructor that takes an array calls this(), but since that other constructor does nothing, this is pointless. The variable names a and i are poor, it would be better to rename them to arr or items, and item, respectively.

As others have pointed out, it would make sense to move the adding logic outside of the constructor. In fact, how about removing all the constructors, and using this new method instead to add elements:

public void add(int... items) {
    for (int item : items) {
        add(item);
    }
}


jQuery score card form to determine pass or fail

Personally I wouldn't change anything about the calculation itself. It all quite reasonable the way it is.

There are just two things could be optimized concerning jQuery:

You should be using .closet() instead of .parents() since you only need the first (closest) matching parent and not all ancestors.
Also you can optimize assigning the event handler to the radio buttons by using .delegate() (or .on with jQUery 1.7) instead.

There are also a few things which personally I'd do differently:

In the HTML I'd use th elements for the question cells and td just for the options, allowing you to get rid of the classes webform-grid-question and webform-grid-option.
I'm not a big fan of using $ in variable names, especially if they don't point to a jQuery object.
I don't like using input elements for output. I'd use a "normal" element such as span or div (or if HTML5 is a option the new output element).


Check if a linked list is a palindrome in Scala

What you do is very inefficient. You check if the elements of the list are similar from the outside in, and that too utilising both very unintuitive pattern matching and guard clauses.

Note: You do not need to specify the type parameter A in the recursive call to isPalindrome(), as the compiler can infer that.

Your code, on simple singly linked lists, is O(n2), thanks to the repeated O(n) calls to list.last. The code that I explain and provide below runs in O(n), as reversing a list is O(n) and subsequently checking for equality is also O(n).

What is the definition of a palindrome?

While what you have mentioned is absolutely correct, there's an easier way to think about it.

A sequence is a palindrome whenever it is equal in every way to a sequence that contains the elements of the first sequence in reverse order.

That is, a list is a palindrome if and only if it is equal to its reverse.

I think that as your code already uses enough library functions, why not try this:

def isPalindrome[A](list: List[A]) = list == list.reverse

Simple, succinct, and to the point.

I'm absolutely sure your code is overcomplicated for its intended purpose, and functional programming is not just about pattern matching and recursion, it's about being able to create greater functionality from pre-existing functions.


Is it possible to optimize the following boolean checks?

I came up with a different solution by utilizing Python's magic method for == which is __eq__(self, other).

I define it in the User class like so:

class User(object):
    def __init__(self, key):
        self.key = key
    def __eq__(self, other):
        return self.key == other.key if isinstance(other, User) else False

This allows you to do the obvious User(1) == User(2) testing but also this allows you to test membership in a collection using the in keyword:

User(1) in [User(1)] # This will return True
User(1) in [User(2)] # This will return False

We can then change the condition slightly to make the is_ok function like this:

def is_ok(user_dbs, self_db):
    count = len(user_dbs)
    if not self_db:
        return not count
    return count == 1 and self_db in user_dbs or count == 0

This has the advantage of being a bit more readable, and hence Pythonic. This might come in handy elsewhere as well.

Another minor point is that if you ever rename key to something else or change the structure of your User class, this code will still work (remember to update __eq__!), while most of the alternatives will break.


Singly Linked List implementation in Java

General

Default Values

Java uses default values for all its fields. Meaning :

public  Node(){
    item = null;
    next = null;
}

Does nothing except take up space for you. I would remove it, and the other lines / constructors like it. Some consider it bad practice to rely on the default values, you can then explicitly state the default value of a field on the same row as you are declaring it.

private Node head = null;

Reference

Inconsistency

You are inconsistent at spacing your code. I also recommend having fields at the right below the class declaration. I should not have to look for the fields, I want to find them instantly.

Bug in remove, insertBefore

If head is null, then current.next will throw a NullPointerException. I suggest guarding against null for head first in the method.

if (head == null) {
    System.out.println ("Item doesn't exist in the list.");
    return;
}

Nitpicks

public void add(T item)

You always execute the size++; why have it in two different places? And not directly under Node p = new Node (item);

public boolean isEmpty()

Looks perfect, why can't every method turn out to be like this? One option is to match against head == null as well, however in terms micro-optimization, it is slower.

public int getSize()

Nothing needs to be said, a simple getter.

public void remove(T item)

Instead of letting it handle the error printing, let remove return a boolean, true if removed, false if not, making it more flexible to use in future applications.


Chaining is the power way in jQuery:

var button = $("#submit-button");
$("#search").focus(function(){
    button.slideDown("slow");
}).blur(function(){
   button.slideUp("slow");
});


ConsumingRouter to consume based on condition

There is a Map.forEach(BiConsumer) that you can use as well:

@Override
public void accept(T t) {
    map.forEach((k,v) -> {
        if (k.test(t)) {
            v.accept(t);
        }
    });
}

Alternatively, you can convert that if-statement in the form of an Optional too if you can ignore null values (as commented by @Misha):

@Override
public void accept(T t) {
    // answer update: switched to Optional.of() for reasons mentioned in comments
    map.forEach((k,v) -> Optional.of(t).filter(k::test).ifPresent(v));
}

You can also take a look at this StackOverflow question for some insight about splitting two Streams into two Streams... similar to yours, except that you are only concerned with multiple Consumers to terminate the source Stream.

edit: Oh yeah, you may want to consider having your sub() (subscribe?) method return the reference to itself, so that you can do method chaining as such:

router.sub(p1, c1).sub(p2, c2);

edit 2: @Misha has a good suggestion for doing away with the Map, if that suits your requirements as well.


C# Security Module for generating secure hashes

public static class Hashing
{

    public static int SaltSize = 32;

This is public, static, and not const or readonly. That means:

"Anyone" can change it.
It's not thread-safe.
Hash validation is undermined.

I see no reason for it to be public, and every reason for it to be readonly or const. Personally I'd favour readonly and initialised from ConfigurationManager.AppSettings so that an upgrade path can be built in which doesn't require recompiling the code.

    public static string HashPassword(string passwordToHash, byte[] salt, int numberOfRounds)
    ...
    public static string HashPassword(string passwordToHash, int numberOfRounds)
    ...
    public static byte[] GenerateSalt()
    ...
    public static byte[] HashPassword(byte[] toBeHashed, byte[] salt, int numberOfRounds)

Why expose everything? I would expect the only public method to be HashPassword(string password) (or maybe HashPassword(SecureString password), although SecureString is such a nuisance to do anything with that I can understand not supporting it).

        return Convert.ToBase64String(salt.Concat(hashedPassword).ToArray());

Cryptography is an arms war: it's always worth thinking about the upgrade path. That means recording the parameters (name of hash, number of iterations, length of salt) in such a way that they can be extracted when it's time to validate.

        using (var randomNumberGenerator = new RNGCryptoServiceProvider())

I think it's better practice to use RandomNumberGenerator.Create() and leave the selection of the provider to the system-wide configuration.

        using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(toBeHashed, salt, numberOfRounds))

RFC 2898 was intended as a key derivation function, not a password validation mechanism. It's probably safe, but I'm leery of using it for a different purpose without including a reference to a respected cryptographer who says it's safe.

public abstract class HashVerification
{
    public abstract string GetDatabaseHash(string username);

    public bool HashMatch(string username, string password)

The guideline that one should favour composition over inheritance suggests that hash verification (HashMatch) should probably be in Hashing, and the database fetching should be independent of it.

        var salt = Convert.FromBase64String(combinedHash).Take(Hashing.SaltSize).ToArray();

        var serverHash = Hashing.HashPassword(password, salt, username.Length * 100);

Yikes! Why should people with shorter usernames get less protection? The number of rounds should be another thing that comes from a configuration file so that it can be increased over time, and it should be constant for everyone.

        return combinedHash.Equals(serverHash);

Already addressed in an earlier answer.


Automate the Boring Stuff Chapter 8 Sandwich Maker

PEP8
The "PEP 8 -- Style Guide for Python Code" has many recommendations on how programs should be written, for maximum understandability between programmers.
Variable Names
The one that you violate the most relates to variable naming.  PEP8 recommends snake_case for all variables.  So customerOrder should be customer_order, sandwichTotal should be sandwich_total, etc.
Constants
Constants, things which never change, should be named using UPPERCASE or UPPERCASE_WITH_UNDERSCORES.  Therefore, optionPrices should be OPTION_PRICES.
White Space
PEP-8 recommends no space between a diction key and the :.
Encapsulate Data into Containers
optionPrices contains breads, proteins, cheeses, and extras.  This seems like it is stuffing too much -- well, stuffings -- into one container.
I might write:
BREAD_PRICE = {'white':2.00, 'wheat': 2.50, 'sour dough': 3.00}
PROTEIN_PRICE = {'chicken': 2.50, 'turkey': 2.25, 'ham': 1.75, 'tofu': 4.00}
CHEESE_PRICE = {'cheddar': 1.00, 'swiss' : 1.25, 'mozzarella' : 2.00}
EXTRA_PRICE = {'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.30, 'tomato': 0.50}

With the bread, protein, and cheese options, you could now write a common function:
def get_sandwich_choice(category, options):
    prompt = "Please choose your " + category + ":\n"
    choices = list(options.keys())
    choice = pyip.inputMenu(choices, prompt, lettered=True)
    return choice

bread_choice = get_sandwich_choice('bread', BREAD_PRICE)
protein_choice = get_sandwich_choice('protein', PROTEIN_PRICE)
...

The price containers are all really the same kind of things, just in groups.  So one might instead ...
PRICE = {'bread': {'white':2.00, 'wheat': 2.50, 'sour dough': 3.00},
         'protein': {'chicken': 2.50, 'turkey': 2.25, 'ham': 1.75, 'tofu': 4.00},
         'cheese': {'cheddar': 1.00, 'swiss' : 1.25, 'mozzarella' : 2.00},
         'extras': {'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.30, 'tomato': 0.50},
         }

and the choices could be fetched with:
bread_choice = get_sandwich_choice('bread', PRICE['bread'])
protein_choice = get_sandwich_choice('protein', PRICE['protein'])
...

You could expand this further by adding more data.  bread is choice, protein is a choice, cheese is an optional choice, extras are optionals.  Based on the category type, you could call the appropriate user input functions.  The prompt for each category could be customized, and so on.  To add this extra data, I'd look into @dataclass.
Are all things in customerOrder the same?  The bread is kind of unique; you need two slices for the sandwich.  The extras might eventually have options like "light on the mayo" or "heavy on the mustard", where as you can't ask for extra bread.  So it might make more sense keeping them separate.  bread_choice, protein_choice, cheese_choice, and a list of extras.  This also helps our cost, since the prices are in different containers.
def sandwich_cost(bread, protein, cheese, extras):
    cost = PRICE['bread'][bread] + PRICE['protein'][protein]
    if cheese:
        cost += PRICE['cheese'][cheese]
    for extra in extras:
        cost += PRICE['extra'][extra]

sandwich_total = sandwich_cost(bread_choice, protein_choice, cheese_choice, extras)

Again, a @dataclass may be useful in construction a sandwich object.
By having a separate function for computing the sandwich cost, you make your code testable.  For example, you could check:
assert sandwich_cost('white', 'tofu', 'cheddar', ['tomato']) == 7.50
assert sandwich_cost('white', 'tofu', '', []) == 6.00

Look into unittest for better ways of writing test code.
Main Guard
It is a good habit to move your code into functions, and call it from inside a "main guard" at the end of the code.  Eg)
import pyinputplus as pyip

... helper functions here ...

def main():
    ... code here ...

if __name__ == '__main__':
    main()

Summary
Lots of ways to improve this code.  I've touched on a few.  Experiment, and once you've got something working, post a new followup question for further advice.


Bugs
j unconditionally loops to TABVALUE - 1. This is wrong:

If d happens to not be a space, it is not printed out.
If next d happens to be a space, it is still counted.

Test against a  b  cdef. The output is a\tf.


In the code I only would modify the variable declarations:

var defaults = {blurRadius:2, deblurOnHover:false},
settings = $.extend(defaults, options),
img, blurContainers, clone;

Personal preference, but you can read a discusion about it here.

Answering your questions:

The efect work great. I think the approach is good, don't think
that adding four elements would be a big cost.
You could check if the  has the fixed property to avoid breaking anything.
By the parameters you have rigth now I shouldn't bother. If you decide
to add the opacity again it would be a good idea to check it. If
greater than 0.x use the default instead.


I don't know much about angular.js myself, but I can give some small tips about your code.

Indentation

Code, in general, looks ugly without proper indentation.

I recommend that you indent the body of the second parameter passed into app.filter.

Why are you checking with 'undefined'?

On the line that goes:

if (typeof categories != 'undefined') {

Why are you comparing with 'undefined'?

If you want to check is categories was defined, you could just do

if (categories) {


This is typically something you do with a cursor:

DECLARE @tmpFolderId INT;
DECLARE @RelatedParentFolderIds TABLE (FolderID INT, ParentFolderID INT);

DECLARE folderCurs CURSOR LOCAL FAST_FORWARD FOR SELECT FolderID FROM #TmpDistinctFolderIds;
OPEN folderCurs
FETCH NEXT FROM folderCurs INTO @tmpFolderId
WHILE @@FETCH_STATUS = 0
BEGIN
    -- Get all possible hierarchy level parent folder ids
    INSERT INTO @RelatedParentFolderIds (FolderID, ParentFolderID)
    SELECT FolderID, ParentFolderID
    FROM [dbo].[fnGetAllParentFolderIds] (@tmpFolderId)

    FETCH NEXT FROM folderCurs INTO @tmpFolderId
END


Prefer using a lock guard:

int city_index = 0;
{
    std::lock_guard<std::mutex> guard(city_counter_lock);
    if (current_city + 1 < (int) cities.size()) {
        city_index = ++current_city;
    }
}

This makes sure that an exception will not leave the mutex locked;

You will need to handle failures to get the webpage. If res != CURLE_OK then a failure occurred somewhere.

You are encouraged to reuse the CURL handle you can do so by creating it inside fetch_weather_async before the loop and passing it into fetchJson

void fetch_weather_async(){
    CURL *curl;

    curl = curl_easy_init();

    if(!curl) return;
    while (current_city + 1 < (int) cities.size()){
        int city_index = 0;
        {
            std::lock_guard<std::mutex> guard(city_counter_lock);
            if (current_city + 1 < (int) cities.size()) {
                city_index = ++current_city;
            }
        }

        std::cout << "requesting " << city_index << std::endl;
        fetchJson(city_index, curl);
        std::cout << "acquired " << city_index << std::endl;
    }
    curl_easy_cleanup(curl);
}

void fetchJson(int i, CURL *curl){
    CURLcode res;
    std::string readBuffer;

    curl_easy_setopt(curl, CURLOPT_URL, (URL_BASE + cities[i]).c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
    res = curl_easy_perform(curl);
    if(res == CURLE_OK)
        std::cout << i << " : " << readBuffer << std::endl;

}


This doesn't quite answer your questions, but still hopefully helpful.

var perRound = 1; perRound < 5; perRound++ only executes four times; the fifth execution is coming from the last line of your program. It's customary to use i when simply doing something multiple times, and to start with 0 such as: var i = 0; i < 5; i++. Then remove that extra playRound at the end so you still have five rounds.

I would rename convertMoves to playerMove to better describe what it does instead of how it does it.

playRound isn't using its arguments. So you can change the first few lines to:

    function playRound() {
        var computerSelection = computerPlay();
        var playerSelection = convertMoves();

You might play with changing moves to an array and see if you like it better as moves = ['rock', 'paper', 'scissors'];. This will require several other changes to how you use it but I think it'll read easier in the end.

Just as a matter of style, put the ++ after the variable except for the rare times when you really need the other behavior.

Again, hope this helps.

Edit: I see now why you have the extra playRound at the end. But result is already global so you can simply end with console.log(result) instead of returning it from playRound each time.


Changing a single jQuery plugin option on window resize

$(window).smartresize(function () {

  var chosenSettings;

  // We could map out the defaults first.
  var defaults = {
    accordionW: config.wWidth,
    accordionH: config.wHeight,
    visibleSlices: 0,
    expandedHeight: 600,
    expandedWidth: 1000,
    contentAnimSpeed: 200
  };

  // Then, depending on the conditions, create an object of the modifications
  // This way, it's easier to add in more differences.
  if (config.wWidth >= 768 && config.wWidth <= 1024) {
    chosenSettings = {visibleSlices: 2};
  } else if (config.wWidth < 768) {
    chosenSettings = {visibleSlices: 1};
  } else {
    chosenSettings = {visibleSlices: 3};
  }

  // Then use extend to create an object with the chosen settings
  var settings = $.extend({}, defaults, chosenSettings);
  $('#va-accordion').vaccordion(settings);

// Assuming smartresize returns the same object, we can chain trigger.
}).trigger('smartresize');


Reading MultiPart From Data with descriptors

The naming and variable conventions in your method look like it was written by at least three different persons:

var provider ..
Stream _id ..
StreamReader reader ..

You really should pick just one style and stick to it for the entire application. It's very hard to read.

But the variables are not the only thing that is extremely incosistent.

Stream _id = postId.ReadAsStreamAsync().Result;

Why are you not awaiting this result like you do with the other ..Async methods?

All streams need to be disposed.

Overall I've got the impression that you put this method together just for the sake of this question and mixed variables and fields which would explain why some of them are prefixed with the underscore.


Code samples in this are approximate, I didn't test them.
A couple thoughts:

1)

You've currently called prepare() inside the body of your foreach loop. This is unnecessary, you only need to prepare your query once. You may reuse the PDOStatement that prepare() returns repeatedly in every iteration of your loop. This is actually very efficient, as the query will only have to be evaluated once. Once you're prepared, the preparation is done, no need to re-prepare for each loop iteration if your query structure is the same.

(For the record, prepare is indeed the correct method to use in batch operations like this. In the future, if you only need to execute a single query, you could alternative use PDO:query() (if you need results) or PDO:exec() (if you don't need results from the query -- it simply returns the number of rows affected by the query as an integer.))

The same goes for bindParam(). You don't need to re-bind the params each loop iteration-- once bound, they're bound. bindParam() binds by reference, the actual evaluation of the param happens every time execute() is called.

So let's do this minor refactor. We prepare the statement and bind the params before the loop begins, we execute() the statement on every iteration of the loop, and we'll move the close()-ing of the PDOStatement to be after the loop. Your sample now looks like this, and will be a bit more performant:

$obj = new RecursiveIteratorIterator( new RecursiveArrayIterator( json_decode( $return, TRUE ) ), RecursiveIteratorIterator::SELF_FIRST );

$stmt = $connection->prepare( "INSERT INTO heartrate SET `encodedid` = ?, activitydate = ?, rhr = ? ON DUPLICATE KEY UPDATE rhr= ?" );
$stmt->bind_param( 'ssii', $studentencodedid, $dateTime, $restingHeartRate, $restingHeartRate );

foreach ( $obj as $key => $val ) {
    $$key = $val;
    $stmt->execute();

    if ( $stmt->affected_rows < 1 ) {
        header( "Location: " . $url . "/index.php?errormessage=Failed to updated the resting heart rate value." );
    }
}

$stmt->close();

2)

$$key = $val;

I'd recommend NOT to use variable variables. They're generally considered a blight on the language, and people have pretty strong opinions on them.

They tend to make code more confusing to read, debug, and lint; and they don't do much that you can't do in a simpler manner.

2.5)

Actually, looking at your sample data array, your data doesn't look to be of arbitrary depth. It looks fixed-depth. Yes, there are n number of heartRateZones per day, but the the structure is repetitive. It looks keyed per-day, each day has a few unique key/value sets. The only thing in the value array you seem to care about is the per-day dates and resting heart rates. You aren't using them yet, but I can also imagine maybe you want the heartRateZones, you can just grab those directly without iterating over all the other keys in the 'value' array.

I'm not seeing a need for recursion at all.

We can easily eliminate the variable variables and get rid of the unnecessary recursion all at once. I'd probably handle this with loops or nested loops instead of recursion.

You don't appear to currently be using any of the heartRateZones. If you wanted to insert a record per zone, you could run execute() in that inner foreach. Otherwise just delete that loop and run the execute() in the days loop.

I didn't see $studentencodeid defined in the code sample you gave, or in the JSON data. I assume you already defined that elsewhere in your script.

$obj = json_decode($return, TRUE);

$stmt = $connection->prepare( "INSERT INTO heartrate SET `encodedid` = ?, activitydate = ?, rhr = ? ON DUPLICATE KEY UPDATE rhr= ?" );
$stmt->bind_param( 'ssii', $studentencodedid, $dateTime, $restingHeartRate, $restingHeartRate );

// Iterate through days
foreach ($obj as $key => $value) {

    // Grab data unique to a whole day that you care about
    $dateTime = $value['dateTime'];
    $restingHeartRate = $value['restingHeartRate'];

    // Iterate through heartRateZones (Or remove this loop if you don't need them)
    foreach($value['value'] as $zoneKey => $zoneValue) {
        // If you want to insert records based on individual heart rate records, do that here and remove the execute() below. You'd insert a record per-heartrate with the same dateTime and restingHeartRate values as all the other heartrates on that day.
        // $stmt->execute();
    }

    $stmt->execute();

    if ($stmt->affected_rows < 1 ) {
        header( "Location: " . $url . "/index.php?errormessage=Failed to updated the resting heart rate value." );
    }
}

$stmt->close();


refactor python strategy pattern to use abstract base class

Only the Character and WeaponBehaviour classes are actually useful and neither of them needs to inherit anything. The rest can be just factory functions, because only the constructors differ. If a class constructor does anything except assign arguments to properties, it is probably wrong.
Strategy pattern is based on composition rather then inheritance.
class Character:
    def __init__(self, weapon):
        self.weapon = weapon

    def set_weapon(self, weapon):
        self.weapon = weapon

    def fight(self):
        self.weapon.use()

def Queen():
    return Character(Knife())

def King():
    return Character(Bow())

class Weapon:
    def __init__(self, message):
       self.message = message
    def use(self):
       print(self.message)

def Knife():
    return Weapon("Stabby stab stab")

def Bow():
    return Weapon("Thwing!")

king = King()
queen = Queen()
king.fight()
queen.fight()
queen.set_weapon(Bow())
queen.fight()

Notice that I have removed the behavior part of the names as it seemed a bit useless.
I have also renamed use_weapon() to just use() because it is called on a weapon variable, and so it seemed redundant.
Also notice, that unless I used the set_weapon() method on a constructed Character instance (ie. to switch weapon in middle of battle), the Character class would be useless, because everything could have been done with the weapons alone. Of course I know this is just a pattern demonstration code, but I wanted to point out anyway..
As a bonus, here is something (not only) for the king :) Also notice how again composition is prefered over inheritance to provide flexibility.
class DoubleWeapon:
    def __init__(self, left, right):
        self.left = left
        self.right = right
    def use(self):
        self.left.use()
        self.right.use()

king.set_weapon(DoubleWeapon(Knife(), Sword()))
king.fight()
```


Using brute force to do large scale permutations and combinations

Use integers instead of strings

I don't really understand the problem you are trying to solve, so I don't know if your algorithm can be improved.  But I can see that your program spends a lot of time creating and modifying strings that are between 4 and 8 characters long, containing the letters '1' .. '6'.

Instead of using strings, you could use an integer to represent your string.  Simply use the hex representation as your integer value.  For example, instead of the string "123456", use the int 0x123456.

Integers are more compact than strings, and operations on integers are faster than string operations.  As an example of how to build an integer as opposed to a string, this:

 sb.append(String.valueOf(data[k]));

would become this:

// Assumes k loop goes from 5 to 0 instead of 0 to 5:
val = (val << 4) | ((data >> k) & 0xf);

More efficient check for all characters present

One function that appears to be where much of the time is spent is gen8string(), and within that function the inner loop does this:

    for(int i = 0; i < 15; i++){

        for(int j = 0; j < 15; j++){
            combinedString = pattern1[i] + pattern2[j]; //combine both 4 letter strings into 8 char length string
            char[] parsedString = combinedString.toCharArray(); //parse into array

            //check if all 6 characters are present
            for(int k = 1; k <= 6; k++)
            {
                if(new String(parsedString).contains(k+"")) {
                    present++;
                }
                else
                    break;
                //if all 6 are present, then add it to combined subset
                if(present == 6)
                    combinedSubset[index++] = combinedString;
            }
            present = 0;
        }
    }

There are several inefficiencies, such as concatenating pattern1[i] and rechecking its characters when they could be checked in the outer loop only.  If you converted to integers, you could do this check like this:

// Returns bitmask of numbers present in a 4 digit value
public static int presentBits(int val)
{
    int presentMask = 0;
    for (int i=0; i<16; i+=4) {
        int digit = (val >> i) & 0xf;
        presentMask |= 1 << digit;
    }
    return presentMask;
}

    // Within get8string()...
    for (int i = 0; i < 15; i++) {
        int present1 = presentBits(pattern1[i]);
        for (int j = 0; j < 15; j++) {
            int presentMask = present1 | presentBits(pattern2[j]);

            if (presentMask == 0x7e) {
                // 0x7e is binary 01111110, which means each of
                // the digits 1 through 6 was seen at least once.
                combinedSubset[index++] = (pattern1[i] << 16) |
                                           pattern2[j]
            }
        }
    }

Checking subsets

Another heavily called function is checkSubsets(), which appears to just count the number of unique strings among an array of 720x90 strings.  It does so with an \$O(n^2)\$ duplicate removal algorithm.  You could do better by sorting the strings (or integers preferably) and then counting uniques in one pass.  Even faster would be to add all the strings to a HashSet, which naturally removes duplicates.  The sorting method takes \$O(n \log n)\$ time, and the HashSet method takes \$O(n)\$ time.


Your using the email sanitize filter on each field, you need to use FILTER_SANITIZE_STRING for the name and FILTER_SANITIZE_FULL_SPECIAL_CHARS for the message field.

Sanitizing is not the same as validating...

VALIDATE Filters

SANITIZE filters


Plotting different parameterized polynoms

You're not really using numpy at the moment. If we use the simple 'translation table' below, your code would work if you just replaced the NumPy function with the Python equivalent:

np.arange -> range, assuming your domain is just integers,
np.fabs -> abs,
np.cos -> math.cos, and,
np.pi -> math.pi.

Instead you want to take advantage of NumPy. Take tschebyscheff_points, you have the equation:

$$\cos(\frac{\pi(2i + 1)}{2(\text{count} + 1)})$$

But your Python code is:

def tschebyscheff_points(count):
    points = []
    for i in np.arange(0, count):
        points.append(np.cos(((2 * i + 1) * np.pi) / (2 * (count + 1))))
    return points

Yes it contains the equation, but with numpy you can just write the equation:

def tschebyscheff_points(count):
    return np.cos(((2 * np.arange(count) + 1) * np.pi) / (2 * (count + 1)))

This significantly improves both performance, and readability. As you only need to read the equation.

I'd also change your code to use comprehensions. lebesgue_function should use sum as writing the addition yourself is WET. And in as_supporting_point_poly and lagrange_poly you should factor out the multiplication into a product function.

I'm not too good with NumPy and matplotlib so I can't really help with improving the display of the data.
But the above should get you to the following code.
Note, that I have two lagrange_poly as I don't know if a pure Python function is better than the NumPy equivalent.

import numpy as np
import matplotlib.pyplot as plt
from operator import mul
from functools import reduce

def product(it, initial=1):
    return reduce(mul, it, initial)

def equidistant_points(count):
    return np.arange(count) * 2 / count - 1

def tschebyscheff_points(count):
    return np.cos(((2 * np.arange(count) + 1) * np.pi) / (2 * (count + 1)))

def as_supporting_point_poly(points, x):
    return product(x - point for point in points)

def lagrange_poly(points, j, x):
    point_j = points[j]
    p = np.delete(points, j)
    return product((x - p) / (point_j - p))

def lagrange_poly(points, j, x):
    return product(
        (x - point) / (points[j] - point)
        for i, point in enumerate(points)
        if i != j
    )

def lebesgue_function(points, x):
    return sum(
        np.fabs(lagrange_poly(points, i, x))
        for i in range(len(points))
    )

def plot_and_save(n, x, poly_calc, name):
    equi = plt.plot(x, poly_calc(equidistant_points(n), x), 'r-', label='Äquidistante Stützstellen')
    tsch = plt.plot(x, poly_calc(tschebyscheff_points(n), x), 'g-', label='Tschebyscheff-Stützstellen')

    plt.xlabel("x")
    plt.ylabel("y")
    plt.title(name + " mit n = " + str(n))
    plt.grid(True)
    plt.legend(loc='upper right', shadow=False)
    plt.savefig("Aufg1"+ poly_calc.__name__ + str(n) + ".png")
    plt.show()

if __name__== '__main__':
    domain = np.arange(-1.0, 1.0001, 0.0001)
    plot_and_save(8, domain, as_supporting_point_poly, "Stützstellenpolynome")
    plot_and_save(20, domain, as_supporting_point_poly, "Stützstellenpolynome")

    plot_and_save(8, domain, lebesgue_function, "Lebesgue-Funktion")
    plot_and_save(20, domain, lebesgue_function, "Lebesgue-Funktion")


1. Comments on your code

No docstrings! What does your code do and how am I supposed to use it?
No test cases. This ought to be a good opportunity to use doctests.
Given that your purpose here is to implement RPG lookup tables, your design seems a bit hard to use. The printed RPG table probably says something like this:

1-8     giant spider
9-12    skeleton
13-18   brass dragon
...

but you have to input it like this (adding one to the limit of each range):

range_dict((range(1, 9), "giant spider"),
           (range(9, 13), "skeleton"),
           (range(13, 18), "brass dragon"),
           ...)

which would be easy to get wrong.
The design also seems fragile, because it doesn't ensure that the ranges are contiguous. If you made a data entry mistake:

d = range_dict((range(1, 8), "giant spider"),
               (range(9, 13), "skeleton"),
               (range(13, 18), "brass dragon"),
               ...)

then the missing key would later result in an error:

>>> d[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 8

2. An alternative approach

Here's how I'd implement this lookup table:

from bisect import bisect_left
from collections.abc import Mapping

class LookupTable(Mapping):
    """A lookup table with contiguous ranges of small positive integers as
    keys. Initialize a table by passing pairs (max, value) as
    arguments. The first range starts at 1, and second and subsequent
    ranges start at the end of the previous range.

    >>> t = LookupTable((10, '1-10'), (35, '11-35'), (100, '36-100'))
    >>> t[10], t[11], t[100]
    ('1-10', '11-35', '36-100')
    >>> t[0]
    Traceback (most recent call last):
      ...
    KeyError: 0
    >>> next(iter(t.items()))
    (1, '1-10')

    """
    def __init__(self, *table):
        self.table = sorted(table)
        self.max = self.table[-1][0]

    def __getitem__(self, key):
        key = int(key)
        if not 1 <= key <= self.max:
            raise KeyError(key)
        return self.table[bisect_left(self.table, (key,))][1]

    def __iter__(self):
        return iter(range(1, self.max + 1))

    def __len__(self):
        return self.max

Notes on this implementation:

The constructor takes the maximum for each range (not the maximum plus one), making data entry less error-prone.
The minimum of each range is taken from the end of the previous range, thus ensuring that there are no gaps between ranges.
The collections.abc.Mapping abstract base class provides much of the functionality of a read-only dictionary. The idea is that you supply the __getitem__, __iter__ and __len__ methods, and the Mapping class supplies implementations of __contains__, keys, items, values, get, __eq__, and __ne__ methods for you. (Which you can override if you need to, but that's not necessary here.)
I've used bisect.bisect_left to efficiently look up keys in the sorted table.


Script that counts quarters, dimes, nickels, and pennies

Separate input from processing.  If you want to test your method with a number of different values, you'll have to call change() multiple times, and enter in the value each time.  Instead, change the function to accept the amnt, and you can call it many times passing in the amount of cash as an argument:

def change(amnt):
    # ...

Working with tuples from divmod is awkward.  Python has deconstructing assignment, which will take a returned tuple an assign the members to separate variables:

def change(amnt):
    quarters, amnt = divmod(amnt, 0.25)
    print("Quarters: ", quarters)

    dimes, amnt = divmod(round(amnt, 2), 0.10)
    print("Dimes: ", dimes)

For the last operation, you don't use the remainder, so the "throw-away" variable _ can be used for it:

    pennies, _ = divmod(round(amnt, 2), 0.01)
    print("Pennies: ", pennies)

If you import this script into another program, you probably don't want the script to immediately run; rather you just want the change(amnt) function to be defined so this other program can call it.  This is done by adding a "guard" at the end of the script, which only runs the code if the script is invoked directly:

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    change(amnt)

In addition to separating input from processing, you might want to separate the processing from the output:

def change(amnt):
    quarters, amnt = divmod(amnt, 0.25)
    dimes,    amnt = divmod(amnt, 0.10)
    nickels,  amnt = divmod(amnt, 0.05)
    pennies = round(amnt / 0.01, 0)

    return list(map(int, [quarters, dimes, nickels, pennies]))

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    quarters, dimes, nickels, pennies = change(amnt)
    print("{} quarters, {} dimes, {} nickels, {} pennies".format(
          quarters, dimes, nickels, pennies))

Despite attempts to fix rounding errors with things like round(amnt,2), calling change(0.85) returns [3, 0, 1, 5], showing that there wasn't quite enough change to make 2 nickels, but after removing 1 nickel, approximately 5 pennies remained.  This is caused by floating point math.

We can avoid these issues by switching to integer math, based on the number of pennies:

def change(amnt):
    pennies = round(amnt * 100)   # Convert from dollars to pennies

    quarters, pennies = divmod(pennies, 25)
    dimes,    pennies = divmod(pennies, 10)
    nickels,  pennies = divmod(pennies, 5)

    return quarters, dimes, nickels, pennies

if __name__ == '__main__':
    amnt = float(input("Enter an amount in USD: "))
    quarters, dimes, nickels, pennies = change(amnt)
    print("{} quarters, {} dimes, {} nickels, {} pennies".format(
          quarters, dimes, nickels, pennies))

As mentioned in the comments by @Ilmari, round(...) with only a single argument will round the value to the nearest whole number and return an integer value.  When integer values are used with divmod, results are also integers, so switching from dollars-and-cents to integer pennies eliminates the ugly rounding issues.


Instead of splitting each item in alarms to hours and minutes and then zipping them again like this:

hours = [int(a.split(":")[0]) for a in alarms]
mins = [int(a.split(":")[1]) for a in alarms]

for hour,minute in zip(hours,mins):
    # ...

You could do it in one go without zipping:

hours_minutes = [[int(x) for x in a.split(":")] for a in alarms]
for hour, minute in hours_minutes:
    # ...

It's recommended to follow the coding style guide PEP8.

For example you could simplify things like this:

    if commands != '':

To this:

    if commands:

It's also recommended to avoid multiple imports on the same line like this:

import subprocess,time,threading, winsound, sys, basepipe

And it would be better to move all code out of the if __name__ == "__main__": guard into a def main(): method to avoid variable shadowing in the other methods called from there, as the code in the if guard is in global scope.


You could get rid of the GOTO statements by using labelled loops with EXIT and CYCLE statements.  These allow you to do the sort of flow control that you've used the GOTOs for, but don't permit the less desirable features, such as computed GOTOs.  Using these newer Fortran features also gives you a clearer idea of the flow control at the point at which the branching occurs.  E.g., CYCLE or EXIT statements send you respectively further up or down the source code, and a well chosen label may indicate what the branching is trying to achieve.

Another suggestion, although this is more of a personal preference, is to avoid the potentially endless DO WHILE(1 == 1) loop by using a normal DO loop with a large upper limit and adding warning message if that limit is reached before the end of file is encountered.  Plenty of people might find that overly fussy though.

Example code showing these two points:

PROGRAM so_goto

  IMPLICIT NONE

  INTEGER,PARAMETER :: line_max = 100000

  INTEGER :: i, ios, line_length
  CHARACTER( len=2048 ) :: line

  OPEN(UNIT=10,FILE="so_goto.txt",ACTION="read")

  fread: DO i=1,line_max
    READ(UNIT=10,FMT='(A)',IOSTAT=ios) line
    IF( ios < 0 ) EXIT fread
    line_length = LEN_TRIM(line)
    IF( line_length == 0 ) CYCLE fread

    IF( i == line_max ) THEN
      print*,"BTW, you've hit your read limit before the end of the file."
    ENDIF
  ENDDO fread
  CLOSE(10)

END PROGRAM so_goto


Best place to locate filters in MVC n-layer web application and should I use services/repositories in them?

Here's my take on this problem.

Your use of the AttributeFilter in the presentation layer is fine. You are correct about avoiding the use of a Repository in the filter, it does not belong there. However you can call upon the business layer (which in turn calls your repository) to check if they are subscribed. Keep your business logic where it belongs.

Dependencies in Filters can be mocked, you simply need to create a constructor which accepts the IBusinessService of your choice. Most dependency injection frameworks will create Filters and pass in the correct dependency.

If you don't want to go down that route, change your Filter like so.

class AuthoriseAttribute {

  // Use for testing
  public AuthoriseAttribute(IMockedBusinessService) {
  }

  // Production
  public AuthoriseAttribute():this(new ConcreteBusinessService()) {
  }
}

As always with these things, "it depends". If you have a high performance site, say > 200 connections per second and you get considerable performance gains by having the repository in directly in the presentation layer, then I would bend the rules and leave a nice comment in the code on why you have data access in the presentation layer.

Almost always I prefer code readability and separation of concerns much higher than anything else. Just be sure to take measurements on the performance gains by doing X. If your not measuring, your guessing.


Fetching the total amount of SE reputation accumulated

It's simple to extract all reputation and subsequently sum an index. This is instead of performing the ifelse inside the *apply function to demonstrate indexing.

library(httr)
allc <- content(GET(paste0("http://api.stackexchange.com/users/",'10400443',"/associated")))
allci <- allc$items

# get all reputation out of list
allrep <- sapply(allci,`[[`,'reputation')

# sum only index of > 101
sum(allrep[allrep > 101])

I'm not familiar with Python, but it appears that indexing in R serves the same purpose as list comprehension in Python - list comprehension in r


Things you could improve

Variables/Initialization

Where do you declare multiplier?  I assume that since it is not declared within the method, it is declared as a global variable.  Try to avoid global variables.

The problem with global variables is that since every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

To understand how the application works, you pretty much have to take into account every function which modifies the global state. That can be done, but as the application grows it will get harder to the point of being virtually impossible (or at least a complete waste of time).

If you don't rely on global variables, you can pass state around between different functions as needed. That way you stand a much better chance of understanding what each function does, as you don't need to take the global state into account.

So instead of using global variables, initialize the variables in main(), and pass them as arguments to functions if necessary.  In this case, I don't see the need for multiplier to be used outside of the function at all, so simply keep it declared within the function.
sign should be an int, and not a char.

Algorithm

Right now you are implementing a complicated and hard to follow method of converting a character into a number.  The easy way is to have isdigit() do the hard work for you.  This also will help you implement the DRY principle.

while(*pointer != '\0')
{
    if(*pointer >= '0' && *pointer <= '9')
        multiplier = multiplier * 10;

    pointer = pointer + 1;
}

pointer = pointer1;

while(*pointer != '\0')
{
    if(*pointer >= '0' && *pointer <= '9')
    {
        result = result + ( (*pointer%48)  * multiplier);
        multiplier = multiplier / 10;
    }

    pointer = pointer+1;
}

See how you have two loops doing almost identical things?  Here is how I simplified all of that by using isdigit().

while (isdigit(*c))
{
    value *= 10;
    value += (int) (*c - '0');
    c++;
}

You loop through the characters in the string as long as they are digits. For each one, add to the counter you're keeping - the value to add is the integer value of the character. This is done by subtracting the ASCII value of '0' from the ascii value of the digit in question.
Note that this code doesn't handle overflow. If you pass in "89384798719061231" (which won't fit in an int), the result is undefined.  The fix is simple enough, just use a long long int to mitigate against that.  We'll still have issues for extremely long numbers, but fixing that so that the function works as intended is a bit more complicated.

Documentation

Where did all of your comments go?  A newer developer would simply gawk at some of your code.

result = result + ( (*pointer%48)  * multiplier);

Comments can really go a long way into helping other understand your code.  Don't go overboard with them though, you will have to balance how much of them to put into your program.

Syntax/Styling

This looks like a typo.

if(*pointer == '-')
    sign =- 1;

Add a space for clarity.

if(*pointer == '-') sign = -1;

You should not be modifying your char* you accept as a parameter into the function. Therefore, declare the parameter as constant.

int my_atoi(const char* pointer)

Use more shorthand operators.

pointer++;         // same as pointer = pointer+1;
multiplier /= 10;  // same as multiplier = multiplier / 10;
multiplier *= 10;  // same as multiplier = multiplier * 10;

Final Code

#include <stdio.h>
#include <assert.h>
#include <ctype.h>

long long int my_atoi(const char *c)
{
    long long int value = 0;
    int sign = 1;
    if( *c == '+' || *c == '-' )
    {
        if( *c == '-' ) sign = -1;
        c++;
    }
    while (isdigit(*c))
    {
        value *= 10;
        value += (int) (*c-'0');
        c++;
    }
    return (value * sign);
}

int main(void)
{
    assert(5 == my_atoi("5"));
    assert(-2 == my_atoi("-2"));
    assert(-1098273980709871235 == my_atoi("-1098273980709871235"));
    puts("All good."); // I reach this statement on my system
}


Global variables should always be avoided, so instead of $VALID it should simply be VALID. The entire Ruby ecosystem does not need access to that variable and it might overwrite some important variable somewhere.

Instead of Exception you should be using StandardError. Rubyists do not rescue Exceptions ever really because it catches every single possible exception or error, so if someone (including you) wants to rescue from parse, it will be confusing and non idiomatic. Exception is the top level class for all errors, including syntax errors, interruption errors, and memory errors. I would recommend either doing the simple fail "Error", or take a more object oriented approach (which will improve potential rescues) and create a new error object, perhaps UnmatchedBracketsError which inherits StandardError. This also means that when you decide to change the message, you only need to change it in the UnmatchedBracketsError class rather than in both of the identical throw calls.

I may be misunderstanding the scoping decisions taken here but it seems like parse should be a method in the BF class. It can be "static" by doing def self.parse, but it just seems weird to have it in the main namespace. Moving that would also mean it would make sense to move VALID out of the main namespace and into BF.

Array#<< is faster than Array#push so I recommend using that.

Now for the stylistic things.

Typically, multiline blocks are defined using do end syntax rather than {}. So

ast.each {|e|
    ...
}

becomes

ast.each do |e|
    ...
end

Every instance of then in your code is unnecessary.

For that ARGV[0] == nil call, firstly it can be optimized to ARGV[0].nil?. After that, it might be better to use the boolean-y value of ARGV[0]. So if ARGV[0] == nil -> if ARGV[0].nil? -> unless ARGV[0].

if level != 0 then
    throw Exception.new "Unmatched brackets"
end

can be shortened to throw Exception.new("Unmatched brackets") if level != 0.

Both of your while loops are using negated conditionals, which means they can be idiomatically changed to until loops. while !empty? can become until empty? and while a != 0 can become until a == 0.

Lastly, I'm pretty sure self can be omitted in the run call.


Few comments:

Make your code more abstract, use IEnumerable instead of List

 public interface ICsvReader
 {
    IEnumerable<Contact> ParseCsv(string filePath);
 }

Provide an asynchronous version

public interface ICsvReader
{
    IEnumerable<Contact> ParseCsv(string filePath);
    Task<IEnumerable<Contact>> ParseCsvAsync(string filePath);
}

Use StreamReader instead of File.ReadAllLines, it has an async version that you can use in your ParseCsvAsync method

using(var stream = new StreamReader(filePath)){
 // read all lines
}

Try to use the var keyword for local variables, it makes refactoring easier

var rows = GetRows(filePath);

Use the beauty of deferred execution in C#

private IEnumerable<Contact> MakeContacts(string[] headers, List<string[]> rows)
{
    for (int i = 1; i < rows.Count; i++)
    {
        string[] row = rows[i];
        Contact contact = new Contact();
        for (int e = 0; e < row.Length; e++)
        {
            string header = headers[e];
            string value  = row[e];

            contact = MatchHeader(contact, header, value);
        }
        yield return contact;
     }
}

You can convert ToList immediately without calling ToArray

  private IEnumerable<List<string>> GetRows(string filePath)
  {
    // why you creating this List here???
    List<Contact> users = new List<Contact>();
    lines = File.ReadAllLines(filePath);
    var csv = (from line in lines
              select line.Split(',')).ToList();

    return csv;
  }

Consider @Snowbody suggestions about using a Dictionary instead of a massive switch.


Closing InputStream of a running process

To add to @ChrisWue's answer I would pull the Process away from the actual processing of it's data. IE: Make a separate class that takes a stream and does processing. Think about it this way: what is your code doing? It is taking data off of some InputStream and checking for a specific keyword. Does that processing code need a Process instance to do that? Nope! You could pass your code any InputStream and it would be able to look for a keyword. Making sure your methods are only given exactly what it needs dramatically increases testability, flexibility, and re-usability.

For the second part actually using the Process' Input/Output/Error streams. If you read the JavaDocs you will find this:

  By default, the created subprocess does not have its own terminal or
  console. All its standard I/O (i.e. stdin, stdout, stderr) operations
  will be redirected to the parent process, where they can be accessed
  via the streams obtained using the methods getOutputStream(),
  getInputStream(), and getErrorStream(). The parent process uses these
  streams to feed input to and get output from the subprocess. Because
  some native platforms only provide limited buffer size for standard
  input and output streams, failure to promptly write the input stream
  or read the output stream of the subprocess may cause the subprocess
  to block, or even deadlock.

Basically, what this is telling me is that you need to make sure you are managing all of these streams appropriately. If you close one of the processes streams prematurely you have to be sure that the Process can handle that case. Most applications will crash or exit with an error code. Unless you know you won't break the Process you're trying to run be sure to process all the data from these streams until that process is done. You could use a simple thread which just reads and discards the data if you don't need it.

Just a thought but if you are controlling the application you are running as a Process you could possibly tell the application to close gracefully by sending it something using the OutputStream.


This implementation allows for reusability of the indexer backing logic, as shown on MyClass two having two indexers using the same backing implementation. This pattern is much more reusable.

public abstract class PropertyIndexer<TKey, TValue>
{
    public abstract TValue this[TKey index] { get; set; }
}
public class MyClass
{
    private class StringDictionaryPropertyIndexer : PropertyIndexer<string, string>
    {
        private Dictionary<string, string> BackingCollection { get; set; }
        public StringDictionaryPropertyIndexer(Dictionary<string, string> backing)
        {
            this.BackingCollection = backing;
        }
        public override string this[string index]
        {
            get
            {
                string value;
                if (BackingCollection.TryGetValue(index, out value))
                    return value;
                return null;
            }
            set
            {
                BackingCollection[index] = value;
            }
        }
    }
    private Dictionary<string, string> data { get; set; }
    public PropertyIndexer<string, string> Data { get; private set; }
    private Dictionary<string, string> alternateData { get; set; }
    public PropertyIndexer<string, string> AlternateData { get; private set; }
    public MyClass()
    {
        data = new Dictionary<string, string>();
        Data = new StringDictionaryPropertyIndexer(data);
        alternateData = new Dictionary<string, string>();
        AlternateData = new StringDictionaryPropertyIndexer(alternateData);
    }
}


Bidirectional numeric (floating point) sequence iterator

Counter intuitive?

Infinite loops.

The function is an iterator so this may not be undesired or potentially fatal for the application. However some inputs would make one wonder about the callers intent.

numrange(0, 100, 0); // will endlessly return 0
numrange(0, 100, -1); // will return 0, -1, -2, ... Infinity
numrange(0, -100, 1); // will return 0, 1, 2, ... Infinity

Not part of sequence.

There are situation where the last value can be out of sequence

numrange(0, 4, 2); // will return 0, 2.5, 4.

Or two values are returned rather than one.

numrange(4, 4, 1); // will return 4, 4.

Names

The function name should be numRange to be consistent with JS camelCase convention.
The argument ival (should be iVal) in shouldLoop is excessive, you could just have used i.
The function name shouldLoop can also be simplified as it expresses a question "should loop?" which can be shortened considering the context of its use to "loop?"

Logic and flow

The function shouldLoop is called 2 times each iteration, there is no need to do this, on top of this there are cases where the first clause of the inner statement is redundant. eg numRange(0, 20, 1.01) BTW use strict inequality !== rather than !=

You can improve efficiency if you removed the inner statement and yielded end after the loop. You would also need to change the return condition inside the function shouldLoop to start > end ? ival > end : ival < end

Each time you iterate you test if start > end This is known from the very start of the function and is thus repeating the same logic for no need. Use the condition to assign one  of two functions and avoid the repeated logic.

Rewrite

Thus you can have the same behavior as your original code with

function* numRange(start = 0, end = 100, step = 1) {
    const loop = start > end ? (i) => i > end : (i) => i < end;
    if (start > end) { step = -1 * step }
    for (let i = start; loop(i); i += step) {
        yield i;
    }
    yield end;
}

Example

Fixing what I see as problems (as outlined at the start of the answer)

Ensure that step is in the correct direction no matter what its sign.
Check if step is 0 and just return the start if so.
Check if end is part of the sequence and ignore it if not.

Using the var as argument start to count.

.

function* numRange(start = 0, end = 100, step = 1) {
    step = Math.sign(end - start) * Math.abs(step);
    if (step) {
        const loop = step > 0 ? () => start < end : () => end < start;
        while (loop()) {
            yield start;
            start += step;
        }
        if (start !== end) { return }
    }
    yield start;
}


This code is far from readable.

Optional braces should not be considered optional.
Omitting these braces leaves your code prone to future errors.
Besides this, I personally find it makes your code harder to parse.  I'm so used to seeing loop bodies (or if/else) contained within braces, that it becomes easy to mentally skip that block and say "Yup, this is the looping stuff that's happening."  Here, without the brackets, it just looks like your code has indentation problems, and it is distracting.

Single-letter variable names are not acceptable.
The only place that they're even remotely acceptable is as for loop iteration variables, and even this is a purely historical exception to the rule (and I'd argue that i and j are in violation of this exception as they're not declared within the for loop's initialization statement).

Small variable names don't make your code run faster.
Small variable names don't make your code use less memory.
Small variable names don't make your code compile faster.
Small variable names don't make your executable size smaller.
Small variable names do make your code harder to read.

An amazing example of this last point is your code base where we have six different single letter variable names all in the same scope (plus another two in the factorial function).
To the compiler, it doesn't matter what you name all of your variables.  It's smart enough to keep up with all of them.  I'm not that smart.  I'm looking at six variables with completely meaningless names that I'm expected to keep track of.
A variable's name should tell the human reader exactly what it is meant to store.

It's called main.  It's not called everything.
You did manage to move the factorial function out.  But there's a lot of complexity remaining in main that can surely be refactored out into smaller, bite-size functions that can be good names to explain exactly what they're doing.  And that'd definitely help with your code's readability.


Animation of multiple text elements in sequence

For readability, take advantage of jQuery methods that use the jQuery Deferred object to eliminate your deeply nested callback structure.
Example jQuery.when() can turn your code into this.

$.when({}).then(function(){
    return line.stop(true, true).show('slide', {direction: whichway}, speed-150);
}).then(function() {
    return title.stop(true, true).fadeIn(speed-200);
}).then(function() {
    return sub.stop(true, true).show('slide', {direction: whichway}, speed-50 );
}).then(function() {
    subtext.stop(true, true).show();
    return paragraph.stop(true, true).slideDown(speed);
});

Here's another example of using $.when: http://jsfiddle.net/Tp569/

Code from demo.

CSS:

.box{
    width: 10em;
    height: 10em;
    display:none;
}

HTML:

Box 1

Box 2

JS:

$.when({}).then(function(){
    return $("#box1").css("backgroundColor", "blue" )
        .fadeIn( "slow" ).delay(500).animate({
            opacity: 0.5,
            margin: '50'
        }, "slow").delay(1000);
}).then(function() {
    return $("#box2").css("backgroundColor", "yellow" ).fadeIn( "fast" );
});

For speed, try out animate.css, which is a pure css 3 base animation library.
If that's not enough then read this


First of all, the code suffers a very typical problem. The single most important feature of merge sort is stability: it preserves the order of the items which compare equal. As coded,

            if left[l] < right[r]:
                sortedArray[i] = left[l]
                l = l+1
            else:
                sortedArray[i] = right[r]
                r = r+1

of two equals the right one is merged first, and the stability is lost. The fix is simple:

            if left[l] <= right[r]:

(or if right[i] < left[i]: if you prefer).

I don't think that try/except on each iteration is a way to go. Consider

        try:
            while i in range(len(array)):
                ....
        except:
            ....

Of course here i is not known in the except clause. Again, the fix is simple. Notice that the loop is never terminated by condition: either left or right is exhausted before i reaches limit. It means that testing the condition is pointless, and i is an index on the same rights as l and r:

        l = 0
        r = 0
        i = 0
        try:
            while True:
                ....
        except:
            ....

Naked except are to be avoided. Do except IndexError: explicitly.


There's a few notable things here:

You're prepending to a list, then reversing the result at the end. It would be better to just start with a vector ([]). conjoining to a vector appends the element to the end instead, so you don't need to reverse it after.

If you really want a list here because it's checking for type, then either ignore this suggestion, or put this code into a helper and do something like:

(def primeFactorsOf [n]
  (list* (helper n)))

I personally think a vector makes more sense here, but it may prove to not be worth it in this case.

(= (mod number candidate) 0)

can just be

(zero? (mod number candidate))

I wouldn't have all your loop accumulators on the same line like you have. It's much harder to read, since you have to manually group them in two's in your head to make sense of them. I'd split them up:

(loop [number n
       candidate 2
       factors []]
  . . .)

If you really want to have them on one line though, add some commas in there. Commas have, as far as I know, no purpose other to allow you to group expressions to help readability. I'd add them in every two here:

(loop [number n, candidate 2, factors []]
  . . .)

Nested if expressions are usually cleaner using a cond. There are a multitude of ways to format a cond block, but when you have long lines like you have here, I like to format it almost like you would an if statement in a imperative language (below).

All together, I end up with:

(defn primeFactorsOf
 "Return all prime factors of a number"
 [n]
 (loop [number n
        candidate 2
        factors []]
   (cond
     (= number 1)
     factors

     (zero? (mod number candidate))
     (recur (/ number candidate) candidate (conj factors candidate))

     :else
     (recur number (inc candidate) factors))))


Return a string based on Type, Color and Position

public override string ToString()
    => ((int)Type > 99 ? "t" : "s")
    + ((int)Type > 99 ? ((int)Type).ToString().Remove(0, 1) : ((int)Type < 10 ? "0" + (int)Type : "" + (int)Type))
    + ((int)Color < 10 ? "0" + (int)Color : "" + (int)Color)
    + (int)Position;

You definitely should split it in a exactly four methods/variables:

Method 1: GetPrefix

((int)Type > 99 ? "t" : "s")

Method 2: FormatSomething, sorry, I don't know what.

((int)Type > 99 ? ((int)Type).ToString().Remove(0, 1) : ((int)Type < 10 ? "0" +  (int)Type : "" + (int)Type))

Method 3: FormatColor:

((int)Color < 10 ? "0" + (int)Color : "" + (int)Color)

Method 4: FormatPosition - this might be unnecessary but because all other formattings are method let's make this consistant.

(int)Position

Finally your ToString would look like this:

public override ToString() =>
    $"{GetPrefix()}{FormatSomething()}{FormatColor()}{FormatPosition()}"

and nobody asks any more questions about what your method is doing.


Calculating relative strength index over a period

Your code is already pretty Pythonic.

There is a bug in your code. If no losses were reported in that window then losses == 0.0 which when you append to rsi will throw a ZeroDivisionError.

There are two suggestions I would make:

Use zip (or izip if possible)

The zip function takes two iterables and combines them. It essentially returns:

>>>zip([1,2,3], ['a','b','c'])
[(1, 'a'), (2, 'b'), (3, 'c')]

We can use this instead of directly indexing through j and j-1.
If-Else

Currently your if-statement looks like this:

if diff > 0:
    gains += diff
elif diff < 0:
    losses += abs(diff)

I would recommend making the elif into a simple else. This is because anything that the elif won't catch is if diff == 0 and since losses == losses + 0, it won't effect losses. Also, you remove a comparision using a simple else.

With these suggestions taken into account (plus the simple bug fix), we can refactor your code a little bit:

def get_rsi(self, period):
    rsi=[]
    for i in range(len(self.hist_d)-period):
        gains = 0.0
        losses = 0.0

        window = self.hist_d[i:i+period+1]
        for year_one, year_two in zip(window, window[1:]):
            diff = year_two - year_one

            if diff > 0:
                gains += diff
            else:
                losses += abs(diff)

        # Check if `losses` is zero. If so, `100/(1 + RS)` will practically be 0.
        if not losses:
            rsi.append(100.00)
        else:
            rsi.append(round(100 - (100 / (1 + gains / losses)), 2))

    return rsi


About your code:

As a general rule, the imperative pattern acc = 0; xs.each { |x| acc += f(x) }; total = acc should be replaced by the functional expression total = xs.reduce(0) { |acc, x| acc + f(x) } or total = xs.map { |x| f(x) }.reduce(0, :+). Given that Rails provides an Enumerable#sum, it can be simplified even more: total = xs.map { |x| f(x) }.sum.
That said, this is not the way you do things in Rails, you should use associations and scopes. The code will be much faster (all the processing is performed by the database engine) and more reusable.

I'd write:

class User
  has_many :conversations, ->(user) { Conversation.with_user(user) }
  has_many :messages, through: :conversations

  def unread_messages_count
    messages.not_sent_by(self).unread.count
  end
end

class Conversation
  scope :with_user, ->(user) { where("? IN (user1_id, user2_id)", user.id) }
end

class Message
  scope :unread, -> { where(read: false) }
  scope :not_sent_by, ->(user) { where.not(user: user) }
end

Note that we could write the where-condition of with_user directly in the has_many block, but this way we respect encapsulation: the User model knows nothing about the attributes of the Conversation table.


Estimating the number of tanks based on a sample of serial numbers

I'm not going to comment on speed, only on coding style. For speed you should probably look at the python numerics library numpy (often abbreviated to np) especially Quickstart, Random numbers and Statistics sections.

The biggest problem with the code is that one huge block is doing everything. There aren't any functions; the code is generating random numbers, attempting to reverse-engineer them, and then testing performance. It's very hard to distinguish what part of the code is responsible for what; I had trouble piecing it together until I read over several times. It would be very hard to re-use portions of this code, even with copy and paste.

These should all be separate functions. This won't get you any speed boost but will make analysis much easier. That way you can update each function on its own without having to comb through your code for where the logic is located. Each function should have one job, this is called the single responsibility principle.

In addition, there should be a main() type function that acts as the driver for all the other functions. And the only line that ought to be at top-level of the file is the main guard:

    if __name__ == "__main__":
        main()

In particular, main() should pass the parameters in to the functions that actually do the work. Don't rely on global variables; again it makes the code impossible to use elsewhere. Variables should be scoped to where they are actually used.

Use _ for dummy variables in loops

for x in range(numRuns):

Since the loop index is not being used, convention is to use _ for the variable name.
Don't repeat yourself, make sure code is modular.

randNum = [random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1),random.randint(1,chosenNum + 1)] #generates the seven serial numbers.

This line is too long, has repeated code, and is fixed at 7. What if the problem requirements change, and you need to solve the problem for capturing 13 tanks? Much better to have the number of captured tanks be a parameter, then use a list comprehension to call the randomness repeatedly. (I think since you used randint you don't need to add the + 1. randint is already inclusive. randrange is half-inclusive.) I suggest

tankSerialNumbers = [random.randint(1,chosenNum) for _ in range(numCapturedTanks)]

Choose meaningful variable names, and don't repeat yourself

maxNumSTD = statistics.mean(randNum)+(3*(statistics.stdev(randNum))) #three standard deviations above the mean

You just calculated stdev(randNum) on the line above, why calculate it again? And maxNumSTD is a poor variable name as it does not describe the variable at all. It's not a max of anything, and it's certainly not a standard deviation. It's a guess as to the highest tank number, so call it that!

highestTankSerial = statistics.mean(randNum) + 3*NumSTD

Don't repeat yourself. Seeing a trend here? In this section

if (maxNum - maxNumSTD < 0):
  for y in range(maxNum,int(maxNumSTD)): #n is max number to max number from Standard Deviation
    randNumZwei =  [random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y)]
    testNumSTD = statistics.stdev(randNumZwei)
    STDarray.append(testNumSTD)
else:
  for y in range(int(maxNumSTD),maxNum):
    randNumZwei =  [random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y),random.randint(1,y)]
    testNumSTD = statistics.stdev(randNumZwei)
    STDarray.append(testNumSTD)

the code is almost exactly the same in the if and else blocks. Compare the two elements and swap them if necessary, then you don't need to duplicate your code.
Use Python's list features. In your code,

for z in range((len(STDarray) - 1)):
    if((min(STDarray, key=lambda x:abs(x-NumSTD))) == STDarray[z]): #find closest number to original standard deviation
        numGuessed = z + maxNum

you do use both the array index and the value. That's what enumerate is for. Also why are you skipping the last element of the list? And why are you recalculating the min each time through the loop? And why aren't you jumping out of the loop right away?

minStd = min(STDarray, key=lambda x:abs(x-NumSTD))
for (z,this_std) in enumerate(STDarray):
    if(minStd == this_std): #find closest number to original standard deviation
        numGuessed = z + maxNum
        break

But wait a minute. The whole goal of this is just to get the index of the minimal element. That's easy to do in one step with enumerate using tools you already know about.

(z, _) = min(enumerate(STDarray), key=lambda (_,x):abs(x-NumSTD))
numGuessed = z + maxNum


Determine if two strings with no repeating characters are permutations of each other

You could use the SetEqual<T> helper method from this answer.
It uses a dictionary as follows:

The dictionary is filled with the items of the first collection and with their number of occurences.
Number of occurences is decreased for each item in the second collection.

Thus your method can be rewritten as:

private static bool IsPermutation(string first, string second)
{
    if (first.Length != second.Length)
    {
        return false;
    }
    return SetEqual(first, second);
}

If you are sure that strings contain only unique chars, there is a more efficient approach using the HashSet<T>:

private static bool IsPermutation(string first, string second)
{
    if (first.Length != second.Length)
    {
        return false;
    }
    HashSet<char> chars = new HashSet<char>(first);
    return second.All(chars.Contains);
}


Preg_match pattern for user input filtering

Well if having an underscore in your line could be acceptable, then

$reg = "#[^\w\s-']#i";

could be used. If you cannot have underscores, then

$reg = "#[^a-z\d\s-']#i";

could be correct.

A conditional using preg_match would be safe with this.


A shell script to mount a disk image file

The first conditional group can be reorganized to make it flatter and simpler:

if [ ! -e "${MOUNTPOINT}" ]; then
    sudo mkdir -p "${MOUNTPOINT}"
elif [ -d "${MOUNTPOINT}" ]; then
    echo "Mountpoint exists, but isn't a directory..."
    exit 1
fi

The exit 0 is pointless in the last condition,
and as such, you could replace it with a one-liner using &&:

mountpoint -q "${MOUNTPOINT}" && echo "Already mounted..."


Obviously this is one of those things which is opinionated but:

1) It might be simpler to use num.zero? as your base case

2) I would pass the spare tower as a parameter rather than calculating it all the time.

Something like:

def hanoi(num, from, to, spare)
  return [] if num.zero?                   # base case

  moves =  hanoi(num - 1, from, spare, to) # move everything to the spare peg
  moves << Move.new(num, from, to)         # move the sole remaining disk to the 'to' peg
  moves += hanoi(num - 1, spare, to, from) # move all the disks on top of the 'to' peg
end


Blocks longer than one line are conventionally written using do…end rather than braces.
Code of the form

out = []
list.each { |l| ... out.push(something) }

… would be better expressed as

out = list.collect { |l| something }

Besides being slightly more compact, there is a subtle difference in thinking: the former feels like "do this, then this, then this to build a result"; the latter says "transform each element like this", and it's easier to see that there is a one-to-one correspondence between input elements and output elements.
Within that block,

out = list.collect do |l|
  # Calling l.downcase! would have the side-effect of modifying
  # strings in the original list, which is impolite.
  l = l.downcase

  shared_chars = []
  key.split.each_with_index do |c, keyi|
    index = l.index(c)
    # Actually, char:c is never used and could be eliminated
    shared_chars.push(char: c, index: index, kindex: keyi) if index
  end

  distance, kdistance = 0, 0
  shared_chars.each_cons(2) do |a, b|
    distance += (b[:index] - a[:index]).abs
    kdistance += (b[:kindex] - a[:kindex]).abs
  end

  { val: l, shared_chars: shared_chars, distance: (distance - odistance).abs }
end

Furthermore,

out.sort_by! { |e| ... }
out

could just be

out.sort_by { |e| ... }

(.sort_by is defined because an Array is an Enumerable.)
I think that the whole function would be better as one chained expression:

def search(key, list)
  key = key.downcase

  list.collect do |l|
    ...
  end.sort_by do |e|
    # There's no point in adding 100 to each element
    e[:distance] - 3 * e[:shared_chars].length
  end
end


Replacing the occurence of the character in string

An easy way to generate all of the possible 0 and 1 combinations is to use binary numbers.

If there are 3 ?'s then the combinations of 0's and 1's will be all binary numbers from 0 to 2^3 - 1:

0:  000
1:  001
2:  010
3:  011
4:  100
5:  101
6:  110
7:  111

So all you need to do is count the number of question mark characters (N) and then count from 0 to 2^N - 1 to generate all the possible 0 and 1 combinations.

Also I notice that half of these strings will have a 0 in the first position, and half will have a 1. I wonder if this feature could be used to reduce the amount of iteration you need to do.


Given this method, we don't know which syntax is the more appropriate.

Neither is appropriate as both your options employ promise anti-patterns (creating new promises when you can just work with and return the one you already have).

Assuming req() already returns a promise (which you imply with your use of await), you should just return that promise directly.  I see no reason to even use async or await here.

// presumably from your use of this, this is a method declaration
function finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };
  return req(options);
}

this.finishUpgrade({id: someId}).then(result => {
    // upgrade done here
}).catch(err => {
    // error here
});

When you do need to modify the return value, you just add a .then() handler and the modified value you return from that .then() handler becomes the new resolved value:

// presumably from your use of this, this is a method declaration
function finishUpgrade({id}) {
  let options = {
    method: 'POST',
    uri: this.apiUrl + `${id}/?action=proceed`,
    body: {}
    json: true
  };
  return req(options).then(result => {
      // change the resolved value of the promise to our data object
      let data = { someData: someValue };
      data.response = result;
      return data;
  });
}

this.finishUpgrade({id: someId}).then(result => {
    // upgrade done here
}).catch(err => {
    // error here
});