Introducing custom validators!

Assuming you validate your dates with this "fresh" syntax:

validates :reservation_start,        # Note the comma!
  availability: true                 # ...and some other validations
validates :reservation_end,
  availability: {name: "End date"}   # same here

Define this validator separately, a common place is app/validators, in this case that file would be named availability_validator.rb

class AvailabilityValidator < ActiveModel::EachValidator

  # `each` stands for 'each attribute with a validation'
  def validate_each(record, attribute, value)
    # Args: a model instance, a symbol of attribute and a value it has
    # You also get a hash in `options`
    # If you specified validation as `availability: true`, you wouldn't get it

    reservations = Reservation.where(["transport_id =?", record.transport_id])
    date_ranges = reservations.map { |e| e.reservation_start..e.reservation_end }

    date_ranges.each do |range|
      if range.include? value
        errors.add(attribute, "#{options[:name] || 'Date'} not available")
      end
    end

  end
end

Sure this example needs some refinement, but it demonstrates most tools you have at hand.

The first validation gets no options, because there's true specified, we avoid errors by using a default name with ||. Not the best practice (merging with a separate hash with defaults is), but when you don't have many parameters and places, that will do.
Extraction of transport_id into options could come in handy if validation like this is broadly used.
"Availability" is a bit too common term, you might need to rename this class.
Stuff like error messages and attribute names is better be put into a locale file and fetched using I18n.t 'some.key.name'.
You're doing too much on Ruby side. When armed with a relational database, you can do stuff like this:

Reservation.where(transport_id: transport_id). # period tells there are further calls
  where("reservation_start <= :date AND reservation_end >= :date", date: value).
  exists? # returns true if there's a reservation with our value in range

If a lower bound is smaller and the upper bound is bigger than our balue, then our value is in the range of that entry. SQL can handle it.
There is a possible error: the validation (even yours) will false-accept the range if the submitted range encloses one existing range completely (start and end are both outside bounds of any other range). I'm not sure if that's what you want, so be advised. This can be fixed by an extra validation, I'm leaving this up to you.


Do you really anticipate the data model changing so much that this needs to be ultra flexible?  In order to do so the code is quite complex - for instance having a forEach inside of an if inside of a forEach inside of a map.  You already have model specific checks in the code anyways, such as the check for the 'sickLeave' and 'holidayLeave' keys.  I think a solution along these lines would be perfectly acceptable:

const initialNormalizedVals = {
  "sickLeaveDifferance": [],
  "sickLeaveRevision": [],
  "sickLeavePaid": [],
  "holidayLeaveDifferance": [],
  "holidayLeaveRevision": [],
  "holidayLeavePaid": [],
  "received": [],
  "taken": [],
  "result": [],
}

const normalizedData = data.periods.reduce((outcome, { sickLeave, holidayLeave, received, taken, result }) => {
  outcome.sickLeaveDifferance.push(sickLeave.differance)
  outcome.sickLeaveRevision.push(sickLeave.revision)
  outcome.sickLeavePaid.push(sickLeave.paid)
  outcome.holidayLeaveDifferance.push(holidayLeave.differance)
  outcome.holidayLeaveRevision.push(holidayLeave.revision)
  outcome.holidayLeavePaid.push(holidayLeave.paid)
  outcome.result.push(result)
  outcome.taken.push(taken)
  outcome.received.push(received)

  return outcome
}, initialNormalizedVals)

const transformedData = Object.keys(normalizedData).map(key => {
  return {
    name: key,
    result: normalizedData[key],
  }
})


A couple of basic string parsing functions

If you are using ColdFusion 9+, you should abandon your vars within functions and move toward using the LOCAL scope.  LOCAL vars do not escape the function.

This:

<cfset var last = getLast(arguments.str)>
<cfset var lastLen = len(last) + 1>
<cfset var thisLen = len(str) - lastLen>
<cfset var returnVar = str>

Should be:

<cfset LOCAL.last = getLast(arguments.str)>
<cfset LOCAL.lastLen = len(LOCAL.last) + 1>
<cfset LOCAL.thisLen = len(LOCAL.str) - LOCAL.lastLen>
<cfset LOCAL.returnVar = str>


If you have only valid Roman numbers you could use a simpler algorithms.  (i.e IIV is invalid )

  The symbols "I", "X", "C", and "M" can be repeated three times in succession, but no more. (They may appear more than three times if
  they appear non-sequentially, such as XXXIX.) "V", "L", and "D" can
  never be repeated. A common exception to this is the use of IIII on
  clocks; see below.
  "I" can be subtracted from "V" and "X" only. "X" can be subtracted from "L" and "C" only. "C" can be subtracted from "D" and "M" only.
  "V", "L", and "D" can never be subtracted
  Only one small-value symbol may be subtracted from any large-value symbol.

Just (string-)replace IV by IIII, IX by VIIII and so on. Afterwards you just have to sum the numbers from left to right.


This code could do with some editing...

First of all is the spacing. It is absolutely horrible (we will fix that after the edits).

Also, the naming is horrible. Scanner x could be scanner and y could be num. As for z, it is completely unnecessary:

for (i = 2; i < y; i++) {
    long z = y % i;
    if (z != 0)
        continue;
    System.out.print(i + " , ");
}

Becomes:

for (i = 2; i < y; i++) {
    if (y % i != 0)
        continue;
    System.out.print(i + " , ");
}

The program can do without the continue statement:

for (i = 2; i < y; i++) {
    if (y % i == 0)
        System.out.print(i + " , ");
}

It's also a good idea to put braces around statements in an if statement, even when there is only one:

for (i = 2; i < y; i++) {
    if (y % i == 0) {
        System.out.print(i + " , ");
    }
}

You are also wasting time going through for loops doing nothing. After all, num's largest factor before itself possible is num / 2, which makes it more efficient doing it like this:

for (i = 2; i <= num / 2; i++) {
    if (num % i == 0) {
        System.out.print(i + " , ");
    }
}

I also noticed:

 public static void main(String args[])

It is better to put [] at the type (String):

public static void main(String[] args)

But the main problem is that you have a memory leak. It could be solved by closing the Scanner:

scanner.close();

Final code:

Your final code will look like this:

public class PrimeNum2 {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number :  ");
        long num = scanner.nextInt(), i;
        System.out.print("Divisors of " + num + " = 1 , ");
        for (i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                System.out.print(i + " , ");
            }
        }
        System.out.println(num);
        scanner.close();
    }
}


Arbitrary precision Euler-Mascheroni constant via a Brent-McMillan algorithm with no math module

The single largest optimization I was able to make was to the logarithms. Once the two terms of a AGM are the same, they will not differ again. Therefore you can be sure you have converged. The argument of oscillating convergence does not apply.

I also noticed that, code aside, y=2^x+8; AGM(1, y) converges the fastest out of the numbers. I don't know the exact Math behind AGM convergence rates but I noticed that.(therefore in the script, put precision as 2^x -1 for ultra fast Ln convergence)

Since this is my own answer, I'm fine with me putting gmpy2 in places to make the computations faster.

I computed 212,143 digits of Gamma in 3.5 hours with the script. Usable precision into the thousands is done in less than  breath :) .

import decimal
from tqdm import tqdm
from gmpy2 import mpc
import gmpy2

def agm(a, b):
    """Arithmetic Geometric Mean"""
    a, b = D(a),D(b)
    for i in tqdm(range(prec)):
        a, b = (a + b) / 2, (a * b).sqrt()
        if a == b:
            break
    return a

def pi_agm():
    """Pi via AGM and lemniscate"""
    print('Computing Pi...')
    a, b, t = 1, D(0.5).sqrt(), 1/D(2)
    p, pi, k = 2, 0, 0
    while 1:
        an    = (a+b)/2
        b     = (a*b).sqrt()
        t    -= p*(a-an)**2
        a, p  = an, 2**(k+2)
        piold = pi
        pi    = ((a+b)**2)/(2*t)
        k    += 1
        if pi == piold:
            break
    return pi

