Writing to and reading from socket in an IMAP client

The code looks fine.  Instead of const std::string &command, you can take std::string_view command to avoid unnecessary allocation when the argument is not readily a std::string (e.g., string literals).  std::ostringstream seems more appropriate than std::stringstream here, since you are not reading from it.  Creating a new stream may also be more readable than reusing the stream.

Prior to C++20, str on string streams always make a copy of the buffer, so there isn't much you can do about it.  Since C++20, you can move the underlying buffer by moving the string stream itself:

// since C++20
std::string response = std::move(ss).str();


Extract string list as array from an array of objects

Sounds like a perfect case for generator functions. Unfortunately, map and the other array default methods don't have lazy versions of map/filter, but these functions aren't hard to write.

const images = [
    {id:1, cook:"jim",   ingredients:"chicken salsa mayo ketchup tomato"},
    {id:2, cook:"steve", ingredients:"pasta mozzarela chicken"},
    {id:3, cook:"jim",   ingredients:"bread lettuce tomato onions"},
    {id:4, cook:"jim",   ingredients:"ketchup sausage bread"},
    {id:5, cook:"jim",   ingredients:"avocado ground_meat chili"},
    {id:6, cook:"jim",   ingredients:"ground_meat guacamole tomato parsley"},
    {id:7, cook:"steve", ingredients:"chicken tomato broccoli"}
]

function* lazyMap(iterator,callback) {
    for (const value of iterator) {
        yield callback(value)
    }
}

function* lazyFilter(iterator,callback) {
    for (const value of iterator) {
        console.log(`looking at order with id=${value.id}`)
        if (callback(value)) yield value
    }
}

function* lazyFlat(iterator) {
    for (const list of iterator) {
        for (const value of list) {
            yield value
        }
    }
}

function* lazyUnique(iterator) {
    const seen = new Set()
    for (const value of iterator) {
        if (!seen.has(value)) yield value
        seen.add(value)
    }
}

function takeSome(iterator,limit) {
    let list = []
    for (const value of iterator) {
        list.push(value)
        if (list.length>=limit) return list
    }
    return list
}

function extractIngredients(orders,cook,limit=25) {
    const cook_orders = lazyFilter(orders,order=>order.cook===cook)
    const orders_ingredients = lazyMap(cook_orders,order=>order.ingredients.split(' '))
    const all_ingredients = lazyFlat(orders_ingredients)
    const unique_ingredients = lazyUnique(all_ingredients)
    return takeSome(unique_ingredients,limit)
}

console.log(extractIngredients(images,'jim',10))

As you can see from the console output, only IDs up to 5 are looked at, because on the order with ID=5, the 10th ingredient is found and the function returns.
The bonus seems confusing, as if your goal is to sort by frequency, you must traverse all of your data to build an accurate histogram.


This is not JSON. However JSON was inspired from Javascript Native way of creating object. This is why they're really similar.

However JSON handles only data, not functions.

Furthermore you can rewrite your function like this :

function newObj(name){
    this.name = name;
    return this;
};
newObj.prototype.greeter = function(lang){
    switch (lang){
            case "en":return "hi "+this.name;
            case "es":return "hola "+this.name;
            default: return "hello "+this.name;
    }
}

var obj = new newObj("name");
obj.greeter("de");

As you can see

I got rid of the 2nd parameter in the newObj function since it was not used.
I bind greeter to the Object so now I can use this.name in greeter to greet you by your name.
If you try to JSONify this, everything under prototype will be ignored so you won't have any error.


This is needlessly complicated and inefficient. Rather than making an array of all digits in the array, you should make an array of counted occurrences. Since a digit can have a value 0 to 9, this array size will be 10. For each occurrence, increase the value of the index in the array corresponding to the digit by 1.

This also means that you can count non-repeating characters on the fly while iterating through the number. When the number of occurrences is exactly 1, it should be counted. If more than that, it shouldn't.

This makes the code behave the same no matter the number of digits used as input.

Example:

#include <stdio.h>

int non_repeating (int val)
{
  if(val == 0) // special case, value 0 gives 1 digit
  {
    return 1;
  }

  int digit_count[10]={0};
  int non_rep=0;

  for(; val!=0; val/=10)
  {
    int i = val%10;
    digit_count[i]++;

    if(digit_count[i]==1)
    {
      non_rep++;
    }
    else if(digit_count[i]==2)
    {
      non_rep--;
    }
  }

  return non_rep;
}

int main (void)
{
  printf("%d %d\n", 252,        non_repeating(252));
  printf("%d %d\n", 25000,      non_repeating(25000));
  printf("%d %d\n", 1234567890, non_repeating(1234567890));
  printf("%d %d\n", 0,          non_repeating(0));
}

Output:

252 1
25000 2
1234567890 10
0 1


1. Bug

A correct implementation of breadth-first search visits each node at most once, but the code in the post visits some nodes multiple times. In this example, \$C\$ gets visited twice:

>>> graph = {'A': 'BC', 'B': 'C', 'C': 'A'}
>>> bfs(graph, 'A', 'Z')
A
vertex ['B']
vertex ['B', 'C']
B
vertex ['C', 'C']
C
vertex ['C', 'A']
C
vertex ['A']

The problem is that a node is only added to the history list after you pop it from the vertex list. But that means that if there are multiple paths to a node, then it can be added to the vertex list multiple times (as in the example above, where node \$C\$ gets added twice).

Instead, a node should be added to the history list at the same time as you add it to the vertex list.

2. Review

The name queue would be better than vertex (it's a queue of nodes that have been visited in the search but whose neighbours have not yet been considered for visiting).
The queue is implemented using a list. But this is inefficient because popping the leftmost element of a list takes time proportional to the length of the list (because the other items in the list get moved down in the list to fill the space). It is better to use a collections.deque, which has an efficient popleft method.
The name visited would be better than history (it's a collection of nodes that have been visited in the search).
The collection of visited nodes is implemented using a list. But this is inefficient because finding an element in a list takes time proportional to the length of the list (because the element gets compared against each member of the list in turn). It is better to use a set, which has efficient membership determination.
The name neighbour would be better than i (it's a neighbour of node in the graph).
It's pointless to add a node to the queue and then immediately remove it again:

    if i:  #if i is not empty
        vertex.append(i)
    if i in history:
       vertex.pop(-1)

Instead of testing for node == end after popping the node from the queue, it would be better to test before adding it to the queue. That way you wouldn't have to wait for the end node to move all the way up the queue.

3. Revised code

from collections import deque

def bfs(graph, start, end):
    """Return True if there is a path from start to end in graph, False if
    not. graph must be a dictionary mapping a node to a collection of its
    neighbours.
    """
    if start == end:
        return True
    queue = deque([start])
    visited = set(queue)
    while queue:
        node = queue.popleft()
        for neighbour in graph.get(node, ()):
            if neighbour not in visited:
                if neighbour == end:
                    return True
                queue.append(neighbour)
                visited.add(neighbour)
    return False


I have some suggestion for you.

1) Constant name should always be uppercase.

private static final Scanner SCANNER = new Scanner(System.in);

2) When creating arrays, I suggest that you use the java style instead of the c style, since it's the more used and less error-prone, in my opinion.

Before

public static void main(String args[]) {
   //[...]
}

After

public static void main(String[] args) {
   //[...]
}

3) For the variables, I suggest that you create them on the same line as the initialization, you will save 3 lines in the method and make the code more readable.

        System.out.print("Money in Euro: ");
        double money = SCANNER.nextDouble();
        System.out.print("Annual percentage rate: ");
        double rate = SCANNER.nextDouble();
        System.out.print("Term in years: ");
        int years = SCANNER.nextInt();

4) You can extract the questions in methods, to separate the logic and it will be easier to read, if you want; but will have to explain to him :)

public static void main(String args[]) {
    // write your solution here:

    double money = askForAmountInEuro();
    double rate = askForAnnualPercRate();
    int years = askForTerm();

    for (int i = 1; i <= years; i++) {
        money += money * (rate / 100);
        System.out.println("Money after " + i + ". years: " + money);
    }
}

private static int askForTerm() {
    System.out.print("Term in years: ");
    return SCANNER.nextInt();
}

private static double askForAnnualPercRate() {
    System.out.print("Annual percentage rate: ");
    return SCANNER.nextDouble();
}

