It seems to me that you are making multiple requests to 'https://localhost/answers'.$k['id'] inside a loop and that you have one route for each answers, such as:

https://localhost/answers100
https://localhost/answers101
https://localhost/answers102

My suggestion is to abandon that approach and combine them into one route that can handle multiple ids.
For instance:

https://localhost/answers?id[]=100&id[]=101&id[]=102

Then grab the id like this:

$ids = $_GET['id'];

which is an array.
Process each id one by one and combine the result and send as JSON.
For instance:

{
    "100": {
        "summary": "",
        "solution": ""
    },
    "101": {
        "summary": "",
        "solution": ""
    },
    "102": {
        "summary": "",
        "solution": ""
    }
}

So, instead of making 400 requests, you only need to make 1 request.
Much faster.


I have my doubts that any method is significantly faster than another given the sink-hole of time that printf() is, but here is another approach

#define FB "FizzBuzz\n"
#define F "Fizz\n"
#define B "Buzz\n"
#define N "%d\n"

int main(void) {
  static const char *fmt[15] = {
      FB, N, N, F, N, B, F, N, N, F, B, N, F, N, N };
  for (int a = 1; a <= 100; a++) {
    printf(fmt[a % 15], a);
  }
  return 0;
}


First of all, your solution for this task looks pretty elegant, from my point of view. I would just provide minor comments to optimize this code.

Your input data is a boolean matrix, so instead of keeping every value as a byte you can use just one bit. For that purpose you can use bitarray module.

Another point, that you are loading whole matrix to the memory. It can be too expensive in certain circumstances. I can suggest one stream-based solution which will calculate a number of islands in dynamic manner. This method was discussed here.


Python script to calculate the Collatz conjecture

The output does not start with the number I enter, which I find a bit surprising.  Rather, the output starts with the following number in the Collatz sequence.

The Collatz sequence deals with integers, so why convert the input to a float rather than an int?  To catch invalid input, you should catch just ValueError rather than every kind of error.  Otherwise, you wouldn't even be able to exit the program using CtrlC.  Also, since you are using Python 3, you should use the // operator for integer division instead of the / operator, which does floating-point division.

The initiate flag variable is awkward.  Also, the code for calculation, number input, and restarting are all mingled together.  I recommend splitting the Collatz calculation code into a generator function:

def collatz_seq(n):
    yield n
    while n != 1:
        n = (3 * n + 1) if (n % 2) else (n // 2)
        yield n

while True:
    try:
        start_num = int(input('Enter a number: '))
        for n in collatz_seq(start_num):
            print(n, end='\n====\n')
    except ValueError:
        print('Error! Please try again.')
    if 'y' == input('Quit (y/n)? '):
        break


That's a lot of code for something that could be done with a single function. The number of operations required to determine the output is relatively small, so writing a whole TimeUnit class hierarchy for it is overkill. Keeping your code short and simple makes it easier to understand, which helps preventing (or spotting) bugs.

If you do want to write a utility class, then a single, configurable TimeUnit class is sufficient. The only difference between the time units are lamp color and number of lamps per row, which can be passed in via the TimeUnit constructor.

Instead of passing strings around, why not use a built-in date/time type? That, or a set of 3 integers. That will clearly communicate how the function is to be used. A string is more ambiguous: should I pass in "15:30:05", "3:30:05PM", or some other format?

The 'S' in SOLID stands for Single responsibility. Let another function do the parsing. Your function should focus on the time-to-BerlinClock-display conversion. That's also related to 'I': Interface segregation. It's better to have several classes (or functions, in this case) that each do one thing well, than one big class/function that does everything, but turns out to be very inflexible when you only need part of that 'everything'.

Remember, KISS: Keep It Short and Simple. Also, DRY: Don't Repeat Yourself.


Basic templating engine in F# using F# syntax

There are a few suggestions which immediately occur to me:  some are minor changes which could improve the clarity of the code and there is one major change which would shorten the code quite a bit.

The minor changes:

For List.fold you can just pass a function which matches the expected type and not write the full lambda.  With an operator like + it's not obvious, but you can clean up your code a bit using:

attrs
|> List.map (fun (name,value) -> sprintf "%s=\"%s\"" name value)
|> List.fold (+) ""

In the function childContent, I would move the call to expandTree into a List.map, to reduce the amount of nesting and to allow us to clean up the List.fold:

children
|> List.map (fun child -> expandTree child [])
|> List.fold (@) []

With Text(string) you should use a name other than string since that's the name of an existing type and that could cause confusion for someone reading your code.

The major change is that you can combine the tokenWriter and the expandTree into a single function.  At the heart, what you are doing is an in order traversal of a tree to convert your HTML structure into a string:  expandTree does an in order traversal to flatten the tree into a list and then tokenWriter converts those tokens into strings.  You're not gaining much by flattening the tree and then generating the output string; so, you could just use the tree traversal to generate the output string.

Making this change also allows you to remove the Token type, further reducing the overall complexity of your code.

Here's the updated code:

    let Template el =
        let rec elementToString el output =
            let attributesToString attrs =
                attrs
                |> List.map (fun (name,value) -> sprintf "%s=\"%s\"" name value)
                |> List.fold (+) ""

            match el with
            | Tag(tagName, attrs, children) ->
                let attributes = attributesToString attrs
                let tagStr = sprintf "<%s%s>" tagName attributes
                let childContent =
                    children
                    |> List.map (fun item -> elementToString item "" )
                    |> List.fold (+) tagStr
                let closeTagStr = sprintf "</%s>" tagName
                sprintf "%s%s%s" output childContent closeTagStr
            | TagSelfClosing(tagName, attrs) ->
                let attributes = attributesToString attrs
                sprintf "%s<%s%s />" output tagName attributes
            | Collection(elements) ->
                elements
                |> List.map (fun e -> elementToString e output)
                |> List.fold (+) ""
            | Text(text) ->
                sprintf "%s%s" output text

        let expandedTree = elementToString el ""
        let content =
            expandedTree

        printf "%s" content


Given the restrictions you outline that seems sensible, I also couldn't
find a CDR for it (in contrast to an extensible equality operator for
example), however I'd probably try to find a better name than UCOPY.
Also, since you often might have to choose between shallow and deep
copies, perhaps introduce a parameter for that.

The method for STRUCTURE-OBJECT isn't guaranteed to work, so it might
be more advisable to leave out that method and require the user to
implement them by hand.

Rest looks fine to me.


Using a generator function gives you some flexibility.  You don't have to create a list.

def generate_documents( document_nodes ):

    for document in document_nodes:
        # create a MockDocument for each item returned by the API
        document_object = MockDocument()
        for field in document:
            # store the corresponding fields as object attributes
            if field.tag == "something":
                document.something = field.text
        yield  document_object

You can do this of the list object is somehow important.

document_objects = list( generate_documents( document_nodes ) )

Or, more usefully, this

for d in generate_documents( document_nodes ):
    ... process the document ...

Which never actually creates a list object.


I wanted to know if this form is safe for my users and if it will work on most devices.

Your HTML form will definitely work on all devices. But as for being 'safe for users', that would probably depend on your backend code you are using to submit your form eg PHP. You would use PHP (or some other backend language eg Python) to handle the submitted data. The browser would decide if the form is safe enough based on how safely and securely you encrypt and submit the data.

  Am I following all the good web development practices?

You have followed most of the good programming practices for web development. Though there aren't many things I can improve on for such a simple webpage, there are some minor problems:

It is more conventional to use
 not
 because it is a self-closing tag. Adding the / in the tag tells the browser not to waste time looking for the (non-existent) closing
 tag.
And it is not a good idea to place your input labels as 'naked' untagged text. Instead, use label tags:

Firstname:
<input type="text" name="firstname" />

Web developers usually write the doctype in lowercase, like this:

<!doctype html>

not this:

<!DOCTYPE HTML>

But there is no major difference.

  Is my code pure HTML5?

This is all pure HTML5, I see no other programming language (eg JS) or markup language (eg CSS) in your sample code.


Throwing the Exception But Using the Finally Block

You could use the closeQuietly methods of IOUtils (Apache Commons IO) (or similar ones) for input streams. It ignores exceptions and accepts null values.

Its implementation is just a few lines of code, so you can copy it directly to your Android application without the jar file:

public static void closeQuietly(Closeable closeable) {
    try {
        if (closeable != null) {
            closeable.close();
        }
    } catch (IOException ioe) {
        // ignore
    }
}

You could also create a close method for ouput streams:

public static void closeQuietly(OutputStream stream) throws IOException {
    if (stream != null) {
        stream.close();
    }
}

Both methods accept null values which means that you can call them with null, closeQuietly and close will handle that and you don't have to check null values in the finally block:

} finally {
    if (input != null) {
        closeQuietly(input);
    }
    close(output);
}

Instead of this the following is completely enough:

} finally {
    closeQuietly(input);
    close(output);
}

It's much simpler.

closeQuietly ignores exceptions which means that it catches them but don't do anything with them. Notice the empty catch block:

    } catch (IOException ioe) {
        // ignore
    }

It ensures that if closeable.close() throws an IOException the close(output) will run and it will close the output stream too.

I'm a little bit paranoid about this so I always put a logging statement to the catch block:

    } catch (IOException ioe) {
        logger.warn("Could not close the stream", ioe);
    }

To be honest, I've never seen this exception, so I think it's safe to left this block empty.

Ignoring IOExceptions of output streams could be dangerous: you might miss a bug and get a corrupted output file.


Finding two movies whose lengths add up to a given length

Returning from the body of the loop isn't necessary a problem in itself. Nonetheless, your code does have a fairly significant problem.

When you search for a second movie of a particular length, you use the subscript operator. The problem arises from the fact that when this doesn't find an existing entry for a particular length, it inserts a new entry for that length. The value associated with the key will be value-initialized, will will give false in this case.

That means the code will work, but because you're potentially inserting a lot of unnecessary items into your map, you could waste a lot of time. As long as you're only dealing with half a dozen movies, it's probably irrelevant, but if you deal with a lot it could get ugly.

In fact, there doesn't seem to be any reason to use a map here at all. It looks like an unordered_set will work perfectly fine for the task at hand.

There is something else here that could probably be viewed as a bug: if you have a movie whose length is exactly half the total length of the flight, it appears that your code will suggest watching the same movie twice in succession, which probably isn't something anybody would actually want.


Linq will make it look better:

protected bool IsGroupB_Valid()
{
    return Page.GetValidators("B").All(v => v.IsValid);
}

But probably you should look for something really different


Date and time incrementation, using a fictional calendar / clock

Feedback

The code seems to work okay, though it appears that the counting is off because of the comparison operators used (i.e. >) and the initial value of the indexes (e.g. secondIndex = 0). Use Greater than Or equal to (i.e. >=) in order to accurately count with the correct number of seconds per minute, minutes per hour, etc.

Your code doesn't display the value of currentSecond but I added it (see code snippet below) and noticed it was going between values of 1, 2 and 3.

Suggestions

Pre-increment instead of post-increment and use immediately after

Instead of incrementing each value using the post-increment operator and then using it, use the pre-increment operator.

So lines like this:

secondIndex++;
currentSecond = secondIndex;

Can be converted to a single line like this:

