Apply additions on a base array based on date ranges

To preface, PEP8 recommends 4 spaces instead of 2 spaces for indentation, so I've written all below code as such.

There is a subtle bug in your program (and may be nonexistent at all, the requirements are ambiguous here), but:

if elem['date'] < mod_arr[mod_index]['date']:
    elem['value'] += mod_arr[mod_index]['value']
else:
    elem['value'] += mod_arr[mod_index + 1]['value']
    mod_index += 1

assumes that mod_array[mod_index + 1]["date"] > mod_array[mod_index]["date"], though your requirements never say that "date" is strictly increasing (and mod_array being sorted doesn't imply this).

We can handle this by changing the if / else to a while:

while elem['date'] >= mod_arr[mod_index]['date']:
    mod_index += 1

elem['value'] += mod_arr[mod_index]['value']

Note that this also increments mod_index before the mutation of elem["value"], allowing us to de-duplicate its mutation.

Since we are only moving forward in mod_arr, we actually don't need mod_index at all. We can do mod_array_iter = iter(mod_array), and replace mod_index += 1 with mod = next(mod_array_iter). This also helps us avoid any off-by-one errors.

Another benefit of using iter here is it opens up an easy way to exit the function if mod_array is empty (implying no mutations to base_arr should be done, the original program didn't account for this) or if we've traversed through all of mod_array_iter (implying necessary mutations to base_arr have been done, original program accounted for this with the if and inner break). We can use a try / except for both of those cases, and get rid of the initial if with inner break.

Final code ends up looking like (wrapped is a function for reusability):

def mutate_base_arr(base_arr, mod_arr):
    mod_arr_iter = iter(mod_arr)

    try:
        mod = next(mod_arr_iter)

        for elem in base_arr:
            while elem['date'] >= mod['date']:
                mod = next(mod_arr_iter)

            elem['value'] += mod['value']
    except StopIteration:
        return

If you really wanted to take this a step further, you could get rid of the while and duplicate nexts by using itertools, yielding this version of the function:

def mutate_base_arr(base_arr, mod_arr):
    mod_arr_iter = iter(mod_arr)

    try:
        for elem in base_arr:
            valid_mod = next(mod for mod in mod_arr_iter if elem["date"] < mod["date"])
            mod_arr_iter = itertools.chain([valid_mod], mod_arr_iter)

            elem['value'] += valid_mod['value']
    except StopIteration:
        return

Though I'm not sure if I'd recommend this, as having to prepend valid_mod with mod_arr_iter each iteration so it can be re-checked next iteration of the for is a bit unusual.


Modeling and computing intersection between continuous intervals

Review

You are constrained to float which makes your class only usable for a limited number of scenarios. I would like to be able to work with int, double, DateTime, MyCustomEntity, ..
You should not need to care about special cases as unbounded or NaN. NaN should be filtered out beforehand, since it is unusable for comparison. Unbounded and bounded values should be compared by using the built-in interface IComparable.
Intersection of continuous data when 2 edges match requires both edges to be IsInclusive in your specification. I would argue that only one of them should require this flag. Adjacent items that meet each other form an intersection ( [source required] ).
Your struct is immutable, which is proper design. Whether or not to make a class instead, depends on how you would like to use this. I tend to prefer class more than struct. Note that a struct has an inherent default value, while a reference type is null by default. How would you distinguish a default value from a value that happens to have the same value? This is one reason to go with a class, unless you cope with this issue by using a Nullable<T> and accepting the overhead it provides.
It is good practice to override GetHashCode() and Equals().

Suggestions

1201ProgramAlarm's answer suggests to use IComparable on DimensionBound, but I would use it on the generic type parameter.

public class DimensionBound<T> where T : IComparable<T>
{
    public readonly T Value;
    public readonly bool IsInclusive;

    public DimensionBound(T value, bool isInclusive)
    {
        Value = value;
        IsInclusive = isInclusive;
    }
}

The interval could then be refactored to compare the values. Note that I would provide a convenience constructor accepting an inclusive start and exclusive end (which is considered common practice when dealing with continuous data).

I would also favour instance methods over the static comparison. Furthermore, I would argue the purpose of the dimension in this class. I would remove it and call the class Interval. You can always create an additional class or use a tuple (int, Interval) to include the dimension.

public sealed class Interval<T> where T : IComparable<T>
{
    public readonly DimensionBound<T> Start;
    public readonly DimensionBound<T> End;

    public Interval(T start, T end)
        : this(ew DimensionBound<T>(start, true), new DimensionBound<T>(end, false))
    {
    }

    public Interval(DimensionBound<T> start, DimensionBound<T> end)
    {
        Start = start;
        End = end;
    }

    public bool Contains(T value)
    {
        // method body ..
    }

    public bool Intersects(Interval<T> other)
    {
        // method body ..
    }
}

If we don't change your specification and require both edges to be inclusive when 2 intervals meet, we could implement Intersects (Contains is similar) as follows (comments added for code review purposes only):

public bool Intersects(Interval<T> other)
{
    // compare start to other end
    var compareToStart = Start.Value.CompareTo(other.End.Value);

    // no intersection possible; instance starts after other is finished
    if (compareToStart == 1) return false;

    // both intervals meet but at least one of the bounds is exclusive, so no intersection
    if (compareToStart == 0 && !(Start.IsInclusive && other.End.IsInclusive)) return false;

    // compare end to other start
    var compareToEnd = End.Value.CompareTo(other.Start.Value);

    // no intersection possible; instance finishes before other is started
    if (compareToEnd == -1) return false;

    // both intervals meet but at least one of the bounds is exclusive, so no intersection
    if (compareToEnd == 0 && !(End.IsInclusive && other.Start.IsInclusive)) return false;

    return true;
}

This works with float, or any other IComparable<T>.

Assert.IsTrue(new Interval<float>(0, 1).Intersects(new Interval<float>(0.5f, 1.5f));


All the caesar cypher does is rotate an alphabet by n places. If we let the alphabet be an Array, we can use Array#rotate to do the rotating for us. To substitute single characters, there is String#tr. Its name and usage are a little odd, but you'll quickly get used to it.

Basically, it maps characters in a String to characters in another String by their index. So "abc".tr("abc", "123") maps "a" to "1", "b" to "2" and "c" to "3".It expands ranges such as "a-c" first, so you can can write "abc".tr("abc", "123") as "abc".tr("a-c","1-3").

Though the interface is different, here's a simple implementation of the Caesar cypher.

module Caesar
  def self.encrypt(message, shift = 3)
    message.tr("a-zA-Z", rotated_alphabet(shift))
  end

  def self.decrypt(message, shift = 3)
    encrypt(message, 26 - shift)
  end

  def self.rotated_alphabet(shift)
    lower = "a".upto("z").to_a.rotate(shift)
    upper = "A".upto("Z").to_a.rotate(shift)

    lower.concat(upper).join
  end
end

Caesar.decrypt Caesar.encrypt("hi")
# => "hi"

For efficiency, you could change how you calculate the rotated alphabets. Here's an efficient, but not exactly a readable implementation.

  def self.rotated_alphabet(shift)
    lower = (97 + shift).chr # 97 is the ASCII code for "a"
    upper = (65 + shift).chr # 65 is the ASCII code for "A"

    "#{lower}-za-#{lower}#{upper}-ZA-#{upper}"
  end


Parsing numbers from equations into strings

Without changing things too much...

You need some #includes.
Don't use using namespace. One of the issues is knowing where a function comes from (which one is being used) - this hides it. Using a short std:: gains you a lot in understandability. You can do using std::string which is better, but imo even that isn't worth it.
You might as well put printHelp before main rather than after, that way you don't have to declare it.  And it's not used currently anyway.
Matrix also isn't used.
Having an Equation class doesn't make sense for what you're (currently) using it for. You might as well just have a naked function.
You don't allow for the possibility that firstx may be invalid, ie there are no x in the equation. This may be a given, of course. And for that matter, that the x^2 term will be first!
If secondx is invalid, skip over processing it.
Multiple breaks in while loops should be avoided, for readability. This (first) loop probably should be split off into another function since it's used twice, together with the following section.
I'm a little nervous of int startloc = firstx - 1;, since firstx is unsigned and startloc isn't. I'd cast firstx to an int first if I were using it like this.
Consider using std::string::find_last_of and std::string::substr. They'll simplify the code somewhat.
Check that you don't lose a negative coefficient.


This isn't mergesort! sort' is a different sorting algorithm entirely, so you end up only performing one merge step before kicking it over to (I believe) selection sort.

First let's address the easy stylistic issues so we have a good base to work from. The primary issue is that the argument passed to merge' is a tuple, which is unnecessary, uncurried, and not very Haskell-y. I'll also drop the extra apostrophes where there isn't an actual naming conflict with the Prelude. We use as-patterns to avoid reconstructing patterns we just deconstructed. And let's just toss sort' and filterOne', they're not part of the solution!

mergesort :: (Ord a) => [a] -> [a]
mergesort []     = []
mergesort xs     = merge (??? left) (??? right)
    where half = (length xs) `div` 2
          left  = take half xs
          right = drop half xs

merge :: (Ord a) => [a] -> [a] -> [a]
merge [] []                 = []
merge xs []                 = xs
merge [] ys                 = ys
merge xss@(x:xs) yss@(y:ys) = if x <= y then x : merge xs yss else y : merge xss ys
                                 -- ^ Less than *or equal* so our sort is stable

One question is what goes in for the ??? where we used to call sort'? Well, mergesort!

One more complex issue of style is the usage of if in merge. Top-level ifs are better represented as guards in Haskell, it's easier to extend guards and their usage is more idiomatic.

merge xss@(x:xs) yss@(y:ys) | x <= y    = x : merge xs yss
                            | otherwise = y : merge xss ys

One small change we can make is adding another base case to mergesort to account for lists of length 1, which are by definition sorted.

mergesort xs@[x] = xs

There's only one more improvement I'd make to this, and that's to call splitAt rather than take and drop in mergesort. Using both take and drop leads to walking half the list twice in each recursive step where we can walk it only once by doing some more bookkeeping. splitAt takes an index to split a list at, and returns the prefix and remainder just like using take and drop separately would.

So putting all of that together, here's the final version.

mergesort :: (Ord a) => [a] -> [a]
mergesort []     = []
mergesort xs@[x] = xs
mergesort xs     = merge (mergesort left) (mergesort right)
    where half = (length xs) `div` 2
          (left, right) = splitAt half xs

merge :: (Ord a) => [a] -> [a] -> [a]
merge [] []                 = []
merge xs []                 = xs
merge [] ys                 = ys
merge xss@(x:xs) yss@(y:ys) | x <= y    = x : merge xs yss
                            | otherwise = y : merge xss ys


Class that only creates an instance of a new game

Being pedantic about the terminology: Not the class, but the IDE, complains about the unused value. As hinted by markspace, I agree that first creating an instance of the game and then starting it is the natural way to think about it. Don't add to many side effects to the constructor that the user might not expect.

To get rid of the warning about the unused value, don't assign the instance to a variable. Just do new Game() or new Game().start().

Here is my recommendation, with fixed formatting and changed class name (since RunGame sounds like a method name). I also removed the constructor from the main class; I don't think you need it, since main() is static.

public final class Main
{
    public static void main(String[] args) {
        new Game().start();
    }
}


I think I would replace { resize: [1200, 1200] } with { operation: 'resize', parameters: [1200, 1200] }. This is more verbose, but easier to maintain/read. This way it's eligible for extension (maybe you want to add identifiers later?). The same can be done for the tasks.

Other than that there's not a lot to say. I find the indentation not easily readable, but that's just style. I'd prefer:

[
    {
        name: "I'm task one",
        operations: [
            {
                operation: "resize",
                parameters: [1200, 1200]
            },
            {
                operation: "moveTo",
                parameters: ["dest/nick"]
            },
            {
                operation: "rename"
                parameters: ["{base}-12.{ext}"]
            },
            {
                operation: "toWeb",
                parameters: [true]
            },
            {
                operation: "rename",
                parameters: ["{base}.{ext}"]
            }
        ]
    },
    {
        name: "I'm task two",
        operations: [
            {
                operation: "resize",
                parameters: [1000, 1000]
            },
            {
                operation: "rename",
                parameters: ["{base}-10.{ext}"]
            }
        ]
    }
]

Also note that the value of the parameters is an array, even if it has one value.


No need for stack

You've complicated things by constructing a stack for no reason.  All you need to remember is the last character.  For example:

private static int countChanges(String text) {
    char prev  = 0;
    int  count = 0;

    for (char c : text.toCharArray()) {
        if (c == prev) {
            count++;
        } else {
            prev = c;
        }
    }
    return count;
}

Misleading comment

This comment:

            // top >= 0 or c == chars[top]

should read:

            // top >= 0 and c == chars[top]


Redundancy of both out parameter and return

    public static string TellMeWhatToSay(out string passTheQuote)
    {
        string whatIsWritten;
        Console.WriteLine("Tell Me What To Say");
        whatIsWritten = Console.ReadLine();
        passTheQuote = whatIsWritten;
        return passTheQuote;
    }

You both write the result to an out parameter and return it. A violation the DRY principle, this outputs the same information twice. As the out parameter does not feel appropriate for a modern language to me, I will leave only the return:

    public static string TellMeWhatToSay()
    {
        string whatIsWritten;
        Console.WriteLine("Tell Me What To Say");
        whatIsWritten = Console.ReadLine();
        passTheQuote = whatIsWritten;
        return passTheQuote;
    }

Now that we eliminated that redundancy, we can simplify by returning directly:

    public static string TellMeWhatToSay()
    {
        Console.WriteLine("Tell Me What To Say");
        return Console.ReadLine();
    }

Unecessary alias of a built-in Console.ReadLine

    public static void HelloWorld(string itWillBeSpoken)
    {
        Console.WriteLine(itWillBeSpoken);
    }

HelloWorld is the same as Console.WriteLine so there is no need to write it.


Vba to create a new column and insert array formula

Usually with mass-Formula, I would recommend judicious use of the Application.Calculation property to ensure that you don't recalculate for every cell (3773 times in your example!) - but, in this case I am also going to recommend using the Range.FillDown method instead of assigning the Array Formula to every cell in the range.

(Also the MODE function is only included for Legacy Support, and has been replaced by the MODE.SNGL and MODE.MULT functions)

Application.Calculation = xlCalculationManual 'Do not recalculate formula until we say so!
With ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))
       .Cells(1,1).FormulaArray = "=IFERROR(MODE.SNGL(IF($M2=AllSites,$L$2:$L$" & LastRow & ")),""N/A"")" 'Set the Array Formula for the first cell
       '.Cells(1,1).FormulaArray = "=IFERROR(MODE.SNGL(IF(RC[-2]=AllSites,R2C12:R" & LastRow & "C12)),""N/A"")"'In R1C1 Notation
       .FillDown 'Copy the Array Formula down to the end
End With
Application.Calculation = xlCalculationAutomatic 'Reset Calculation Mode

(For comparison - running your method on 99999 rows of junk data took me 105 seconds.  Using the .Filldown method on the same data took 29 seconds, and 99% of that was just waiting for Excel to finish calculating the Worksheet after the functions where in!)


Use the built in gcd

In Python 3, you can just do:

from math import gcd

Consider keeping with the standard library

Instead of using np.random.permutation, consider just using random.shuffle to generate a random permutation. Removes the numpy dependency altogether.

Just use # instead of """

Comments such as:

"""count how many times we have crossed (-1-ed) a number from p"""

Are usually used for docstrings, you are using them to elaborate on certain steps in an algorithm, I would use # for this.

Place the cycle decomposition into a function

The while loop introduces a lot of global variables and makes it hard to use, I would put the contents into a function. Also explain that this function displays a permutation as disjoint cycles.

Please use better names.

I'm still not sure what every variable does. Like why is p=list(range(10))? I would think p is short for permutation, but l seems to be what the actual permutation is. This program is really hard to understand simply because of your name choice.


Ruby if-statement, possible to shorten it further?

You could remove a little duplication like this:

@identification_type = if self.citizenship == 'ES'
  IDENTIFICATION_TYPES[0]
elsif self.country == 'ES'
  IDENTIFICATION_TYPES[1]
end


#include <mem.h> should be properly #include <string.h>. The former is non-standard.
I prefer avoiding the duplication inherent in forward-declarations, so would put the definition before first use.
Unless, of course, I'm writing a header-file.
Remember that your friendlyLookup() can fail. And test for that.
It's a bad idea to name the type in a sizeof like in *head = malloc(sizeof(struct bstNode));. Changing it to *head = malloc(sizeof **head); is more resilient to change, obviously correct, and even shorter.
There are a few viable strategies for handling failure:

Ignoring it and hoping the program will crash. Even for toy-programs, that's extremely bad form.
Deteting it and aborting the program with an error-message. Often acceptable when resources are exceeded.
Fixing the failure. Often not possible, or at least not at that place.
Reporting the failure to the caller and letting them deal with it. The preferred method, especially for library-code.

You are instead doing a mixture: Printing an error-message (part of option 2) and then pretending you succeeded. That's a really bad combo.
Learn to love the ternary operator condition ? true-case : false-case. It would often simplify your code.

Applying some of the above:

void die(char* msg) {
    fprintf(stderr, "%s", msg);
    abort();
}

void insert(struct bstNode **head, int val) {
    if(!*head) {
        *head = malloc(sizeof **head);
        if(!*head)
            die("malloc failed!");
        **head = (struct bstNode){.val = val};
        return;
    }
    insert(val < (*head)->val ? &(*head)->left : &(*head)->right, val);
}

if (head->left != NULL) is exactly the same as if (head->left).
In friendlyLookup() you are copying one of two string-literals into a (far too big) array, just to copy it again. Why? Use a pointer.

const char* resultString = result > -1 ? " is present in the bst\n" : " is not present in the bst\n";

Also, numberString is far too big, but whatever.
printAndCleanString is a curious name. If such a utility-function makes sense, it should be "free" instead of "clean".
If you want to output a string, don't give it as format-string to printf(), but as an argument. Make it:

printf("%s", string);


Iterators in JavaScript and remembering position

How about the following recursive approach

function link(list) {
    if(!list.length)
        return [];

    let [car, ...cdr] = list;
    return {
        car,
        cdr: link(cdr),
        [Symbol.iterator]: function*() {
            yield this;
            yield *this.cdr;
        }
    }
}

ls = link([1, 2, 3, 4])

for (let t of ls)
    console.log(t.car)


Getting the current timestamp and compute the timestamp difference in minutes

Note that none of these suggestions will have any significant impact on the performance of your application overall. Don't micro-optimize performance until you have known, tested bottlenecks.

The getTimestamp() method is noise. If all you care about is the current timestamp in milliseconds, use System.currentTimeMillis().

You can use a constant to store the number of milliseconds in a minute, potentially saving the multiplication. Even if the compiler optimizes the math away, it's easier to read.

A java.sql.Timestamp is a kind of java.util.Date, and the getTime() method is defined there. Your method should accept a java.util.Date to support more clients at no cost.

Your method is poorly named. Something like getMinutesSince() would be more readable. Likewise, there are better variable names than what you've selected.

Use final to indicate that variables won't be reassigned. That reduces the cognitive load on the reader.

You don't really need as many variables as you have. You might even be able to get away with none and still have a reasonably clear method.

If you were to use all my suggestions, your code might look more like:

private static final long MILLISECONDS_PER_MINUTE = 60 * 1000;

public static long getMinutesSince(final java.util.Date startTime) {
  final long millisecondsSinceStart =
      System.currentTimeMillis() - startTime.getTime();
  return millisecondsSinceStart / MILLISECONDS_PER_MINUTE;
}


Naming

Oh my, what would Mr.Maintainer think if he would inherit the code... single letter variable names, methodnames like fF. He would have a hard time to figure out what is happening.

So let us clean this a little bit

public int fF(int possiblePrime)
{
    int baseNumber = 2, v = 0;

    while (baseNumber < possiblePrime)
    {
        int exponent = possiblePrime - 1;
        v = operate(baseNumber, exponent, possiblePrime);
        if (v != 1)
            break;
        baseNumber++;
    }
    return baseNumber;
}

int operate(int baseNumber, int exponent, int divisor)
{
    if (exponent == 2)
        return (baseNumber * baseNumber) % divisor;
    return (exponent % 2 != 0) ? (baseNumber * operate(baseNumber, exponent - 1, divisor)) % divisor : (operate(baseNumber, exponent / 2, divisor) * operate(baseNumber, exponent / 2, divisor)) % divisor;
}

Style

As many will agree, using braces {}, for single if statements also, is a have to.So let us use them and also let us remove the tenary expression and add an int result which we will return

public int fF(int possiblePrime)
{
    int baseNumber = 2, v = 0;

    while (baseNumber < possiblePrime)
    {
        int exponent = possiblePrime - 1;
        v = operate(baseNumber, exponent, possiblePrime);
        if (v != 1)
        {
            break;
        }
        baseNumber++;
    }
    return baseNumber;
}

int operate(int baseNumber, int exponent, int divisor)
{
    int result = 0;
    if (exponent == 2)
    {
        result = (baseNumber * baseNumber) % divisor;
    }
    else if (exponent % 2 != 0)
    {
        result = (baseNumber * operate(baseNumber, exponent - 1, divisor)) % divisor;
    }
    else
    {
        result = (operate(baseNumber, exponent / 2, divisor) * operate(baseNumber, exponent / 2, divisor)) % divisor;
    }
    return result;
}

Refactoring

Now let us focus on operate()

What you are doing, is always calling number * number % divisor so let us extract this to a method

private int calculateProductModulo(int firstValue, int secondValue, int moduloNumber)
{
    return (firstValue * secondValue) % moduloNumber;
}

The operate() method now looks

int operate(int baseNumber, int exponent, int divisor)
{
    int result = 0;
    if (exponent == 2)
    {
        result = calculateProductModulo(baseNumber, baseNumber, divisor);
    }
    else if (exponent % 2 != 0)
    {
        result = calculateProductModulo(baseNumber, operate(baseNumber, exponent - 1, divisor), divisor);
    }
    else
    {
        result = calculateProductModulo(operate(baseNumber, exponent / 2, divisor), operate(baseNumber, exponent / 2, divisor), divisor);
    }
    return result;
}

If we now extract the recursive calls out of the call to calculateProductModulo() we will see clearly what you have stated in your answer

int operate(int baseNumber, int exponent, int divisor)
{
    int result = 0;
    if (exponent == 2)
    {
        result = calculateProductModulo(baseNumber, baseNumber, divisor);
    }
    else if (exponent % 2 != 0)
    {
        int recursiveResult = operate(baseNumber, exponent - 1, divisor);
        result = calculateProductModulo(baseNumber, recursiveResult, divisor);
    }
    else
    {
        int recursiveResult1 = operate(baseNumber, exponent / 2, divisor);
        int recursiveResult2 = operate(baseNumber, exponent / 2, divisor);
        result = calculateProductModulo(recursiveResult1, recursiveResult2, divisor);
    }
    return result;
}

The code is calling 2 times the same method with the same arguements.

Let us eleminate the double calling

int operate(int baseNumber, int exponent, int divisor)
{
    int result = 0;
    int recursiveResult = 0
    if (exponent == 2)
    {
        result = calculateProductModulo(baseNumber, baseNumber, divisor);
    }
    else if (exponent % 2 != 0)
    {
        recursiveResult = operate(baseNumber, exponent - 1, divisor);
        result = calculateProductModulo(baseNumber, recursiveResult, divisor);
    }
    else
    {
        recursiveResult = operate(baseNumber, exponent / 2, divisor);
        result = calculateProductModulo(recursiveResult , recursiveResult , divisor);
    }
    return result;
}


Your code seems fine. However, there is one part I'd definitely change: the scope of variables. For example, lockercount isn't necessary for more than the initial lc. We can keep its scope down:
    println!("How many students?");
    let lc = {
        let mut lockercount = String::new();
        io::stdin().read_line(&mut lockercount).expect("expected int");
        lockercount.trim().parse().unwrap()
    };

Similarly, I would prefer to use enumerate instead of an explicit counter. An explicit counter might not be incremented by accident, but enumerate on an iterator will always fit:
    println!("Opened lockers:");
    for (n, v) in lockers.iter().enumerate() {
        if *v == true {
            print!("{}, ", n + 1);
        }
    }

We could also get rid of the if via filter, but that's a little bit much:
    for (n, _v) in lockers.iter().enumerate().filter(|(_, &b)| b) {
        print!("{}, ", n + 1);
    }

On the algorithmic part of the code, I'd prefer to use the position explicitly instead of i*j:
    for i in 1..(lockers.len() + 1) {
        let mut pos: usize = i;
        while pos <= lc {
            lockers[pos - 1] = !lockers[pos - 1];
            pos += i;
        }
    }

Again, instead of explicitly changing a counter, I would prefer an immutable variable, for example via step_by:
    for i in 1..(lockers.len() + 1) {
        for pos in (i..lc).step_by(i) {
            lockers[pos - 1] = !lockers[pos - 1];
        }
    }


Fetch, parse, and store JSON in PostgreSQL

I would narrow down your try:except to only the statement(s) which could throw the error. Having such a large chunk of code in a try:except block could result in many exceptions thrown, none of which would be caught as you're only looking for IOError.

Also, for performance, you should build the statement and the data set from the loop, then throw the statement against cursor.executemany(statement, data) as a single database call instead.

Regarding construction, your code is just one huge blob. It's important that you refactor each operation into its own function, this saves on tracking down errors, and if you make changes in the future, your changes only affect one function. If the change is not liked by the rest of your code, it's easy to back out.
Can you imagine if you made 5 or 10 changes in your program as it is right now, and then it stops working? Which change was the breaking change? How would you find out? Why did it break? etc. Also, I'm not talking just simple syntax errors, I'm also talking about logic errors or data errors. These can be hard to track down if you don't have any tests validating your code.

Good luck!


User input function keep looping until valid filename entered

is this the proper way to accomplish this?

Yes; looping is the best approach for this type of functionality (see e.g. Asking the user for input until they give a valid response).

are there other errors that could get triggered that I should deal with?

There are reasons other than not finding the file that opening and reading the file could fail; in this case, I would probably catch the more general OSError to handle all of these. I would also restructure slightly to minimise the code in the try block:
try:
    with open(filename) as f:  # note that 'r' is the default mode
        my_file = f.read()
except OSError:
    print('Error accessing file. Check file name and path and try again.')
else:
    return my_file

A few other minor notes:

You should consider adding a docstring, explaining what the function does and how to use it;
Currently, the file_type is only used for display purposes - consider adding checks that the user has selected an appropriate file;
Returning the string content of the file means you have to read the whole thing into memory up-front, which may not be ideal with larger files; and
I would use str.format rather than + concatenation, and just pass the text straight to input as the prompt argument rather than having a separate print call.


Your component is pretty good. I even had to look at this guide to check when props and state should be used, and your code pretty much nailed it. There are a few things to change though.

First is to not rely on the fact that props and state get handed down to your component. It's best if you provide default props the same way you did with state. That way, you're always sure they have values. It also serves as pseudo-documentation, telling the developer that's lost and found his way into your component that this component expects the following props and state.

So... changeYardage selects a yardage, a single yardage. It makes no sense keeping it an array and end up using find later on. You can use find on changeYardage instead so that yardages stores an object instead of an array. If find returns undefined, just default it to a blank object. And since it's a single yardage object, we rename it to a singular yardage instead.

this.setState({
  yardage: this.props.yardages.find(yardage => yardage.hole_id === option.id) || {};
});

I notice you use React, so probably you're using Babel (if not, you should). This gives you access to a lot of shortcuts seen above. First, in ES6, arrays now have a find method so you can drop using lodash/underscore for that. Then there's the arrow functions to make callbacks a bit shorter. Not related to ES6 syntax, you should also use strict comparison, unless the comparison calls for loose comparison.

Now with regards to the yardages table, I'm not sure you want to actually show a blank table when yardage is not defined. You might want to actually just show an error message instead of a blank table.

And I notice you use BEM convention for CSS. Good. At least you are not using inline styles, because it has a very high specificity and makes it hard for stylesheets to override.


Consider moving what Transliterate() does to an external dictionary in a file that can be parsed by your program at runtime. You don't want to recompile your program every time you want to add something or change something in that map.


Code duplication:

There is a code duplication in the overloads of the operator. I believe that the second should call the first with parameters swapped, or vice versa.

Last feature:

The last thing I would add, aside from what @Justin mentioned, is some support for std::basic_string<>. Although it will introduce abundance of template parameters, the code will be more or less generic.

Do note that in this case reserving might make sense.


Proof technique

I was pleasantly surprised at the speed of this algorithm (generating all 6-digit palindromes, then taking the largest one with two 3-digit factors), as compared to the alternative approach (multiplying all 3-digit pairs, then finding the largest product that is a palindrome).  I would have expected the latter to be faster, as factoring is normally a more expensive operation — but you take advantage of a clever shortcut.  That, I suppose, is part of the point of Project Euler questions.

On the other hand, I would consider the program to be slightly incomplete.  The property that the palindrome is divisible by 11 only holds if it contains an even number of digits.  As a counterexample, 101 ∙ 101 = 10201 is a number within the parameters of the question (a palindrome that is the product of two 3-digit numbers) that is not divisible by 11.  Your palindromes function only generates 6-digit candidates for consideration.  While there is no need for your program to produce a result that requires no human interpretation, it would be desirable to note the assumption (or proof) of the existence of a 6-digit result, at least as a comment.

Implementation

I am puzzled by your boilerplate main function.  Reading an input number as an upper bound on the palindrome candidates seems superfluous.  An excessively large input won't scale the problem to cover 4-digit × 4-digit products, either, as your palindromes function is hard-coded to produce 6-digit candidates only.  So, this would have sufficed:

problem4 :: Int
problem4 = head $ filter isMultiple $ sortBy (flip compare) $ palindromes

main :: IO ()
main = do
    print problem4

Integer is overkill.  The numbers involved fit very comfortably under maxBound::Int.

sortBy (flip compare) is just the same as reverse.  But why reverse anything at all, when you could just generate the palindrome candidates in descending order in the first place?

palindromes :: [Int]
palindromes = [calcPalindrome a b c | a <- [9,8..1], b <- [9,8..0], c <- [9,8..0]]
    where
        calcPalindrome a b c = 100001 * a + 10010 * b + 1100 * c

is3Digit is fine, though I would find is3Digit n = 100 <= n && n < 1000 more aesthetically pleasing.

isMultiple could be better named, and the do … return would be better written as a list comprehension.  (See Do notation considered harmful.)

isProductOfThreeDigitNumbers :: Int -> Bool
isProductOfThreeDigitNumbers n = not $ null threeDigitFactors
    where
        -- All palindromes with an even number of digits are divisible by 11
        factors = [(d, n `div` d) | d <- [11, 22 .. 99 * 11], n `isDiv` d]
        threeDigitFactors = filter (\ (m, n) -> is3Digit m && is3Digit n) factors

Then, problem4 would just be

problem4 :: Int
problem4 =
    head $ filter isProductOfThreeDigitNumbers $ palindromes


Optimization and restructuring

Redundant and inefficient things
The getvalueofnode function is unneeded: text attribute of a node will be None or string value. All intermediate dataframes are also unnecessary.Avoid using pd.Dataframe.append method within any loop as it will create a copy of accumulated dataframe of each loop iteration.

Namings
Use a meaningful names for your functions and if __name__ == '__main__': guard.I would suggest phones_to_df function name.

Assuming that the goal is to convert all Phones tags child nodes into dataframe records - all you need is collect a dictionaries of child nodes as <el.tag: el.text> mappings at once (+ special case for nuk tag, see below).Note, that some Phones tags could have their children in different order. So a list of dictionaries provides a robust way to arrange columns to respective values.

See the concise optimized approach below:

import xml.etree.cElementTree as cET
import pandas as pd

def phones_to_df(fname):
    tree = cET.parse(fname)
    pd.DataFrame([{**{el.tag: el.text for el in list(phone)},
                   **{f'nuk_{k}': v for k, v in phone.find('nuk').items()}}
                  for phone in tree.iterfind('Phones')]).to_csv('export.csv', index=False)

if __name__ == '__main__':
    phones_to_df(fname="test.xml")

After generating the expected export.csv file the resulting sample dataframe may look as below (I've tested on xml file with 2 Phones tags):

print(pd.read_csv('export.csv').to_string())

   Date  Prog  Box  Feature     WIN     Set     Pr     Number Simple  Nr          gt  Reno    QW  ER  VR  Use    Dar  age     name1            Sys         aac   time             nuk           nuk_name nuk_text_g  nuk_text_h
0   NaN   NaN  NaN      NaN  MAFWDS  234234  23423  afasfhrtv  dfasd NaN  6070106091  1233  3234 NaN NaN  NaN  sdfsd  NaN  sdfsfdfs  IVECO E.A.SY.  2019-05-29  02:00  fsdfsfd3432fdf  This is some text   asadsdas           2
1   NaN   NaN  NaN      NaN    ABCD     123    456        aaa    bbb NaN        1111   222   333 NaN NaN  NaN    rrr  NaN      wwww  TIMES E.A.SY.  2019-12-29  03:00        text ...  This is some text   asadsdas           2


The role of your ZStack and border rectangle could be replaced with a .background or .overlay modifier on the Sparkline itself - would allow more flexibility in presentation at the point-of-usage.


Separation of concerns

At the moment, all your code is in a convoluted main function handling :

getting the input from stdin
solving the problem
printing the answer in stdout.

It would be better to separate the concerns. On top of making things clearer and easier to maintain, it would also make things easier to test.

Writing tests

Because you'll probably want to improve the algorithm, it can be a safe option to write tests to ensure you are aware if you break your code. Great thing is that you have test cases provided with the problem, you just need to write them as code, run them and be happy.

At this stage, my code looks like :

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <assert.h>

using namespace std;

typedef multimap<int,int> MMap;

vector<int> get_input_from_std()
{
    // contains input for each test case
    vector<int> in_vec;
    int size;
    cin>> size;
    int val;
    for(int i=0;i<size;++i) {
        cin>>val;
        in_vec.push_back(val);
    }
    return in_vec;
}

int get_min_team_size(vector<int> in_vec)
{
    if(in_vec.size()==0) {
        return 0;
    }
    sort(in_vec.begin(),in_vec.end());
    vector<vector<int> > vec_teams;
    vec_teams.push_back(vector<int>());
    // maintains ordered, key value pair of size and its position(index) in vec_teams
    MMap mmap;
    mmap.clear();
    vec_teams[0].push_back(in_vec[0]);
    mmap.insert(pair<int,int>(vec_teams[0].size(),0));

    for(int id=1; id<in_vec.size(); ++id) {
        bool added = false;
        MMap::iterator it = mmap.begin();
        //inserts the skill level to correct team
        // if not possible to add to any
        // then new team is created after the loop
        for(int i=0; i<vec_teams.size(); ++i,++it) {
            int mpos = (*it).second;
            if (vec_teams[mpos][vec_teams[mpos].size() -1 ] + 1 == in_vec[id]) {
                pair <MMap::iterator, MMap::iterator> pa= mmap.equal_range(vec_teams[mpos].size());
                MMap::iterator mmit;
                for (mmit=pa.first; (*mmit).second!=mpos; ++mmit);
                mmap.erase(mmit);
                vec_teams[mpos].push_back(in_vec[id]);
                mmap.insert(pair<int,int>(vec_teams[mpos].size(),mpos));
                added = true;
                break;
            }
        }
        // Since not able to add to existing teams
        // new team is created and added to it
        if(!added) {
            vec_teams.push_back(vector<int>());
            vec_teams[vec_teams.size() -1].push_back(in_vec[id]);
            mmap.insert(pair<int,int>(1,vec_teams.size() -1));
        }
    }
    int ans = (*(mmap.begin())).second;
    return vec_teams[ans].size();
}

/*
Using http://stackoverflow.com/questions/8906545/how-to-initialize-a-vector-in-c
*/

void unit_tests()
{
    {
        int vv[]{4, 5, 2, 3, -4, -3, -5};
        vector<int> v(begin(vv), end(vv));
        assert(get_min_team_size(v) == 3);
    }
    {
        int vv[]{-4};
        vector<int> v(begin(vv), end(vv));
        assert(get_min_team_size(v) == 1);
    }
    {
        int vv[]{3, 2, 3, 1};
        vector<int> v(begin(vv), end(vv));
        assert(get_min_team_size(v) == 1);
    }
    {
        int vv[]{1, -2, -3, -4, 2, 0, -1};
        vector<int> v(begin(vv), end(vv));
        assert(get_min_team_size(v) == 7);
    }
}

void stdin_tests()
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int t;
    cin>>t;
    for(int tcase=0; tcase<t; tcase++) {
        vector<int> in_vec = get_input_from_std();
        cout<< get_min_team_size(in_vec) <<endl;
    }
}

int main() {
    unit_tests();
    return 0;
}

Algorithms and performances

In the case of programming problems like the one you are trying to solve, the real issue is usually the complexity of your algorithm, how it behaves on large inputs.

In order to see how your code behaves on larges inputs, you have two main strategies (and you should try apply both):

pen, paper and mathematics
tests : great thing is that now, it is quite easy to define tests of any size you like. You just need to time your program.

For instance, you could add the following tests to your test suite :

int nb_elts = 100000;
{ // Single big team
    vector<int> v;
    for (int i = 0; i < nb_elts; i++)
        v.push_back(i);
    assert(get_min_team_size(v) == nb_elts);
}
{ // Double big team
    vector<int> v;
    for (int i = 0; i < nb_elts; i++)
    {
        v.push_back(i);
        v.push_back(i);
    }
    assert(get_min_team_size(v) == nb_elts);
}
{ // Multiple different one-player teams
    vector<int> v;
    for (int i = 0; i < nb_elts; i++)
        v.push_back(2 * i);
    assert(get_min_team_size(v) == 1);
}
{ // Multiple identical one-player teams
    vector<int> v;
    for (int i = 0; i < nb_elts; i++)
        v.push_back(0);
    assert(get_min_team_size(v) == 1);
}
{ // Overlapping three-player teams
    vector<int> v;
    for (int i = 0; i < nb_elts; i++)
    {
        v.push_back(2*i);
        v.push_back(2*i+1);
        v.push_back(2*i+2);
    }
    cout << get_min_team_size(v) << endl;
    assert(get_min_team_size(v) == 3);
}

A quick look at your code tells me is probably somewhere around O(n^2) which grows "very" fast.

I have designed an algorithm which seems to be faster on the various inputs I have tried but I might have forgotten edge-cases.

In any case, the principle is the following :

we sort the individuals by levels just like you did.
we count of many individuals we have for each levels
when considering a new group of individual :

if we have more people than the number of teams, we create as many new teams keeping track of the level of the smallest level
if we have more teams than the number of people, we end the formation of as many teams, starting with the longest ones (the one with the smallest starting levels).

I hope :

I managed to make this explanation clear
this actually works.

And here is the corresponding code :

int get_min_team_size(vector<int> levels)
{
    if (levels.size()==0)
        return 0;
    sort(levels.begin(),levels.end());

    int sol = levels.size(); // Solution will not be bigger that the size of the input
    queue<int> lowest_lvl; // Storing the (sorted) levels of the less skilled member of the teams being formed.
    int level = levels[0] - 2; // Level of the individuals being processed (the minus 2 is a trick not to have to handle the beginning in a special way).
    int nb_in_level = 0; // Number of individual being processed
    levels.push_back(levels.back() + 2); // trick not to have to handle the end in a special way
    for(int id=0; id<levels.size(); ++id)
    {
        int ind_lvl = levels[id];
        if (ind_lvl == level)
        {
            // Same level : just counting the new individual
            nb_in_level++;
        }
        else
        {
            bool lvl_gap = ind_lvl != level + 1;

            // Different level : processing what needs to be done for previous level :
            // 1) If we haven't started enough teams, let's start them from that level
            while (lowest_lvl.size() < nb_in_level)
                lowest_lvl.push(level);

            // 2) If we have too many teams started, let's end the one starting with the longest ones
            // (they correspond to the first teams as we have them sorted by the level of the smallest individual)
            // and check their length. If we have a gap of level, we want to end them all.
            if (lvl_gap)
                nb_in_level = 0;

            while (lowest_lvl.size() > nb_in_level)
            {
                // Theoritically, lowest_lvl is sorted so only the last element is relevant but we have to unpop them anyway
                sol = min(sol, 1 + level - lowest_lvl.front());
                lowest_lvl.pop();
            }

            // 3) If there is a gap of level, we add the new beginning of team.
            if (lvl_gap)
            {
                lowest_lvl.push(ind_lvl);
            }
            nb_in_level = 1;
            level = ind_lvl;
        }
    }
    assert(nb_in_level == 1);
    assert(lowest_lvl.size() == 1);
    cout << sol << endl;
    return sol;
}


Greedy algorithms to find minimum number of coins (CS50)

This code needs compiling with more warnings enabled:
gcc -std=c17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds  -Wstrict-prototypes    -Wconversion    254841.c    -o 254841
254841.c: In function ‘main’:
254841.c:14:13: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]
     money = dollars_to_cents(ask_money());
             ^~~~~~~~~~~~~~~~
