You've a lot of unnecessary code. First off, as janos stated:

local n = "0000000000"
n = no_as_string:gsub("[^0-9]", "")

  The initialization of n is pointless here.

You can instead use just the lua pattern to match your input to desired result:

function PhoneNumber:new( Number )
    local n = string.gsub( Number, "%D", "" )
    n = n:match "^1?(%d%d%d%d%d%d%d%d%d%d)$" or "0000000000"
    return setmetatable({ number = n, __index = self }, self)
end

Notice that I've changed the input argument to Number and later use string.gsub( Number.... This way; you've the advantage of inputting direct numbers and provide flexibility.

The pattern

"^1?(%d%d%d%d%d%d%d%d%d%d)$"

is self-explanatory. In lua, if string.match failed to find any matched group; it returns nil. I've used this property to check for bad numbers.

Next thing I'd suggest that you do is store the number as an integer instead of string:

return setmetatable({ number = tonumber(n), __index = self }, self)

This is just because integers take less memory than strings. For retrieving area code etc., use mathematical operations:

function PhoneNumber:areaCode()  -- what was symbol parameter for?
    return math.floor( self.number / 10^7 )
end

Lastly, lua provides a meta-method: __tostring for conversion to strings from other types. Use it (It is the reason why I was able to use string.gsub above):

function PhoneNumber:__tostring()
    local f, n = math.floor, self.number
    local sFormat, iPart1, iPart2 = "(%d) %d-%d", f( n / 10^7 ), f( n / 10^3 % 10^4 )
    return sFormat:format( self:areaCode(), iPart1, iPart2 )
end

Now, instead of calling PhoneObject:toString(), you can do:

tostring( PhoneObject )


The time complexity of your solution is O(n ^ 2), where n is the length of the given string. It is possible to do much better. Here is a linear solution:

static int getPalindromeIndex(String word) {
    if (isPalindrome(word))
        return -1;
    // Finds the first pair of characters that don't match.
    int left = 0;
    int right = word.length() - 1;
    while (word.charAt(left) == word.charAt(right)) {
        left++;
        right--;
    }
    // One of them must be removed and it sufficient to remove one of them.
    if (isPalindrome(word.substring(0, left) + word.substring(left + 1)))
        return left;
    return right;
}

The idea is the following:

If it is not a palindrome, there is a pair of positions (i, n - i - 1) such that characters on this positions do not match.
We can remove one of them. It is guaranteed that a solution always exists so we can try to remove the first one and check if a string is a palindrome. If it is the case, then we can just return it. Otherwise we can just return the second one.


You could theoretically overload the show action to only return the partial if request.xhr?. So if it's an ajax request, only render that button partial. But that's inelegant.

Alternatively, you can simply keep the default show action, send the entire page back, and just pluck out the button element (similar to how Turbolinks work). It'll keep the controller RESTful and keep the update-magic in the JS only. The trade-off is that you'll be rendering stuff that you won't actually use for anything. However, you can avoid some of it by disabling layout rendering for XHR requests (which is somewhat less kludgy than just rendering a partial; at least you're still rendering the show template).

However, having the publish button's state just defined by its color doesn't sounds like a very clear UI to me. Does a (presumably) green button mean "not published; clicking will publish" or "already published; clicking will unpublish"? I'd much prefer the button actually having a verb on it like "Publish" or "Unpublish" (or whatever you'd call it), so it's clear what the button will do.

Regardless, using the btn-sucess class gives you the desired look, but it's semantically meaningless. The class name doesn't really describe the current state or the action the button will take.

Picking the "re-render the show template"-option above will give you a chance to re-render the entire post with a published class. Then you can have a CSS rule like:

#post.published #publish-button {
  // set color etc.
}

Not as simple as using the generic btn-success class, but to me it makes more sense to track the state for the post as a whole, rather than a single button.

I imagine something like this for the view

<article id="post_123" data-url="..." class="<%= 'published' if @article.published? %>">

...

    ...

That'll mean that the element with the update URL is the same element that should be replaced by whatever is being sent back from the ajax-request. The JS only really needs to know that rule: Update the element with the data-url attribute. It doesn't need to know the specifics of re-styling individual elements.

Even if you don't go that route, toggling a published class in both view and JS is at least more readable/straight-forward that toggling a semantically unrelated class like btn-success.


Simple Chaining Implementation of HashMap

There is a bug in 'remove' method. A while loop never changes 'curr' object so in case when key is not equals then loop will never exit


Split Collection to two list depend on criteria

Here is a solution which replicates Guava's Predicate interface. Since this interface is really easy, here is how it is done:

public interface Predicate<T>
{
    // returns true if input obeys the predicate
    boolean apply(T input);
}

Given this interface, implement it for your types; and then do a method like this:

public static <T> List<List<T>> filteredLists(final List<T> list,
    final List<Predicate<T>> predicates)
{
    final int size = predicates.size();
    final List<List<T>> ret = new ArrayList<List<T>>(size);

    // Fill ret with initial lists
    for (int i = 0; i < size; i++)
        ret.add(new ArrayList<T>());

    // Now walk the predicates and add to the necessary lists

    for (final T element: list)
        for (int i = 0; i < size; i++)
            if (predicates.get(i).apply(element))
                ret.get(i).add(element);

    // Done! Return...
    return ret;
}

Now, if you had a utility class, say MyPredicates, with two methods even() and odd(), you could write:

final List<List<Integer>> filtered = filteredList(inputList,
    Arrays.asList(MyPredicates.even(), MyPredicates.odd()));

The "drawback" here is that it is up to the caller to remind what predicates where in what order in the calling lists, of course.

As to your MyPredicates hypothetical class:

public static final class MyPredicates
{
    // No instansiation
    private MyPredicates()
    {
    }

    public static Predicate<Integer> even()
    {
        return new Predicate<Integer>()
        {
            @Override
            public boolean apply(final Integer input)
            {
                return input.intValue() % 2 == 0;
            }
        }
    }

    public static Predicate<Integer> odd()
    {
        return new Predicate<Integer>()
        {
            @Override
            public boolean apply(final Integer input)
            {
                return input.intValue() % 2 == 1;
            }
        }
    }
}


You use a constant N as your variable... not dreadful, but a little confusing.

You first ask the user for how many times they want to run the code, then for which number to sum the mods of 3 & 5 for; it would be simpler to just write the code which asks for a number and works the sum - if the user wants to run it multiple times, then let them! :-)

No need to start at zero - 0,1, & 2 are never going to be divisible by three (although we'd need to add some validation in case the user adds a very low number)

Instead of setting up an intermediate arr value and iterating with each, you can select to get the numbers that return true for the block.

But your main question is about speed - have you benchmarked your code to find out if the speed is an issue?

n = gets.to_i
return 0 unless n > 2 # you could do this as a ternary or `if` statement if you prefer
(3...n).select { |j| j % 3 == 0 || j % 5 == 0 }.reduce(:+)


I had a general review primed up for this question, but other answers beat me to those more general aspects.

@TheKittyKat provided a good starting point on the most efficient means of calculating the sum of each sequence, and then subtracting the double-count

Now, the solution @TheKittyKat provides for each sequence, is, for example:

for (int i = 5; i < n; i += 5) {
    sum += i;
}

If we were to put this in a function:

public static int sumOfSequence(int value, int limit) {
    int sum = 0;
    for (int i = value; value < limit; i += value) {
        sum += i;
    }
    return sum;
}

So, having generalized that, we can do:

int total = sumOfSequence(3, N) + sumOfSequence(5, N) - sumOfSequence(15, N);

But, there's a trick, the function:

public static int sumOfSequence(int value, int limit) {
    int sum = 0;
    for (int i = value; value < limit; i += value) {
        sum += i;
    }
    return sum;
}

can be reduced to a single \$O(1)\$ operation using the math behind a Arithmetic Progression / sum-of-sequence

This boils down to the fact that the sum of a sequence:

$$
1k + 2k + ... + (n-1)k + nk  = \tfrac{n(1k + nk)}{2}.
$$

The equation:

$$
\tfrac{n(1k + nk)}{2}
$$

can be rewritten as:

$$
\tfrac{kn(1 + n)}{2}
$$

Now, either \$n\$ or \$(1 + n)\$ is even, and any even number times any other even number, is even, so you can always safely halve it.

Thus, the function can be reduced to:

public static int sumOfSequence(int value, int limit) {
    final int count = (limit - 1) / value;
    return value * count * ( count + 1) / 2;
}

So, the end result, is:

public static int sumOfSequence(int value, int limit) {
    final int count = (limit - 1) / value;
    return value * count * ( count + 1) / 2;
}

public static void main(String[] args) {

    int limit = 1000;

    int sum = -sumOfSequence(15, limit) + sumOfSequence(3, limit) + sumOfSequence(5, limit);
    System.out.println(sum);
}


This may sound harsh, I meant to be friendly though :)

It's bad/unsafe/vulnerable. This type of situation comes around a lot, which is sort of understandable. However, what is your class really doing? It's essentially pointless to make this class. You've basically just put a class in a class without doing anything different! So actually what you've done is make things less secure.

You mentioned a "more dangerous" option of preparing the query. That would be a false assumption. Preparing queries are one of the largest features of the PDO and MySQLi interfaces. They're far from dangerous if used correctly.

It's hard to tell if what you're really doing is "secure" because the actual SQL handling functions you've left out.

Now that that's out of the way...

To improve your coding, you can:

Fix indentation
Pick a coding style and apply it. You want clean code, not messy. Here's Zend's styles, which is one I like to offer because it's easy to follow and apply.

Then you're code will be nice and tidy!

Hows 'bout that PHP now!

Starting from the top:

$host = 'mysql:host' . $this->_hostname ';dbname' . $this->_database;

Where are you getting $_hostname and $_database? Same with $_username and $_password. It's okay to add those in your question next time (just without the actual values!) :)

In you first try...catch you have a typo. The assignment to this->db should really be $this->db. I'm not sure why you didn't receive an error for that.

This

public function execute() {
    return $this->stmt->execute();
}

is a nice try, but what's it's point? It's really not useful at all. That's be another reason home-made DB access classes aren't so great. If you do keep it, is it being called by the caller? If not, then you could make it private at least.