def lnagm(x):
    """Natural log of via AGM"""
    if x == D(1):
        return 0
    if x == D(2):
        return lntwo()
    m = prec*2
    ln2 = lntwo()
    decimal.getcontext().prec = m
    pi = pi_agm()
    print('Coverging on Ln({0})...'.format(x))
    twoprec = (D(2)**(2-m))/x
    den = agm(1, twoprec)*2
    diff = m*ln2
    result = ((pi/den) - diff)
    logr = D(str(result)[:m//2])
    decimal.getcontext().prec = prec
    return logr

def lntwo():
    """Fast converging Ln2"""
    print('Computing Ln(2)...')
    def lntwosum(n, d, b):
        logsum, logold = mpc(0), mpc(0),
        e, n, d = mpc(0), mpc(n), mpc(d)
        while True:
            logold = logsum
            logsum += (1/((b**e)*((2*e)+1)))
            e += 1
            if logsum == logold:
                return (n/d)*logsum
    logsum1 = lntwosum(14, 31, 961)
    logsum2 = lntwosum(6, 161, 25921)
    logsum3 = lntwosum(10, 49, 2401)
    ln2 = logsum1 + logsum2 + logsum3
    return D(str(ln2.real)[:-4])

def gamma():
    n = D(prec)
    a = u = mpc(str(-lnagm(n)))
    print('Computing Gamma...')
    b = v = mpc(1)
    i = mpc(1)
    while True:
        k = (n/i)**2
        a *= k
        b *= k
        a += (b/i)
        if (u+a) == u or (v+b) == v:
            break
        u += a
        v += b
        i += 1
    return D(str(u/v)[:prec-3])

if __name__ == "__main__":
    """Setting precision plus 5 to accomodate error"""
    prec = int(input('Precision: '))+5
    gmpy2.get_context().precision=(prec*4)
    decimal.getcontext().prec = prec
    D = decimal.Decimal
    gam = gamma()
    print(gam)


Not bad.  However, we can do away with if component not in address_components and component is not "".

A better way to check if component not in address_components would be to use collections.OrderedDict:

  An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

That's exactly what we want.  (Well, almost exactly.  What we really want is an ordered set, but we can just use the keys of an OrderedDict and ignore the values.)

We can eliminate the need for component is not "" by using str.split() instead of str.split(" "):

  If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

To get rid of the commas, you don't need a regular expression.  str.replace() will do.

It's bad practice to use the same variable (address) for two different purposes, especially when the type changes (from a list of strings to a string).

With those changes, we can write the solution as just a single expression.

from collections import OrderedDict

obfuscated_address = …
address = ' '.join(
    OrderedDict(
        (component, None) for component in
        ' '.join(obfuscated_address).replace(',', '').split()
    ).keys()
)


Your code is pretty good, but some of your logic isn't.

The game loop should be structured differently.
Also I'm ignoring second_chance.

There are two main things that should happen after I pick a number:

I'm correct, you say I win and the game ends.
I'm wrong, you tell me if I'm higher or lower.

This in psudocode could be:

while True:
    user-input = get-user-input()
    if user-input == random-number:
        stop game
    else:
        display if user is higher or lower.

This should highlight that it's pretty much Python.
And we could do with another function.

First, stop game should exit out of the game, and tell us if we won or not.
This can simply be return True.

The logic to display if the user is higher or lower then the guess is an if and an else.
If the guess is larger then you want to display "A bit lower ..." otherwise (the else) "Guess higher ...".
To do this simpler I will use a turnery operator.

And so it'd be:

guess_text = "Take a guess."
random_number = random.randrange(1,21)
while True:
    user_number = int(raw_input(guess_text))
    if user_number == random_number:
        return True
    else:
        guess_text = "A bit lower..." if user_number > random_number else "Guess higher..."

Ok so we now have a solid loop, but it's not much of a game.
And the rest of your elif's are pretty good here.
I'd change the attempts = 0 to return false and remove the continue.

This should get you:

guess_text = "Take a guess."
random_number = random.randrange(1,21)
attempts = 0
maximum_attempts = 7
while True:
    user_number = int(raw_input(guess_text))
    if user_number == random_number:
        print "Well done %s, You beat me!" %(user_name)
        return True
    else:
        guess_text = "A bit lower..." if user_number > random_number else "Guess higher..."

        attempts += 1
        if attempts == maximum_attempts:
            print "Sorry %s, You lost!" %(user_name)
            return False
        print "You have %s  lives left." %(maximum_attempts - attempts)

Now you should know that return is only allowed in a function.
This means you need to make a function that gets passed the user_name.
So:

def play_game(user_name):
    guess_text = "Take a guess."
    attempts = 0
    ...

Finally you want to be able to play multiple games!
I'll use second_chance for the basis for this loop.

You should change quit() to break.
Remove the continue.
Put all the prints and definition for user_name at the top (not in the loop).
Rename it as main.

This should get you:

def main():
    print "Guess my number!"
    print " What's your name?"
    user_name = raw_input()
    print "Hello %s, i'm thinking of a number between 1 and 20." %(user_name)
    while True:
        choice = raw_input("wanna give it another shot?(y/n)")
        if choice == "y":
            play_game(user_name)
        elif choice == "n":
            break
        else:
            print "That wasn't a (y) or (n)!, Try again."

Finally I'd recommend using str.format over %.

So as you should guess, your code was pretty good!
Apart from the duplicate questions.


Finding Second Largest Element in an Array

Inefficient algorithm

As stated in the comments, the algorithm is actually pretty convoluted. One cannot find the maximum without looking at all of the elements, if they don't have any idea about the pattern of the input.

On top of that, it allocates quite a lot of memory.

Non-standard C++

VLA (variable length array) is not part of C++. It might be an extension in your compiler

Using C++ as C

The code is extremely imperative. It has a lot of control that it doesn't use, and doesn't have any benefit over standard algorithms. It is also bound to int arrays, to pointers, in fact. May be as C code it would be ok (if algorithm problems are fixed), but this is not effective usage of C++ features.

Benchmarking

Usually when seriously talking about performance people also use benchmarks. Having some real statistics on multiple platforms will strengthen your argument.

Alternative approach

Now that we know that we need to pass through anyway, lets write simple loop over the whole range:

#include <functional>
#include <array>
#include <utility>

template <typename ForwardIterator, typename Compare = std::less<>>
std::array<ForwardIterator, 2> find_2greatest(ForwardIterator first,
                                              ForwardIterator last,
                                              Compare cmp = {})
{
    if (first == last)
    {
        return {first, first};
    }

    auto greatest = first;
    auto runner_up = greatest;

    for (++first; first != last; ++first)
    {
        if (cmp(*runner_up, *first))
        {
            runner_up = first;
            if (cmp(*greatest, *runner_up))
            {
                std::swap(greatest, runner_up);
            }
        }
    }

    return {greatest, runner_up};
}

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> v{1, 1, 2, 3, 4, 5, 6};

    auto greatest2 = find_2greatest(std::begin(v), std::end(v));

    std::cout << "the greatest: " << *greatest2.front() << '\n'
              << "second greatest: " << *greatest2.back() << '\n';
}

The code doesn't return the objects themselves. They might be non-copyable, or user might want only the location of those elements. In general, C++ search algorithms usually return iterators. Also it is not bound to only vectors or ints, it can work on anything that allows multiple passed over the range. Your naming might be better than mine though.


midpoint()

This function could be written more elegantly using zip(), and it would work for any number of dimensions. (I suspect it might be slower, though.)

def midpoint(p1, p2):
    """
    Find the midpoint of two cartesian points.
    """
    return tuple((c1 + c2) / 2 for c1, c2 in zip(p1, p2))

translate() and image_rep()

Since translate() gives a result in Pillow coordinates, I think that the result should be quantized as integers. You should round to the nearest integer rather than truncating.

Pillow coordinates increase towards the right and towards the bottom.  Conventionally, cartesian coordinates increase towards the right and towards the top.  I would therefore incorporate a reflection of the vertical axis in the translation.

I don't see why the image must be square.

You can just pass point instead of packing it into a new tuple.

translated = translate(point, img_size)

I suggest hiding these two helper functions inside a plotting routine. (See below.)

play_chaos()

I would split this into the mathematical concept and its visualization.

def chaos_points(attractors, start_point):
    attractor_stream = (random.choice(attractors) for _ in itertools.count())
    return itertools.accumulate(itertools.chain([start_point], attractor_stream), midpoint)

def plot(img, points):
    half_width, half_height = img.size[0] / 2, img.size[1] / 2
    to_pillow = lambda p: (int(round(half_width + p[0])), int(round(half_height - p[1])))
    for point in points:
        img.putpixel(to_pillow(point), 1)

Demo

Your GUIDERS don't form an equilateral triangle as suggested.

def main():
    """
    Create an image and populate it with chaos.
    """
    IMAGE_SIZE = 300, 300
    SEED = (0.0, 0.0)
    GUIDERS = [(-100.0, -50 * 3**.5),
               (+100.0, -50 * 3**.5),
               (   0.0, +50 * 3**.5)]
    img = Image.new('1', IMAGE_SIZE)
    plot(img, itertools.islice(chaos_points(GUIDERS, SEED), 1000))
    img.save('chaos.png')

if __name__ == '__main__':
    main()


To answer your questions:

Sure looks like it.
No, see next point.
No, it is not safe. std::mersenne_twister_engine::operator() reads and increments its internal state. AFAIK, this makes it not thread safe at all.

So, here are a few suggestions:

An extra semicolon hid itself in your code:

std::cout << result.get() << std::endl;;
                                       ^

Don't use std::endl. It implicitly uses std::flush to flush the stream. This is not very cheap, so it is better for performance if you just output '\n'.

If you do want to flush the stream, it would be better to state your intent and use std::flush, but this depends on you.
Mark functions that do not throw noexcept. That way, you state your intent that the functions will not throw, and it helps the compiler optimize a bit.
Currently, your shuffle takes a container. While that is desirable in most cases, sometimes, you just need to shuffle a subrange of a container. It's for exactly this reason that all the standard algorithms take an iterator pair instead of a container.
If you try to include Random.h more than once, you will get symbol collision for the variable generator. The same thing happens for functions. Here's what you can do:

Use C++17, and mark the variable inline, which behaves exactly like in functions:

thread_local inline std::mt19937_64 generator(std::random_device{}());

Mark the variable extern, and put its definition in Random.cpp.

You don't need return 0; at the end of main(). The compiler implicitly adds it for you.
I like to use types as parameter that try to match the preconditions of a function. For example, I would use unsigned integers everywhere where you use signed integers, because I do not see the point in calling let's say random_walk with a negative number_of_steps.
You can shorten the definitions in Random.cpp by removing Random:: if you wrap them around namespace Random, like in the declarations.


I would suggest putting all the code in main() except for the imports. Then at the bottom, do

if __name__ == '__main__':
    main(sys.argv)

The advantage of structuring your file this way is that you can run the python interpreter and import your code and play with it. If you break it up into multiple routines, you can run each routine by itself to be sure it does the right thing. As it is now, if you try to import the file, half the code will be run immediately and then main() gets run unconditionally at the bottom, so you can't control it easily in the python interpreter.
To translate email_provider to smtp_server, you could do

host = {'GMAIL': "smtp.gmail.com",
        'GOOGLE': "smtp.gmail.com",
        'AOL': "smtp.aol.com",
        'YAHOO': "smtp.mail.yahoo.com",
        'COMCAST': "smtp.comcast.net"}

smtpserver = smtplib.SMTP(host[email_provider.strip('!').upper()], 587)

And you might want to handle the case where the user types an unknown email provider.

try:
    smtpserver = smtplib.SMTP(
          host[email_provider.strip('!').upper()], 587)
except KeyError:
    print("Unknown email provider '%s'" % email_provider)
    sys.exit(1)

Instead of making the user type 'y' to run again every time, you could do something like this:

while True:
    sendto = raw_input("Target address (or just hit ENTER to quit) > ")
    if sendto == '':
        sys.exit(0)
    to = CC = sendto
    ...


Does refactoring a while loop increase CPU usage?

Well, after more resarch and testing, it appears that the GetConsumingEnumerable() method of the BlockingCollection<T> is actually blocking when there are no items to consume. And it handles the case where the collection is completed as well.

The final touch, it that, instead of using a ManualResetEvent to signal the consumer to stop, like the original code, I'm using a CancellationToken instead.

This allows me to simplify the code drastically.

Here is the final snippet:

    protected override void Run(string[] args)
    {
        try
        {
            foreach (var item in queue_.GetConsumingEnumerable(cancellation_.Token))
            {
                tasks_.Add(CreateWorkItemHandler(item));
                if (tasks_.Count == MaxConcurrentHandlers)
                    WaitAndDiscardAnyCompletedTask();
            }
        }
        catch (OperationCanceledException /* e */)
        {
        }

        while (tasks_.Count > 0)
            WaitAndDiscardAnyCompletedTask();
    }

PS: I should have done more testing before posting. But, I'm leaving the question and its answer here for reference.


Your is_operator function can be rewritten as
return token == '+' || token == '-' || token == '*' || token == '/' || token == '^';

Much cleaner, in my opinion.

The program has a memory leak. Your tokenize function allocates a struct token on the heap, but the object is never freed.
Better yet, instead of returning a struct token*, just return a struct token. The struct certainly isn't large enough to warrant an allocation on the heap.

Instead of checking whether token is an operand by comparing operator to 0, use an enum.
typedef enum {
       TokenType_Operator,
       TokenType_Operand
} token_type;

Then your token struct can consist of the token_type enum, and an union.
struct token
{
   token_type type;
   union {
       char operator;
       float operand;
   } data;
};

If you're using C11, you don't even need to name the union anything.

As a next step, try to implement a tokenizer that tokenizes in one pass. Right now, your tokenizer 1) removes whitespace (which involves a linear pass) and 2) copies of the rest of the string after the tokenizing an operand into the original buffer. If you have a large buffer, this could become a bottleneck.
A common way to implement a tokenizer is using a DFA (deterministic finite automata). In fact, a DFA is a starting point for most handwritten lexers.