254841.c:17:40: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]
     printf("%i\n", min_coins_exchanged(money, coin_types, arr_length));
                                        ^~~~~
254841.c: In function ‘get_max_coins’:
254841.c:24:21: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
     int max_coins = floor((float)((_cents) / coin_type));
                     ^~~~~
254841.c:25:11: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]
     money -= max_coins * coin_type;
           ^~
254841.c: In function ‘ask_money’:
254841.c:36:12: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]
     return money;
            ^~~~~
254841.c: In function ‘dollars_to_cents’:
254841.c:42:12: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]
     return round(money * 100);
            ^~~~~~~~~~~~~~~~~~
254841.c:40:26: warning: unused parameter ‘dollars’ [-Wunused-parameter]
 int dollars_to_cents(int dollars)
                      ~~~~^~~~~~~
254841.c: In function ‘min_coins_exchanged’:
254841.c:51:18: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]
         _money = money;
                  ^~~~~

You have avoided some of the common traps, such as embedding the set of coins into the logic, although I wouldn't give those locale-specific names - here in Britain, we have 1, 2, 5, 10, 20, 50, 100 and 200 but they don't have nicknames.
I would instead make the set of coins be a global constant, without naming them individually:
const unsigned int coin_values = {
    25,  /* quarter */
    10,  /* dime    */
    5,   /* nickel  */
    1    /* penny   */
};
const size_t coin_values_len = sizeof coin_values / sizeof *coin_values;