In both results() and result(), you return the associative array (PDO::FETCH_ASSOC) which may not be the best idea. What if you want to change the format of return down the line? There's not one easy way to do this.

Speaking of those two functions, I suggest you changes their names. I almost started to write how you had to of the same function. It's hard to tell them apart is what I'm saying.

So overall, there are many database access classes that come with frameworks that actually do improve the safety and handling of databases, unfortunately it's difficult to replicate your own. Don't be discouraged though! It's not a simple task, Laravel has about 50 different classes + interfaces just to make sure connecting to the database is perfect!


8051 RFID reader for Atmel microcontroller

Here are some ideas that may be useful to you.

Decide what's most important

Since the 8051, including your AT89S52 variant, has few resources, you'll have to make some hard decisions on how to use them.  If you're already using the single serial port for some other purpose and it's fixed for some reason (e.g. can't respin boards), then perhaps it's out of your hands.  If not, then taking a good look at both UART uses would likely be useful.  It would be most useful to put the less frequent, lower bit rate, less important traffic on a software UART.  Sometimes the right choice is readily apparent; other times not so much.  Another possibility is to multiplex them into the single hardware UART, but of course that only works if it's acceptable to block reception of one UART while the other is receiving.

Use an interrupt

The sole purpose for the delays is timing, so I'd suggest using a timer instead.  As you know, this CPU only has three timers and Timer 2 is tied to the Baud Rate Generator for the hardware UART, so that leaves Timer 0 and Timer 1.  You may be able to use one of those in either mode 0 (13-bit timer) or mode 1 (16-bit timer).  One way to do this would be to use two interrupts.  One interrupt would be set to trigger on the falling edge of RX.  Once that's detected, disable that interrupt and enable a timer interrupt for half bit time.  When the timer triggers, read the bit and if it's not a 0, that is, not a true start bit, disable the timer interrupt and re-enable the falling edge interrupt.  If it is a zero, count it as a start bit and set the timer for a full bit time.  Thereafter, just read the bits for each timer interrupt until you get to the stop bit.  If the stop bit is not 1 when it's supposed to be, you'll probably want to signal a framing error.  If it is, the byte is probably good and can be stored.  Either way, disable the timer interrupt and re-enable the falling edge interrupt.  It's not ideal, but it should work, given the limitations.


Calculate min, max, mean and median out of array

I see a number of things that may help you improve your program.

Don't violate const

The calculate_median routine takes a const array, makes a duplicate and then sorts the original!  I think you meant to sort the duplicated array instead.

Understand pointers

In main there's this line:

int numbers[] = { 1,7,3,4,5,6,7,8,9 }; // 9 elements
// other stuff
struct Result result = calculate_values(&numbers, len);

The problem is that &numbers is not really what you want.  With an array, the name is already effectively a pointer to the array, so you don't need & at the front in this context.

Don't leak memory

The intdup function allocates and copies the passed array, but then that memory is never freed.  I'd suggest freeing the memory again as soon as the function is done with the duplicate array.

Think about naming

The variables len and mean are good because they suggest the significance of these variables in the context of the program.  However, result and numbers are a little generic.  I'd suggest perhaps summaryData and testArray as possible replacement names.

Eliminate unused variables

The tmp variable within calculate_median is never used.  Since unused variables are a sign of poor code quality, you should seek to eliminate them.  Your compiler is probably smart enough to warn you about such things if you know how to ask it to do so.

Think about efficiency

This suggestion is last for a reason.  It's important to have a correct program first, and then optimize for space/time efficiency.  In this case, a productive approach is suggested by the wording of the question itself:

  Write a function that takes an array of 'ints' as its input and finds the smallest and largest elements. It should also compute the median and mean. Use a struct holding the result as the return value.

It says to write a function and that's a good strategy for this.  Since you're sorting the array anyway to get the median, you could also use the sorted array to easily get the min and max values from that sorted array.  The mean could be calculated the same way you're currently doing it, but this would reduce the number of times that the array would need to be traversed.


Filling an array with the same data at a regular interval without a for loop

For starter, I would suggest making a function out of this pile of code so its easier to read an reason about:

def create_surface(bins_count=50, radius_start=0.0001, radius_end=50):
    radii = np.linspace(radius_start, radius_end, bins_count, endpoint=True)
    thetas = np.linspace(0, np.pi / 2, bins_count, endpoint=True)

    coordinates = np.vstack([radii, thetas]).T

    surface = np.zeros((bins_count**2, 3))
    lower_bound = 0
    upper_bound = numbins

    # this is the size of the bin for phi
    delta_phi = (2 * np.pi) / bins_count

    for phi in np.linspace(0, (2 * np.pi) - delta_phi, bins_count):
        surface[lower_bound:upper_bound, :2] = coordinates
        surface[lower_bound:upper_bound, 2] = phi
        lower_bound += bins_count
        upper_bound += bins_count
    return surface

Optionnally, throwing in a docstring here wouldn't hurt.

Now this function has two purposes: compute the coordinates and build a surface out of it, let's split things up.

def build_coordinates(bins_count=50, radius_start=0.0001, radius_end=50):
    radii = np.linspace(radius_start, radius_end, bins_count, endpoint=True)
    thetas = np.linspace(0, np.pi / 2, bins_count, endpoint=True)

    return np.vstack([radii, thetas]).T

def create_surface(coordinates):
    bins_count, two = coordinates.shape
    assert two == 2

    surface = np.zeros((bins_count**2, 3))
    lower_bound = 0
    upper_bound = numbins

    # this is the size of the bin for phi
    delta_phi = (2 * np.pi) / bins_count

    for phi in np.linspace(0, (2 * np.pi) - delta_phi, bins_count):
        surface[lower_bound:upper_bound, :2] = coordinates
        surface[lower_bound:upper_bound, 2] = phi
        lower_bound += bins_count
        upper_bound += bins_count
    return surface

Usage being phi_slice = build_coordinates(50); surface = create_surface(phi_slice). With the advantage of being able to build several surfaces out of the same coordinates.

Now let's start to look into removing that for loop. So basicaly, the surface you want to build should look like:

[[r0, Θ0, φ0],
 [r1, Θ1, φ0],
 ...
 [rn, Θn, φ0],
 [r0, Θ0, φ1],
 [r1, Θ1, φ1],
 ...
 [rn, Θn, φ1],
 ...
 [r0, Θ0, φn],
 [r1, Θ1, φn],
 ...
 [rn, Θn, φn]]

Where

[[r0, Θ0],
 [r1, Θ1],
 ...
 [rn, Θn]]

are the coordinates (your phi_slice) and

[φ0, ..., φn]

are np.linspace(0, (2 * np.pi) - dphi, numbins).

So better build surface by repeating phi_slice and the elevations enought time and then concatenating them together rather than copy/pasting them into a blank array.

This is rather simple since numpy provides np.repeat and np.concatenate. But both have their specifics:

np.repeat return a flat array when no axis is given and repeat each element the requested amount of time before starting to repeat the next one. This is exactly what is needed for the elevations:

>>> np.repeat(np.array([φ0, φ1, φ2]), 3)
array([φ0, φ0, φ0, φ1, φ1, φ1, φ2, φ2, φ2])

But not quite so for the coordinates:

>>> np.repeat(np.array([[r0, Θ0], [r1, Θ1], [r2, Θ2]]), 2, axis=0)
array([[r0, Θ0],
       [r0, Θ0],
       [r1, Θ1],
       [r1, Θ1],
       [r2, Θ2],
       [r2, Θ2]])

Instead, we would like to repeat the whole block of coordinates at once. So let's add a dimension to repeat along it and then reshape the result to remove the extra dimension:

>>> coordinates = np.array([[r0, Θ0], [r1, Θ1], [r2, Θ2]])
>>> np.repeat(coordinates[np.newaxis, :, :], 2, axis=0).reshape(6, 2)
array([[r0, Θ0],
       [r1, Θ1],
       [r2, Θ2],
       [r0, Θ0],
       [r1, Θ1],
       [r2, Θ2]])

Where 6 is the length of axis 0 times the amount of repetitions.

The last step being to combine both repeated arrays using np.concatenate. However concatenate requires that both array have the same amount of axis so we need to add one to the elevation vector:

>>> elevations = np.repeat(np.array([φ0, φ1, φ2]), 3)
>>> coordinates = np.array([[r0, Θ0], [r1, Θ1], [r2, Θ2]])
>>> repeated_coordinates = np.repeat(coordinates[np.newaxis, :, :], 3, axis=0).reshape(9, 2)
>>> np.concatenate((repeated_coordinates, elevations[:, np.newaxis]), axis=1)
array([[r0, Θ0, φ0],
       [r1, Θ1, φ0],
       [r2, Θ2, φ0],
       [r0, Θ0, φ1],
       [r1, Θ1, φ1],
       [r2, Θ2, φ1],
       [r0, Θ0, φ2],
       [r1, Θ1, φ2],
       [r2, Θ2, φ2]])

This yield:

def build_coordinates(bins_count=50, radius_start=0.0001, radius_end=50):
    radii = np.linspace(radius_start, radius_end, bins_count, endpoint=True)
    thetas = np.linspace(0, np.pi / 2, bins_count, endpoint=True)

    return np.vstack([radii, thetas]).T

def create_surface(coordinates):
    bins_count, two = coordinates.shape
    assert two == 2

    elevation = np.linspace(0, 2 * np.pi * (1 - 1/bins_count), bins_count)
    elevations = np.repeat(elevation, bins_count)
    coords = np.repeat(coordinates[np.newaxis, :, :], bins_count, axis=0).reshape(bins_count**2, 2)

    return np.concatenate((coords, elevations[:, np.newaxis]), axis=1)