How can I improve the design of this serialization mechanism?

You can use an internal traits type to reduce redundancy and complexity.

template< typename serialized >
struct serialize_traits; // no implementation of general case

enum class serialize_style {
    string,
    integral
};

typedef std::vector< char > serial_type; // consider std::string instead

template<>
struct serialize_traits< char * > {
    static const serialize_style style = serialize_style::string;
};

template<>
struct serialize_traits< std::string > {
    static const serialize_style style = serialize_style::string;
};

// Since serializer has no state, I broke this into a free function.
/* It works with both char * and std::string, but uses std::enable_if
   to hide itself unless you specify in serialize_traits that it will work. */

template < typename serialized >
typename std::enable_if< serialize_traits< serialized >::style == serialize_style::string,
serial_type >::type
serialize( serialized const &in ) {
    using std::begin;
    using std::end;
    return serial_type( begin( in ), end( in ) );
}

I need to go so I'll post this now… not tested.


I think that you are writing similar functions to make very similar things. You can take advantage of ternary operator ? and make a simpler function instead:

int Collatz( int &len, int number )
{
    std::cout << number << " - ";
    len++;

    if( number == 1 )
        return 1;

    int NextNumber = number % 2 ? number*3+1 : number/2;

    return Collatz( len, NextNumber );
}

int main()
{
    int len = 0;
    Collatz( len, 13);

    std::cout << "Lenght: " << len << std::endl;

    return 0;
}

The output is:

13 - 40 - 20 - 10 - 5 - 16 - 8 - 4 - 2 - 1 - Lenght: 10


Number aware string sorting with comparator

Exceptions should be reserved for exceptional situations, and should be avoided if possible.  The fundamental reason you have to deal with NumberFormatException is that after splitting, you don't know whether each part contains a number or a non-number.

Here's a strategy that always compares non-digits to non-digits, and numbers to numbers.

import java.math.BigInteger;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberAwareStringComparator implements Comparator<CharSequence> {
    public static final NumberAwareStringComparator INSTANCE =
        new NumberAwareStringComparator();

    private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)");

    private NumberAwareStringComparator() {
    }

    public int compare(CharSequence s1, CharSequence s2) {
        Matcher m1 = PATTERN.matcher(s1);
        Matcher m2 = PATTERN.matcher(s2);

        // The only way find() could fail is at the end of a string
        while (m1.find() && m2.find()) {
            // matcher.group(1) fetches any non-digits captured by the
            // first parentheses in PATTERN.
            int nonDigitCompare = m1.group(1).compareTo(m2.group(1));
            if (0 != nonDigitCompare) {
                return nonDigitCompare;
            }

            // matcher.group(2) fetches any digits captured by the
            // second parentheses in PATTERN.
            if (m1.group(2).isEmpty()) {
                return m2.group(2).isEmpty() ? 0 : -1;
            } else if (m2.group(2).isEmpty()) {
                return +1;
            }

            BigInteger n1 = new BigInteger(m1.group(2));
            BigInteger n2 = new BigInteger(m2.group(2));
            int numberCompare = n1.compareTo(n2);
            if (0 != numberCompare) {
                return numberCompare;
            }
        }

        // Handle if one string is a prefix of the other.
        // Nothing comes before something.
        return m1.hitEnd() && m2.hitEnd() ? 0 :
               m1.hitEnd()                ? -1 : +1;
    }
}

Since strings of digits (such as those representing dates, like 20131212123456.log) can overflow an int, I've used java.math.BigInteger.

Also, since the code works just as well with CharSequence as with String, I've generalized the type to Comparator<CharSequence>.


Displaying data from from many-to-many table

By the looks of it, you

get the category IDs using the post ID
get the categories according to the category IDs you just had

Well, you can use JOINS to bridge the tables:

SELECT c.category_name       //select category name
FROM cats_to_posts cp        //from cats_to_posts
    INNER JOIN categories c  //joined with categories
        ON cp.cats_id=c.id   //where the cats_to_posts id  = category id
WHERE cp.post_id = {$id}     //get for post with ID

This single query should return an array of all category names for that certain post ID. The INNER JOIN joins the cats_to_posts table with categories table and returns only those categories that have an equivalent ID in cats_to_posts


I see you want to apply Separation of Concerns by separating business logic from the View's.
The database::listAllVacatures() method should return the $vacatures array. This way you can move the foreach() (which prepares the HTML output) from inside the method into the template like so:

Vacatures:

<?php foreach ($db->listAllVacatures() as $vacature): ?>

        <a href="vacature.php?id=<?= $vacature[0] ?>"><?= $vacature[1] ?>
        - <a href="delete.php?id<?= $vacature[0] ?>">delete
        - Edit

<?php endforeach; ?>

Additional Information

It would be best to follow a naming convention that uses one language. It only makes everything harder to understand when you have to read code that is written in multiple languages (like English and Dutch). I'd say stick to the same language of the programming language you're using. So listAllVacatures() method would now actually be renamed something like findAllJobs().

Your database class isn't actually what the name implies it to be. It's actually a class which responsibility is (or should be) to retrieve all job data from the database. You might wanna call it JobFetcher or something like that (note the CamelCase naming convention for classes in PHP).

I see that you're instantiating your database class like $db = new database();. No dependencies are injected. In the database::listAllVacatures() you use $this->db to communicate with the database. Which means you have your database class tightly coupled with PDO.
What if you need to update the credentials to connect to the database? You will have to change your class, which is a bad thing. I recommend you to utilize Dependency Injection to get rid of this problem, so you can inject the PDO instance the class needs to operate. It introduces many benefits.

Since you showed interest in wanting to separate your concerns I would advise you to take a look at the MVC pattern that does just what you want: It separates business logic from the View's.
Also try to adhere to the widely known coding standards defined by the PHP Framework Interop Group. It improves the code's readability, especially to other programmers who follow these standards as well. Of course, you do not have to be perfect with it.


Executing query until there is nothing more left

Sorry, but you definitely need a null check here:

  if (result.Any())

Else there is not much to comment.

About the usage:

I don't understand, why you create a lambda for the query argument:

 async Task Main()
{
    var numbers = new NumberRepository();
    await Unfold.ForEachAsync
    (
        query: async token => await numbers.GetNumbersAsync(token),
        body: ProcessBatch,
        CancellationToken.None
    );
}

Why not just:

async Task Main()
{
  var numbers = new NumberRepository();
  await Unfold.ForEachAsync
  (
      query: numbers.GetNumbersAsync,
      body: ProcessBatch,
      CancellationToken.None
  );
}

numbers.GetNumbersAsync is awaitable already?


There's nothing wrong with your code in terms of functionality, but there are a number of things we can do to make it more stylish and idiomatic.

The #1 most important thing you have missed is to always provide a type signature for top-level definitions. Just reading the type signature of a function can often give you an intuition as to what that function will do (think of IO actions, or higher order functions) or confirm that what you've written actually does something like what you're expecting after you've called the compiler to check your work.

collatz :: Int -> Int
cltzList :: Int -> [Int]

There are a few small tweaks to your definitions that we should make to come in line with good Haskell style, these won't impact functionality but help your function definitions to read more like English definitions instead of instructions for a computer.

When checking to see if a number is even, use the function even instead of checking the value in modulo 2. The definition of even may be doing the same operation under the hood but using even expresses your intent instead of the method. Changes like these will improve the readability of your code in larger projects remarkably. (Additionally, abstracting out even allows the implementer of that function to change the definition to be more efficient without requiring any changes to your code, e.g., even may check the least significant bit instead of performing any mathematical operation at all.)

collatz n | even n = n `div` 2

When calling error, you should always include the module and function name so that users of your code know what function the error actually originated from. I.e, error "Collatz.cltzList: The number must be positive" That way if someone calls your function with a negative number they see this

*** Exception: Collatz.cltzList: The number must be positive

instead of this

*** Exception: The number must be positive.

On this line | n == 1 = [n] I would change [n] to [1]. That's the only value n will ever be, so it's better to be explicit than to be clever.

You have far too many comments that have little to no value. For instance, you can assume that unless you're writing an "Intro to Haskell" book your readers will know what pattern guards are and so you don't need to explain what they are or why you used them.

And finally in my version below I've cleaned up the alignment with liberal use of whitespace. This is mostly an aesthetic effect but I find beautiful code easier to read than otherwise, and this is not an uncommon style in Haskell code.

-- Implements the Collatz sequence.
--
--        n / 2     if n is even
-- c(n) =
--        3 * n + 1 if n is odd

module Collatz where

collatz :: Int -> Int
collatz n | even n    = n `div` 2
          | otherwise = 3 * n + 1

-- Produces the Collatz sequence for a given non-zero natural number
collatzList :: Int -> [Int]
collatzList n | n <= 0    = error "Collatz.collatzList: n must be positive"
              | n == 1    = 1 : []
              | otherwise = n : collatzList (collatz n)


AngularJS directive for common form fields

address-dir

What is "dir"? Is there something special about "dir"? It would be best to provide a very common and understandable name to directives. That way, new devs wouldn't be scratching their heads and waste the next 20 mins figuring out what it does. I would name it <address-field> or <address-input>.