Avoid using floating-point types for money.  The problem is that .01 is not an exact fraction in binary, so the code is prone to error due to rounding.
Instead, do something like
unsigned int dollars, cents = 0;
if (scanf("%u.%u") < 1) {
    fputs("Currency parse failure\n", stderr);
    return EXIT_FAILURE;
}
/* if we got here, we read the dollars, and perhaps the cents */
unsigned int total_cents = 100 * dollars + cents;  /* TODO: deal with overflow */

You're using some names that you shouldn't:

int get_max_coins(int _cents, int coin_type)

All identifiers beginning with _ followed by a letter are reserved for use by the implementation.  That means it's a bad idea to use these names in your own code.  There's no reason not to just call the argument cents without that prefix, so that's what I'd recommend.
There's some pointless conversion here:

int max_coins = floor((float)((_cents) / coin_type));

cents / coin_type is of type int.  We convert that to float (losing precision), truncate the fractional part (which will be zero, since we started with an integer) and then implicitly convert to int.  That code is a very inefficient and problematic way to write

int max_coins = _cents / coin_type;

There's some serious problems with global variables, and there seems to be confusion passing values by parameter or via globals.  Look at this:
float money;

int main(void)
{
    money = dollars_to_cents(ask_money());
}

int dollars_to_cents(int dollars)
{
    return round(money * 100);
}