currentSecond = ++secondIndex;

Parameter passing

function incrementOneSecond() references all variables defined with scope outside of it (e.g. currentSecond, currentMinute, etc.), so why pass those to updateTime()? For consistency, either pass them all to incrementOneSecond() when calling it, or just reference them the same way within updateTime().

var dateDisplay = document.getElementById('dateDisplay');
var btnNext = document.getElementById('next');

var weekdays = [
  'Morndas',
  'Tirdas',
  'Middas',
  'Turdas',
  'Fredas',
  'Loredas',
  'Sundas'
];
var months = [
  'Morning Star',
  'Sun\'s Dawn',
  'First Seed',
  'Rain\'s Hand',
  'Second Seed',
  'Midyear',
  'Sun\'s Height',
  'Last Seed',
  'Hearthfire',
  'Frostfall',
  'Sun\'s Dusk',
  'Evening Star'
];
var monthMaxDays = 30;
var yearStart = 1888;
var secondsPerMinute = 2;
var minutesPerHour = 30;
var hoursPerDay = 24;

var currentSecond = currentSecond || 0;
var currentMinute = currentMinute || twoDigitFormat(0);
var currentHour = currentHour || twoDigitFormat(0);
var currentDay = currentDay || weekdays[0];
var currentDateNumber = currentDateNumber || 1;
var currentMonth = currentMonth || months[0];
var currentYear = currentYear || yearStart;

var secondIndex = currentSecond;
var minuteIndex = currentMinute;
var hourIndex = currentHour;
var dayIndex = parseInt(weekdays.indexOf(currentDay), 10);
var dateNumberIndex = currentDateNumber;
var monthIndex = parseInt(months.indexOf(currentMonth), 10);
var yearIndex = currentYear;

var secondLoop = setInterval(incrementOneSecond, 500);

function twoDigitFormat(input) {
  return ("0" + input).slice(-2)
}

function incrementOneSecond() {
  currentSecond = ++secondIndex;
  if (secondIndex >= secondsPerMinute) {
    secondIndex = 0;
    currentMinute = twoDigitFormat(++minuteIndex);
    if (minuteIndex >= minutesPerHour) {
      minuteIndex = 0;
      currentHour = twoDigitFormat(++hourIndex);
      if (hourIndex >= hoursPerDay) {
        hourIndex = 0;
        currentDay = weekdays[++dayIndex];
        if (dayIndex >= weekdays.length) {
          dayIndex = 0;
          currentDateNumber = ++dateNumberIndex;
          if (dateNumberIndex > monthMaxDays) {
            dateNumberIndex = 1;
            currentMonth = months[++monthIndex];
            if (monthIndex >= months.length) {
              monthIndex = 0;
              currentYear = ++yearIndex;
            }
          }
        }
      }
    }
  }

  updateTime();
}

function updateTime() {
  timeDisplay.innerHTML = currentHour + ':' + currentMinute + ':' + currentSecond;
  dateDisplay.innerHTML = currentDay + '
' + currentMonth + ' ' + currentDateNumber + ', ' + currentYear;
}
html,
body {
  font-family: sans-serif;
  font-size: 1rem;
  line-height: 1.2rem;
}


An alternative algorithm for sorting a stack using only one additional stack

I really don't recommend trying to write anything that is more complicated than necessary during an interview, especially if it's on a whiteboard. Interviews are stressful enough for you; introducing more opportunities for errors is not a good idea. As for the interviewer, their likely thoughts are that your code lacks elegance and is hard to verify.

In this case, your code is buggy and crashes for sort_stack([3, 1, 4, 1]) on line 22, in asc_swap:

    if insert < yet_max:
TypeError: '<' not supported between instances of 'int' and 'NoneType' `


Codewars: "Twice linear" is running too long

As I understand it, the algorithm employed is as follows:

set is a set of numbers, all of which are in the sequence
arrOfResult is set in order
Invariant: the first nextInvoker + 1 elements of arrOfResult are complete: i.e. they form a prefix of the sequence with no gaps
We loop, extending set/arrOfResult by two elements each time until we have n elements, so the prefix is of length n/2 (plus or minus a couple: I haven't worked through the exact details)
We then form the closure under the two operations \$x \to 2x+1\$ and \$x \to 3x+1\$ and claim that the prefix of that closure contains the first n elements with no gaps.

The claim of that last point seems to me to need a comment showing why it's true.

But more importantly, the way in which the algorithm works seems to repeat a lot of work.

       arrOfResult = Array.from(set).sort((a, b) => a - b);

sorts the same elements as the previous time round the loop, plus two more, with a full \$\Omega(n \lg n)\$ sort.

An easy way to get an asymptotic improvement would be to use a suitable priority queue. A standard binary heap would probably be sufficient. It would also simplify the main method: just three variables (the heap, a counter, and the previous element in order to detect duplicates) and a single loop.

In fact, if you really optimise that loop it's not even necessary to fully implement the binary heap.

function dbl_linear(n) {
    var prev = 0,
        heap = [1];
    while (true) {
        if (heap[0] === prev) {
            // Standard heap pop: move last element to replace first and downheap
            heap[0] = heap.pop();
        }
        else {
            if (n-- === 0) return heap[0];

            // We want to pop x and then insert 2x+1 and 3x+1
            // Since 3x+1 is guaranteed to be larger than anything in the heap,
            // we can optimise its insertion. Then we can combine the pop and the
            // other insertion into one assignment and a downheap.
            prev = heap[0];
            heap.push(3 * prev + 1);
            heap[0] = 2 * prev + 1;
        }

        // Push heap[0] down until we restore the heap property
        downheap(heap);
    }
}

downheap not included.

The clever way of tackling a problem about a sequence of integers if you're allowed access to the Internet is to use the Online Encyclopedia of Integer Sequences to see what's known about it. Searching for the prefix given in the problem statement gives two results: the desired sequence with and without duplicates. Since you clearly interpret the (IMO ambiguous) problem statement as being without duplicates, look at the notes on the sequence without duplicates:

  ...
  a(n+1) = A007448(a(n)); giving also the record values of A007448 and their positions. - Reinhard Zumkeller, Jul 14 2010
  ...

A007448 is

  Knuth's sequence (or Knuth numbers): a(n+1) = 1 + min( 2*a(floor(n/2)), 3*a(floor(n/3)) )

I would be happy to leave it there, but since some commentators doubted my observation that this gave a simple and efficient solution, two implementations.

A naïve implementation (ignoring everything from Zumkeller's comment after the semicolon) would be

function dbl_linear(n) {
    var cache = {0 : 1},
        a = 1,
        knuth = function(n) {
            return cache[n] = cache[n] || 1 + Math.min(2 * knuth(Math.floor((n - 1) / 2)),
                                                       3 * knuth(Math.floor((n - 1) / 3)));
        }
    while (n--) a = knuth(a);
    return a;
}

But taking into account the observations made after the semicolon we can optimise quite heavily. This is slightly less simple (although a binary search is still simpler than a heap), but more efficient, and easily argued to run in \$O(n \lg n)\$ time:

function dbl_linear(n) {
    // a(n+1) = A007448(a(n)); giving also the record values of A007448 and their positions.
    // - Reinhard Zumkeller, Jul 14 2010

    // A007448(n+1) = 1 + min(2 * A007448(n/2), 3 * A007448(n/3))

    var A002977 = [1],
        i,
        ai = 1;

    function A007448(x) {
        // Find the smallest element of A002977 which is larger than x by binary chop
        // Invariant: A002977[lb] <= x < A002977[ub]
        // To ensure the invariant we need a special case
        if (x === 0) return 1;

        var lb = 0,
            ub = A002977.length - 1,
            mid;
        while (ub - lb > 1) {
            mid = lb + ((ub - lb) >> 1);
            if (A002977[mid] > x) ub = mid;
            else lb = mid;
        }
        return A002977[ub];
    }

    for (i = 1; i <= n; i++) {
        ai = 1 + Math.min(2 * A007448(Math.floor((ai - 1) / 2)),
                          3 * A007448(Math.floor((ai - 1) / 3)));
        A002977[i] = ai;
    }

    return ai;
}

Performance measured on tio.run using Spidermonkey. Times based on a single run, so take with a pinch of salt. They are at least illustrative.

n    | original code | sineemore's code | heap   | naïve Knuth | optimised Knuth
100  |        0.034s |           0.038s | 0.028s |      0.026s |          0.029s
10^3 |        0.185s |           0.031s | 0.028s |      0.032s |          0.031s
10^4 |       15.2s   |           0.147s | 0.031s |      0.042s |          0.040s
10^5 |       timeout |           8.3s   | 0.042s |      0.268s |          0.051s
10^6 |       timeout |          timeout | 0.195s |      4.4s   |          0.155s
10^7 |    not tested |       not tested | 2.4s   |    segfault |          1.9s


There are no docstrings. What do these functions do? What do they return?
The function pytagoras is already built into Python under the name math.hypot.
In point_in_line it appears that a line is being represented by a slope \$ m \$ and a y-intercept \$ b \$. But not all lines can be represented in this form! In particular, vertical lines have no slope or y-intercept.

It is more robust to represent a line in one of these three forms:

Two different points \$ p_0 \$ and \$ p_1 \$ on the line.
A point \$ p \$ on the line and a vector \$ v \$ along the line.
A vector \$ n \$ normal to the line, and its perpendicular distance from the origin \$ d \$.

The function average is built into Python under the name statistics.mean.
Much of this code is awkward because points are represented by Python tuples or lists. A simple operation like subtracting two points (in distance) requires disassembling the points into their elements, subtracting the elements, and then reassembling the result. If the code represented points using some kind of vector data structure, then a lot of it could be simplified.

For example, if the implementations were written very simply like this:

from math import hypot

def distance(p, q):
    """Return the distance from p to q."""
    return hypot(*(p - q))

def middle_point(p, q):
    """Return a point halfway between p and q."""
    return 0.5 * (p + q)

Then using the built-in turtle.Vec2D:

>>> from turtle import Vec2D
>>> distance(Vec2D(0, 0), Vec2D(3, 4))
5.0
>>> middle_point(Vec2D(1, 2), Vec2D(3, 4))
(2.00,3.00)

(Note that I don't actually recommend that you use turtle.Vec2D. This vector class is very basic: it doesn't have dot products or cross products or even division. But it's built into Python, so you can experiment with it without having to download or install anything. For actual use, NumPy arrays would be good, or pygame.math.Vector2, or something pure-Python like my vector.py.)
The unit test cases are always the same. There's nothing wrong with this, but it seems a bit wasteful, because every time you run the tests they go through the same steps. If a case passed last time you ran it, and you haven't changed the function under test, then it's certain to pass this time. All the test is protecting you against is a regression: it doesn't help you find new bugs.

A technique that sometimes does find new bugs is randomizing the test case. For example, we could test the distance function by generating random points that are a known distance apart:

import random

def test_distance(self):
    z = 1000000
    u = random.uniform
    p = Vec2D(u(-z, z), u(-z, z))
    self.assertEqual(cartesian.distance(p, p), 0)
    d = u(0, z)
    q = p + Vec2D(0, d).rotate(u(0, 360))
    self.assertAlmostEqual(cartesian.distance(p, q), d)
    self.assertAlmostEqual(cartesian.distance(q, p), d)

Then each time the test case is run a different set of points will be tested.

If you actually do get an error from a randomized test case, you'll want to reproduce it for debugging. How do you do that when it's random? You need to seed the random number generator when the test suite starts, and record the seed, for example like this:

import binascii
import os
seed = os.urandom(16)
print("seed:", binascii.hexlify(seed))
random.seed(seed)


for i in range(len(...)): is almost never the right way to go in Python. Instead, in this case, you should iterate directly over the characters:

for char in chaine:
    if char == 'A':
        ...

Rather than separate names nA, nC, etc., use a dictionary to map each character to its count:

counts = {'A': 0, 'C': 0, ...}

Now you don't need the ifs at all:

for char in chaine:
    counts[char] += 1
print counts['A'], counts['C']

In fact, Python already implements collections.Counter, a dictionary subclass that makes this task trivial:

from collections import Counter

counts = Counter(chaine)
print counts['A'], counts['C']


I personally would have saved it as a simple timestamp rather than a date, whether or not that's actually a better idea is debatable, but a timestamp requires half as much space as a datetime and is, imo, much easier to use.

On the client side you can get the user's UTC offset with a simple new Date().getTimezoneOffset() which will return the difference between the user's time and UTC in minutes (multiply by 60 to get seconds). Then you can use PHP's time() function to get the current timestamp and subtract the user's offset.

When you need to display it as a human readable date, PHP's date() can take a timestamp as a second parameter to display a specific time. Timestamps are just a lower level, more efficient way to handle time differences.

if($this->userIsAuthenticated())
{
   $this->session->timezone_offset = "-600"; // this value is coming from db
}

// inserting records
$data = array("created_time"=>time());
$this->db->insert("my_table", $data);

// fetching records
$date_from_db = $row->created_time;
$display_date = date("m/d/Y h:i a", $date_from_db - ($this->session->timezone_offset * 60));


The maxCheck variable is unused.  You also don't need the str.length() == 1 special case.

The whitespace around the else is unconventional.

The efficiency is fine.  Your algorithm, like any reasonable algorithm for this problem, is O(L), where L is the length of the input string.  You could try to squeeze out a small performance improvement, but it's almost certainly not worth it.

For a simple function like this, I don't think you need code comments.  However, a JavaDoc comment would always be useful.

The code works equally well on any CharSequence, not just a String, and should therefore be generalized.

/**
 * Finds the length of the longest run of identical characters.
 */
public static int maxRun(CharSequence seq) {
    if (seq.length() == 0) { return 0; }

    int maxRun = 1,
        currentRun = 1;

    for (int i = 1; i < seq.length(); i++) {
        if (seq.charAt(i) == seq.charAt(i - 1)) {
            currentRun++;
            if (currentRun > maxRun) { maxRun = currentRun; }
        } else {
            currentRun = 1;
        }
    }
    return maxRun;
}

The tests that you wrote are fine for a beginner, but the de facto standard for Java is to use junit.


Identify and extract URLs from text corpus

Have you considered:

re.compile('(www|http)\S+')

I tested it on your example string and it worked well (for both www and http). This does assume your links are likely to be links, and your data is fairly clean/consistent.


Codeforces problem python code optimization

A few things:

You should probably put the start = time.time() as early as possible if you want it to make sense.
As your class consists on a simple dict, there is no or little value in defining it. (In a "real life" scenario, it would be considered as a good practice).

Things got 25% quicker on average starting with 1000 ants.

You could make your code more concise by using structure to isolate the parts that change.

move_ants() would look like this :

def move_ants(g,point):
    x,y = point
    for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor
        if (a,b) in g.keys():
            g[a,b] += 1
        else:
            g[a,b] = 1
    g[point] -= 4

(Not performance impact)

In check_status(), instead of iterating on keys and then retrieve the corresponding value, you could use iteritems() :

check_status() would be like this :

def check_status(g):
    for k,v in g.iteritems():
        if v >= 4:
            return k
    else: return False

(This does improve performances)

To get the values from your dict with default values, you could use get(). You'd have something like print(g.get((x,y),0)) and g[a,b] = 1 + g.get((a,b),0). (I really didn't expect so but this made the script more than twice faster).

At the end, my script is like this (I've changed other details but it's mostly personal preferences) :

#!/usr/bin/python

import sys
import time

start = time.time()

##_no_of_ants, _no_of_queries = (input().split())
##no_of_ants = int(_no_of_ants)
##no_of_queries = int(_no_of_queries)

no_of_ants = 1000
no_of_queries = 1

def move_ants(g,point):
    x,y = point
    for a,b in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]: # or you could define x generxtor
        g[a,b] = 1 + g.get((a,b),0)
    g[point] -= 4

def check_status(g):
    for k,v in g.iteritems():
        if v >= 4:
            return k
    else: return False

g = {(0,0) : no_of_ants} # or you could use default dict
point = check_status(g)
while point:
    move_ants(g,point)
    point = check_status(g)
print("Sec:{}".format(time.time()-start))
for q in xrange(no_of_queries):
    ###_x,_y = input().split()
    ###x = int(_x)
    ###y = int(_y)
    x,y=1,1
    print(g.get((x,y),0))


One way to simplify this would be to use nested pairs (('a * 'b) * 'c) instead of a triple ('a * 'b * 'c). That way, you can use fst and snd to get to the parts that you want:

let triplets = List.zip (List.zip A B) C
let best = List.maxBy snd triplets
fst best

Notice that I also changed the names of variables to lowercase, that is the common naming convention in F#.


Is it possible to use if statement this way?

Yes.

Whether it is a good style depends on other factors.

Let us look at a few alternatives. First, your code (with cuddled braces):

if ( $update1 ) {
    if ( copy( "..." ) ) {
        if ( unlink( "..." ) ) {
            $update2 = $DB->query( "UPDATE ..." );
        }
    }
}

Then the same code using logical AND (&&).

if ( $update1 && copy( "..." ) && unlink( "..." ) ) {
    $update2 = $DB->query( "UPDATE ..." );
}

And another one without the braces {};

if ( $update1 && copy( "..." ) && unlink( "..." ) )
    $update2 = $DB->query( "UPDATE ..." );

And finally, an example that doesn't use if.

$update1
    && copy( '...' )
    && unlink( '...' ) )
    && $update2 = $DB->query( "UPDATE ..." );

All these examples perform the same operations.

If the ... stuff is long, the latter methods can get very wide conditionals making it difficult to read the code to see what is going on.

if ( $update1 && copy( 'a/very/long/source/path', 'a/very/long/destination/path' ) && unlink( 'a/very/long/source/path' ) )
    $update2 = $DB->query( "UPDATE ..." );

You could rewrite it like this:

if (   $update1
    && copy( 'a/very/long/source/path', 'a/very/long/destination/path' )
    && unlink( 'a/very/long/source/path' ) )
    $update2 = $DB->query( "UPDATE ..." );

But it looks little clunky. It is hard to see where the conditional ends.

The last style makes this prettier:

$update1
    && copy( 'a/very/long/source/path', 'a/very/long/destination/path' )
    && unlink( 'a/very/long/source/path' ) )
    && $update2 = $DB->query( "UPDATE ..." );

I do not care for this style, but it looks pretty and it tells you exactly what is happening at a glance.

One problem with most of the alternatives to the first method is debugging and maintenance.

If I want to log the unlink error is some special way I can do this in the first method:

if ( $update1 ) {
    if ( copy( "..." ) ) {
        if ( unlink( "..." ) ) {
            $update2 = $DB->query( "UPDATE ..." );
        } else {
            log_unlink_error( '...' );
        }
    }
}

To quickly add that code to the other methods described here, may require more rewriting.

So, in this case, your style for handling multiple conditions might depend on the age of your code and how much testing you expect to be doing.

If it is well tested and you never need to edit it, then one of the alternatives is fine if you use that style consistently throughout all your code.
If this is new code, write it out the long way. It may be easier to test and maintain.


Besides the already mentioned things I like to add a few of my own:

Connection charset
You should set the charset of the connection the be the same of your php files (and  definition when you use html):

Simply add , array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'") after $this->pass

Coding Style

The naming of class variables shouldn't be all uppercase, so rename $DBH to $dbh.

Additionally I'd advice you the read the Coding Style Guide from the PHP Framework Interop Group which many php framework developers pay attention to lately.
http://www.php-fig.org/psr/psr-2/

There it says in Chapter 4.3 that you should put the opening curly brace of function on a new line.

User Input

As soon as some user input gets into your sql statement you should use parameterized queries, for example:

$stmt = $this->dbh->prepare("SELECT * FROM user WHERE passwort_hash = :passwort_hash");

$stmt->bindParam(":passwort_hash",md5($_POST['passwort']));
$stmt->execute();
...

This protects you against SQL-Injections.


Initialise your variables

You aren't initialising inc.  This is probably working for you, because the compiler is setting it to 0.  This isn't guaranteed though, so you should be explicitly initialising it before you use it:

long inc = 0;
srand(time(0));
while (inc < 20)

Cleanup after yourself

As I mentioned in the comments, you're also leaking memory:

bool* b = new bool[size];

the allocated array is never cleaned up by your application.  You should have a paired delete somewhere in the code when you're done with the array:

delete [] b;

Expressive names

Think about using more expressive names.  You're referring to the array of bools as both 'b' and 'array' in different parts of your code.  One of the names tells your there's going to be more than one, whilst the other name hints at the type.

Your returnarray method actually prints it to the console.  If you get the names right, your program will be a lot easier to follow.


Find occurrences of strings in view B in column from table A

I think you could just simplify this with CHARINDEX and CROSS APPLY().  See how this method stacks up in your environment and paste your execution plans if it happens to be slower, if you can.

To give a concrete example, create these tables:

declare @ViewB table (myStrings varchar(16))
insert into @ViewB
values
('ABC'),
('EFGH'),
('IJ')

declare @TableA table (colToSearch varchar(256))
insert into @TableA
values
('123 ABC 45 IJ'),
('IJ'),
('IJ EFGH 22')

Then this CROSS APPLY() query should be more efficient:

select
    charindex(b.myStrings,a.colToSearch) as Pos
    ,a.colToSearch as String
    ,b.myStrings as Occurance
from
    @ViewB b
cross apply (select * from @TableA) a
where
    charindex(b.myStrings,a.colToSearch) > 0
order by
    String, charindex(b.myStrings,a.colToSearch)

Alternatively, you could use CROSS JOIN:

select
    charindex(b.myStrings,a.colToSearch) as Pos
    ,a.colToSearch as String
    ,b.myStrings as Occurance
from
    @ViewB b
cross join @TableA a
where
    charindex(b.myStrings,a.colToSearch) > 0
order by
    String, charindex(b.myStrings,a.colToSearch)

RESULTS

+-----+---------------+-----------+
| Pos |    String     | Occurance |
+-----+---------------+-----------+
|   5 | 123 ABC 45 IJ | ABC       |
|  12 | 123 ABC 45 IJ | IJ        |
|   1 | IJ            | IJ        |
|   1 | IJ EFGH 22    | IJ        |
|   4 | IJ EFGH 22    | EFGH      |
+-----+---------------+-----------+


Summing up distinct elements in steps (follow up)

Bugs

Console.WriteLine(CalculateScore(new[] { 1 } ));
Console.WriteLine(CalculateScore(new[] { 2, 1 } ));
Console.WriteLine(CalculateScore(new[] { 3, 2, 1 } ));

What's the expected output? The question is maybe underspecified for the first case (I would say it's 0), but the other two are clear: 0 and 2.

But we get:

-2147483648
-2147483646
-2147483643

Bonus question: what is the correct result for the array { 1, 1 }? I would say 2, but your program returns 0.


Since the elements in each row grows, sorting the row only to take the k smallest is a bit wasteful. Using numpy.partition should always be faster:

sorted_row_t = np.partition(row_nonzero, k)[:k]

This is not needed with the examples you give, the row is already an array and flattened:

flat_row = np.squeeze(np.asarray(row))

Similarly, you can just use numpy.nonzero, no need to flatten the flattened row again:

row_nonzero = flat_row[np.nonzero(frow)]

However, this whole for loop can be done entirely in numpy:

First, mask all zeros by setting them to numpy.nan:

D = np.where(D == 0, np.nan, D)

Get the k smallest elements of each row. Since numpy.nan is not smaller than any number it will only appear at the beginning if (almost) the whole row was zeros:

k_smallest = np.partition(D, k, axis=1)[:, :k]

Compute the median of each row, and then the median of the median, ignoring numpy.nan values using numpy.nanmedian:

kmedian_dist = np.nanmedian(np.nanmedian(k_smallest, axis=1))

The first two steps can even be pulled outside of the for k in ... loop, which will save some more time. In that case we have to sort the whole array, though, because numpy.partition does not guarantee that the values are sorted, only that the k smallest values are in the slice up to k. Since K seems to be max(D_sym.shape) in all cases anyway, this should not make such a big difference. It will if the k at which the for loops stops is small enough, though, so you will have to test this.

There's no need to break and then immediately return afterwards, just return directly.

Python has an official style-guide, PEP8. It recommends using 4 spaces as indentation (not 3) and spaces after commas.

In summary, this should do the same as your code:

def autoselect_minsamps_graipher(D_sym, eps, K, kmedian_thresh):
    D = np.sort(np.where(D_sym == 0, np.nan, D_sym), axis=1)
    kmedian_dist_prev = 0
    for k in range(2, K):
        kmedian_dist = np.nanmedian(np.nanmedian(D[:,:k], axis=1))
        if abs(kmedian_dist - kmedian_dist_prev) <= kmedian_thresh:
            return k
        kmedian_dist_prev = kmedian_dist
    return 10 # fall back value

This is faster than your implementation, but suffers from similar scaling behaviour:

n       autoselect_minsamps_orig    autoselect_minsamps_graipher
100     0.028 s                     0.0088 s
1000    0.32 s                      0.064 s
10000   9.5 s                       3.6 s

You could also make timing your code easier by using a decorator:

from time import perf_counter

class Timer:
    def __init__(self, name=""):
        self.name = ""
        self.start = None

    def __enter__(self):
        self.start = perf_counter()

    def __exit__(self, *args, **kwargs):
        delta = perf_counter() - self.start
        print(f"{self.name} finished in {delta:.2f} seconds")

Or, if you are stuck on Python 2:

from time import time

class Timer:
    def __init__(self, name=""):
        self.name = ""
        self.start = None

    def __enter__(self):
        self.start = time()

    def __exit__(self, *args, **kwargs):
        delta = time() - self.start
        print "{} finished in {:.2f} seconds".format(self.name, delta)

Which you can use like this:

D = euclidean_distances(X,X)
eps = 0.25
kmedian_thresh = 0.005
K = num_training_examples

with Timer(f"autoselect_minsamps_orig, K = {K}"):
    min_samples = autoselect_minsamps_orig(D, eps, K, kmedian_thresh)

Note that I used time.perf_counter, which is better suited for timing, but which is Python 3 only.


Check if a numpy array contains numerical data

1. Question

You write, "I feel like the .dtype.kind in ... is too complex". You're probably right about that: I've never needed anything like this in NumPy code. Normally I know what the datatypes are, or I rely on the caller setting them up correctly. But I don't think I can help unless you can explain what you are using this for. Why do you need to know whether an array is numeric or not?

Update: you say in comments that you are trying validate data read in from files. For this use case, consider using np.genfromtxt, passing loose=False. For example:

>>> from io import BytesIO
>>> np.genfromtxt(BytesIO(b'1,2,x,3'), dtype=float, delimiter=',', loose=False)
Traceback (most recent call last):
  File "numpy/lib/_iotools.py", line 688, in _strict_call
    new_value = self.func(value)
ValueError: could not convert string to float: b'x'

2. Review

You've written a docstring! That's excellent.
But I think the docstring could be clearer about what happens when array is not a NumPy array. I would write something like, "Determine whether the argument has a numeric datatype, when converted to a NumPy array."
The docstring says, "False if object or string" but those are not the only non-numeric kinds (there's also unicode and void), so I would write something like, "True if the array has a numeric datatype, False if not."
np.asarray is cheap if the argument is already an array: "No copy is performed if the input is already an ndarray" so you might as well call it in all cases, and avoid the try: ... except: and the duplicated code.
The set numerical_dtype_kinds is always the same, and so it ought to be a global variable.
The test cases would be more convenient to run if you used the features in the unittest module.
There's a lot of repetition in the test cases. Since all the tests are of the form assert is_numeric_array(x) or assert not is_numeric_array(x), it would make sense to put the test cases in a couple of lists, and iterate over them. There's duplication between test_not_array and test_array that could easily be removed.
There are no test cases checking that Booleans are numeric, or that objects are not.

3. Revised code

import numpy as np

# Boolean, unsigned integer, signed integer, float, complex.
_NUMERIC_KINDS = set('buifc')

def is_numeric(array):
    """Determine whether the argument has a numeric datatype, when
    converted to a NumPy array.

    Booleans, unsigned integers, signed integers, floats and complex
    numbers are the kinds of numeric datatype.

    Parameters
    ----------
    array : array-like
        The array to check.

    Returns
    -------
    is_numeric : `bool`
        True if the array has a numeric datatype, False if not.

    """
    return np.asarray(array).dtype.kind in _NUMERIC_KINDS

from unittest import TestCase

class TestIsNumeric(TestCase):
    NUMERIC = [True, 1, -1, 1.0, 1+1j]
    NOT_NUMERIC = [object(), 'string', u'unicode', None]

    def test_is_numeric(self):
        for x in self.NUMERIC:
            for y in (x, [x], [x] * 2):
                for z in (y, np.array(y)):
                    self.assertTrue(is_numeric(z))
        for x in self.NOT_NUMERIC:
            for y in (x, [x], [x] * 2):
                for z in (y, np.array(y)):
                    self.assertFalse(is_numeric(z))
        for kind, dtypes in np.sctypes.items():
            if kind != 'others':
                for dtype in dtypes:
                    self.assertTrue(is_numeric(np.array([0], dtype=dtype)))


If one were to abstract out the filter function (named filt here), it would greatly simplify writing same-parity:

(define (filt test? lis)
  (cond
    ((null? lis) lis)
    ((test? (car lis)) (cons (car lis) (filt test? (cdr lis))))
    (else (filt test? (cdr lis)))))

(define (same-parity n . lis)
  (filt (if (odd? n) odd? even?) lis))

The filter function is common enough that it is part of the Scheme standard and is appropriately named filter.


OleDbContext to keep OleDbConnection alive

It turns out that OleDb does not have connection pooling and
  opening/disposing it takes a lot of time.

I have read somewhere, that as long as you keep one connection (for sure with the exact same connection string) open the connection pooling works, but don't count on it, just test it. You could at test initialize open this said connection and close it at test terminate.

Now let us look at your code.... well, there isn't much to say. It is easy to read, you are using braces {}, fields, methods and method parameters are well named.

Just some little nitpicks:

what happens if the constructor argument is an empty string ?
you are testing excel files, why don't you ensure that the passed fileName has at least the correct file extension ?


Static wrapper class for log4net Logging - thread safety

This is not thread safe, just because the LogType static property. The basic problem of such design is that any log operation while setting the log type requires two calls and changes in global state. Imagine how an hypothetical client code would look like:

Log.LogType = LogType.Database;
//What happens between these two lines?
Log.Info("CodeReview", "Testing error logging", new Exception("Kaboom"));

The first line sets the global log type, and the second uses it, quite simple. But what happens if another thread runs similar code in between? LogType can be changed in the meanwhile (look at my comment in the code), changing the effective destination to the unsuspecting code. Thus, it's not thread safe. As you mention, since Log4Net in itself is thread safe, logs methods have no problems with this, but the destination can be somewhat surprising.

You mention a lock to overcome this in comments. Again an hypothetical usage could be like this:

lock (typeof(Log))
{
    Log.LogType = LogType.Database;
    Log.Info("CodeReview", "Testing error logging", new Exception("Kaboom"));
}

This solves the issue but at a high cost, the "fix" must be implemented in each and every call, instead of doing it centrally from within the Log class. Since the operation spans 2 methods, you can't lock within a method. Additionally this increases contention and reduces performance, as all logging is now syncronized and each thread must wait for the others to finish logging. While Log4Net could potentially do the same internally, it may also implement other optimizations, that such approach will nulify.

The root problem comes from the global state, the logger is a just stored in a static variable and can be overwriten by anyone, including between calls. A possible solution would be to pass the log type as a parameter and create a local logger for each call and get rid of the LogType property altogether:

public static void Info(string source, string description, Exception exc = null, LogType logType = LogType.CMS)
{
    ILog logger = LogManager.GetLogger(logType.ToString());
    logger.Info(new LogItem() { Source = source, Description = description }, exc);
}

This results in NO global state, which eliminates chances of races conditions, and also simplify client code, as now every log request is a single call to the appropriate method.


Mapping values. Should a single use variable be declared as a variable at all?

In this specific scenario, I would definitely go with your first approach. Putting a large amount of data right in the middle of your logic makes it extremely difficult to follow the logic.
To answer the general question of "should data associated with a specific function go inside its body or outside?" - there's never one right answer. I like to think of it as though there are various pressures going on. If your function is pretty cluttered but your module is pretty empty, then moving some stuff out of the function and into the module helps improve the readability of that function without sacrificing much. On the other hand, if there's already a whole lot of stuff in that module, and the function is really simple to follow then it might be worth it to move stuff into the function (or split the module up into multiple modules, if the containing folder isn't too cluttered). One important task of a programmer is to know when and how to shuffle clutter around to prevent any one spot from feeling too overwhelming.


Checking to see if value is in datalist or not

Your code is a bit hard to read, but I suggest that

array.indexOf(element)

or

array.some(callback)

is what you are looking for.

Documentation:

indexOf

some


Highlighting and copying spreadsheet rows that match a criterion

I don't see you using Option Explicit which is always a good idea. But you are defining your variables - which is good.

Using variable names like Row is generally a bad idea - Row already means something in excel.

The other variables LR, lr2 and r are bad names - what do they do? Why do you need two LR? I'd used SwivelLastRow and DisputedLastRow for the LR variables. The r is just a counter, so why not give it a better name? CurrentRow maybe?

I might also break the two procedures up into different subs, maybe Highlight_Disputed and CopyDisputed.

You're also using ActiveSheet.UsedRange and select which is generally something to be avoided.

The first procedure could be something like this -

   Dim wsSwivel As Worksheet
   Set wsSwivel = Sheets("Swivel")
   Dim TestCell As Range
   Dim LastRow As Long
   LastRow = wsSwivel.Cells(Rows.Count, "F").End(xlUp).row
   Dim TestArea As Range
   Set TestArea = Sheets("Swivel").Range("F1:F" & LastRow)

   Dim AfterDispute As String
   AfterDispute = "After Dispute For SBU"
   Dim ImpactStatus As String
   ImpactStatus = "Impact Status"
   Dim AfterDisputeHighlight As Long
   AfterDisputeHighlight = 6

   For Each TestCell In TestArea
    If TestCell = AfterDispute Then
        TestCell.Rows.Interior.ColorIndex = AfterDisputeHighlight
        TestCell.Rows.Font.Color = RGB(255, 0, 0)
    ElseIf TestCell = ImpactStatus Then
        TestCell.Rows.Interior.Color = RGB(197, 190, 151)
        TestCell.Rows.Font.Color = RGB(0, 0, 0)
    Else:
        TestCell.Rows.Interior.ColorIndex = xlNone
        TestCell.Rows.Font.Color = RGB(0, 0, 0)
    End If
   Next

I'd also find a way to assign the RGB colors to variables so it looks cleaner.

After that you can exit sub or just CopyDisputed. Since CopyDisputed isn't returning a value, it's not a function. And since you already have some needs defined you can put in parameters:

Sub CopyDisputed(ByVal FromSwivel As Long, ByVal DisputedText As String)

And just use what you have -

CopyDisputed LastRow, AfterDispute

This eliminates the LR and one of the For Loops.

Sub CopyDisputed(ByVal FromSwivel As Long, ByVal DisputedText As String)
   Dim wsDisputed As Worksheet
   Set wsDisputed = Sheets("Disputed")
   Dim CopyRow As Long
   Dim DisputedRow As Long
   DisputedRow = 1
   wsDisputed.Range("B:Z").ClearContents

    For CopyRow = FromSwivel To 1 Step -1
        If Cells(CopyRow, "F") = DisputedText Then
           Rows(CopyRow).EntireRow.Copy Destination:=wsDisputed.Rows(DisputedRow)
           'Whoops you don't want to delete, but then why are you step -1?
           'Rows(CopyRow).EntireRow.Delete shift:=xlUp
           DisputedRow = DisputedRow + 1
        End If
    Next

End Sub

I'm assuming I understand your Disputed ws copying to be on the entire row, unless you're trying to keep column A intact?

Breaking it into two procedures makes it easier to gather what each code block is doing.

But, of course, you can avoid this if you do the copying to Disputed when you do the highlighting of the AfterDispute rows. This is something that would increase performance so you don't need to loop through column F twice:

Option Explicit

Sub Highlight_Copy_Disputed()

Application.ScreenUpdating = False

   Dim wsSwivel As Worksheet
   Set wsSwivel = Sheets("Swivel")
   Dim wsDisputed As Worksheet
   Set wsDisputed = Sheets("Disputed")
   Dim TestCell As Range
   Dim LastRow As Long
   LastRow = wsSwivel.Cells(Rows.Count, "F").End(xlUp).row
   Dim DisputedRow As Long
   DisputedRow = 1
   Dim AfterDisputeHighlight As Long
   AfterDisputeHighlight = 6

   Dim TestArea As Range
   Set TestArea = Sheets("Swivel").Range("F1:F" & LastRow)

   Dim AfterDispute As String
   AfterDispute = "After Dispute For SBU"
   Dim ImpactStatus As String
   ImpactStatus = "Impact Status"

   wsDisputed.Range("B:Z").ClearContents

   For Each TestCell In TestArea
    If TestCell = AfterDispute Then
        TestCell.Rows.Interior.ColorIndex = AfterDisputeHighlight
        TestCell.Rows.Font.Color = RGB(255, 0, 0)
        TestCell.EntireRow.Copy Destination:=wsDisputed.Rows(DisputedRow)
        DisputedRow = DisputedRow + 1
    ElseIf TestCell = ImpactStatus Then
        TestCell.Rows.Interior.Color = RGB(197, 190, 151)
        TestCell.Rows.Font.Color = RGB(0, 0, 0)
    Else:
        TestCell.Rows.Interior.ColorIndex = xlNone
        TestCell.Rows.Font.Color = RGB(0, 0, 0)
    End If
   Next
  Application.ScreenUpdating = True
End Sub


Create new columns depending on the columns in a table

Seems like there are up to two rows for f and one for b.

In that case you can simplify it to a single GROUP BY using conditional aggregation:

SELECT legacy_id,
   -- first number 'f'
   Min(CASE WHEN phone_type = 'f' THEN phone_number END) AS f_phone_number_1,
   -- first number 'b'
   Min(CASE WHEN phone_type = 'b' THEN phone_number END) AS b_phone_number_1,
   -- when MIN and MAX are different return the 2nd number
   NullIf(Max(CASE WHEN phone_type = 'f' THEN phone_number END)
         ,Min(CASE WHEN phone_type = 'f' THEN phone_number END)) AS f_phone_number_2
FROM table
GROUP BY 1

Edit:

Of yourse you can't use the MAX/MIN approach when there's more than two rows per type.

But you can reduce the ranks down to one and move the case to the outer select:

SELECT legacy_id,
   Max(CASE WHEN phone_type = 'f' AND rn = 1 THEN phone_number END) AS f_phone_number_1,
   Max(CASE WHEN phone_type = 'f' AND rn = 2 THEN phone_number END) AS f_phone_number_2,
   Max(CASE WHEN phone_type = 'f' AND rn = 3 THEN phone_number END) AS f_phone_number_3,
   Max(CASE WHEN phone_type = 'f' AND rn = 4 THEN phone_number END) AS f_phone_number_4,
   Max(CASE WHEN phone_type = 'b' AND rn = 1 THEN phone_number END) AS b_phone_number_1,
   Max(CASE WHEN phone_type = 'b' AND rn = 2 THEN phone_number END) AS b_phone_number_2,
   Max(CASE WHEN phone_type = 'b' AND rn = 3 THEN phone_number END) AS b_phone_number_3,
   Max(CASE WHEN phone_type = 'b' AND rn = 4 THEN phone_number END) AS b_phone_number_4
FROM
 (
   SELECT legacy_id,
      phone_type,
      phone_number,
      Dense_Rank()
      Over (PARTITION BY a.legacy_id, a.phone_type
            ORDER BY a.phone_number) AS rn
   FROM tab
 ) AS dt
GROUP BY 1


Here's an example adapted to your case which uses ThreadPoolExecutor.

This example allows a configurable throughput while establishing TCP connections to servers.

Checking Future.get() for each submitted worker thread ensures that no servers are checked more than others.

What happens here:

Target domains are added to a list
If the domain is an unknown host (DNS unreachable) than it's skipped.
Resolvable domains are submitted as 1 domain per 1 thread into the pool.
If the pool gets overflown by PingWork threads, that submission is delayed for 3 seconds until the pool is ready to accept.
Each TCP port 80 connection has a timeout of 5 seconds.
When there are no exceptions thrown by a TCP connection to a certain host, it is assumed reachable and not reported.
When all PingWork threads finish, main thread waits for 10 seconds until next round.

Here's the source

// package
// imports

public class Main {
    private static List<InetSocketAddress> servers =
            new ArrayList<InetSocketAddress>();

    public static void main(String[] args)
            throws InterruptedException, ExecutionException {
        String[] domains = new String[]{
                "3Com.com",
                // etc. etc.
                "Kai.com"
        };

        for (String hostname : domains) {
            try {
                servers.add(
                        new InetSocketAddress(
                                InetAddress.getByName(hostname),
                                80
                        )
                );
            } catch (UnknownHostException e) {
                System.out.println("Unknown host: " + hostname);
            }
        }

        System.out.println(
                "Total number of target servers: " + servers.size()
        );

        BlockingQueue<Runnable> work =
                new ArrayBlockingQueue<Runnable>(5);

        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,                      // corePoolSize
                10,                     // maximumPoolSize
                5000,                   // keepAliveTime
                TimeUnit.MILLISECONDS,  // TimeUnit
                work                    // workQueue
        );

        pool.prestartAllCoreThreads();

        pool.setRejectedExecutionHandler(
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(
                            Runnable r,
                            ThreadPoolExecutor executor
                    ) {
                        System.out.println("Work queue is currently full");
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignore) {

                        }
                        executor.submit(r);
                    }
                }
        );

        Collection<Future<?>> futures = new LinkedList<Future<?>>();

        while (true) {
            for (InetSocketAddress server : servers) {
                futures.add(pool.submit(new PingWork(server)));
            }
            for (Future<?> future : futures) {
                future.get();
            }
            System.out.println(
                    "All servers checked. Will wait for 10 seconds until next round"
            );
            Thread.sleep(10000);
        }

    }

    private static class PingWork implements Runnable {
        private static final int TIMEOUT = 5000;
        private InetSocketAddress target;

        private PingWork(InetSocketAddress target) {
            this.target = target;
        }

        @Override
        public void run() {
            Socket connection = new Socket();
            boolean reachable;

            try {
                try {
                    connection.connect(target, TIMEOUT);
                } finally {
                    connection.close();
                }
                reachable = true;
            } catch (Exception e) {
                reachable = false;
            }

            if (!reachable) {
                System.out.println(
                        String.format(
                                "%s:%d was UNREACHABLE",
                                target.getAddress(),
                                target.getPort()
                        )
                );
            }
        }
    }
}

Here's the output of 30 domain sample

    Total number of target servers: 30
    Work queue is currently full
    Work queue is currently full
    Amdahl.com/129.212.11.21:80 was UNREACHABLE
    All servers checked. Will wait for 10 seconds until next round
    Work queue is currently full
    Work queue is currently full
    Amdahl.com/129.212.11.21:80 was UNREACHABLE
    All servers checked. Will wait for 10 seconds until next round

You can increase the maximumPoolSize of ThreadPoolExecutor in order to get all domains into queue in just one iteration. However I left that part for you.


Converting regular text phrase to Pig Latin in Groovy

General

Strings

In Groovy you can use single quotes for "regular" strings. Documentation

buffer = ""
// equivalent to
buffer = ''

It's unlike Java where single quotes are for characters.

One exception to this is when using the $variable in Strings, you have to use double quotes for this.

buffer = "$buffer${textArray[i][j]}"
// not equivalent to
buffer = '$buffer${textArray[i][j]}'

Also, when placing variables in Strings, I tend to always wrap in { } even when it's not needed.

buffer = "${buffer}${textArray[i][j]}"
// it's just more explicit

Method signature

This may be an unpopular opinion, but I like not using def in method signatures and instead using explicit types. It makes IDE suggestions and readability a lot better.

static void makePigLatin(String text){
// better than
static void makePigLatin(def text){

To me def is only okay inside of a method.

eachWithIndex

I actually just looked this up writing the answer. You can use a method called eachWithIndex on arrays in place of a closure. Documentation

for (int i = 0; i < textArray.length; i++) {
// or...
textArray.eachWithIndex { e, i ->
    // where i is the index and e is the textArray[i]
}

Scope

buffer and `translated are only ever used in your for loop. It's important to limit the scope of variables as much as possible. So it's probably better to declare them in the loop like so

