Which is better code for implementing quicksort?

Both are very similar - list of 100000 random int elements (from 0 to 100000) was sorted in (average time taken from 10 tries):

#1st implementation
Average time:
Random: 0.4825087092408925

#2nd implementation
Average time:
Random: 0.48071902671725464

That being said, both implementations aren't good. A lot of people forget to include shuffling at the beginning of quicksort and it has really long call stack. When I added some data sets:

data_sets = {'Sorted': [x for x in range(how_many)],
             'Reverse': list(reversed([x for x in range(how_many)])),
             'Random': [random.randint(0, how_many) for x in range(how_many)],
             'A lot of equal keys': [x if x % 2 else 0 for x in range(how_many)],
             'Same keys': [1] * how_many}

I managed to sort data which was 900 elements in length (more than that gave me recursion error) and performance took a big hit in case of sorted / reversed / lot of equal keys data:

Average time:
Same keys: 0.061130084848424526
Sorted: 0.060439534806328445
A lot of equal keys: 0.032078340092241295
Reverse: 0.06125047935425505
Random: 0.0030011541824106593

EDIT:
As per suggestion in comment, I ran quicksort (with shuffling) and compared it with list.sort(). quicksort was first, then I ran list.sort(), waited for a bit and re-run with reversed order - times were very close in both cases.

100000 items, 10 tries. Tests were ran on my laptop, so hardware is different than in original post.

#QUICKSORT
Average time:
A lot of equal keys: 0.9257455763466982
Sorted: 1.605769951669822
Reverse: 1.5616443986206265
Random: 1.471783668415066
Same keys: 0.28260723572820756

#SORT
Average time:
A lot of equal keys: 0.025862182302070193
Sorted: 0.004639602319800995
Reverse: 0.004855047960047393
Random: 0.10296205183842413
Same keys: 0.0034818929132122674


This is a partial review about some things I saw reading through your code fast.

The setter of your Count property shouldn't be public, because I could set it to one million when there's only one element in the queue.

You should specify the accessibility modifier for your member field, I guess it is private int startingPos, and I think you should put it at the top of your class, it is easier to read this way.

I don't think you should expose methods Shrink and Grow as they aren't part of a Queue but more of its implementation. Exposing these methods imply that you use an Array behind and the users of your class shouldn't know about this.

Also, in your Enqueue method, you grow your array every time your array is half filled, it is overkill. You should expand it only when the current array is full, otherwise you will always have half your array wasted.


Jerry Coffin has already pointed out that your current code leaks memory all over the place, which could certainly be slowing it down (since the heap allocator will have to go get more and more and more memory to feed the leaky code, instead of just reusing the same memory every time).

Consider using std::unordered_map<std::wstring, unsigned int>, as a hash lookup is likely to be O(1) and faster than the O(lg N) lookup associated with a std::map (which is basically the same thing as Java's TreeMap).

Move semantics are your friend. Use them to eliminate all the expensive reallocations and memcpys that are happening in your code. I count three memcpys: once inside RetrieveData, then again from data into str, then again from str into map_columns.

Minor nit: Declare your variables in the smallest, tightest scopes possible; this will aid the optimizer as well as helping the human reader understand the code.

Putting it all together, we get something like this:

std::unordered_map<std::wstring, unsigned int> map_columns;

do {
    unsigned int id;
    RetrieveID(&id);
    unsigned long len;
    RetrieveData(nullptr, 0, &len);
    assert(len % 2 == 0);  // len is measured in 2-byte units
    std::wstring data((len/2)+1);
    RetrieveData(data.data(), len, &len);
    map_columns.emplace(std::move(data), id);
} while (MoveNext());

(You might need to cast data.data() to (void*) or (char*); I don't know. You might also want to see whether the third argument to RetrieveData can be nullptr; or, if not, maybe you should use a temporary variable and assert that the new value is exactly the same as the old value, since it would be Very Bad if that weren't true.)

Oh, and I strongly suspect that you're eventually going to run into problems where you're looking up a Unicode string in your map and you don't find it when you thought you would, because of Unicode normalization issues. So, be prepared for that, if you can.


First and foremost your code is solving a different problem from the one stated in the question Get all the possible palindromes of a string or at least that's what it looks like and as pointed in my comments you need to provide more details and context about the code.

I will try to make a few points concerning your existing code aside from it being overly-complicated :

Do you really need an iterator here ? What's the point of saving the state of this code ? You clearly want all the possible palindromes from a specified string which to me sounds like I would receive a List<string> containing all the palindromes in there.
Usually converting string to char array is redundant but if you really need to do that you are better off using string.ToCharArray() instead of string.ToArray() detailed explanation why is given here.
Contains() is O(n) operation so you should avoid it if possible
It might be a good idea to replace that Tuple<string, int> with a class, but I'm not sure what is the point of having it in the first place.

I will provide an alternative solution to the problem :

Get all the possible palindromes of a string with length more than 1.

First let's start by declaring a method that decides if a string is a palindrome.

private static bool IsPalindrome(string input)
{
    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] != input[input.Length - 1 - i])
        {
            return false;
        }
    }
    return true;
}

Here we are making use of the fact that string is already a char[] and we can simply avoid the redundant call ToCharArray(). Also we are using only a single for loop and we are returning as soon as we find 2 different characters to increase performance.

This can also be converted to a one-liner using LINQ

private static bool IsPalindrome(string input)
{
    return !input.Where((t, i) => t != input[input.Length - 1 - i]).Any();
}

or with C# 6

private static bool IsPalindrome(string input) => !input.Where((t, i) => t != input[input.Length - 1 - i]).Any();

Next we need to actually make use of that method and get all of the possible palindromes of a string :

private static List<string> GetPalindromes(string source)
{
    List<string> subsets = new List<string>();
    for (int i = 0; i < source.Length - 1; i++)
    {
        for (int j = i + 1; j <= source.Length; j++)
        {
            if (j - i > 1 && source[j - 1] == source[i])
            {
                string currentSubset = source.Substring(i, j - i);
                if (IsPalindrome(currentSubset))
                {
                    subsets.Add(currentSubset);
                }
            }
        }
    }
    return subsets;
}

This chunk of code is what I would like to have as I explained in my first point but if you really need an iterator :

public static IEnumerable<string> GetPalindromes(this string source)
{
    for (int i = 0; i < source.Length - 1; i++)
    {
        for (int j = i + 1; j <= source.Length; j++)
        {
            if (j - i > 1 && source[j - 1] == source[i])
            {
                string currentSubset = source.Substring(i, j - i);
                if (IsPalindrome(currentSubset))
                {
                    yield return currentSubset;
                }
            }
        }
    }
}


An attempt to extend an enum to prevent branching without violating the Open-Closed principle

It's really hard to tell which parts of your code are the problem you are trying to solve, and which parts are the example.  I think that's a hint that the solution has made things worse, rather than better.

Attempting to summarize your constraint - you want to use an enum to select the appropriate behavior to use at some point in the code, but you don't want to use a switch statement, and you don't want to have to modify the enum to achieve the new behavior.

If so, I think an EnumMap should serve nicely.

private static final EnumMap<MyEnum, TwoArgFunction<Integer,Integer,Integer>> lookup = new EnumMap<MyEnum, TwoArgFunction> (MyEnum.class);

static {
    lookup.put(MyEnum.FOO, new TwoArgFunction<Integer,Integer,Integer> () {
        Integer apply (Integer lhs, Integer rhs) {
            return lhs.intValue() - rhs.intValue();
        }
    ) ;

    lookup.put(MyEnum.BAR, new TwoArgFunction<Integer,Integer,Integer> () {
        Integer apply (Integer lhs, Integer rhs) {
            return lhs.intValue() + rhs.intValue();
        }
    ) ;
}

public static class SomeObject {
    ...
    public int doMath(int value) {
        return lookup.get(type).apply(value, param);
    }
}

If you really want to use a visitor based approach, you should probably refactor the abstract methods to an interface; which would allow you to extend the existing vocabulary of enums without actually needing to change MyEnum at all.

interface Visitable {
    public abstract <R, A> R visit(OneEnumVisitor<R, A> visitor, A args);
    public abstract <R, A, B> R visit(TwoEnumVisitor<R, A, B> visitor, A argOne, B argTwo);
}

public static enum MyEnum implements Visitable {
    FOO { ... },
    BAR { ... };
}

public static class SomeObject {
    private final Visitable<Integer,Integer,Integer> type;
    private final int param;

    public SomeObject(Visitable<Integer,Integer,Integer> type, int param) {
        this.type = type;
        this.param = param;
    }

    public int doMath(int value) {
          return type.visit(NewMethod.INSTANCE, value, param);
    }
}

Which in turn allows other programmers to introduce their own enums that can be used by SomeObject

public static enum HisEnum implements Visitable {
    BAZ {...}
}


Array duplicate removal for duplicates exceeding `N`-number

As you expected, there is a much simpler way to do this.

Create a map where the keys are the numbers in the array and the value is the number of times each number appears in the array.
Filter the input array for any numbers that appear less than X times.

function removeMany(numbers, max) {
    const numberMap = numbers.reduce((map, num) => {
        map[num] = map[num] ? map[num] + 1 : 1;
        return map;
    }, []);

    return numbers.filter(num => numberMap[num] < max);
}

const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers, 3));


Here are some advices regarding the D3 part of the code:

Use scales!

Your if... else logic for filling the rectangles is cumbersome and luckily unnecessary: you can use a scale, in that case a threshold scale:

var color = d3.scaleThreshold()
    .range(["#F8B195", "#F67280", "#C06C84", "#6C5B7B", "#355C7D"])
    .domain([0.5, 0.55, 0.59, 0.62]);

Then, you can do just this in the attr method:

.attr("fill", function(d) {
    return d[1] === 0 ? "#2A363B" : color(d[1])
});

Do the same for the positions. Right now, you're using a lot of magic numbers everywhere: for translating the groups, positioning the rectangles and setting their width/height.

Instead of that, set up band scales:

var horizontalGrid = d3.scaleBand()
    .range([100, 400])
    .domain(d3.range(cols))
    .padding(0.1);

var verticalGrid = d3.scaleBand()
    .range([0, 300])
    .domain(d3.range(rows))
    .padding(0.1);

Using them for translating the groups...

.attr("transform", function(_, i) {
    return "translate(" + horizontalGrid(i) + ")"
})

...and positioning the rectangles, as well as setting the dimensions:

.attr("y", function(d, i) {
    return verticalGrid(i);
})
.attr("width", horizontalGrid.bandwidth())
.attr("height", verticalGrid.bandwidth());