private static double askForAmountInEuro() {
    System.out.print("Money in Euro: ");
    return SCANNER.nextDouble();
}
```


Check “five in a row” for a 15x15 chess board (part 2)

What an interesting little problem!

You don't need to accumulate any stats at all, if you just test each cell for whether it is at the centre of a line of 5 all the same colour. This also means that, for example, you don't need to look at first two and last two columns when searching for a horizontal line, and similarly for rows and diagonals.

Here's a (rather wholesale) modification of your code. All the real work is done in the winning_cell() function, which just tests the four lines that this cell is at the centre of. This leaves the main loop in check_five() very clean.

Although there's a lot of work in winning_cell, on a randomised matrix this runs about 30% faster.

(EDIT: this is in Python 3.6 - I've just noticed you are on 2.7. Apart from the brackets round the print statement I'm not sure what else this would affect.)

import random
import pprint

# Offsets from the current cell to cells that might form five in a row
# with the current cell as centre, calculated here so as to be outside
# the main loop
OFFSETS = (-2,-1,+1,+2)
DIAG_1 = [*zip(OFFSETS,OFFSETS)]
DIAG_2 = [*zip(OFFSETS,reversed(OFFSETS))]

def winning_cell(m, row, col):
    """ True if the given cell is at the centre of a row of 5 """
    # Note that when checking for a horizontal line we don't need to
    # check the first two or last two columns - the same logic applies
    # to rows and diagonals.
    colour = m[row][col]
    # check within row
    if (1 < col < len(m[0]) - 2 and
        all([m[row][col + c] == colour for c in OFFSETS])):
        return True
    # check within column
    if (1 < row < len(m) - 2 and
        all([m[row+r][col] == colour for r in OFFSETS])):
        return True
    #check diagonals
    if (1 < col < len(m[0]) - 2 and
        1 < row < len(m) - 2 and
        (all([m[row + r][col + c] == colour for r, c in DIAG_1]) or
         all([m[row + r][col + c] == colour for r, c in DIAG_2]))):
        return True
    return False

def check_five(matrix):
    WHITE = 1
    BLACK = 2
    EMPTY = 0
    BLACK_WIN = False
    WHITE_WIN = False

    # main loop to check cells
    for row in range(len(matrix)):
        for col in range(len(matrix[0])):
            cell = matrix[row][col]
            if (cell == EMPTY or
                cell == WHITE and WHITE_WIN or
                cell == BLACK and BLACK_WIN):
                pass
            else:
                if (cell == WHITE and winning_cell(matrix, row, col)):
                    WHITE_WIN = True
                if (cell == BLACK and winning_cell(matrix, row, col)):
                    BLACK_WIN = True
                if WHITE_WIN and BLACK_WIN:
                    return (True, True)

    return (WHITE_WIN, BLACK_WIN)

if __name__ == "__main__":
    matrix = [[random.choice([0,1,2]) for _ in range(15)] for _ in range(15)]
    pprint.pprint(matrix, indent=4)
    print (check_five(matrix))


Here's your shortening including a fold.

bubbleSort :: Ord a => [a] -> [a]
bubbleSort xs = foldr swapTill xs [1..length xs-1]

swapTill :: Ord a => Int -> [a] -> [a]
swapTill 0 = id
swapTill count = \(x:y:xs) -> min x y : swapTill (count-1) (max x y:xs)

Reordering the swaps to sort a growing suffix of the list banishes Int.

bubbleSort :: Ord a => [a] -> [a]
bubbleSort = foldr swapTill []

swapTill x [] = [x]
swapTill x (y:xs) = min x y : swapTill (max x y) xs


While the formulation Does any permutation of word A's letters match word B? is technically correct, it's also terribly impractical when implemented. As you yourself point out, there are a lot of permutations, and we're looking for just one.

A simpler formulation would be

  Are the letters in word A the same as in word B?

Or, in code

word_a.chars.sort == word_b.chars.sort

That'll be a lot quicker.

Also, since you've got 2 arrays, and want to match one word from each at a time, you could use Array#zip to produce a single array of pairs, and loop that instead. You rarely need to deal with plain C-style loops or actual array indexes in Ruby, because you have all the methods from Enumerable. It's not that these are necessarily more efficient than old-school loops, it's that they are more expressive and much more idiomatic.

One of those Enumerable methods, by the way, is all? which simply checks if a block evaluates to non-false/non-nil for all items.

So for instance, you could do this:

def all_anagrams?(words_one, words_two)
  words_one.zip(words_two).all? do |word_a, word_b|
    word_a.chars.sort == word_b.chars.sort
  end
end

Basically: pair up the words from each array, and check if the words in each and every pair are anagrams of each other.

And yes, it returns true for the two arrays in your question.

Of course, it doesn't say much about what words (if any) aren't anagrams. If you want more feedback, you could look into using #detect to find the first pair that isn't anagrammatic (if no such pair is found, well, they are all anagrams). Or you could use #partition to divide the list of pairs into two lists: Those that are anagrammatic, and those that are not.

In any case, I'd recommend against printing anything in a method, unless it's stated purpose is indeed to print stuff. Much better to have more methods and combine their functionality, than have a few methods do many things.

Speaking of methods, the current name of your method, anagrams, doesn't quite say what it does. Does it return some random anagrams? Does it produce them based on input? Does it verify them? Typically, when a method just returns a boolean value, its name is suffixed with a ? in Ruby. Makes it nice and obvious that you can expect a yes/no answer.
I've tried for a slightly more descriptive name above with the all_anagrams? name (it isn't perfect either, though).

Oh, and yes, the duplication of x += 1 is problematic. You can just move it to appear after the if..else. It's doubly wise to do so here, since you'll have an infinite loop if x doesn't get incremented as expected. So it's better to at least have the increment happen in only 1 place, than to hope it happens in several, branching code paths.


The official way to support a system where you control multiple Future instances from an ExecutorService is similar to what @ferada has suggested, you use a 'decorator pattern' to wrap the task, and track the results. But, the Java library has this system built in to the ExecutorCompletionService. Using that service you are able to feed tasks to the service, and wait for tasks to complete.

Your code as it is looks functional, and you successfully wait for all tasks to complete. The problem is that you are not waiting for them in the right order (you are waiting in submit-order, not completion-order).

Since the CompletionService returns a Future on submit, and the exact same one on completion, you can use that as a key to a timing Map... using an IdentityHashMap on the Future would be appropriate because it removes any dependency on the actual implementation of Future.

Note that you can use an 'enhanced-for' loop to get the Caller instances from the list.

Consider the following code:

ExecutorService es = Executors.newCachedThreadPool();
ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<>(es);
Map<Future,Long> times = new IdentityHashMap<>();
Map<Future,Caller> jobs = new IdentityHashMap<>();

for (Caller caller : callerList) {
    Future<Boolean> f = ecs.submit(caller);
    times.put(f, System.currentTimeMillis());
    jobs.put(f, caller);
}

while (!times.isEmpty()) {
    Future<Boolean> future = ecs.take();
    // note, remove the future from the map.
    long time = System.currentTimeMillis() - times.remove(future);
    System.out.println(jobs.get(future) + " result is "
         + future.get() + " in " + time + "ms");
}

One important note here, is that I would not actually print the output of the result in the loop, but just record the details. The println is probably slow, and that would make the timing results biased. I would accumulate the completion data in a different way, and print it all after all tasks are done, or, alternatively, in a different thread.


Counting the number of bits of a positive integer #2

Your code is neat, variables are well named, the input validation is there, etc. It's all good. The assessment of your time complexity being \$O(\log_2{n})\$ is also right.

But, is that as good as it can be? Well, your time-complexity assessment is a hint as to what's a better solution... The base-2 log is also an indication of the number of bits used. Remember, in base 2, the number of bits needed increases at the exponential of 2 as well.

As a consequence, your function could be reduced to \$O(1)\$ with:

import math

def count_bitx(num):
    assert num >= 0
    if num == 0:
        return 0
    return 1 + int(math.log(num, 2))

Note that Python 3.1 introduced the bit_length() method, so you could do:

def count_bits(num):
    assert num >= 0
    return num.bit_length()


Variable Naming

It took me a while to figure out what are p1, p2 and n (and you don't mention them in your example).

String operation

You could use math operation to do the computation:

function KeyGen(base, modulo, exponent) {
  var result = 1;
  while(exponent > 0){
    if(exponent % 2 == 1){
        result = (result * base) % modulo;
    }
    base = (base * base) % modulo;
    exponent = exponent >>> 1;
  }
  return result;
}

The memory footprint is then very small (no array required).

Big numbers

Issues appear when you try to use big integers (more than 54 bits - like in your comment).
To handle them correctly, I would recommand an external library like BigInt:

var bigInt=function(e){"use strict";function o(e,t){this.value=e,this.sign=t,this.isSmall=!1}function u(e){this.value=e,this.sign=e<0,this.isSmall=!0}function a(e){return-r<e&&e<r}function f(e){return e<1e7?[e]:e<1e14?[e%1e7,Math.floor(e/1e7)]:[e%1e7,Math.floor(e/1e7)%1e7,Math.floor(e/1e14)]}function l(e){c(e);var n=e.length;if(n<4&&O(e,i)<0)switch(n){case 0:return 0;case 1:return e[0];case 2:return e[0]+e[1]*t;default:return e[0]+(e[1]+e[2]*t)*t}return e}function c(e){var t=e.length;while(e[--t]===0);e.length=t+1}function h(e){var t=new Array(e),n=-1;while(++n<e)t[n]=0;return t}function p(e){return e>0?Math.floor(e):Math.ceil(e)}function d(e,n){var r=e.length,i=n.length,s=new Array(r),o=0,u=t,a,f;for(f=0;f=u?1:0,s[f]=a-o*u;while(f<r)a=e[f]+o,o=a===u?1:0,s[f++]=a-o*u;return o>0&&s.push(o),s}function v(e,t){return e.length>=t.length?d(e,t):d(t,e)}function m(e,n){var r=e.length,i=new Array(r),s=t,o,u;for(u=0;u<r;u++)o=e[u]-s+n,n=Math.floor(o/s),i[u]=o-n*s,n+=1;while(n>0)i[u++]=n%s,n=Math.floor(n/s);return i}function g(e,n){var r=e.length,i=n.length,s=new Array(r),o=0,u=t,a,f;for(a=0;a<i;a++)f=e[a]-o-n[a],f<0?(f+=u,o=1):o=0,s[a]=f;for(a=i;a<r;a++){f=e[a]-o;if(!(f<0)){s[a++]=f;break}f+=u,s[a]=f}for(;a<r;a++)s[a]=e[a];return c(s),s}function y(e,t,n){var r,i;return O(e,t)>=0?r=g(e,t):(r=g(t,e),n=!n),r=l(r),typeof r=="number"?(n&&(r=-r),new u(r)):new o(r,n)}function b(e,n,r){var i=e.length,s=new Array(i),a=-n,f=t,c,h;for(c=0;c<i;c++)h=e[c]+a,a=Math.floor(h/f),h%=f,s[c]=h<0?h+f:h;return s=l(s),typeof s=="number"?(r&&(s=-s),new u(s)):new o(s,r)}function w(e,n){var r=e.length,i=n.length,s=r+i,o=h(s),u=t,a,f,l,p,d;for(l=0;l<r;++l){p=e[l];for(var v=0;v<i;++v)d=n[v],a=p*d+o[l+v],f=Math.floor(a/u),o[l+v]=a-f*u,o[l+v+1]+=f}return c(o),o}function E(e,n){var r=e.length,i=new Array(r),s=t,o=0,u,a;for(a=0;a<r;a++)u=e[a]*n+o,o=Math.floor(u/s),i[a]=u-o*s;while(o>0)i[a++]=o%s,o=Math.floor(o/s);return i}function S(e,t){var n=[];while(t-->0)n.push(0);return n.concat(e)}function x(e,t){var n=Math.max(e.length,t.length);if(n<=400)return w(e,t);n=Math.ceil(n/2);var r=e.slice(n),i=e.slice(0,n),s=t.slice(n),o=t.slice(0,n),u=x(i,o),a=x(r,s),f=x(v(i,r),v(o,s));return v(v(u,S(g(g(f,u),a),n)),S(a,2*n))}function T(e,n,r){return e<t?new o(E(n,e),r):new o(w(n,f(e)),r)}function N(e){var n=e.length,r=h(n+n),i=t,s,o,u,a,f;for(u=0;u<n;u++){a=e[u];for(var l=0;l<n;l++)f=e[l],s=a*f+r[u+l],o=Math.floor(s/i),r[u+l]=s-o*i,r[u+l+1]+=o}return c(r),r}function C(e,n){var r=e.length,i=n.length,s=t,o=h(n.length),u=n[i-1],a=Math.ceil(s/(2*u)),f=E(e,a),c=E(n,a),p,d,v,m,g,y,b;f.length<=r&&f.push(0),c.push(0),u=c[i-1];for(d=r-i;d>=0;d--){p=s-1,f[d+i]!==u&&(p=Math.floor((f[d+i]*s+f[d+i-1])/u)),v=0,m=0,y=c.length;for(g=0;g<y;g++)v+=p*c[g],b=Math.floor(v/s),m+=f[d+g]-(v-b*s),v=b,m<0?(f[d+g]=m+s,m=-1):(f[d+g]=m,m=0);while(m!==0){p-=1,v=0;for(g=0;g<y;g++)v+=f[d+g]-s+c[g],v<0?(f[d+g]=v+s,v=0):(f[d+g]=v,v=1);m+=v}o[d]=p}return f=L(f,a)[0],[l(o),l(f)]}function k(e,n){var r=e.length,i=n.length,s=[],o=[],u=t,a,f,c,h,p;while(r){o.unshift(e[--r]);if(O(o,n)<0){s.push(0);continue}f=o.length,c=o[f-1]*u+o[f-2],h=n[i-1]*u+n[i-2],f>i&&(c=(c+1)*u),a=Math.ceil(c/h);do{p=E(n,a);if(O(p,o)<=0)break;a--}while(a);s.push(a),o=g(o,p)}return s.reverse(),[l(s),l(o)]}function L(e,n){var r=e.length,i=h(r),s=t,o,u,a,f;a=0;for(o=r-1;o>=0;--o)f=a*s+e[o],u=p(f/n),a=f-u*n,i[o]=u|0;return[i,a|0]}function A(e,n){var r,i=Q(n),s=e.value,a=i.value,c;if(a===0)throw new Error("Cannot divide by zero");if(e.isSmall)return i.isSmall?[new u(p(s/a)),new u(s%a)]:[G[0],e];if(i.isSmall){if(a===1)return[e,G[0]];if(a==-1)return[e.negate(),G[0]];var h=Math.abs(a);if(h<t){r=L(s,h),c=l(r[0]);var d=r[1];return e.sign&&(d=-d),typeof c=="number"?(e.sign!==i.sign&&(c=-c),[new u(c),new u(d)]):[new o(c,e.sign!==i.sign),new u(d)]}a=f(h)}var v=O(s,a);if(v===-1)return[G[0],e];if(v===0)return[G[e.sign===i.sign?1:-1],G[0]];s.length+a.length<=200?r=C(s,a):r=k(s,a),c=r[0];var m=e.sign!==i.sign,g=r[1],y=e.sign;return typeof c=="number"?(m&&(c=-c),c=new u(c)):c=new o(c,m),typeof g=="number"?(y&&(g=-g),g=new u(g)):g=new o(g,y),[c,g]}function O(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var n=e.length-1;n>=0;n--)if(e[n]!==t[n])return e[n]>t[n]?1:-1;return 0}function M(e){var t=e.abs();if(t.isUnit())return!1;if(t.equals(2)||t.equals(3)||t.equals(5))return!0;if(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))return!1;if(t.lesser(25))return!0}function H(e){return(typeof e=="number"||typeof e=="string")&&+Math.abs(e)<=t||e instanceof o&&e.value.length<=1}function B(e,t,n){t=Q(t);var r=e.isNegative(),i=t.isNegative(),s=r?e.not():e,o=i?t.not():t,u=[],a=[],f=!1,l=!1;while(!f||!l)s.isZero()?(f=!0,u.push(r?1:0)):r?u.push(s.isEven()?1:0):u.push(s.isEven()?0:1),o.isZero()?(l=!0,a.push(i?1:0)):i?a.push(o.isEven()?1:0):a.push(o.isEven()?0:1),s=s.over(2),o=o.over(2);var c=[];for(var h=0;h<u.length;h++)c.push(n(u[h],a[h]));var p=bigInt(c.pop()).negate().times(bigInt(2).pow(c.length));while(c.length)p=p.add(bigInt(c.pop()).times(bigInt(2).pow(c.length)));return p}function I(e){var n=e.value,r=typeof n=="number"?n|j:n[0]+n[1]*t|F;return r&-r}function q(e,t){return e=Q(e),t=Q(t),e.greater(t)?e:t}function R(e,t){return e=Q(e),t=Q(t),e.lesser(t)?e:t}function U(e,t){e=Q(e).abs(),t=Q(t).abs();if(e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;var n=G[1],r,i;while(e.isEven()&&t.isEven())r=Math.min(I(e),I(t)),e=e.divide(r),t=t.divide(r),n=n.multiply(r);while(e.isEven())e=e.divide(I(e));do{while(t.isEven())t=t.divide(I(t));e.greater(t)&&(i=t,t=e,e=i),t=t.subtract(e)}while(!t.isZero());return n.isUnit()?e:e.multiply(n)}function z(e,t){return e=Q(e).abs(),t=Q(t).abs(),e.divide(U(e,t)).multiply(t)}function W(e,n){e=Q(e),n=Q(n);var r=R(e,n),i=q(e,n),s=i.subtract(r);if(s.isSmall)return r.add(Math.round(Math.random()*s));var a=s.value.length-1,f=[],c=!0;for(var h=a;h>=0;h--){var d=c?s.value[h]:t,v=p(Math.random()*d);f.unshift(v),v<d&&(c=!1)}return f=l(f),r.add(typeof f=="number"?new u(f):new o(f,!1))}function V(e){var t=e.value;return typeof t=="number"&&(t=[t]),t.length===1&&t[0]<=36?"0123456789abcdefghijklmnopqrstuvwxyz".charAt(t[0]):"<"+t+">"}function $(e,t){t=bigInt(t);if(t.isZero()){if(e.isZero())return"0";throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1))return e.isZero()?"0":e.isNegative()?(new Array(1-e)).join("10"):"1"+(new Array(+e)).join("01");var n="";e.isNegative()&&t.isPositive()&&(n="-",e=e.abs());if(t.equals(1))return e.isZero()?"0":n+(new Array(+e+1)).join(1);var r=[],i=e,s;while(i.isNegative()||i.compareAbs(t)>=0){s=i.divmod(t),i=s.quotient;var o=s.remainder;o.isNegative()&&(o=t.minus(o).abs(),i=i.next()),r.push(V(o))}return r.push(V(i)),n+r.reverse().join("")}function J(e){if(a(+e)){var t=+e;if(t===p(t))return new u(t);throw"Invalid integer: "+e}var r=e[0]==="-";r&&(e=e.slice(1));var i=e.split(/e/i);if(i.length>2)throw new Error("Invalid integer: "+f.join("e"));if(i.length===2){var s=i[1];s[0]==="+"&&(s=s.slice(1)),s=+s;if(s!==p(s)||!a(s))throw new Error("Invalid integer: "+s+" is not a valid exponent.");var f=i[0],l=f.indexOf(".");l>=0&&(s-=f.length-l,f=f.slice(0,l)+f.slice(l+1));if(s<0)throw new Error("Cannot include negative exponent part for integers");f+=(new Array(s+1)).join("0"),e=f}var h=/^([0-9][0-9]*)$/.test(e);if(!h)throw new Error("Invalid integer: "+e);var d=[],v=e.length,m=n,g=v-m;while(v>0)d.push(+e.slice(g,v)),g-=m,g<0&&(g=0),v-=m;return c(d),new o(d,r)}function K(e){return a(e)?new u(e):J(e.toString())}function Q(e){return typeof e=="number"?K(e):typeof e=="string"?J(e):e}var t=1e7,n=7,r=9007199254740992,i=f(r),s=Math.log(r);o.prototype.add=function(e){var t,n=Q(e);if(this.sign!==n.sign)return this.subtract(n.negate());var r=this.value,i=n.value;return n.isSmall?new o(m(r,Math.abs(i)),this.sign):new o(v(r,i),this.sign)},o.prototype.plus=o.prototype.add,u.prototype.add=function(e){var t=Q(e),n=this.value;if(n<0!==t.sign)return this.subtract(t.negate());var r=t.value;if(t.isSmall){if(a(n+r))return new u(n+r);r=f(Math.abs(r))}return new o(m(r,Math.abs(n)),n<0)},u.prototype.plus=u.prototype.add,o.prototype.subtract=function(e){var t=Q(e);if(this.sign!==t.sign)return this.add(t.negate());var n=this.value,r=t.value;return t.isSmall?b(n,Math.abs(r),this.sign):y(n,r,this.sign)},o.prototype.minus=o.prototype.subtract,u.prototype.subtract=function(e){var t=Q(e),n=this.value;if(n<0!==t.sign)return this.add(t.negate());var r=t.value;return t.isSmall?new u(n-r):b(r,Math.abs(n),n>=0)},u.prototype.minus=u.prototype.subtract,o.prototype.negate=function(){return new o(this.value,!this.sign)},u.prototype.negate=function(){var e=this.sign,t=new u(-this.value);return t.sign=!e,t},o.prototype.abs=function(){return new o(this.value,!1)},u.prototype.abs=function(){return new u(Math.abs(this.value))},o.prototype.multiply=function(e){var n,r=Q(e),i=this.value,s=r.value,u=this.sign!==r.sign,a;if(r.isSmall){if(s===0)return G[0];if(s===1)return this;if(s===-1)return this.negate();a=Math.abs(s);if(a<t)return new o(E(i,a),u);s=f(a)}return i.length+s.length>4e3?new o(x(i,s),u):new o(w(i,s),u)},o.prototype.times=o.prototype.multiply,u.prototype._multiplyBySmall=function(e){return a(e.value*this.value)?new u(e.value*this.value):T(Math.abs(e.value),f(Math.abs(this.value)),this.sign!==e.sign)},o.prototype._multiplyBySmall=function(e){return e.value===0?G[0]:e.value===1?this:e.value===-1?this.negate():T(Math.abs(e.value),this.value,this.sign!==e.sign)},u.prototype.multiply=function(e){return Q(e)._multiplyBySmall(this)},u.prototype.times=u.prototype.multiply,o.prototype.square=function(){return new o(N(this.value),!1)},u.prototype.square=function(){var e=this.value*this.value;return a(e)?new u(e):new o(N(f(Math.abs(this.value))),!1)},o.prototype.divmod=function(e){var t=A(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=o.prototype.divmod,o.prototype.divide=function(e){return A(this,e)[0]},u.prototype.over=u.prototype.divide=o.prototype.over=o.prototype.divide,o.prototype.mod=function(e){return A(this,e)[1]},u.prototype.remainder=u.prototype.mod=o.prototype.remainder=o.prototype.mod,o.prototype.pow=function(e){var t=Q(e),n=this.value,r=t.value,i,s,o;if(r===0)return G[1];if(n===0)return G[0];if(n===1)return G[1];if(n===-1)return t.isEven()?G[1]:G[-1];if(t.sign)return G[0];if(!t.isSmall)throw new Error("The exponent "+t.toString()+" is too large.");if(this.isSmall&&a(i=Math.pow(n,r)))return new u(p(i));s=this,o=G[1];for(;;){r&!0&&(o=o.times(s),--r);if(r===0)break;r/=2,s=s.square()}return o},u.prototype.pow=o.prototype.pow,o.prototype.modPow=function(e,t){e=Q(e),t=Q(t);if(t.isZero())throw new Error("Cannot take modPow with modulus 0");var n=G[1],r=this.mod(t);if(r.isZero())return G[0];while(e.isPositive())e.isOdd()&&(n=n.multiply(r).mod(t)),e=e.divide(2),r=r.square().mod(t);return n},u.prototype.modPow=o.prototype.modPow,o.prototype.compareAbs=function(e){var t=Q(e),n=this.value,r=t.value;return t.isSmall?1:O(n,r)},u.prototype.compareAbs=function(e){var t=Q(e),n=Math.abs(this.value),r=t.value;return t.isSmall?(r=Math.abs(r),n===r?0:n>r?1:-1):-1},o.prototype.compare=function(e){if(e===Infinity)return-1;if(e===-Infinity)return 1;var t=Q(e),n=this.value,r=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:O(n,r)*(this.sign?-1:1)},o.prototype.compareTo=o.prototype.compare,u.prototype.compare=function(e){if(e===Infinity)return-1;if(e===-Infinity)return 1;var t=Q(e),n=this.value,r=t.value;return t.isSmall?n==r?0:n>r?1:-1:n<0!==t.sign?n<0?-1:1:n<0?1:-1},u.prototype.compareTo=u.prototype.compare,o.prototype.equals=function(e){return this.compare(e)===0},u.prototype.eq=u.prototype.equals=o.prototype.eq=o.prototype.equals,o.prototype.notEquals=function(e){return this.compare(e)!==0},u.prototype.neq=u.prototype.notEquals=o.prototype.neq=o.prototype.notEquals,o.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=o.prototype.gt=o.prototype.greater,o.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=o.prototype.lt=o.prototype.lesser,o.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=o.prototype.geq=o.prototype.greaterOrEquals,o.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=o.prototype.leq=o.prototype.lesserOrEquals,o.prototype.isEven=function(){return(this.value[0]&1)===0},u.prototype.isEven=function(){return(this.value&1)===0},o.prototype.isOdd=function(){return(this.value[0]&1)===1},u.prototype.isOdd=function(){return(this.value&1)===1},o.prototype.isPositive=function(){return!this.sign},u.prototype.isPositive=function(){return this.value>0},o.prototype.isNegative=function(){return this.sign},u.prototype.isNegative=function(){return this.value<0},o.prototype.isUnit=function(){return!1},u.prototype.isUnit=function(){return Math.abs(this.value)===1},o.prototype.isZero=function(){return!1},u.prototype.isZero=function(){return this.value===0},o.prototype.isDivisibleBy=function(e){var t=Q(e),n=t.value;return n===0?!1:n===1?!0:n===2?this.isEven():this.mod(t).equals(G[0])},u.prototype.isDivisibleBy=o.prototype.isDivisibleBy,o.prototype.isPrime=function(){var t=M(this);if(t!==e)return t;var n=this.abs(),r=n.prev(),i=[2,3,5,7,11,13,17,19],s=r,o,u,a,f;while(s.isEven())s=s.divide(2);for(a=0;a<i.length;a++){f=bigInt(i[a]).modPow(s,n);if(f.equals(G[1])||f.equals(r))continue;for(u=!0,o=s;u&&o.lesser(r);o=o.multiply(2))f=f.square().mod(n),f.equals(r)&&(u=!1);if(u)return!1}return!0},u.prototype.isPrime=o.prototype.isPrime,o.prototype.isProbablePrime=function(t){var n=M(this);if(n!==e)return n;var r=this.abs(),i=t===e?5:t;for(var s=0;s<i;s++){var o=bigInt.randBetween(2,r.minus(2));if(!o.modPow(r.prev(),r).isUnit())return!1}return!0},u.prototype.isProbablePrime=o.prototype.isProbablePrime,o.prototype.next=function(){var e=this.value;return this.sign?b(e,1,this.sign):new o(m(e,1),this.sign)},u.prototype.next=function(){var e=this.value;return e+1<r?new u(e+1):new o(i,!1)},o.prototype.prev=function(){var e=this.value;return this.sign?new o(m(e,1),!0):b(e,1,this.sign)},u.prototype.prev=function(){var e=this.value;return e-1>-r?new u(e-1):new o(i,!0)};var _=[1];while(_[_.length-1]<=t)_.push(2*_[_.length-1]);var D=_.length,P=_[D-1];o.prototype.shiftLeft=function(e){if(!H(e))return e.isNegative()?this.shiftRight(e.abs()):this.times(G[2].pow(e));e=+e;if(e<0)return this.shiftRight(-e);var t=this;while(e>=D)t=t.multiply(P),e-=D-1;return t.multiply(_[e])},u.prototype.shiftLeft=o.prototype.shiftLeft,o.prototype.shiftRight=function(e){var t;if(!H(e))return e.isNegative()?this.shiftLeft(e.abs()):(t=this.divmod(G[2].pow(e)),t.remainder.isNegative()?t.quotient.prev():t.quotient);e=+e;if(e<0)return this.shiftLeft(-e);var n=this;while(e>=D){if(n.isZero())return n;t=A(n,P),n=t[1].isNegative()?t[0].prev():t[0],e-=D-1}return t=A(n,_[e]),t[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=o.prototype.shiftRight,o.prototype.not=function(){return this.negate().prev()},u.prototype.not=o.prototype.not,o.prototype.and=function(e){return B(this,e,function(e,t){return e&t})},u.prototype.and=o.prototype.and,o.prototype.or=function(e){return B(this,e,function(e,t){return e|t})},u.prototype.or=o.prototype.or,o.prototype.xor=function(e){return B(this,e,function(e,t){return e^t})},u.prototype.xor=o.prototype.xor;var j=1<<30,F=(t&-t)*(t&-t)|j,X=function(e,t){var n=G[0],r=G[1],i=e.length;if(2<=t&&t<=36&&i<=s/Math.log(t))return new u(parseInt(e,t));t=Q(t);var o=[],a,f=e[0]==="-";for(a=f?1:0;a<e.length;a++){var l=e[a].toLowerCase(),c=l.charCodeAt(0);if(48<=c&&c<=57)o.push(Q(l));else if(97<=c&&c<=122)o.push(Q(l.charCodeAt(0)-87));else{if(l!=="<")throw new Error(l+" is not a valid character");var h=a;do a++;while(e[a]!==">");o.push(Q(e.slice(h+1,a)))}}o.reverse();for(a=0;a<o.length;a++)n=n.add(o[a].times(r)),r=r.times(t);return f?n.negate():n};o.prototype.toString=function(t){t===e&&(t=10);if(t!==10)return $(this,t);var n=this.value,r=n.length,i=String(n[--r]),s="0000000",o;while(--r>=0)o=String(n[r]),i+=s.slice(o.length)+o;var u=this.sign?"-":"";return u+i},u.prototype.toString=function(t){return t===e&&(t=10),t!=10?$(this,t):String(this.value)},o.prototype.valueOf=function(){return+this.toString()},o.prototype.toJSNumber=o.prototype.valueOf,u.prototype.valueOf=function(){return this.value},u.prototype.toJSNumber=u.prototype.valueOf;var G=function(e,t){return typeof e=="undefined"?G[0]:typeof t!="undefined"?+t===10?Q(e):X(e,t):Q(e)};for(var Y=0;Y<1e3;Y++)G[Y]=new u(Y),Y>0&&(G[-Y]=new u(-Y));return G.one=G[1],G.zero=G[0],G.minusOne=G[-1],G.max=q,G.min=R,G.gcd=U,G.lcm=z,G.isInstance=function(e){return e instanceof o||e instanceof u},G.randBetween=W,G}();typeof module!="undefined"&&module.hasOwnProperty("exports")&&(module.exports=bigInt);

function compute(){
  var base = bigInt(document.getElementById('base').value);
  var exponent = bigInt(document.getElementById('exponent').value);
  var modulo = bigInt(document.getElementById('modulo').value);

  var res = base.modPow(exponent, modulo);
  document.getElementById('result').value = res;
}
Base:<input id="base" value="3">

Exponent:<input id="exponent" value="23984081230374123749712934791249172394719237497219347129374498">

Modulo:<input id="modulo" value="112457129983317064494133258034491756790943511028023366901014968560410379195027">

<input type="button" value="Compute" onclick="compute()">

Result: <input id="result">

The result seems to be exact.

PS: The modPow implementation is actually quite readable.


Is this a correct implementation/interpretation of the "Birthday Problem"?

Nitpicks

$chars = '1234567890qwertyuiopasdfghjklzxcvbnm';

I would find this easier to read if it were in alphabetical order.

$chars = '1234567890abcdefghijklmnopqrstuvwxyz';

That way I can see that are no letters missing.

$alphanumeric_alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';

I think that makes it clearer what the string is.  Also, I prefer to name scalars (numbers, strings, etc.) with singular names.  I'd name $combinations $combination_count for the latter reason.

$probability = 1.0;

This is the probability that you can select the first combination without a collision.

foreach(range(1,$count) as $i) {

This is neat, but PHP doesn't handle it well.  It will create the whole array and then iterate over the array.

for ( $i = 1; $i <= $count; $i++ ) {

This is more efficient in PHP.

Mathematics

However,

for ( $i = 1; $i < $count; $i++ ) {

is probably more correct.  Remember that the probability of finding a combination without a collision is 1.0.  So the first iteration through the loop is the 2nd, and the $count iteration is the $count + 1 combination.

Now, if instead of the birthday problem, you are looking for the chance of a match to an already existing combination, then this would be closer.  However, that problem would normally not care about collisions in the match tries.  So it seems you should either change the upper limit in the for loop or swap out the loop for

$probability = pow(1 - 1/$combinations, $count);

That's the chance of not matching a preexisting selection with $count tries.  Note that in that case, the tries can match each other.  If you want the probability of a collision:

$probability = 1 - pow(1 - 1/$combinations, $count);

More Nitpicks

Assuming the birthday problem is the right model,

    $probability = $probability * (1 - ($i/$combinations));

You could write this as

    $probability *= 1 - ($i/$combinations);

Which seems simpler.  Note that the parentheses around the division are unnecessary as division is higher precedence than subtraction.  Not normally a big deal either way.  They do slow down the loop slightly though, so if you have performance issues, you could try removing them.  With high enough iterations, it could shave off noticeable time.

echo "A total probability their being collisions of ".($probability*100). "%\n";

You misspelled "there":

echo "Total probability there being collisions of ".($probability*100). "%\n";


Repurposing UITableView infinite scroll configuration/properties

I do not see a huge problem with the structure of this code.  It is not a huge number of lines repeated, and the contents of the if structures are obviously different as far as which variables they act upon.  That being said, I do believe that it can be made more clear and concise by using objects to contain some of the data.

Without seeing the whole context of the code, it looks to me like self.checkinsTableView and self.watchlistTableView are basically the same.  If their contents can be converted into a class (possibly a subclass of the Apple class, possibly not, sometimes this can be tricky) then you would be able to more easily break things down into smaller methods.

You would make the following things properties of the class:

@property(nonatomic) int page;
@property(nonatomic) int total;
@property(nonatomic) int total_pages;
@property(nonatomic) BOOL load_more;

Then you would change the if statements to look like this:

if(distanceFromBottom < height)
{
    if(scrollView == self.checkinsTableView){
        [self processThing:checkinsClass]
    }
    if(scrollView == self.watchlistTableView){
        [self processThing:watchListclass];
    }
}

-(void) processThing:(YourClass *)object {
    object.load_more = NO;
    if(class.page < object.total_pages){
        object.page++;
        [self downloadList:object];
    }
}

This class could possibly be integrated into the self.watchListTableView class itself to shorten the code even further.  I haven't subclassed TableView (I'm assuming that's what this is based on the name) so I don't know if it is easy/possible or not.

It might make sense to move these checks into another method for simplicity, but it is hard to say based on the context:

if(scrollView == self.checkinsTableView && !self.checkins_load_more){
    return;
}
if(scrollView == self.watchlistTableView && !self.watchlist_load_more){
    return;
}

I tried to write an example method for this, but I think it would only work easily if you subclassed the TableView, and even if you did you would have to pass in the scrollView also to perform the check, so the way that you have it might be better.

Finally I would like to talk about a couple formatting issues.  Variables in Objective-C should be camelCase, so watchlist_load_more should be watchlistLoadMore.

Also I recommend more white space in a few areas.  @property(nonatomic) BOOL watchlist_load_more; would look better with a space after property.  Your if statements are a bit crowded. if(scrollView == self.checkinsTableView){ would read easier as if (scrollView == self.checkinsTableView) {.

Finally, I would choose one format for {} brackets and stick with it.  I believe that it is fine to have the bracket either on the same line, or on the next line, but you alternate between these two options in the code.  I would recommend that you pick one and be consistent with it. These are minor nitpicks, but I think they would help readability.


I'm not a DBA/DBMS guru, so just some ideas:

Turn off indexes on tData2 during the migration.
Do it in smaller chunks for smaller transaction log. (Batch commit on large INSERT operation in native SQL?, How to implement LIMIT with Microsoft SQL Server?)
Make sure that [tData].[Key] has an index.
I'd consider replacing the subselect with a join if it's possible at all.


public static SensorCrcValue? TryParseCrcValue(string sensorFileLine)

A common design pattern for Try[Action] methods is to return a boolean value to indicate if the action were successful or not and let the result be passed back to the caller through a by reference argument.
public static bool TryParseCrcValue(string sensorFileLine, out SensorCrcValue result)

SensorCrcValue sensorCrcValue;

sensorCrcValue.CrcValue = Convert.ToByte(crcValueField);
sensorCrcValue.IsCrcValid = false;

if (crcValidField.Equals("YES"))
{
    sensorCrcValue.IsCrcValid = true;
}
else if (crcValueField.Equals("NO"))
{
    sensorCrcValue.IsCrcValid = false;
}

return sensorCrcValue;

The last part of your code can be shortened since IsCrcValid is not a nullable boolean.
return new SensorCrcValue
{
    CrcValue = Convert.ToByte(crcValueField),
    IsCrcValid = crcValidField.Equals("YES")
};


Don't dynamically allocate objects if you don't need to.

bool *rowZeros = new bool[M];
bool *colZeros = new bool[N];

If you do it this way you need to take control and do manual memory management (a bad idea).

Most specifically your code is not exception safe. If your code or anything you called throws an exception you leak memory (OK so this function is simplistic enough that it is unlikely but code has a tendency to evolve over time and you want to write code that is easy to maintain so writing it exception safe to begin with is a general goal).

Also C++ has a tendency to have early return backed into the code. This is because of automatic memory management that has been developed over the years. If somebody modifies your code to have an early return (say because they found no zero's on the first pass). Then your code is now likely to leak. So designing your code again t to use automatic memory management just makes your code more maintainable.

I would use a vector here:

std::vector<char> rowZeros(M, true);
std::vector<char> colZeros(N, true);

This allocates memory. But when the function exits all memory is correctly deallocated (even after early return or exception). Use standard container like automatic variables whenever you can.

Notice I did not use std::vector<bool>. Normally I would use the same type in the vector that I would have used in the array. But there is special consideration taken for std::vector<bool> that make it less efficient (everybody has concluded this was a mistake by the committee but it is not going to be fixed for backwards compatibility (at least not any time soon)).

Also note your original code contains a bug:

bool *rowZeros = new bool[M];  // This allocates the array but does not initialize.

Because the array is not initialized reading the elements is undefined behavior (until after they have been initialized). You could have initialized them to zero(false) with:

bool *rowZeros = new bool[M]();
                       //   ^^  forces zero initialization of all members.

But the vector constructor has a more obvious way of doing it.

std::vector<char> rowZeros(M, true);
                    //     ^               Size
                    //        ^^^^         Value copied into each cell of the vector.


Merging trips to the same location with overlapping dates

Let's look at this line:

(p.StartDate <= startDateUnix && (endDateUnix >= p.StartDate && endDateUnix <= p.EndDate))

If p.StartDate <= startDateUnix then p.StartDate <= endDateUnix, since startDateUnix <= endDateUnix. So endDateUnix >= p.StartDate is redundant.

So the first part of the query can be written as

(p.StartDate >= startDateUnix && p.StartDate <= endDateUnix) ||
(p.EndDate >= startDateUnix && p.EndDate <= endDateUnix) ||
(p.StartDate <= startDateUnix && endDateUnix <= p.EndDate)

I would recommend rewriting the first two conditions as follows:

(startDateUnix <= p.StartDate && p.StartDate <= endDateUnix) ||
(startDateUnix <= p.EndDate && p.EndDate <= endDateUnix)

I find it easier to see at a glance that it's saying that p.StartDate lies within [startDateUnix, endDateUnix] (similarly for p.EndDate).

Another way to test for overlapping intervals is

p.StartDate <= endDateUnix && startDateUnix <= p.EndDate


Division without using division, multiplication, or modulus operators

Is bitwise operation mandatory? There's a much simpler way

const divide = (dividend, divisor) => {
     let quotient = 0, neg = false;

     if( (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ){ neg = true; }

     dividend = Math.abs(dividend);
     divisor = Math.abs(divisor);

     if(dividend < divisor) {return 0;}
     else if(dividend > 0 && divisor != 0){
          while(dividend >= divisor){
               dividend -= divisor;
               ++quotient;
          }
     } else { // handle what you want to do for those cases..}

     return neg ? -quotient : quotient;
}

You get your quotient and remainder is ignored. Just do a check if dividend is negative or divisor is 0.


Prepared statements from security viewpoint

This looks pretty good.  I'm glad to see the improvement.

You inexplicably call $connect->bind_params() using variables that have not yet been set.

The main issue I see now is $QuizAdministrationid = $maxId + 1,  which is prone to a race condition.  If two users submit the form simultaneously, it's possible that both pages could see the same result from SELECT MAX(id) … and generate the same next $QuizAdministrationid.

The solution is to ask the database to generate the next ID.  Every SQL database supports this in a slightly different way.  For MySQL, you should declare the id column of QuizAdministration to be AUTO_INCREMENT.  Then, leave id column unspecified when you do the INSERT.  MySQL will automatically fill in the id column with the next available number.  To find out what number MySQL picked for you, use $connect->insert_id.

To make this work for you, you'll need to insert a row into QuizAdministration first, then use the id of the new row to insert the PlayerAnswers.

$stmt2 = $connect->prepare("INSERT INTO QuizAdministration (`quizNumber`, `cookie`, `ip`, `score`) VALUES (?, ?, ?, ?)");
$quizNumber = 1;
$playerCookie = session_id();
$playerIP = getUserIp();
$playersPercent = 90;
$stmt2->bind_param('issi', $quizNumber, $playerCookie, $playerIP, $playersPercent);
$stmt2->execute();
$stmt2->close();

$quizAdministrationid = $connect->insert_id;

$stmt3 = $connect->prepare("INSERT INTO PlayerAnswers (`QuizAdministrationId`, `questionNumber`, `playerAnswer`) VALUES (?, ?, ?)");
for ($yty = 1; $yty <= 20; $yty += 1) {
    $questnum = $yty;
    $questansw = $_POST['qora'.$yty];
    $stmt3->bind_param('iii', $QuizAdministrationid, $questnum, $questansw);
    $stmt3->execute();
}
$stmt3->close();


You can consider implementing the Deque interface so that you can potentially open up its usage as an implementation of the Collections classes.

Your field size seems to be underused here, as I can sort of see a size() method using it too... BTW, regardless whether you use the Deque interface, your method empty() should be written as isEmpty(), to follow Java methods' naming convention as 'is...' for boolean return values.

Back to talking about Collections classes, they throw NoSuchElementException when no element can be returned, e.g. when empty, so perhaps you can throw that too instead of EmptyStackException.

Since you are relying on your TreeMap inner implementation, you can consider having your field declaration as TreeMap too instead of Map, this being one of those cases where using the implementation (class) rather than the interface makes more sense. With a TreeMap, you can replace map.entrySet().iterator().next().getValue() with the neater method map.firstEntry().

In your push() method, if you are on Java 8, you can consider computeIfAbsent():

public void push(E element, P priority) {
    map.computeIfAbsent(priority, ArrayList::new).add(element);
    size++;
}

Last but not least, you should have better unit testing too... Your current case looks OK already, so it's just a matter of comparing the output when you pop() to something you can compare with, such as a List. Remember to test for edge cases, such as getting from an empty instance, or adding null elements (which should be allowed given your ArrayList implementation).


Bank saving account class in Python (pandas)

I think your design is a bit "overkill". After all, banks don't keep empty records for each day of the year, waiting for you to come along and perform a transaction.
Rather than using a DataFrame, I think you'd be better off separating the data record into a class of its own, with the increment and decrement functions.

The display functionality is not part of the data record, it would be a separate class itself, and inheritable by ATMs or a Teller/Bank Manager/technician's computer. Regardless, this is something for kids, so it's fine to violate some SOLID principals.

Regarding def __init__(self, holder, start_date): you could probably make start_date = date.today() as transactions tend to happen on the same day, unless you're performing some cheque activity (which is delayed).

As to your question, if you change the date from the index into its own column, you're shifting the column[:loc] as the lookup, essentially adding an extra step.
For using integer indices to lookup data, it's a bad idea as you should try to keep any [lookup_integer] values as defined constants - so they're not arbitrary numbers (you'd be surprised how often people make simple input mistakes when coding, and as they're usually valid integers, people are scratching their heads why a date is in the address of a decimal number (addition and subtraction would then still be valid operations, so it's not picked up immediately unless you're performing tests on data as part of your CI process, and you go live with faulty code).

Good luck!


Translating array pointer access from C++ to Delphi

Everything there looks right (except for the = on the last line, which should be :=). It's about as close to a literal translation as you can get.

Converting the Delphi code to use dynamic arrays could ease your mind regarding out-of-bounds access, although the initial setup would be more cumbersome. (That might not be a problem if you're ultimately planning on loading the data from a file instead of from constants.) It would look something like this:

program Project1;

{$APPTYPE CONSOLE}

type
    tile_map = array of array of uint32;

function GetTileValueUnchecked(const TileMap: tile_map; TileX, TileY: int32): uint32; inline;
begin
    result := TileMap[TileY][TileX];
end;

const //in the future these will be read from file, so const for now
    Tiles00:  array [0..8, 0..16] of uint32 =
    (
        (1, 1, 1, 1,  1, 1, 1, 1,  0, 1, 1, 1,  1, 1, 1, 1, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0, 1),
        (1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1, 1)
    );
    // More tile map declarations ...
    //Tiles01:  array [0..8, 0..16] of uint32 = ...
    //Tiles10:  array [0..8, 0..16] of uint32 = ...
    //Tiles11:  array [0..8, 0..16] of uint32 = ...
var
    TileMaps : array [0..1, 0..1] of  tile_map;
    PlayerTileX, PlayerTileY : int32;
    TileMapValue : uint32;
    x, y: Integer;
begin
    SetLength(TileMaps[0][0], Length(Tiles00), Length(Tiles00[0]));
    for y := 0 to High(Tiles00) do
      for x := 0 to High(Tiles00[0]) do
        TileMaps[0][0][y][x] := Tiles00[y][x];

    SetLength(TileMaps[0][1], Length(Tiles01), Length(Tiles01[0]));
    for y := 0 to High(Tiles01) do
      for x := 0 to High(Tiles01[0]) do
        TileMaps[0][1][y][x] := Tiles01[y][x];

    SetLength(TileMaps[1][0], Length(Tiles10), Length(Tiles10[0]));
    for y := 0 to High(Tiles10) do
      for x := 0 to High(Tiles10[0]) do
        TileMaps[1][0][y][x] := Tiles10[y][x];

    SetLength(TileMaps[1][1], Length(Tiles11), Length(Tiles11[0]));
    for y := 0 to High(Tiles11) do
      for x := 0 to High(Tiles11[0]) do
        TileMaps[1][1][y][x] := Tiles11[y][x];

    // Usage
    PlayerTileX := 2;
    PlayerTileY := 2;
    TileMapValue := GetTileValueUnchecked(TileMaps[1][1], PlayerTileX, PlayerTileY);
end.

Test with that code for a little while to convince yourself that the array accesses are right. If they're not, Delphi's range checking will alert you. Once you're confident, you can disable range checking inside GetTileValueUnchecked so that it's true to its name:

function GetTileValueUnchecked(const TileMap: tile_map; TileX, TileY: int32): uint32; inline;
begin
    {$R-}
    result := TileMap[TileY][TileX];
    {$R+}
end;


I think you only want to calculate the last working day from today. Here is a better/pythonic approach:

from datetime import timedelta, date

def lastBzDay( d = None ):
  r, d = xrange( 1, 5 ), d or date.today()
  def retfn( curDay = d ):
    w = curDay.weekday()
    prevBzDay = curDay - timedelta( days= 1 if w in r else (w + 3) % 7 )
    return prevBzDay.strftime('%d%m%y')
  return retfn
lastBzDay = lastBzDay()

Now, all you have to do is:

yesterday = lastBzDay()

and you'll get the desired result. Using a closure also gives you the ability to find the last weekday from any other dates:

print lastBzDay( date(2014, 9, 7) )  # will give you 050914

You can see a demo on codepad here.


In general this codes looks pretty good.  A couple of nits.
The Python Library is Huge:
I would suggest replacing the while word: loop block:
while word:
    position = random.randrange(len(word))
    jumble += word[position] # Jumble process 1
    word = word[:position] + word[(position + 1):] #Jumble process 2

With a library call like:
jumble = ''.join(random.sample(word, k=len(word)))

Main loop:
By using a break inside the main loop, it can be restructured to remove some extra code like:
while True:
    print('\nThe Jumble is:', jumble)
    guess = input('Your Guess: ')
    if guess == word:
        print("\nThat's it! You guessed it!\n")
        print('Thanks for playing')
        break

    print("Sorry, that's not it")

This removes an extra comparison and input()
Comments:
I am not a fan of right hand style comments.  I generally prefer a needed comment to proceed the line/block it is commenting.  You used reasonably descriptive variable names, I don't know that anything other than the header comment is providing much value.


If I try to split on the empty string I get an error:

>>> 'a b c'.split('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator

Perhaps you meant .split()?

Anyway, here are some ideas for simplifying your code.

Use from collections import defaultdict to avoid the need to refer to col (I presume you have import collections as col).
Put a dummy key into the byPop aggregation so that its structure matches the others.
Put the aggregates into a dictionary instead of having a bunch of variables. That way you can manipulate them systematically in loops.
Use enumerate in your last loop to get the index as well as the value from the data list.

That leads to this:

from collections import defaultdict

def aggregate(f):
    """
    Aggregate population by several keys.
    """
    aggregates = 'pop merchant plat day affiliate country type'.split()
    result = dict()
    for a in aggregates:
        result[a] = defaultdict(lambda: defaultdict(lambda: [0,0,0,0]))

    for line in f:
        fields = line.strip().split()
        if fields[2] == '\\N': continue

        # Decode fields from this record.
        day          = fields[0]
        popid        = int(fields[1])
        affiliate_id = int(fields[2])
        merchant_id  = int(fields[3])
        clicks       = int(fields[4])
        displays     = int(fields[5])
        sales        = float(fields[6])
        gross        = float(fields[7])

        # Keys under which to aggregate the data from this record.
        keys = dict(merchant = partners_info[merchant_id][0],
                    plat = partners_info[merchant_id][1],
                    day = day,
                    affiliate = publisher_info[affiliate_id][0],
                    country = publisher_info[affiliate_id][1],
                    type = publisher_info[affiliate_id][2],
                    pop = 0)       # dummy key

        # Update all aggregates.
        for i, value in enumerate([clicks, displays, sales, gross]):
            for a in aggregates:
                result[a][keys[a]][popid][i] += value

    return (result['pop'][0],) + tuple(result[a] for a in aggregates[1:])

It's not really a vast improvement.


Refactor nested null checking for multiple possible string values

You can just go with :

// Just check both case at the same time
string propertyGuid = propertyList.Where(x => x.name == "Name" || x.name == "Code").FirstOrDefault()?.ToString();
if (string.IsNullOrEmpty(propertyGuid)) // Same check as you did but written differently
{
    throw new ArgumentNullException();
}

Then for the future, I guess that you can have Guids on node you don't want to extract. You could have properties on a list or array :

List<string> possibleName = new List<string>() {"Code", "Name"};

And then calling an extract function :

Public static string GetGuid(List<string> possibleName, Whatever propertyList)
{
    string propertyGuid = string.Empty;
    foreach (string name on possibleName)
    {
        propertyGuid = propertyList.Where(x => x.name == name).FirstOrDefault()?.ToString();
        if (!string.IsNullOrEmpty(propertyGuid))
        {
             return (propertyGuid);
        }
    }
    throw new ArgumentNullException();
}

Ps : I'd like to add that if propertyList is a NodeList you won't get what you want.


Bash: change git remote from SSH to HTTPS within a given dir

Extracting remote urls

Parsing the config file is error-prone. A much better way to extract the information about remotes is using Git commands. This will simplify your script a great deal.

Limitations

Be aware that the script as it is will not be able to convert remotes that were created using URL shorthands. For example, I have this in my global .gitconfig:

[url "git@github.com:"]
    insteadOf = "gh:"

This lets me clone a GitHub repo with git clone gh:user/repo instead of git clone git@github.com:user/repo. The config file will be written using the shorthand instead of the real URL, so your script will not be able to pick up the pattern.

You can easily solve this limitation by using Git commands to extract Git remote URLs.

String transformations

Instead of echo ... | sed ..., it's better to use here-strings:

sed ... <<< ...

But when the text transformations are simple enough, and Bash's parameter expansion can handle it, that's even better. For example, instead of this:

  user_name=$(echo "$repo_url" | sed -Ene's#git@github.com:([^/]*)/(.*).git#\1#p')

This would be better:

# chop off the beginning until the first :
user_name=${repo_url#*:}
# chop off everything after the first /
user_name=${user_name%%/*}

Exiting with error

There are multiple exit points in the validate_path function.
Without parameter, exit will use the exit code of the previous command, and if that was echo, it's likely to be success,
when in fact you probably want to exit with error instead.

Usability

Reading paths inside a script is not user-friendly,
because you cannot use tab-completion.
It would be better to let users pass paths as parameters to the script.


None of this code should deal in strings, except maybe the final output stage. It can all be thrown away in favour of a single generator function that uses the highly-useful dateutil library. Also type hints will help:
from datetime import date
from typing import Iterable, Tuple
from dateutil.relativedelta import relativedelta

def get_dates(start: date, end: date) -> Iterable[Tuple[date, date]]:

    while True:
        next_start = start + relativedelta(months=1, day=1)
        this_end = next_start - relativedelta(days=1)

        if end <= this_end:
            yield start, end
            break

        yield start, this_end
        start = next_start

def main() -> None:
    start = date.fromisoformat(input('Enter start date: '))
    end = date.fromisoformat(input('Enter end date: '))
    for range_start, range_end in get_dates(start, end):
        print(f'{range_start.isoformat()} - {range_end.isoformat()}')

if __name__ == '__main__':
    main()

Output:
Enter start date: 2020-10-14
Enter end date: 2021-03-26
2020-10-14 - 2020-10-31
2020-11-01 - 2020-11-30
2020-12-01 - 2020-12-31
2021-01-01 - 2021-01-31
2021-02-01 - 2021-02-28
2021-03-01 - 2021-03-26


Retrieve notifications and share across browser tabs

I would try to also add a complete callback function to set running to false. It handles ( ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror")) Those should be handled by error and success but something is going on, so give it a shot?

Other than, your code is quite solid, I ran JSHint over it, and it got very few hits.

You never actually use notbox
You probably want to declare oldids before that if loop

Other than that

The naming is definitely a mixed bag, I would stick everywhere with lowerCamelCase ( lastping -> lastPing, notif_body -> notificationsBody ( or consider notificationsElementor perhaps just notifications )
You are using one liner ifs without curly braces.

Final thought, are you at any point rebuilding the DOM? If you rebuild the DOM (specifically any of the elements captured by notif_ico and notif_body), then your code stops working.


Making a web service call based on a type of request

It would be better to give the Irequest interface an additional "Name" property that returns the value of requestType. Than you can iterate over all Irequest implementations and get the first with the corresponding name ;).

Example:

interface IRequest
{
    void CallService();
    string Name { get; }
}
class EnrolmentRequest : IRequest
{
    public void CallService() { /* impl. */ }
    public string Name => "Enrol";

}
class ReEnrolmentRequest : IRequest
{
    public void CallService() { /* impl. */ }
    public string Name => "ReEnrol";
}

...

public class Client
{
    private static IRequest[] requestHandlers = new IRequest[]
    {
        new EnrolmentRequest(),
        new ReEnrolmentRequest(),
        ...
    }

    public Client(string requestType)
    {
        IRequest request = requestHandlers.SingleOrDefault(x => x.Name == requestType);
        if (request == null) { /* Handle null case */ }

        request.CallService();
    }
}

That code fulfills the open/closed principle because you can add new request handlers without modified existing logic.


C# Code Optimization -- Finding nearest key in a SortedList

Your loop is pretty well written. The only thing that sticks out to me is your use of a constant in the while loop and manually breaking.  I also prefer to use a slightly different version of CompareTo, but it doesn't make much difference:

while ( (lower<=upper))
{
    int comparisonResult = thisValue.CompareTo( thisList.Keys [index]);
    if (comparisonResult == 0) { return thisList.Values[index]; }

    if (comparisonResult < 0)
    {
        upper = index - 1;
    }
    else
    {
        lower = index + 1;
    }
    index = (lower + upper) / 2;
}

You might also be looking for a solution that's just easier to read or shorter. Are you familiar with LINQ? This is one possibility for how your function might look.

    private static string GetTraitRefactor (SortedList<decimal, string> thisList, decimal thisValue)
    {
        var keys = thisList.Keys;
        var nearest = thisValue -
            keys.Where(k => k <= thisValue)
            .Min(k => thisValue - k);
        return thisList[nearest];
    }


You're already using a regex to check that the phone number is 10 digits, but you could also make it more precise, and use it to split the string apart:

def obtain_phone_number
  loop do
    print "Enter phone number: "
    phone_num = gets.chomp
    if phone_num =~ /^(\d{3})(\d{3})(\d{4})$/
      return "(#{$1})#{$2}-#{$3}"
    else
      puts "Invalid phone number, must contain 10 digits only"
    end
  end
end

When the =~ matching runs, it assigns the capture groups to the global $1, $2 etc. variables, so it's easy to glue a string back together from those parts. You can fiddle with it to make it accept more than 10 digits, if you want.

However, I would move the loop somewhere else, and just have the method return a formatted string or nil. Or possibly string, nil or raise an exception. If you get nil back, the user entered nothing (e.g. user cancelled/left it blank). If it raises an error, the user did input something, but it was invalid, and you can warn and retry.

Right now, if you call the method, you can never escape it without entering a number. I don't know the usage context for this, but I'd imagine it'd make sense to allow the user to skip somehow, rather than forcing them to input nonsense just to proceed.

So something like this might be better:

def obtain_phone_number
  phone_num = gets.chomp
  return nil if phone_num.empty?
  if phone_num =~ /^(\d{3})(\d{3})(\d{4})$/
    "(#{$1})#{$2}-#{$3}"
  else
    raise "Invalid input"
  end
end

# simple usage example
begin
  print "Enter phone number: "
  phone = obtain_phone_number
  puts phone
rescue StandardError
  puts "Invalid phone number, must contain 10 digits only"
  retry
end


The semicolons after the closing braces are really unnecessary, and the indentation is a bit off here:

        if (yDegrees < maxRotation) {
            yDegrees = maxRotation;
        };
        if (yDegrees > 0) {
            yDegrees = 0;
            };

It would be better this way:

        if (yDegrees < maxRotation) {
            yDegrees = maxRotation;
        }
        if (yDegrees > 0) {
            yDegrees = 0;
        }

This could be written more compactly:

yDegrees = yDegrees + (((originX - event.pageX) / slidingLength) * maxRotation);

Like this:

yDegrees += (originX - event.pageX) / slidingLength * maxRotation;

That is, using += and removing unnecessary parentheses.


Overview

I can see that you are a beginner and that is totally fine! Some of the points I will be making might, sound a bit harsh and go over your head. If they do try to improve the parts of the code you do understand, and instead post a follow up question.

LMGTFY / RTFM

Asking a question on a SE, site is a great way to learn. However another is searching for answers beforehand. In fact all three questions in your bullet list could be googled / found in the manual.

Turn a list into a string Python
How do I randomly select an item from a list using Python?
When to use for and while loop

As you know CodeReview has it's own hangman tag -- since you tagged your own question with the tag. This means people have asked hangman related questions earlier, and you could have browsed these questions before posting your own. As an example, even I have asked a question about hangman. Here is another very similar question.

This is not to discredit you for asking, however drawing suggestions and inspiration from similar problems is a fantastic way to learn.

PEP 8 - Style Guide for Python Code

As to pick the lowest hanging fruits. Consistency is a key part of programming, as it greatly increases readability. It also tells a bit about the coders eye for detail. Lets' look at how you have named your global constants:

MAX
num
num_string
words
WORD_TO_GUESS
HIDDEN
LETTERS_GUESSED

Do you see the inconsistency? Pep 8 recommends the following naming-conventions:

CAPITALIZED_WITH_UNDERSCORES for constants
UpperCamelCase for class names
lowercase_separated_by_underscores for other names

General structure

A very rough sketch of how a standard python program should look like is as follows

import

global CONSTANTS
global VARIABLES

functions

classes

if __name__ == '__main__':

    main()

All of your code should be split into short simple functions, which each serve a single purpose. You should in general have as little code as possible floating around that is not part of a function. This includes minimizing the need for global variables and constants. There are some exceptions to this rule, however your code is not one of them.

Some more pointers

As earlier answers stated you can change your dictionary word list into

WORD_LIST = [
    'sergeanty',
    'amphipneustic',
    'hypochil',
    'grus',
    'depressed',
    'distortedly',
    'unselected',
    'crakow',
    'preendorsing',
    'convenient'
]

As mentioned earlier you use too many global variables. This

MAX = len(HANGMAN) - 1
num = randint(1, 10)
num_string = str(num)
words = 'rand_word_{}'.format(num_string)
WORD_TO_GUESS = WORD_LIST[words]
HIDDEN = ['_'] * len(WORD_TO_GUESS)
LETTERS_GUESSED = []

can be shortened into

MAX = len(HANGMAN) - 1
word_to_guess = random.choice(WORD_LIST)
hidden = ['_'] * len(word_to_guess)
letters_guessed = set()

Where I have used the choice function from the random module. For an example of use see below

   >>> import random
   >>> a = ["Stack", "Overflow", "rocks"]
   >>> print(random.choice(a))
   rocks

for a more detailed explanation see the second bullet point at the start.

You might also have noticed that some of the variables are not CAPITALIZED that is because they do not need to be global variables, and can be moved into the main function.

def play_hangman():
    hang_size = 0
    word_to_guess = random.choice(WORD_LIST)

    hidden = ['_'] * len(word_to_guess)
    letters_guessed = set()

Note how I also conveniently changed the name of your main() function. Naming variables, functions and classes in programming is one of the more difficult things to do. A general rule of thumb is that the names should be clear, distinct and succinct in that order. As others have pointed out main() only achieves the third, which should be the last thing to worry about.

Handling user input

Jokes aside as a rule you should never except the user to use the correct input syntax. Instead you should build in checks, exceptions to handle these errors.

For an example your code only checks once if I have tried the letter before.

if user_guess in LETTERS_GUESSED:
    print 'You already guessed that.. PAY ATTENTION!'
    user_guess = raw_input('Guess a letter dude: ')

One way to fix this is using a while loop instead

while user_guess in LETTERS_GUESSED:
    print 'You already guessed that.. PAY ATTENTION!'
    user_guess = raw_input('Guess a letter dude: ')

What happens if i decide to try the letter banana or the letter ? Your function does nothing to handle it. What If I try the more common mistake to try A then a? All of this can be fixed by putting the get_user_input into it's own function

ALPHABETH = 'abcdefghijklmnopqrstuvwxyz'

def guess_letter(letters_guessed):
    while True:
        guess = raw_input('Guess a letter dude: ').lower()
        if guess not in ALPHABETH:
            print guess, 'is like totally not in the alphabet dude, try again!'
        elif guess in letters_guessed:
            print 'You already guessed {}.. PAY ATTENTION!'.format(guess)
        else:
            return guess

Do note that I did not have to convert ALPHABETH into a list. Python can compare strings just as well as lists. Also notice how I used Python string lower() method to ensure that the user input was all lowercase.

Continuing on

The next bit of your code could then be written as

while hang_size < MAX:
    print str(hidden)
    user_guess = guess_letter(letters_guessed)
    letters_guessed.add(user_guess)
    if user_guess in word_to_guess:

Where we again used that Python can compare strings just fine. The add is used instead of append since letters_guessed is now a set and not a list. Why am I using sets, you ask?

  When you want to store some values which you'll be iterating over,
  Python's list constructs are slightly faster. However, if you'll be
  storing (unique) values in order to check for their existence, then
  sets are significantly faster.

For words as short as your the difference is negligible, however it is a good practice nevertheless.

for num in range(len(word_arr)):

This can be improved using Pythons enumerate() function that adds a counter to an iterable.

    for i, letter in enumerate(word_to_guess):
        print i, letter
        if user_guess == letter:
            hidden[i] = letter
    if hidden.count('_') == 0:
        print 'You win! Finally you did something right!'
        return

I really see no point in turning the for-loop into a zip list. Yes, it is shorter. However for a novice it is much harder to understand what is going on.

Winning condition and return

The statement

if HIDDEN.count('_') == 0:
    print 'You win! Finally you did something right!'
    quit()

Is weird. The if HIDDEN.count('_') == 0: is cryptic at best. A good practice is to check what you really want to check.. You are not interested in how many _'s are left, but rather if the user has guessed the correct word. This can be checked as follows

user_guessed_word_spaced = ' '.join(hidden)
word_to_guess_spaced = ' '.join(word_to_guess)
if user_guessed_word_spaced == word_to_guess_spaced:

At a first glance this might seem convoluted. However in the actual code word_to_guess_spaced = ' '.join(hidden) is only declared once. Secondly using a spaced string ' '.join() instead of ''.join() allows us to directly print the output at the start of the while-loop.

Your way to exit the function is very intuitive for a beginner, however it should be avoided like the plague for a beginner. A more natural way is to use return instead.

  quit raises the SystemExit exception behind the scenes.

  Furthermore, if you print it, it will give a message:

>>> print (quit)
Use quit() or Ctrl-Z plus Return to exit
>>>

  This functionality was included to help people who do not know Python.
  After all, one of the most likely things a newbie will try to exit
  Python is typing in quit.

  Nevertheless, quit should not be used in production code. This is
  because it only works if the site module is loaded. Instead, this
  function should only be used in the interpreter.

I have made some adjustments to accommodate for this. This includes having only a single return statement, as well as some better handling of printing the winning conditions.

There are more things to nitpick, which I did not try to fix/improve

You should always comment your code. You can never be sure you will understand your code 6months down the road. A common way to do this is with PEP 257 -- Docstring Conventions.
Your creation of strings could be improved.
Your list of words is short, and a simple fix is to use a larger list from the internet.
You could also make a short menu to congratulate the user, or ask if one wants to play again.

Code

Using all of these small improvements leads to the following code.

import random

WORD_LIST = [
    'sergeanty',
    'amphipneustic',
    'hypochil',
    'grus',
    'depressed',
    'distortedly',
    'unselected',
    'crakow',
    'preendorsing',
    'convenient'
]

HANGMAN = (
    """
    x-------x
    """,
    """
    x-------x
    |
    |
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |       |
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      /
    |
    """,
    """
    x-------x
    |       |
    |       0
    |      /|\\
    |      / \\
    |
    """
)

MAX = len(HANGMAN) - 1
ALPHABETH = 'abcdefghijklmnopqrstuvwxyz'

def guess_letter(letters_guessed):
    while True:
        guess = raw_input('Guess a letter dude: ').lower()
        if guess not in ALPHABETH:
            print guess, 'is like totally not in the alphabet dude, try again!'
        elif guess in letters_guessed:
            print 'You already guessed {}.. PAY ATTENTION!'.format(guess)
        else:
            return guess

def play_hangman():
    hang_size = 0
    word_to_guess = random.choice(WORD_LIST)
    word_to_guess_spaced = ' '.join(word_to_guess)

    hidden = ['_']*len(word_to_guess)

    letters_guessed = set()
    user_guessed_word_spaced = ' '.join(hidden)

    print "HANGMAN!"

    while hang_size < MAX:

        print
        print user_guessed_word_spaced

        user_guess = guess_letter(letters_guessed)
        letters_guessed.add(user_guess)

        if user_guess in word_to_guess:

            print "\nYeah yeah.. We're all impressed.. {} is in the word woohoo..".format(user_guess)

            for i, letter in enumerate(word_to_guess):
                if user_guess == letter:
                    hidden[i] = letter

            user_guessed_word_spaced = ' '.join(hidden)
            if user_guessed_word_spaced == word_to_guess_spaced:
                print
                print word_to_guess
                break

        else:
            print "{}.. Really? That's the best you can do.. Not in my word..".format(user_guess)
            hang_size += 1
            print HANGMAN[hang_size]

    return user_guessed_word_spaced == word_to_guess_spaced

if __name__ == '__main__':

    is_winner = play_hangman()
    if is_winner:
        print '\nYou win! Finally you did something right!'
    else:
        print '\nGAME OVER'


A quick review:

JSHint.com

Your code passes all checks, well done

Naming

test and test2 are unfortunate names for elements, I am sure you can come up with something better

Counter Proposal

Looking at the code, there is definitely repetition in making those sliders, you can extract what is common in to a function, and then use that function for any future sliders:

(This is blatantly stolen/modified from the deleted answer):

$(document).ready(function() {

   function registerSlider( buttonId, sliderClass, direction){
     $(sliderClass).hide();
     $(buttonId).click(function () {
       $(sliderClass).toggle("slide", { direction: direction }, 1000);
     });
   }
   registerSlider("#test", '.cambridge', 'right' );
   registerSlider("#test2", '.shopping', 'up' );

});

Your questions

I showed in my counter proposal how you can condense the code, but I do believe you will need each time a distinct class
Finding the answer to that question is not trivial (we would need a working sample), and not something codereview does.


It is absolutely ok to call functions from other functions. There is nothing wrong with that. However, there's room for improvements in your code.

function.php:

There is no need to put simple expressions within parenthesis in your conditions.
The order of your conditions is irritating (negative, positive, negative, negative). Group them properly. That also helps to simplify the conditions.

function validate_registration($password, $confirmpassword, $email)
{
    if (empty($email) || empty($password) || empty($confirmpassword)) {
        registration_form();
        echo "Please enter the required information:";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        registration_form();
        echo "You have not entered a valid email address!";
    }  elseif ($password !== $confirmpassword) {
        registration_form();
        echo "Your password does not match!";
    } else {
        input_registration($email, $password);
    }
}

input_registration:

Escape values on output using the right escaping function.  Since you use prepared statements, no extra escaping is needed for the database.
Create the database connection in central place, so you don't have to change several files and functions, if the database (or your password) changes.

function input_registration($db, $email, $password)
{
    $hash = md5($password); // Consider using a better hash algorithm
    $statement = $db->prepare("INSERT INTO userinfo(email, hash) VALUES (:email, :hash)");

    // Continue with inputting info into database
}

Of course you have to change validate_registration to support the injection of the database dependency.


Is this a reasonable algorithm for shuffling cards?

It's an interesting approach...  Some cleanup to consider...

int i = 0;

i is never used...

rnd.nextInt(52)

You might want to interrogate the size of deck at the start of the method, rather than using a fixed 'magic' number.  That would mean that you'd be able to use the method to shuffle decks of multiple packs of cards for example...

deck.remove(bottomCard);

Although you're treating this as a unique case, it's still card 0, I'd consider defining a constant FIRST_CARD_IN_DECK=0 to represent the card to remove.

It's unclear where deck comes from should it be passed into the shuffle function?


Passing bitmap from C# to C++ via a struct

There is not much to review. The only thing I can contribute with is that you don't have to run in unsafe mode:

If you define the data structure as:

  [StructLayout(LayoutKind.Sequential)]
  internal struct RawImage
  {
    internal IntPtr ImageData;
    internal int Size;
  }

Then you can run the .NET side as:

  using (var bitmap = new Bitmap(@"fileName.Jpeg"))
  using (var stream = new MemoryStream())
  {
    bitmap.Save(stream, ImageFormat.Jpeg);
    var source = stream.ToArray();

    IntPtr handle = IntPtr.Zero;

    try
    {
      handle = Marshal.AllocHGlobal(source.Length);
      Marshal.Copy(source, 0, handle, source.Length);

      var raw = new RawImage
      {
        ImageData = handle,
        Size = source.Length
      };
      submit(raw);
    }
    catch (Exception ex)
    {
      if (handle != IntPtr.Zero)
      {
        Marshal.FreeHGlobal(handle);
      }
    }
  }

The above works with the same signature for submit(RawImage img).

It's a little more code, but you are not limiting the use of your module.


Generating a string with only one space between the words

Always specify length of array pointers.

In C, it is not always guaranteed that an array of char will be null terminated and therefore, the size can be determined by calling strlen. Always pass along the length of the array when passing a pointer to a function. This is not just for strings, but also for other pointer types which point to a dynamically allocated and static arrays.

Naming

Choose a consistent naming plan. The most commonly found style in most C code is snake_case. But whatever you choose, stick to it and don't deviate.

Const-correctness

If a method is not going to modify it's parameters, make that intention clear by accepting the arguments as const. This form of programming is what makes code self-documenting because you don't need to tell anyone that the function does not modify it's parameter, the const specifier tells the whole story.

Malloc + free

Always remember, for every malloc, there should be an equal and opposite free. Not freeing memory leads to unexpected memory leakages. This may not apply to you now, but just know this, many man hours have gone into developing tools for detecting memory leaks (valgrind, leakSanitizer, etc) when the best programmers are making extra effort not to leak memory, but still fail. Memory leaks are no joke. Free the memory when you are finished with it.

With all that being said, here is my rendition of your code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h> /* isspace */
#include <stddef.h> /* size_t */

#define SIZE (size_t)80

void inputStr(char*, size_t);
char* upgradeString(const char const*, size_t);

int main() {
    char string[SIZE] = {'\0'}, *result;
    printf("Enter string: ");
    inputStr(string, SIZE);

    size_t strLength = strlen(string);

    if (strLength > 0 && isspace(string[strLength - 1])) {
        string[--strLength] = '\0';
    }

    result = upgradeString(string, strLength);
    puts(result);
    free(result);
}

void inputStr(char* str, size_t length) {
    fgets(str, length, stdin);
}

char* upgradeString(const char const* oldText, size_t length) {

    size_t i, newSize = 0, foundSpace = 0;
    for (i = 0; i < length; i++) {
        if (isspace(oldText[i])) {
            if (foundSpace) {
                continue;
            }
            foundSpace = 1;
        } else {
            foundSpace = 0;
        }
        newSize++;
    }

    char *result = malloc((sizeof *result) * (newSize + 1));

    if (result) {
        char *temp = result;
        foundSpace = 0;
        for (i = 0; i < length; i++) {
            if (isspace(oldText[i])) {
                if (foundSpace) {
                    continue;
                }
                foundSpace = 1;
            } else {
                foundSpace = 0;
            }
            *temp++ = oldText[i];
        }
    }

    return result;
}

The changes made are based on the following additional considerations:

What happens if the user enters nothing (standard input is empty)?
What happens if the user just presses enter?

Conclusion

In conclusion be precise, be constant with naming, be explicit with intent. This will make your code robust and potentially bug free.

P.S.
It is not necessary to cast the result of malloc


I don't know if I'm just not understanding your situation properly or what, but I don't think converting three classes to static for one static method is really the right thing to do here. Why would you need to call System::DoStuff() statically? Why not just $system->DoStuff()? I would refactor the one method before I refactored the three classes. At most I would convert your base class to an abstract class to prevent its instantiation and I would define the value for the $value property in each individual class.

abstract class Base {
    public $value;
}

class FooController extends Base {
    public $value = 1;

    //etc...
}

class HelloController extends Base {
    public $value = 10;

    //etc...
}

You should use doccomments instead of those normal comments. They're more useful and can be read by your IDE.

/** List of classes I'll have to load */
private static $load = array( 'Foo', 'Hello' );

"Up" is not a very descriptive method name. What is it supposed to do? From your comments and your code it looks like its instantiating the class. So normally this would be in the constructor. I would suggest renaming this to something like instantiate(), or maybe getInstance(); And then I would make this a private method, or at the very least ensure that it hasn't already been instantiated so you don't end up doing it again.

eval() is evil. No seriously, it is. It is a horrible security risk. The only saving grace in this instance is that you have not written this in such a way that user input could be used. If you need to dynamically load a class, then you should just do so like this:

foreach( $load AS $class ) {
    require "./class/$class.php";
    $instance = new $class();
}

The *_once() versions of require and include should be avoided if at all possible. With a small number of files it isn't as noticeable, but PHP has to run a special check on each request to ensure that the file hasn't already been included, this means that it will run slower. Again, this is negligible in this case, but it could become an issue later.

I hope this helps, but I really don't know if I understood your issue well enough.


Applying a formula to 2D numpy arrays row-wise

Here's some alternatives using your arrays:

Yours, for reference:

In [19]: np.fromiter(map(partial(users_formula, S), A, B), dtype=np.float64)Out[19]:
array([  5.88698000e-07,  -1.11998000e-07,   1.87179000e-07,
         4.89032000e-07])

List comprehension with row indexing

In [20]: np.array([users_formula(S,A[i],B[i]) for i in range(A.shape[0])])
Out[20]:
array([  5.88698000e-07,  -1.11998000e-07,   1.87179000e-07,
         4.89032000e-07])

Make the row indexing a bit more explicit - longer, but clearer

In [21]: np.array([users_formula(S,A[i,:],B[i,:]) for i in range(A.shape[0])])
Out[21]:
array([  5.88698000e-07,  -1.11998000e-07,   1.87179000e-07,
         4.89032000e-07])

Replace indexing with good old Python zip (this my personal favorite for readability).

In [22]: np.array([users_formula(S,a,b) for a,b in zip(A,B)])
Out[22]:
array([  5.88698000e-07,  -1.11998000e-07,   1.87179000e-07,
         4.89032000e-07])

Even though I'm generally familiar with apply_along_axis I'm having problems with its application.  Even if I get it right, that's not a good sign.  It may be the most compact, but it clearly won't be the clearest.

In [23]: np.apply_along_axis(partial(users_formula,S),0,A,B)------------------    ...
ValueError: matrices are not aligned

There some other functions to explore, such as np.vectorize and np.frompyfunc.  But they'll have the same problem - I'd have to study the docs and experiment to get a working example.

The problem with apply_along_axis is that it's designed to iterate over one array, not several.

apply_along_axis(func1d,axis,arr,*args)
apply_along_axis(...,0, A, B)

This would iterate on the rows of A, but use the whole B.  S could be passed as *args.  But to use both A and B, I'd have to concatenate them into one array, and then change your function to handle 'rows' from that. MESSY.

Internally, apply_along_axis is just a generalization of:

outarray=np.empty(A.shape[0],A.dtype)
for i in range(A.shape[0]):
    outarray[i] = users_formula(S,A[i,:],B[i,:])


Boilerplate singleton / lazy initialiser

Based on the naming guidelines variables should be named using camelCase casing, at least if you don't have any internal naming guidelines.
So Lazy should become lazy or much better lazyManager to make it clear what's the lazy is about.

Otherwise your code looks good.
What I would like to suggest is to rename the class to better reflect its usage and makes it clear from the name what it is about. Maybe DatatableManager would be better.


Select depart date, 5 days from today and return date, 6 days from today in Selenium

You don't need the Date type. You can do it all with a Calendar instance and a DateFormat instance:

    DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
    Calendar now = Calendar.getInstance(); // gets current date
    now.add(Calendar.DATE, 5);             // add five days
    String firstDate = dateFormat.format(now.getTime());
    ...
    now.add(Calendar.DATE, 1);             // add one more day
    String secondDate = dateFormat.format(now.getTime());


Check that malloc didn't return NULL; in general, use defensive programming; That means always assume things went wrong, and check all return values. It helps with debugging too.

You should be aware that strtok and atoi are not safe functions for arbitrary user input. That means you are vulnerable to stack/buffer overflows. Read the man pages of the two functions carefully. Consider using \0-safe functions instead, or at least put a \0 at the end of the input strings.


This function can be written like this:
char* readStdinLine()
{
        char*  buffer  = NULL;
        size_t bufsize = 0;
        ssize_t characters = getline(&buffer, &bufsize, stdin);
        if (characters == -1) {
            free(buffer);
            buffer = NULL;
        }
        else if (buffer[characters-1] == '\n') {
            buffer[characters-1] = '\0';
        }
        return buffer;
}

The getline() function does everything you need. You simply need to check for errors and remove the new line character)


1. Comments on your code

Python has a built-in module, timeit, for measuring the execution time of small code snippets. So there is no need for all that fussing about with datetime.
Project Euler problem 55 says:

  you are given that for every number below ten thousand, it will either (i) become a palindrome in less than fifty iterations

but your code only tries 25 iterations. It happens to be the case that 25 iterations are enough in this case, but how did you figure that out? If you had a mathematical proof that showed that 25 iterations were enough, then that would be fair enough, but I suspect that in fact you re-ran the program with different values for the count of iterations until you found that smallest one that produces the right answer. This seems like cheating to me: if you are willing to do that, why not just replace the whole program with:

print(answer)

which would be even faster?
The problem statement asks:

  How many Lychrel numbers are there below ten-thousand?

but you test range(10001) which is off by one. Luckily for you, 10,000 is not a Lychrel number, so this doesn't lead to an error.
You've made candidates into a global variable, and run some of your code at top level. This makes it hard to test your program from the interactive interpreter. You need something like this:

def problem55(n):
    """Return a list of Lychrel candidates below n."""
    candidates = []
    for number in range(n):
        if is_lychrel(number):
            candidates.append(number)
    return candidates

and then you can test it like this:

>>> from timeit import timeit
>>> timeit(lambda:problem55(10000), number=100)
8.279778157011606

2. Speeding it up

The problem statement only asks how many Lychrel numbers there are, so there is no need to construct a list of them.
Function calls in Python are moderately expensive, so you can save some time by inlining them. This leads to an implementation like this:

def problem55_1(n, m):
    """Return the count of numbers below n that do not lead to a
    palindrome after m iterations of reversal and addition.

    """
    count = 0
    for i in range(n):
        r = int(str(i)[::-1])
        for _ in range(m):
            i += r
            r = int(str(i)[::-1])
            if i == r:
                break
        else:
            count += 1
    return count

which is about 16% faster than yours:

>>> timeit(lambda:problem55_1(10000, 50), number=100)
6.93482669594232

Janne suggested that you could speed things up by caching the numbers already found to be Lychrel and non-Lychrel, and you replied:

  doing that is going to require more conditions and probably is going to be the same running time or even worse

which is a bit of a defeatist attitude. Certainly the code gets more complex when you add caching, but it's not a priori obvious whether this costs more than it saves, or saves more than it costs. The best way to find out is to knuckle down and try it:

def problem55_2(n, m):
    """Return the count of numbers below n that do not lead to a
    palindrome after m iterations of reversal and addition.

    """
    lychrel = set()
    nonlychrel = set()
    count = 0
    for i in range(n):
        j = i
        if i in lychrel:
            count += 1
            continue
        stack = [i]
        r = int(str(i)[::-1])
        for _ in range(m):
            i += r
            if i in lychrel:
                count += 1
                lychrel.update(stack)
                break
            if i in nonlychrel:
                nonlychrel.update(stack)
                break
            stack.append(i)
            r = int(str(i)[::-1])
            if i == r:
                nonlychrel.update(stack)
                break
        else:
            count += 1
            lychrel.update(stack)
    return count

I find that this is about twice as fast as your code:

>>> timeit(lambda:problem55_2(10000, 50), number=100)
3.935654202941805

One final tweak from me. Now that we are caching, the order in which we check numbers for the Lychrel property matters. As you iterate the reverse-and-add process, the numbers get bigger. So if we start with the larger numbers and proceed downwards, then we are more likely to get cache hits. So I tried replacing the line:

    for i in range(n):

with

    for i in range(n - 1, -1, -1):

and got a further small speedup:

>>> timeit(lambda:problem55_3(10000, 50), number=100)
3.800810826011002