address-*

The prefix is redundant. We already know it's an address field.

address-town-city

Sounds a bit redundant. I'd go with either one, but "city" would be more common in some cases.

address-postcode

Would "zip-code" or just "zip" be a better name? Not sure what it's called in other places, but that's what I normally see in shopping sites.

scope.addressForm = form;

I would prefer that you not let the directive know about the form or anything from the outside world for that matter. This limits the directive's portability. Additionally, it's an implicit dependency which nobody will find out until one actually looks into the implementation - which defeats the purpose of an interface.

It's best that a directive should not make assumptions of the outside world and only know about the things inside it. For it to know something from the outside world, it's best that you explicitly define an interface, like a scope variable. In this case, you want to know if the form was submitted. Why not design a scope variable has-submitted.

Now for suggestions:

You might also want to add in your own required property to require all fields, or several require-* to require separate fields. That's because address line 2 and county are usually optional.
You might also want to add in show-* properties, so that you can conditionally hide fields.
Built-in values for countries and cities. That way, it's not a free text input, which should limit chances of error. There's a lot of libraries you could use for this one.
Built-in validation. The usual checks like whitespace/blank checks, value and length checks. I think ng-pattern covers most cases, but you could pull in a validation library if you want.


Find items in collection one that are the greatest value less than an item in collection two

To me there can only be two such numbers in the first set an they can be selected with these two queries:

var set1MaxLessThenSet1Min = set1.TakeWhile(i => i < set2 .Min()).LastOrDefault();
var set1MaxLessThenSet2Min = set1.TakeWhile(i => i < set2 .Max()).LastOrDefault();

this means that for those two sets:

var set1 = new List<int> { 1, 5, 6, 7, 9 };
var set2 = new List<int> { 3, 4, 9, 10, 11 };

those numbers are 1 and 9 whereas your query finds also the 7 which is not at the same time the highest number in set1 and lower then the highest in set2.

Both queries are for ordered sets. If they are not ordered the Where clause should be used.


How to think smarter when you need diff args in functions

If you build a dictionary of keyword arguments (customarily called kwargs), you can address the two options separately and consolidate everything into one call to MongoClient. This has the advantage that if you update e.g. the SSL part, you only need to change it in one place instead of remembering to change it twice:

host = '{host}:{port}'.format(**config[component])
kwargs = {"serverSelectionTimeoutMS": timeout}

if config.getboolean(component, 'ssl', fallback=False):
    kwargs["ssl"] = True
    kwargs["ssl_ca_certs"] = config.get(component, 'ssl_path')

if auth_required:
    kwargs.update({"username": username, "password": password,
                   "authSource": auth_source, "authMechanism": auth_mechanism})

client = MongoClient(host, **kwargs)

I also used the fact that config[component] seems to be a dictionary, so you can unpack it in the format and the host and port keys will be used.

I used two different ways to change the values in the dictionary so you can choose, depending on which one is easier to read. Using both is also fine, as I did here. For the SSL part there is few values, so using dict.update would make it more cluttered, but for the auth part there are enough values that typing kwargs[...] = ... would get tedious.


Hackerrank problem: Climbing the Leaderboard (Java)

I have some suggestions to make the code cleaner, not faster.
Always try to pass the size of the maximum size to the Collection / Map when known
The ArrayList has a default size of 10 elements, if you have more elements, the list will have to resize its internal pool. By setting the size, you can prevent the resize and make your code faster.
//[...]
int totalPlayers = scanner.nextInt();
ArrayList<Integer> playerScores = new ArrayList<>(totalPlayers);
//[...]
int aliceTotalScores = scanner.nextInt();
ArrayList<Integer> aliceScores = new ArrayList<>(aliceTotalScores);
//[...]

Always use the base class / interface in the left part of the variable when possible
By setting the java.util.List interface in the variable part, this could make the code more refactorable in the future, since you could easily change the list type without changing everything (inheritance).
Before
 ArrayList<Integer> playerScores = new ArrayList<>(totalPlayers);

After
 List<Integer> playerScores = new ArrayList<>(totalPlayers);

Replace the for loop with an enhanced 'for' loop
In your code, you don’t actually need the index provided by the loop, you can the enhanced version.
Before
for (int i = 0; i < aliceTotalScores; i++) {
   finalScores.add(aliceScores.get(i));
   finalScores.sort(Collections.reverseOrder());
   Set<Integer> set = new LinkedHashSet<>(finalScores);
   finalScores.clear();
   finalScores.addAll(set);
   System.out.println(finalScores.indexOf(aliceScores.get(i)) + 1);
}

After
for (Integer aliceScore : aliceScores) {
   finalScores.add(aliceScore);
   finalScores.sort(Collections.reverseOrder());
   Set<Integer> set = new LinkedHashSet<>(finalScores);
   finalScores.clear();
   finalScores.addAll(set);
   System.out.println(finalScores.indexOf(aliceScore) + 1);
}

Extract some of the logic to methods.
To remove some of the code of the main method, you could move both list instantiation (playerScores & aliceScores) to methods. Since the logic is similar, you could make only one method to read the inputs to a list and reuse the same for both cases.
public static void main(String[] args) {
   List<Integer> playerScores = getPlayerScores(scanner);
   List<Integer> aliceScores = getAliceScores(scanner);
}

private static List<Integer> getAliceScores(Scanner scanner) {
   return getIntegers(scanner);
}

private static List<Integer> getPlayerScores(Scanner scanner) {
   return getIntegers(scanner);
}

private static List<Integer> getIntegers(Scanner scanner) {
   int size = scanner.nextInt();
   List<Integer> integers = new ArrayList<>(size);
   for (int i = 0; i < size; i++) {
      integers.add(scanner.nextInt());
   }
   return integers;
}

or
public static void main(String[] args) {
   List<Integer> playerScores = getIntegers(scanner);
   List<Integer> aliceScores = getIntegers(scanner);
}

private static List<Integer> getIntegers(Scanner scanner) {
   int size = scanner.nextInt();
   List<Integer> integers = new ArrayList<>(size);
   for (int i = 0; i < size; i++) {
      integers.add(scanner.nextInt());
   }
   return integers;
}

Refactored code
public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   List<Integer> playerScores = getPlayerScores(scanner);
   List<Integer> aliceScores = getAliceScores(scanner);
   List<Integer> finalScores = new ArrayList<>(playerScores);

   for (Integer aliceScore : aliceScores) {
      finalScores.add(aliceScore);
      finalScores.sort(Collections.reverseOrder());
      Set<Integer> set = new LinkedHashSet<>(finalScores);
      finalScores.clear();
      finalScores.addAll(set);
      System.out.println(finalScores.indexOf(aliceScore) + 1);
   }
}

private static List<Integer> getAliceScores(Scanner scanner) {
   return getIntegers(scanner);
}

private static List<Integer> getPlayerScores(Scanner scanner) {
   return getIntegers(scanner);
}

private static List<Integer> getIntegers(Scanner scanner) {
   int size = scanner.nextInt();
   List<Integer> integers = new ArrayList<>(size);
   for (int i = 0; i < size; i++) {
      integers.add(scanner.nextInt());
   }
   return integers;
}


What is an optimal way of not repeating myself in the following code?

DRY review

You don't need to wrap try catch around async function or promise. The errors will all get passed onto the final promise.catch. So can remove all 5 try catches.

The function readFile is just wrapping a promise and is completely redundant.

The two functions getAttachment and getFileName are almost identical apart from the final return.

The two file loads are of the same file that need only be done once.

filePath as a string is defined twice, again only once is best.

All you want is attachments[0] of the one email. So you don't need to store file and email.

You use util.promisify and fs.readFile only once so no need to hold a reference for either.

Assigning the variables attachment and filename can be done via destructuring saving another token.

You are creating a module so keep variable names short, use the context to infer meaning.

The end result is
const reader = require("util").promisify(require("fs").readFile);
const parser = require('mailparser').simpleParser;

async function main(file) {
    const atts = (await parser(await reader(file))).attachments[0];
    const [attachment, filename] = [atts.content.toString(), atts.filename.toString()];
    console.log(filename);
}
main("./mock-data/google-report.email").catch(err => /*do something with error*/ );


Generate unique string permutations recursively

✅ Solution
 Fix - Missing Combinations

Recursively generate each permutation of characters.
For every permutation, iterate through each index and move the last character to each position of the permutation.
Add each permutation to the Set.

fun getPerms(input: String): HashSet<String> {
    val perms = hashSetOf<String>()
    if (input.length <= 1)
        return hashSetOf(input)
    val allCharsExceptLast = input.substring(0, input.length - 1)
    val permsOfAllCharsExceptLast = getPerms(allCharsExceptLast)
    val lastChar = input.substring(input.length - 1)
    for (s in permsOfAllCharsExceptLast) {
        for (i in 0.. allCharsExceptLast.length) {
            perms.add(s.substring(0, i) + lastChar + s.substring(i))
        }
    }
    return perms
}

 Questions
1: How does the problem change if the string can have duplicate characters?
Considering the input aaaaaaaaaaaaaaaaaaaaaa, it would return one combination. However, the algorithm would check each possible combination at every index which is highly inefficient. For example, with input aaa, the algorithm would run 9 times for the character at index 0, 1, and 2 for all 3 positions, so 3 x 3 iterations.
2: What is the space and time complexity?
Considering the input abcdefghijklmnopqrstuvwxyz, it seems like the space complexity grows larger than O(n^2) and closer to O(n^n), exponential growth.
3: How to optimize the time complexity?
If we take a simple example with one repeated character, a, in the input abac, the second combinations of a at index 2 are entirely repeated throughout the rest of the iterations.
Therefore, if a character value is a repeat value the iterations for the repeated value should be skipped. The algorithm may be adjusted to store an instance variable set of characters already searched for to improve the time efficiency.
Index 0
abac
baac
baac
baca
Index 1
baac
abac
aabc
aacb
Index 2: This is the second time using character a, therefore, we can skip these iterations.
aabc
aabc
abac
abca
Index 3
caba
acba
abca
abac


LeetCode 124: Binary Tree Maximum Path Sum 2

Unnecessary checks in depth_first_search()
The function depth_first_search() always returns an integer value, never None. So the check for a partial sum being None or < 0 can be rewritten using max():
left_sum = max(0, depth_first_search(node.left))
right_sum = max(0, depth_first_search(node.right))