Finally, two important advices:

Always name your selections

That's very important when the visualisation becomes more and more complex. For instance, you should do:

var groups = svg.selectAll("g")
    //etc...

Break your selections

By breaking your selections not only you can easily reference the correct selection, but you can also avoid things (silently) breaking. And it's way easy to maintain. For instance, in your code:

var groups = svg.selectAll("g")
    //etc...

var rects = groups.selectAll("rect")
    //etc...

Now you have two selections, groups (which refers to the containing <g> elements) and rects (which refers to the rectangles).

Select nothing

You read it right. If you don't plan to have an update selection here, just select nothing in your enter selections, or for a cleaner code select null. So, since you're not selecting anything, you have an enter selection which always contains all the data points, and a way faster code.

So, the move snippet becomes:

var groups = svg.selectAll(null)
    //etc...

var rects = groups.selectAll(null)
    //etc...

If you want to read more about selectAll(null) read my explanation here: Selecting null: what is the reason behind 'selectAll(null)' in D3.js?.

Demo

Here is your code with those changes:

var data = [
  [
    ["Arsenal", 0.0],
    ["Chelsea", 0.6014876082652767],
    ["Liverpool", 0.5204181171517794],
    ["ManchesterCity", 0.549210189254557],
    ["ManchesterUnited", 0.5440890632512689],
    ["Tottenham", 0.6304670189118691]
  ],
  [
    ["Arsenal", 0.6014876082652767],
    ["Chelsea", 0.0],
    ["Liverpool", 0.5507313736526684],
    ["ManchesterCity", 0.5559069243804156],
    ["MancheserUnited", 0.5231358671618266],
    ["Tottenham", 0.6508134781353688]
  ],
  [
    ["Arsenal", 0.5204181171517794],
    ["Chelsea", 0.5507313736526684],
    ["Liverpool", 0.0],
    ["ManchesterCity", 0.49759390310994533],
    ["MancheserUnited", 0.4787550034617063],
    ["Tottenham", 0.5749363562907429]
  ],
  [
    ["Arsenal", 0.549210189254557],
    ["Chelsea", 0.5559069243804156],
    ["Liverpool", 0.49759390310994533],
    ["ManchesterCity", 0.0, ],
    ["MancheserUnited", 0.50215325905151],
    ["Tottenham", 0.5802928689025063]
  ],
  [
    ["Arsenal", 0.5440890632512689],
    ["Chelsea", 0.5231358671618266],
    ["Liverpool", 0.4787550034617063],
    ["ManchesterCity", 0.50215325905151],
    ["MancheserUnited", 0.0],
    ["Tottenham", 0.5497016431211542]
  ],
  [
    ["Arsenal", 0.6304670189118691],
    ["Chelsea", 0.6508134781353688],
    ["Liverpool", 0.5749363562907429],
    ["ManchesterCity", 0.5802928689025063],
    ["MancheserUnited", 0.5497016431211542],
    ["Tottenham", 0.0]
  ]
];

var teams = ["ARS", "CHE", "LIV", "MCI", "MUN", "TOT"];

var width = 600,
  height = 500;

var cols = data.length;
var rows = data.length;
var cellSize = 55;

var horizontalGrid = d3.scaleBand()
  .range([100, 400])
  .domain(d3.range(cols))
  .padding(0.1);

var verticalGrid = d3.scaleBand()
  .range([0, 300])
  .domain(d3.range(rows))
  .padding(0.1);

var color = d3.scaleThreshold()
  .range(["#F8B195", "#F67280", "#C06C84", "#6C5B7B", "#355C7D"])
  .domain([0.5, 0.55, 0.59, 0.62])

var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height)

var groups = svg.selectAll(null)
  .data(data)
  .enter()
  .append("g")
  .attr("transform", function(_, i) {
    return "translate(" + horizontalGrid(i) + ")"
  });

var rects = groups.selectAll(null)
  .data(function(d) {
    return d;
  })
  .enter()
  .append("rect")
  .attr("fill", function(d) {
    return d[1] === 0 ? "#2A363B" : color(d[1])
  })
  .attr("y", function(d, i) {
    return verticalGrid(i);
  })
  .attr("width", horizontalGrid.bandwidth())
  .attr("height", verticalGrid.bandwidth());
<script src="https://d3js.org/d3.v5.min.js"></script>


General notes

Always prefix your functions with the name of your package or project, e.g. tagariffic-create-tag-table and so on. Emacs has no package scoping.
Whenever possible (i.e. in the absence of mutual recursion), define your functions before using them. It's a lot clearer for the reader. It's also necessary if you ever define macros.
You're using some functions from the cl package, so you should start with (require 'cl).
The usual style for predicates in Lisp is name-p, not name? (that's Scheme).
Emacs has functions to manipulate file and directory names. Use them rather than going around concatenating slashes; this way your code will work on exotic platforms such as Windows.

Finding the tags file

Emacs 23 has a function locate-dominating-file (in files.el).

  Look up the directory hierarchy from FILE for a file named NAME.
  Stop at the first parent directory containing a file NAME,
  and return the directory.  Return nil if not found.

Your (find-parent-tags default-directory) is almost equivalent to (locate-dominating-file (buffer-file-name) "TAGS"). If you want to use the current directory rather than the directory of the current buffer's file (they're almost always the same), use (locate-dominating-file (concat (default-directory) ".") "TAGS"). locate-dominating-file stops at your home directory, too.

The code you posted does nothing with the tags-file variable. Did you mean to run the tag generation command in that directory, or failing that in the current directory? If so, this should do it:

(let ((default-directory (if tags-file (file-name-directory tags-file) default-directory)))
  (shell-command …))

From file type to shell commands

Rather than build in an exception for Haskell, the usual style would be to define an alist from extensions to commands.

(defvar tagariffic-command-alist
  '(("hs" . "… hasktags …")
    (t . "… etags …")))

However, there's a better approach than separate commands for each type; see below.

The shell commands

Your hasktags command will choke on file or directory names that contain shell special characters: \[?* and whitespace. This isn't very common in source trees, but it could happen. Generally speaking, never use command substitution to generate a list of file names. Instead, let find call the command.

find . -type f -name '*.hs' -exec hasktags --ignore-close-implementation --etags {} +

A second problem is that if there are too many files, the command you wrote will die of a command line too long error; the one I just showed will run hasktags several times with command lines of a permitted size, causing the tag file to be overwritten. As a workaround, start by creating an empty tags file and tell hasktags to append to the tags file.

: >TAGS
find . -type f -name '*.hs' -exec hasktags --ignore-close-implementation -e -a {} +

An improvement to the find commands would be to ignore certain directories belonging to version control systems. Especially with svn, this could speed things up.

find . -type d \( -name .bzr -o -name .git -o -name .hg -o -name .svn -o -name CVS -o -name _darcs \) -prune -o \
       -type f …

Above I mentioned a different approach to choosing the tag generation command. Your approach assumes that a given project will be in a single language. It's easy enough to cater for mixed-language projects: build a single tags file containing the output generated by etags and hasktags.

: >TAGS
find . -type d \( -name .bzr -o … \) -prune -o \
       -type f -name '*.hs' -exec hasktags -e -a {} + -o \
       -type f \( -name '*.[CScls]' -o -name '*.el' -o … \) -exec etags {} +


There's a method in XNA called MathHelper.Clamp that does what you need. I understand if you don't want to import XNA libraries for this one function, though. You can do this with extension methods. Here's an implementation that uses generics (so you can apply it to various types) so you can use it for ints, longs, anything that implements IComparable

static class Extensions
{
    public static T Clamp<T> (this T self, T min, T max) where T: IComparable
    {
        if (self.CompareTo( min) <0)
            return min;
        return self.CompareTo(max) > 0 ? max : self;
    }
}


Welcome to CodeReview, and greetings! Your code looks nice: it is well indented, mostly PEP8-conformant, and has clear names. I suspect you may not have spent enough time in Atlantic City or Las Vegas, however. ;-)

Encapsulation

You correctly guard your "main routine" code with if __name__ == '__main__' but you didn't bother to put all that code into a function. Please do so. Call it main if you like, but take the chance to wrap it all up into something that can be invoked from outside, for testing.

def main():
    ''' Play one hand of blackjack. '''
    deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']*4
    player = []
    dealer = []
    standing = False
    first_hand = True
    deal(deck, player, dealer)
    while True:
        display_info(player, dealer, standing)
        results(player, dealer, first_hand, standing)
        hit_stand(deck, player, dealer, first_hand, standing)

if __name__ == '__main__':
    main()

Similarly, have a look at this:

if choice == '1':
    player.append(deck.pop())

And this:

while score(dealer) <= 16:
    dealer.append(deck.pop())

What are you doing there? That seems like another opportunity to use a name to describe what's happening:

if choice == '1':
    deal_card(shoe, player)

# ... and ...

while score(dealer) <= 16:
    deal_card(shoe, dealer)

Also, what's 16? Is that a magic number? Should it have a name? (Hint: yes!)

while score(dealer) <= DEALER_MINIMUM_SCORE:
    deal_card(shoe, dealer)

While we're looking at the hit_stand function, consider that it does two things:

def hit_stand(deck, player, dealer, hand, stand):
    print("What would you like to do")
    print("[1] - Hit\n[2] - Stand")
    choice = input("> ")

    ########## End of part 1, start of part 2 ##########

    hand = False
    if choice == '1':
        player.append(deck.pop())
    elif choice == '2':
        stand = True
        while score(dealer) <= 16:
            dealer.append(deck.pop())
        display_info(player, dealer, stand)
        results(player, dealer, hand, stand)

First, it asks for user input. Then it tries to update the game state based on that input. That's one thing too many!

Create separate functions for separate things. I know it may seem pointless when some of those functions are one line long. But it represents a chance for you to "write" an explanation of what you are doing, and it also provides a place to make changes to the behavior.

Also, consider that when you "grow" this blackjack game you will really want places to add behavior. There are many more possibilities than "hit or stand" at the table!

And always remember, user input is unreliable! You have to validate it. What if I type "hit" or "stand" instead of 1 or 2?

Control Flow

You don't actually have an exit condition for your while loop. Instead, you are relying on calls to sys.exit() from lower in your code. That's not going to work for very long as your code complexity grows. Instead, why not create a boolean variable still_playing = True and use while still_playing: as your loop condition. Then you can change that value when it's appropriate.

