Effective way to handle multiple time string to timestamp

It's not really appropriate to print the result or the exception message instead of returning the result or throwing the exception.

It's not right to eliminate all dots from the input before proceeding.

I think that a good strategy would be to transform the input into a canonical representation.  You've started along that path by replacing "midnight" and "noon" with "12:00 am" and "12:00 pm", respectively.  You could go further and set the minutes to ":00" if necessary.  To accomplish that, I would use regular expression matching.

A doctest seems very appropriate here, both for documentation and as a unit test.

from datetime import datetime
import re
from time import mktime

def convert(timestring):
    """
    Convert a time string, in one of four accepted formats, in the
    local time zone, into the number of seconds since the Epoch.

    >>> import os, time
    >>> os.environ['TZ'] = 'US/Pacific'
    >>> time.tzset()
    >>> convert("July 5, 2016, 12:04 a.m.")
    1467702240.0
    >>> convert("July 5, 2016, 7 a.m.")
    1467727200.0
    >>> convert("July 5, 2016, midnight.")
    1467702000.0
    >>> convert("July 5, 2016, noon.")
    1467745200.0
    >>> convert("2016-07-05 12:34:56")
    Traceback (most recent call last):
     ...
    ValueError: time data '2016-07-05 12:34:56' does not match format '%B %d, %Y, %I:%M %p'
    """
    match = re.match(
        '(?P<date>.*)\s+'
        '(?:(?P<noon>noon)|midnight|'
           '(?P<hour>1?[0-9])(?::(?P<minute>[0-5]?[0-9]))?'
           '\s+(?:(?P<pm>p)|a)\.?m)\.$',
        timestring
    )
    if match:
        # Canonicalize the time of day as "HH:MM am/pm"
        timestring = '{date} {hh}:{mm} {ampm}'.format(
            date=match.group('date'),
            hh=match.group('hour') or '12',
            mm=match.group('minute') or '00',
            ampm=['am', 'pm'][bool(match.group('pm') or match.group('noon'))]
        )
    return mktime(
        datetime.strptime(timestring, '%B %d, %Y, %I:%M %p').timetuple()
    )


First thing, it unnecessary to use the included hook methods. Since your purpose is to redefine some methods in ActiveresourceResponse::Connection and Activeresource::Base, why not just do so directly?

# if ActiveResource has not been loaded yet, Rails' const_missing hook
#   will load it automatically
ActiveResource::Connection.class_eval do
  alias_method :__handle_response__ :handle_response
  # ... and so on
end
ActiveResource::Base.instance_eval do
  alias_method :__find__ :find
  # ... and so on
end

By using instance_eval in the second case, we can redefine class methods with 1 less line of code, because class << self is unnecessary.

In add_response_method, it is unnecessary to pass 'http_response' as an argument. That code will never be run with any other value, so why use an argument? Just use a literal value, it's clearer and easier to read.

Every time a model object is returned from ActiveResource::Base.find, you define the http_response method on it with class_eval. This is very inefficient -- I think you should just define a http_response instance method on ActiveResource::Base, and all model classes derived from ActiveResource::Base will inherit it. (Think of the work which is done to define a method -- the Ruby parser has to run on the code, it has to be compiled to bytecode, then an entry has to be made in a method table...)

I just benchmarked Object#instance_variable_set, and it's very fast, faster than using instance_eval or instance_exec. So I think that should stay, but don't generate a new symbol using :"#{}" each time. Just use something like :@__http_response__. (Why the "special" name? Because when you are adding instance variables to a user-defined class, you want to reduce the chances of a collision with a user-defined variable.) Of course, this will mean you can't use attr_reader, but that's no problem. You can just do something like: def http_response; @__http_response__; end

For tests, why don't you look at how ActiveResource itself is tested? I'm sure all that code is open-source and should be available from a public repo.

EDIT: I just looked at the GitHub repo and noticed that you changed to a thread-local variable to try to make the code thread-safe. My question is: is a single ActiveResource::Connection object shared by the whole application? Or each time you make a request, does it create a new Connection object? If it creates a new Connection object for each request, then using thread-local variables is unnecessary, and an instance variable would be better. If the whole application is sharing only one Connection object, then using the thread-local variable is a good idea.

EDIT 2: I just found a bug. If a user tries to use add_response_method to add an alias for http_response, subsequent calls to find will go into an infinite loop. Try it and you will see.


The code sure must be streamlined. I didn't find any better way to review but to rearrange the code and put my notes as comments.

    // First, you test the character against the same condition twice.
    // A more direct way would be to do it once

    if (c == '#' || c == '[') {
        while (fgetc(f) != '\n')
            ;
        continue;
    }
    if (c == ' ' || c == '\n')
        continue;

    // Notice that here you still have `c` intact (so the comment about
    // NOW is misleading). Time to initialize the `url`:

    u = new_url();

    // Since you have the first character of the `u->path`, a correct
    // idiom is a `do {} while ();` loop:

    do {
        string_push_char(u->path, c);
        c = fgetc(f);
    } while(c != '\n' && c != '[');

    // Here `c` is the reason of loop termination. Test it and proceed accordingly:

    if (c == '[') {
        while ((c = fgetc(f)) != ']') {
            string_push_char(u->title, c);
        }
        while(fgetc(f) != '\n')
            ;
    } else {
        string_copy(u->title, u->path);
    }

This almost it. The code parses the well-formed file, but will fall into an infinite loop if, for example, the title-closing bracket is missing.

As a side note, isspace(c) is strongly preferred to a manual testing.


Save 2 related models through a single form

The way you have this implemented, by overriding the save method to save the related models, is correct and is how it should be implemented. Unless you implement this logic outside of the form, in which case you are probably violating some DRY principles, the form is the correct place to manage data for multiple models.


Sum of proper divisors of every number up to N

1. Analysis

The code in the post loops over \$2 ≤ i ≤ {n\over 2}\$ and then over the multiples of \$i\$ below \$n\$:

for i in range(2, N//2+1):
    for j in range(i+i, N, i):
        div_sum[j] += i + j//i if i != j//i else i  # (A)

This means that the line (A) is executed at most $$ {n\over 2} + {n\over 3} + {n\over 4} \dotsb + {n \over n/2} $$ times, that is $$ n\left({1\over 2} + {1\over 3} + {1\over 4} \dotsb {1\over n/2}\right) $$ which is \$n(H_{n/2} - 1)\$ (where \$H_n\$ is the \$n\$th harmonic number), and this is \$Θ(n \log n)\$.

2. Improvement

The first thing to note is that if we had a function that computed the sum of all the divisors, then we could compute the sum of proper divisors by subtracting the number itself:

def sum_proper_divisors(n):
    """Return list of the sums of proper divisors of the numbers below n.

    >>> sum_proper_divisors(10) # https://oeis.org/A001065
    [0, 0, 1, 1, 3, 1, 6, 1, 7, 4]

    """
    result = sum_divisors(n)
    for i in range(n):
        result[i] -= i
    return result

Let's call the sum-of-all-divisors function \$σ\$, and consider for example \$σ(60)\$: $$ σ(60) = 1 + 2 + 3 + 4 + 5 + 6 + 10 + 12 + 15 + 20 + 30 + 60. $$ Collect together the divisors by the largest power of 2 in each divisor: $$ \eqalign{σ(60) &= (1 + 3 + 5 + 15) + (2 + 6 + 10 + 30) + (4 + 12 + 20 + 60) \\ &= (1 + 3 + 5 + 15) + 2(1 + 3 + 5 + 15) + 2^2(1 + 3 + 5 + 15) \\ &= (1 + 2 + 2^2)(1 + 3 + 5 + 15).} $$ Now, the remaining factor \$1 + 3 + 5 + 15\$ is \$σ(15)\$ so we can repeat the process, collecting together the divisors by the largest power of 3: $$ \eqalign{σ(15) &= (1 + 5) + (3 + 15) \\ &= (1 + 3)(1 + 5).}$$ And so $$ σ(60) = (1 + 2 + 2^2)(1 + 3)(1 + 5). $$ This is obviously connected to the fact that \$ 60 = 2^2·3·5 \$. In general, if we can factorize \$n\$ as: $$ n = 2^a·3^b·5^c\dotsb $$ then $$ σ(n) = (1 + 2 + \dotsb + 2^a)(1 + 3 + \dotsb + 3^b)(1 + 5 + \dotsb + 5^c)\dotsm $$ These multipliers occur many times, for example \$(1 + 2 + 2^2)\$ occurs in the sum of divisors of every number divisible by 4 but not by 8, so it's most efficient to sieve for the sums of many divisors at once, like this:

def sum_divisors(n):
    """Return a list of the sums of divisors for the numbers below n.

    >>> sum_divisors(10) # https://oeis.org/A000203
    [0, 1, 3, 4, 7, 6, 12, 8, 15, 13]

    """
    result = [1] * n
    result[0] = 0
    for p in range(2, n):
        if result[p] == 1: # p is prime
            p_power, last_m = p, 1
            while p_power < n:
                m = last_m + p_power
                for i in range(p_power, n, p_power):
                    result[i] //= last_m    # (B)
                    result[i] *= m          # (B)
                last_m = m
                p_power *= p
    return result

3. Analysis

The lines marked (B) are executed at most $${n\over 2} + {n\over 2^2} + \dotsb + {n\over 3} + {n\over 3^2} + \dotsb $$ times, that is $$n\left({1 \over 2} + {1 \over 2^2} + \dotsb + {1\over 2^{\lfloor \log_2 n\rfloor}} + {1 \over 3} + {1 \over 3^2} + \dotsb + {1\over 3^{\lfloor \log_3 n\rfloor}} + \ldots\right)$$ which is less than $$n\left({1\over 2-1} + {1\over3-1} + {1\over5-1} + \dotsb + {1\over p-1}\right)$$ where \$p\$ is the largest prime less than or equal to \$n\$, and this is \$Θ(n \log \log n)\$ (see divergence of the sum of the reciprocals of the primes) and so asymptotically better than the code in the post.


We can convert a plain string to a list rather than maintain a list for the characters.
It is far easier to modify and read the following then a list.
lib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!"§$%&/()=ß´`+#-.,><@€|^~–{[]}ÄÖÜäöü')

When we have counter0, counter1, ..., countern it's a hint that we should use a list.
counters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

We can then use counters[0] as a drop in replacement for counter0.

Now that we have counters which is a list we can simplify your print from the following.

print(lib[counters[0]] + lib[counters[1]] + lib[counters[2]] + lib[counters[3]] + > lib[counters[4]] + lib[counters[5]] + lib[counters[6]] + lib[counters[7]] + lib[counters[8]] + lib[counters[9]], end="\r")

We can use a for loop to loop through counters, index lib and print the character. We'll use end="" to get the same format that you have. Since we've changed from "\r" to "" we'll need to print that afterwards.
for counter in counters:
    print(lib[counter], end="")
print(end="\r")

It would be better to use len(lib) rather than hard coding 99 in your ifs. If we change the content of lib it's much easier to edit just lib rather than lib and 10 99's.

Rather than counter0=counter0*0 it would make more sense to remove the multiplication and just set the value to 0.
counter0 = 0

It's convention in Python to put a space either side of operators. This means a+b should instead be a + b. This is as it makes it easier to see what is and is not an operator and either side of an operator.

It's convention in Python to use _ as a 'throw away' variable. This means it's normal to use _ rather than i in your for loop.

Together this gets:
import sys

lib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!"§$%&/()=ß´`+#-.,><@€|^~–{[]}ÄÖÜäöü')
counters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for _ in range(sys.maxsize**99999):
    counters[0] += 1
    if counters[0] >= len(lib):
        counters[0] = 0
        counters[1] += 1
    elif counters[1] >= len(lib):
        counters[1] = 0
        counters[2] += 1
    elif counters[2] >= len(lib):
        counters[2] = 0
        counters[3] += 1
    elif counters[3] >= len(lib):
        counters[3] = 0
        counters[4] += 1
    elif counters[4] >= len(lib):
        counters[4] = 0
        counters[5] += 1
    elif counters[5] >= len(lib):
        counters[5] = 0
        counters[6] += 1
    elif counters[6] >= len(lib):
        counters[6] = 0
        counters[7] += 1
    elif counters[7] >= len(lib):
        counters[7] = 0
        counters[8] += 1
    elif counters[8] >= len(lib):
        counters[8] = 0
        counters[9] += 1
    elif counters[9] >= len(lib):
        print("DONE.")
    else:
        for counter in counters:
            print(lib[counter], end="")
        print(end="\r")
        sys.stdout.write("\b"*10 + " "*10 + "\b"*10)

There are still some changes that we can make to your code to make it easier to work with.
These are a bit more advanced so don't worry if you don't get them straight away.

We can change your big if elif block into a single for loop.
Lets see what we have so far:

if counters[0] > len(lib):
    counters[0] = 0
    counters[1] += 1

We know that this section is repeated each time for each index.
So we can make this generic by changing 0 to index and 1 to index + 1.
if counters[index] >= len(lib):
    counters[index] = 0
    counters[index + 1] += 1

Now we just need to loop over range(len(counters) - 1) to duplicate the block 9 times.
for index in range(len(counters) - 1):
    if counters[index] >= len(lib):
        counters[index] = 0
        counters[index + 1] += 1

We can use some Python sugar to make your print for loop 'cleaner'.
Firstly we can remove all the prints by building a list.
combination = []
for counter in counters:
    combination.append(lib[counter])

From here we can join all the strings together with "".join and pass it to print like you did before. This will join the list by empty strings so it converts it's like manually doing combination[0] + combination[1] + ....
print("".join(combination), end="\r")

We can then use a list comprehension to build combination in one line.
This is just syntaxtic sugar and is the same as the for loop we used before.
It's just different, cleaner, syntax.
combination = [lib[counter] for counter in counters]

We can use either a while True loop or itertools.count rather than range(sys.maxsize**99999) to loop infinitely.
while True:
    counters[0] += 1

import itertools

for _ in range(itertools.count()):
    counters[0] += 1

We can probably just use print rather than sys.stdout.write.
To make it so there is no newline we can pass end="".
This however doesn't flush the stream straight away, and so we need to pass flush=True.

lib = [''] + list('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz°!"§$%&/()=ß´`+#-.,><@€|^~–{[]}ÄÖÜäöü')
counters = [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

while True:
    counters[0] += 1
    for index in range(len(counters) - 1):
        if counters[index] >= len(lib):
            counters[index] = 0
            counters[index + 1] += 1

    if counters[9] >= len(lib):
        print("DONE.")
    else:
        print("".join([lib[counter] for counter in counters]), end="\r")
        print("\b"*10 + " "*10 + "\b"*10, end="", flush=True)


Refactor to provide for multiple instances on a single page

Use a closure, so everything will be only inside it's scope. Additionally you can use $ now!

(function ($) {
    var now = new Date();
    var date = $('.form-date');
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear() + "-" + (month) + "-" + (day);

    date.val(today);

    var form = $('form');

    form.on('submit', function (e) {
        var currentForm = $(this);
        var newVal = currentForm.find('.form-date').val().split('-'),

            dateParts = {
                year: parseInt(newVal[0], 10),
                month: parseInt(newVal[1], 10),
                day: parseInt(newVal[2], 10)
            };

        currentForm.find('.anchor').append($.map(dateParts, function (index, key) {
            console.log(['date', form.index(currentForm), key].join('_'));
            return $('<input>', {
                type: 'hidden',
                name: ['date', key].join('_'),
                id: ['date', form.index(currentForm), key].join('_'),
                value: dateParts[key]
            });
        }));

    });
})(jQuery);

Also change class="anchor1" to class="anchor"

Edit: Whoops, looks like I'm wrong. You have to scope your selectors as $('.anchor').append will work on all .anchor elements. I'm assuming that it's the child of form now.


I just have a couple of small points:

Exiting in Constructor

You shouldn't just exit in a constructor, but throw an exception instead. But in this case, the only statement in the try block is an assignment, so there isn't really anything that can go wrong. You should just remove the entire try-catch block.

Naming

Your naming is somewhat inconsistent. For methods you use camelCase, and for parameters you either use all lowercase (which you should always avoid), or under_score. At the very least custpoid should be custpoId.

I would also use somewhat more descriptive names inside the queries. Having c, cp, cy, as well as ct all in one query is a bit confusing.

SQL Style

Your SQL statements are also a bit inconsistent. If you write SQL keywords in all uppercase, do it always (see for example as, on, and Select).


Maximum sub-array of non-negative numbers

1. Bugs

maxset returns the wrong answer for some inputs. For example:

>>> maxset([2, 1, -1, 1, 3])
[2, 1]

The correct answer is [1, 3]. The cause of this bug is the line:

if max_array < array[start:stop]:

which causes the sub-array with the higher sum (here, [1, 3]) to be ignored because it lexicographically precedes max_array (here, [2, 1]).
maxset goes wrong when all the elements of the input are negative:

>>> maxset([-1, -2])
-1

The number -1 is not a valid result: it's not the maximum sub-array, it's just a number.

It also goes wrong when the input is empty:

>>> maxset([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr193902.py", line 7, in maxset
    max_array = array[0]
IndexError: list index out of range

To fix these two problems, instead of this initialization:

max_array = array[0]

start with an empty list:

max_array = []

2. Review

The code in the post uses the print statement and so only runs on Python 2.7. But support for Python 2.7 is scheduled to end in 2020. It is long past the time when it was a good idea to start writing new projects in Python 2.7. If you really can't use Python 3 then use:

from __future__ import print_function

so that your code is portable to Python 3.
The name maxset is misleading since it does not return a set.
When you take a slice of a list, for example array[start:stop], Python has to copy out all the elements of the slice in order to construct a new list. This is a waste unless you are actually going to need the new list. So instead of:

len(array[start:stop])

(which creates a list and then throws it away again) you could write:

stop - start

This line copies out a slice of the list each time you find a new maximum sub-array:

max_array = array[start:stop]

but in many cases you are never going to need this list, because later on you will find an even bigger sub-array. So instead of copying out a slice, you could remember the location of the maximum sub-array found so far:

max_start = start
max_stop = stop

and at the end of the function

return array[max_start:max_stop]

The code has a loop over the indexes into array:

for i in range(len(array)):

and then within the loop it looks up the element at that index using array[i]. Whenever you see this pattern, you can simplify it using the built-in function enumerate. In this case the loop becomes:

for i, element in enumerate(array):

and wherever you had array[i] you now have element.
The two branches of the if: ... elif: ... both have the line:

max_array = array[start:stop]

This duplication could be avoided by combining the two conditions into one:

if (max_sum < current_sum
    or (max_sum == current_sum
        and max_stop - max_start < stop - start)):

and this can be further simplified by comparing tuples:

if (max_sum, max_stop - max_start) < (current_sum, stop - start):

There's no need to maintain a running variable stop since it always has the value i + 1.
The test cases don't check the results. When I run it, I get the output:

>>> main()
[1, 2, 5]
[1]
[1, 2, 5, 7, 2, 5]
[222]
[1, 1]
[1, 1, 1]
[5]
[1, 1, 1]
[1, 1, 1]

Is this right? The usual way to write a test case is to raise an exception if the result is incorrect. There are various ways to do this. You could use the assert statement and write:

assert maxset([ 1, 2, 5, -7, 2, 5 ]) == [1, 2, 5]

or you could use the unittest module from the Python standard library.

3. Revised code

def max_sub_array(array):
    """Return maximum sub-array of non-negative numbers."""

    start = 0                   # Start of current sub-array
    current_sum = 0             # Sum of current sub-array
    max_start = 0               # Start of maximum sub-array
    max_stop = 0                # Stop of maximum sub-array
    max_sum = 0                 # Sum of maxium sub-array

    for stop, element in enumerate(array, start=1):
        if element >= 0:
            current_sum += element
            if (max_sum, max_stop - max_start) < (current_sum, stop - start):
                max_sum = current_sum
                max_start = start
                max_stop = stop
        else:
            start = stop
            current_sum = 0

    return array[max_start:max_stop]

import unittest

class TestMaxSubArray(unittest.TestCase):
    CASES = [
        # array, expected result
        ([], []),
        ([-1, -2], []),
        ([2, 1, -1, 1, 3], [1, 3]),
        ([1, 2, 5, -7, 2, 5], [1, 2, 5]),
        ([1,-1, 1, -1, 1, -1], [1]),
        ([1, 2, 5, 7, 2, 5] , [1, 2, 5, 7, 2, 5]),
        ([222], [222]),
        ([1, 1], [1, 1]),
        ([3, -1, 1, 1, 1, -1, 3], [1, 1, 1]),
        ([5, -1, 1, 1, 1, 1, -1, 5], [5]),
        ([3, -1, 1, 1, 1, -1, 2], [1, 1, 1]),
        ([3, -3, -1, 1, 1, 1, -1, 2], [1, 1, 1]),
    ]

    def test_max_sub_array(self):
        for array, expected in self.CASES:
            self.assertEqual(expected, max_sub_array(array))

4. A different approach

The single responsibility principle say that each piece of code should do just one thing. By splitting code into pieces with single responsibilities, the individual pieces become easier to understand, check and test.

So for this problem we could split the code into two parts:

find all the sub-arrays of non-negative numbers in array;
find the maximum sub-array in the results of step 1.

For part 1 the Python standard library has a useful function itertools.groupby for splitting an iterable into groups based on a key function. In this case the key function needs to be "is the element non-negative". Then for part 2 we can use the built-in max function, again using a key function.

from itertools import groupby

def max_sub_array(array):
    """Return maximum sub-array of non-negative numbers."""
    sub_arrays = [list(group)
                  for non_negative, group in groupby(array, lambda e: e >= 0)
                  if non_negative]
    if sub_arrays:
        return max(sub_arrays, key=lambda a: (sum(a), len(a)))
    else:
        return []

In Python 3.4 or later, max has a default keyword argument to handle the case where there are no items, and so we can combine this into a single expression:

from itertools import groupby

def max_sub_array(array):
    """Return maximum sub-array of non-negative numbers."""
    return max((list(group)
                for non_negative, group in groupby(array, lambda e: e >= 0)
                if non_negative),
               key=lambda a: (sum(a), len(a)),
               default=[])


Use chr($randInt) instead of $charUniverse[$randInt], and abandon the $charUniverse variable altogether.
Use the $str .= "str" dot-equals operator in PHP to append to your final string.

Thus your code becomes:

public function generateKey($size){

   $randomString = "";
   $charDomainSize = 256;
   for($i=0;$i<$size;$i++){
     $randInt=mt_rand(0, $charDomainSize-1);
     $randChar=chr($randInt);
     $randomString .= $randChar;
   }
   return $randomString;

}

If we compress your code further, it becomes:

public function generateKey($size){
   $randomString = "";
   for($i=0;$i<$size;$i++){
      $randomString .= chr(mt_rand(0, 255));
   }
   return $randomString;
}

I conducted a speed test, as well. The new code is faster (1000 runs, varied sizes between 1128 and 1148). The units are seconds.

Function 1 Average: 0.024438648223877
Function 2 Average: 0.015253195762634

Only using 256 as a size, 1000 runs:

Function 1 Average: 0.00031177306175232
Function 2 Average: 0.00017282342910767

This is a little overkill, but I was bored.

It should be very easy to port your random string generator to other platforms, although it may develop more or less dependable randomness based on the underlying generators. E.g. don't use Java's java.util.Random for security or scientific purposes (see Difference between java.util.Random and java.security.SecureRandom).

You might also want to consider PHP's openssl_random_pseudo_bytes, depending on your intent. That may not be as easily ported, though, as your current code.


Is there a smarter way to approach this question?

We'll see in a moment. Parts of it can be improved for sure.

How can I improve the space and time complexity of the given question?

You can't. The complexity will remain the same. The changes you can make might give small increases in performance or decrease memory usage, but the complexity will remain the same.

Have I gone too overboard by using BigInteger Library for this question?

I thought at first that it was possible to use just long, but I'm afraid not. Because of 1000 nCr 500, and such big numbers, you are stuck with BigInteger.

You can use BigInteger.valueOf instead of using the constructor with a String.

You can save some time by using the symmetric property of nCr if r > n / 2. For example, 100 nCr 80 is the same as 100 nCr 20.

You can use just one for-loop instead of two:

value = 1;
for (int i = 0; i < r; i++) {
    value = value * (n - i) / (i + 1);
}
return value;

I used something similar in a project of mine (where I used double instead and thus didn't have to think about truncating integers - an issue which is fixed above thanks to Martin R).


Pass by value
There is little point passing integrals by reference:

They are Copy, meaning that they can be copied implicitly, so there is no usability penalty to having the caller by pass value,
They are cheap to copy, so there is no performance penalty either. Actually... it may actually perform better.

It's cheaper and easier so pass by value!
This will get rid for the weird &(first_prime + second_prime + third_prime) == input thing.
Expression oriented language
Rust is an expression oriented language. In short, it means that practically everything is an expression.
Notably, a block {} is an expression which evaluates to the value of its last expression (or () if its ends with a statement).
Therefore, the body of a function is an expression, you can simple use None at the end instead of return None;.
Avoid recomputing primes over and over
At the moment, the complexity of your program is horrendous because you keep recomputing the primes over and over. This is unnecessary.
Instead, you can compute the primes up until input once, and then filter those primes.
First Draft
Applying the two above strategies already cleans up the code quite a bit:
fn get_goldbach_solution(input: usize) -> Option<[usize; 3]> {
    let primes = list_primes_until(input);

    for &first_prime in &primes {
        let remainder = input - first_prime;

        for &second_prime in primes.iter().take_while(|p| **p < remainder) {
            let remainder = remainder - second_prime;

            for &third_prime in primes.iter().take_while(|p| **p <= remainder) {
                if third_prime == remainder {
                    return Some([first_prime, second_prime, third_prime]);
                }
            }
        }
    }

    None
}

The last step however is not, in terms of algorithmic complexity, as efficient as it could be. We are iterating over primes until finding one which equals remainder. Since primes is sorted, a simple binary_search would be more algorithmically palatable; although in practice, for small numbers, linear iteration might be faster.
Result
fn get_goldbach_solution(input: usize) -> Option<[usize; 3]> {
    let primes = list_primes_until(input);

    for &first_prime in &primes {
        let remainder = input - first_prime;

        for &second_prime in primes.iter().take_while(|p| **p < remainder) {
            let third_candidate = remainder - second_prime;

            if let Ok(_) = primes.binary_search(&third_candidate) {
                return Some([first_prime, second_prime, third_candidate]);
            }
        }
    }

    None
}

It might be more efficient to start from the highest primes, as it reduces the size of the list to iterate further.
I'm not quite sure about it; you can test it using .rev() on the iterators to reverse them.


Overall, I find the code pretty good. A couple of suggestions from my side:

self.__pipes=Set(): I think add_pipe() should not be doing this. When the object is created it should be initialized fully. So this line should be placed inside __init__() at the start of the elif out_splitter: part.
x = open(pn,'w+'): What if this call fails? Exceptions should be handled. There is a good chance that someone using this class may trigger file open failure because they may instantiate the same object from another object (constructor is allowing this). If you make low-level stuff easy to do, you should also provide for exception handling where things might go wrong.
Files opened are not closed. In fact, it might be a good idea to open/close file handles using __enter__() and __exit__() methods, which need to be defined for this class.
One of the things I find with file I/O is that users want control on the order in which messages are printed. The application may throw out stdout and stderr prints in a certain order and the user might want to preserve that order. Unfortunately, the current code flushes the queue of one pipe first before moving on to the next pipe. Users of this class might find this to be inadequate.
In addition, users might want stdout and stderr to be redirected to files. This is not possible with the current class. It maybe okay now, but sooner or later someone will want this and they will start looking for alternatives.
Just a thought: since a getter method is used for __pipes, perhaps you can consider a setter method as well.


In terms of the original code I find it a bit more complex than it needs to be. Once you get to the point where code will exist for a long time or be used by other people a cleaner/simpler solution with similar attributes is often a better bet.

Anyway, I created a solution which is very similar to your own but there are a few differences that might be worth highlighting.

$years = array();
$types = array();
$ytx   = array();

foreach ($array1 as $item)
{
  list($type,$year) = $item;

  $years[$year] = $year;
  $types[$type] = $type;

  if ( !isset($ytx[$year][$type]) )
    $ytx[$year][$type]=0;
  $ytx[$year][$type]++;
}

ksort($years);
ksort($types);

I'm big on simplification and variables are relatively cheap. So, above there are arrays for the years and types as well as new variable collecting the count of year/type instances.

For sorting purposes the year and type keys are set to the year or type while the (dummy) value used is the same which allows simple foreach use later.

echo "
Year";
foreach ($types as $type)
  echo "\t$type";
echo "
\n";

foreach ($years as $year)
{
  echo "$year";
  foreach ($types as $type)
  {
    $val = 0;
    if ( isset($ytx[$year][$type]) )
      $val = $ytx[$year][$type];
    echo "\t$val";
  }
  echo "
\n";
}
echo "
\n";

The above is also very similar. However, you'll  notice I avoided the else statement by setting a variable to zero. There doesn't seem to be a need to be overly concerned for efficiency so, to me, avoiding the else is just a little bit cleaner -- the same reason I often avoid the brackets for single line if statements though some will not.

A few other general review notes:

Strive for meaningful variable names. I tend to us shorter names than many folks do these days (such as $ytx) but in the context of the code I find them meaningful.
I didn't find a need to use all kinds of array related functions. If we are walking through the array anyway things like array_count_values, implode, array_unique, array_key_exists and so on aren't necessarily adding much value. Someone maintaining the code in the future may not be very familiar with PHP's array functions.

In short, I'd prefer your solution to the original. However, if it was being created for inclusion on a project of mine there is no way I'd accept it with the undefined index notices.

Other than that, get into the habit of putting time into what I call simplification. The total project effort can often be significantly reduced with design choices and in terms of long term maintenance simpler code is faster to modify and less risky to work with. If you don't think about simplification during smaller efforts it is not going to be second nature when you get into larger projects.

Of course, your view of simplicity may not coincide with mine which is fine as long as you don't work for me. ;)


SQLite search disregarding spaces and Pinyin tones

Very interesting question!

I can't see which other way could be used in SQL by itself.

But an alternative method might be to prepare a regexp pattern, then use it with REGEXP, like this:

function tones_pattern($str) {
  for ($i = 0, $n = strlen($str); $i < $n; $i++) {
    @$pattern .= $str[$i] . '([1-4] )?';
  }
  return @$pattern;
}

$results = $db->query("
SELECT CHS, PIN, DEF
FROM MAIN
WHERE CHS LIKE '%" . $q . "%'
OR PIN REGEXP '" . tones_pattern($q) . "'
OR PIN LIKE '%" . $q . "%'
");

So you get rid of what ashames you :)
But I didn't test it, and it might have performance issues. Let me know!

Note: I wrote the $pattern above according what I understand from the example you gave in your comment, i.e. each tone digit is always followed by a space. So two points:

If the above rule is true, then your own solution could already be a bit simplified into
REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1 ',''),'2 ',''),'3 ',''), '4 ','')
At the opposite if the space is not always present, my $pattern must be turned from '([1-4] )?' to [1-4]? ?


Binary search tree in Java with only one class

There are however a couple of improvements and refactoring that you could definitely make. The problem in your logic is that a node is holding a reference to the root node, when it shouldn't. A node should only know what data it contains and what are its left and right nodes, nothing more (you could perhaps argue that, in some cases, it could also contain a reference to its parent).

Never use raw types. In this case, you are using Comparable as a raw type. Since your Node class can hold data for every type, what you want is to make that class a typed class.

public class Node<T extends Comparable<T>> {
    private T data;
    private Node<T> left;
    private Node<T> right;
    // ...
}

This makes the rest of the code type-safe. In this case, you are saying that your node can contain data of a type T that is comparable with itself, for any type matching this.

Making this change will show the problem with your design:

private static Node<T> root;

This won't compile anymore and it echoes to what I said in the beginning of this answer: this shouldn't exist in the first place. So you should delete it.
Then, the default constructor, which is

public Node() {
    root = null;
}

can also be removed: when constructing a node, you should just need to specify the value its going to hold. As such, your next private constructor should be made public. Furthermore, you don't need to explicitely set the left and right node to null since it will be their default value.

public Node(T data) {
    this.data = data;
}

The method addToTree should be renamed add. Furthermore, it takes an int as argument when it should be made more generic: you can accept in your node any object of type T. You could then refactor it to the following. Note that I also added explicits curly braces: it isn't a good practice to omit them.

public void add(T data) {
    if (data.compareTo(this.data) < 0) {
        if (left == null) {
            left = new Node<>(data);
        } else {
            left.add(data);
        }
    } else {
        if (right == null) {
            right = new Node<>(data);
        } else {
            right.add(data);
        }
    }
}

Your current code doesn't handle the case where you're adding an element that is already present in the tree. If this is intended, it should be documented because BST are allowed not to contain duplicated elements (and most do not).
In the same way, printTree should be renamed print. Consider adding curly braces here also.

public void print() {
    if (left != null) {
        left.print();
    }
    System.out.println(data);
    if (right != null) {
        right.print();
    }
}

For now, you are accepting in your node any Comparable objects. It would be better to accept any type T but also accept a Comparator<T>. The reason is that you may want to have in your tree:

data for which you have no control over so you can't make it Comparable (note: you could still wrap it in a Comparable delegate).
the same type of data but ordered differently (e.g. String ordered by their length, or their lexicographic order...).

This would make your class even more generic since it wouldn't be restricted to Comparable objects.


private static char Shifter(char originalChar, int shift, int letterA, int lettera, int letterCount)

seeing this method declaration makes me shiver.
Let us start with the name of that method. Shifter is a noun but method names should be made out of a verb or a verb phrase hence Shift would be the way to go.

It is always the best if a method declaration can be understood without reading the documentation, so if we rename int shift to int shiftAmount it will become a lot clearer.

The small difference between int letterA and int lettera can be easily overlooked which is bad. So it better should be for instance int upperA and int lowerA but maybe we should think about this some more.

By reading the documentation

/// <param name="letterA"> letter A in ASCII </param>
/// <param name="lettera"> letter a in ASCII </param>

I assume this values are always the same A and a (correct me if I am wrong) hence it doesn't serve any real purpose why this parameters should exist in the method declaration. These values should be extracted to const int either method scoped or private static int class members.

/// <param name="letterCount"> range of alphabet </param>

What is a range of alphabet ? Should it be the number of characters in an alphabet ?

Having a parameter named originalChar doesn't add any value. Maybe just char letter would be better and easier to understand ?

Although you are passing a char to this method I would change the documentation from

/// <param name="originalChar"> char to shift </param>

to (intergated the name change too)

/// <param name="letter"> letter to shift </param>

I agree with @EthanBierlein about the expression-bodied members part. You really shouldn't do something just because it can be done. The expression-bodied members does have a value but IMO only for small amount of code. Having a line of code which is spawned over two lines is just to much code.

This ternary expression

char.IsLower(originalChar) ? lettera - letterA : 0

should better be expressed by a simple if statement because the result is added to a variable and adding 0 just doesn't make a difference. IMO the indent become more clear.

Implementing the mentioned points will then lead to

private static int upperA = 'A';
private static int lowerA = 'a';
/// <param name="letter"> letter to shift </param>
/// <param name="shiftAmount"> amount to shift by </param>
/// <param name="alphabetLetterCount"> count of letters in alphabet </param>
/// <returns> shifted letter </returns>
private static char Shift(char letter, int shiftAmount, int alphabetLetterCount)
{
    var result = upperA;

    result += (char.ToUpper(letter) - upperA + shiftAmount + alphabetLetterCount) % alphabetLetterCount;

    if (char.IsLower(letter))
    {
        result += lowerA - upperA;
    }

    return (char)result;
}

This implementation assumes that the code doesn't need to pass the turkey test.


Generating a random maze using disjoint sets

import random
from grouper import Grouper
import sys

X = 20
Y = 20

class Cell():

Either put object as the base class, or don't include the (). It doesn't really matter, but I think this is ugly.

    """Represents a cell in the maze, with an x and y coordinate and its
    right hand wall and downwards wall.

    """
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.right_wall = self.down_wall = None

class Wall():
    """Represents a wall in the maze with its two neighbouring cells.
    """
    def __init__(self):
        self.neighbours = None
        self.active = True

def popchoice(seq):
    """Takes an iterable and pops a random item from it.
    """
    return seq.pop(random.randrange(len(seq)))

Call it pop_choice so that you don't have guess where one word begins and the other exists. Also it takes a sequence not an iterable

# A mapping of coord tuple to Cell object
cells = {}

I recommend looking at numpy. It has an array type. Basically, you can create an array like: cells = numpy.array( (Y,X), object) which will provide an efficent 2d array structure. That would be nicer to work with and faster then the dictionary you are using.

# A list of all the non-edge walls
walls = []

# Generate cells
for y in range(Y):
    for x in range(X):
        cells[(x, y)] = Cell(x, y)

You shouldn't do logic and loops in module scope. They are slower there then in functions.

# Generate walls and add to the neighbouring cells
for y in range(Y):
    for x in range(X):
        current_cell = cells[(x,y)]
        down_wall = Wall()
        current_cell.down_wall = down_wall
        right_wall = Wall()
        current_cell.right_wall = right_wall
        if y != Y-1:
            down_wall.neighbours = (current_cell, cells[(x,y+1)])
            walls.append(down_wall)

        if x != X-1:
            right_wall.neighbours = (current_cell, cells[(x+1,y)])
            walls.append(right_wall)

You create Walls in every case, but only sometimes add them to walls. This suggests either a bug or a misnamed walls variable.

# Get a list of all the cell objects to give to the Grouper
cell_list = [cells[key] for key in cells]

If using dict, this is the same as cell_list = cells.values() If you use numpy arrays like I suggest its cell_list = cells.flatten()

maze = Grouper(cell_list)

This variable really isn't holding the maze. Calling it maze is misleading

for _ in range(len(walls)):
    # Pop a random wall from the list and get its neighbours
    wall = popchoice(walls)
    cell_1, cell_2 = wall.neighbours
    # If the cells on either side of the wall aren't already connected,
    # destroy the wall
    if not maze.joined(cell_1, cell_2):
        wall.active = False
        maze.join(cell_1, cell_2)

Do it like this instead:

random.shuffle(walls)
for wall in walls:
    cell_1, cell_2 = wall.neighbours
    ...

That'll be more efficient and is clearer.

# Draw the maze

maze_map = []

x_max = (X*2)+1
y_max = (Y*2)+1

Its not clear why you need x_max, a comment would be helpful explaining that

# Make an empty maze map with True for wall and False for space
# Make top wall
maze_map.append([True for _ in range(x_max)])
for y in range(1, y_max):
    # Make rows with left side wall
    maze_map.append([True]+[False for _ in range(1, x_max)])

Here is another case that can really use numpy's ndarrays:

maze_map = numpy.zeros( (x_max, y_max), bool)
maze_map[0,:] = True
maze_map[:,0] = True

That does the same as all your maze_map code so far. Also, calling maze_map, blocked or something would make it clearer why you are putting True/False in it.

# Add the down and right walls from each cell to the map
for coords, cell in cells.items():
    x, y = coords
    # Add the intersection wall for each cell (down 1 right 1)
    maze_map[(y*2)+2][(x*2)+2] = True
    if cell.right_wall.active:
        maze_map[(y*2)+1][(x*2)+2] = True
    if cell.down_wall.active:
        maze_map[(y*2)+2][(x*2)+1] = True

The formula being used to figure out which cells are being reference is kinda hard to figure out.

def output(string):
    sys.stdout.write(string)

# Print the map
for row in maze_map:
    for tick in row:
        if tick: output('X'),
        else: output('.'),
    output('\n')

The following might be a clearer version for drawing:

def output(blocked):
    sys.stdout.write(".*"[blocked])

for x in range(2*X+1):
    output(True)
sys.stdout.write('\n')

for y in range(Y):
    output(True)
    for x in range(X):
        cell = cells[(x,y)]
        output(False)
        output(cell.right_wall.active)
    sys.stdout.write('\n')
    output(True)
    for x in range(X):
        cell = cells[(x,y)]
        output(cell.down_wall.active)
        output(True)
    sys.stdout.write('\n')

I think its a bit clearer because it doesn't have formulas like 2*x+1. It needs more comment but I trust you can handle that.

EDIT

For numpy, use it like this:

cells = numpy.empty( (X,Y), object)
# object is the python object type, not the object you want to put into it
# python's default is to use a number types which are more efficient
# but we aren't storing numbers
for x, y in numpy.ndindex(X, Y):
    cell[index] = Cell(x,y)

Speed:

The biggest time-consumer in the code is the grouper code. That code has opted to implemented the simpler rather then more efficient algorithm for the task. You should really implememt the union-find algorithm. That algorithm is crazy efficient, running in for what is all intents and purposes constant time.

Memory:

If memory is a concern, add slots to your classes. Look up the documentation for how to do it. However, I wouldn't bother unless you are really running out of memory.


The short answer to your question is that forms are evaluated while functions are called (using funcall or apply).

I.e., the way you structure your code (lists of forms) you are painting yourself into the eval corner.  You need to replace lists of forms with lists of functions and then you will be able to use funcall or apply.

E.g., replace

`((problem_id ,(read-string "inpur problem id: "))
  (language ,(read-string "select language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan "))
  (source ,(with-temp-buffer
            (insert-file-contents (read-file-name "select source file"))
            (buffer-string)))
  (submit "Submit"))

with something like

`((problem-id read-string "problem id: ")
  (language read-string "language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan ")
  (source ,(lambda () (file-to-string (read-file-name "source file: "))))
  (submit identity "Submit"))

Where file-to-string is defined thus:

(defun file-to-string (file)
  "Read the content of FILE and return it as a string."
  (with-temp-buffer
    (insert-file-contents file)
    (buffer-string)))

Now you can replace (eval form) with (apply (car form) (cdr form)).


Provide binding event mechanism in revealing module pattern

The names aren't too bad. Yes, if you're using underscore to indicate a private variable, then all privates should start with an underscore. I'd suggest:

_click could be _onClick
s could be settings.

You're overwriting the settings completely. If there were a few more settings, I should be able to specify the ones I care about, but leave the default ones as is.

For example:

var settingsDefault = {
    clickObject: 'body',
    onClick: function(elSelector){
        console.log('clicked occurred on ' + elSelector);
    }
};
var s = settingsDefault;

var init = function (settingsCustom) {
    s = settingsCustom;
};

var _click = s.onClick;

In the above, if I do this:

module.init({
    clickObject: '.foo'
});

it'll blow up because s.onClick is not defined. You're better off to $.extend default settings with config settings.

var init = function(settingsCustom){
    s = $.extend({}, settingsDefault, settingsCustom);
};

This isn't quite true with your code, as the bind is an IIFE, but it does demonstrate the weakness in overwriting settings, rather than extending.

I would suggest keeping all bindings happening within the module, where it is at the minute - this way, everything is in one place.
I'm not a huge fan of IIFE's - the consumer should be in control of what happens when. I'd do away with the IIFE completely, but if it suits your needs, and you're happy to have your module as a singleton, then it's absolutely fine.
Nothing else to add really. Consume your own code, see if it meets your needs - I've found that I rarely need a singleton, so it might not work as you're hoping. That said, I do use them sometimes - but not as often as I originally expected!


Inefficient PowerShell function for checking group membership

This is completely 100% NOT TESTED because I don't have the means to test it at this time however, it should work the way you want and a bit faster than before because it will do alot less queries. It should in theory only query each group once throughout the entire script which if your running even a single group against hundreds of users will save hundreds of queries. Next step I would suggest that you move to a more different loggin function such as streamwriter, is literally over 100x faster at writing logs.

Function Update-GroupMembership {
    Param (
        [Parameter(Mandatory=$True)]
        [ValidateSet('Add','Remove')]
        [String]$Action,
        [Parameter(Mandatory=$True)]
        $ADUser_Properties,
        [Parameter(Mandatory=$True)]
        [String]$ADGroup,
        [Parameter(Mandatory=$True)]
        [String]$LogPathFileName
    )

    IF (-NOT (Test-Path Variable:/Function)) {
        New-Variable -Force -ErrorAction Stop -Scope Script -Name UGM -Value @{}
        $Script:UGM.Users = @{}
        $Script:UGM.Groups = @{}
        if (-not (Get-Module -Name "ActiveDirectory")) {
            Try {
                Import-Module ActiveDirectory
                $Script:UGM.ActiveDirectory = $True
            } Catch {
                $Script:UGM.ActiveDirectory = $False
            }
        }
    }

    #Skip script is active directory not loaded.
    If (!$Script:UGM.ActiveDirectory) {
        Throw "Active Directory module not loaded."
    }

    IF (-NOT ($Script:UGM.ContainsKey($ADGroup))) {
        $Script:UGM.$ADGroupName = New-Object -Type 'System.Collections.ArrayList'
        Get-ADGroupMember -Identity $ADGroup |Select -ExpandProperty SamAccountName |ForEach {$Script:UGM.$ADGroupName.Add($_)}
    }

    $UGM.InGroup = $Script:UGM.$ADGroup.Contains($ADUser_Properties.SamAccountName)
    $Date = ([datetime]::Now).ToString('dd/MM/yyyy HH:mm:ss')
    Switch ($Action) {
        'Add' {
            If ($UGM.InGroup) {
                Write-Host "$($ADUser_Properties.Name) Already in $ADGroup"
            } Else {
                Try {
                    Add-ADPrincipalGroupMembership -MemberOf:$ADGroup -Identity:$ADUser_Properties |Out-Null
                    $Script:UGM.$ADGroup.Add($ADUser_Properties.SamAccountName)
                    Write-Host "  ... Updated: Added to $ADGroup" -ForegroundColor Yellow
                    "[$Date]  ... Updated: Added to $ADGroup" | Out-File $LogPathFileName -Append
                } Catch {
                    Throw "[$Date]  ... Failed: Unable to add $($ADUser_Properties.Name) to $ADGroup"
                }
            }
        }
        'Remove' {
            If ($UGM.InGroup) {
                Write-Host "$($ADUser_Properties.Name) not in $ADGroup"
            } Else {
                Try {
                    Remove-ADPrincipalGroupMembership -MemberOf:$ADGroup -Identity:$ADUser_Properties |Out-Null
                    $Script:UGM.$ADGroup.Remove($ADUser_Properties.SamAccountName)
                    Write-Host "  ... Updated: Removed from $ADGroup" -ForegroundColor Yellow
                    "[$Date]  ... Updated: Removed from $ADGroup" | Out-File $LogPathFileName -Append
                } Catch {
                    Throw "[$Date]  ... Failed: Unable to remove $($ADUser_Properties.Name) from $ADGroup"
                }
            }
        }
        Default {}
    }
}


Split the regex into smaller parts to check each rule individually.

Here's the code for JavaScript. The same simple logic can be used for Ruby or any other language.

// Check the length
if (str.length >= 8 && validate()) {

}

// Check if all the characters are present in string
function validate(string) {
    // Initialize counter to zero
    var counter = 0;

    // On each test that is passed, increment the counter
    if (/[a-z]/.test(string)) {
        // If string contain at least one lowercase alphabet character
        counter++;
    }
    if (/[A-Z]/.test(string)) {
        counter++;
    }
    if (/[0-9]/.test(string)) {
        counter++;
    }
    if (/[!@#$&*]/.test(string)) {
        counter++;
    }

    // Check if at least three rules are satisfied
    return counter >= 3;
}


Compute the next occurrence of Friday the 13th

I think this can be slightly simplified by using dateutils.relativedelta (since datetime.timedelta does not support months, unfortunately). This way you don't need to manually keep track of the year and month and if you ever need to implement something for e.g. next end of a month that is on a Sunday, it is way easier, because it takes care of the peculiarities for you, like months ending on different days of the month.

I would also make the magic constant 4 into a global constant called FRIDAY.

from datetime import date
from dateutil.relativedelta import relativedelta

FRIDAY = 4    # Monday is 0

def next_fri_13(start_date):
    '''Get the next Friday 13th after the specified start_date.

    Args:
        start_date (datetime.date)

    Returns:
        datetime.date: The first Friday 13th after the start_date.
    '''
    thirteenth = date(start_date.year, start_date.month, 13)
    if start_date.day >= 13:
        thirteenth += relativedelta(months=1)

    while thirteenth.weekday() != FRIDAY:
        thirteenth += relativedelta(months=1)
    return thirteenth

Alternatively, you could make a generator of thirteenths days and drop all that are not a Friday using filter and use the fact that relativedelta does not only take offsets, but can also replace attributes at the same time (using the keywords without a trailing "s"):

from itertools import count

def next_fri_13(start_date):
    '''Get the next Friday 13th after the specified start_date.

    Args:
        start_date (datetime.date)

    Returns:
        datetime.date: The first Friday 13th after the start_date.
    '''
    thirteenths = (start_date + relativedelta(months=n, day=13)
                   for n in count(start_date.day >= 13))
    return next(filter(lambda d: d.weekday() == FRIDAY, thirteenths))

IMO the first is easier to read, though, while this one is slightly easier to convert into a generator yielding all Friday the 13ths after start_date (just replace return next(...) with yield from ...).

In any case, there is a bit of a philosophical debate about doing

import itertools

itertools.count()

or

from itertools import count

count()

I personally tend to favor the latter, as long as it is still somewhat easy to figure out which module a function comes from, and there is no shadowing. This makes the lines a bit shorter and easier to read, especially if you use one particular module quite heavily (which the itertools module is a bit predestined for). It is also slightly faster, because you only need to do a global lookup instead of a global lookup and an attribute lookup, but that is negligible most of the time (and if it is not, you should make it a local variable anyway). But in the end the choice is yours.


Binary search for random access iterators in C++

I wrote a generic binary search routine in C++ for ranges that are specified by random access iterators.

Very good idea.

In case the user inputs a range with non-random access iterators, an exception will be thrown. My code is below:

Bad idea. You are doing a runtime check for something that can be detected by the compiler. This should force a compile time error.
Code Review
template<typename RandomIt, typename T>
RandomIt search(RandomIt begin,
                RandomIt end,
                T value,
                std::random_access_iterator_tag)

No need for the type T here. In fact putting it here is probably a bad idea. As it allows you to search a vector of double with an integer. Now there is not much you can do with compiler standard conversions but at least you can make sure that the value passed to the function has already been converted to the correct type for comparison.
template<typename RandomIt, typename Cat = typename std::iterator_traits<RandomIt>::iterator_category>
RandomIt search(RandomIt begin,
                RandomIt end,
                typename std::iterator_traits<RandomIt>::value_type const& value,
                std::random_access_iterator_tag)

Also I would not bother passing the fourth parameter that should be a type to the template. Then you can have a template specialization that implements it for random iterators only.
// Generic Declaration with no implementation.
template<typename RandomIt, typename Cat = typename std::iterator_traits<RandomIt>::iterator_category>
RandomIt search(RandomIt begin,
                RandomIt end,
                typename std::iterator_traits<RandomIt>::value_type const& value);

// Partial specialization for Random Iterator
template<typename RandomIt>
RandomIt search<RandomIt, std::random_access_iterator_tag>(
                RandomIt begin,
                RandomIt end,
                typename std::iterator_traits<RandomIt>::value_type const& value)
{
    // Your implementation here.
}

Now the code will generate a compile time error when you use anything but a random access iterator. With a tiny bit of effort you can do this in a single declaration using the new std::enable_if<> but I leave that as an exercise.
Make Intenet clear
        RandomIt middle = begin + ((end - begin) >> 1);

Not everybody will see >> 1 as a divide by 2. Don't do that it just makes the code unclear. Use the divide operator it express intent much better (and does not have any worse performance).
        RandomIt middle = begin + ((end - begin) / 2);


All of your methods on Node are useless. Just use Node.val and Node.next like you already are.
insert_after_key is likely to insert the data multiple times if there are multiple keys. Given how insert_before_key works differently you should test you code with unittests.
Your code fails silently. I don't recommend this.
You can remove the looping from all your functions if you add add a _iter function.
You can remove the need to loop to fine the key in most of your functions if you add a _find_key function, which returns the previous and next node.
I'd implement (5) using pairwise (itertools recipe) and use the _iter function.
You can simplify append if you use the tail itertools recipe.
You don't seem to have much code to handle empty lists.

import collections
import itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def tail(n, iterable):
    "Return an iterator over the last n items"
    # tail(3, 'ABCDEFG') --> E F G
    return iter(collections.deque(iterable, maxlen=n))

class Node:
    def __init__(self, data, next=None):
        self.val = data
        self.next = next

class SingleLinkedList(object):
    def __init__(self, data):
        self.head = data

    def __repr__(self):
        return '->'.join(str(n) for n in self._iter())

    def __len__(self):
        return sum(1 for _ in self._iter())

    def _iter(self):
        node = self.head
        while node is not None:
            yield node
            node = node.next

    def append(self, data):
        if not self.head:
            self.head = Node(data)
            return

        last, = tail(self._iter(), 1)
        last.next = Node(data)

    def _find_key(self, key):
        if self.head is None:
            raise IndexError('Key not found')
        if key == self.head.value:
            return None, self.head

        for prev, curr in pairwise(self._iter()):
            if curr.val == key:
                return prev, curr
        raise IndexError('Key not found')

    def insert_before_key(self, key, data):
        prev, curr = self._find_key(key)
        if prev is None:
            self.head = Node(data, self.head)
        else:
            prev.next = Node(data, curr)

    def insert_after_key(self, key, data):
        _, node = self._find_key(key)
        node.next = Node(data, node.next)

    def delete(self, key):
        prev, curr = _find_key(key)
        if prev is None:
            self.head = curr.next
        else:
            prev.next = curr.next

    def search(self, key):
        _, node = _find_key(key)
        return node

    def reverse(self):
        cur = self.head
        prev = None
        while cur:
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
        self.head = prev


Just checking that you intend to be reinventing-the-wheel, you can do:

System.out.println("happy".indexOf("app"));

You did know that, right?

Or, if you want to reformat the 'signature' to match yours, it is:

public static int subStringIndex(String str, String substr) {
    return str.indexOf(substr);
}

There are a number of helper methods on String which will help:

String.indexOf(substr) - return the index of the first occurrence of substr
String.indexOf(substr, start) - return the index of the first occurrence of substr on or after the start position.
String.lastIndexOf(substr) - return the index of the last occurrence of substr
String.lastIndexOf(substr, start) - return the index of the last occurrence of substr starting before the start position.
 -


Slice a list or NumPy array into consecutive tuples

I believe that what you are looking for is already available as an itertools recipe; even though pairwise only allow you to return couples and not tuple of arbitrary length.

You will need to modify it so that:

tee will return num iterators;
you advance each of these iterators by one more element than the previous one (see the consume recipe for that).

This can lead to the following code:

import itertools

def advance(iterator, step):
    next(itertools.islice(iterator, step, step), None)

def tuplewize(iterable, size):
    iterators = itertools.tee(iterable, size)
    for position, iterator in enumerate(iterators):
        advance(iterator, position)
    return zip(*iterators)

Usage being:

>>> for t in tuplewize(lst, 4):
...   print(t)
...
(10, 11, 12, 13)
(11, 12, 13, 26)
(12, 13, 26, 28)

However, you are using numpy so we may come up with a better numpy approach:

numpy.roll allows us to advance the nth element on top of the list;
numpy.stack allows us to concatenate the rolled arrays into a single 2D array;
numpy.transpose allows us to convert a "list of lists" into a "list of tuples".

Full code being:

import numpy as np

def tuplewize(array, size):
    if size < 2:
        return np.array([array])

    stack = np.stack([np.roll(array, -i) for i in range(size)])
    return np.transpose(stack)[:-size+1]

Usage being:

>>> tuplewise(lst, 4)
array([[10, 11, 12, 13],
       [11, 12, 13, 26],
       [12, 13, 26, 28]])

And as @Peilonrayz indicated in a comment, a third possibility is to use the more_itertools package and its windowed function which has extended capabilities; and as such more overhead, so depending on your needs it may or may not suit you.


Draw the table like 6³ = 3³ + 4³ + 5³ to 100³ = 35³ + 70³ + 85³

I would make a few changes for readability:

Rename:

$p3a → $cubes
$numlist → $cubeRoots

Hard-code $tnum.  It's not going to vary anyway, since it wasn't a parameter.
Eliminate $testmax.  It's not worth the effort to save a few loop iterations.
More generous horizontal spacing.  (You use lots of newlines in your source code, but need more spaces.)

Changing $numlist from a two-level array to a 1-dimensional array results in better readability as well as a performance improvement.

$i * $i * $i is simpler and faster than pow($i, 3).

Changing the termination condition of your inner loop results in an even more dramatic performance improvement.

Overall, this completes in about 1/3 of the time of the original code:

function funcC($n) {
    $exp = '³';

    $cubes = array();
    $cubeRoots = array();

    for ($i = 0; $i <= $n; $i++) {
        $j = $i * $i * $i;
        $cubes[$i] = $j;
        $cubeRoots[$j] = $i;
    }

    for ($i = 3; $i <= $n; $i++) {

        for ($j = 1; $j <= $i; $j++) {
            for ($k = $j; ($diff = $cubes[$i] - $cubes[$j] - $cubes[$k]) >= $cubes[$k]; $k++) {
                if (isset($cubeRoots[$diff])) {
                    echo " $i$exp  =  $j$exp + $k$exp + " . $cubeRoots[$diff] . $exp . '<br>' . PHP_EOL;
                    break;
                }
            }
        }

    }

}


Find the largest exponent x such that p^x evenly divides n

I would do an "early exit" in the case \$ p \le 1 \$ and
save an indentation level for the "main case":

if (p <= 1) {
    return -1;
}

The status variable is not needed, the while-loop can be
simplified to

int count = 0;
while (n % p == 0) {
    count++;
    n = n / p;
}

Your program should check if the input number \$ n \$
is zero, otherwise it will run into an infinite loop in that case.


Printing calculator - Stephen Kochan exercise

This seems correct, and it works. Some simplifications are possible.

Don't repeat yourself

These lines appear many times in the code:

printf("= %.3f\n", output);
scanf("%f  %c", &value, &operator);

You can move this part after the switch block to reduce duplication.

Remove unnecessary elements

The exit variable is written to but never read.
It seems unused, so I suggest to remove it.

Coding style

It would be easier to read if you indent the body of case statements.

It's recommended to use braces with all if-else statements.

I suggest to put a space after #include and before <stdio.h>

Suggested implementation

Putting together the suggestions above, your implementation becomes simpler and easier to read:

#include <stdio.h>

int main(void)
{
    float value, output;
    char operator;

    printf("Please enter a value and operator to begin\n");
    scanf("%f %c", &value, &operator);

    while (operator != 'e' || operator != 'E')
    {
        switch(operator)
        {
            case 'S':
            case 's':
                output = value;
                break;

            case '+':
                output += value;
                break;

            case'-':
                output -= value;
                break;

            case '*':
                output *= value;
                break;

            case '/':
                if (value == 0)
                {
                    printf("Division by zero\n");
                }
                else
                {
                    output /= value;
                }
                break;

            case 'E':
            case 'e':
                output += value;
                printf("= %.3f\n", output);
                return 0;

            default:
                printf("Unidentified operator\n");
                return 0;
        }
        printf("= %.3f\n", output);
        scanf("%f %c", &value, &operator);
    }

    return 0;
}


Best approach for the Design Pattern for multiple schedulers using interface and abstract class

It seems not a good idea to hard code the different constants. I would inject them through the constructor (I am using properties instead of Get-methods):
public sealed class Publisher : interfaces
{
    public void Publisher (string userType, string dataType, Timespan interval, string url)
    {
        UserType = userType;
        DataType = dataType;
        Interval = interval;
        Url = url;
    }

    public string UserType { get; }
    public override string DataType { get; }
    public override Timespan Interval { get; }
    public override string Url { get; }
}

Then create a factory
public static class PublisherFactory
{
    public static Publisher CreateCustomerRetroPublisher()
    {
        return new Publisher("Customer", "Retro", Timespan.FromMinutes(2), "CustRetroUrl");
    }

    ...
}

If you need different behaviors for different publishers, you can inject them this way as well. For instance, inject services for timeline-specific behavior (through a ITimelineService) and user type-specific behavior (through a IUserService). Like this you can combine the different behavior types in different ways. 3 timeline services + 4 user services = 7 services is better than 12 different classes.
The constructor would then have additional parameters
public void Publisher (string userType, string dataType, Timespan interval, string url,
    ITimelineService timeLineService, IUserService userService)

The services can be assigned to private fields, as they do not need to be visible publicly.
See also: Composition over inheritance (Wikipedia)


Calculate how many coins, coin values are 50, 20, 10 and 5

Invalid C code

OP’s C compiler may support various language extensions, but int &amount is not supported in standard C  @Ben Steffan. This makes the code less portable and harder to review.

// void GetNum(int &amount)
// scanf("%d%*c", &amount);
void GetNum(int *amount)  // Let caller pass the address of `amount` instead
scanf("%d%*c", amount);

Lack of error checking/weak end-of-line consumption

scanf("%d%*c", &amount); does not check the return value from scanf().  Should the user enter non-numeric data, nothing is scanned, amount will not be changed and offending input remains in stdin.
Alternative code;

int GetNum(int *amount) {
  printf("Enter an integer between 5 and 95 inclusive:\n");
  char buf[80];
  if (fgets(buf, sizeof buf, stdin)) return EOF;
  char ch;
  // Does input consists of one `int` and not trailing junk?
  if (sscanf(buf, "%d %c", amount, &ch) != 1) return 0; // Invalid input
  return 1; // success;
}

Unneeded ()

// return(change);
return change;

Consider standard true/false and bool.

// #define TRUE 1
// #define FALSE 0
// int Verify(int amount)
//   return FALSE;

#include <stdbool.h>
bool Verify(int amount)
  return false;

See also to use '#include ' in VS 2010
 and We also added the new headers ..., stdbool.h,

Thought for a likely next assignment:

Consider how to make 60c change when the available coins are only 50c,20c,20c,20c using the below algortim.

fifty = CalcChange(a, 50, 1);
twenty = CalcChange(a, 20, 3);
ten = CalcChange(a, 10, 0);


Generate code from full name and index number

Your code is quite confusing, are you new to Python? You seem to have some misunderstandings about how it works. First of all, no you don't need sys. Python scripts end automatically when they reach the end. You only need to call sys.exit() if you want to end a script in the middle of it for any reason.

Next, you're calling str on a string that's already a string. Based on the other variables you've defined this might be a placeholder, but it's confusing so it's worth saying that you're using placheolder values. I would also put it in as a number, except that you start the number with 0. An int can't have 0 as its first digit, so either you should be getting that number as a string (removing the need for str()) or there's something else going on here. Also I would suggest that you put the comment on a separate line, to be more readable.

# Converting number to str so it can concat
index_number = str('02001201525')

The from_index function is confusing. The name doesn't tell you what it does. It runs split but there's no need to if you just need the first 5 characters. It also probably shouldn't be a function. It has a very specific seeming use, takes no useful parameters and in the end just returns [0:5] on the string that's passed into it. It's easier to just do this:

index_number[0:5]

The only difference between that and your function is that your function would cut the result short if there was white space in the number, but that doesn't sound like it's what you want.

As for your generate_code, it does work for the most part, but is again a lot of lines to do something relatively simple. It also doesn't take index_number as a parameter even though it really should. I'd actually reduce it to one line, like this:

def generate_code(first_name, last_name, index_number):
    return first_name[-1] + last_name[2:4] + index_number[0:5]

Note that you also put in the wrong parameters to get the second and third parameters of last_name. I'm not sure if it was just a typo or misunderstanding, but I'll explain slicing if you need me to. Just comment and I can write up a bit about it.


Null check when enabling Up navigation in Android

Assuming java conventions are being followed, methods that begin with get should return an already-computed value with no business logic performed. In that case, the only real 'cost' tradeoff is the overhead of a second method call vs. the memory for new pointer to the value. Both should be insignificant. It's generally a matter of style as to which approach is preferable.


Style

Initializing of multiple variables on one line removes readability.
Writing for loops on one line removes readability.

Dead code should be deleted (// p = i + 1)

Bug

It seems that you have a little unnoticed bug in your code. Your loop

for (int i = 0; i < A.Length - 1; i++) {

misses the last element of your array.

Problem

Let us assume we have an array A containing 8 elements like

3 5 7 2 5 2 1 3

The ideal divider would be if the arrays left half summed up would be equal to the right half summed up.
Unfortunatetly here

sumLeft = A[0] + A[1] + A[2] + A[3] == 17
sumRight = A[4] + A[5] + A[6] + A[7] == 11
difference = sumLeft - sumRight == 6

So as we see that the left half > right half let us take the last element of the left side and check if 2 * A[half-1] <= difference wich is 2 * 2 <= 6 so we can do

sumLeft = sumLeft - A[3] == 15
sumRight = sumRight + A[3] == 13
difference = difference - 2 * A[3] == 2

Or simplified for sumLeft > sumRight

difference = sumLeft - sumRight;
while (2*A[currentHalf-1] <= difference)
{
    currentHalf = currentHalf -1;
    sumLeft = sumLeft - A[currentHalf]
    sumRight = sumRight + A[currentHalf]
    difference = difference - 2 * A[currentHalf];
}

EDIT : Based on @Dmitry's comments I rechecked the algorithm and came to the result that this algorithm only works for positive numbers.

And my implementation of the above

public int solution(int[] A)
{
    int length = A.Length;
    int sumLeft = 0;
    int sumRight = 0;

    int currentArrayHalf = length / 2;

    for (int i = 0; i < currentArrayHalf; i++)
    {
        sumLeft = sumLeft + A[i];
        sumRight = sumRight + A[i + currentArrayHalf];
    }

    Boolean isEven = length % 2 == 0;

    if (!isEven) { sumRight = sumRight + A[length - 1]; }

    int step = 1;
    if (sumLeft > sumRight)
    {
        step = -1;
        if (isEven)
        {
            currentArrayHalf--;
        }
    }

    int difference = Math.Abs(sumLeft - sumRight);
    if (difference == 0) { return difference; }

    while (currentArrayHalf >= 0 && currentArrayHalf < length && 2 * A[currentArrayHalf] <= difference)
    {
        sumLeft = sumLeft - A[currentArrayHalf];
        sumRight = sumRight + A[currentArrayHalf];
        difference = difference - 2 * A[currentArrayHalf];
        currentArrayHalf = currentArrayHalf + step;
    }

    return difference;
}


Getting JSON data from an HTTP response using conditional binding

To answer your explicit question with what is probably an obvious answer... Wrap it up in a function.

func debugSerialize(data: NSData) -> AnyObject? {
    let jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
    if(jsonData == nil) {
        print("Could not parse data")
    }
    return jsonData
}

Another option would be to let NSJSONSerialization.JSONObjectWithDatas thrown error propagate up the stack and have a centralized place to catch them and put the print there... Unless you are married to the idea that the rest of your code must run even if jsonData is nil...

Keep in mind that most of the code you have posted does nothing but print debug output. Once the debugging is complete all of that code can, and should, be removed (don't leave a bunch of debugging print statements in production code.) Once you do that, you will see that all your code really does is check to see of the JSON deserialization created a ReturnType object.

Likely, you need this code to do more than produce debug output on bad server responses, but I'm not able to review hypothetical code that you could have written.


Here are some of the quick performance wins you may get:

switch to using requests and reuse a Session instance which should provide a performance boost:

  if you're making several requests to the same host, the underlying TCP
  connection will be reused, which can result in a significant
  performance increase (see HTTP persistent connection).

import requests

session = requests.Session()

# iterate over v, t in the known table ranges
for v in range(2, 26):
    for t in range(2, 7):
        # download the webpage and find the elements
        url = "http://www.public.asu.edu/~ccolbou/src/tabby/%d-%d-ca.html" % (t, v)
        response = session.get(url)

use the fastest available underlying parser - lxml (requires to install lxml):

soup = BeautifulSoup(response, 'lxml')

parse only table elements from a page source via SoupStrainer:

parse_only = SoupStrainer('table')
soup = BeautifulSoup(response, 'lxml', parse_only=parse_only)

Requires importing SoupStrainer from bs4.

And, applying some bs4 related shortcuts, the HTML parsing part would transform into:

table = soup.table
for row in table('tr'):
    elements = []
    for cell in row('td'):
        value = cell.string
        if value is not None and value not in ("k", "N", "Source"):
            elements.append(value)


It is impossible to know the variable name without passing it separately because the name is not part of the object itself, but only one (of potentially many) signs pointing to that object. Expecting the object to know that variable name is like expecting a building to know which road you drove in on. Besides, specifying the localStorage key separately is a good thing - it allows you to refer to the same key using different names in different parts of the program.

You can get around having your methods show up in for-in loops by using getters instead of properties or prototypes. If you're concerned about compatibility, you can fallback to __defineGetter__.

Here's what I came up with.

function localObject(key) {
    var _this = JSON.parse(localStorage[key] || '{}');
    Object.defineProperty(_this, 'save', {
        get: function () {
            return function () {
                localStorage[key] = JSON.stringify(this);
            };
        }
    });
    return _this;
}

The new is optional - you can write both

var scores = new localObject('highscores'); // and
var scores = localObject('highscores');`.

While the above solution works, it is somewhat inefficient and messy. This stems from the fact that you're trying to get javascript to work the way you want, when what you should be doing is trying to understand how javascript wants to work. Each language has a style, even a personality, and if you're flexible enough to go with it then your code will be shorter, faster, and cleaner. Here's how I would abstract away my JSONification.

function local(key, value) {
    if (value === undefined) {
        return key in localStorage ? JSON.parse(localStorage[key]) : undefined;
    } else {
        localStorage[key] = JSON.stringify(value);
        return value;
    }
}

Now we can write code like this:

var score = local('highscore');
// use score like a normal variable, because it is one. then, eventually:
local('highscore', score);


Also If I'm missing any corner cases please let me know as this code is tested on very few examples as I didn't find any online problem that checks its appropriate output.

[emphasis mine]

Graph colouring is a relatively nice problem in that regard: you can easily check the validity of the result. The only conditions are that every vertex must have a color, the number of colors must be less-than-or-equal-to m, and neighboring vertices don't share a color. So as a test you could generate random graphs (or for small graphs, enumerate all symmetric graphs without self-loops), color them, and theck the results. Any valid coloring is appropriate. The main problem is testing whether graphs that your algorithm decides are not m-colorable are actually not m-colorable.

I suspected there was such an issue (as this algorithm never "uncolors" a vertex, it should be possible for it to get stuck) so I enumerated some graphs to find a concrete breaking test-case:

int n = 6, m = 3;
int[][] graph = {
    {0, 1, 0, 0, 1, 1},
    {1, 0, 1, 1, 0, 1},
    {0, 1, 0, 1, 0, 0},
    {0, 1, 1, 0, 0, 1},
    {1, 0, 0, 0, 0, 0},
    {1, 1, 0, 1, 0, 0}};

This algorithm results in [1, 2, 1, 3, 3, 0], the zero indicating that no valid coloring was found, but there actually are valid colorings, for example [1, 2, 3, 1, 2, 3]. Just to confirm that it's a valid coloring, here it is as a drawing:

Keep in mind though that if there is one valid coloring, there are almost always many more. Even if there are no fundamentally different colorings, the color-names can be permuted to yield a superficially different-looking coloring. So test-cases should not compare for equality with some coloring found by a different solver, that's too strict.

To find that case I had to implement an other graph colorer that is capable of coloring the graph above, I used this small rewrite of your code:

static int[] graphColor(int m, int[][] graph) {
    int[] colors = new int[graph.length];
    // the color of the first vertex is a free pick
    colors[0] = 1;
    if (graphColorInternal(1, m, colors, graph))
        return colors;
    else
        return null;
}

static boolean graphColorInternal(int k, int m, int colors[], int graph[][]) {
    for (int c = 1; c <= m; c++) {
        if (isSafe(k, c, colors, graph)) {
            colors[k] = c;
            if (k + 1 < colors.length) {
                if (graphColorInternal(k + 1, m, colors, graph))
                    return true;
                colors[k] = 0;
            }
            else
                return true;
        }
    }
    return false;
}

static boolean isSafe(int k, int c, int[] colors, int graph[][]) {
    for (int i = 0; i < colors.length; i++) {
        if (graph[k][i] == 1 && c == colors[i])
            return false;
    }
    return true;
}

In addition to the line colors[k] = 0; which gets the solver "unstuck" after backtracking, there are some more changes that I would like to highlight:

The function graphColor that is supposed to be called returns its result, rather than modifying a function argument. Generally you should prefer that. Output-parameters should be avoided, unless there is a good enough reason not to.
graphColor does not take redundant parameters (n, which it knows from the graph itself).
The search indicates explicitly whether it found something or failed, so the wrapper does not have to inspect the coloring to find that out.
The search returns immediately after finding a valid coloring. The original algorithm does not return immediately, it tries to fill in different colors though most of it fails because isSafe returns false a lot when given a filled coloring.

  I would like review about its performance, time complexity and improvements.

Not much can be done about the time complexity, not for the worst case anyway: graph coloring is NP-complete after all.

But there are things that can be done.

Rather than coloring the vertices simple in order of their index, color them in order of Most Constrained Variable (MCV) first, that is, color the vertex with the most colored neighbors first.
Maintain a set of "possible colors" for every vertex. This makes it easy to detect early that the current partial-coloring is no good (if any vertex has an empty set of colors left, backtrack), and easy to find the MCV (uncolored vertex with the smallest set of possible colors). It also means that rather than checking isSafe for every color, the solver already has a list of possible colors - though of course it pays for that by maintaining those sets every time the color of a vertex is changed.
Advanced: improve those sets of possible colors with the AC-3 Algorithm or similar.


Easily! You can use a regular expression to match page[1-7].html and also search/?:

if ($('.content').length && document.referrer.match(/page[1-7]\.html|search\/\?/)) {
        window.location.href = document.referrer;
};

And never write conditions in such wasteful way:

if (A && B || A && C || A && D) {

when it can be easily simplified to:

if (A && (B || C || D)) {


Regex for matching expression that consists of single digit numbers and operators

While your regex appears to work, it will fail for the condition that your expression should not exceed 100 characters mark. With the boundary of {0,99} on a 2 character pattern \d{1}[\*\+]{1}, you are already expecting a possible expression of length 198 characters.
Using {1} quantifier is just redundant.
No need for escaping inside a character set. The only things needing a leading backslash (\) inside a characters list are ] and ^, where the caret is the only character inside, or the first.
Your expressions will not reach a 100 character mark, unless you allow the + to act as an unary operator.

Therefore, the following pattern will be the simplest approach (imo)

^(?:\d[*+]){0,49}\d$

which is the tiniest bit modified from your original expression.

You can check the pattern in action here on the following expressions:

1+2*3*8+0
9
9*9
1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8

1++1
12+1
2*25
1+
47
+
+1
11
1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8+9


Grid search parameter combinations in Python

split
The method does a few things at the same time.

It expands the ranges
generates the combinations
takes the sums
compares to the target
assembles a DataFrame

better would be to split it up in a few logical units. This will not only help freeing memory in-between steps, but also help with debugging the intermediate values
looping
Check the talk "Looping like a pro"
You loop over the index, and end up with real long variables like ranges[parameter][0]. If you use tuple expansion, you can do this:
def expand(ranges, increment):
    for start, end in ranges.values():
        expansion= list(np.arange(start, end, increment))
        # np.arange() is exclusive of the upper bound, let's fix that
        if expansion[-1] != end:
            expansion.append(end)
        yield expansion

For me, this is a lot clearer. It also has the benefit of keeping the lines shorter.
Since it are more the expansions of the ranges you create instead of the combinations, I renamed the method and variables.
This also uses a generator instead of an intermediate list.
This alternative might even simpler:
def expand(ranges, increment):
    for start, end in ranges.values():
        yield  np.arange(start, end + increment/2, increment)

This can then be combined and summed like this:
def combine_naive(expansions, target):
    for combination in itertools.product(*expansions):
        # using np.isclose() so that the algorithm works for floats
        if np.isclose(sum(combination), target):
            yield combination

I like your comment there. It explains why you use np.isclose instead of ==
Alternative approaches
numpy
instead of having itertools.product assemble the combinations, you could use numpy.meshgrid
def combine_numpy(expansions, target):
    grid = np.meshgrid(*expansions)
    summary = np.array(grid).sum(axis=0)
    indices = np.where(np.isclose(summary, target))
    return (
        [row[i] for row, i in zip(expansions, idx)]
        for idx in zip(*indices)
    )

This is approximately the same, but staying in the numpy universe. You can reduce the memory footprint here with the correct choice of dtype and reducing the number of intermediary variables
sorted
or you could use the fact the expansions are sorted, and break when a sum is over the target. This uses recursion, tuple unpacking and the fact an empty sequence is Falsey.
def combine_sorted(expansions, target, previous=()):
    series, *rest = expansions

    sum_max = sum(item[-1] for item in rest)
    for item in series:
        current = previous + (item,)
        sum_current = sum(current)
        if rest:
            if sum_current + sum_max < target and not np.isclose(
                sum_current + sum_max, target
            ):
                continue
            yield from combine_sorted(rest, target, previous=current)
        else:
            if np.isclose(sum_current, target):
                yield current
            elif sum_current > target:
                return

The sum_max is to skip numbers where the total some will be less than target as soon as possible.
testing and timing with real data will show which option is more memory and CPU intensive.
if __name__ == "__main__":
    ranges = {"a": (95, 99), "b": (1, 4), "c": (1, 2)}
    increment = 1.0
    target = 100.0
    df = solution(ranges, increment, target)

    expansions = list(expand(ranges, increment))
    results = list(combine_naive(expansions, target))
    df1 = pd.DataFrame(results, columns=ranges.keys())
    print(df1)

    results_sorted = list(combine_sorted(expansions, target))
    print(results_sorted)
    df_sorted = pd.DataFrame(results_sorted, columns=ranges.keys())
    print(df_sorted)

    results_numpy = list(combine_numpy(expansions, target))
    print(results_numpy)
    df_sorted = pd.DataFrame(results_numpy, columns=ranges.keys())
    print(df_sorted)


Here's a one liner for you (since the question asks for the minimum number of lines):

encode = lambda s: "".join([(c if (i+1) % 2 == 0 else chr(ord('a') + (ord(c) - ord('a') + i + 1) % 26)) for i, c in enumerate(s)])


Loading the JDBC driver jar dynamically from external location

There is a possible performance issue in connecting and disconnecting from a database with each request.  Setting up a connection can be expensive, so if these connections are not pooled/cached/reused on the driver level, you may want to look into libraries or techniques for JDBC connection pooling.

(Also be sure to close connections you get from your driver.  Database connections are external resources that can not be reliably handled by the garbage collectors, and need to be explicitly cleaned up.)

As far as I can tell, you already have the driver you want; why work through DriverManager?  Ask your driver for the connection:

  Connection   connect(String url, Properties info)

  Attempts to make a database connection to the given URL.

The reflection workaround assumes that the system class loader is an URLClassLoader and that you have the privileges to call its addURL method.  That's not necessarily true, especially for a server environment.

And, uh, I don't think it really needs saying, but the error handling is... less than optimal. ;-)


Quicker way to go through 550 variables with very similar code

This is an odd code review for me. I could talk about giving your variables meaningful names, proper indentation, avoiding activate and select, extracting functions/subs, looping over ranges using a For Each, etc. , but I'm not going to talk about any of that. Because you don't need code to do this at all.

With some patience, you should be able to craft a native excel formula that does all of this. It will be less readable than code, but it will also be exponentially faster.

Let's start here:

wsMaster.Cells(i, 3) = Application.VLookup(wsMaster.Cells(i, 1), Vrange, mf_pLN, 0)

and translate this into a formula.

=VLOOKUP("[MasterTab]!$A2","[Sheet2]!A:ZA",mf_Pln,FALSE)

We obviously can't use a variable there, so let's take a look at how we get that value.

mf_pLN = Application.Match(mf_pLN_TEXT, Mrange, 0)

Okay, so let's nest that into our function.

 =VLOOKUP("[MasterTab]!$A2","[Sheet2]!A:ZA",Match(A$1, "[Sheet2]!$A$2:$ZA$2", 0),FALSE)

Take careful note of the dollar signs. They make the reference absolute, so the reference cell doesn't change as the formula gets copied into new cells. Those without a $ are relative and will "move with" the cells.

Now, just nest this inside of your COUNTIF and you have a formula ready to go into your worksheet. Fill right, then down.

Of course, this works on a single specified worksheet. You'll still need to loop through all of the worksheets to actually build your final formula. Replacing the target sheet name accordingly.

It's going to be nested deep, but a considerably faster solution using formulas versus VBA.


Grab set of data from database that matches userid and return it to the view

Use an anonymous type to store a single object retrieved from the database and then populate your view from this temporary (and anonymous) object.

Answering from my mobile, so I apologize if this doesn't compile.

public ActionResult EditUserAccount()
{
            UserAccountViewModel editUserAccountViewModel = new UserAccountViewModel();
            db_user user = new db_user();
            editUserAccountViewModel.UserName = UserSession.GetValue(StateNameEnum.UserName, StateNameEnum.UserName.ToString()) as string;

            var user = context.db_user.Where(x => x.UserId == editUserAccountViewModel.UserId)
                .Select(x => new {x.Title, x.FirstName, x.LastName, x.PhoneNumber, x.AltPhoneNumber, x.EmailAddress } );

            editUserAccountViewModel.Title = user.Title;
            editUserAccountViewModel.FirstName = user.FirstName;
            editUserAccountViewModel.LastName = user.LastName;
            editUserAccountViewModel.PhoneNumber = user.PhoneNumber;
            editUserAccountViewModel.AltPhoneNumber = user.AltPhoneNumber;
            editUserAccountViewModel.EmailAddress = user.EmailAddress;
            return (PartialView("~/Views/Account/UserAccount.cshtml", editUserAccountViewModel));

}

This lets you hit the database once instead of once per property.


VueJS to do list - handling clear event on input

DOM references

If you are using functions to lookup DOM elements (e.g. document.getElementById()) for elements contained within the root element (or component), it might likely be the wrong way of doing things, as far as VueJS code goes. With VueJS, you can use v-model to bind the value of the input to a data property - for example, the <input> for the new list item can have a v-model attribute added, like:

<input v-on:keyup="removeError" type="text" id="list-input" v-model="newItem">

And it would be wise to add an entry in the data object for that model value:

data: {
    todos: [],
    //...
    newItem: ''

Then when creating an item, use this.newItem for the value.

Conditional Rendering

The error message can be conditionally rendered using v-if (or v-show, depending on how the DOM should be laid out in various cases). Read more about conditional rendering here.

That way there is no need to lookup the DOM element and set the style to display: block, display: none, etc.

Method context

In the method toggleSeen() the variable app is used, but realize that the method is called in the context of app so this can be used instead (of app).

Computed properties

Use computed properties to control values that depend on other values. For example, the button text can be added to a computed property. Remove button from data and then add a computed property:

computed: {
    button: function() {
      return {
        text: this.seen ? 'Hide' : 'Show'
      };
    }
  }

That way the logic for the text property can be removed from the method toggleSeen(). Then that method call could be replaced by an inline expression, or else a checkbox could be used with the v-model attribute bound to seen.

// components
Vue.component('todoitem', {
  template: "
Test Item
"
})

// app code
var app = new Vue({
  el: '#app',
  data: {
    todos: [],
    seen: true,
    showError: false,
    newItem: '',
  },
  computed: {
    button: function() {
      return {
        text: this.seen ? 'Hide' : 'Show'
      };
    }
  },
  methods: {
    addItem: function() {
      this.showError = (this.newItem == "");
      if (!this.showError) {
        app.todos.push({
          text: this.newItem
        });
        this.newItem = '';
      }
    },
    removeItem: function(index) {
      this.todos.splice(index, 1);
    },
    removeError: function() {
      this.showError = false;
    },
    toggleSeen: function() {
      this.seen = !this.seen;
    }
  }
});
#app {
  width: 900px;
  padding: 2em;
  margin: 0 auto;
}

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

li:hover .todo-list__delete {
  display: inline-block;
}

Add an Item to the list

      {{ todo.text }}
      Delete

  <input v-on:keyup="removeError" type="text" id="list-input" v-model="newItem">
  <input type="submit" id="list-submit" v-on:click="addItem">
  Please Enter Text

    <todoitem></todoitem>

SEEN

  <button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>