int ask_money(void)
{
    do
    {
        money = get_float("Change owed: ");
    }
    while (money < 0);
    return money;
}

In main(), we assign to money, which we're also using in ask_money.  And dollars_to_cents() completely ignores its argument and shares the global variable.  There's no need for this variable to be shared - each function can have its own local variable:
int main(void)
{
    int money = dollars_to_cents(ask_money());
}

int dollars_to_cents(float dollars)
{
    /* don't actually use float - see earlier in review */
    return round(dollars * 100);
}

float ask_money(void)
{
    float money;
    do
    {
        money = get_float("Change owed: ");
    }
    while (money < 0);
    return money;
}

Summary

Eliminate the global variables
Use more appropriate numeric types


Sending a file in servlet response, using a class inside a method

Yeah..... no. Not a good idea.... ;-)

You are using a class to do the job of a method. The real question is why you feel you need to declare the method inside your other method (for the record, it is highly unconventional to declare a formal class inside a method too... an anonymous class is common, but a formal class is odd)

You really just want to have a private-static method that does the work for you... something like:

    private static final String HEADER_KEY = "Content-Disposition";
    private static final String HEADER_VALUE = "attachment; filename=\"%s\"";
    private static final String TEMPLATE_FILE_NAME = "filename.html";

    private static void processResponse(HttpServletResponse response, String fileBody) throws IOException {
        byte[] bytes = fileBody.getBytes();
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setHeader(HEADER_KEY, String.format(HEADER_VALUE, TEMPLATE_FILE_NAME));
    }