And your program structure doesn't really resemble the flow of a blackjack game. At a blackjack table, the dealer deals starting cards to all the players, then each player "plays" their entire game, then the dealer "plays" according to his rules, then the results are evaluated. You jammed your "dealer plays" element into the hit_stand function. Pry it loose! Make your flow look more like the real flow of the table, and it will be easier to understand and easier to extend.

Data Flow

In Pascal, a programming language we used in that last millennium by training dinosaurs to interpret the statements for us, there were two kinds of subroutines, procedures and functions. The difference was that a function could return a value, while a procedure just executed statements with no returned result. That discrimination doesn't exist in Python: you can do either thing, but it all starts with def. Regardless, you seem to write only subroutines that do not return values. I think you should change that.

Creating and shuffling the deck is a place where a function could be put to good use, especially if you grow your game. Just write:

shoe = new_shoe()

or later:

shuffle_shoe(shoe)

(If you can't tell, this is heading towards a Shoe class. That will come in a much later review. Also: a shoe is what the dealer takes the cards from.)

Speaking of data, have a look at this:

def hit_stand(deck, player, dealer, hand, stand):
    print("What would you like to do")
    print("[1] - Hit\n[2] - Stand")
    choice = input("> ")
    hand = False

Notice that you take a hand parameter, do nothing with it, and then set it to False? What's up with that? The only thing you use it for is to pass it down to results, but you could just as well write results(..., False, ...) and not bother with the hand parameter.

Also, have a look at the results subroutine. You call it in the middle of the loop, right after displaying the hands. But you've divided showing the hands and evaluating them, when that's kind of the same thing. And you're ignoring the distinction between "showing the current situation" and "wrapping up the end of the game." I'd suggest that your checking for blackjack and for busting should go near where you deal the cards, and should update the loop control variable.

Game Flow

There are a few aspects of blackjack that you are missing, even at this simple level. First, check for and announce blackjack, for both the dealer and the player! If a player gets blackjack, there's no Hit/Stand question, there's only the question of whether the dealer pushes. And if the dealer gets blackjack, the game is over before it began. So check that first.

The obvious extras, like assigning and displaying card suits as well as ranks, multiple players, support for splits, doubling down, insurance, surrendering, etc., would all take you away from a "simple" blackjack game. But your code should be organized in such a way that it is simple to add those features!

Update:

To answer your question from the comments,

  Also, how do I handle the choice variable in the second function if I split hit_stand() as you suggested? And how results() should look like after I make still_playing Boolean?

Let's say hit_or_stand becomes a separate function. You would write something like:

def hit_or_stand():
    while True:
        ans = input("Hit or stand? ").lower()
        if ans in ('hit', 'stand'):
            return ans

# In your main loop:

player_stands = False
while not player_stands:
    # stuff like before
    if hit_or_stand() == 'stand':
        player_stands = True

    if not player_stands:
        deal_one_card(shoe, player)
        if score(player) > 21:
            break

# After loop: dealer takes cards, etc.
results()

The results can stay mostly the same. But some of your passed in variables are not needed, since you can compute them from the other data. For example, if the len(player) is 2, that's the first_hand flag. What's key is that results is outside the loop, not inside. You print the results after breaking/exiting from the loop.


MS Access SQL query for active assigned cases

I can't see any major flaw in this query.

I would just make the Jointures like this, as it's more clear :

SELECT
    sites.city,
    employees.[first name],
    employees.[last name],
    cases.[assigned to],
    cases.ref,
    cases.status,
    cases.priority,
    cases.[opened date],
    Round(Now()-cases.[opened date],0) AS Age
FROM ((cases
LEFT JOIN employees ON cases.[assigned to] = employees.username)
LEFT JOIN sites ON employees.site = sites.site)
WHERE cases.[assigned to]<>"Not Assigned"
  AND cases.status="Active"
  AND cases.priority<>"first contact"
ORDER BY
    sites.city,
    employees.[first name],
    employees.[last name],
    cases.[opened date] desc;

If you can't have any case with non existing employees and sites, it's better to change your 2 LEFT JOIN into INNER JOIN. Just throw the 2 queries and compare the results.

In your WHERE clause, having some <> is generally inefficient on large tables. It's always better to make a IN() and list all the possibilities excluding "Not assigned" or "first contact" :

If  cases.[assigned to] can only contain an employee username or "Not Assigned", then just doing an INNER JOIN on the employee table will automatically filter the not assigned and you don't need to specify it in the WHERE clause.
if you have a limited number of case.priority values, list them all but "first contact" : AND cases.priority IN ("priority1", "super urgent", "can wait")

For the Age, if you want to compute the days from your open_date, it's better to do :

dateDiff("d",Now(),cases.[opened date]) AS Age

you can also concatenate the first and last name in one column:

 (employees.[last name] & ' ' & employees.[first name]) AS EmpName,

That's all what comes to my mind.


Running a block of code on every interval except the first iteration

Initialize the first byte, and then start the loop from 1.....

You may also want to do a bit-check instead of modulo, but they may be equally fast...

if (dataSize > 0) {
    data[0] ^= key;
}
for (int i = 1; i < dataSize; i++) {

   // Increase the key as per the algorithm
   if (i & 3 == 0) {
      key *= 13
   }

   // Shift over i bytes, as per the algorithm
   data[i] ^= key >> (8 * (i % 4));
}

EDIT:

I have seen the following done (translating from memory of a C program)... this has been known to be able to compile down to SIMD-using instructions on supporting compilers, etc.

for (int i = 0; i < dataSize - 3; i+=4) {

   // Shift over i bytes, as per the algorithm
   data[i + 0] ^= key; // >> (   0);
   data[i + 1] ^= key >> (   8);
   data[i + 2] ^= key >> (  16);
   data[i + 3] ^= key >> (  24);

   key *= 13

}

// handle up to 3 remaining bytes.....
for (int i = dataSize - (dataSize & 3); i < dataSize; i++) {
    data[i] ^= key >> (8 * (i & 3));
}


Well, of course your code is too slow, it's O(n²) but should be O(n):
Unless you already found a run of the same length, you don't skip to the end of the run!

Your inner for-loop only tests whether you are beyond your list after already having read there. That's slightly too late, rearrange that.

A side-question: Why do you insist on the dataset not being empty?

Why do you call your mode max_value? That's strange.

Restrict the scope of your values to the minimum you need: If it's not in scope, there's nothing for you to keep track of, allowing you to concentrate on other issues.

Consider investing in a bit more whitespace, especially around binary operators.

You know that true is 1 and false is 0?

Never use ; as the empty statement: It always looks suspicious. Either put a comment before it /**/; or use a block {} instead.


Get metadata from an Icecast radio stream

def radioPoller():

Python convention says that function names should be lowercase_with_undescores. Also, they should be verb, so: poll_radio would be better

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))

I recommend not using s as its not obvious what that means.

    finalData=[]

Python convention, local names should be lowercase_with_underscores.

    f=open("/media/hdd1/data.txt","a")

Again, don't use single letter variable names.

    s.send(msg1)                                 #sending http request

Instead of doing HTTP requests yourself, it'd make more sense to use urllib2 to do it for you. That way it'd take care of parsing etc.
Where is msg1 coming from? Also, you don't know that this sent all the data. To be sure all data was sent, use s.sendall

    data=""
    while len(data)<1024:
        data=s.recv(1024)               #recieving a few characters

Shouldn't you be using +=?

    t=data.find("metaint")                       #finding the metaint response header
    data=data[t+8:]                      #jumping 8 characters to the end of the string

    splitter="\r\n"                         # to split the contents and find when header ends and
    data1=data.split(splitter)                      #data1 stores the splitted data. First list has length and last has data

Why assign splitter to a local variable? just pass the constant.

    metaInt=int(data1[0])                      #find the metadata interval byte length
    #print metaInt

Rather then mucking with this use, use python's tool to parse the headers for you.

    finalData.append(data1[len(data1)-1])           #contains only the data part

You can use data1[-1] for the same result.

    lengthTotal= len(finalData[0])                  #length of data we have

    #print "total data is", lengthTotal,"\n"

    #print "TOtal bytes we should get is", (metaInt+4080),"\n"

Don't leave dead code in comments

    while lengthTotal<(metaInt+4080):
        data = s.recv(8192)

        lengthTotal=lengthTotal+len(data)
        #print "Total length now is", lengthTotal
        finalData.append(data)

In this case I suggest using StringIO rather than a list.

    print finalData
    string12=''.join(finalData)

Don't use meaningless names

    metaLen=ord(string12[metaInt])
    #print "This is multiplier", metaLen, "No of characters to read ", (metaLen*16)

    metaString=string12[metaInt+1:metaInt+1+(metaLen*16)]
    metaString=metaString+"\r\n"

    #print "Extracted String is \n", metaString

    f.write(str(metaString))

It's already a string, don't pass it to str

    s.close
    f.close

These last two don't do anything.

Here's my reworking of your code:

def parse_headers(response):
    headers = {}
    while True:
        line = response.readline()
        if line == '\r\n':
            break # end of headers
        if ':' in line:
            key, value = line.split(':', 1)
            headers[key] = value
    return headers

def poll_radio():
    request = urllib2.Request("http://sc.buddharadio.com:80/", headers = {
        'User-Agent' : 'User-Agent: VLC/2.0.5 LibVLC/2.0.5',
        'Icy-MetaData' : '1',
        'Range' : 'bytes=0-',
    })
    # the connection will be close on exit from with block
    with contextlib.closing(urllib2.urlopen(request)) as response:

        headers = parse_headers(response)

        meta_interval = int(headers['icy-metaint'])
        response.read(meta_interval) # throw away the data until the meta interval

        length = ord(response.read(1)) * 16 # length is encoded in the stream
        metadata = response.read(length)
        print metadata


A very secure procedural MySQLI login script against injections

You're not checking whether $_POST[..] exists at all or whether any data has been submitted via POST, this may cause Undefined index notices.
You're not supposed to use empty on variables that you're explicitly declaring. empty is shorthand for !isset($var) || !$var. Since your variables are guaranteed to be set (you define them in the previous two lines), no need to suppress error reporting here with empty.
You don't need to clean a username or password against any sort of injection. Injection issues must be mitigated by properly escaping data in the right context, not by restricting the allowed characters used. If you have a specific business rule for restricting allowed characters so be it, but injection prevention is not it.
You're MySQL-escaping the values before you're checking for their validity. You need to do that in the opposite order. Escaping is always the last thing you do. There's no real issue in this case, since you're not modifying the string after escaping and your validity check isn't influenced either; but you should still stick to that rule.
You're using an inadequate password hash. Use password_hash instead.
You could be using a switch instead of the if..else chain.
You really should be using prepared statements to avoid escaping altogether. I know you're trying to take it slow, but you (should) have to make that move eventually, so why not now?