from time import time, ctime, sleep
from random import choice, uniform
from glob import glob
import os

# Gets current working directory
DIRECTORY_NAME = os.getcwd()

Given that its global and all caps, I'd expect it to be a constant. But it's not really a constant.

def load():
    """Prints loading messages"""
    os.system("clear")

This isn't portable, you may want to check out: https://stackoverflow.com/questions/2084508/clear-terminal-in-python

    MESSAGES = ["Deleting hard drive...", "Reticulating Spines...", "Fetching Your Credit Card Number...", "Hacking your computer..."]

I'd put this as a global outside of the function.

    print(choice(MESSAGES))
    sleep(uniform(1, 5))
    os.system("clear")

def print_dir(dirname):
    """Prints the current directory"""

It prints the directory passed in, not the current directory

    print("Directory: %s" % dirname)
    print("-"*80)

You do this several times, perhaps write a function for it

def number_of_files(dirname):
    """Finds the number of files in the directory using glob"""

I wouldn't put details like how it counts the files in the docstring

    num_of_files = len(glob("*"))
    print(num_of_files, "files")
    print("-"*80)

def last_access(dirname):
    """Prints a ctime representation of the last access to a file"""
    print("Last Access: ")
    print(ctime(os.path.getatime(dirname)))
    print("-"*80)

def last_change(dirname):
    """Prints a ctime representation of the last change to a file"""
    print("Last Change: ")
    print(ctime(os.path.getmtime(dirname)))
    print("-"*80)

These two functions are quite similar. Considering combining them, passing the os.path.xtime function as a parameter

def size_of_dir(dirname):
    """Walks through the directory, getting the cumulative size of the directory"""
    sum = 0

sum isn't a great choice because there is a builtin python function by that name

    for file in os.listdir(dirname):
        sum += os.path.getsize(file)

I'd use directory_size = sum(map(os.path.getsize, os.listdir(dirname))

    print("Size of directory: ")
    print(sum, "bytes")
    print(sum/1000, "kilobytes")
    print(sum/1000000, "megabytes")
    print(sum/1000000000, "gigabytes")
    print("-"*80)
    input("Press ENTER to view all files and sizes")

As palacsint mentioned, this should really be in the next function, or perhaps in your main function.

def files_in_dir(dirname):
    """Walks through the directory, printing the name of the file as well as its size"""
    print("Files in directory: %s" % dirname)
    for file in os.listdir(dirname):

file is builtin class in python, I'd avoid using it as a local variable name

        print("{0} => {1} bytes".format(file, os.path.getsize(file)))

load()
print_dir(DIRECTORY_NAME)
number_of_files(DIRECTORY_NAME)
last_access(DIRECTORY_NAME)
last_change(DIRECTORY_NAME)
size_of_dir(DIRECTORY_NAME)
files_in_dir(DIRECTORY_NAME)

I'd suggesting putting all of these in a main() function.


I can see two obvious points:

Constructor names are usually capitalized, to indicate that they should be invoked with new
You've got some code duplication between bst::insert and node::insert. This even leads to the bug that you don't recognise/handle duplicate values in the root node.

So, I'd suggest:

function Bst() {
    this.root = null;
}
Bst.prototype.insert = function(obj) {
    if (this.root == null) {
        this.root = new Node(obj);
    } else {
        this.root.insert(obj);
    }
};

  I am new to data structures.

Binary trees are a wide field :-) First, I'm missing some other basic operations like searching, traversing, and deleting. If you have mastered these, you can go on with optimizing your tree, e.g. making it a balanced one.


Find intersection of two arrays without duplicates

Your solution doesn't have explicit instructions to use the property that no duplicate elements in the array, but it naturally benefits from it.
The binary search is slightly faster because it doesn't need to visit duplicate elements unnecessarily.
The iteration is faster too for the same reason.
Actually if there were duplicates it would be a lot tougher problem to solve.

The only way I see to make it faster won't be possible in \$O(1)\$ space:
instead of sorting the first list, you could put it in a hash set.
That way the binary search becomes a hash lookup, which is much faster,
but at the expense of doubling the memory usage of one of the lists.

When you have two lists of very different sizes,
I'm wondering if it can be said that making the shortest to be the first or the second will yield better performance in general.


Algorithm that generates orthogonal vectors: C++ implementation

Welcome to C++.

It seems that you are more or less trying to write C code rather than C++ though. Lets have a look at what you can improve:

Never do using namespace std; It is a terrible practise that gets you into trouble really fast. std:: is not that hard to type so get in the habit early.
If you have compile time constants use them via constexpr
Your dot_product function is already implemented in the standard library. It is called inner_product. So the following code can be replaced

float dot_product(float *vector1, float vector2[],int dimension){
    float sum = 0;
    for (int i = 0; i < dimension; i++){
        sum += (vector1[i])*(vector2[i]);
    }
    return sum;
}

by the following code

std::inner_product(a.cbegin(), a.cend(), b.cbegin(), float(0.0));

Similarly there is a generate function that fills a vector with a generator. Note that C++ has a variety of good random number generators (rand() is not one of them) in the <random> header. I don't know why you use integers for the float vectors but you can adapt that easily.

EDIT: Incorporated problems found by @L.F.

#include <algorithm>
#include <random>

class randomStreamUniformInt {
public:
    explicit randomStreamUniformInt(int lower_bound, int upper_bound)
    : mt(std::random_device{}()), uniform_dist(lower_bound, upper_bound) {}
    explicit randomStreamUniformInt(int lower_bound, int upper_bound, double seed)
    : mt(seed), uniform_dist(lower_bound, upper_bound) {}

    int operator() () { return uniform_dist(mt); }
private:
    std::mt19937_64                     mt;
    std::uniform_int_distribution<>     uniform_dist;
};

static randomStreamUniformInt rng(-MAXRANGE, MAXRANGE);

std::vector<float> generate random(const std::size_t numElements) {
    std::vector<float> res(numElements);
    std::generate(res.begin(), res.end(), rng);
    return res;
}

It would be even better to pass the random number generator as an argument rather than a global variable. I leave that as an exercise.
You should use standard facilities for arrays such as std::vector or std::array depending on whether you know the size at compile time. So the following code:

float arbitrary_vector[dimension], orthogonal[dimension]

Should be better written as

std::vector<float> arbitrary_vector = generate_random(dimension);

Note that it is always better to put each declaration into a single line.
Your method generate_orthogonal can be improved accordingly.

std::vector<float> generate_orthogonal(const std::vector<float>& a) {
    // get some random data
    std::vector<float> b = generate_random(a.size());

    // find the last non zero entry in a
    // We have to turn the reverse iterator into an iterator via std::prev(rit.base())
    auto IsZero = [] (const float f) -> bool { return f == float(0.0);};
    auto end = std::prev(std::find_if_not(a.crbegin(), a.crend(), IsZero).base());

    // determine the dot product up to end
    float dot_product = std::inner_product(a.cbegin(), end, b.cbegin(), float(0.0));

    // set the value of b so that the inner product is zero
    b[std::distance(a.cbegin(), end)] = - dot_product / (*end);

    return b;
}

So put together it would look something like this:

#include <algorithm>
#include <random>
#include <vector>

constexpr int MAXRANGE = 1000;

class randomStreamUniformInt {
public:
    explicit randomStreamUniformInt(int lower_bound, int upper_bound)
    : mt(std::random_device{}()), uniform_dist(lower_bound, upper_bound) {}
    explicit randomStreamUniformInt(int lower_bound, int upper_bound, double seed)
    : mt(seed), uniform_dist(lower_bound, upper_bound) {}

    int operator() () { return uniform_dist(mt); }
private:
    std::mt19937_64                     mt;
    std::uniform_int_distribution<>     uniform_dist;
};

static randomStreamUniformInt rng(-MAXRANGE, MAXRANGE);

std::vector<float> generate random(const std::size_t numElements) {
    std::vector<float> res(numElements);
    std::generate(res.begin(), res.end(), rng);
    return res;
}

std::vector<float> generate_orthogonal(const std::vector<float>& a) {
    // get some random data
    std::vector<float> b = generate_random(a.size());

    // find the last non zero entry in a
    // We have to turn the reverse iterator into an iterator via std::prev(rit.base())
    auto IsZero = [] (const float f) -> bool { return f == float(0.0);};
    auto end = std::prev(std::find_if_not(a.crbegin(), a.crend(), IsZero).base());

    // determine the dot product up to end
    float dot_product = std::inner_product(a.cbegin(), end, b.cbegin(), float(0.0));

    // set the value of b so that the inner product is zero
    b[std::distance(a.cbegin(), end)] = - dot_product / (*end);

    return b;
}

int main() {
    std::size_t dimension = 20;

    std::vector<float> a = generate_random(dimension);
    std::vector<float> b = generate_orthogonal(a);
}


Since you're not updating the variables path, rootPath and currentPath anywhere, use a single variable.

Define the function walk locally.

You can also break out of your c_GetFileDir loop once you've updated the empty flag. This will remove the time to iterate through all children of a directory.

  The help pages for WFTPServer have a
  different return values for c_GetFileDir than
  yours!

function EmptyFolderDeleter( options )
    local root = options.path

    local walk = function( path )

        --cycle through the current directory, walking directories
        for dir in c_GetDir( path ) do
            walk( path..dir.."/" )
        end

        --if we've got this far then we're at the bottom of the tree
        --there are no more directories to visit
        --now check if there is ANYTHING (file or folder) in the current folder
        local empty = true
        for isdir, file in c_GetFileDir( path ) do
            empty = false
            break
        end

        --now check the 'empty' flag and if the folder is the root
        if empty and path ~= root then
            c_RemoveFileDir( path )
        end
    end

    walk( root )
 end


First of all better use clear variable names.
Coming from android I can guess what an 'ed' is. But for everybody it is always better to name it properly like :
private EditText editText;
editText = findViewById(R.id.editText);

or in this case maybe even
editTextTTS;

or something similar.
Same with myTTS, I personally would also name that :
private TextToSpeech textToSpeech;

You are creating a TextToSpeech Object on every click, which is absolutely unneccessary, create it once when starting the application, and reuse it. So this piece of code belongs in your onCreate() not your onClick() :
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, 1);