then your code becomes:

public static String downloadFile(final String fileBody, HttpServletResponse response) {
    try {
        processResponse(response, fileBody);
        return StringUtils.EMPTY;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

which in turn, probably means the functional extraction is too much... how about just:

public static String downloadFile(final String fileBody, HttpServletResponse response) {
    try {
        byte[] bytes = fileBody.getBytes();
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setHeader(HEADER_KEY, String.format(HEADER_VALUE, TEMPLATE_FILE_NAME));
        return StringUtils.EMPTY;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}


SPOJ "SBANK - Sorting Bank Accounts" TLE

Time limit exceeded

When a solution is too slow, it's typically because the algorithm is one or more orders of magnitude worse than intended for the challenges. So take a hard look at the time complexity of the implementation.

In your implementation, it all comes down to this expression:

sorted(set(x+"%d"%(k.count(x)) for x in k))

k.count(x) : the centerpiece of the expression, to find the count of some value in a list. The count function does this by iterating over all elements k, and checking each for equality with x. Time complexity: \$O(N)\$, where N is the number of items in k
... for x in k : do something for each item in k. Again, \$O(N)\$, where N is the number of items in k
set(...) : probably \$O(N)\$
sorted(...) : probably \$O(N\log(N))\$

In total that gives: \$O(N^2) + O(N) + O(N\log(N))\$

Can this be better?

You need to sort, that's for sure. That's fast enough.
Do you really need a set? You used a set because the previous operations generate a list with duplicates. Using a set to remove duplicates is fine, but I would question why are duplicates at all in the first place.
The previous two items actually don't even matter. It's the slowest operation in the \$O(N^2) + O(N) + O(N\log(N))\$ that will drag everything down, the \$O(N^2)\$, so that's what you really need to optimize.

Instead of iterating over every account number for each account number,
you could iterate only once,
building a dictionary with counts along the way:

def print_sorted_with_count(accounts):
    counts = {}
    for account in accounts:
        counts[account] = counts.get(account, 0) + 1
    for account, count in sorted(counts.items()):
        print('{} {}'.format(account, count))

This implementation reduces the time complexity from \$O(N^2)\$ to \$O(N)\$,
and also gets rid of an \$O(N)\$ operation (no more need for the set.)

UPDATE

As @abarnert pointed out,
the dictionary of counts can be created with a single expression using collections.Counter, so the above code can become simply:

from collections import Counter

def print_sorted_with_count(accounts):
    counts = Counter(accounts)
    for account, count in sorted(counts.items()):
        print('{} {}'.format(account, count))

Naming

The variable names in the posted code are horrible,
and it makes it very hard to read.
Avoid single-letter variable names,
try to use descriptive names.

Coding style

I suggest to follow the recommendations of PEP8.


I have to disagree with palacsint about using HashMap, if anything, I think that you should use a Set implementation such as HashSet. You're never using the value that is stored in the map, and you have no reason to use it either. Therefore, I would go with a Set. (The fact that a HashSet internally uses a HashMap is an entirely different subject) Palacsint is correct though that HashMap is a better alternative than Hashtable.

Reading lines like this makes me sea-sick:

if( (!myTable.containsKey(minVal-1)) && minVal-1>0){

Use spacing properly and remove unnecessary parameters and it becomes:

if(!myTable.containsKey(minVal - 1) && minVal - 1 > 0) {

Overall, I think that you shouldn't need to use Objects for this (except an array of course, which technically is an object). I would only use primitives and use more self-documenting variable names.

An unnecessary operation in your code is that on each iteration you check containsKey twice. Once to see if value - 1 is set and once to see if value + 1 is set. Why not just check if value itself is set?

Your code can be rewritten and optimized into this: (This is a fixed version of ChrisW's approach, I had started the approach when he posted his answer and then I did some modifications to make sure it matched your code).

public int firstMissingPositive(int[] array) {
    boolean[] foundValues = new boolean[array.length];
    for (int i : array) {
        if (i > 0 && i <= foundValues.length)
            foundValues[i - 1] = true;
    }

    for (int i = 0; i < foundValues.length; i++) {
        if (!foundValues[i]) {
            return i + 1;
        }
    }
    return foundValues.length + 1;
}


Optimizing primes generating program in C++

I'm not sure what your optimizations are doing(comments would be nice), but I did notice several inefficiencies:

Never include a calculation in the limit test in a for loop.  It get's re-calculated on every iteration.  In this case set the limit to sqrt(limit).  the calculation is kind of expensive but it's done only once.

The same goes for the iteration step, calculate it once before you enter the loop.

In the tests, in the first set of loops, you use 3*x*x twice and y*y 3 times.  putting these in variables would be a lot cheaper.


First things first, make this a function.
If you then add a doctest to the function you can test if it works correctly, without having to change the code.
This is good, as it also describes how to use it to your users.
Whilst this is a homework assignment, but it's better to get used to using these things.

At the moment you should have the following code.
The import doctest is so that you don't have to use the command line to test the code.
This is good if you don't know how to use the command line or if there are problems with Python and the system PATH.

def overlapping_count(s, seek):
    """
    >>> overlapping_count('azcbobobegghakl', 'bob')
    2
    >>> overlapping_count('auoeunbobnoeubobob,ntonethbobobo', 'bob')
    5
    """
    matches = 0
    # Rest of code...
    return matches

if __name__ == "__main__":
    import doctest
    doctest.testmod()

The biggest improvement in clarity that you can make with the code you have is to use slicing.
Python allows you to index from a beginning to an end of a sliceable object.
To use this is quite simple.

>>> s = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
>>> s[0]
'L'
>>> s[1]
'o'
>>> s[0:1]
'L'
>>> s[0:5]
'Lorem'

As you can probably guess, using this for your match check will greatly decrease the amount of lines, and clarity.
Now the inside of your for-loop can be:

if s[i] == seek[0]:
    if s[i:i + len(seek)] == seek:
        matches += 1

If you use some (premature?) optimizations, you can make your code faster.
It keeps roughly the same amount of complexity in the function.
But mostly, you don't want to waste CPU cycles on things you can remember.
Therefore you would want to store both len(seek) and seek[0] in variables.
Finally enumerate can add a small speed boost to the function,
and is also generally preferred in this scenario.

This solution is twice as fast as your solution:

def overlapping_count(string, seek):
    """
    >>> overlapping_count('azcbobobegghakl', 'bob')
    2
    >>> overlapping_count('auoeunbobnoeubobob,ntonethbobobo', 'bob')
    5
    """
    matches = 0
    seek_len = len(seek)
    seek_c = seek[0]
    for i, c in enumerate(string):
        if c == seek_c and string[i:i + seek_len] == seek:
            matches += 1
    return matches


While I cannot comment on your Node.js code, I can tell you that we're doing something very similar on a project that uses Mongo to store every bit of information for around 200 social profiles. In our case, we're doing something like:

foreach ($videos as $video) {
    $payload = ['$set'  => $defaults + $meta + $this->interjectTimestamps((array)$video)];

    if (isset($video['statistics'])) {
        // Maintain a log of statistics for each video
        $payload['$push'] = ['statistics_log' => ['execute_at_ts' => $meta['execute_at_ts'], 'statistics' => $video['statistics']]];
    }
    $coll->update(['_type' => 'video', 'id' => $video['id']], $payload, ['upsert' => true]);
}

From my research, this is fine. Mongo's $push works great for logs like this, but be wary, it can be difficult to query data in array's like this. If you plan on doing a lot of querying against a user's app's, it may be better to store this information in a separate collection.

On the flip side, this design can be crucial if you ever need to perform any calculations with data from both your User document and the nested log. In our case, we're doing MapReduce on data from the entire document, log and all.


Print values of an array while stripping out some parts of the string

I'm assuming that file=${file//*lettus_} is supposed to be file=${file##*lettus_}.
Don't do file=. There is no reason to declare the file variable before-hand. Using it is a the loop variable automatically creates it.
Get rid of the temporary ARRAY1 variable (which fyi is not a good variable name). Just do for file in lettus_*.sh. In fact, since you don't quote ${ARRAY1[@]}, word-splitting would make your program fail in some cases.
Why do you want a more efficient way? This should run in a split-second unless you have a million files.


Closing a ResultSet and rethrowing an Exception

Close a ResultSet/Resource

If you are using java 7 then I would recommend to use try with resources

it will take care of closing ResultSet for you and make your code a little cleaner.

public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus) throws Exception {
    String strSelect = this.createReplicationSelectStatement(taskBean);
    try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) {
        if (resultSet.next()) {
            resultSet.updateString(COLUMN_STATUS, strStatus);
            resultSet.updateRow();
        }
    } catch (Exception e) {
        throw e;
    }
}

Exception Handling

personal I prefer to wrap my own exceptions around generic exceptions.

That way I can throw a more precise exception with a comment to help myself when debugging

public void updateReplicationStatus(BeanReplicationTask taskBean, String strStatus)   throws ReplicationStatusException {
    String strSelect = this.createReplicationSelectStatement(taskBean);
    try (ResultSet resultSet = DerbyDog.getResultSet(strSelect) {
        if (resultSet.next()) {
            resultSet.updateString(COLUMN_STATUS, strStatus);
            resultSet.updateRow();
        }
    } catch (SqlException e) {
        throw new ReplicationStatusException("update ReplicationStatus failed because of a SQLException", e);
    } catch (Exception e) {
        throw new ReplicationStatusException("update ReplicationStatus failed because of an unexpected exception", e)
    }
}

that's about my 2 cents


Fetch: how to deal with a json payload in an error response?

Note this reads more like a hypothetical question but I'm giving you the benefit of the doubt.

Your example is alright, but it has a few issues. I'm going to mostly touch on semantics here, so bear with me. Note I'll be going with the WHATWG spec that's implemented in browsers now, which should be the same as the repo you've linked, but just so you are aware :)

  if (response.status >= 200 && response.status < 300) {
    return response

There's no need to check response.status like this; it also doesn't cover all "success" responses (assuming that is indeed what you're trying to do. WHATWG fetch exposes an ok property on the response object which will do this for you..

  if (response.ok) {
    return response

Let's look at your function as a whole.

function checkStatus(response) {
  if (response.ok) {
    return response
  } else {
    ...
  }
}

As this is just a straight up if-else, you can reduce cyclomatic complexity by dropping the else here.

  return response.json()
    .catch(() => {
      var error = new Error(response.statusText)
      error.response = response
      throw error
    }).then((json) => {
      var error = new Error(json.message || response.statusText)
      error.response = response
      throw error
    });

I think this is a bit redundant. I'm guessing what you're trying to do is either:

Catch, and re-throw (thus rejecting the promise), the error with the response property if you hit this branch if there was already an exception
Reject the promise by throwing an error if there was not an exception by taking the response json and assigning it as an error message.

I'd argue that you should not be catching the error in the first place. The only place an error will occur here is if there is a JSON syntax error. There's nothing you can do to handle this, so don't attach bits and pieces to it; the only thing it would be useful for is debugging, and you shouldn't be adding debugging stuff like this to the user's browser - this should be caught in e2e tests. Instead, just let the default error propagate up. This leaves you with this so far:

function checkStatus(response) {
  if (response.ok) {
    return response
  }
  return response.json().then((json) => {
    var error = new Error(json.message || response.statusText)
    error.response = response
    throw error
  });
}

The next thing I have to add is this function could either be synchronous or asynchronous depending on what is passed to it. This is a bad thing and is explained here by more clever people than I. The upshot is that you should design your API so that if it can return asynchronously, it always should. Solution to this is just to wrap response in a Promise.resolve().

function checkStatus(response) {
  if (response.ok) {
    return Promise.resolve(response)
  }

  return response.json().then((json) => {
    var error = new Error(json.message || response.statusText)
    error.response = response
    throw error
  });
}

Next:

Your semi colons aren't consistent. Either use them or don't. Don't mix and match, it just confuses everyone.
If you're using ES6 arrows, you can use const/let as well. Use them.

You could simplify your promise handler code by using something like Object.assign if you support it or _.assign otherwise, which makes things nice and sugary.

function checkStatus(response) {
  if (response.ok) {
    return Promise.resolve(response)
  }

  return response.json().then(json => {
    const error = new Error(json.message || response.statusText)
    throw Object.assign(error, { response })
  })
}

Consider using Promise.reject instead of throw. It's a standard API for promises and clearly communicates your intent. Unwinding the stack trace isn't fun.

function checkStatus(response) {
  if (response.ok) {
    return Promise.resolve(response)
  }

  return response.json().then(json => {
    const error = new Error(json.message || response.statusText)
    return Promise.reject(Object.assign(error, { response }))
  })
}

I think that's about it for now. I think it's weird you're doing either json.message || response.statusText as an error message, but whatever floats your boat. Error reporting messages are largely what is helpful to the developer. I'd recommend you put user-friendly error message handling somewhere, though.


Return sum of three values, excluding values within a specified range

I may be off the mark here as I didn't test my code (no access to a Python environment), but this is the way I'd 'start' to work at it.

def no_teen_sum(a, b, c):
    return fix_teen(a) + fix_teen(b) + fix_teen(c)

def fix_teen(n):
    if n in [13, 14, 17, 18, 19]:
        return 0
    else:
        return n

Quite simple.


How many chores can you accomplish in a set time?

Formatting: Indent after opening { and unindent after closing }.

Variable naming: A better name for list would be choreList.

When iterating through an array use an enhanced-for loop:

for (int chore:list) {
        chore = Integer.parseInt(input.readLine());
}

Your algorithm for computing the maximum amount of chores that can be accomplished could be simplified as follows:

for (int chore:list){
    maxMins -= chore;
    if (maxMins > 0){
        chores++;
    }
    else {
        break;
    }
}


Both of the other answers make some very good points, especially when it comes to replacing vector. Two dimensional vectors are particularly iffy because the whole lump of memory will not be contiguous. If you access elements[y][x] you first have to look in elements[y] for the address of the inner vector, and then have to look into that inner vector. By contrast if you have an array that is say, 4x4, the compiler would typically internally have a single 1D array of length 16. Then to get elements[2][2] it might just grab the entry in offset 11 (i.e. 2*4+3)

There are (at least) three distinct performance advantages associated with this when you think about low level hardware.

You don't waste time chasing pointers to find which bit of memory you need.
Having the values that you're working with all be close together gives you nice cache locality.
This simplifies the code within the key loops, giving the compiler a better chance of automatically vectorizing your code.

Snowbody mentions templating your Matrix so that you could have different primitive types in it (A matrix of ints or of doubles or whatever). I would further suggest templating your matrix to specify the sizes. Comparing with how std::array is done, where you might have std::array<int, 3>;, you could have matrix<float, 3, 3>. (In fact it would be necessary if you wanted your internal data storage to be a std::array as vnp suggests.)

This again gives the compiler more guarantees about your program ahead of time, which again means it has a better chance of doing helpful optimisations. For example a classic optimisation that compilers might do is "Loop unrolling", whereby they actually rewrite

for (int i = 0; i < 3; ++i) {
    doSomething();
}

as

doSomething();
doSomething();
doSomething();

They can do this because they know ahead of time how many iterations of the loop to expect, and calculate whether duplicating the machine code is justified by getting rid of the loop overhead.

As well as probably helping performance, this opens the door to writing compile time checks for your program. For example you could get the compiler to stop you from accidentally adding a 4x4 matrix to a 2x2 matrix, just like it would stop you from adding a double and a string.

Finally, because this information is known at compile time it does not need to be stored or accessed during the running of the program. Instead of i < dest.width the compiler would be writing machine code for i < 3. (But, importantly, you would still not have to write i < 3 which is inflexible and harder to understand than width.)

Modern optimisers have their own cost models to decide when to inline methods, but sensible hints still wouldn't go amiss. I'd suggest that get_element and set_element are particularly good candidates for inlining.

I actually disagree with vnp about directly accessing elements, although I do agree that the current getter and setter aren't any better. The advantages of using such methods are that they give you opportunity to

add precondition and postcondition checks, such as requiring that the indices are within bounds.
mess with the internal representation, such as the aforementioned storing your data in a 1D array and directly indexing it as if it was a 2D one. (If for some reason you didn't trust the compiler to do that indexing for you.)

Note that

float t_elements[right.width][left.height];

Is not legal c++, because c++ requires that array size (for stack arrays) must be a constant expression. You do have the option of using new, in which case you must remember to delete[]

I would also suggest, though this strays away from performance questions, that doing some error checking would be sensible. If you don't want to include sizes in the templates as above, it's still worth a basic check that you're not multiplying a 2x5 matrix by a 3x4 one.

Please note that all of the above is based on some theoretical understanding of the sorts of machine code that compilers can write. It is not based on empirical profiling of your code with a representative set of test data, which should be your first move when looking to optimise anything. (Closely followed of course by questioning whether there might be a suitable third party library that has already done all the hard work for you.)


Have you considered an array?

You can then create multiple objects, having each object the values per point.

Like this:

var coords = [
    {lat: 49.18589, lng: -2.19917, zoom: 17},
    {lat: 101.1986, lng: -50.2445, zoom: 17},
    {lat: 29.125285, lng: -82.048823, zoom: 17}
];
var markers = [];
var maps = [];

function initialize() {
    for(var i = 0, length = coords.length; i < length; i++)
    {
        var point = coords[i];
        var latlng = new google.maps.LatLng(point.lat, point.lng);

        maps[i] = new google.maps.Map(document.getElementById('map-canvas' + (i + 1)), {
            zoom: point.zoom,
            center: latlng
        });

        markers[i] = new google.maps.Marker({
            position: latlng,
            map: maps[i]
        });
    }
}

Here's what I did:

Created a few variables at the top, with needed information.
Created a loop to go through all the elements
Reduced the number of local variable to the bare minimum
Removed global variables being declared inside the function

Notice that I have this for loop:

for(var i = 0, length = coords.length; i < length; i++)

I'm not accessing the length property directly because it may decrease performance. Accessing a local variable is always faster than a property in an array/object.

Also, since i starts in 0 and your elements' id starts in 1, I had to add 1 to i, to match the right element.

Using an array, you also don't need to re-re-re-repeat everytime you need to add a point: just add a new element inside the array coords.

I hope you can understand everything and hope it is clear enough for you. And hope it really helps you.


Remove the occurences of an element from array if it occurs more than n times

It's been said multiple times but you should avoid one letter variable most of the time.

Class name arr is also no good. It's recommended that class name follows camel case convention and using abbreviation is often considered bad.

Don't code something in your main as it makes it harder to test your code.
Putting it in an outside function makes for a clearer code :

public static int[] removeOccurencesFromArray(final int[] array, final long maxOccurence) {
    // TODO
}

Array have an "old-school" feel and I'd avoid them if possible. Consider using List (and especially ArrayList) for those kind of use case, thus transforming previous method in :

public static List<Integer> removeOccurencesFromList(final List<Integer> list, final long maxOccurence) {
    // TODO
}

Now, onto the main course :

I find your algorithm overly complex. :/
It's also higly "procedural" IMO, in modern computing we'd rather "tell" the program to do something instead of manipulating everything by ourselves.

Julien Rousé has shown a nice and short solution in another answer... which is probably faster than mine but please bear with me :)

(After rereading my answer, I see that I used some Java 8 tricks that may feel overwhelming if you are a beginner, if you are new to programming I'd recommend to not consider my solution)

Let's try to solve your problem step by step :

Here is a simple solution I came up with (almost the same as Julien Rousé)
1) count the number of occurences within your array... you end up with a structure linking all elements with the number of occurence... it's usually called a bag, while there are some java library that supports this structure let's keep things simple and use a Map
2) if any occurences count is greater than the maxOccurence parameter then it should be set to maxOccurence
3) for each elements in your array, print it if the number of occurences is greater than 0 and reduce the number of elements in your bag

Let's dig a bit in java 8... surely there's a tool for us in there.
We are looking for something that'd allow us to "tell" instead of creating everything by hand.

In the Collectors util class (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html), we can find some really fancy tools. For our use case, groupingBy and counting sounds useful.

groupingBy allows you to transform a stream of data into a map where the key is found using the first parameter.
counting counts the number of input elements (from Javadoc).

list.stream().collect(Collectors.groupingBy(element -> element, Collectors.counting()));

With this simple line, we now have the number of occurence of each elements of your list.

This is still not enough as we want to consider the maximum number of occurences.

We want to have the number of occurence if it's below a threshold.
Collectors (again) comes to the rescue :

list.stream().collect(Collectors.groupingBy(element -> element,
            Collectors.collectingAndThen(Collectors.counting(), v -> Math.min(v, maxOccurence))));

So we are counting unless we have more than maxOccurence, in which case the min will always give us maxOccurence as a result.
That's not very palatable though IMO, I'll use static import to make it cleaner. Let's also not forget to store the result.

    Map<Integer, Long> value = list.stream().collect(groupingBy(element -> element,
            collectingAndThen(counting(), v -> Math.min(v, maxOccurence))));

We can now easily compute the result :

    List<Integer> result = new ArrayList<>();
    for (Integer element : list) {
        long remaining = value.get(element);
        if (remaining > 0) {
            value.put(element, remaining - 1);
            result.add(element);
        }
    }

    return result;

If you really want to have an array at the end, use the toArray method ;)


With your JavaScript version, there is not much to optimize. So I am just going to provide some minor improvements:

Within a function, it is better to declare your variables using the var keyword. You should apply this to the i inside for() loop
The JavaScript interpreter is a single thread: this means, unfortunately, you can not perform real parallelism to sum different chunks of the array.
You can choose better variables and function names.


public static IEnumerable<T> AsList<T>(this Recordset rs) where T : new()
{
    ..
    List<T> results = new List<T>();
    ..
    return results.AsEnumerable();
}

This might be very inefficient because when I see that a method returns an IEnumerable<T> I assume its execution is deferred so I automatically do AsList(..).ToList() to execute it but what it actually does, is to iterate the list twice. First time to create the first list and then to create the second list. You should either create a real deferred method or return the List<T> so there is no doubt about the result.

IEnumerable<PropertyInfo> props = new List<PropertyInfo>(typeof(T).GetProperties()).Where(p => p.CanWrite);

You are executing this Where query for each record because the list wrapps only the GetProperties part (which is an array anyway so I don't understand why you convert it into a list in the first place - linq can work with arrays). You need to call the ToList extension after the Where

var properties = typeof(T).GetProperties().Where(p => p.CanWrite).ToList();

I also suggest moving the object creation into a separate method so that you don't have any nested loops like this:

public static IEnumerable<T> AsList<T>(this Recordset rs) where T : new()
{
    var properties = typeof(T).GetProperties().Where(p => p.CanWrite).ToList();
    while (!rs.Eof)
    {
        yield return CreateInstance<T>(properties, rs);
        rs.MoveNext();
    }
}

private static T CreateInstance<T>(IEnumerable<PropertyInfo> properties, Row row) where T : new()
{
    var obj = new T();
    foreach (var property in properties)
    {
        var value = row[property.Name].Value;
        if (value != null) property.SetValue(obj, Convert.ChangeType(value, property.PropertyType));
    }
    return obj;
}


You should use a key strengthening function like PKBDF2, scrypt or bcrypt to generate a key from the password.
The part with XTEA is useless: you're relying on security through obscurity.
You shouldn't hash before encrypting if you want to ensure the data has not been tampered with. Use HMAC SHA-256 on the encrypted data.

And finally: don't write your own crypto algorithm. Use well known and audited solutions.


Minimum steps to reach target by a Knight In Scala

At first glance, the isValidPos() method looks to be clear and succinct, requiring only two tests to see if the passed position is on the board.

def isValidPos(position: Pos): Boolean =
  ((0 until Size) contains position.row) && ((0 until Size) contains position.col)

But it turns out that the contains() method on a Range is a bit complicated and most valid positions will have to pass around 10 if checks before the method returns true, so there are probably more efficient ways to get the same result.

But a bigger question is, can this be done without any mutable collections or variables?

One approach is to create a Knight class that holds all current valid board positions and the history of how each position was arrived at and then, when taking the next step, instead of modifying the Knight instance you create a new immutable Knight instance with all the new information built from the current (old) data.

type Cell = (Int,Int)

class Knight(dim :Int, history :Map[Cell,Cell], val cells :Set[Cell]) {
  def this(dim :Int, cell :Cell) = this(dim, Map(cell->(-1,-1)), Set(cell))

  def backtrack(cell :Cell) :List[Cell] =
    if (history(cell) == (-1,-1)) cell :: Nil
    else                          cell :: backtrack(history(cell))

  def next :Knight = (new Knight(dim, _:Map[Cell,Cell], _:Set[Cell])).tupled{
    cells.foldLeft((history, Set.empty[Cell])){
      case ((hMap,cSet),(x,y)) =>
        val newSet = Set((x-2, y-1), (x-2, y+1), (x-1, y-2), (x-1, y+2)
                        ,(x+1, y-2), (x+1, y+2), (x+2, y-1), (x+2, y+1)
                        ).filter{ case (a,b) =>
              a >= 0 && a < dim && b >= 0 && b < dim && !hMap.keySet((a,b))
                                }
        (hMap ++ newSet.map(_ -> (x,y)).toMap, cSet ++ newSet)
    }
  }
}

def knightMoves(boardSize :Int, knight :Cell, target :Cell) :List[Cell] = {
  def loop(k1 :Knight, k2 :Knight) :List[Cell] = {
    val met :Set[Cell] = k1.cells.intersect(k2.cells)
    if (met.nonEmpty) k1.backtrack(met.head).reverse ++
                      k2.backtrack(met.head).tail
    else if (k1.cells.isEmpty || k2.cells.isEmpty) Nil
    else if (k1.cells.size > k2.cells.size) loop(k1, k2.next)
    else                                    loop(k1.next, k2)
  }
  loop(new Knight(boardSize, knight), new Knight(boardSize, target))
}

knightMoves(3,(0,1),(1,1))    //res0: List[Cell] = List()
knightMoves(14,(0,1),(10,12)) //res1: List[Cell] = List((0,1), (2,2), (4,3), (6,4), (7,6), (8,8), (9,10), (10,12))

Some efficiency is obtained here by making the target position a Knight instance as well. That way they can "move" toward each other and, as soon as they intersect, a path from one to the other is found.


Extract, filter and match three letters from the given arguments and predict the name

I'll show an example implementation first, and then describe it:

from typing import Iterable
import re

def case_rank1_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str:
    # extract the three-letter pattern
    protein_pattern = re.search(r"[A-Z][a-z]{2}", best_match_protein_name).group()

    # extract the numbers
    best_number = max(
        int(re.search(r"[A-Z][a-z]{2}(\d{1,3})", name)[1])
        for name in proteins_available
    )

    # Add the protein pattern, the next predicted number and 'Aa1' at the suffix
    return f'{protein_pattern}{best_number + 1}Aa1'

def main():
    proteins_available = (
        'Xpp1Aa1', 'Xpp2Aa1', 'Xpp35Aa1', 'Xpp35Ab1', 'Xpp35Ac1',
        'Xpp35Ba1', 'Xpp36Aa1', 'Xpp49Aa1', 'Xpp49Ab1'
    )
    best_match_protein_name = 'Xpp35Ba1'
    predicted_name = case_rank1_naming(proteins_available, best_match_protein_name)
    assert predicted_name == 'Xpp50Aa1'

if __name__ == '__main__':
    main()

Add type hints to better-define your function signature
Don't write {1} in a regex - you can just drop it
Call max immediately on a generator rather than making and sorting a list
Shorten your variable names. Especially don't include the type of the variable in its name. Type hints and appropriate pluralization will cover you instead.
Use f-strings
Have a main function
In main, use a tuple for proteins_available instead of a list because it doesn't need to mutate


Control Signin Class - Remove Dependencies

Without a question there's no way to give a definitive answer.  Still, here's a few comments you might want to take on board.

You're instantizing your dependencies in your constructor.  This means that your class is now irrevocably coupled to those dependencies.  This makes testing and reuse very difficult, as it's basically impossible to test your class in isolation and if you move the class over to another project then you'll have to move all the dependencies over as well.  You should use dependency injection instead and pass your dependencies to the constructor instead.
It looks like you're statically invoking some static methods as well.  You should avoid doing this for the same reasons that you should inject dependencies.  A static dependency is still a dependency, and your class will now be coupled to those classes whose static methods you're using.  Furthermore, static methods tend to be frowned upon as they represent global state.  For reasons I'm sure you're familiar with, global state is a Bad Thing.  You'll be better off passing in instances of objects instead.
Your header comment is non-standard.  Good to see you're including comments at all, but there are various automated tools out there (DocBlox for example) that are capable of generating documentation files for you, but only if your comments are in the right format.  If you look at the documentation for those tools they'll give you a rundown of how to format a comment and what tags are available to you.  IDEs like Netbeans and Eclipse can also use the docblocks to provide you with pop-up help, they'll show your comment when you type the class name so you'll be reminded of what it does.
Aside from your header comment (which is good), you don't comment your code at all.  You should at the very least put a docblock comment at the start of all your methods to tell you what they do so that they can be documented by tools like DocBlox and so that you'll get help on your class from your IDE.  You should also provide a running commentary in plain-English comments as to what's going on in your code.

One last tip. You can abbreviate the code at the start of your invoke() method as follows:

    $continue = Constant::VALIDATE_ON==true?
        $this->checkInput():
        true;


The code can be sped up, and it can also be simplified. For n > 0, there is a unique way to write a balanced string as (a)b where a and b are balanced strings.

a and b must have n-1 pairs of parentheses, total. This leads us to the following solution:

balancedParens 0 = [""]
balancedParens n = ["(" ++ a ++ ")" ++ b | i <- [0 .. n - 1], a <- balancedParens i, b <- balancedParens (n - i - 1)]


void myquicksort(std::vector<int>& A, const int left, const int right)
{
    // .......
}

Is myquicksort() supposed to be callable by those that use your sort?  If not, hide those internal implementation details by using a namespace to signify that.

std::vector::operator[] parameter takes a pos of type size_type.  Consider using a similar type (std::vector<int>::size_type, std::size_t).

int pivot = A[left + ((right - left) / 2)];

Certain inputs can make your partitioning algorithm behave poorly, degrading from \$O(n\ log\ n)\$ to \$O(n^2)\$.  In your implementation, your pivot choice of picking the median is vulnerable to organ-pipe input sequences (\$1, 2, ..., n/2, ..., 2, 1\$).  If you want to use the median, consider using a stronger pivoting rule, such as the median-of-\$k\$ (median-of-3, median-of-9, etc).

Certain inputs also just break your code. Your implementation produces a segmentation fault when trying to sort an empty sequence.

  One remark: I am curious about times where i == j on some occasions in those lines:

if(left < j) myquicksort(A, left, j);
if(i < right) myquicksort(A, i, right);

  therefore calling myquicksort with overlapping ranges. Is that an issue?

You won't be able to parallelize it using task parallelism while doing more comparisons and utilizing more space.  Just have your two calls work over the ranges [left, j] and [j + 1, right].

Keep functions short and simple.  They become easier to understand, test, and reuse.  Ideally, your myquicksort would refactor the median calculation and partitioning into their own functions.  Example:

void myquicksort(std::vector<int>& A, const std::size_t left, const std::size_t right) {
    if (right - left <= 1) {
        return;
    }
    const auto pivot_value = range_median(A, left, right);
    const auto partition_point = hoare_partition(A, left, right, pivot_value);
    myquicksort(A, left, partition_point);
    myquicksort(A, partition_point + 1, right);
}

Now if you decide that you want to use a different pivoting or partitioning strategy, you are affording yourself the opportunity to reuse code.


An extension method to get the current user

When I encountered a similar issue I had a base controller that the rest of my controllers inherited from. Then, on that base controller there was a read only property named User that got the current user.

Personally I think inheritance can be confusing when it is abused just like everything else. As long as you keep your base controller relatively lean, and don't use it as a place to drop random methods which may not used in every controller, then I think inheriting from a base controller would be a pretty straight forward solution.


Is_permutation() on sequence containers in O(n) complexity - follow-up

I would initially agree that the complexity of your solution is O(n), though, there are extreme cases where the performance of your count_frequency could be greater - unordered_map.emplace() is 'average case constant time, worst case linear', I don't believe a worst-case situation would happen for you.

Note that you have a very complicated equality-check comparing your two frequency-maps.... you have:

if( std::distance( first1, last1 ) != std::distance( first2, last2 ) )
{
    return false;
}
std::unordered_map< int, int > first_map = count_frequency( first1, last1 );
std::unordered_map< int, int > second_map = count_frequency( first2, last2 );

std::pair<std::unordered_map< int, int >::iterator,std::unordered_map< int, int >::iterator > myPair=
    std::mismatch( std::begin( first_map ), std::end( first_map ), std::begin( second_map ),
    []( std::pair< const int, int >& seed1, std::pair< const int, int > & seed2)
    { return seed1.second == seed2.second; }
    );

return  myPair.first == first_map.end() && myPair.second == second_map.end();

as far as I can tell, the size-check is redundant, and the rest can be simply:

template < typename T1, typename T2 >
bool is_permutation( const T1 first1, const T1 last1, const T2 first2, const T2 last2 )
{
    return count_frequency( first1, last1 ) == count_frequency( first2, last2 );
}

I put your code in this ideone, and the replacement code in this ideone here.


Too many parentheses to format a percentage in SELECT

There is something you can do about

CAST((SUM(product1) + SUM(product2)) AS FLOAT) / CAST(salescalls.visits AS FLOAT) * 100

To perform floating-point division rather than integer division, either the dividend or the divisor needs to be a float.  You don't need make both of operands floats.  Furthermore, you can make a the dividend a float by using floating-point multiplication.  That means that you don't need to cast anything to a float.  That simplifies it to

100.0 * (SUM(product1) + SUM(product2)) / salescalls.visits

Next, you can rewrite the sums as one aggregate by adding the two columns in each row before summing the rows:

100.0 * SUM(product1 + product2) / salescalls.visits

I don't think that there's not much that can be done about ROUND(), ISNULL(), and CAST(… AS VARCHAR), though.  Consider doing that formatting in your application-layer code instead of SQL.

You've written the query using an old-style join.  It would be better to write it using a JOIN keyword:

SELECT CAST(
           ISNULL(
               ROUND(
                   100.0 * SUM(product1 + product2) / salescalls.visits,
                   2
               ),
               0
           ) AS VARCHAR
       ) + '%' AS avrg
    FROM sales INNER JOIN salescalls ON sales.salescallId = salescalls.id


Deciding between four user statuses based on two flags

I think it is time to bring out the enum!

Enums in Java are pretty handy overall when there is a fixed number of possible values. In this case there is only four possible values, so an enum can be a good candidate for the job.

public enum Status {
    HAS_CONTACT(true, true),
    PENDING(true, false),
    ACCEPT_REQUEST(false, true),
    ADD_CONTACT(false, false);

    private final boolean hasContact;
    private final boolean hasUser;

    private Status(boolean hasContact, boolean hasUser) {
        this.hasContact = true;
        this.hasUser = true;
    }

    public static Status findStatusWith(boolean hasContact, boolean hasUser) {
        for (Status status : Status.values()) {
            if (status.hasContact == hasContact && status.hasUser == hasUser) {
                 return status;
            }
        }
        return null;
    }
}

You can get the string representation of the enum by calling .name() or .toString()

Status status = Status.findStatusWith(userHasContact, contactHasUser);
String statusDescription = status.name();

Overall I don't recommend using Strings for this kind of data, you have no guarantee that your String will only have one of the four possible values. What if the String suddenly says "ACCPT_SMTHNG"? An enum is much more preferable in this way.