You may want to read:

The Great Escapism (Or: What You Need To Know To Work With Text Within Text)
The Definitive Guide To PHP's isset And empty

In summary, I'd write it like this (using procedural style for your benefit):

if (!isset($_POST['form_user'], $_POST['form_password'])) {
    header('Location: index.php?error=1');
    exit;
}

session_start();
include 'database/connection.php';

$stmt = mysqli_prepare($database, 'SELECT * FROM `accounts` WHERE `member` = ?');
mysqli_stmt_bind_param($stmt, 's', $_POST['form_user']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);

if (!$user) {
    header('Location: index.php?error=4');
    exit;
}

if (!password_verify($_POST['form_password'], $user['password'])) {
    header('Location: index.php?error=5');
    exit;
}

$_SESSION['username'] = $user['member'];

switch ($user['privilege']) {
    case 'USER':
        header('Location: users/index.php');
        exit;
    case 'ADMIN':
        header('Location: admins/index.php');
        exit;
    case 'MOD':
        header('Location: mods/index.php');
        exit;
    default:
        header('Location: kick.php?error=6');
        exit;
}


Creating json objects with undefined properties

To make your code a bit more accurate you could run a function before every call to firebase (this is the main reason you need it) and create a new object with only defined props

function getDefinedProps(obj) {
  var o = {}
  for (key in obj) {
    if (obj[key] !== undefined)
      o[key] = obj[key]
  }

  return o;
}


As Jef Vanzella mentioned, exceptions are for unexpected bad things, not for jumping out of control flow. Hence the second option is better, but it is still substandard code.

Instead of using this, you should have a meaningful parameter name in your function declaration.

Also, you could simply return the falsey !ui instead of !valid.

Finally, not many people know that returning false stops the iteration, that deserves a comment.

Now imagine that your data structure was Cache -> Orders -> Shipments -> Items then you could write:

var ui;

//Returning false to each() will stop the iteration
$.each(this._cache, function( order ) {
    $.each(order, function( shipment ) {
        $.each(shipment, function( item) {
            if (item.label.toLowerCase() === valueLowerCase) {
                ui = {item: $.extend({}, this) };
            }
            return !ui ;
        });
        return !ui ;
    });
    return !ui ;
});


Alternatives for checking if something is not None in Python

I thought the readme on dry-python/return did a good job of explaining the usage of the Maybe type.
The key to understanding Maybe is that it represents computations which might "go wrong" by not returning a value.
The bind method (bind_optional) in this library allows you to write code without having to worry about the result of the computation at any intermediate step, it handles the case where one of the computations returns None.
In the code you use to demonstrate the conditionals, you still have to handle the cases of None via an if statement, the use of if not None vs if Some isn't relevant. As a hypothetical consider a computation with many level of optional results from computation, you'd still have to implement the same level of nesting.
In the example from the documentation
user: Optional[User]

# Type hint here is optional, it only helps the reader here:
discount_program: Maybe['DiscountProgram'] = Maybe.from_optional(
    user,
).bind_optional(  # This won't be called if `user is None`
    lambda real_user: real_user.get_balance(),
).bind_optional(  # This won't be called if `real_user.get_balance()` is None
    lambda balance: balance.credit_amount(),
).bind_optional(  # And so on!
    lambda credit: choose_discount(credit) if credit > 0 else None,
)

the comments in the code say the same. You can imagine a library using a symbolic function name >>= with infix operators allowing the above code to be rewritten as

credit = user >>= (lambda real_user: real_user.get_balance())
              >>= (lambda balance: balance.credit_amount())
              >>= (lambda credit: choose_discount(credit) if credit > 0 else None)

IMO, you approach to utilizing getattr is more akin to programming in a "duck typing" style than functional.
I used the haskell wiki's description of the Maybe monad if you want to dig in further.


Minor suggestions:

public class UrlToken

The class has no instance data, so it could be made static:

public static class UrlToken

Microsoft's Naming Guidelines and their Framework Design Guidelines suggest not using underscores and also using PascalCasing for constants, so

    private const int BYTE_LENGTH = 32;

could be:

    private const int ByteLength = 32;

However, even that name doesn't tell us much of what it is for. Let's try again:

    private const int NumberOfRandomBytes = 32;

Typo/misspelling in the XML doc comment: "encoding" is written as "endcoding".