That way the TTS will be ready before the user can click the button and is only initialised once.
You are getting the value of your editText AFTER you startActivityForResult().
This does not seem to be the logical order, although if you remove the code above from your onClick(), that also solves this problem.
You have a magic number 1 in your startActivityForResult() method, better use a final value with a proper name like :
private final int TTS_REQUEST_CODE = 1;

makes this also look way better :
startActivityForResult(checkIntent, TTS_REQUEST_CODE);

if (requestCode == TTS_REQUEST_CODE)

In case the application becomes larger and more complex this will be way more secure and readable since the value is final and cannot be tampered with.
There is no information to the user wether the TextToSpeech is installed and ready or not, I would suggest showing a Toast or a Snackbar to let the user know what is happening, especially in case of
status == TextToSpeech.ERROR

You might even want to smooth exit the application in this case.
This app will only please Users with US English language. Why not make it get the Locale from the Users device, to set the proper language dynamically :
myTTS.setLanguage(Locale.getDefault());

The onInit() method should only be called once when initialising the TTS Object, so your
myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);

is misplaced there. This code should go into your onClick() method along with a check that the editText is not empty :
public void onClick(View arg0) {

    final String phrase = ed.getText().toString();
    if(!phrase.isEmpty()) {
        myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);
    } else {
        // Toast or Snackbar to tell the user Edittext is empty
    }

This will also convert
private String phrase;

to a local final variable, which is always better than having an unneccessary global variable.


Design/reiterate or code reuse for linked list

No, it would not be good design. That method signature says "you can insert an element at any point in the list" and then the body says "but only if it's the place I want you to put it." This is why the Collections API doesn't have a sorted list, but rather allows lists to be sorted. Sorted and Unsorted lists share some contract, but insertion is fundamentally different for them. Unless your assignment requires it, I would not put them in the same inheritance hierarchy, and I'd be leery of putting them under the same interface (contract) unless it didn't include addition of elements.


Zero pad function trim extra leading zeros

Naming

Based on the naming guidelines parameters should be named using camelCase casing.

Select Case

If you omitt the Case Is > ToLength and the else part aka having only 2 cases you will have

Friend Function ZeroPad(ByVal Number As String, ByVal ToLength As Integer, Optional ByVal TrimExtraZeroes As Boolean = False) As String
    Const ZeroChar = "0"c

    Select Case Number.Length
        Case Is < ToLength
            Return New String(ZeroChar, ToLength - Number.Length) & Number
        Case Is = ToLength
            Return Number
     End Select

     If (TrimExtraZeroes) Then
         Do While Number.StartsWith(ZeroChar) AndAlso Number.Length > ToLength
             Number = Number.Substring(1)
         Loop
     End If
    Return Number
End Function

Why don't you use the built in String.PadLeft() method which would obsolete the Select Case. In addition to first stripping any 0 of the left side of Number you won't need the loop at all.

This boils down to only this

Friend Function ZeroPad(ByVal Number As String, ByVal ToLength As Integer, Optional ByVal TrimExtraZeroes As Boolean = False) As String
    Const ZeroChar = "0"c
    If (TrimExtraZeroes) Then
        Number = Number.TrimStart({ZeroChar})
    End If
    Return Number.PadLeft(ToLength, ZeroChar)
End Function

Update
Some timetables for calling both methods 1.000.000 times

                                    Yours(ms)  Mine(ms)
ZeroPad("0000000001", 2, False)       227       231
ZeroPad("0000000001", 2, True)       1696       297
ZeroPad("01", 2, False)               251       235
ZeroPad("01", 2, True)                248       263
ZeroPad("01", 12, False)              256       247
ZeroPad("01", 12, True)               257       260


PHP exercise to read or write database values

Instead of using a big stack of if/elseif, since you're just checking the value of a single variable you should be using a switch/case instead.
What if action and mykey are both set, but action is neither read nor write - Your user will get a blank response.. yet another reason to use a switch (with a default option).
Don't use real_escape_string, use prepared statements instead.
Don't SELECT * ... if you only need the value column, just select value ...
I would suggest creating a function to handle errors.
I would suggest holding your errors in an array and joining them rather than concatting to a string - this will be more efficient and manageable.
There is no reason to use LOCK_EX in conjunction with FILE_APPEND - If you lock the file and the script is called simultaneously one instance will be blocked or denied while the other is writing. See here for more info.
Is this not supposed to be an API? If it is you might consider outputting JSON instead of print_ring the results. I would suggest putting this in an output function as well.

include("opendb.php");
$logging = true;
$log = array(date('d-m-Y'));
$log[] = serialize($_REQUEST)

$reply = array("id" => null, "status" => 'success');

if(!isset($_REQUEST["mykey"])) error("No key provided.");
$action = empty($_REQUEST["action"]) ? "" : strtolower($_REQUEST["action"])

switch($action){

    case "read":
        if(!isset($_REQUEST["id"])) error('No ID provided.');
        $stmt = $mysqli->prepare("SELECT value FROM data WHERE mykey = ? AND id = ?");
        $stmt->bind_param('si', $_REQUEST["mykey"], $_REQUEST["id"]);
        $stmt->execute();
        $stmt->bind_result($value);
        if(!$stmt->fetch()) error("No results found.");
        $reply["id"] = $_REQUEST["id"];
        $reply["value"] = $value;
        output();

    case "write":
        if(!isset($_REQUEST["value"])) error('No value provided.');
        $stmt = $mysqli->prepare(INSERT INTO `data` (`value`, `mykey`) VALUES (?, ?));
        $stmt->bind_param('ss', $_REQUEST["value"], $_REQUEST["mykey"]);
        if(!$stmt->execute()) error($mysqli->error);
        $reply["id"] = $mysqli->insert_id;
        output();

    default: error('Invalid action.');
}

function error($msg){
    $GLOBALS['log'][] = $msg;
    $GLOBALS['reply']['status'] = 'error';
    $GLOBALS['reply']['error'] = $msg;
    output();
}

function output(){
    if($GLOBALS['logging']){
        file_put_contents('log/read_write_exercise.log',  implode(PHP_EOL, $GLOBALS['log']), FILE_APPEND) ;
    }
    header('Content-Type: application/json');
    echo json_encode($GLOBALS['reply'], JSON_PRETTY_PRINT);
    exit;
}


Infix to postfix implementation using a stack

The first thing I notice is the deep nesting in infix_to_postfix. Deep nesting like that is generally undesirable. We'll get to that later.

Second, for the parenthesis, my instinct would be to say: "Use frozenset instead of set.". But after some benchmarking: set is actually fastest on my machine, so probably also on yours. (I also checked using a tuple instead, again slower than using a set). However, a more Pythonic declaration of the set would be PARENTHESIS = {"(", ")"}.

Regarding the regular expression and the method parse: it could be faster by using a compiled regex instead of using re.findall. Also, convention has it that you use raw strings for regular expressions.

REGEX = re.compile(r"(\d+|\w+|[-+*/^%()])")
def parse(e, REGEX=REGEX):
    return REGEX.findall(e)

The REGEX=REGEX trick is an optimization trick preventing a lookup to the global dictionary. Using compiled regular expressions also gains a bit of speed. (On the other hand: I don't see parse being used, so that's probably ok).

Since it's not documented, I'm going to assume the calling convention will be