// String buffer, translated
// remove above

for (int i = 0; i < textArray.length; i++) {

    String buffer = ""
    String translated = ""

Return a String instead of printing

Instead of your method being void make it return a String and remove all the println from it. Then from where you call makePigLatin instead do println makePigLating('some string here').

This limits the side-effects of the method. For tiny programs this is not a big deal but in larger projects knowing exactly what a method will do is very handy -- especially if the method is what is known as a "pure function" which means it literally has no side effects and its output is directly dependent on its output.

Consistent formatting

In some places you have spaces before braces (for (int i = 0; i < textArray.length; i++) {) and in others you don't (static void makePigLatin(String text){). It's less important whether or not you use them than how important it is to be consistent. Personally I put spaces before them.

Specifics

The below code is a little odd to me, it's saying in the ith word in the jth character, find each a in the jth character that is any of the vowels.

textArray[i][j].find { a -> vowels.any {a.contains(it)}}

No need to do a find on a single character. The below is a cleaner way to me.

vowels.any { vowel -> vowel.equals(textArray[i][j]) }

The below

buffer = "$buffer${textArray[i][j]}"

Can simply be

buffer += textArray[i][j]


Parsing a string containing arithmetic operations in prefix notation

First, since you're parsing strings at the character level, you could cast the character to an int and utilize a switch statement to check the values (vs. an else if which checks each branch), e.g. switch (static_cast<unsigned int>(s[k])). Also, unless there's a specific need, it's advisable to prefer the pre-increment vs. post-increment operators, e.g. ++k vs. k++. These 2 changes are for speed optimizations (since you are doing parsing). For the static_cast of the char type, strictly speaking, you do not need the explicit cast to an int type, that's there for explicitness (pedant/completeness/explanation) since switch statements only work on integral types, thus any type that can be converted is (either implicitly by the compiler, or explicitly by the user).

Also, there's a logic bug in your code, the line that reads else if(48 <= s[k] <= 57) will always be true. This line evaluates to the following: else if ((48 <= s[k]) <= 57) .. take note of the added parenthesis. Essentially you're asking if a boolean value is <= 57 which is always true. This line should read as such: else if ((48 <= s[k]) && (s[k] <= 57)).

The following is the updated code:

void parse(Formula*& f, std::string s, int &k)
{
    switch (static_cast<unsigned int>(s[k])) // explicit cast
    {
        case '(':
        {
            switch (s[++k]) // implicit cast
            {
                case '+': f = new Add(); break;
                case '/': f = new Div(); break;
                case '-': f = new Sub(); break;
                case '*': f = new Mul(); break;
                default:  f = new Exp(); break;
            }
            parse(f->left, s, ++k);
            k = k + 2;
            parse(f->right, s, k);
            ++k;
        } break;
        case 'x':
            f = new X();
            break;
        default:
            if ((48 <= s[k]) && (s[k] <= 57)) {
                f = new Integer();
                (static_cast<Integer*>(f))->i = s[k] - 48;
            }
            break;
    }
}

Again, I don't have your complete code so these semantics might need to be adjusted for your specific case, but in general this cuts down branch prediction and temporary usage (which the compiler can then optimize further).

Hope that can help.


Ruby implementation of Soundex algorithm

Per your request, your code converted to the Ruby way perhaps would be as follows.

A small point: in our output, in the Ruby world, we would avoid the => fat comma which Rubyists (at least in the English-speaking world) call a 'hash-rocket' because:

It reads like Ruby's (older) hash accessing syntax.
In Ruby language documentation (e.g., see Array), the similar #=>, comprising a hash to introduce a comment, followed by a hash-rocket (presumably, this gave us the name), shows us the result (or value) of an individual line of code—the two meanings conflict.

BTW, we also would avoid ->, dash-greater-than, which in Ruby (syntax) generates a lambda.

class Soundex < String
  IGNORED_BEGINNING_LENGTH = 1
  MINIMUM_LENGTH = 3

  CASES = [ # Keep order.
    /[bfpv]/,
    /[cgjkqsxz]/,
    /[dt]/,
    /l/,
    /[mn]/,
    /r/,
  ]
  CASES_LENGTH = CASES.length

  def initialize(surname)
    a = surname.split ''
    kept    = a.take(IGNORED_BEGINNING_LENGTH).join ''
    indices = a.drop(IGNORED_BEGINNING_LENGTH).map do |e|
      (0...CASES_LENGTH).detect{|i| e =~ (CASES.at i)}
    end.compact
# Adjust to one-based notation; collapse repetition; right-pad with zeros.
    digits = indices.map(&:succ).join('').squeeze.ljust MINIMUM_LENGTH, '0'
    super kept + digits
  end

  def self.show(s) "#{s}: #{new s}" end
end

names = %w[Smith Johnson Williams Jones Brown Atchison]
names.each{|s| puts Soundex.show s}

gives the results

Smith: S530
Johnson: J525
Williams: W452
Jones: J520
Brown: B650
Atchison: A325


Function equal to built-in
def get_subdirs(Dir):
    dir_array = []
    for x in os.listdir(Dir):
        dir_array.append(x)
    return dir_array

This is exactly the same as os.listdir, so just use it instead of the whole function.
Iterate simpler
for x in range(len(dir_array)):
    file_size = float(get_dir_size(Dir + "\\" + dir_array[x])) / 1073741824  # Converts the bytes to GB

    Dict[dir_array[x]] = file_size

Can become:
for dir in dir_array:
    file_size = float(get_dir_size(Dir + "\\" + dir)) / 1073741824  # Converts the bytes to GB

    Dict[dir] = file_size

Constants at the start
Putting constants at the start of the code is better than putting them inside, so at the start:
BYTES_IN_GIGABYTE = 1073741824

User message
Your code works for files so:
Dir = askdirectory(title="Select Folder")

becomes:
Dir = askdirectory(title="Select Folder or File:")

Fancy progressbar
A fancy way to signify that the program is working can be found here
-1 lost in code
You return -1 sometimes from get_dir_size but you never check for it.
One comment on the logic
for i in sort_dict:
    if i[1] > 1:  # continues using gigabytes

I would rename i to dir and add a comment saying what i[1] is.
Cross platform compatibility
As suggested by @s.dallapalma avoid concatenating paths with the plus (+) sign, and use os.path.join or pathlib instead. Thus, the code can work on different OS.
I liked the attention to handling of exception and the new clean format strings.


Writing strcat (string concatenate) in C

You renamed strcat() to cat_string(), so I suppose it's fitting that you reversed the traditional order of the parameters as well.  ☺

I would make three changes:

Changing the first argument to const helps prevent users notice if they call the function with the parameters swapped (but doesn't prevent it in all cases).
You have a stray pointer dereference.  It was misleading, but luckily harmless.  (In the first while loop, you just want to advance the copy pointer.  You don't care about what value it points to as you advance; you only care when you check for the NUL terminator.)
You can remove a statement just by changing the loop structure.
Edit (Rev 3): Previous recommendation was buggy, and has been retracted.  Credit to @MarcvanLeeuwen.

To answer your questions…

The only way to find out where to start appending is to walk the entire destination string to locate where it ends.  That's just how C-style strings work.
Yes, returning destination seems appropriate.  It's analogous to what strcat() does.

One final note: two spaces for indentation is too stingy, in my opinion.  It's insufficient for readability, and it also encourages inappropriately deep nesting (which would be a symptom of poorly organized code).

char *cat_string(const char *to_cat, char *destination) {
    char *copy = destination;
    while (*copy != '\0') {
        copy++;                 /* Removed superfluous dereference. */
    }
    …
}


Calculating pi with Monte Carlo using OpenMP

This code has a serious problem due to (at least the typical implementation of) rand(). rand() normally has a (hidden) seed value, and each call to rand() modifies the seed. At least in most implementations, that means rand always forces serialization.
That means, calling rand() (a couple of times) in your inner loop will prevent code from scaling well at all. In fact, in most cases (as Toby Speight showed) a multi-threaded version will run substantially slower than a single-threaded version.
To fix this, you pretty much need to use some other random number generator. Your implementation may provide one (e.g., erand48 is fairly common). If you really need your code to be portable, you could write your own, something on this order:
#include <time.h>

typedef unsigned long long rand_state;

// multiplier/modulus taken from Knuth Volume 2, Table 1
static const int multiplier = 314159269;
static const int addend = 1;
static const int modulus = 0xffffffff;

// note that this works differently from srand, returning a seed rather than setting
// a hidden seed.
rand_state omp_srand() {
    rand_state state = time(NULL);
    state ^= (unsigned long long)omp_get_thread_num() << 32;
    return state;
}

int omp_rand(rand_state *state) {
    *state = *state * multiplier + addend;
    return *state & modulus;
}

Note that since it's entirely likely that all the threads get started in the same second, this combines the current time with the thread ID to seed each thread's generator. Although it's not 100% guaranteed, this gives a pretty high likelihood that each thread's generator will start with a unique seed. On the other hand, it also means that we have to start the thread, and then seed the generator inside that thread.
To use this, our code would be something on this general order:
double calculate_in_circle_random_count(void) {

    static const unsigned total = 1000000000;
    unsigned in_circle = 0;

#pragma omp parallel reduction(+:in_circle)
    {
        // do per-thread initialization
        rand_state seed = omp_srand();
        int count = total / omp_get_num_threads();
        int i;

        // then do this thread's portion of the computation:
        for (i = 0;  i < count;  ++i) {

            double x = (double)omp_rand(&seed) / OMP_RAND_MAX;
            double y = (double)omp_rand(&seed) / OMP_RAND_MAX;

            double val = x * x + y * y;
            in_circle +=  val < 1.0;
        }
    }
    return 4.0 * in_circle / total;
}

int main(int argc, char const *argv[])
{
    int num_threads = 1;

    if (argc > 1)
        num_threads = atoi(argv[1]);

    omp_set_num_threads(num_threads);

    float pi_approx = calculate_in_circle_random_count();

    printf("Pi approximation: %.6f\n", pi_approx);

    return 0;
}

With this modification, the code is at least capable of scaling. To get it to scale very well, you'd need to change your total to a rather larger number though--with it as small as you've specified, it takes longer to start up multiple threads than it saves in calculation. But at least this code can scale well, so if we make total quite a bit larger, it really will run faster. For timing, I added a few more zeros to total, and rewrote main a bit, to create a loop to use 1, 2, 3, and 4 threads and print out the time each iteration. On my machine, this produced the following:
With 1 threads: Pi approximation: 3.140259, time: 3,652,683 microseconds
With 2 threads: Pi approximation: 3.139389, time: 1,892,415 microseconds
With 3 threads: Pi approximation: 3.138885, time: 1,268,917 microseconds
With 4 threads: Pi approximation: 3.138306, time:   935,579 microseconds

So with this, 4 threads is at least close to 4 times as fast as one thread. I'm pretty sure if you use rand inside the loop, you'll never get it to scale well at all.
For anybody who cares, the version of main that produces that output is written in C++, and looks like this:
int main(int argc, char const* argv[]) {
    using namespace std::chrono;

    std::cout.imbue(std::locale(""));

    int processors = omp_get_num_procs();

    for (int num_threads = 1; num_threads <= processors; num_threads++) {
        std::cout << "With " << std::setw(2) << num_threads << " threads: ";
        omp_set_num_threads(num_threads);

        auto start = high_resolution_clock::now();
        float pi_approx = calculate_in_circle_random_count();
        auto stop = high_resolution_clock::now();

        printf(" %.6f, time: ", pi_approx);
        std::cout << std::setw(9) << duration_cast<microseconds>(stop - start).count() << " microseconds\n";
    }
    return 0;
}

This remains pretty much the same, but with some timing code hacked in. In particular, it's not an attempt at rewriting the code in C++ in general. If I were doing that, I'd probably do a number of things rather differently (starting with the fact that the C++ <random> header already provides a clean way to handle per-thread random number generation, so I'd use that instead of rolling my own).


MySQL query: blog entry has comments or not

UPDATE: Ah...I've reread your original query. When I first read it, I thought that you were only retrieving this for a single blog, but now I see that you're retrieving for every blog record.

This might be inefficient, though I'm not sure.  I suppose it depends on how good MySQL is at dealing with that subquery.

Below is probably the most straightforward approach:

SELECT
    blogs.blog_id,
    COUNT(comments.blog_id)
FROM blogs
LEFT OUTER JOIN comments on
    comments.blog_id = blogs.blog_id
GROUP BY
    blogs.blog_id

Of course, this gives you a count, which is more information that was asked for, but this will probably be pretty efficient if you have an index on blog_id.

Another alternative is to union together a result of the  blogs that have comments with another result of the blogs that don't have comments.

SELECT blog_id, true
FROM blogs
WHERE
    EXISTS (
        SELECT true
        FROM comments
        WHERE
            comments.blog_id = blogs.blog_id
    )

UNION ALL

SELECT blog_id, false
FROM blogs
WHERE
    NOT EXISTS (
        SELECT true
        FROM comments
        WHERE
            comments.blog_id = blogs.blog_id
    )


Beginner's Implementation of Guess The Word

Overall the code looks really nice. I like the separation with a separate Difficulty type instead of doing the parsing directly in fetchWords.
Bugs
I have found three bugs:
Crash on invalid user input
If a user enters a number that is larger than the number of characters in the string, the program will crash. This is because you use the partial1 function (!!) without verifying its precondition that for xs !! i, i >= 0 and i < length xs. This could also be solved if you used a non-partial version of the function which returns a Maybe value so you can display a better error to the user and ask them to retry.
Random crash every 3:rd execution
There is also an off-by-one error in generateSecret, since randomRs generates an inclusive range and length xs is not a valid index for xs. This will cause the program to crash randomly on average once every length (fetchWords difficulty) + 1 times you play.
Only one random number
Speaking of randomness: the randomNumber function calls getStdGen, which
doesn't update the RNG state, it just fetches it. This means that all random numbers will be the same. To make it update the state, you can either use randomRIO which will update the global RNG state automatically, or use newStdGen which will split the RNG state to allow you to generate random numbers from pure code. In this code you don't notice it though, since you only generate a single number.
The randomNumber function can be fixed by simplifying it to
randomNumber :: Int -> Int -> IO Int
randomNumber begin end = randomRIO (begin, end)

Idiomatic code
Partial functions
You use partial functions in a couple of places. Many of them can be avoided by using the principle "Parse, don't validate". In this case, all the "isX" functions can be replaced with getX functions that try to parse the data and Maybe returns a parsed value. The createDifficulty function is already such a function. This guarantees that the validation actually matches the code that uses it.
Here's an example of how it could be done. I have only included the relevant functions here. The index is validated, but there is no easy way to tell which list it is a valid index for unless you use some advanced trickery2.
import Text.Read (readMaybe)

newtype ValidIndex = ValidIndex Int

createDifficulty :: String -> Maybe Difficulty
createDifficulty s = lookup s [
    ("e", Easy),
    ("m", Medium),
    ("h", Hard),
    ("", Easy)
    ]

getInt :: String -> Maybe Int
getInt = readMaybe

isValidIndex :: [a] -> Int -> Bool
isValidIndex list idx = idx >= 0 && idx < length list

getValidIndex :: [a] -> String -> Maybe ValidIndex
getValidIndex list str = do
  idx <- getInt
  guard $ isValidIndex list idx
  return $ ValidIndex idx

getChar :: String -> Maybe Char
getChar [c] | isAlpha c = Just c
getChar []  = Nothing

promptUntil :: (String -> Maybe a) -> String -> String -> IO a
promptUntil parser prompt failureMessage = do
    putStr (prompt ++ "\n> ")
    input <- getLine
    case parser input of
      Just result -> return result
      Nothing -> do
        putStrLn $ input ++ failureMessage
        promptUntil parser prompt failure

loop :: String -> String -> IO ()
loop secret guess = do

    putStrLn guess

    pos <- promptUntil (getValidIndex secret) "Enter position:" " is not a valid index."
    c <- promptUntil getChar "Enter character:" " is not a character."

    let result = compareSecret secret guess pos c
    if result /= secret then
        loop secret result
    else
        return ()

main = do
    putStrLn "\n Welcome to Guess The Word!\n"

    difficulty <- promptUntil createDifficulty "Enter difficulty level [e/m/h] or leave empty for easy difficulty: "
        " is not a valid difficulty."

    putStrLn $ show difficulty ++ " difficulty selected."

    secret <- generateSecret difficulty

    loop secret $ replicate (length secret) '-'

    putStrLn secret
    putStrLn "You win!"

-- These functions are still partial, but we have checked their preconditions.
replaceChar :: ValidIndex -> String -> Char -> String
replaceChar (ValidIndex n) s c = pre ++ [c] ++ tail post
    where (pre, post) = splitAt n s

compareSecret :: String -> String -> ValidIndex -> Char -> String
compareSecret secret guess pos@(ValidIndex i) c =
    if secret !! i == c then
        replaceChar pos guess c
    else
        guess

Separating business logic from generic combinators
There are some cases where you can separate the code that is specific
to your application from generic code that could be used anywhere.
For example, the generateSecret function can be split into a pickOne function:
pickOne :: [a] -> IO a
pickOne [] = error "pickOne: Empty list"
pickOne xs = do
    num <- randomRIO (0, length xs - 1)
    return $ xs !! num

generateSecret :: Difficulty -> IO (String)
generateSecret = pickOne . fetchWords

As you can see, the function is still partial, but since the word list is hard coded, we can probably assume that there is at least one word for each difficulty.
Explicit import lists
The recommended way of handling imports is to either use a qualified import like this:
import qualified Data.Char as Char

example = Char.isDigit '2'

or use an explicit import list like this
import Data.Char (isDigit)

example = isDigit '2'

This makes it easier for readers to see where functions come from.
Performance
Since all strings and lists are really short in this example, performance will not really be an issue. However, if the strings or lists were a lot longer, there are a few things to note. All functions that work with an index into a list are O(n) (instead of the O(1) they would be if we were working with a mutable array).
Haskell has support for mutable vectors, but then you lose the purity that is so nice about Haskell. If you want to keep purity, you can use a Data.Map, which has O(n*log n) complexity, but at the cost of a O(n*log n) memory cost. You could also use Data.Text, which still has O(n) complexity, but has a much more compact representation and is faster overall.
Anyways, as I said, this is not really relevant for this program since n (the length of the lists/strings) is really small and will probably never be large.

A partial function is any function that can crash
For example using Liquid Haskell or by using some fancy type-level trickery where the length of the list is in its type


Cygal's answer covers style, but you also asked for optimisation so here goes.

Your divisorCount can be a lot more efficient. The number of divisors can be calculated cia the following formula:

d(n) = prod((k + 1)) for a^k in the prime factorisation of n

For example, consider the prime factorisation of 360:

360 = 2^3 * 3^2 * 5^1

The exponents in the prime factorisation are 3, 2, and 1, so:

d(360) = (3 + 1) * (2 + 1) * (1 + 1)
       = 24

Note that 360 indeed has 24 factors: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360].

Combine this with the fact that a number n can have at most one prime factor greater than sqrt(n), and you get something like the following:

# Calculates the number of positive integer divisors of n, including 1 and n
def d(n):
    divisors = 1
    stop = math.sqrt(n)

    primes = # Calculate prime numbers up to sqrt(n) in ascending order
    for prime in primes:
        if prime > stop:
            break

        exponent = 0
        while n % prime == 0:
            n /= prime
            exponent += 1

        if a != 0:
            divisors *= (a + 1)
            stop = max(stop, n)

    # At this point, n will either be 1 or the only prime factor of n > root
    # in the later case, we have (n^1) as a factor so multiply divisors by (1 + 1)
    if n > root:
        divisors *= 2

    return divisors

Since you are going to be calling this function many times consecutively, it makes sense to pre-calculate a list of primes and pass it to the divisor function rather than calculating it each time. One simple and efficient method is the Sieve of Eratosthanes which can be implemented very easily:

# Compute all prime numbers less than k using the Sieve of Eratosthanes
def sieve(k):
    s = set(range(3, k, 2))
    s.add(2)

    for i in range(3, k, 2):
        if i in s:
            for j in range(i ** 2, k, i * 2):
                s.discard(j)

    return sorted(s)

This function can also fairly easily be modified to compute a range in pieces, e.g. to calculate the primes to 1M and then to 2M without recalculating the first 1M.

Putting this together your main loop will then look something like this:

primes = [2, 3, 5]
triangularNumber = 0
increment = 1
maxDivisors = 0
while maxDivisors < 500:
    triangularNumber += increment
    increment += 1

    if math.sqrt(triangularNumber) > primes[-1]:
       primes = sieve(primes, primes[-1] * 4)

    divisors = d(triangularNumber, primes)
    maxDivisors = max(divisors, maxDivisors)

print triangularNumber, "has", maxDivisors, "divisors."

As far as performance goes, here are the triangular numbers with the largest number of divisors and the times (in seconds) taken to get there (py1 is your code, py2 is using primes, c++ is the same as py2 but in c++):

TriNum      Value     d(n)  py1  py2  c++
 12375      76576500   576    0    0    0
 14399     103672800   648    0    0    0
 21735     236215980   768    1    0    0
 41040     842161320  1024    4    0    0
 78624    3090906000  1280  128   13    9
 98175    4819214400  1344  350   23   15
123200    7589181600  1512  702   38   23
126224    7966312200  1536  749   41   24
165375   13674528000  1728   -    74   42
201824   20366564400  1920   -   107   61
313599   49172323200  2304   -   633  153
395199   78091322400  2880   -   790  259
453375  102774672000  3072   -   910  358

There are probably other optimisations you can make based on the properties of triangular numbers, but I don't know the math. :)


A few points that nearly jump out at me:

You've implemented it as a linked list of individually allocated nodes. This nearly guarantees poor locality of reference and for small types wastes quite a bit of space.
Your destructor leaks memory:

template <typename T>
queue<T>::~queue() {
    node *curr = new node();
    while(head) {
        curr = head;

This allocates a node (not clear why you'd want to allocate a node in the dtor, but there it is), then if head != nullptr, it overwrites that pointer with head, thus leaking the node it just allocated (and if that condition isn't met, it just flows off the end without doing any more with curr, also leaking the memory).
Your node type takes for granted that a T can be initialized from 0:

node()
    : data(0)

For a generic type, this assumption is unwarranted. You typically want to use T() to create a value-initialized object, which will be 0 for arithmetic types, a null pointer for a pointer type, an empty string for a string type, and so on.


In addition to Janos's answer.

You're truncating the color value too early here:

  c.a = c1.a * (w + h - i - j) / (w + h) + c2.a * (i + j) / (w + h);

This results in a rounding error on each channel. Also this forces the compiler to perform two divisions per channel, as it cannot combine the divisions due to truncation rules of integer types.

For example:

int a = 1;
int b = 2;
int c = 3;

int result = a / c + b / c;

The result must be calculated as (a/c) + (b/c)=0 if optimized to (a+b)/c=1 the result will differ. And in your case you actually want (a+b)/c as the correct answer.

In your case you should do:

SDL_Surface* DrawDescendingDiagonalGradient(SDL_Color& c1, SDL_Color& c2, int w, int h){
    SDL_Color c;
    SDL_Surface *s = SDL_CreateRGBSurface(0, w, h, 32, 0, 0, 0, 0);
    SDL_LockSurface(s);
    int wh = w + h;
    for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
            int ij = i + j;
            c.a = (c1.a * (wh - ij) + c2.a * ij) / wh;
            c.r = (c1.r * (wh - ij) + c2.r * ij) / wh;
            c.g = (c1.g * (wh - ij) + c2.g * ij) / wh;
            c.b = (c1.b * (wh - ij) + c2.b * ij) / wh;
            PutPixel32(s, i, j, SDL_MapRGBA(s->format, c.r, c.g, c.b, c.a));
        }
    }
    SDL_UnlockSurface(s);
    return s;
}

This will make sure you get the correct rounding and remove one division per channel. Also when running the code un-optimized (while debugging) this should perform slightly better due to elimination of some subexpressions.


Optimizing nested loop for calculating geodesic distance

I'll first go through the different section and outline possible improvements, then give some general comments at the end. I am not checking the algorithm for correctness, as I don't know it.

Img=imread('input.jpg');
[rows, columns, numberOfColorChannels] = size(Img);
[L,N] = superpixels(Img,250);

%Identifying neighborhood relationships
glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset',  [0,1;1,0]); %Create gray-level co-occurrence matrix from image
glcms = sum(glcms,3);    % add together the two matrices
glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric
glcms(1:N+1:end) = 0;    % set the diagonal to zero, we don't want to see "1 is neighbor of 1"

You need to have defined idx by now, but you haven't, so the code doesn't run. Based on the superpixels documentation, you need to add idx = label2idx(L);

data = zeros(N,3);
for labelVal = 1:N
    redIdx = idx{labelVal};
    greenIdx = idx{labelVal}+numRows*numCols;
    blueIdx = idx{labelVal}+2*numRows*numCols;
    data(labelVal,1) = mean(Img(redIdx));
    data(labelVal,2) = mean(Img(greenIdx));
    data(labelVal,3) = mean(Img(blueIdx));
end

This is fine, it probably is fine to just write data(labelVal,1) = mean(Img(idx{1:N})), etc. but the performance should be similar.

Euc = zeros(N);
% Euclidean Distance
for i=1:N
    for j=1:N
        if glcms(i,j)~=0
            Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2));
        end
    end
end

This can be replaced by Euc = pdist2(data,data).*(glcms~=0);

W=zeros(N);
W_num=zeros(N);

W_den=zeros(N);
OMG1=0.1;
for i=1:N
    for j=1:N
        if(Euc(i,j)~=0)
         W_num(i,j)=exp(-OMG1*(Euc(i,j)));
         W_den(i,i)=W_num(i,j)+W_den(i,i);
        end
    end
end

This can be replaced by W_num = exp(-OMG1*Euc).*(Euc~=0); and W_den = sum(W_num); (here W_den is a vector, not a matrix, but that's what you want because you were only using diagonal elements of your W_den matrix).

for i=1:N
    for j=1:N
         if(Euc(i,j)~=0)
             W(i,j)=(W_num(i,j))/(W_den(i,i));   % Connectivity Matrix W
         end
    end
end

This can be replace by W = W_num./W_den.'; and W(isnan(W)) = 0;.

s_star_temp=zeros(N);   %temporary variable for geodesic distance measurement
W_sparse=zeros(N);
W_sparse=sparse(W);
for i=1:N
    for j=1:N
        if W(i,j)==0 & i~=j;
            s_star_temp(i,j)=graphshortestpath(W_sparse,i,j); % Geodesic Distance
        end
    end
end

Here you define W_sparse twice, you don't need to initialise it with zeros(N). This part is finding all shortest paths, and there is a builtin for that (which is probably a lot more efficient that generating the paths independently). Replace this whole section with s_star_temp = graphallshortestpaths(W).*(W==0); This seems to speed it up from ~15 seconds to 0.005 seconds.

So this is how I would write your algorithm

Img = imread('input.jpg');
[rows, columns, numberOfColorChannels] = size(Img);
[L,N] = superpixels(Img,250);

idx = label2idx(L);

%Identifying neighborhood relationships
glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset',  [0,1;1,0]); %Create gray-level co-occurrence matrix from image
glcms = sum(glcms,3);    % add together the two matrices
glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric
glcms(1:N+1:end) = 0;    % set the diagonal to zero, we don't want to see "1 is neighbor of 1"

data = zeros(N,3);
for labelVal = 1:N
    data(labelVal,1) = mean(Img(idx{labelVal}));
    data(labelVal,2) = mean(Img(idx{labelVal}+rows*columns));
    data(labelVal,3) = mean(Img(idx{labelVal}+2*rows*columns));
end

Euc = sparse(pdist2(data,data).*(glcms~=0));

OMG1 = 0.1;

W_num = exp(-OMG1*Euc).*(Euc~=0);
W_den = sum(W_num);

W = W_num./W_den.';
W(isnan(W)) = 0;

s_star_temp = graphallshortestpaths(W).*(W==0);

Notice that I made Euc a sparse matrix. This makes the resulting matrices (W_num, W_den, W) also sparse. Your original code left them as full matrices, which was unnecessary. This code runs in about 1.3 seconds on my machine, compared to about 16 for your original code (with the picture I used).

Minor general comments on your code:

Use spaces around your = signs, it makes things easier to read
Try to avoid very long lines, for example the graycomatrix line with its comment will go over the end of the window and be lost
Write more comments
Matlab best practice is to avoid using i and j for loop variables, prefer ii and jj. It's not very important, but i and j can also mean the imaginary unit.


Showing a certain screen depending on a particular status

if Preferences.getDeviceIsActive() == true {
    // Checks if deviceIsActive flag is true.
    redirectToView(.LoginScreen)
} else {
    // If there is not deviceID, generate one.
    if Preferences.getDeviceID() == nil {
        var deviceID = NSUUID.UUID().UUIDString
        deviceID = deviceID.stringByReplacingOccurrencesOfString("-", withString: "") // e,g: 70788AEB8586513C46B0599AEA4F82BF
        Preferences.setDeviceID(deviceID)

        // Send the ID to the backend to check.
        register()
    } else {
        // If there is a deviceID already, still send it to the server to check and make sure.
        register()
    }
}

This seems to be the chunk of code you're primarily concerned with, so it's where I'll focus on for now.

First, == true is basically always redundant.  Our first if could simply be:

if Preferences.getDeviceIsActive() {

If the nested else were truly necessary, I'd recommend unnesting the nested if else and turning this into an if else if else, but the nested else is unnecessary.  We're calling register() unconditionally inside the else.  We can just write:

if Preferences.getDeviceID() == nil {
    var deviceID = NSUUID.UUID().UUIDString
    deviceID = deviceID.stringByReplacingOccurrencesOfString("-", withString: "")
    Preferences.setDeviceID(deviceID)
}

register()

api.registerDevice()

You haven't included any details about what API is or what the registerDevice method does specifically, but it looks like it most likely is asynchronous, and it probably calls to a web service of some sort.

This sort of logic would be fine in say a standard view controller that loads after your app delegate was finished.  But we don't know how long we may be waiting for this return.

If the call is asynchronous, then your application(application:, didFinishLaunchingWithOptions launchOptions:) -> Bool will most likely return before we figure out where to navigate to.  Best case scenario, your project is set up to have a root view controller via the storyboard without the redirectToView method being called and it just looks a little weird when it then later redirects you.  Worst case scenario, you don't have a default view controller set up and we have to rely on redirectToView which means we may sometimes not have a view before we're done with the didFinishLaunchingWithOptions returns and the app will crash.

And heaven forbid this line of code ever get called without a default view already in place:

default:
    println("No view controller specified")

Because this might also leave the window without a view, which again, is a crash.

If the call is synchronous, now we're causing the didFinishLaunching to hang out for an unnecessarily long amount of time because we're performing network operations when we're supposed to be loading up resources and initializing our app.

Ultimately the best solution to this is to move this sort of logic into a base view controller.  For now, let's call it the "Home" view controller.  Our app will be set up to always load to "Home".  We want to have somewhere to go to in order to get out of didFinishLaunchingWithOptions as quickly as possible.

Once we're at "Home", now we perform the logic for determining whether we need to login or activate.

Or perhaps, given that the activation is a one-time process, perhaps we should default to the login screen.  The login screen can check if the device is activated or not.  If it determines it's not activated, we can give the user a pop up.  "This device is not activated.  Would you like to activate it now?" and answering yes to this pop up takes us to the activation screen.


I was asked by @Timtech to join + post an improvement. Using arrays is a lot easier to understand, and there were so many optimizations that I decided to completely re-write the code. I'm sure it could be improved by other advanced programmers like me, as I'm using several long expressions here... note that L1 represents list #1 (2nd + 1 on the calculator) and ~ is the negative token.

:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER
:DelVar IInput Str1
:DelVar L1~{2,2,2,2→L1
:While I<length(Str1
:I+1→I
:sub(Str1,I,1→Str2
:(Str2="I")-(Str2="D
:Ans+L1(4→L1(4
:If Str2="S
:L1(4)²→L1(4
:If Str2="P
:Then
:L1(1
:If 2+Ans
:Disp Ans
:ΔList(cumSum(L1->L1
:0->L1(4
:End
:L1(4
:If Ans=256 or Ans<0
:0->L1(4
:End

Improvements

Saved bytes by removing several unneeded ending parentheses and quotes
Used DelVar since it does not need a following colon
Used an array instead of four variables
Used a complex expression :(Str2="I")-(Str2="D saved to Ans to save space
Used ΔList(cumSum(L1->L1 to get L1 minus its first element
Several others I'm not listing due to their minisculity; mainly using Ans to save space and speed