There is mixed curly brace formatting. Microsoft guidelines (see links above) suggest the opening and closing curly braces should be on their own line.

        using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) {

to:

        using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())
        {

By the way, kudos to you on your proper use of the using construct! Looks fantastic!


First of all, you are not supposed to modify the list in-place. Instead, return a shuffled copy of the original list. This is also checked by this doc test:

>>> cards[:12]  # Should not be changed
['A♡', 'A♢', 'A♤', 'A♧', '2♡', '2♢', '2♤', '2♧', '3♡', '3♢', '3♤', '3♧']

Furthermore, using recursion makes this overly complicated. After all, the solution to get the desired result is pretty simple: Cut the list in half and then take one item alternatively from each sublist. The first part is simple splicing, and ways to do the latter is covered in this question. So you could end up with this:

def shuffle (cards):
    # split the list in halves
    first, second = cards[:len(cards) // 2], cards[len(cards) // 2:]

    # combine them alternatively, e.g.
    return sum(map(list, zip(first, second)), [])

You can also do it without splitting the list by just iterating it alternatively from the beginning and from the middle:

def shuffle (cards):
    result = []
    half = len(cards) // 2
    for i in range(half):
        result.append(cards[i])
        result.append(cards[i + half])
    return result


Your code is pretty good. It has elements in it which are relatively sophisticated too. For example, the recursion is clear, and the midpoint function is "right" (that needs an explanation - there's a 'well known' midpoint bug that many midpoint calculations have, but yours does not).

I prefer 1-liner code to be braced, and yours is not. That's disappointing, because I don't like reviews that focus on that only.... but that's really all I can find wrong with your code style.

There are a number of technical problems though.

why throw an exception for an empty array? Why not return null?
you have not followed the instructions correctly... it is impossible for a 0, 1, or 2 element array to actually have a peak, since there is no i - 1 or i + 1 to compare against. Additionally, there is no peak in cases like [3, 2, 2, 3], since the 2's are not peaks, and the three's are at the edges.
your first if conditions are newLeft <= right and newRight >= left, and those are just messy.... your findUtil should have a recursion-terminating condition if (right < left) { return null; } and not spread it around in the method.
I am a pragmatist about OOP in Java... Objects are great, I agree, but there is no reason to have an instance for this code. A static method passing the input array in would be fine....:

public <E extends Comparable<? super E>> E findPeak(E[] data) { ....

Finally, about the algorithm. I am not convinced that it works... I have not run it, but I am pretty sure that the compareTo methods are the wrong way around... they should be < 0 and not > 0)....


Given some integers, find triplets where the product of two numbers equals the third number

Your combinations(…, 3) loop makes your algorithm O(N3).

It's easy to improve it to be O(N2).  The question is, essentially: for every pair of entries, how many occurrences of their product are in the list?  So, make an indexes data structure to help you find, in O(1) time, where the product might be located.

from collections import defaultdict
from itertools import combinations

a = [int(ai) for ai in input('Input: ').split()]

indexes = defaultdict(set)
for i, ai in enumerate(a):
    indexes[ai].add(i)

triplets = set()
for x, y in combinations(range(len(a)), 2):
    for z in indexes[a[x] * a[y]].difference([x, y]):
        triplets.add(tuple(sorted((x, y, z))))

print(len(triplets))

Here, I've chosen to stick closer to the notation used in the challenge itself, with a being the list, and x, y, z as the indexes of entries (but 0-based rather than 1-based).


Print the lexicographically smallest permutation that satisfies the given formation

If you print out the solutions for the first couple of numbers,
a pattern becomes obvious:

def print_first_imba(max_):
    """
    >>> print_first_imba(2)
    1 2
    >>> print_first_imba(3)
    2 1 3
    >>> print_first_imba(4)
    2 3 1 4
    >>> print_first_imba(5)
    3 2 4 1 5
    >>> print_first_imba(6)
    3 4 2 5 1 6
    >>> print_first_imba(7)
    4 3 5 2 6 1 7
    """

The pattern looks like:

given an input sequence 1, 2, 3, ..., n, and an empty output list
pop the last number from the sequence and prepend to the output
pop the first number from the sequence and prepend to the output
keep popping until there are no elements left in the sequence

That will be substantially faster than searching the permutation space.

The doc tests I wrote above should help a lot in implementing this alternative algorithm. Your current implementation passes these tests btw, if you reorganize your code to fit it into this method:

checksum = max_ + 1
list_ = range(1, max_ + 1)
for perm in permutations(list_):
    if check_condition(perm, checksum):
        print(" ".join(map(str, perm)))
        break

My alternative implementation also passes these tests:

from collections import deque

imba = deque()
highest = max_
lowest = 1
while lowest <= highest:
    imba.appendleft(highest)
    highest -= 1
    if lowest < highest:
        imba.appendleft(lowest)
        lowest += 1
print(" ".join(map(str, imba)))

In case you don't know, you can run doc tests with python -m doctest yourfile.py.

I also recommend to go a bit further and separate printing from the main logic, by renaming this method to get_first_imba and make it return perm instead of printing it.


Parametrization
DOWNLOAD_DIR is being used as a default for a command-line argument. This is surprising, since at first glance one would assume that this global constant is simply being used as the download directory value itself. It's less clutter and more obvious if you simply remove this global and write the string literal beside the default kwarg.
More pathlib
You're already using it, but you can benefit from it more. Rather than making a Path() here:
path = Path(parent / filename)

Use urllib.parse.urlparse to get you a ParseResult with a path component, since it's a more thorough and safe parsing method than bare split and you only care about path

Call path.rsplit('/', 1)[-1] - not split - on the path component to get the filename-like

Make a Path from the result

If you deeply care about image-likes, then check mypath.suffix for .png, etc.

Use / as you are now.

Set membership
if suffix in ("png", "jpg", "gif", "jpeg"):

should use a set for speed, and also because it more closely matches your meaning. Also, pathlib will need leading dots:
if suffix in {'.png', '.jpg', '.gif', '.jpeg'}:

Noisy failure
if not path.is_dir():
    return

does not help the user understand why the script quit with no message. Raise some kind of error here.
Fail-safe list construction
The first part of this expression:
[emoji.get("name"), *emoji.get("aliases", [])]

will not do what you want. If there is no 'name', a None will be inserted rather than nothing. A more "naive" approach that will actually work is:
names = emoji.get('aliases', [])
name = emoji.get('name')
if name is not None:
    names.append(name)

Order probably doesn't matter to you since you had been kicking off threads all at once.
Somewhat-related: is this -
src = emoji.get("src")

actually optional? I doubt it. Currently you require that it be an actual URL. Either use [] if you want this to keep being fatal, or:
src = emoji.get("src")
if src is not None:
    create_download_thread ...

List append of a comprehension
        threads += [create_download_thread(src, name, emoji_dir) for name in names]

creates a temporary list only to throw it away again once it's been appended. The following will use the generator but not materialize it to a temporary list:
threads.extend(create_download_thread(src, name, emoji_dir) for name in names)


Vectorize/speed-up exponentially weighted covariance calculation in R

A key performance bottleneck in your code is your calculation of the Cov_t^{k,l} values:

Sum <- 0
for(j in 1:i){ # calc sum of exponentially weighted average of past returns
  Sum <- Sum + (1-60/61)*(60/61)^(j-1)*(Data[i-(j-1),k] - means[k])*(Data[i-(j-1),l] - means[l])
}
Cov[k,l] <- Sum

You are summing from j=1 through j=i by looping through the values individually and adding them up. In R you can get significant speedups by using the vectorized sum function:

Cov[k,l] <- sum((1-60/61)*(60/61)^(0:(i-1))*(Data[i:1,k] - means[k])*(Data[i:1,l] - means[l]))

Additionally, this part of the code hard-codes the choice of delta=60/61, which may make it harder to see what the code is doing or update to another delta value. It would be best to pass delta to the function and then use delta instead of 60/61 in this expression. Here is the updated function:

rollEWCovMod <- function(Data, delta){
  res <- c()
  for(i in 1:nrow(Data)){ # Expanding window of data used to calc covariances
    means <-  colMeans(Data[1:i,])
    Cov <- matrix(0,nrow = ncol(Data),ncol=ncol(Data))
    for(k in 1:ncol(Data)){ # first data-column
      l <- k
      while(l <= ncol(Data)){ # second data-column
        # calc sum of exponentially weighted average of past returns
        Cov[k,l] <- sum((1-delta)*delta^(0:(i-1))*(Data[i:1,k] - means[k])*(Data[i:1,l] - means[l]))
        l <- l + 1
      }
    }
    res[[i]] <- Cov
  }
  return(res)
}

To see the performance improvements of the vectorized sum, we can benchmark with a 500 x 2 matrix:

Data <- data.frame(matrix(rnorm(1000),ncol = 2))
system.time(rollEWCov(Data))
#    user  system elapsed
#  11.300   0.103  12.031
system.time(rollEWCovMod(Data, 60/61))
#    user  system elapsed
#   0.142   0.006   0.149
all.equal(rollEWCov(Data), rollEWCovMod(Data, 60/61))
# [1] TRUE

We obtained a 80x speedup and got identical results to the original function.


Parse copied data from Excel using AutoHotkey

I realize this is an older question, but hopefully, this will help a future asker, if not the original asker.

I agree with your assessment of using StrSplit() and would recommend using a 2D array. This can be done using a nested parsing loop. Here is a working example of the data in your example (assuming the range was copied from Excel and not from your post):

f1::
aData := {} , nCt := 0 , clipboard := RegExReplace( clipboard , "`r" , "" )
Loop , Parse , clipboard , `n
{
    nCt++
    Loop , Parse , A_LoopField , `t
        aData[ nCt , A_Index ] := A_LoopField
}
Loop , % aData.Length()
    MsgBox , % aData[A_Index,1] . "`t" . aData[A_Index,2] . "`t" . aData[A_Index,3]
Return


It's tough to review only part of the code, because there are often small improvements which could be made but they depend on knowing the structure of the entire program -- for example, why are you using a tuple to pass around the positions ((upPosition, downPosition, leftPosition, rightPosition))? You'd likely be better off using a record type to encapsulate those values, since you'd only have to pass one variable around (the record) and it also facilitates structural matching which'll allow you to clean up some of your other functions.

The Direction enum would be much better as a discriminated union type (see the code below). Even though enums can define certain values (e.g., Up, Down, Left, Right) they can also take on any integer value by casting the value to the enum type. Discriminated union types also allow you to define a fixed set of values, but the F# type system ensures that your variables can have only the defined values -- which in turn, keeps you from having to use the wildcard pattern (_) to check for error conditions in your match statements.

Here's my version of your code -- it's largely the same, but I've changed Direction into a union type and moved the Reverse function into a new Direction module.

type Direction =
    | Up
    | Down
    | Left
    | Right

[<RequireQualifiedAccess; CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Direction =
    /// Reverses a specified direction.
    [<CompiledName("Reverse")>]
    let rev = function
        | Direction.Up ->
            Direction.Down
        | Direction.Down ->
            Direction.Up
        | Direction.Left ->
            Direction.Right
        | Direction.Right ->
            Direction.Left

[<CompiledName("Go")>]
let go myDirection filter pos =
    match myDirection with
    | x when x = filter ->
        pos
    | Direction.Up ->
        GoUp pos
    | Direction.Down ->
        GoDown pos
    | Direction.Left ->
        GoLeft pos
    | Direction.Right ->
        GoRight pos

let (upPosition, downPosition, leftPosition, rightPosition) =
    match myMove.MyDirection with
    | Direction.Up ->
        (GoUp y, y, GoLeft x, GoRight x)
    | Direction.Down->
        (y, GoDown y, GoLeft x, GoRight x)
    | Direction.Left ->
        (GoUp y, GoDown y, GoLeft x, x)
    | Direction.Right ->
        (GoUp y, GoDown y, x, GoRight x)

let (upPosition, downPosition, leftPosition, rightPosition) =
    let rev = Direction.rev myMove.MyDirection
    (go Direction.Up rev y, go Direction.Down rev y, go Direction.Left rev x, go Direction.Right rev x)

EDIT: Answers to your questions:

Normally, you can't have a module and a type with the same name within a certain namespace, but the [<CompilationRepresentation(...)>] attribute I used adds "Module" to the name of the compiled module type. So in this case, the Direction module would be compiled to a type called DirectionModule.
You could make rev a member function of the Direction type. However, in F# it's easier (in general) to consume module-based functions instead of type members because it works much better with F#'s type inference mechanism. In our example, if you had an instance of Direction you wouldn't be able to call myDirection.Reverse() unless you declared myDirection as a variable of type Direction (or the F# compiler was able to figure it out another way); if you call the module-based function (Direction.rev myDirection) F# can easily infer the type of the myDirection variable so you don't need any explicit type annotations.

If you're consuming this code from C#, then I'd write the code like this to get the best of both worlds:

type Direction =
    | Up
    | Down
    | Left
    | Right

    member this.Reverse () =
        match this with
        | Direction.Up ->
            Direction.Down
        | Direction.Down ->
            Direction.Up
        | Direction.Left ->
            Direction.Right
        | Direction.Right ->
            Direction.Left

[<RequireQualifiedAccess; CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module internal Direction =
    /// Reverses a specified direction.
    [<CompiledName("Reverse")>]
    let inline rev (dir : Direction) =
        dir.Reverse ()

In this version of the code, I've defined Reverse as a member on the direction type (making it easy to consume from C#), but I also have the module-based function which is easier to consume from F#. Note the module-based function is now marked inline; as it only calls the Reverse() member it makes sense for the F# compiler to emit code which directly calls Reverse(). Another way to think about this is that within this version of the code, the module-based rev function is only useful for type-inference purposes (but it is useful if you're using it from within F#).
[<CompiledName(...)>] is an attribute specific to F#; when you use it on a function, the F# compiler will compile the function so it has the name you've specified in the attribute. This is primarily used when you want to consume some F# code from C#; you can define your F# functions with idiomatic F# names (e.g., rev), but by applying this attribute the methods in the compiled assembly can have idiomatic C# names (e.g., Reverse) to make them easier to consume.


Join - order by vote-sum and check if user has voted

Schema

Your schema isn't well normalized: you shouldn't have network_name in the comments table when you already have network_id.

Non-standard GROUP BY

Standard SQL requires that when the query has a GROUP BY, all columns being selected must either be mentioned in the GROUP BY clause or be an aggregate function.  However, MySQL is sloppy, and allows non-sensical queries like yours that violate that rule, unless you enable the standard behaviour explicitly by setting the ONLY_FULL_GROUP_BY option on the server.  (When you write SELECT *, …, which created_at timestamp would you expect to appear in the results, for example?)

You wrote GROUP BY ( v.`foreign_id`), but GROUP BY c.id would make it more obvious that you want to group by comment.

Subselect

Subselects within the SELECT column list are a bit nasty, and can nearly always be expressed better.  In this case, I think that a COUNT() of votes whose user_id is 123 would do the job — and it doesn't require another join.

Indentation

More meaningful indentation would make the query easier to read.  You don't have to indent it the way I suggest, but you should do something better than nearly no indentation at all.

Suggested solution

SELECT c.id AS comment_id
     , SUM(v.value) AS votesum
     , COUNT(WHEN v.user_id = 123 THEN 1 END) > 0 AS user_voted_already
    FROM comments as c
        LEFT JOIN votes as v
            ON v.foreign_type = 'comment'
            AND v.foreign_id = c.id
    WHERE c.network_id = 3183
    GROUP BY c.id
    ORDER BY votesum DESC;


Learning PHP MVC: bootstrapping and front-controller

I would say you are generally on the right track but have some mixed responsibilities: there are some things in the front-controller that belong to the bootstrapping and some things in the front-controller that belong in the actual controller.

Also a major comment: I think as long as you are doing this you should take the time and also implement a dependency injection container (of some sort, even if a very simple one).  DI and Inversion of Control are standards in not just the PHP MVC world but also the OOP world in general.  As long as this is a learning exercise for you, you might as well learn another very critical component of such a system.  No bootstrapping/front-controller would be complete without proper use of dependency injection, if for no other reason that to enable proper unit/integration testing.

Starting at the beginning then:

A nitpick, but I would give your bootstrap file a namespace.  If it is using things from app\core, I think it makes sense for it to live in app\core itself.  Related to that: is this your index.php file, or is it included by your index.php file?  Personally I split things up a bit more even, and have the bootstrap simply initialize the app (i.e. require all necessary files, initialize error catchers, etc) and let the index.php file require the bootstrap file.  Then, I have the index.php file load and call the FrontController.  That's certainly not a requirement, but I find it to be helpful as you might have a couple different "environments" that run differently, but still require bootstrapping (i.e. command line, testing, and responding to web requests).
You have a lot of lines like this: realpath(__DIR__ .DS.'..'.DS.'..').  Many systems will define constants for these sorts of things in the bootstrap so that you don't have to repeat it so often (in particular because knowing where directories are is often needed by other parts of the system, i.e. file caching, uploads, etc...).
Because you are passing the router into the FrontController, you are already halfway to dependency injection.  However, you then have the FrontController directly build the database connection.  Especially since the database connection isn't used by the FrontController, there is no reason for the FrontController to be building it.  You make it public which implies that you intend for other things to get the database out of the FrontController, but it is not clear how they would access it, nor is this a good way of passing necessary resources back and forth.  Again, a DI container would fix all of these issues, and then you can have a class that is a simple wrapper around the PDO object, and which initializes the DB connection when it is actually needed. You just have to design your DI container so that you can make your database object a "singleton" which is only created once.
Your FrontController is initializing both the model and view.  Ignoring issues revolving around using a DI container to instantiate resources, it doesn't make sense for the FrontController to be doing anything with models or views at all.  The point of the FrontController is to act more like a directory.  It takes the route, determines what controller should be handling the route, and then defers execution to the actual controller assigned to the route.  The final controller is then responsible for instantiating models (if needed), calling views, etc.  As a for instance, what if a view isn't needed because a particular route represents an API call which returns JSON?
In essence, your biggest issue is that your front-controller is strongly coupled to the rest of your application, leaving no room for flexibility on how the application should respond to a given request.  Effectively, your system is requiring one model, view, and controller for every route.  It rarely works out that cleanly in practice, and so decoupling your FrontController from the rest of the application is a necessity.  Again, you should think of it more as a gatekeeper than as something that actually performs any actions itself.

All in all I would say that this is a good starting point.  You obviously have best-practices and design patterns in mind, and that is always a good thing.  From here on out it is all about understanding and implementing good SOLID principles, in particular a good division of labor and separation of concerns between all the various actors of your system.


Strongly-typed reading values from CSV DataTable

A few comments:

This method does way too much.  It is difficult to understand and will be difficult to debug and maintain.  Break it down into smaller methods that each have a single responsibility.
Use curly braces after your if and else statements.  This improves readability of the code and makes it less likely for other code to sneak in there in the future.
Can't your else statement just be a plain else with no if after it?  It seems like you want to put quotes around a string, and use the plain value for everything else.  Are there other requirements here?
The type of csvKeyValue could just be string, since it's pulling a value out of a string[]
No need for the call to .ToString() in your if branch
I would try to write the call to parameters.DataTableOriginal.Select only once.  Consider using your if/else to set a delimeter variable to either string.Empty or ', then write your query once like so:

DataRow[] rowsOriginal = parameters.DataTableOriginal.Select(
    DBSLEUTELVELDNAAM + "=" + delimeter + csvKeyValue + delimeter);


Calculate the closest point to many hyperbolic paraboloids

How would you change the function to improve its performance?

I agree that using masks differently could prove fruitful. Here is my suggestion. Currently the tolerance is a constant. Suppose we substitute it with cur_tol which starts out as e.g. 100 * tol, and change the loop exit criterion to (niter and mask.shape[0] AND cur_tol <= tol)? Then perform cur_tol /= 2 in each iteration. The idea is to have mask reference fewer elements during early updates, and for each iteration to simultaneously get closer to the answer AND include a potentially larger number of input values that will drive us closer to that answer. So we are lazy about evaluating a smaller number of points when we clearly are far from the answer, and cast a wider net as we approach closer to it.


There is nothing inherently wrong with foreach loops.

Alternatives might include:

Creating objects that contain the data and extend Iterator, and using that to recurse the options. The disadvantages are that it would be less efficient and would involve quite a lot more code. The advantage is it would make the foreach loops more readable; particularly whats inside them, once you give methods to each of the objects that extend Iterator that perform the action that happens within the foreach code.
use PHP array functions. This is probably the most efficient, but can make code painfully unreadable. I would not recommend this unless you desperately need greater efficiency.

By the way, one change I would make no matter what you do, is replace "magic constants" with named constants. E.g.:

if ( in_array( $menu_item[2], $new_menu_items ) ) {

becomes

define ('MEANINGFUL_NAME', 2);

// ....

if ( in_array( $menu_item[MEANINGFUL_NAME], $new_menu_items ) ) {

Otherwise, when you come back to look at the code after a long time, you will have no idea if each time you see a 2, whether they all refer to the same "thing" or not; in other words, say you want to change an aspect of it to be "3" instead, you will have to painstakingly work out what each bit of code does to see if it is a 2 that you need to change or not. (Using comments is a bad idea for this, as comments are easily forgotten to be changed, and it would have to be commented each time you have a magic number - the more you have, the more likely changes in code will not have corresponding comments changed

One final change I would make is perhaps splitting up the function into sub-functions, since doing that would mean you can give the functions names that describe the sub-process being performed. Putting that method and sub methods into an appropriate class could nicely tidy things up. While OOP can lead (IMO) to the very best code, if it's implemented badly it can be a nightmare to manage. Plenty of books on it, which I could recommend if you like. I have 5-10 books on it that I always keep by my side.

"Design Patterns" Gamma / Helm / Jhnson / Vlissides (1995)
"Patterns of Enterprise Application Architecture" Martin Fowler (2003)
"The pragmatic programmer" Hunt / Thomas (2000)
"Refactoring to patterns" Kerievsky (2005)
"Refactoring" - Martin Fowler (1999)
"OO Design Heuristics" - Arthur Riel (1996)
"Growing Object-Oriented Software Guided by Tests" - Freeman / Pryce (2009)

I would actually suggest first getting Freeman/Pryce, even if you find TDD doesn't really agree with you - their bibliography was very useful to me, and I picked and choose what suited me. There's a lot of controversy about TDD, but they'll show you why refactoring is such a powerful principle, and you can then try one or two books on patterns and refactoring. Choose one that seems to have patterns you think you'll be most likely to use.


Efficient Album Cover loading for ListView

Your lag will be coming from this line:

 Bitmap coverBitmap = BitmapFactory.decodeFile(cursor.getString(holder.column3));

Your right about doing it asyncrhonously.
You could also scale the image.

What you'll want to do is:

spawn a new thread
use a handler for when the bitmap has decoded
set the bitmap on the imageview in the callback

You could set the image to a spinner whilst it is loading.

An example of something similar is:

http://blog.blundellapps.co.uk/imageview-with-loading-spinner/

And an example of image scaling is:

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html#load-bitmap


How can I optimize this code that finds the GCD?

Assuming that findgcd is correctly implemented and that i and j are guaranteed to both be non-negative, findgcd(i, j) == j is equivalent to j != 0 && i % j == 0. That allows a further optimisation to a single loop, because the number of values in 1..n which are divisible by j is floor(n/j):

for (int j = 1; j <= n; j++)
{
    count += n;
    gcdCount += n / j;
}


Convert .NET DateTime to a string using ordinals

You can simplify it a bit and make a trivial improvement to performance (this will be noticeable if you call this method a lot).

public static string ToStringWithOrdinal(this DateTime d) {
  switch (d.Day) {
    case 1: case 21: case 31:
      return d.ToString("dd'st' MMMM yyyy");
    case 2: case 22:
      return d.ToString("dd'nd' MMMM yyyy");
    case 3: case 23:
      return d.ToString("dd'rd' MMMM yyyy");
    default:
      return d.ToString("dd'th' MMMM yyyy");
  }
}

As a side note this format doesn't read well to me. Normally I would write it as follows:

  October 11th 2011

Is this format common in the UK?


Slow data-processing and inefficient memory usage in .NET containers

Edit in response to OP comment above:

CreateCategoryClasses may appear to be slow because of the WaitOne calls.  You're essentially waiting waiting on either ParseCategories or AddIDF to complete before moving on. It would help if you could also post the ParseCategories method as well.  Otherwise, you're just adding stuff to collections, which generally shouldn't perform too bad, except for some of my comments below.

Original answer:

Some of this is performance suggestions, some is just general advice...

If you have one, run this through a performance profiler. This can point you directly to the lines that are using the most CPU time very quickly. Personally, I use ANTS from Red Gate.  Another good one is DotTrace from JetBrains.
Why is categoryClasses a ConcurrentQueue?  As a general rule, a Queue is used for removing the items as you process them. If you just need to loop over a collection (possibly multiple times), a List<T> would be a better choice. This would also avoid the call to ToList() each time through your secondWord loop.  ToList() will iterate through the entire collection every time you call it (granted it's only 5 element, but still...). This may also apply to result as well, depending on where else it might be used.
You call ElementAt() every time through your foreach loop in AddIDF, even though i isn't changing.  If you must use a ConcurrentQueue for categoryClasses, then ElementAt() is \$O(i)\$.  If you can use a List, then it will be \$O(1)\$.  You could save the current ConcurrentDictionary before the loop to avoid the repetitive indexing.
String comparisons are slow compared to integers and enums (your Where() calls in AddIDF). If you changed Category to an enum or integer (or possibly add a second property for comparison purposes), that would improve the count performance.
You pass an int into your AddIDF method, not an int?, so you can just do a direct cast to an int.  This avoids the .Value property everywhere you access the index in AddIDF.
sum is already a double, so there's no need to call Convert.ToDouble. Because sum is a double, temp will be a double, even if the result of Count is an int.
What is this 5 I keep seeing?  Typically it's good to assign this to a const value for clarity.


With regards to variable names and readability, I would recommend the following:

Change p to outputIndex
Change p1 to firstIndex
Change p2 to secondIndex
Change sizeFirst to firstSize
Change sizeSecond to secondSize


first of all remove your global use strict.

Why? Global use strict declarations can lead to big fails in your software.

From Mozilla website:

  This syntax has a trap that has already bitten a major site: it isn't possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only concatenating strict and non-strict scripts is problematic.

So what you can do is to use the module pattern:

var lsHelper = (function() {

    "use strict";
    let status = "available";
    let timeout = 5000;

    return {
       //Register a function by its name, itself (callback) and the needed time span for the check cycle
        RegisterLocalStorageFunction: function(name, callback) {

            //Set local storage items for function and its result
            resetFunction(name);

            //Setting the event
            window.addEventListener('storage', function(e) {
                //Getting the params or eventually just the status

                //Call the function if params are set and reset all
                if (e.key === name && e.newValue != status) {
                    let result = callback(e.newValue);
                    //Set result
                    localStorage.setItem(name + "Result", result);
                    //Reset call
                    localStorage.setItem(name, status);
                }
           });
       },
        CallLocalStorageFunction: function(name, params, callback) {
            //Check if the function is already called
            if (localStorage.getItem(name) == placeholder &&
                localStorage.getItem(name + "Result") == status) {

                //Call remote function
                localStorage.setItem(name, params);

                //Define timeout and event for future usage
                let timeout = {};
                let storageEvent = {};

                //Check in interval for result
                storageEvent = function(e) {
                    //Check wheter the result is set
                    if (e.key == name + "Result" && e.newValue != status) {
                        //Call callback with results
                        callback(e.newValue);

                        //Reset result in local storage
                        localStorage.setItem(name + "Result", status);

                        //Dismiss listener and timeout
                        clearTimeout(timeout);
                        window.removeEventListener('storage', storageEvent, false);
                    }
                }

                //Add listener to event
                window.addEventListener('storage', storageEvent);

                //Start timout to cancel listener if no result is set, hence no remote function was called
                timeout = setTimeout(function() {
                    //Dismiss interval
                    clearTimeout(timeout);
                    //Clean up
                    window.removeEventListener('storage', storageEvent, false);
                }, timeout);
            }
        },

        //Reset local storage values
        resetFunction: function(name) {
            localStorage.setItem(name, status);
            localStorage.setItem(name + "Result", status);
        }
    };
})();

Second. The name lsHelper does not tell what the function does. I think that localStorageHelper is a better name.


Main changes:

Assuming you keep an int length, check for size >= 0 in constructor IntArray(int size = 0);, and in void IntArray::insertBefore(int d, int index)
You thought about delete[] data in the destructor. However, there are other places in your code where data needs to be deleted: each time you change data's value, you need to deallocate what used to be pointed by data. Ie, delete[] data before any data =

You added data = new int[length]; in the copy constructor, so you've solved the out of bound issue, but introduced a memory leak instead. You need to deallocate data first.
Same for the assignment constructor.
resize had an out-of-bound issue you've fixed

Code used to be:

void IntArray::resize(unsigned int size){
    for(int i=length; i<size; i++){
        data[i] = 0;
    }
    length = size;
}

(Note: you're not supposed to edit your code, or put your updated code in a separate section, at the bottom of your question)

Opinion-based

Maybe use an unsigned type (like std::size_t) instead of the signed int for the length.

Pros:

You enforce the invariant "the length can only be positive"

Cons:

Special values (like -1 for "Index not found") will look like regular values, higher risk of underflow.
(see Herb Sutter comment at 44:30)

Other

Superfluous this-> in operator[](int index)
Style: pick one of length or getSize()to get the data length, but don't mix the two (Here length is fine, in classes where you'd like to make a check before accessing the value, getSomething() is better.
Add a const version of operator[](int index)
Don't add an extra space at the end of operator<< (which you removed by mistake)

Going further

It depends on the assignment.

Optimization: Introducing capacity to reduce the number of allocations/deallocations
Add iterators
Add convenience methods (bool empty() const;, int& front();)
Add typedefs like typedef int value_type (useful for for metaprogramming)
Add relationship operators (at least == and !=)

@glampert made excellent points I forgot, check his answer.


Using doParallel to cycle through *.rds files

Parallelization is not necessarily implemented nicely in R. However, it is far more ideal to use R's batch process than opening 10x Rstudio sessions as you saw (less of a resource drain per task).

Cores, cores, where art thou?

The first thing I would do is find out how many cores you have access to. Within this script 4 seem to be allocated. It is very important that you have at most or less than the total number of cores on your system for the parallel jobs to be appropriately scheduled.

# Find out how many cores exist
parallel::detectCores()

Speed

Speed-wise, I find the foreach iterator to consume more time than I really care for. The reason is because it has a lot of unnecessary overhead and combine operations that tend to dynamically grow objects. So, I normally just interface directly with R's parallel package's parLapply function.

Code

I realize that this is just a condensed example, however, without seeing everything, we really cannot give super specific feedback.

With that being said, you will probably end up with an error running this code since i is not defined within check(). Only x is in the function's scope.

Try to return some value to the foreach loop, e.g. an i value from check or a "pass-i", "fail-i" to figure out if a process fails.

Another bit to note is that the script is currently set to output to the input directory. Try to create dedicate directories for input and output. The reason for this is, if you were to re-run your script, the processed files would be included within the next run. (Unless the pattern specified by list.files is more specific to file nomenclature that you have.)

Also, since it seems like you are using spatial data. Is this a raster image that is contained within .rds? If so, could you get away with using a stack instead of the whole raster into memory?

Aside

If you are interested in learning more about how to parallelize with R, I would recommend looking over this slide deck (Disclaimer: I wrote it)

Edit

Per the submitter's comment that using lapply is not possible. Please note that a for loop in R is the same in this case as using an lapply. There are some benefits (speed being one) that make lapply typically better than using a for loop. Furthermore, the foreach here is really a cast over the parXapply statements.

library(parallel)
cl <- makeCluster(detectCores())

# Function
check <- function(x){
  df <- readRDS(paste0("./", x))
  df$var <- df$var*2
  saveRDS(df, paste0("./temp/", x))
}

# Directory where *.rds files are
files <- list.files("./")

# Obtain unique files
i = unique(files)

# lapply statement
lapply(i, FUN=check)

# parlapply
parLapply(cl, X=i, fun=check)

Edit 2

This edit is meant to show how to export functions or variables per submitter's issue. Since the submitter has not made available the functions or variables needed within the parallelization this is a generic example.

library(parallel)
cl <- makeCluster(detectCores())

# Load packages on cluster's R sessions
clusterEvalQ(cl, library(pkgname))

# Export functions or variables to cluster's R session
func <- function(a){
out <- a*a
return(out)
}

v = 1:10

clusterExport(cl,c("func","v"))

stopCluster(cl)


Your code is generally fine. I suspect you are not doing enough validation (for
example, to forbid negative values or multi-character keys). Also, if you want
to expand your toolkit, you can think about eliminating the duplication in your
code by generalizing the input collection process.
Collecting user input involves a few common elements: an input prompt, a
function to convert the string to a value, a function to validate that value,
an error message in the event of bad input, and possibly some other stuff (max
allowed attempts, fallback/default value in the event of bad input). If we
focus on just the basics, we end up with a function along the lines of this
sketch:
def get_input(convert, validate, prompt, errmsg):
    while True:
        try:
            x = convert(input(prompt + ': '))
            if validate(x):
                return x
            else:
                print(errmsg)
        except ValueError:
            print(errmsg)

With that in hand, all of the algorithmic detail will reside in that single
function, and your main() will be little more than straightforward,
step-by-step orchestration code.
def main():
    key = get_input(
        str.strip,
        lambda s: len(s) == 1,
        'Key to be autopressed',
        'Invalid, must be single character',
    )
    n_clicks = get_input(
        int,
        lambda n: n > 0,
        'Number of autopresses',
        'Invalid, must be positive integer',
    )
    delay = get_input(
        float,
        lambda n: n > 0,
        'Delay between autopresses',
        'Invalid, must be positive float',
    )
    auto_click(key, n_clicks, delay)

As shown in that sketch, I would also encourage you to favor a more compact
style in messages to users. Brevity usually scales better across a variety of
contexts than verbosity: it's easier to maintain; it's easier to make
consistent across an entire application; and most people don't appreciate
having to slog through long messages when an equally clear short one
is possible.
Finally, you might also consider whether input() is the best
mechanism to get this information from the user. In my experience,
it is almost always preferable to take such values from the
command-line, either from sys.argv directly or, more commonly,
using a library like argparse. The advantages
to this approach are numerous.


A few observations in no particular order:

I would consider redesigning the class so that it presents a static method: checkDay(day, month, year). There doesn't seem to be much benefit in requiring callers to create an instance of the class, bound to a particular date. If you do this, ensure you make your constructor private so that the class cannot be instantiated.
If you decide to stick with the current layout, then the fields day, month and year could be declared as final, since you don't adjust them at all within the class.
A minor point, but your constructor may be more readable if you use day, month and year rather than d, m and y.
Because your leapYear method is static, you should call it in a static way:

public boolean checkDay() {
  if (this.month == 2 && leapYear(this.year)) { // <----- here
    Months.getMap().put(this.month, 29);
  }

In general, you use this. more than is necessary. I guess it's a style issue, but generally code will only use this. when it's necessary to distinguish between local variables of the same name and class fields.
In your Months enum, you have a field named MonthNumber, but it should be monthNumber to match normal Java style.
You've created an enum for your month data, however this is used solely to populate a map. The rest of your code just uses the map. As a result, I would suggest you remove the enum and just stick with a map, unless you plan to extend this class in future and use the enum for other purposes. If you stick with using an enum, the map can be declared final.
It would be easier to read your leapYear method if you added some parentheses, rather than relying solely on operator precedence. You don't need the outer parentheses however:

return (y % 4 == 0) && ((y % 100 != 0) || (y % 400 == 0));

In your checkDay() method, I would avoid putting data into your map. Certainly you don't want to pollute your map if you plan to move to a static checkDay() method as discussed above. I would do something like this instead:

public boolean checkDay() {
  int daysInMonth =
      month == 2 && leapYear(year) ? 29 : Months.getMap().get(month);

  return day <= daysInMonth;
}

(Very minor...) Typically one would call your method isLeapYear rather than simply leapYear.


Extract strings from nested array in Perl

Your concept of "string" seems incomplete.  I would look to firm up that definition and precisely match the need.  Is "" a string?  Do you want "valid identifiers" (/^[^\d\W]\w+$/) or "plausible ASCII words"  (/^[A-Za-z]+$/) or just "not numbers"  (!/ ^ ( [+-]? \d* \.? \d+ (?:[Ee][+-]?\d+)? ) $/x)?

I like use warnings FATAL => 'all'; so that I don't miss a warning in the midst of other output.

A fat arrow between arguments of different purpose can enhance readability.

Coding in functional style (with grep and map instead of @output) is a natural fit to this kind of problem.

Plain old recursion is suited to the task and would obviate the need for experimental features.

Having extract_strings take a ref (as it does now) and return a list simplifies the logic even further.

print join ', ' => extract_strings($nested);

sub extract_strings {
    grep /^[a-zA-Z]/ => map { ref eq 'ARRAY' ? extract_strings($_) : $_ } @{ $_[0] }
}

If returning a ref is necessary, wrap and unwrap accordingly:

sub extract_strings {
    [ grep /^[a-zA-Z]/ => map { ref eq 'ARRAY' ? @{ extract_strings($_) } : $_ } @{ $_[0] } ]
}


Refactoring
The first thing I'd do is remove the redundant else statements.  If you return from every branch, then there's really no need for the else clauses, they're just adding noise.
Constants?
It seems like there's some scope for constants / or lookups since there's some numbers floating around that seem to have meaning (discount amount, discount trigger threshold) etc.  If you're labelling a number with a comment (baker's dozen), it's a good indication that it could be replaced with a constant to 'name' the value.
What are you really be looking for?
However, for me, I think the code actually serves more to prompt questions about whether or not it is performing as desired.  If it is performing as expected, then it's the type of pricing system I hate (because it relies on the customer to optimize their own purchases).
If I buy 12 items, I'm charged for 12 at the discounted rate.
If I buy 13, I'm charged for 12 items at the standard rate.
If I buy 14, I'm charged for 14 at the discounted rate.  This is more expensive than me buying 13, then buying a single item as a separate transaction.
Is this correct? Are you hitting me with the postage?  Why don't I get 26 for the price of 24?
etc...
Constants Revisited
I think some of the above contribute to your difficulty coming up with constants... I'd go with something like this:
private static double getTotalPrice(int quantity, double itemPrice) {
    if (quantity == SPECIAL_ONE_OFF_DISCOUNT_QUANTITY) {
        return itemPrice * (SPECIAL_ONE_OFF_DISCOUNT_QUANTITY - 1);
    }
    if (quantity >= TRIGGER_DISCOUNT_QUANTITY) {
        return itemPrice * quantity * DISCOUNT_MULTIPLIER;
    }
    return itemPrice * quantity;
}

I'm using 'SPECIAL_ONE_OFF_DISCOUNT_QUANTITY', because it really is a special one off amount, with the current logic.  It doesn't duplicate at 26 etc.  I've got rid of the '12' constant, because really it's just 1 less than the trigger amount.  Having a 'ONE_OFF_DISCOUNTTED_QUANTITY' constant might make sense if you could see the need to pay for 10 when you bought 13 for example, however this seems a it unnecessary.
As I said, I'd prefer to rework the logic so that you always pay the lowest amount + so that discounts are additive.  This changes the output prices, so obviously wouldn't be possible if it didn't actually make sense to the client.  It does allow some of the constants to have different names though:
private static double getTotalPrice(int quantity, double itemPrice) {
    var chargeableQuantity = quantity - quantity / BUY_X_GET_ONE_FREE_QUANTITY;
    var valueMultiplier = chargeableQuantity >= TRIGGER_DISCOUNT_QUANTITY ? DISCOUNT_MULTIPLIER : 1;

    return itemPrice * chargeableQuantity * valueMultiplier;
}

I think 'BUY_X_GET_ONE_FREE_QUANTITY' is a better name than 'SPECIAL_ONE_OFF_DISCOUNT_QUANTITY', but it only really makes sense if buying twice the amount results in twice the discount...


Function that calls the database connection and query

A couple simple notes:

your code is very hard to read because the lines are so long. Strive to keep each line under ~80 characters.
most of the time in more complex applications, DB connection management is put into a class or classes, not functions. This better allows you to do things like share a single DB connection in different parts of the app, rather than instantiating a new connection every time you need to query the database. That is an expensive operation.
Your method that executes the prepared statement considers only happy path. What if statement preparation or execution fails? Also, it seems strange this this function then "leaks" the underlying PDO implementation to the method caller, requiring the caller to deal with getting the query result set from the PDOStatement object.


Bash - script to encrypt pdf files using pdfencrypt

Usability

Typing filenames on standard input is extremely annoying.
It would be better if the script took the input filename as command line argument.
That way users can benefit from path completion in the shell.

Simplify

Instead of this:

 while true; do
     echo "please select Pdf input file:"
     read -e -r infile
     if file --mime-type "$infile" | grep -q pdf$; then
         echo
         break
     else
         printf "\nis not a PDF file :-(\n\n"
     fi
 done

I would eliminate the else statement, and also simplify the echo-ing:

 while true; do
     echo "please select Pdf input file:"
     read -e -r infile
     echo
     file --mime-type "$infile" | grep -q pdf$ && break
     echo "is not a PDF file :-("
     echo
 done

Redundant exit

The exit at the end of the script is redundant, I suggest to remove it.


Convert a matrix ("DataFrame") to printable string

V already has a built-in enumeration for plain arrays:
for i, a in arr {
}

Which removes six unnecessary lines of code.
List comprehension would remove another dozen lines, and what little I understand about V's map/reduce, it seems very limited (think lambda without closure) so that is not an option. Python's list comprehension with zip is an efficient way to reduce dumb code, but perhaps it defeats V's "only one way to do things." And perhaps this is a rare scenario.


Useful property names:

I find using names as theData bad practice. It doesn't give any info on the instance. Give it a useful name you, and others, easily understand.

Casing of property names:

Don't use PascalCase for local fields, use camelCase instead. Your MyModel will become myModel. You had already done this correctly for dataSetRow.

Redundant parentheses:

Following:

if ((!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value)))

can be replaced by:

if (!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value))

There's no need to encapsulate the whole expression again in parantheses.

Simplifying the code:

Finally, the important part! :) There's only one way I can think of to achieve this: reflection. I created following extension method to get the PropertyInfo of your instance (note that it doesn't have to be placed in an extension method, I only think it looks cleaner and is good for reusability elsewhere if needed):

public static class Extensions
{
    public static PropertyInfo GetProperty<T>(this T obj, string propertyName) where T : class
    {
        return typeof(T).GetProperty(propertyName);
    }
}

The above allows you to do following (get a property by it's name-value):

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }
}

var user = new User { ID = 1, Name = "Simsons" };
var nameProp = user.GetProperty("Name");

And now you can get and/or set the value of that property using the GetValue() or SetValue() methods:

nameProp.SetValue(user, "Abbas", null);

With this in mind, add following changes to your code:

place all your column names in an array over which you will loop
simplify your code using the reflection part

Here's your code with the above applied:

theData = GetData();

if (theData.Rows.Count > 0)
{
    myModel = new CustomModel();
    dataSetRow = theData.Rows[0];
    var columnNames = new [] { "Column1", "Column2", "Column3", "Column4" };

    foreach(var columName in columnNames)
    {
        if(theData.Columns.Contains(columName))
        {
            if (!object.ReferenceEquals(dataSetRow[columName], DBNull.Value))
            {
                var columnProperty = myModel.GetProperty(columName);
                columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[columnName], null);
            }
        }
    }
}

Update:

As RobH stated in the comments, you can use LinQ to avoid nested if statements. Here's how your code would look like:

var columnNames = new [] { "Column1", "Column2", "Column3", "Column4" };

foreach(var existingColumn in columnNames.Where(x => theData.Columns.Contains(x)))
{
    if (!object.ReferenceEquals(dataSetRow[existingColumn], DBNull.Value))
    {
        var columnProperty = myModel.GetProperty(existingColumn);
        columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[existingColumn], null);
    }
}

You can even take it a final step further to avoid any if statement:

var validColumns = columnNames.Where(x => theData.Columns.Contains(x) &&
                                          !object.ReferenceEquals(dataSetRow[x], DBNull.Value)))

foreach(var column in validColumns)
{
    var columnProperty = myModel.GetProperty(existingColumn);
    columnProperty.SetValue(myModel, Convert.ToString(dataSetRow[existingColumn], null);
}


Storing global constants in app delegate or singleton

Storing everything in a global singleton can be problematic, I wouldn't recommend that.

I worked on a project once where all data ever passed to view controllers from outside was stored a giant singleton class with a lot of properties. Essentially these properties were just global variables.

All this led to bugs where some view controller changed a variable at a wrong point in time and another view controller didn't expect that. If you ask anybody on the internet, they are probably going to say that singletons are bad. And in most situations they are, especially like this one.

So instead of using a singleton I would recommend passing parameters to view controllers somehow before you show them. It can be a as simple as setting a property:

@interface ViewController : UIViewController

@property (nonatomic) NSString *someParameter;

@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Update your UI based on someParameter. For example:
    self.myAwesomeLabel.text = someParameter;
}

@end

If ViewController presents another view controller that happens to need someParameter too, what previously used to be a simple access to your singleton property now has to be replaced with code that will explicitly pass someParameter to the presented view controller like so:

AnotherViewController *vc = [[AnotherViewController alloc] init];
vc.someProperty = self.someProperty;
vc.anotherProperty = @"Another property";
[self presentViewController:vc animated:YES completion:nil];

I think this is called property injection (a kind of dependency injection). There is also constructor (initializer) injection:

@interface ViewController : UIViewController

@property (nonatomic, readonly) NSString *someProperty;

- (instancetype)initWithSomeProperty:(NSString *)someProperty;

@end

@implementation ViewController

- (instancetype)initWithSomeProperty:(NSString *)someProperty {
    if (self = [super initWithNibName:nil bundle:nil]) {
        _someProperty = someProperty;
    }
    return self;
}

@end

There is also a great article on objc.io about this stuff.


I learned something from this

On Error Resume Next
    If Len(inputValue) = 0 Then
        PrintErrorMessage ZLS_ERROR_TEXT
        Stop
    End If
On Error GoTo 0

I learned that On Error GoTo 0 disables error handling in the current procedure. The KB also says:

  Without an On Error GoTo 0 statement, an error handler is
  automatically disabled when a procedure is exited.

So you really don't need it. I also can't figure out under what conditions the len would error. The only thing I could think of is if it's an object, but you've exited by that point. It can't be a negative length can it?


Implement numbering scheme like A,B,C... AA,AB,... AAA..., similar to converting a number to radix26

The function in the question converts to base 26, then splits the resulting string, and converts each digit back to decimal - and then to a letter. That seems roundabout.

Here's a simpler one:

function convertToNumberingScheme(number) {
  var baseChar = ("A").charCodeAt(0),
      letters  = "";

  do {
    number -= 1;
    letters = String.fromCharCode(baseChar + (number % 26)) + letters;
    number = (number / 26) >> 0; // quick `floor`
  } while(number > 0);

  return letters;
}

This function basically does a repeated "divmod" of the input number; getting the modulus 26 and the quotient (floor of n divided by 26). The modulus is converted to a A-Z character that's prepended to the output string, and the quotient is used as the input for the next iteration of the loop.