postfix_tokens = infix_to_postfix(parse(infix_tokens)

Now, let's start analysing the large method infix_to_postfix. First of all, we could apply the same trick as we did for REGEX to speed up the lookup for OPERATORS. That's going to make your code a bit more efficient.

It's a tad large, so let's first talk about the if c in OPERATORS branch.

if len(stack) > 0:
    top = stack[-1]

    if top in OPERATORS.keys():
        if OPERATORS[c] > OPERATORS[top]:
            stack.append(c)
        else:
            while top in OPERATORS.keys() and OPERATORS[top] >= OPERATORS[c]:
                op = stack.pop()
                postfix.append(op)

                if len(stack) > 0:
                    top = stack[-1]
                else:
                    break
            stack.append(c)
    else:
        stack.append(c)
else:
    stack.append(c)

All these else conditions look the same. Let's see if we can simplify it a bit. Let's start by flipping the if and else branch in if OPERATORS[c] > OPERATORS[top]. (> becomes <=).

if len(stack) > 0:
    top = stack[-1]

    if top in OPERATORS.keys():
        if OPERATORS[c] <= OPERATORS[top]:
            while top in OPERATORS.keys() and OPERATORS[top] >= OPERATORS[c]:
                op = stack.pop()
                postfix.append(op)

                if len(stack) > 0:
                    top = stack[-1]
                else:
                    break
            stack.append(c)
        else:
            stack.append(c)
    else:
        stack.append(c)
else:
    stack.append(c)

Now, we have the following construct:

if cond:
    A()
    B()
 else:
    B()

Which we can rewrite to

if cond:
    A()
 B()

Applying that several times we get

if len(stack) > 0:
    top = stack[-1]

    if top in OPERATORS.keys():
        if OPERATORS[c] <= OPERATORS[top]:
            while top in OPERATORS.keys() and OPERATORS[top] >= OPERATORS[c]:
                op = stack.pop()
                postfix.append(op)

                if len(stack) > 0:
                    top = stack[-1]
                else:
                    break

stack.append(c)

Wow, we saved a few lines of code. If we're lucky, it's also going to gain us some performance.

Next, you have top in OPERATORS.keys(). This can be replaced by top in OPERATORS (as that's how dict containment checking works). Furthermore, len(stack) > 0 can be replaced by stack.

Furthermore, you write op = stack.pop() followed by postfix.append(op). You can simplify this to postfix.append(stack.pop()).

if stack:
    top = stack[-1]

    if top in OPERATORS:
        if OPERATORS[c] <= OPERATORS[top]:
            while top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
                postfix.append(stack.pop())

                if stack > 0:
                    top = stack[-1]
                else:
                    break

stack.append(c)

Let's continue our focus on the nested if top in OPERATORS. Now, for symmetry, we replace OPERATORS[c] <= OPERATORS[top] with OPERATORS[TOP] >= OPERATORS[C]. (I'm not showing the if stack: and stack.append(c) anymore).

if top in OPERATORS:
    if OPERATORS[top] >= OPERATORS[c]:
        while top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
            postfix.append(stack.pop())

            if stack > 0:
                top = stack[-1]
            else:
                break

We can merge the first two conditionals, because there are no else branches, using

if cond_a:
    if cond_b:
        ...

to

if cond_a and cond_b:
    ...

We get

if top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
    while top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
        postfix.append(stack.pop())

        if stack > 0:
            top = stack[-1]
        else:
            break

Now the similarity should be obvious, we can drop the if.

Zooming out again:

def infix_to_postfix(infix):
    stack = []
    postfix = []

    for c in infix:
        if c in OPERATORS:

            if stack:
                top = stack[-1]

                while top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
                    postfix.append(stack.pop())

                    if stack:
                        top = stack[-1]
                    else:
                        break

            stack.append(c)

        elif c in PARENTHESIS:

            if c == ")":
                if len(stack) > 0:
                    top = stack[-1]

                    while top != "(":
                        try:
                            # pop throws an IndexError if the list is empty
                            r = stack.pop()
                            postfix.append(r)  # Adding what's in between ( ) to the postfix list
                            top = stack[-1]
                        except IndexError:
                            raise ValueError("'(' not found when popping")

                    stack.pop()  # Removes ( from the top of the stack
                else:
                    raise ValueError("')' cannot be added to the stack if it is empty")
            else:
                stack.append(c)  # c == '('
        else:

            postfix.append(c)

        #print("Stack:", stack)
        #print("Postfix:", postfix)

    while len(stack) > 0:
        top = stack.pop()

        if top in OPERATORS.keys():
            postfix.append(top)

    return postfix

The first branch of the conditional is cleaned up nicely. Let's consider the second branch, most specifically the handling of ")".

You're checking if len(stack) > 0, and throwing a ValueError otherwise because of an empty stack. What you actually mean is "')' cannot be added to the stack if there is no '(' in the stack". That's already checked by the other branch, so this condition is superfluous. However, we can't just remove it just yet, because top = stack[-1] might then throw an IndexError. So, let's continue and see if we get another opportunity to fix it later.

In the while loop, we see a try/except. The except has a raise, so we might as well move it outside the loop. (I took the liberty to also remove the temporary variable r).

top = stack[-1]
try:
    while top != "(":
        postfix.append(stack.pop())
        top = stack[-1]
except IndexError:
    raise ValueError("'(' not found when popping")

stack.pop()  # Removes the ( from the top of the stack

Looking at efficiency: you're storing stack[-1] in a temporary variable, and then loading it again for the while condition. We can fix that

try:
    while stack[-1] != "(":
        postfix.append(stack.pop())
except IndexError:
    raise ValueError("'(' not found when popping")

stack.pop()  # Removes the ( from the top of the stack

Remember the if we wanted to remove? We can actually do that now!

        ...
        elif c in PARENTHESIS:

            if c == ")":
                try:
                    while stack[-1] != "(":
                        postfix.append(stack.pop())
                except IndexError:
                    raise ValueError("'(' not found when popping")

                stack.pop()  # Removes ( from the top of the stack
            else:
                stack.append(c)  # c == '('
        else:
            ...

The code is now shaping up nicely. Let's consider the final while loop. Here you're poping until it's empty. Why not just loop over it in reverse? (The stack is going to be destructed anyway). Iteration is probably cheaper than mutation.

    for token in reversed(stack):
        if token in OPERATORS.keys():
            postfix.append(token)

In fact, it would probably be more efficient to use a generator comprehension here.

     postfix.extend(token for token in reversed(stack) if token in OPERATORS)

In the end, we end up with

def infix_to_postfix(infix):
    stack = []
    postfix = []

    for c in infix:
        if c in OPERATORS:

            if stack:
                top = stack[-1]

                while top in OPERATORS and OPERATORS[top] >= OPERATORS[c]:
                    postfix.append(stack.pop())

                    if stack:
                        top = stack[-1]
                    else:
                        break

            stack.append(c)

        elif c in PARENTHESIS:

            if c == ")":
                try:
                    while stack[-1] != "(":
                        postfix.append(stack.pop())
                except IndexError:
                    raise ValueError("'(' not found when popping")

                stack.pop()  # Removes ( from the top of the stack
            else:
                stack.append(c)  # c == '('
        else:

            postfix.append(c)

        #print("Stack:", stack)
        #print("Postfix:", postfix)

    postfix.extend(token for token in reversed(stack) if token in OPERATORS)

    return postfix

And we can probably shave some extra lines off it even more, but I don't think that's necessary because now it is a bit more understandable.

As for the points @GarethRees mentioned: those should also be taken care of, as it does not make much sense like this. Probably best to ask for a new code-review after you made these changes.


JavaScript function to change an element tag

You will have a css concatenation issue if the passed element already has a class, for example :

will turn into :

Then on the actual efficiency of the function, I would use standard calls and quicker logic to speed things up :

function divilize(elm) {

   var clone = elm.cloneNode(true);
   var tagName = clone.tagName.toLowerCase();

   clone.className += " divilize-"+tagName;
   elm.outerHTML = clone.outerHTML.replace(tagName, "div");

}

@ Fiddle


Python 2.7: 100 ms, pypy 1.8.0: 60 ms (Intel Core i7-3770K, 4x 3.50GHz):

import time

def rwh_primes2(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a list of primes, 2 <= p < n """
    correction = (n%6>1)
    n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
    sieve = [True] * (n/3)
    sieve[0] = False
    for i in xrange(int(n**0.5)/3+1):
      if sieve[i]:
        k=3*i+1|1
        sieve[      ((k*k)/3)      ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
        sieve[(k*k+4*k-2*k*(i&1))/3::2*k]=[False]*((n/6-(k*k+4*k-2*k*(i&1))/6-1)/k+1)
    return [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]

def main():
    start = time.time()
    primes = set(rwh_primes2(1000000))
    circular_primes = set()
    for prime in primes:
        include = True
        s = str(prime)
        for n in xrange(len(s)-1):
          s = s[1:] + s[:1]
          if int(s) not in primes:
              include = False
              break
        if include:
            circular_primes.add(prime)
    print(len(circular_primes))
    print("Time (s)     : " + str(time.time()-start))

main()


Embed MD5 digest in a directory path name

MD5 is simply a 128 bit number.

Convert the number into a string that is the ASCII representation of the number. Note: Usually this is done as hex number. If you make sure it is 0 padded it will be 32 characters long (as each 8 bits is converted into two hex digits).

This is how I would do it:

static_assert(sizeof(int) == 4, "Figure it out with other sizes");

int*  data = reinterpret_cast<int*>(ret);
int   len  = 128 / (sizeof(int) * 8);

for(int i=len-1; i >= 0; --i)
{
    std::cout << std::setfill('0') << std::setw(8) << std::hex << data[i];
}


1.- You should try to declare and instance variables at the same time. Instead of int age = 0; age = getUserInput(); this is better: int age = getUserInput();

2.- One method should do one thing, DetermineCost should 'determine cost', if you want to inform how much the cost is, then you should create another method (in this case I created PrintWeeklyCost())

3.- You should know where the variables are going to live, I mean, the scope of the variables. In you case isInt and isDouble should go only where they are going to be used.

4.- The if else if to see numeric ranges; it's really easy to make little mistakes. What if the dog is exactly 15 kg/pounds/whatever?. Will the cost be 125? An easy way to discover little errors is being consistent and, for me, that style helps a lot.

5.- What if the user doesn't enter text at all in HandleStringInput? (here I changed the name of the methods, I think that overloading methods can add more complexity to your program when it is not needed, now if you are learning go ahead!) Check for errors in input is a good practice !

class Program
{

    static void Main(string[] args)
    {
        int id = HandleIntegerInput("Please enter your Owner ID");
        String name = HandleStringInput("Please enter the name of your dog");
        String breed = HandleStringInput("Please enter the breed of your dog");
        int age = HandleIntInput("Please enter the age of your dog");
        double weight = HandleDoubleInput("Please enter the weight of your dog");

        DogOwner dogOwner = new DogOwner(id);
        Dog newDog = new Dog(age, name, breed, weight);

        double cost = DetermineCost(newDog.GetDogWeight());
        PrintWeeklyBill(cost);

        Console.Read();
    }

    private static int HandleIntInput(String input)
    {
        Console.WriteLine(input);

        int output;
        bool validInput = false;
        while(!validInput)
        {
            Console.WriteLine("Please enter an integer value\n");
            validInput = int.TryParse(Console.ReadLine(), out output);
        }

        Console.WriteLine("");
        return output;
    }

    private static String HandleStringInput(String input)
    {
        Console.WriteLine(input);

        String output;
        bool validInput = false;
        while(String.IsNullOrEmpty(output))
        {
            Console.WriteLine("Please enter a valid text value\n");
            output = Console.ReadLine();
        }

        Console.WriteLine("");
        return output;
    }

    private static double HandleDoubleInput(String input)
    {
        Console.WriteLine(input);

        double output;
        bool validInput = false;
        while(!validInput)
        {
            Console.WriteLine("Please enter an decimal value\n");
            validInput = double.TryParse(Console.ReadLine(), out output);
        }

        Console.WriteLine("");
        return output;
    }

    private static double DetermineCost(double weight)
    {
        double cost;
        if (weight <= 15.0)
        {
            cost = 55.00;
        }
        else if (15.0 < weight && weight <= 30.0)
        {
            cost = 75.00;
        }
        else if (30.0 < weight && weight <= 80.0)
        {
            cost = 105.00;
        }
        else
        {
            cost = 125.00;
        }

        return cost;
    }

    private static void PrintWeeklyBill(double costPerWeek)
    {
        String costMsge = String.Format("Your bill for weekly day care is going to be: $", costPerWeek);
        Console.WriteLine(costMsge);
    }
}


Initialize a Sieve of Eratosthenes in Scala

There are many other ways of writing a Sieve of Eratosthenes in Scala. Regarding this particular code, the for-comprehension is better written as:

val sieve = Array.fill[Boolean](100)(true)

for {
  p <- 2 until sieve.length
  if sieve(p) && math.pow(p, 2) <= sieve.length
  i <- p * 2 until sieve.length by p
} sieve(i) = false

Also,

  the outer loop still evaluates all numbers from some Y until
  sieve.length to test the condition sieve(p) && math.pow(p,2) <=
  sieve.length,

You could compute the square root too, though that's an expensive computation. You can use takeWhile to avoid it:

p <- 2 until sieve.length takeWhile (x => x * x < sieve.length)

Also, the starting place of the final loop can be improved:

i <- p * p until sieve.length by p

Altogether, you get this:

val sieve = Array.fill[Boolean](100)(true)

for {
  p <- 2 until sieve.length takeWhile (x => x * x < sieve.length)
  if sieve(p)
  i <- p * p until sieve.length by p
} sieve(i) = false

Now, I wouldn't use booleans for this, nor an Array. Instead, my preferred implementation (for efficiency) uses BitSet instead. For example:

val last = 100
val numbers = 2 to last
val sieve = collection.mutable.BitSet(numbers: _*)
for (p <- numbers takeWhile (x => x * x <= last) if sieve(p))
  sieve --= p * p to last by p

There are other implementations I value for their functional nature, but I'll leave that to others.


Computing resilience of the network presented as an undirected graph in Python

1. Review

The docstring for bfs_visited should explain the node argument.
The docstring for compute_resilience should explain that the ugraph argument gets modified. Alternatively, the function could take a copy of the graph so that the original is not modified.
In bfs_visited the lines:

queue = deque()
queue.append(node)

can be simplified to:

queue = deque([node])

The function largest_cc_size builds a list of pairs:

res = [(len(ccc), ccc) for ccc in cc_visited(ugraph)]
res.sort()
return res[-1][0]

But you can see that it only ever uses the first element of each pair (the size of the component). So you could simplify it by not building the pairs:

res = [len(ccc) for ccc in cc_visited(ugraph)]
res.sort()
return res[-1]

Since only the size of the largest component is needed, there is no need to build the whole list. Instead you could use max to find the largest:

if ugraph:
    return max(map(len, cc_visited(ugraph)))
else:
    return 0

If you are using Python 3.4 or later, this can be further simplified using the default argument to max:

return max(map(len, cc_visited(ugraph)), default=0)

This is now so simple that it probably doesn't need its own function.
This line:

remaining_nodes = set(graph.keys())

can be written more simply:

remaining_nodes = set(graph)

There is a loop over the set remaining_nodes where on each loop iteration you update remaining_nodes:

for node in remaining_nodes:
    visited = bfs_visited(graph, node)
    if visited not in connected_components:
        connected_components.append(visited)
    remaining_nodes = remaining_nodes - visited

It looks as if the intention of the code to avoid iterating over the nodes in visited by removing them from remaining_nodes, but this doesn't work! The problem is that the for statement:

for node in remaining_nodes:

only evaluates the expression remaining_nodes once, at the start of the loop. So when the code creates a new set and assigns it to remaining_nodes:

remaining_nodes = remaining_nodes - visited

this has no effect on the nodes being iterated over.
You might imagine trying to fix this by using the difference_update method to adjust the set being iterated over:

remaining_nodes.difference_update(visited)

but this would be a bad idea because then you would be iterating over a set and modifying it within the loop, which is not safe. Instead, you need to write the loop as follows:

while remaining_nodes:
    node = remaining_nodes.pop()
    visited = bfs_visited(graph, node)
    if visited not in connected_components:
        connected_components.append(visited)
    remaining_nodes.difference_update(visited)

Using while and pop is the standard idiom in Python for consuming a data structure while modifying it — you do something similar in bfs_visited.
There is now no need for the test:

if visited not in connected_components:

since each component is produced exactly once.
In compute_resilience the first line is:

res = [len(ugraph)]

but this only works if the graph is a single connected component to start with. To handle the general case, the first line should be:

res = [largest_cc_size(ugraph)]

For each node in attack order, compute_resilience calls:

res.append(largest_cc_size(ugraph))

But this doesn't take advantage of the work that was previously done. When we remove node from the graph, all connected components remain the same, except for the connected component containing node. So we can potentially save some work if we only do a breadth-first search over that component, and not over the whole graph. (Whether this actually saves any work depends on how resilient the graph is. For highly resilient graphs it won't make much difference.)

In order to do this we'll need to redesign the data structures so that we can efficiently find the component containing a node, and efficiently remove that component from the collection of components.

This answer is already quite long, so I won't explain in detail how to redesign the data structures, I'll just present the revised code and let you figure it out for yourself.

def connected_components(graph, nodes):
    """Given an undirected graph represented as a mapping from nodes to
    the set of their neighbours, and a set of nodes, find the
    connected components in the graph containing those nodes.

    Returns:
    - mapping from nodes to the canonical node of the connected
      component they belong to
    - mapping from canonical nodes to connected components

    """
    canonical = {}
    components = {}
    while nodes:
        node = nodes.pop()
        component = bfs_visited(graph, node)
        components[node] = component
        nodes.difference_update(component)
        for n in component:
            canonical[n] = node
    return canonical, components

def resilience(graph, attack_order):
    """Given an undirected graph represented as a mapping from nodes to
    an iterable of their neighbours, and an iterable of nodes, generate
    integers such that the the k-th result is the size of the largest
    connected component after the removal of the first k-1 nodes.

    """
    # Take a copy of the graph so that we can destructively modify it.
    graph = {node: set(neighbours) for node, neighbours in graph.items()}

    canonical, components = connected_components(graph, set(graph))
    largest = lambda: max(map(len, components.values()), default=0)
    yield largest()
    for node in attack_order:
        # Find connected component containing node.
        component = components.pop(canonical.pop(node))

        # Remove node from graph.
        for neighbor in graph[node]:
            graph[neighbor].remove(node)
        graph.pop(node)
        component.remove(node)

        # Component may have been split by removal of node, so search
        # it for new connected components and update data structures
        # accordingly.
        canon, comp = connected_components(graph, component)
        canonical.update(canon)
        components.update(comp)
        yield largest()

In the revised code, the max operation has to iterate over all the remaining connected components in order to find the largest one. It would be possible to improve the efficiency of this step by storing the connected components in a priority queue so that the largest one can be found in time that's logarithmic in the number of components.

I doubt that this part of the algorithm is a bottleneck in practice, so it's probably not worth the extra code, but if you need to do this, then there are some Priority Queue Implementation Notes in the Python documentation.

2. Performance comparison

Here's a useful function for making test cases:

from itertools import combinations
from random import random

def random_graph(n, p):
    """Return a random undirected graph with n nodes and each edge chosen
    independently with probability p.

    """
    assert 0 <= p <= 1
    graph = {i: set() for i in range(n)}
    for i, j in combinations(range(n), 2):
        if random() <= p:
            graph[i].add(j)
            graph[j].add(i)
    return graph

Now, a quick performance comparison between the revised and original code. Note that we have to run the revised code first, because the original code destructively modifies the graph, as noted in §1.2 above.

>>> from timeit import timeit
>>> G = random_graph(300, 0.2)
>>> timeit(lambda:list(resilience(G, list(G))), number=1) # revised
0.28782312001567334
>>> timeit(lambda:compute_resilience(G, list(G)), number=1) # original
59.46968446299434

So the revised code is about 200 times faster on this test case.


You could take advantage of the fact that push accepts more than one argument so you only call push once. Build the arguments array and use apply.

Array.prototype.push.apply($scope.committees, Object.keys(data).map(function(key){
  return data[key];
}));

Or if you're just putting values instead of actually appending to the existing array:

$scope.committees = Object.keys(data).map(function(key){
  return data[key];
});

Now for the AJAX part, you don't need to have a sequential request, that's that last thing you'd want to do in AJAX (besides making them synchronous). You'll need something like Promise.all or jQuery's $.when, fire them at the same time and resolve when all is done.

var comitteePromise = $http({method: 'GET', url: 'data.php'});
var employeePromise = $http({method: 'GET', url: 'data2.php'});

Promise.all([comitteePromise, employeePromise]).then(function(values){
  var committees = values[0];
  var employees = values[1];
  ...
});

The further I look into your code, what you're just doing is merging the data from both arrays. You can build a lookup for one array, and iterate the other. That way, two loops and not to the power of two loops.

var comitteePromise = $http({method: 'GET', url: 'data.php'});
var employeePromise = $http({method: 'GET', url: 'data2.php'});

Promise.all([comitteePromise, employeePromise]).then(function(values){
  var committees = values[0];
  var employees = values[1];

  // Use the committee code (assuming it's unique) as a key for lookup
  var committeesByCode = committees.reduce(function(carry, committee){
    carry[committee.code] = committee;
    return carry;
  }, {});

  // For each employee, lookup the committee and add in the data
  $scope.arr = employees.map(function(employee){
    var committee = committeesByCode[employee.code];
    return {
      committee: committee.name,
      color: committee.color,
      members: committee.members,
      femaleAnnual: employee.femaleAnnual,
      maleAnnual: employee.maleAnnual,
      totalAnnual: employee.totalAnnual
    };
  });

});


jQuery function to link nested checkboxes

Firstly use .prop not .attr if you are using jQuery v1.6+.

Secondly your code has a bug in it. When you click the parent then uncheck both the children then uncheck the parent it will then mark the children checked even though the parent is unchecked.

If you mean that the parent is "checked" when any of the children are "checked":

http://jsfiddle.net/FS3CC/1/

$.fn.linkNestedCheckboxes = function () {
    var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]');

    childCheckboxes.change(function(){
        var parent = $(this).closest("ul").prevAll("input[type=checkbox]").first();
        var anyChildrenChecked = $(this).closest("ul").find("li input[type=checkbox]").is(":checked");
        $(parent).prop("checked", anyChildrenChecked);
    });

    // Parents
    childCheckboxes.closest("ul").prevAll("input[type=checkbox]").first()
        .change(function(){
            $(this).nextAll("ul").first().find("li input[type=checkbox]")
                .prop("checked", $(this).prop("checked"));
        });

    return $(this);
};

Firstly in the //Parents change event you want to set the children to what ever the value of the parent no matter what.

This is the parent element:

// Parents
childCheckboxes.closest("ul").prevAll("input[type=checkbox]").first()

its change event means set all the child check boxes to the same value

.prop("checked", $(this).prop("checked"));

The child check box change event is slightly more complicated but basically it finds any child check boxes that are checked and sets the parent accordingly.

(if you meant that the parent should be check ONLY when all the check boxes are checked its slightly different so please comment as such.)

A different approach would be to specify who the parent is on the element:

<form>
    <input type="checkbox" name="parent" id="parent" />

<input type="checkbox" name="child1" data-parent="parent" />

<input type="checkbox" name="child2" data-parent="parent" />

</form>

Which would make the selectors easier:

(from child)

var parent = $("#" + $(this).data("parent"));

(from parent)

var children = $("input[data-parent=" + $(this).attr("id") + "]");