The name Converter is pretty ambiguous. It could mean anything.
I'd suggest doing less work in the initializer, and more lazy evaluation.
Skip that self line in the initializer - it's an initializer; it'll always return self (or, technically, it doesn't matter what the initializer returns, since you'll be calling new and that will return the new instance. Point is, skip that line)
Use Enumerable#inject to do the sum
Use String#chars instead of String#split
It'd probably be better to raise right away in the initializer if the string isn't a binary number. Also better to raise an ArgumentError while you're at it.
You can check the string with a simple regular expression: /^[01]*$/
Your #two_to_power_of method can be replaced with 2 ** n
Don't use prefixes like is_ and get_ in your method names (specifically, is_set?, get_bits and get_total); it's not Ruby's style. For instance, the nil? method isn't called is_nil?, and the chars method mentioned above isn't called get_chars.
All methods return something so a get_ is redundant, and a ? suffix is a substitute for an is_ prefix, just like a = suffix is a substitute for a set_ prefix.
Favor accessor methods over directly accessing instance variables. Such indirections allow for better internal decoupling. That is, as soon as you start accessing a value through a method, you make your class more flexible. You can begin with simple attr_reader-synthesized methods, which will of course not do anything special, but should you ever need or want to  add more logic, you need only change the accessor method(s). In this case, however, a first step would be to simply use fewer instance variables (see #2)
A class method might be nice for quick conversions, so you don't always have to deal with instantiating an object. E.g. a class method could allow you to say Converter.convert("101010") and get 42 directly. It'd just be a shortcut for Converter.new("101010").to_base_ten, but that's still a nice shortcut to have.
Might be nice if you could specify endianness of the binary number, instead of assuming it's always little endian.

In the end, I get something like this, if we want memoization of the converted values:

class BinaryNumberConverter
  attr_reader :binary

  def self.convert(string, little_endian = true)
    self.new(string).base_ten(little_endian)
  end

  def initialize(binary)
    if binary =~ /^[01]*$/
      @binary = binary
    else
      raise ArgumentError.new("'#{binary}' is not a valid binary number")
    end
  end

  def base_ten(little_endian = true)
    little_endian ? little_endian_value : big_endian_value
  end

  private

  def little_endian_value
    @little_endian ||= convert(binary.reverse)
  end

  def big_endian_value
    @big_endian ||= convert(binary)
  end

  def convert(string)
    string.chars.each_with_index.inject(0) do |sum, digit|
      char, index = digit
      sum += char == "1" ? 2 ** index : 0
    end
  end
end

Usage:

instance = BinaryNumberConverter.new("101010")
instance.base_ten        # => 42
instance.base_ten(false) # => 21

BinaryNumberConverter.convert("101010")        # => 42
BinaryNumberConverter.convert("101010", false) # => 21

Of course, it'd be a lot simpler to just extend String rather than make an entire class:

class String
  def bin_to_dec(little_endian = true)
    raise "'#{self}' is not a valid binary number" unless self =~ /^[01]*$/
    digits = little_endian ? reverse.chars : chars
    digits.each_with_index.inject(0) do |sum, digit|
      char, index = digit
      sum += char == "1" ? 2 ** index : 0
    end
  end
end

And you get

"101010".bin_to_dec        #=> 42
"101010".bin_to_dec(false) #=> 21

No memoization, but I'd call that pretty clean.

Took a quick look at your tests, and it's a bit overkill (also, you should use the expect syntax of rspec; the should syntax is old-school).

I'd actually just do something like

number = rand(12345) # can be anything really
string = number.to_s(2)
expect(string.bin_to_dec).to eq(number)

And call it good. You'll note I'm using to_s(2) above, but here it makes sense. We have to assume that Ruby works anyway, so in this case, it's a perfect yardstick. Similarly, to check big endian conversion, we can use to_i(2) with a clear conscience

string = rand(12345).to_s(2).reverse
expect(string.bin_to_dec(false)).to eq(string.to_i(2))

Add a test for the exception raising, and you've tested everything.

On another note, you say you "wanted to use a minimum of functions that come with Ruby by default as that would sort of defeat the purpose of this as a practice program". But I'd recommend you use as much built-in functionality as possible, especially in your practice programs (in this case stopping short of using String#to_i, of course).

Learning any language is usually less about learning the language itself (as in syntax), as it is about learning the conventions, idioms, and the built-in goodies. Intentionally doing things "the hard way" will probably teach you the wrong lessons. And the code you write won't teach you conventions and idioms, because it's unconventional to make things hard for yourself and no idioms exist for it.

Besides, at first, the easy solution will actually be the difficult one, because the easy solution is the one that requires experience. But brute-forcing your way though a problem won't earn you that experience and will actually teach you a lot less than trying to use the language to your advantage.


Given a String, return a boolean if it is a number

Instead of reading the output of those print statements, it's better write proper unit tests to verify your implementation:

@Test
public void testValidInteger() {
    assertTrue(isNumber("123"));
}

@Test
public void testValidStartsWithDecimal() {
    assertTrue(isNumber(".123"));
}

@Test
public void testValidNegativeStartsWithDecimal() {
    assertTrue(isNumber("-.123"));
}

@Test
public void testValidDecimal() {
    assertTrue(isNumber("1.23"));
}

@Test
public void testValidMinusZero() {
    assertTrue(isNumber("-0"));
}

Your implementation passes all these, which is good. I would add at least two more:

@Test
public void testValidEndsWithDecimal() {
    assertTrue(isNumber("123."));
}

@Test
public void testValidDecimalLooooong() {
    assertTrue(isNumber("1.2311111111111111111111111111111111111111111"));
}

The second passes but the first doesn't and maybe it should, no?

For testing cases of non-numbers:

@Test
public void testNotValid() {
    assertFalse(isNumber("-."));
    assertFalse(isNumber(".-"));
    assertFalse(isNumber("12.34.56"));
    assertFalse(isNumber("-"));
    assertFalse(isNumber("12$%^&*#"));
    assertFalse(isNumber("hello"));
    assertFalse(isNumber("   "));
    //assertFalse(isNumber(""));
}

It would be good to split these to individual cases as I did for the valid cases. I leave that for you as an exercise. I added some more cases here too, and unfortunately the one with empty string doesn't pass. I think that's a bug.

As per your implementation, it seems more complicated than it needs to be.
Most importantly, I'm wondering if the interviewer would consider regular expressions as "parse function". If not, then the implementation can be simplified:

public static boolean isNumber(String toTest) {
    return toTest.matches("[+-]?(\\d*\\.?\\d+)|(\\d+\\.?\\d*)");
}

This passes all the above tests. To correct and simplify your implementation, it should not be terribly difficult to implement the logic of the regular expression.


How to avoid code duplication in ordering system

You are right that you have code duplication where no duplication should be. As far as I can see from the code you have posted, nothing really changes if you would write a class that would handle it as a BaseOrder, since all the properties you are referring to are available on the BaseOrder (except for OrderItems, however this could be retrieved through an extra method implementing it)

So you could write your class more like

Public MustInherit Class BaseOrderConfirmation
    Private _itransactionService As ITransactionService

    Protected MustOverride Function GetOrderItems(order as BaseOrder) As IEnumerable(Of BaseItem)

    Protected Sub AssignNewTransactionsToOrderItems(orders As List(Of BaseOrder))
        For Each order In orders
            For Each item In GetOrderItems(order)
                If (Not item.TransactionId.HasValue) Then
                    Dim newTransactionId = _itransactionService.GenerateTransactionId()
                    _itransactionService.AssignTransactionToOrderItem(order.OrderReference, item.Sku, item.Id, newTransactionId)
                    item.TransactionId = newTransactionId
                End If
            Next
        Next
    End Sub

    Protected Sub FilterForConfirmation(orders As IEnumerable(Of BaseOrder))
        For Each order In orders
            GetOrderItems(order).RemoveAll(Function(i) _itransactionService.IsTransactionProcessedSuccesfully(order.OrderReference, i.Id))
        Next
    End Sub
End Class

This would now be an abstract class (ie: a class that cannot be instantiated), from which the GetOrderItems method has to be implemented still.

Also note, that this change means that all methods now changed from Private modifier to the Protected modifier

In the implementing classes you can then implement something like:

Public Class SoOrderConfirmation
    Inherits BaseOrderConfirmation

    Protected Overrides Function GetOrderItems(order as BaseOrder) as List(Of BaseItem)
        return DirectCast(order, SoOrder).OrderItems
    End Function
End Class

Preferably though, the GetOrderItems method shouldn't return anything that can be modified. I wish I could create it as an IEnumerable(Of BaseItem) instead, however, that would not work with your FilterForConfirmation method.

As I do not know how you intend to filter, I chose to keep the List(Of BaseItem). The filter also doesn't seem to filter, but rather seems to remove items from that list, so without knowing how you are using it, I chose to stick with List(Of BaseItem).


LeetCode 560: Subarray Sum Equals K - C++/Java

I have some suggestion for the Java version
Always try to pass the size of the maximum size to the Collection / Map constructor when known
The map has a default size of 16 elements, if you have more elements, the map will have to resize its internal cache. By setting the size, you can prevent the resize and make your code faster.
In this case, you can set the maximum size since it's based on the size of the array + 1.
Map<Integer, Integer> prefixSum = new HashMap<>(nums.length + 1);

Extract the expression to variables when used multiple times
In your code, when you check if the key is present, you can extract the value to a variable to reuse it when present.
Before
if (prefixSum.get(sum - target) != null)
   subarrays += prefixSum.get(sum - target);

After
Integer currentValue = prefixSum.get(sum - target);
if (currentValue != null)
   subarrays += currentValue;

This will be better, since this will prevent the rechecking and the rehashing in the map.
Always add curly braces to loop & if
In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.
Before
if (prefixSum.get(sum - target) != null)
   subarrays += prefixSum.get(sum - target);

After
if (prefixSum.get(sum - target) != null) {
   subarrays += prefixSum.get(sum - target);
}

Extract some of the logic to methods.
In this case, I suggest to extract the map creation to a method; this will allow to group the logic and make the main code shorter.
public int subarraySum(int[] nums, int target) {
   Map<Integer, Integer> prefixSum = buildMap(lengthOfNums + 1);
   //[...]
}

private Map<Integer, Integer> buildMap(int defaultSize) {
   Map<Integer, Integer> prefixSum = new HashMap<>(defaultSize);
   prefixSum.put(0, 1);
   return prefixSum;
}


Is this a safe way of using HTTP query parameters to build a SQL query?

It is safe. You have a white list of allowed values and ensure that the user provided input is on the list.

But I'd still do the white list checking as the very first thing, and then do the other processing later, so it would be:

$field = 'name';
$direction = 'asc';
if(preg_match('^([a-z]+)_(asc|desc)$', $_GET['order'], $matches)) {
    if(in_array($matches[0], array("name", "level", "vocation"))) {
        $field = $matches[0];
        $direction = $matches[1];
    }
}

What happens here is that the block splits up and validates the input. You can be sure that once you're past this block, $field and $direction can be trusted. An important point is to use $_GET['order'] exactly once, since accessing it multiple times may lead to errors that will leak non-validated data.


Getting list from an Oracle database and storing it in an object

Well my first gut reaction is that I don't like what I see. Here is why though and hopefully that will help you understand why I feel this way. First is with the naming convention. GetAdminInfo is a verb. Classes are nouns. This is true in all of mainstream OO languages. Therefore a more appropriate name would be AdministratorInformation. But even that name is misleading because of the contents. Your class has 2 arrays which of type String. Since you are dealing with a database it would be ok to make a class called AdministratorGroup which has 2 properties Name and Id with appropriate Getters and setters. Then your AdministratorInformation class would be renamed to AdministratorGroupCollection and have only 1 Array of type AdministratorGroup. Now after you put this program down for some time and come back to it you will find it easier to remember what these classes do. A name should always indicate its intent. You would be very angry at me if i had a class called CartesianPoint and instantiated it like this CartesianPoint point = new CartesianPoint("5Mhz"); You'd be angry because I lied to you. I normally don't do this as I leave it up to you to make changes, but I want to show some sort of code. SO here is what your code would look like after I got my hands on it.

AdministratorInfo

public class AdministratorInfo
{
    private String ID;
    private String name;

    public String getID()
    {
        return ID;
    }
    public String getName()
    {
        return name;
    }

    public void setID(String ID)
    {
        this.ID = ID;
    }
    public void setName(String name)
    {
        this.name = name;
    }
}

AdministratorGroupCollection

public class AdministratorGroupCollection
{
    private List<AdministratorInfo> persons;

    public List<AdministratorInfo> getPersons()
    {
        return persons;
    }

    public void setPersons(List<AdministratorInfo> newList)
    {
        persons = newList;
    }
}

With this code you will not have to add more and more Lists to your collection class to add or remove properties. You'll only have to change the AdministratorGroup class to adjust those properties.

Last point I want to point out is the confusing basis for your SQL method. By the name of it I get the impression that you are returning a single user and not a collection of users. but your code says that you are returning a collection of users. Don't let your names and methods lie about their intent. If you only intend to return a single user then return a class that is not a collection. If your intent is to get a group or a collection of things then you will return a list. Otherwise you are just making it hard for others (others can mean you in the future) to know how to use your code. Although I would break this method up some more to make it a little bit easier to read it serves its purpose. This is how I interpreted your code, and how I would have fixed it.

public static AdministratorInfo fetchPersonIdInfo(String adminGroup) throws SQLException
{
    AdministratorInfo personInfo = new AdministratorInfo();
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    try
    {
        connection = createConnection();
        statement = connection.prepareStatement("SELECT PERSON_ID,PERSONS FROM ADMIN_INFO WHERE ADMINGROUP = ?");
        statement.setString(1, adminGroup);
        rs = statement.executeQuery();
        if (rs.next())
        {
            //what purpose does it serve to change adminGroup?
            adminGroup = rs.getString(COLUMN_ADMINGROUP) != null ? rs.getString(COLUMN_ADMINGROUP) : "";
            personInfo.setID(rs.getString(1));
            personInfo.setName(rs.getString(2));
            personInfo.setDeviceIds(deviceId); //I don't like not knowing what this is
        }

    }
    finally
    {
        rs.close();
        connection.close();
        statement.close();
    }

    return personInfo;
}


public interface IView
{
    Controller Controller { set; }
}

NO!!
You have just coupled the View with the Controller, which defeats the entire purpose.
This is also broken:

public abstract class Controller
{
    protected readonly IModel model;

    protected readonly IView view;

    protected Controller(IModel model, IView view)
    {

Now you have a circular dependency, with the controller knowing about the view, and the view knowing about the controller - but the controller knowing about the view and model is fine:

I don't understand this line:

Thread.Sleep(5000);

Why sleep for five whole seconds?

I'll just add that the naming convention, as noted by BCdotNET, is off: ControllerPerson should be PersonController - not because that's how ASP.NET MVC has it, but because C# and the .NET framework in general does it that way; it's just a matter of consistency... and it's what someone maintaining your code would expect to see.


Risks related to overriding attribute access

I'd start with the caveat that you're buying some syntax sugar at the cost of possible bugs - the need to do the attribute resolution, and as you point out the possibility of name clashes, makes it seem like it may not be worth the effort unless you need to access these class properties in lots of places in your code.

That said you can simplify this by converting your sections - which are dictionaries -- to namedtuples:

from collections import namedtuple

def section2dict(self, secname):
   if secname in self.__dict__:
      raise KeyError, "%s is cannot be used as a property name" % secname
      opts = self.options(secname)
      #nb: I didn't bother recreating the type code, but you would do it here...
      nt = namedtuple(secname, opts.keys())(**opts)
      self.__dict__[secname] = nt

By sticking the result into dict you don't have to override getattr yourself, which limits the intervention to a single place although it does deprive you of the option to do guard checks for bad values, etc.   This example would except on name collisions and get you off the hook for manually redirecting double-dotted attribute queries.


Calling an Oracle Stored Procedure with C# Code

I could see using it for the connection, command and reader since they implement IDisposable and the documentation for them does say to always call Dispose().

For the parameters it seems not only unnecessary but in my opinion it really decreases readability.  I would kill the using statements for the parameters and make them simple declarations.

For what it's worth, here's how I'd write it.

private static Dictionary<string, List<string>> GetSubscriptionKeyList(string proc)
{

    var result = new Dictionary<string, List<string>>();
    result.Add("Adds", new List<string>());
    result.Add("Deletes", new List<string>());

    using (var conn = new OracleConnection(conStr))
    {
        conn.Open();
        using (var cmd = new OracleCommand(proc, conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new OracleParameter("p_add", OracleDbType.RefCursor, ParameterDirection.Output));
            cmd.Parameters.Add(new OracleParameter("p_delete", OracleDbType.RefCursor, ParameterDirection.Output));

            using (var rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    result["Adds"].Add(rdr.GetString(0));
                }
                rdr.NextResult();
                while (rdr.Read())
                {
                    result["Deletes"].Add(rdr.GetString(0));
                }

            }
        }
        conn.Close();
    }
    return result;
}

Obviously some things are a matter of taste, like whether to declare the parameters on a separate line and whether to keep the initializers there for the dictionary.  (I thought it was more clear to separate them.)


PHP download counter script with htaccess

You are doing a lot of things right. You are using a whitelist instead of a blacklist for extensions, you are using pathinfo to get the extension, you clean nullbytes (optional, but still good practice), you use basename in the filename (also optional), you have a strict whitelist for filenames (theoretically), you use a good content type, and so on.

There is one issue, and two small suggestions:

Your filename whitelist allows all characters between ascii 0 and ascii 57, eg NUL, TAB, !, ", <, etc. Given the rest of your code, I'm assuming that this is a bug and that you only wanted to allow alphanum + umlaute. The same is true for the extension filter.
There is pretty much never a good reason to use REQUEST. You probably know the HTTP method you are using, so you should use that. This is somewhat of an issue if the method is POST, as an attacker can downgrade that to GET, which can make exploitation of some issues easier.
You may want to consider checking if the resolved $finalpath is inside the download directory. This isn't necessary right now, as your pathinfo approach as well as your whitelist both on their own are defense enough against directory traversal. But it is best-practice, and it may be useful if the code is reused in a different context, or if your whitelist (and pathinfo) approach need to be changed for some reason.

Regarding non-security aspects:

Your comments do not add all that much and should probably be removed. Some can be used to create better variable names (filetypes might be allowedExtensions), others are just repeating the code, and some are somewhat unclear (what is a local extension?).
Your ifs are a bit too nested for my taste. If you reverse the ifs they will be easier to read. If you return/die on the else case, you would also get rid of the nesting.


Enforce what is passed to an activity in an intent similar to the newInstance pattern for fragments

Your solution looks great to me, apply Fragment's instantation to a Class seems to be a good pattern and a nice idea. However, I have just a little tip for this static method: pass the current Context instead of Application Context:

public class SampleActivity extends BaseActivity {
    public static Intent createIntent(Context context, String[] a, String b) {
        Intent intent = new Intent(context, SampleActivity.class);
        intent.putExtra(AppConstants.KEY_ARG_ARRAY,  a);
        intent.putExtra(AppConstants.KEY_ARG_STRING, b);
        return intent;
    }
}

This allows you to get the right Activity calling the new Intent instead of whole application context. So, the called syntax could be:

startActivity( SampleActivity.createIntent(this, a, b) );
// 'this' being the calling class Context (like 'MainActivity.this' or 'getActivity()')


The code is written in a nice, clean style.
It's easy to read like that, which helps the reviewer a lot, keep it up!

This sort of thing doesn't make much sense:

class Email {
    // ...
    public function sendEmail(Email $email) {

It's strange to pass an object of its own type as a method parameter.
Normally you would do such thing in a copy-constructor or some kind of clone or factory method, where you want to build a copy from the parameter.
But that's not the case here.
And in any case, the sendEmail implementation as it is doesn't use the $email parameter for anything: you can safely remove it.

Another big problem with this method is that it makes assumptions that are not enforced programmatically: before the method is called, body, displayName and other fields must be set. If you forget to set some of them, the program may still work and might not raise obvious errors, but you can experience nasty bugs.

Here's a safer alternative:

public function sendEmail($fromEmailAddress, $displayName, $body, $toEmailaddress) {
    // ...
}

There are no hidden assumptions here: the only way to call this method is by adding all parameters. You cannot forget any of them, the code won't compile.

Note that with this implementation the class becomes a utility class with no member data.
At which point it can be just a standalone function,
it doesn't really need to belong to a class.

Another issue is error handling:

if (!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
    exit;
}

So if email sending fails, you exit, effectively crashing the program.
Most probably you want to return false instead,
and the caller should handle gracefully.

Even if this script runs as a batch program without a user friendly web interface,
the exit points of programs are best controlled in one place,
the caller of this method, or even higher in the call stack,
not buried inside utility methods.


Start task as soon as multiple tasks are successful

Well, whatever you do, you should only re-check those sources which have not finished, so you should remember which have finished already, or equivalently, only those which have not.

class MatchCollector:
    def __init__(self, teams, sources=settings.sources):
        self.teams = teams
        self.sources = sources
        self.unfinished = {SourceCollector(source, teams) for source in sources}
        self.timeout = 600  # s
        self.iterations = 1000 # arbitrarily chosen, have to make calc, when would be a good point to give up

    def execute(self):
        counter = 0
        while self.unfinished:
            self.unfinished = {source for source in self.unfinished if not s.execute()}
            time.sleep(self.timeout)
            counter += 1
            if counter >= self.iterations
                 raise IterationException('Tried for x hours without success. Somethings broken')
        d = DataAggregator(self.sources)
        d.execute()

This assumes that SourceCollector.execute can be run repeatedly without needing to re-initialize it. If this is not the case, just do self.unfinished = {source for source in self.unfinished if not SourceCollector(source, self.teams).execute()}.

Note that doing counter += counter is probably not what you want. Since you initialize it to 0, it does 0 + 0 = 0, so nothing. If you had initialized it to a non-zero value, it would also not simply count up, but double every iteration.

I also made the timeout between retries and the number of iterations members of the class so they are no longer magic numbers.

You should also follow Python's official style-guide, PEP8, which recommends using spaces around = in assignments and after commas in argument lists of functions and methods.


Here are a few things I thought of:

Use let when you can, it is a pretty versatile function for testing.

before :all
  @city = City.new :country_version, :directory, :country_host, :locale
end

Can be rewritten as:

let(:city) { @city = City.new :country_version, :directory, :country_host, :locale }

This will only call city when you use it.
I don't typically test accessors/intatiation but if I did, I would probably test it with a specify block, it is also good for most tests where the description is "it should do something correctly":

This is nice for simple tests that explain themselves

specify { city.should be_an_instance_of City }
When testing, I try to think in terms of cases:
Ex:

it "should act in manner x when no cities are found"
it "should act in manner y when 1 city is found"
it "should act in manner z when n cities are found"

I find testing 0, 1, n catches a lot of potential errors
The testing gods expect you to test first, then write code.  If you don't :D, then make sure that your test fails in the way you expect it to.


Are these scripts secure?

They are not. All three scripts are vulnerable to directory traversal.

This is what an attacker can achieve with each script:

uploadscript.php: upload files with certain extensions to arbitrary directories, for example to deface the main site. This isn't that serious, but should be fixed.
downloadscript.php: download arbitrary files. This is serious, and needs to be fixed. An attacker can read any files the webserver has access to, thus revealing sensitive information.
deletescript.php: delete arbitrary files in arbitrary directories. This may possibly be used to bypass authentication in your application (eg by deleting something like authentication.php), or to make your application unusable (DOS).

You need to sanitize your inputs (basename for filenames, .. filter for directories, although you could filter stricter), and you need to check if the normalized filename + path is inside the directory you want it to be in.

Note also that even if you fix this, as ids are passed from the user, users will still be able to upload files to other users directory, read files of other users, and delete files of other users.

Note also that getimagesize is nice as defense in depth, but can easily be bypassed. I would remove the comment as to not leave a false sense of security (it's mainly a usability check).

Misc

Comments that just repeat what the code does are usually frowned upon, as they bloat your code and make it harder to notice relevant comments. If you want to structure your code, use functions (eg isValidFilesize, isValidFileExtension, etc).
500000 could actually either use an inline comment, or be put into a properly named variable.
I would get rid of the uploadOk flag, as it isn't all that nice to read. You also perform a header redirect for many of the cases anyways, so normal users will not see the echo.
don't mix snake_case and camelCase without a good reason.
imageFileType doesn't hold the image file type, but the file extension.


Linked List: Smart Pointer Implementation

I would appreciate if you could pay special attention to usage of shared_ptr.

This fills me with dread. It implies that you want every node to have shared ownership. My question would be, "shared with what? another list?".

shared_ptr contains code for thread-safe reference counting. For this reason, use of a shared_ptr in a single-threaded program brings with it an unnecessary overhead.

There may be some use cases for sharing nodes - for example in a directed graph structure. In this case, almost any other container for holding node pointers would be superior to a linked list.

Before I can continue the review, I'd have to ask what the intended use-case of the list is.

After comments, here's an implementation that uses unique_ptr. Comments inline.

You will see that I have dropped the last pointer as it's not required. If you want 2-way linkage then use a ptr_type for the forward pointer and an observer_type for the back-link.

#include <iostream>
#include <string>
#include <memory>
#include <cassert>

const int SIZE=7;

// create the concept of an observer-only deleter
struct observer_only {
    template<class Any>
    void operator()(Any*) const noexcept {
        // nop
    }
};

// abstract the pointer type so we can change it if we don't like it
template<class Node> using ptr_type = std::unique_ptr<Node>;

// create the concept of an observer-only pointer
template<class Node> using observer_type = std::unique_ptr<Node, observer_only>;

// a means of converting a raw pointer to an observer
template<class Node> auto observe(Node* ptr) {
    return observer_type<Node>(ptr);
}

// a means of creating an observer to an owning pointer
template<class Node> auto observe(ptr_type<Node> const& ptr) {
    return observe(ptr.get());
}

struct Node {
    Node(int i)
            : val(i)
    {}

    // member function to add nodes provides logical encapsulation
    observer_type<Node> insert_after(ptr_type<Node>&& ptr) {
        assert(ptr.get());
        assert(ptr->next.get() == nullptr);
        ptr->next = std::move(this->next);
        this->next = std::move(ptr);
        return observe(this);
    }

    int val;
    ptr_type<Node> next = nullptr;
};

// node generator
ptr_type<Node> newNode(int v) { // Create and return new node
    ptr_type<Node> n(new Node(v));
    return n;
}

// print an observer
void print(observer_type <Node> o) { // Print the list
    for ( ; o.get() != nullptr ; o = observe(o->next))
    {
        std::cout << o->val << ' ';
    }
    std::cout << std::endl;
}

// print a node
void print(ptr_type<Node> const& r) { // Print the list
    print(observe(r));
}

// test
int main() {
    srand(time(NULL));
    auto root = newNode(rand());
    auto observer = observe(root);
    for (int i=1; i<SIZE; ++i) { // Build the list
        observer = observer->insert_after(newNode(rand()));
    }
    print(root);
    std::cout << std::endl;
    return 0;
}

Explanation of architectural approach

As requested in comments.

The the old days of assembler or C I'd have implemented a singly linked list (the second-simplest of all data structures) as merely a node containing a value and a pointer (address) to the next node. Of course we'd have to remember to destroy the node when removing it. We'd also have to remember whether a pointer "owned" (controlled the lifetime of) a node, or was merely an observer.

In modern c++, there are at least 2 enhancements available. First of course, we have RAII and smart pointers, so the destruction timing is always correct. Second, we can use types to indicate roles.

In the above code, I have two pointer types. One is an "owner" pointer and one is an "observer". These are both specialisations of unique_ptr in my code, but I could have written my own. However, using unique_ptr, I have some built in advantages:

a unique_ptr cannot be copied, so I cannot cause myself problems by accidentally sharing ownership.
even though the owning and non-owning pointers have different deleters (the observer's deleter is a no-op), they have the same interfaces. This makes generic programming easy.

In c++17, there is a template called std::observer_ptr, which is designed to perform the same role as my observer_type.

Now I can use the owner_type to handle the forward node linkages. This gives me clean RAII and firm ownership of nodes. It also mean that I can implement a remove function which returns the removed node pointer. I can then re-insert that node pointer into another list, or discard it (let it go out of scope). Either way, because it's controlled by an auto-deleting unique_ptr, the code will be correct. No leaks.

All operations on the list that do not affect lifetimes are done through an observer (there is a free function to create an observer from an owner). This provides both a visual cue to a maintainer, plus a compiler guarantee, that I won't accidentally mutate lifetimes when I am supposed to be observing or merely mutating the value held in the node.

fully linked list

OK, but how would I implement a linked list this way (i.e. with back-links as well as forward-links)?

We'd pick an 'owning' direction. Lets say forwards. Nodes would contain an owner_type pointing to and owning the next node, and an observer_type pointing to the previous node.

The list 'begin' pointer is an owner_type, the list's 'end' is an observer_type.

The Node would look something like this:

struct Node
{
    int value;  // my value type

    owner_type<Node>    next;   // pointer to the next node
    observer_type<Node> prev;   // observer of the previous node.
};

Inserting an removing nodes is the same as if they were raw pointers, it's just that we need to assign the pointers using std::move, because they're not copyable.

This is good, because it shows graphically in the code what we are trying to achieve. It forces us to spell out our intentions. If the code is later modified, it will be more difficult to introduce a logic error, because logically incorrect code won't compile.


Python: pass "mutable integer" in recursion

Optimization and restructuring

Node class constructor (__init__ method)

the arguments keyParam, childrenParam introduce unneeded verbosity and better named as just key and children
the whole if ... else ... condition for ensuring children list is simply replaced with self.children = children or [] expression

The initial dfsWithDepth function should be renamed to say find_max_depth to follow PEP8 style guide naming conventions.

The former parameters currentDepth, currentMaxContainer become unneeded. Within the crucial recursive function it's worth to capture "empty" node and node with no children beforehand. That's achieved by the following condition:

if node is None or not node.children:
    return 1

The remaining recursive search relies on the crucial find_max_depth and builtin max functions calls and accumulates the final max depth through traversing all subsequent sub-trees (child nodes).

The final optimized version:

class Node:
    """
    Node in a tree, with children stored in a list.
    """

    def __init__(self, key, children=None):
        self.key = key  # some id of the node; not strictly required, but often needed.
        self.children = children or []

def find_max_depth(node):
    if node is None or not node.children:
        return 1
    return 1 + max(map(find_max_depth, node.children))

Testing (I've added additional 5th level for demonstration):

# Construct tree
rootNode = Node('n1')
rootNode.children = [Node('n2'), Node('n3')]
tempNode = rootNode.children[0]  # n2
tempNode.children = [Node('n3'), Node('n4')]
tempNode = tempNode.children[1]  # n4
tempNode.children = [None, Node('n5')]
tempNode = tempNode.children[1]  # n5
tempNode.children = [Node('name7')]

print(find_max_depth(rootNode))   # 5


Idiomatic Scala Style

Class, object, and trait names follow camelCase style with the first letter capitalized. One example where you don't follow this rule is abstract class spMeta extends logging.

For a few reasons, it is considered bad practice to user underscores in names. Applying the convention from the bullet point above with this we'd make the following transformation to your code: class sp_01 extends spMeta => class Sp01 extends SpMeta.

The above rules also extend to types that you define. Consequently I'd change type inputT to type InputT, etc.

Methods which act as accessors should be declared without parenthesis (unless they have side effects). In particular this applies to your def getSolution(): SolutionT = ... which should just be plain old parenthesis-less def getSolution: SolutionT = ...

If you ever have any style questions check out this documentation.

Code Suggestions
A modified version of your getSolutionFiles method with explanations below.
    def getSolutionFiles(dir: File): Array[File] = {
        val dirContents = dir.listFiles
        val targetFiles = dirContents filter(x => x.getName.startsWith("sp_") && !x.isDirectory)
        val childDirs   = dirContents filter(_.isDirectory)
        targetFiles ++ childDirs flatMap(d => getSolutionFiles(d))
    }

I renamed the method paramter to dir from file.
All of the operations in this method are on the container type Array.  So I renamed some of the values to remove any mention of List.
Overall I think the renaming of these values make this method much easier to to immediately comprehend.
Just to show you 'another way' and not because I thought anything was wrong with your original choice, I replaced your use of a regular expression for finding the correct files with startsWith(...). Note there is also a method endsWith(...).
A bug could occur if the name of a file passed your filter predicate but is in fact a directory. I added a condition to to eliminate that possibility.

Cheers :)


Finding the nth Fibonacci number using recursive technique

Firstly, a minor point. fact? Have you refactored a recursive factorial method and forgotten to rename the accumulator?

That aside, I find this hilarious. Almost certainly the intended solution was along the lines of

def fibonacci(num)
  if num < 2
    return 1
  else
    return fibonacci(num - 2) + fibonacci(num - 1)
  end
end

which is the naïve recursive definition, and a classic teaching example of how naïve implementations can be insanely inefficient.

Your answer meets the rather vague spec (it is recursive), but is much better than the intended solution because it takes linear time (or maybe quadratic if push is linear, but I doubt it) rather than exponential.

If you want an additional challenge, here are two:

Your solution takes linear time and linear space. Can you modify it to take linear time and constant space?
Can you modify it further to take logarithmic time and constant space?

Hint for the second one:

   \$F(m+n) = F(m+1) F(n) + F(m) F(n-1)\$


Shuffle a sorted array so that left portions contains even indices and right portion contains odd indices numbers

Use std::swap rather than writing your own

    int p1=0;
    int p2=0;

    while(p2 < nums.size())
    {
        if(p2 % 2 == 0)
        {
            int tmp = nums.at(p1);
            nums[p1] = nums[p2];
            nums[p2] = tmp;

            p1++;
            p2++;
        }
        else
        {
            p2++;
        }
    }

    std::sort(nums.begin()+p1, nums.end(),std::greater<int>());

You'd be better off using std::swap:

        std::swap(nums[p1], nums[p2]);

But you don't need to swap

However, we can do it without any swaps nor the final sort.

First, create a new vector:

    std::vector output = new std::vector();

Now iterate over the sorted vector with a for loop.

    int n = nums.size();
    for ( int i = 0; i < n; i += 2 ) {
        output.push_back(nums[i]);
    }

And again with a second for loop.

    for ( int i = (n % 2 == 0) ? n - 1 : n - 2; i >= 1; i -= 2 ) {
        output.push_back(nums[i]);
    }

The initialization for the second for loop is tricky because you want it to start on the last odd number.  If there are an even number of elements in the vector, then the last odd index is the last index:  n - 1; otherwise, it is one less than that:  n - 2.

After that, you just need to copy the new vector over the old:

    nums = std::move(output);

This saves you an entire sort and a lot of swapping.

Constant memory

You can do it without the extra vector, but it requires more calculations to get the indexes right.

void shuffleEvenOdd(std::vector<int>& nums) {
    int n = nums.size();
    if ( n <= 1 ) {
        // we need more than one element; one and zero length vectors are already sorted
        return;
    }

    std::sort(nums.begin(), nums.end());

    int middle = (n + 1) / 2;

    // we start by putting the correct element in the last element
    int start_index = n - 1;
    int previous_index = start_index;

    // if there is more than one element in the vector, the element at [1] goes to [n-1]
    // otherwise, we should have exited already
    int index = 1;
    int temp = nums[start_index];

    // while we haven't looped back to the start
    while ( index != start_index ) {
        // move the next element
        nums[previous_index] = nums[index];
        previous_index = index;
        // if index is in the left half of the array,
        // we just move from double the index; e.g. 0 from 0, 1 from 2, 2 from 4, etc.
        // otherwise, we count index spaces back from n-1, double it, and add 1
        // e.g. n-1 from 1, n-2 from 3, n-3 from 5, etc.
        // (n-1 - index) * 2 + 1 == (n - index) * 2 - 1
        index = ( index < middle ) ? 2 * index : (n - index) * 2 - 1;
    }

    nums[previous_index] = temp;
}

This works and uses minimal memory, but it is less readable than making the extra vector.  That's why it makes such heavy use of comments.

I also don't have any proof that it will always move all the necessary elements.  It does in my testing, but that's not proof.


Plain enum (unlike enum class) convert implicitly to integers, so there's no need for the as_int() functions if you declare the enums in ascending order.  You probably want the suits in the order ♣♦♥♠ if you want to re-use your cards for Bridge as well as Poker.

I had to make up the constructor and get methods, since they are missing from the review:

Card(Value value, Color color)
    : value{value},
      color{color}
{}

Color getColor() const { return color; };

Value getValue() const { return value; };

I also created a simple test program that returns non-zero if we break the expectations:

int main()
{
    return
        + (Card{Two, Clubs} > Card{Ace, Spades})
        + (Card{Two, Clubs} > Card{Two, Spades})
        + (Card{Two, Spades} > Card{Ace, Spades});
}

Now, we can remove the as_int():

enum Value { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace};
enum Color { Clubs, Dimonds, Hearts, Spades};

inline bool operator==(const Card& lhs, const Card& rhs)
{
    return rhs.getValue() == lhs.getValue()
        && rhs.getColor() == lhs.getColor();
}

inline bool operator!=(const Card& lhs, const Card& rhs) { return !(lhs==rhs); }

inline bool operator< (const Card& lhs, const Card& rhs)
{
    if (lhs.getValue() < rhs.getValue()) {
        return true;
    }
    else if (rhs.getValue() == lhs.getValue()) {
        return lhs.getColor() < rhs.getColor() ? true : false;
    }
    else {
        return false;
    }
}

inline bool operator> (const Card& lhs, const Card& rhs) {return rhs < lhs;}
inline bool operator<=(const Card& lhs, const Card& rhs) {return !(lhs>rhs);}
inline bool operator>=(const Card& lhs, const Card& rhs) {return !(lhs<rhs);}

Note that this ternary conditional:

        return lhs.getColor() < rhs.getColor() ? true : false;

is exactly equivalent to this:

        return lhs.getColor() < rhs.getColor();

But we can simplify the < much further by delegating to std::tuple:

inline bool operator< (const Card& lhs, const Card& rhs) {
    return std::tuple(lhs.getValue(), lhs.getColor()) < std::tuple(rhs.getValue(), rhs.getColor());
}

In C++20, the entire set of 6 comparisons can be replaced with a single function:

public:
    auto operator<=>(const Card&) const = default;


Could this ExecuteScalar call be written better?

public bool CheckSomething(string paramA, int paramB)
{
    using (var conn = new SqlConnection(".."))
    using (var comm = new SqlCommand("", conn))
    {
        conn.Open();
        object noOfRecords = comm.ExecuteScalar();
        return noOfRecords != null;
    }
}

There is no need to close or dispose, the using handles that part.  This removes the need for a manual try catch or closing logic, leaving a much compressed chunk of code that is functionally equivalent and just as safe.

As for the select statement itself, either use parameterized SQL or a stored procedure as opposed to string concatenation.  Parameterized SQL:

string sql = "SELECT ColumnA FROM OurTable WHERE ColumnB = @param1 AND ColumnC = @param2";

using (var comm = new SqlCommand(sql, conn))
{
    comm.Parameters.AddWithValue("@param1", param1);
    comm.Parameters.AddWithValue("@param2", param2);

    conn.Open();
    // etc...
}


asMap-implementation for Java (based on Arrays.asList)

In my opinion MapBuilder should contain a Map, not extend one. Another possible design would be to use a single call with varargs:

public class MapUtil {
    public static <K,V> Map<K,V> asMap(Map.Entry<K,V>... entries) {
        Map<K,V> map = new HashMap<K,V>();
        for(Map.Entry<K,V> entry : entries) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    public static <K,V> Map.Entry<K,V> e(final K k, final V v) {
        return new Map.Entry<K, V>() {
            public K getKey() {
                return k;
            }
            public V getValue() {
                return v;
            }
            public V setValue(V value) {
                throw new UnsupportedOperationException("Not supported");
            }
        };
    }
}

import static very.useful.MapUtil.*;
...
Map<String, Integer> map = asMap(e("x",1),e("y",2),e("z",3));


EDIT: Please see update at end because there is an improved solution that is inspired by Mike Chamberlain's answer...

There are two solutions which come to mind for your problem, but first, let's look through your code:

you have the variables pointer1 and pointer2. These are very descriptive names, which is great, but unfortunately they are not pointers. They are the values at the i and k positions in the array. In other words, i and k are the actual pointers. I would call pointer1 and pointer2 something like val1 and val2. But, in fact, I would drop the pointers entirely, and just use an index in to the data (why copy the data when you don't need to....? )
In most languages the variable name i is 'reserved' for indexed looping through data, just like you have for (int i = 0; i < len; i++) {...}. It is standard to use j and k as the variable names for any inner/nested loops you need. i is the top level, j is the first nested level, k is the subsequent level, and, if you need more than that, you should be calling a function/method (Never use l as a variable name, it is too easy to confuse with 1). You are breaking this convention by using j as an array, and going immediately to k inside your loop. My suggestion is to rename j to be data, and to rename k to be j.
as a general rule, when you have a loop constrained by an index, like you have for (int i = 0; i < len; i++) { ..., you should never modify the index inside the loop. I cannot think of a reason why it should ever be necessary, and, certainly, it should never be conditionally modified (inside an if-statement inside another loop). This will lead to bugs. In fact, the simple fact that you have that inner i++ tells me you do not understand your own code's behaviour.
Your method should return the interface type List<String> instead of the concrete class ArrayList<String> since there is no reason for outsiders to know the physical implementation.
storage is not a great name for a variable.... everything could be called storage since all variables store things... I would choose something like: results.
Your inner if condition makes sure that the sums are a match, but also checks pointer1 != pointer2. This second check is a problem, because it should not be testing the values, but the indexes.... For example what if the data is [4,4] and the target sum is 8?
To get your result pair as a String you do: String pair = Integer.toString(pointer1) + " and " + Integer.toString(pointer2).... this is serious overkill, try this instead: String pair = pointer1 + " and " + pointer2. In Java the + String operator will implicitly convert the integers to a String... no need to do it yourself.

So, you have some style problems, and some concerns about your inner workings.

Now, let's talk about your algorithm..... It loops through each value. For each value, it then compares it against every other value (except itself). So, you loop n times, and, for each n you do m checks. Your complexity is O(n x m), but, in reality, n and m are the same, so your complexity is O(n2)

Now, about that i++ inside the k loop.... the reason you need it is because your k loop is starting from the wrong place. your algorithm is wrong. Let me explain.

If you have the data [ 0, 1, 2, 3, 4, 5 ] , you are using your i index to loop through all the data. Your first data will be 0. You sum this with 5 (Note, you have summed 0 + 5 now), and check the result, then with 4, and so on. When you are done, you move i to the value 1, and you keep moving i until you get to the value 5 for i. You then compare **this value 5 to all the other values, including 0. This is **the second time you sum the items 0 + 5  (but it is now 5 + 0) **.

You need to change the algorithm to only scan those values that have not yet been scanned. The easiest way to do this is to modify your inner/nested loop. Consider your code:

   for (int i = 0; i < len; i++) {
       ...
       for (int k = len - 1; k >= 0; k--) {
           ...

Now, we change the inner loop as follows:

for (int i = 0; i < len; i++) {
    ....
    for (int j = i + 1; j < len; j++) {

(note, I have renamed k to be j). We start our j index at i + 1, because we don't need to sum values before i since that sum was done already when i was smaller.....

Now, our loops only calculate the sum value once for each pair of values.

Unfortunately, our complexity is still O(n2) because even though our inner loop is only testing half (on average) the values, we have not actually changed the way the algorithm scales (if you double the input data, you with quadruple the execution time).

Still, even with this algorithm change, and some variable renaming, and some bug fixing, your code will look like:

public static List<String> pairSum(int[] data, int sum) {
    int len = data.length;
    int val1;
    int val2;
    List<String> results = new ArrayList<String>();

    for (int i = 0; i < len; i++) {
        val1 = data[i];
        for (int j = i + 1; j < len; j++) {
            val2 = data[j];
            if (val1 + val2 == sum) {
                String pair = val1 + " and " + val2;
                results.add(pair);
            }
        }
    }
    return results;
}

This is OK, but my preference would be to strip all the val1 variables entirely, and you can simplify some other things too. Consider the following more 'compact' code:

public static List<String> pairSum(int[] data, int sum) {
    List<String> results = new ArrayList<String>();

    for (int i = 0; i < data.length; i++) {
        for (int j = i + 1; j < data.length; j++) {
            if (data[i] + data[j] == sum) {
                results.add(data[i] + " and " + data[j]);
            }
        }
    }

    return results;
}

That is what I would recommend for a simple, easy-to-read option that is O(n2). For small data sets (say less than 50 or so), this solution will be great.

But, if you have more data, a better solution would be more complicated, but faster.

In your example code, you have an input test array that is all positive, sorted, and the values are unique. Let's assume that all the data will be this way (we can modify this assumption later).

Consider the algorithm that does:

take all values that are less than half the target `sum`.
find a value that is the difference

It would look like:

public static List<String> pairSumFast(int[] data, int sum) {
    List<String> results = new ArrayList<String>();

    int limit = sum / 2;
    for (int i = 0; i < data.length && data[i] <= limit; i++) {
        int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);
        if (match >= 0) {
            results.add(data[i] + " and " + data[match]);
        }
    }

    return results;
}

This has the complexity of O( nlog(n) ) for the loop, and the binary-search respectively.

If your data set is large, and the values are unique, but the data is unsorted, then I would recommend the change:

public static List<String> pairSumFast(int[] indata, int sum) {
    List<String> results = new ArrayList<String>();

    int[] data = Arrays.copyOf(indata, indata.length);
    Arrays.sort(data);

    int limit = sum / 2;
    for (int i = 0; i < data.length && data[i] <= limit; i++) {
        int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);
        if (match >= 0) {
            results.add(data[i] + " and " + data[match]);
        }
    }

    return results;
}

This is O(n log(n) ) for the complexity still... (it scales this way, even through it does more computation....)

Finally, if the data is not unique, then you will get duplicate output values. To accommodate that, I would add an inner loop to the match....:

public static List<String> pairSumFast(int[] data, int sum) {
    List<String> results = new ArrayList<String>();

    int limit = sum / 2;
    for (int i = 0; i < data.length && data[i] <= limit; i++) {
        int match = Arrays.binarySearch(data, i + 1, data.length, sum - data[i]);
        if (match >= 0) {
            String pair = data[i] + " and " + data[match];
            results.add(pair);
            // binary search will return the index of one match, look around to find others.
            int more = match - 1;
            while (more >=0 && data[more] == data[match]) {
                results.add(pair);
                more--;
            }
            more = match + 1;
            while (more < data.length && data[more] == data[match]) {
                results.add(pair);
                more++;
            }
        }
    }

    return results;
}

EDIT: A better solution...

Mike Chamberlain suggests using a Map to preserve the values you have seen in order to match the pairs in a single O(n) iteration of the list.

This single-iteration made me realize that there is a much simpler solution to this problem... iterate from both sides of the data.... consider the following:

public static List<String> pairSumFastest(int[] data, int sum) {
    ArrayList<String> results = new ArrayList<String>();

    int low = 0;
    int high = data.length - 1;
    while (low < high) {
        while (low < high && data[low] + data[high] < sum) {
            low++;
        }
        while (low < high && data[low] + data[high] > sum) {
            high--;
        }
        if (low < high) {
            results.add( data[low] + " and " + data[high]);
            low++;
            high--;
        }
    }

    return results;
}

This has true O(n) complexity, and has no memory overhead either.


Sorry I was busier earlier. Here is a more complete review. Just a few things off the top of my head.

Try and be consistent with your class naming. Instead of  .js_container-reloader and js_reload-container use a common prefix, i.e. .js_reloader-trigger (or even just .js_reloader) and .js_reloader-container
You can use a single call to the on function like:

$(document).on("submit", ".js_container-reloader", ...
var element = $(element), is syntactically incorrect since element is already defined as a parameter. One options is just use element = $(element);  another pattern I often see is using a $ prefix on variables to indicate jQuery objects, i.e. var $element = $(element),
requestUrl = element.attr('action'); would be better asrequestUrl = element.prop('action'); the latter will retrieve the default method for the form if no attribute is set.
I personally think the use of wrap andunwrap` is an odd way to handle adding an element. I would remove the wrap and container code and just have something like the following on success:

success: function(result){
   ....
   element.after(result);
   element.remove();

I would add a .js_reloader-loading class to the element before starting the ajax query so that you can style it differently (fade it, add a spinner, etc).
Lastly you probably want to implement some kind of logic to prevent multiple attempts at loading the form.


Listing every date between two dates in input fields

I wouldn't bother with calculating the difference - especially as it's not actually used for anything.

Instead I'd just do this:

var start = new Date(document.querySelector('[name="startdate"]').value),
    end = new Date(document.querySelector('[name="enddate"]').value),
    year = start.getFullYear(),
    month = start.getMonth()
    day = start.getDate(),
    dates = [start];

while(dates[dates.length-1] < end) {
  dates.push(new Date(year, month, ++day));
}

That'll give you a dates array beginning with the start date and continuing up to and including the end date.

From there, it's pretty much the same as now: Create and append input elements. I'm not sure I like the <br>, though. I imagine it's mostly for layout purposes, in which case I'm sure you could handle it better in CSS.

As for the date formatting, I don't know of a way to change that. Browser support for the date-type input is very poor so just be glad if you can use it at all. But since it's not widely supported, you'll probably want to use a cross-browser widget anyway, and in that case you'll likely have options for formatting the date.


vectorize 2D gradient with spatially varying bins

Your f and ssh are already vectorized, you can do the same quite trivially with u and v also. There is nothing tricky going on in your loop. The process is simply to remove the for, leaving the assignment i=2:size(x,1)-1. And replace all matrix multiplication and division by element-wise multiplication and division (.* and ./). This leaves:

%Calculate geostrophic current
u = zeros(size(ssh));
v = zeros(size(ssh));
i = 2:size(x,1)-1;
j = 2:size(y,2)-1;
dx(i,j) = (x(i+1,j)-x(i-1,j)) .* (R*cosd(y(i,j))*pi/180);
dy(i,j) = (y(i,j+1)-y(i,j-1)) .* (R*pi/180);
u(i,j) = -g(i,j) ./ f(i,j) .* (ssh(i,j+1)-ssh(i,j-1)) ./ dy(i,j);
v(i,j) =  g(i,j) ./ f(i,j) .* (ssh(i+1,j)-ssh(i-1,j)) ./ dx(i,j);

You can then do a slight simplification, dx and dy do not need indexing, since you're using the same part that you assign:

dx = (x(i+1,j)-x(i-1,j)) .* (R*cosd(y(i,j))*pi/180);
dy = (y(i,j+1)-y(i,j-1)) .* (R*pi/180);
u(i,j) = -g(i,j) ./ f(i,j) .* (ssh(i,j+1)-ssh(i,j-1)) ./ dy;
v(i,j) =  g(i,j) ./ f(i,j) .* (ssh(i+1,j)-ssh(i-1,j)) ./ dx;


You have a portability bug, because names ending in _t are reserved for future Standard Library types.  Rename node_t, perhaps to Node.

This kind of recursion is problematic, because it can't be transformed into iterative form by the compiler.  It needs to keep each call's e value until all the inner recursive calls have completed, before it can do the comparison.

If you can, strive to make your function tail-recursive, which means that it's in the form:

ResultType function(args) {
    ...
    return function(other_args);
}

To make a non-tail recursive function into a tail-recursive one, you generally need to pass the current state into the recursive call.

Here, I'd actually split the function into two: a recursive function to find the node_t with largest value (or NULL if the list is empty), and a wrapper function to call it with the right parameters, extract the result, and handle errors:

/* untested */

static const Node *find_node_max(Node *list, Node *best_so_far)
{
    if (!list) {
       return best_so_far;
    }
    if (!best_so_far || list->val > best_so_far->val) {
        best_so_far = list;
    }
    return find_node_max(list->next, best_so_far);
}

int trovaMassimo(const Node *head) {
    const Node *n = find_node_max(head, NULL);
    if (!n) {
        /* empty list - N.B. message to stderr, not stdout */
        fputs("Lista vuota\n", stderr);
        exit(1);   /* not good in library code */
    }
    return n->val;
}


Import data from XML files into data.frame

With a few XML files to read you could have done something like this to address your concerns, where the files are only read at once, but all loaded into memory at the same time:

subdirs <- strsplit(dirname(filenames),
                    split = .Platform$file.sep)
subdirs <- lapply(subdirs, rev)
job   <- sapply(subdirs, `[[`, 3)
build <- sapply(subdirs, `[[`, 1)
xmls <- lapply(filenames, xmlParse)
duration <- sapply(xmls, xpathSApply, "//duration", xmlValue)
result   <- sapply(xmls, xpathSApply, "//result", xmlValue)
build.data <- data.frame(job, build, result, duration)

With thousands of files though, it makes more sense to process the files one by one and only keep the useful information before moving from one file to the next. It also makes sense to write a function to process each file. It could be:

build.info <- function(file, xml_fields = c("duration", "result")) {
   res <- list()
   # process filepath
   subdirs <- rev(unlist(strsplit(dirname(file),
                                  split = .Platform$file.sep)))
   res$job   <- subdirs[[3]]
   res$build <- subdirs[[1]]
   # process xml data
   doc <- xmlTreeParse(file)
   build <- doc$doc$children$build
   res[xml_fields] <- lapply(build[xml_fields], xmlValue)
   # return as a data.frame
   as.data.frame(res)
}

See how the function returns a one row data.frame. Then you can call the function on all files via lapply and bind all the outputs together:

build.data <- do.call(rbind, lapply(filenames, build.info))

With a few changes, you can write a more general function that will take one or more files and do the binding itself (like file.info does)

build.info <- function(file, xml_fields = c("duration", "result")) {
   stopifnot(length(file) > 0L)
   if (length(file) == 1L) {
      res <- list()
      # process filepath
      subdirs <- rev(unlist(strsplit(dirname(file),
                                     split = .Platform$file.sep)))
      res$job   <- subdirs[[1]]
      res$build <- subdirs[[3]]
      # process xml data
      doc <- xmlTreeParse(file)
      build <- doc$doc$children$build
      res[xml_fields] <- lapply(build[xml_fields], xmlValue)
      # return data.frame
      as.data.frame(res)
   } else {
      do.call(rbind, lapply(file, build.info))
   }
}

build.data <- build.info(filenames)


Convert seconds to hours/minutes/seconds and pretty print

There is a built-in timeit module which is quite convenient for measuring execution times, but, if we were to improve this particular solution, I would switch to using divmod as suggested by Brandon here, utilize short if/else version for the status definition and join the time value parts with a comma filtering non-zero values only.

Something along these lines:

seconds = int(seconds)
status = 'has been running for' if not finished else 'finished in'

minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

periods = [('hours', hours), ('minutes', minutes), ('seconds', seconds)]
time_string = ', '.join('{} {}'.format(value, name)
                        for name, value in periods
                        if value)

print('The script {} {}'.format(status, time_string))


It's impossible to say what the problem is without knowing how the data is structured, how many rows are in each table, what the indexes are, and other information. Even then, the problem may not even be with this query but with some other query that causes problems for the database as a whole. Basically, your question is far too narrow.

That said, you could try a few things:

Try running this with Explain Plan turned on. That should tell you what part of the query is taking the longest.
Run SET STATISTICS IO ON; and then your query. That will give you an idea if the I/O usage is high.
If the above don't suggest improvement, check the overall DB for problems. Glenn Berry's SQL diagnostics queries are a good place to start.
If you still can't figure it out, hire someone like Glenn to help you. Or start reading a lot of books on SQL Server optimization.

(disclaimer: Glenn's a friend and former colleague of mine, but he is really good at this stuff. I don't get kickbacks. Maybe a beer, but probably not.)


The code looks good! A few comments:

I'd use the requests library instead of urrllib2.
Make sure to follow PEP8 (second line has a trailing whitespace and a space after the dictionary key).
Use more semantic variable names than div, text, or final.
If your code gets bigger, think about separating the HTTP request from the parsing code.


Object oriented architecture with an image processing code

Reducing repetition

self.sizes

self.sizes being repeated 4 times is not necessary:

    self.sizes                    = OrderedDict()
    self.sizes['image_main']      = (800, 800)
    self.sizes['thumbsize_big']   = (200, 200)
    self.sizes['thumbsize_small'] = (100, 100)

You may give an initial argument to OrderedDict to avoid it:

    self.sizes = OrderedDict( (
        ('image_main', (800, 800)),
        ('thumbsize_big', (200, 200)),
        ('thumbsize_small', (100, 100))
    ))

myimage

def resize_image(self, image, size):
    myimage = Image.open(image)
    myimage = myimage.resize(size, Image.ANTIALIAS)
    return myimage

In fact the myimage variable may be avoided completely, just chaining the method calls is much simpler:

def resize_image(self, image, size):
    return Image.open(image).resize(size, Image.ANTIALIAS)

Whole block repetition

        if self.image_format == 'png':
            # Save images on disk
            self.save_image(self.resize_image(self.image, value),save_dir, self.png_compress, self.jpg_compress)
            # Save images in fields
            if self.has_iterated == 0: self.instance.image_main = self.saving_path + self.slug + '_' + key + '.png'
            if self.has_iterated == 1: self.instance.image_thumbsize_big = self.saving_path + self.slug + '_' + key + '.png'
            if self.has_iterated == 2: self.instance.image_thumbsize_small = self.saving_path + self.slug + '_' + key + '.png'
            self.has_iterated += 1
        if self.image_format == 'jpg' or 'jpeg':
            self.save_image(self.resize_image(self.image, value),save_dir, self.png_compress, self.jpg_compress)
            if self.has_iterated == 0: self.instance.image_main = self.saving_path + self.slug + '_' + key + '.jpg'
            if self.has_iterated == 1: self.instance.image_thumbsize_big = self.saving_path + self.slug + '_' + key + '.jpg'
            if self.has_iterated == 2: self.instance.image_thumbsize_small = self.saving_path + self.slug + '_' + key + '.jpg'
            self.has_iterated += 1

The blocks are very similar just the file-extension changes.

extension = 'png' if self.image_format == 'png' else 'jpg'

And then you can delete the conditional branches that follow and leave only one path.

Bug on the use of or

    if self.image_format == 'jpg' or 'jpeg':

Does not work as you intended. or returns the first truthy value, so you wrote the same as:

    if self.image_format == 'jpg':


Find the corresponding closing parenthesis

You might want to confirm that the character at the given position is indeed a (.

There is no reason to care about what appears before the given position.  You can start examining the string starting at pos + 1.  Once you have found the the position of the matching closing parenthesis, you can just return it right away; there is no need to ever set index.

function findClosingBracketMatchIndex(str, pos) {
  if (str[pos] != '(') {
    throw new Error("No '(' at index " + pos);
  }
  let depth = 1;
  for (let i = pos + 1; i < str.length; i++) {
    switch (str[i]) {
    case '(':
      depth++;
      break;
    case ')':
      if (--depth == 0) {
        return i;
      }
      break;
    }
  }
  return -1;    // No matching closing parenthesis
}

console.log(findClosingBracketMatchIndex('a (bc)', 2)); // 5
console.log(findClosingBracketMatchIndex('a (b ())', 2)); // 7
console.log(findClosingBracketMatchIndex('a (b ())', 5)); // 6
console.log(findClosingBracketMatchIndex('(a (b ()))', 0)); //9


Too simple? Hardly. That is pretty much a textbook implementation of animation using a callback-based event model. In a production-grade version there would be a few extra null checks and similar to check for programming mistakes, but the basic implemation could be very similar.
I'm assuming that elsewhere there is a main loop that periodically calls update on each relevant sprite. I'm also assuming that either update takes care of drawing the spite, or that code not shown is responsible for that.
One Weakness and Possible Solution
One thing though that may be problematic for complicated animations is that your design gives the function no scratch space in which to store any state information (complicated animations may want to know if this is the first or second time the sprite was at coordinate (457,758) for example).
An easy solution is to add an extra void * to the sprite. This would be an extra pointer the animation function can set to whatever it wants (usually an animation specific structure). Have BeginAnimation set this new pointer to NULL. Document that the pointer must either be left NULL, or allocated with new. EndAnimation would delete the pointer on the animation's behalf if it was not still NULL, since the animation is not given the opertunity to cleanup if EndAnimation is called directly.
There are cleaner solutions than the above, but the that one is easy to explain, and should work.