Fetching files or directories in a given directory

Let's compare your two methods GetFiles and GetDirectories:

func GetFiles(path string) []FileDetail {
    var details []FileDetail

    walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !fileInfo.IsDir() {
            var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
            details = append(details, detail)
        }
        return nil
    }

    filepath.Walk(path, walkFunc)

    return details
}

func GetDirectories(path string) []FileDetail {
    var details []FileDetail

    walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if fileInfo.IsDir() {
            var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
            details = append(details, detail)
        }
        return nil
    }

    filepath.Walk(path, walkFunc)

    return details
}

This is a classic case where copy&paste code is a problem. How can this be simplified? In Go, a good use-case will be a "file test" function that returns true if a file passes a test. Consider the "general purpose" private function that takes a "test" function as an input:

func filterFiles(path string, test func(os.FileInfo) bool) []FileDetail {
    var details []FileDetail
    walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if test(fileInfo) {
            var detail FileDetail = fileDetail{path: filePath, info: fileInfo}
            details = append(details, detail)
        }
        return nil
    }
    filepath.Walk(path, walkFunc)
    return details
}

Now, you can reuse that in your directories and files lists with:

func GetFiles(path string) []FileDetail {
    return filterFiles(path, func(file os.FileInfo) bool {
        return !file.IsDir()
    })
}

func GetDirectories(path string) []FileDetail {
    return filterFiles(path, func(file os.FileInfo) bool {
        return file.IsDir()
    })
}

Now you can also easily add interesting checks on file names, permissions, etc.

I realize that the interface FileDetail is there to teach you how they work, but in this instance, the interface is overkill, and I'd just keep things as a struct and move on.

As for the implementation of the interface, it's not horrible. Your concerns about the pointers is not really valid since all the data is small, and static.

It's OK in Go default to real data structures where the data is copied around, the memory cost is considered trivial.


Loops and Indexes

Why are you using a while loop? A for loop keeps track of indexes for you. Admittedly you do still need to track one index yourself, but you can eliminate one to loop processing:

int addIndex = 0;
for (int i = 0; i < items.Count; i++) {
    output.Add(items[i]);

    if (i % nthStep == 0) {
        output.Add(itemsToAdd[addIndex++]);
    }

    if (i == (items.Count - 1) && addIndex < (itemsToAdd.Count - 1)) {
        i = 0;
    }
}

In words:

define an index for the items you're adding
loop through the items list, on every pass:

add the current item to the output list
if the current step is the nth step, add the next item to add and increase the index
if we've run out of items but have more left to add, reset the items index so we loop back through

Now you're only tracking and handling one index yourself, instead of the three that your while loop requires.


Java - propagating a threadlocal by wrapping a runnable

It might be good to revert the ThreadLocal changes in the worker thread as soon as command.run() finished (using try-finally). This would have the following advantages:

If your ExecutorService delegate (provided to the constructor) is also used somwhere else for different tasks, then currently these tasks would be affected by the changes you make to the ThreadLocals as part of ListeningDecorator.execute. For example:
ExecutorService delegateExecutor = Executors.newFixedThreadPool(10);
ListeningDecorator listeningExecutor = new ListeningDecorator(delegateExecutor);

// Sets MyService thread data
Future<?> future = listeningExecutor.submit(() -> {
    ...
});
future.get();

// In different thread: Directly use delegateExecutor
delegateExecutor.execute(() -> {
    // Would still have MyService thread data even though this was submitted
    // by different thread
    ...
});

If the MyService thread data changes were reverted as soon as command.run() finished, then this would not be an issue.
Reverting the changes might allow the garbage collector to collect MyService thread data earlier. Otherwise it might linger around indefinitely if ExecutorService delegate reuses threads.


Program to display array elements in the ascending order of number of factors each element has

int main(void) {
    int n,a[2][25],i,j;
    printf("Enter the no. of items\n");
    scanf("%d",&n);
    printf("Enter the items\n");
    for(j=0; j<n; j++)
    {
        scanf("%d",&a[0][j]);
    }
    for(j=0; j<n; j++)
    {
        a[1][j] = facts(a[i][j]);         // here i is not set yet
    }

Your compiler should've warned you about this. Please make sure all variables have a set value before checking them.

The only reasons this works is because your compiler decided to initialize i at zero here. However, it is not required to do so by the specification. This means it will break on other systems.


Merge the two sorted array of numbers into single array

Walkthrough
Let me walk through the code with you and see what can be improved.
    var getCommandLineVariables = getCommandLineVariables;

    var mainFunction = mainFunction;

These are already available in your scope, so you do not need to reassign them to a local variable with the same name.
            mergedArray = [], i = 0, j = 0;

        for(i = 0; i < firstArray.length; i++){
            for(j = j; j < secondArray.length; j++){

You initialize i and j, then you reinitialize i in the outer for loop, then do nothing with j in the inner one.  You don't need to write an initialization step in the for loop if you don't want to.
            throw "Pass two comma seperated numbers";

Here you throw a string.  You can throw any value, but it's more helpful for debugging purposes if you throw an Error object.  Just pass this string into the Error constructor to make your own error message.
            someArray.push((function(someString){
                var someArray = someString.split(",");

                someArray = someArray.map(function(str){
                    return parseInt(str);
                });

                return someArray;
            })(arg_array[i]));

You pass an immediately invoked function expression (IIFE) to the push method, but this is totally unnecessary.  You can execute the code above the push method and make things considerably more readable.  Also, you redeclare the variable someArray inside this IIFE and use it for something else, which is pretty confusing.  It'd be better to use a different variable name.
Time Complexity
Your current algorithm is O(n2) because of the nested for loops.  A more efficient algorithm would be to step through both arrays at the same time, adding the next smallest element to the merged array.  This approach would be O(n), so an improvement!
Changes
Altogether, this is how I would restructure your existing code:
(function(){
    'use strict';

    mainFunction();

    function mainFunction(){
        var array = getCommandLineVariables();
        var firstArray = array[0],
            secondArray = array[1],
            mergedArray = [], i = 0, j = 0;

        for(; i < firstArray.length; i++){
            for(; j < secondArray.length; j++){

                if(firstArray[i] < secondArray[j]){ // if number from first array is less than number of second array
                    mergedArray.push(firstArray[i]);
                    break;
                }else{ // if number of second array is less than number of first array
                    mergedArray.push(secondArray[j]);
                }

            } // end of for

            /*
                The below condition executes when
                length of first array is greater than second array
            */
            if(j >= secondArray.length){
                mergedArray.push(firstArray[i]);
            }
        } // end of for

        /*
            If length of second array is greater than
            first array
        */
        for(; j < secondArray.length;j++){
            mergedArray.push(secondArray[j])
        }

        console.log(mergedArray);
    } // mainFunction

    /*
        Capture the numbers passed as commandline arguments
    */
    function getCommandLineVariables(){
        var arg_array = process.argv.slice(2),
            someArray = [];

        if(arg_array.length !== 2){
            throw new Error("Pass two comma separated numbers");
        }

        for(var i = 0; i < arg_array.length; i++){
            var inputArray = arg_array[i].split(",");

            inputArray = inputArray.map(function(str){
                return parseInt(str);
            });

            someArray.push(inputArray);
        } // end of for

        return someArray;
    } // end of getCommandLineVariables
})();

And this is how I would implement the more efficient algorithm I described above:
function mainFunction(){
    var array = getCommandLineVariables();
    var firstArray = array[0],
        secondArray = array[1],
        mergedArray = [], i = 0, j = 0;

    while(i < firstArray.length && j < secondArray.length) {
        if(firstArray[i] < secondArray[j]) {
            mergedArray.push(firstArray[i]);
            i++;
        } else {
            mergedArray.push(secondArray[j]);
            j++;
        }
    }

    while(i < firstArray.length) {
        mergedArray.push(firstArray[i]);
        i++;
    }

    while(j < secondArray.length) {
        mergedArray.push(secondArray[j]);
        j++;
    }

    console.log(mergedArray);
} // mainFunction


The special case:

if not nums or len(nums) == 1:

can be simplified to:

if not nums:

because the case len(nums) == 1 is already handled correctly by the main code.
Instead of starting with count = 0, setting count += 2 when a trend is found for the first time, and having an adjustment at the end if no trend was found, you could start with count = 1, set count += 1 when a trend is found for the first time, and remove the adjustment.
There is no need to initialise current_num = nums[0] because this immediately gets overwritten by the for current_num in ... loop.
There is an unnecessary assignment of prev_num = current_num in one of the branches.
Using the strings "down_to_up" and "up_to_down" to represent the current trend is risky: if you made a typo and wrote "up_to_dwon" somewhere, then the code would be broken but Python would not detect this. It would be better to use global constants, for example

_DOWN_TO_UP = "down to up"
_UP_TO_DOWN = "up to down"

and then if you make a typo like _UP_TO_DWON you will get a NameError from Python.
Now the main logic of the function looks like this:

if not trend:
    if current_num > prev_num:
        trend = _DOWN_TO_UP
        count += 1
    elif current_num < prev_num:
        trend = _UP_TO_DOWN
        count += 1
elif trend == _DOWN_TO_UP:
    if current_num < prev_num:
        trend = _UP_TO_DOWN
        count += 1
elif trend == _UP_TO_DOWN:
    if current_num > prev_num:
        trend = _DOWN_TO_UP
        count += 1
prev_num = current_num

There is a lot of repetition here. In particular, on each branch we check to see if the trend has changed direction, and if it has, then we update trend and increment count. So we could refactor it so that we work out the new trend first, and then compare it with the old trend, like this:

# Work out current trend
if current_num > prev_num:
    current_trend = _DOWN_TO_UP
elif current_num < prev_num:
    current_trend = _UP_TO_DOWN
else: # current_num == prev_num
    current_trend = 0

# Compare with previous trend
if current_trend != 0 and current_trend != trend:
    trend = current_trend
    count += 1
prev_num = current_num

In the case current_num == prev_num we know that the trend does not change, and so there can't be a change to trend, so it would make sense to test this first, and so avoid the test current_trend != 0, like this:

if current_num != prev_num:
    # Work out current trend
    if current_num > prev_num:
        current_trend = _DOWN_TO_UP
    else:
        current_trend = _UP_TO_DOWN

    # Compare with previous trend
    if current_trend != trend:
        trend = current_trend
        count += 1
    prev_num = current_num

And now we can make a further simplification by using True instead of _DOWN_TO_UP and False instead of _UP_TO_DOWN:

if current_num != prev_num:
    current_trend = current_num > prev_num
    if current_trend != trend:
        trend = current_trend
        count += 1
    prev_num = current_num

After making this change, it should be clear that prev_trend would be a better name than trend, for parallelism with prev_num.

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    count = 1
    prev_num = nums[0]
    prev_trend = None
    for current_num in nums:
        if current_num != prev_num:
            current_trend = current_num > prev_num
            if current_trend != prev_trend:
                prev_trend = current_trend
                count += 1
            prev_num = current_num
    return count

It would make sense to stop here, as the revised code is already a lot simpler than the original. But if you are comfortable with Python iterators then you might want to read on to see how the functions and recipes in the itertools module can be used to further simplify the code.
First, we can avoid the current_num != prev_num test by using itertools.groupby to group identical numbers together:

from itertools import groupby

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    prev_num = next(nums)
    count = 1
    prev_trend = None
    for current_num in nums:
        current_trend = current_num > prev_num
        if current_trend != prev_trend:
            prev_trend = current_trend
            count += 1
        prev_num = current_num
    return count

Now that we have an iterator over groups of identical numbers, we can use the pairwise recipe from the itertools documentation to iterate over adjacent pairs of numbers, avoiding the need to assign to prev_num.

from itertools import groupby, tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    count = 1
    prev_trend = None
    for prev_num, current_num in pairwise(nums):
        current_trend = current_num > prev_num
        if current_trend != prev_trend:
            prev_trend = current_trend
            count += 1
    return count

Now we can construct an iterator over the trends:

    trends = (cur > prev for prev, cur in pairwise(nums))

and apply itertools.groupby to this iterator, thus grouping identical trends together and avoiding the need for current_trend and prev_trend. In fact, all we have to do now is count the groups of identical trends.

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    if not nums:
        return 0
    nums = (n for n, _ in groupby(nums))
    trends = (cur > prev for prev, cur in pairwise(nums))
    return 1 + sum(1 for _ in groupby(trends))

This could be written as a single expression:

def wiggleMaxLength(self, nums):
    "Return length of longest wiggle subsequence of nums."
    return bool(nums) + sum(1 for _ in groupby(
        a > b for a, b in pairwise(n for n, _ in groupby(nums))))

(But only if you like that kind of code.)


the only change I would make is to remove your use of the Dict. Dicts are great when you need mutability, but here there is the much simpler solution Int(letter)-Int('A'). With this change, namescore becomes

function namescore(name)
    return sum(Int(char)-Int('A') for letter in name[2:end-1])
end

This, however is not ideal, as we can take out the subtraction, yielding

function namescore(name)
    return sum(Int(char) for letter in name[2:end-1]) - (lenth(name)-2) * Int('A')
end

I haven't done performance testing, but this should be a fair bit faster, as I would expect Int to be faster than a dictionary lookup.


Break early instead of nested if

           if (input > 3 || input < 1) {
               System.out.println("You Can Only Remove 3 Marbles At A Time");
           } else {
               ....
           }

The above can be rewritten as a simple if statement with continue, this prevent the indention from creeper up at the side of the screen.

           if (input > 3 || input < 1) {
               System.out.println("You Can Only Remove 3 Marbles At A Time");
               continue;
           }
           ....

Placing the scanner outside the loop

Scanners use internal buffering to buffer its inputstream, this mean they may consume large amounts, instead of only the part they need for the the concurrent operation. When placing the scanner outside the loop, this also allows for the player to put in the moves much quicker after each other, an still having the program pick up every move.

Place Scanner scanInput = new Scanner(System.in); before while(true){, and wrap the scanner in a try with resources like this:

try(Scanner scanInput = new Scanner(System.in)){
    while(true) {
        ....
    }
}

This also allows you to get rid of @SuppressWarnings("resource").

Proper english doesn't have all words title case

(all println statements)

SOme people have problems with reading sentences with every word uppercase, use the english grammar rules, make only names and the first word of a sentence starting with a uppercase.

Check the state of scanInput.hasNextInt()

You should check the state of scanInput.hasNextInt() before every number is get, this method can return false if the program is accessed by the command line and the command line return EOF, this can be triggered with ctrl + D on linux. The best way to do this is replacing the true in your while loop with the check.

Unused variables

public static int comFirst = (int) (Math.random() * 3 + 1);

At the moment, you have 1 unused variable. Either you will be using this variable for a future expansion, or this variable is left while you were working on the application.

You have won case triggers after the computer move

This case triggers after the computer has done its move. If you really planning on the player to win sometime, you should move this case before the computer makes a move.

Win cases too strict

if (marble - cpuAnswer == 0) {
if (marble - input == 0) {

While with the current implementation of your application, all wins are perfect and ending with exactly 0. If you update your implementation of the computer or player in the future, this may pose a problem in the future.

if (marble - cpuAnswer =< 0) {
if (marble - input =< 0) {

The final result would look like this:

import java.util.Scanner;

public class Main {

    public static int input;
    public static int marble = 12;

    public static void main(String[] args) throws InterruptedException {

        System.out.println("There Are 12 Marbles, You Can Only Remove Up To 3 Marbles At A Time");
        System.out.println("Your Goal Is To Remove The Last Marble, Marble 1");
        System.out.println("To Remove A Marble Either Enter 1, 2 or 3");
        System.out.println("");

        try (Scanner scanInput = new Scanner(System.in)) {
            while (scanInput.hasNextInput()) {

                if (marble == 1) {
                    System.out.println("There Is " + marble + " Marble Remaining");
                } else {
                    System.out.println("There Are " + marble + " Marbles Remaining");
                }

                input = scanInput.nextInt();

                if (input > 3 || input < 1) {
                    System.out.println("You Can Only Remove 3 Marbles At A Time");
                    continue;
                }
                marble = marble - input;
                if (marble - input =< 0) {
                    System.out.println("There Are No Marbles Remaining, You Have Won!!");
                    return;
                }
                Thread.sleep(250);
                int cpuAnswer = 4 - input;
                if (cpuAnswer == 1) {
                    System.out.println("The Computer Has Removed " + cpuAnswer + " Marble");
                } else {
                    System.out.println("The Computer Has Removed " + cpuAnswer + " Marbles");
                }
                if (marble - cpuAnswer =< 0) {
                    System.out.println("There Are No Marbles Remaining, The Computer Has Won!!");
                    System.out.println("The Computer Has Won");
                    return;
                }

                marble = marble - cpuAnswer;
            }
        }
    }
}

Splitting the main method

By splitting the main method you archieve better code reuse.

@TheCoffeeCup has written an excellent answer for this part of the code.


This is cleaner.
added <title> for no HTML Errors W3C Markup Validator.
changed CSS units px to em, for 100% W3C Mobile OK
changed width to 20em (320px) for Mobile Viewport
added mobile meta viewport for Google PageSpeed Insights 100% (less when target divs overlap)
Moved JS below HTML
Made count global
added
 to get misses
added
 to replace alert
replaced CSS div { with .target{
changed div ids to d+index
created target array and init code instead of calling getElementById
added [CDATA[ to JS
added miss counter
added elapsed time
added "Again" button and function
removed function rInt(), was not worth the stack push and pop of calling another function.

While some might say the update() should be added by EventListener. When only one event is required onclick is easy, reliable, and more universally compatible.

W3C HTML Markup Validation Service HTML5: NO ERRORS
W3C HTML Markup Validation Service XHTML Basic 1.1: NO ERRORS
W3C CSS Validation Service: NO ERRORS
W3C mobileOK Checker: Perfect Score: 100%

Google's "Usability Assesment" PageSpeed Insights

Mobile User Experience: Perfect Score: 100%
Desktop User Experience: Perfect Score: 100%
Mobile Speed: Perfect Score: Perfect Score: 100%
Desktop Speed: Perfect Score: 100%

Yahoo's YSlow Grade Perfect Score: 100% (gtmetrix.com)
Page Speed Grade: 99% (gtmetrix.com) 1% loss due to bug in PageSpeed scoring
Page Load time 0.250 seconds (gtmetrix.com)

HTML CSS

<!DOCTYPE html>
<title>Piccoche</title><meta name="viewport" content="width=device-width, initial-scale=1.0" />

All Gone!

<button onclick="playAgain()">Again</button>

JS

New Play Again function

function playAgain(){
  for (var div=0; div<10; div++){
    target[div].style.top = Math.floor(Math.random()*290) + 'px';
    target[div].style.left= Math.floor(Math.random()*290) + 'px';
    target[div].style.display = 'block';
  }
  count = 10;
  misses = -1;
  elapsed = new Date();
  document.getElementById('msg').style.display='none';
}


You have a couple of methods that repeat themselves for the most part that could be factored out.  For example;

the openCont and closeCont are nearly identical, so you could factor them out to be their own function, for example,

var _openCont = function(theId, classesToSet) {
    $scope.all = false;
    $scope[theId] = true;
    for (var key in classesToSet) {
      $(key).addClass(classesToSet[key]);
    }
    $location.hash('main');
    $anchorScroll();
};

Which would be called like:

_openCont('theIdOne', {
  '.lftMn': 'lftMnOpnd',
  '.lftCnt': 'mnCntOpnd',
  '.mainLeftImg': 'mnImgOpnd'
});

Along with this, I'd recommend naming your variables more clearly.  Ideally code should be able to be read very easily even to a new set of eyes.  This will make maintainability far easier down the road.


Close to the metal C++ Palindrome Program

for(int i=0; num_to_parse; i++)

wut

Why is num_to_parse your condition? Then you have if (i == num_to_parse) in there, too? That's odd. I'd rewrite this as:

for(int i=0; i < num_to_parse; i++) {
  int point_end = num_to_parse - i - 1;
  if(inputString[i] == inputString[point_end]) {
    continue;
  } else {
    return false;
  }
}
return true;

If you want to simplify that even further, you can just do this:

for(int i=0; i <= num_to_parse; i++) {
  int point_end = num_to_parse - i - 1;
  if(inputString[i] != inputString[point_end]) {

    return false;
  }
}
return true;

Take note of the different condition. There are a couple of other simplifying improvements, but they're mentioned in another answer.

While I was writing that, I realized that your indentation is... odd, to say the least. Please don't use things like }} in code; while there are a few rare cases where it might be OK (nested namespaces that, as is typical, you didn't indent), none of them apply here.

using namespace std is a bad idea. Please don't do it.

printf("%s", is_palidrome(inputString)?"This is a palindrome.":"Not a palindrome.");

This is just... weird. I mean, first of all, you don't have a trailing newline, so it might never output anything at all. In my C IDE, for example, it would, but on my Bash console, it'd definitely look odd (This is a palindrome.q@my-hostname ~>), if it prints at all. Even ignoring that inconsistency... why do it like that? The ternary just makes it more complicated than it has to be.

If you insist on using C functions (more on that later), do this:

if (is_palindrome(inputString)) {
  puts("This is a palindrome.");
} else {
  puts("Not a palindrome.");
}

The C++ equivalent should be fairly straightforward; replace the puts(...) with std::cout << ... << "\n";, or std::endl in place of "\n" if you want to be paranoid about flushing every single line instead of just ensuring that it's flushed in a few key places (which is what I do in performance-critical stuff, because writing to the console is slow, and until you tell them to, most C++ standard libraries will avoid doing it for as long as is reasonable)

Now to talk about that "using C functions" thing. Why are you doing it at all? You have all of C++'s power to bring to bear, but you don't. If you want to write this in C, write it in C -- it'd only be changing, like four lines. Maybe less. Don't use just a tiny part of C++. Or, alternatively, just write C.

With regards to your original concern about speed, you're doing this in O(n) (as far as I can tell), which is the absolute lower limit. You're still iterating over every character, though, so it's not as fast as it could get -- you only need to iterate over half.

Finally, what do you mean by "close to the metal"? This is just C with a tiny sprinkling of C++, which are both high-level languages. Not as high-level as, say, Python, but the definition of a high-level language is that it's abstracted from any one particular machine, which C and C++ are. There's nothing close to the metal here. That would be machine code, or maybe Assembly.


Is this Agent/Actor implementation issue free?

Few minor points:

Generic type parameter should be called <T> as per convention.
public constructors in abstract classes make no sense - make it
protected.
Make thread and messageQueue readonly and don't
set them to null in the Dispose() method.
Better yet, implement the Disposable Pattern correctly. Though note, I do disagree with their setting of the IDisposable members to null. It's really not necessary at all; but calling Dispose() is. Their _disposed class member conveys enough information necessary.
You should also lock on a dedicated locking class member when accessing your quit class member since it is accessed via multiple threads.
Possibly wrap your call to ProcessMessage(message) in a try..catch block with appropriate error handling (or not, as the case could be). Unless, of course, you trust any subclasses from doing nasty things in their override of it.

Just my initial thoughts. Hope they help.


Decomposing a number as a sum of two products using tree recursion

First try to solve without a helper function. Also try to solve using a helper function and adding up to the sum.

You haven't included an implementation without a helper function.
You implemented memoization, which was not part of the description.
In any case, memoization won't be possible without a helper function or annotations.

Code review

There are several problems with your implementation:

memoiz shouldn't be a list, but a set
The value variable is confusing: it merely stores the original values of n1 and n2, you could simply save those values before calling the helper function
sum is a poor name for a variable, because it shadows the built-in named "sum"
There should be spaces around operators to improve readability, for example instead of (x+1)*value[0] it should be (x + 1) * value[0]
Instead of multiplying value[0] and value[1], it would be better to accumulate a sum
If result1 is True, there's no need to evaluate result2

With the above tips, the solution can be simplified a bit and become more efficient:

memoiz = set()
def has_sum(sum, n1, n2, x=0, y=0):
    if n1 + n2 == sum:
        return True
    if n1 + n2 > sum:
        return False
    if (x+1, y) not in memoiz:
        memoiz.add((x+1, y))
        result1 = has_sum(sum, n1 + orig_n1, n2, x+1, y)
        if result1:
            return True
    if (x, y+1) not in memoiz:
        memoiz.add((x, y+1))
        return has_sum(sum, n1, n2 + orig_n2, x, y+1)
    return False
orig_n1, orig_n2 = n1, n2
return has_sum(sum, 0, 0)

An alternative solution

Consider this alternative algorithm:

If target is 0, then we can reach it by 0 times n1 and n2
If target is below 0, then we cannot reach it
If target can be reached by a sum of multiples of n1 and n2,
then target - n1 or target - n2 must be reachable too

Implementation using memoization:

memoize = { 0: True }
def helper(target):
    if target not in memoize:
        if target < 0:
            memoize[target] = False
        else:
            memoize[target] = helper(target - n1) or helper(target - n2)
    return memoize[target]
return helper(target)

Iterative solution

At first I overlooked your requirement of a recursive solution.
For the record, this was my original suggestion using iterative logic.

Unless I'm missing something,
you can solve this using a much simpler algorithm:

If a solution exists, then sum == n1 * A + n2 * B where A and B are integers
Loop from A = 0 to sum, by steps of n1
If sum - A is divisible by n2, then a solution exists
If the end of the loop is reached, then a solution doesn't exist

That is:

for A in range(0, sum + 1, n1):
    if (sum - A) % n2 == 0:
        return True
return False


How to differentiate web fonts font-face font-weights?

Always option 1. That way it will correctly use bold in cases when the browser doesn't support or can't download the fonts.

EDIT: One more point I've noticed just now: Don't use bold (700) for "semi-bold". Most font creators suggest a font-weight value for each variant. Usually it's 600 for "semi-bold" (and 500 for "medium").


Immediate security problem

Do you know which ng, cp, rm, gradlew does the script execute? You shouldn't rely on PATH.
Indirect security problem

rm and cp can fail midway, and you may end up deploying something unintended. Along the same lines, can ng produce something half-baked? Consider testing exit codes and act accordingly.
Every time you want to comment the behavior, consider factoring it into a well-named function, e.g.

recreate_static_directory() {
    cd "$1"
    echo "Deletic static web resources"
    rm -r static

    echo "Creating static directory"
    mkdir static

    echo "Copying static resources into directory"
    cp -r "$webapp/dist/."  "$1/static"
    cp "$serverapp/secured/emmanuel-arzate/private-key.p12" "$1"

I am not sure I follow the mix of cds and fully-qualified paths.


Use 'shellcheck' to spot common problems

200236.sh:2:12: warning: Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames. [SC2010]
200236.sh:2:18: note: Use ./*glob* or -- *glob* so names with dashes won't become options. [SC2035]
200236.sh:4:8: note: Don't use variables in the printf format string. Use printf "..%s.." "$foo". [SC2059]
200236.sh:4:53: note: Backslash is literal in "\n". Prefer explicit escaping: "\\n". [SC1117]
200236.sh:6:21: note: Double quote to prevent globbing and word splitting. [SC2086]

Don't parse the output of ls

The ls program works well for interactive use, but isn't designed to be parsed by scripts.  The main problem is that whitespace and other shell-significant characters are shown as-is, with no quoting.  You could try to work around this using ls -b, but it's more robust to avoid the problem altogether:

for i in */
do
  if [[ i =~ proc ]]; then continue; fi
  # ...
done

The test for virtual filesystems is too broad

grep proc will pick up names such as processor - do you really want to exclude them?  If you want to avoid inspecting filesystems not backed by disks, there are more reliable means:

case $(stat --file-system --format '%T' "$i") in
  proc|tmpfs|sysfs) continue ;;
esac

Always quote parameter expansions

du -h --max-depth=1 "$i"
#                   ^^^^

Don't expand parameters into a format string

Use echo or printf, but don't confuse the two ($i may contain %):

echo "**** $i has the following breakdown ********"

printf '**** %s has the following breakdown ********\n' "$i"

Constrain du to a single filesystem

I'm not sure whether or not you want du to cross mountpoints.  If not, then add -x / --one-file-system to its options.

Modified code

#!/bin/bash
for i in */
do
    case $(stat --file-system --format '%T' "$i") in
        proc|tmpfs|sysfs) continue ;;
    esac

    echo "**** $i has the following breakdown ********"
    du -h --one-file-system --max-depth=1 "$i"
done


Is it proper to use nested loops a lot in python?

From what I understand from your comment, using itertools did solve your problems.

Here are a few suggestions anyway (that you may want to take into account before submitting a new question with the updated code):

instead of using global variables, you should add parameters to your functions.
you could take this chance to add a proper documentation about what your function is supposed to do and what the parameters are.
the indentations seem to be of various sizes. PEP8, the Style Guide for Python code recommands using 4 spaces. It is probably worth reading the whole document.


You should never throw an empty exception. Imagine someone uses your code and receives an empty IOException. What happened? How do you debug this?

First, you need a message that explains the situation. Second, you should use this constructor : IOException(String, Exception). This way, the exception you throw will contain the real exception, the one that causes problem. This will help debugging your code.

if(totalBytesRead < expLength)
{
    // should probably throw something here
    throw new IOException();
}

Yeah, you probably should throw something.. meaningful! Once again, add some information in there. Think about the poor soul that would need to debug this later.

I don't think it's a bad thing to throw exceptions in two separate places, but it's a bad thing to throw meaningless exceptions (I hope the message is clear ahah)


Replace tabs in input and variable vs symbolic parameter

The code is not ready for review, because it does not solve the exercise. It blindly replaces each tab with TABLENGTH spaces. This is not detabbing; the amount of blanks must give you a next tab stop. For example, for

a\tb
aa\tb
aaa\tb

the output should be

a       b
aa      b
aaa     b

(number of blanks is 7, 6, and 5 respectively, to align b at the tab stop, the 8th column). Your code produces

a        b
aa        b
aaa        b

instead.


I recommend using Valgrind as the first step of the self-code review. Here it only reports one error when compiled with gcc on Linux:

 $ gcc -O2 main.c -o main -std=c99 -Wall -Wextra  -g
 $ valgrind  --track-origins=yes ./main
 (...)
 ==24100== Conditional jump or move depends on uninitialised value(s)
==24100==    at 0x4009B4: comment_start (main.c:85)
==24100==    by 0x4009B4: no_comments (main.c:54)
==24100==    by 0x40062E: main (main.c:21)
==24100==  Uninitialised value was created by a stack allocation
==24100==    at 0x400620: main (main.c:20)
==24100==
==24100== Conditional jump or move depends on uninitialised value(s)
==24100==    at 0x4009CA: quote_start (main.c:102)
==24100==    by 0x4009CA: no_comments (main.c:62)
==24100==    by 0x40062E: main (main.c:21)
==24100==  Uninitialised value was created by a stack allocation
==24100==    at 0x400620: main (main.c:20)
==24100==
==24100== Conditional jump or move depends on uninitialised value(s)
==24100==    at 0x518C1B2: vfprintf (in /lib64/libc-2.21.so)
==24100==    by 0x51928E8: printf (in /lib64/libc-2.21.so)
==24100==    by 0x400640: main (main.c:23)
==24100==  Uninitialised value was created by a stack allocation
==24100==    at 0x400620: main (main.c:20)
=

The problem lies inside get_input(), exactly in this line:

input[++i] = '\0';

Add printing value of i after each iteration and after the pre-incrementation. You will see something like this:

i == 0
i == 1
i == 2
i == 3
i == 4
i == 5
i == 6
i == 7
i == 8
i == 9
i == 11

Position 10 is not set. However, later on in no_comments() you have a loop:

for (int idx = 0; idx <= len; idx++) {
    if (strlen(comments) == 0) { // outside comment

        if (!quoted && comment_start(input, idx)) {

Input array and index are passed to comment_start() and read there:

return input[idx] == '/' && (nxt == '*' || nxt == '/');

At some point you will read an element of input array that has not been initialized. It's an undefined behavior in C and it's quite dangerous.


You should consider what happens when a user passes an action which can error:

new List<string> { "a", "b", "c" }.Foreach(_ => { throw new Exception(); });

In this case, your manual reset event will never be signalled and the code will never finish executing. Eeek!

As ManualResetEventSlim was introduced in .Net 4 you may as well use another class that was new at the same time CountdownEvent.

public static void Foreach<T>(this ICollection<T> source, Action<T> action)
{
    var allDone = new CountdownEvent(source.Count);
    foreach (var item in source)
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            try
            {
                action((T)state);
            }
            finally
            {
                allDone.Signal();
            }
        }, item);
    }
    allDone.Wait();
}

Having said that Foreach is a bad name, it's too similar to List.ForEach and doesn't even hint at the internal behaviour.

You should be checking that source != null and action != null.

Update:
If you want to catch exceptions and rethrow them as an AggregateException, add them to a concurrent collection e.g. ConcurrentBag so you don't need to worry about synchronisation.


The Lecture Notes advocate "wholemeal" programming, which I would summarize as being the use of higher-order functions.  Your code, on the other hand, suffers from the "indexitis" that you are being encouraged to avoid.

The key insight for this exercise is that it resembles a list-chunking problem.  If you transform "hello!" into, say, chunks of increasing length…

[
    ["h", "e", "l", "l", "o", "!"],
    ["he", "ll", "o!"],
    ["hel", "lo!"],
    ["hell"],
    ["hello"],
    ["hello!"]
]

… then the problem boils down to taking the last element of each substring.

skips :: [a] -> [[a]]
skips xs =
  map (map last . fullChunks) $ zip [1..] (replicate (length xs) xs)
  where
    fullChunks (n, ys)
      | n > length ys = []     -- Discard incomplete chunks
      | otherwise     = chunk : fullChunks (n, rest)
      where (chunk, rest) = splitAt n ys

Unfortunately, you can't use the functions provided by Data.List.Split, since incomplete chunks at the end need to be discarded.


I would say that one of the major differences between a DTO and a POCO is the fact that a DTO should be immutable because it is meant to be used for transferring only. See what are the differences between a POCO and a DTO in this SO question. That said, someone could suggest that your DTO implementation should be the following:

public class Settings
{
    public bool FullScreen{get; private set;}
    public int WindowWidth{get; private set;}
    public int WindowHeight{get; private set;}
    public Setting(int width, int height, bool fullScreen){
       WindowWidth = width;
       WindowHeight = height;
       FullScreen = fullScreen
    }
}

This is only if you want to be a purist in the implementation of a DTO because the usage of this is a pain, especially if your DTO class has many properties. The work around is the one you already have, although I would trade the fields for properties because properties respect the principle of encapsulation and are implemented with the same space in C# (in Java I wouldn't mind having public fields though).

About your second issue, I would say that your real problem is to isolate the domain from its representation, be it JSON or something else. So how could you separate them? I would personally use the proxy pattern:

public class Sprite
{
    public virtual string AssetName{get; set;}
    public virtual Vector2 Position{get; set;}
}

public class SpriteJson : Sprite
{
    public SpriteJson(Sprite sprite){
       AssetName = sprite.AssetName;
       Position = sprite.Position;
    }
    public SpriteJson(){}
    [JSonProperty]
    public override string AssetName{get; set;}
    [JSonProperty]
    public override Vector2 Position{get; set;}
}

It may seem that you have too much redundancy, but it does isolate the objects from their representation. You could receive a Sprite object anywhere in your code, whether it is a SpriteJson object or not.

Edit: I think I only answered your question partially, so I edited my answer to provide more details.

Leaving the representation aside, the logic associated with the object would be in your Sprite class:

public class Sprite
{
    public virtual string AssetName{get; set;}
    public virtual Vector2 Position{get; set;}
    public void Move(Vector2 direction)
    {
         // do move
    }
}

I think an object should always have the logic associated with it whenever it makes sense and is reasonable. There is no need for making a wrapper only to separate the logic (a useless abstraction, in my opinion). The question I linked also stated that POCO classes may contain logic operations. So when is it not reasonable? Imagine that your move code is highly dependent on another class and many of your objects also have their own move logic. In that case, it would be better to refactor the move code to another place so you wouldn't have code redundancy and eliminate those dependencies.


The name addNode2Head will be better as addNodeToHead. Using the number 2 for the word to is rather poor choice in a function name.
The function addNodeToHead can be simplified to:

sList *addNodeToHead(sList *psList, void *data)
{
   sList* node = newNode();
   node->data = data;

   // It doesn't matter what psList is. The new
   // node is now the head of the list.
   node->nextNode = psList;

   return node;
}

Given the simplified implementation of addNodeToHead, the function addHeadNode might be unnecessary.
Don't explicitly cast the return value of malloc. See Do I cast the result of malloc?

Instead of

sList *psList =(sList *) malloc(sizeof(sList));

use

sList *psList = malloc(sizeof(sList));

Always check the return value of malloc before proceeding to use it.

sList *newNode(void)
{
    sList *psList = malloc(sizeof(sList));
    if ( psList == NULL )
    {
       return NULL;
    }
    psList->nextNode = NULL;
    return psList;
}

Make sure that you check the value returned by the above function.

   sList* node = newNode();
   if ( node == NULL )
   {
      // Decide how you want to handle the error.
      // return NULL???
   }

   node->data = data;


The code is easy to read and to follow. There isn't a global in sight, the indentation is consistent, you use EXIT_SUCCESS and EXIT_FAILURE, and the control flow is simple. Therefore I have no comments about superficial aspects of style.

However, there is a bug in interpret: You are reading uninitialized memory. The code assumes that code will end in a null character; this is not usually the case. Keep in mind that ftell, fseek, fread do not account for a terminating \0.
Most of the time, fsize will be the number of characters in the file. If the file happens to end in \0, all is well. But if it ends in some other fashion, then code[fsize - 1] (the last valid index of code) will not be \0. Hence codep will begin wandering into memory outside of code until it chances upon a 0.
In C, it is valid to have a pointer to one element past the end of an array. In other words, there is no issue having codep > code + fsize. The problem occurs when codep is dereferenced, since the contents of *codep is undefined.
You can fix this by reserving space for a null character and adding it yourself.

After fixing the problem, there are some other things to be careful about. You check the the return value of fopen, but you don't do the same for other input/output functions. For example, fgetc's result is assigned to a cell blindly, even though fgetc does not return a char. It returns an int, which might be EOF; you should check for and handle this case, as long as the type of your cell is char. (See also the remarks on parameterization below.)

Function name
Error return

fputc
EOF

fgetc
EOF

fseek
a nonzero value

ftell
-1L

fread
a value less than the third argument in the call

fprintf
a negative value

fclose
EOF

My (somewhat controversial) stance on error checking is to do it for any function that can fail. Most people would probably not check fputc and fprintf, even if they check the others. I certainly don't object to this, but it isn't my personal choice.
In each failure case, you should exit(EXIT_FAILURE), probably after printing an indication of what happened. The perror function might be useful.

Why not perform bounds checking to avoid undefined behavior if the pointer moves outside the memory? You can print an error message and leave the pointer unchanged. A similar case to look out for is when a [ or a ] is missing. One way to handle bounds checking is to use offsets (probably of type size_t) instead of real pointers.

I would also suggest parameterizing the program a bit more. Your specification does say that the memory is 30 000 cells in size, but why not give the 30000 a symbolic name? But I think the most interesting aspect is the types you use.
For the most part, char works great as a cell type. However, there are two properties to note: (1) char might be wider than eight bits; (2) char might be signed or unsigned. The former is much less important than the latter. Because the signedness of char is uncertain, I would suggest using a fixed-width and fixed-signedness type.
Regardless of the underlying type, you should probably give a meaningful name to it with typedef—perhaps cell_type. I recommend doing this even if you stick with char.
Most brainfuck interpreters use signed, eight-bit cells. One choice of type is naturally int8_t, but such a type may not be provided by an implementation. You can test for its presence by checking whether INT8_WIDTH is defined. Alternatively, you could use int_least8_t or int_fast8_t, both of which are guaranteed to be provided by a conforming C implementation.
You should pay attention to overflow in memory cells, since overflow of signed numbers in C is undefined behavior. The simplest thing to do is to use unsigned types (uint8_t, uint_least8_t, uint_fast8_t), which wrap on overflow.

Finally, I should address your method of reading the input file. It is simple to read it all in at once, but ftell and fseek might fail, and you're wasting memory. An alternative is to store only the text associated with currently active loops. This is much more complicated to implement, however, especially if you want to allow loops to be arbitrarily sized.


If a problem has been encountered before by someone else, chances are that there is a CPAN module for that (DataExtract::FixedWidth).

If you don't want to use a CPAN module, then my next choice would be to use regular expressions.

use strict;

# Strips leading and trailing whitespace from all parameters
sub strip {
    for (@_) { s/^\s+//; s/\s+$//; }
    @_;
}

# Extracts data from lines of text in tabular format.
#
# First parameter is a regular expression for capturing fixed-width fields.
#
# Subsequent parameters are the lines of tabular data, the first of which holds
# the column headings.  Any line that does not match the regular expression,
# as well as subsequent lines, are discarded.
#
# Returns a list (one element per input line) of hashes (keyed by column names).
sub extract_table {
    my ($fmt, $first_line) = (shift, shift);

    my (@headers) = strip($first_line =~ $fmt);

    my @table;
    for my $line (@_) {
        my (@fields) = $line =~ $fmt;
        last unless @fields;

        my %data;
        @data{@headers} = strip(@fields);
        push @table, \%data;
    }
    return @table;
}

my $fmt = qr/^(.{14})(.{17})(.{19})(.{5})(.{8})(.{14})(.{6})(.*)/;

# Take lines of input from a reasonable source (STDIN or a filename
# argument on the command line)
my @table = extract_table($fmt, <>);

use Data::Dumper;
print Dumper(\@table);

Note that chomp() is unnecessary since we're stripping whitespace characters anyway.


First step : functions and tests

The very first thing you probably should write is a function computing what you really want : a sum of primes. Also, a value is provided as part of the problem, use this to write a test : as soon as something goes bad, you might notice it.

def sum_primes_to_limit(lim):
    i = 2
    now = []
    total = 0
    for i in range(2,lim+1):
        for x in range(1,int(math.sqrt(i))+1):
            if len(now) ==2:
                break
            elif i % x == 0:
                now.append(x)

        if len(now) == 1:
            total += i
        now = []
    return(total)

def main():
    assert sum_primes_to_limit(10) == 17
    print(sum_primes_to_limit(2000000))

Making things simpler

Declaring the i variable is not needed.
Similarly, the now variable does not need to be defined before the loop and cleared at the end of each iteration : just define it as empty at each iteration.

def sum_primes_to_limit(lim):
    total = 0
    for i in range(2,lim+1):
        now = []
        for x in range(1,int(math.sqrt(i))+1):
            if len(now) == 2:
                break
            elif i % x == 0:
                now.append(x)

        if len(now) == 1:
            total += i
    return(total)

Making things even simpler

You don't really care about the content of now, just its length. Also, there's no need to check that it does not get longer that 2 at each iteration : just check when you update the list.

Also, you can get rid of the list and make it a simple counter :

def sum_primes_to_limit(lim):
    total = 0
    for i in range(2,lim+1):
        nb_div = 0
        for x in range(1,int(math.sqrt(i))+1):
            if i % x == 0:
                nb_div += 1
                if nb_div == 2:
                    break

        if nb_div == 1:
            total += i
    return(total)

More function

Given the way you check if a number is prime or not, it probably make sense to define a function for this :

def is_prime(i):
    nb_div = 0
    for x in range(1,int(math.sqrt(i))+1):
        if i % x == 0:
            nb_div += 1
            if nb_div == 2:
                return False
    return nb_div == 1

def sum_primes_to_limit(lim):
    total = 0
    for i in range(2,lim+1):
        if is_prime(i):
            total += i
    return(total)

A bit of Python cool syntax

Among the cool things in Python are generator expressions. Using generator expressions and sum, you can write sum_primes_to_limit in a concise and fancy way :

def sum_primes_to_limit(lim):
    return sum(i for i in range(2,lim+1) if is_prime(i))

Rewriting the function

You can avoid considering 1 as a divisor if you simply start at 2 (then, you might need some special processing for 1 but I'll leave this to you).

Then your function becomes :

def is_prime(i):
    nb_div = 0
    for x in range(2,int(math.sqrt(i))+1):
        if i % x == 0:
            nb_div += 1
            if nb_div == 1:
                return False
    return nb_div == 0

Then, you don't need the number anymore :

def is_prime(i):
    for x in range(2,int(math.sqrt(i))+1):
        if i % x == 0:
            return False
    return True

And this looks like it really wants to be written with generator expression (and all or any this time).

def is_prime(i):
    return all(i % x for x in range(2,int(math.sqrt(i))+1))

(Please note that I took this chance to remove a != 0 as non-zero boolean will evaluate to True).

This is all pretty cool but we want speed!

You want to compute/check primes up to a certain limit. Good for you there is an algorithm just for this : the Sieve of Eratosthenes.

Here's an implementation :

def sieve(lim):
    primes = [True] * (lim+1)
    primes[0] = primes[1] = False
    for i in range(2, int(math.sqrt(lim))+1):
        if primes[i]:
            for j in range(i*i, lim+1, i):
                primes[j] = False
    return primes

def sum_primes_to_limit(lim):
    primes = sieve(lim)
    return sum(i for i in range(2,lim+1) if primes[i])

Final details

I am used to Python 3 but if you are using Python 2, range generates an actual list. When this is not required (and in your case, this is not required), you should be using xrange.


The standard way to do this would be to use a tkinter canvas or pygame, but rolling with your method, you only have one huge efficiency problem, you are wasting subpixel precision on your calculations, I added a simple PRECISION constant so that you can decide at will how many degrees you advance per step, you only used 1 degree per step that is really to little, I suggest \$10\$, it looks good and goes fast.

I  also added a constant for 10**5 so that you can avoid computing it every cycle (not a big deal) but mainly so that you could explain with a name what that number does.

I also replaced the while loop with a for loop so that the program does not run indefinitely (I was quite trolled by the program taking my mouse cursor for infinite time, it was not easy to shut it down).

Also please put care in your comments, about spelling formatting etc.. and the standard format is a docstring on top of the file.

Removing the printing can also speed up your program a bit.

Enjoy your improved program:

"""
This program takes control of the mouse to draw an ellipse.

(x-h)^2 + (y-k)^2 = r^2
Knowing radius and degree,
rise = r*sin(deg*pi/180)
run  = r*cos(deg*pi/180)
"""

from numpy import sin, cos, pi
import pyautogui as cc
import time

BIG_NUM = 10**5
PRECISION = 10 # higher is less precision
ITERATIONS = 300

input('Enter to Begin\n-->')
radius = int(input('What do you want your beginning radius to be?\n-->'))
rate = int(input('How much do you want it to increase by each cycle?\n-->'))
h, k = cc.position()
degree = 0
x = h+radius*(int(cos(degree*pi/180)*BIG_NUM)/BIG_NUM)
y = k+radius*(int(sin(degree*pi/180)*BIG_NUM)/BIG_NUM)
cc.moveTo(x, y)
cc.mouseDown()

for i in range(ITERATIONS):
    degree += PRECISION
    degree %= 360
    radius += (PRECISION * rate) / 360
    x = h+radius*(int(cos(degree*pi/180)*BIG_NUM)/BIG_NUM)
    y = k+radius*(int(sin(degree*pi/180)*BIG_NUM)/BIG_NUM)
    cc.moveTo(x, y)
    #print('Cords: '+str(x)+'||'+str(y))
    #print('radius: '+str(radius))
    #print('degree: '+str(degree))
    #print()


Throwing error if settings / arguments are undefined is this a good breakout function?

The abstraction is good but the tight coupling is bad.  The only real use case for checkSettingsUndefined is for your Class object.

Here is an example of a more generic method, it just takes an array of validation objects that will be run on their associated calling args.

/**
 * @param  {[Object]} validationArray Array of validation configs
 * that follow the api of
    {
        fn: function(value) {},
        message: ''
    }
 * @return Function
 */

function createArgValidatorFn(validationArray) {

    return function() {
        var argValue,
            validationFn,
            args = arguments;

        validationArray.forEach(function(obj, index) {
            validationFn = obj.fn;
            argValue = args[index];

            if (validationFn(argValue)) {
                throw new Error('argument[' + index + '] : '  + obj.message);
            }

        });
    }
}

You can use in Class by doing:

var classValidationFn = createArgValidatorFn([{
        fn: _.isEmpty,
        message: 'settings are empty'
    }
]);

var Class = function(settings){
    classValidationFn.apply(this, arguments);
    this.settings = settings;
};

This will allow to stuff like:

var fn = createArgValidatorFn([{
        fn: function(val) {
            return typeof val !== 'string'
        },
        message: 'Argument must be a string'
    }, {
        fn: function(val) {
            return !val;
        },
        message: 'Argument must be a truthy'
    }
])

fn('a');

  "argument[1] : Argument must be truthy"


Query of consultants and their expected payments for the month

you are doing a lot of CONVERTing in this query.

Instead of converting the Date variables inside the WHERE clause you should do that before you even start the query, otherwise you are running this convert for every row in the SELECT because the WHERE decides if a row should be kept or discarded from the returned table.

Are the date fields not already in DateTime format?

get rid of all the Converts that are not needed.

also you should format your code with some indentation so that it is easier to read, for you and for others who will maintain the code you write.


As youself noted F(x) can be reduced to:

x*x*(x+1)/2 + (x+1)! - 1

As @Daniel Sokolov pointed, you don't need to calculate full factorial for each p[i]. If p is a sorted array, you can use previously calculated factorial in the current (x+1)! calculation.

Furthermore it would be better to get modulo after each arithmetic operation. This ensure that the current result after each operation will always < m*m < 10^14.

So the code might look like this:

/**
 *  @param m modulo
 *  @param n number of integers
 *  @param p sorted array of integers
 *  @return sum of F(pn) series modulo m
*/
function sum(unsigned long m, unsigned n, unsigned long long int *p) {
    unsigned long long int
        x, // current element of p array
        x0 = 1, // previous element of p array
        a, // sum of arithmetic progression
        fac = 1, // factorial of (x + 1)
        ret = 0; // result
    for (unsigned i = 0; i < n; i++) {
        x = p[i];
        if (x < x0) return 0;
        a = x % m * x % m * ((x + 1) / 2 % m) % m;
        for (var k = x0 + 1; k <= x + 1; k++)
            fac = fac * (k % m) % m;
        ret = ((ret + a) % m + fac - 1) % m;
        x0 = x;
    }
    return ret;
}

Note that it assumes p is a sorted array.


Random Delay Generator for Workflow Foundation

don't new it every time
it is expensive and is not as random as just keep using random
new Random() is based on a time seed

    private Random rand = new Random();
    protected override int Execute(CodeActivityContext context)
    {
        var min = context.GetValue(MinSeconds);
        var max = context.GetValue(MaxSeconds);
        var secondsToWait = rand.Next(min, max);
        return secondsToWait;
    }

OP said the many of the class are generated at once
Just create random once and pass it in the constructor

public class RandomSecondsGenerator
{
    public int MinSeconds { get; set; }
    public int MaxSeconds { get; set; }
    private Random rand;
    protected int Execute(DateTime context)
    {
        var secondsToWait = rand.Next(MinSeconds, MaxSeconds);
        return secondsToWait;
    }
    public RandomSecondsGenerator(Random random)
    {
        rand = random;
    }
}


Your whole function get_seconds is not needed at all. You can use the function time.time(), which gives you the seconds since epoch (Jan 1, 1970 0:00:00). Subtracting two such times will yield the number of seconds passed in between. I would also do the time measurement exclusively around the actual download, otherwise you add the (small) overhead of reading the header for the file-size.

def downspeed():
    url = "http://speedtest.ftp.otenet.gr/files/test100k.db"

    start = time.time()
    file = requests.get(url)
    end = time.time()

    time_difference = end - start
    file_size = int(file.headers['Content-Length'])/1000
    return round(file_size / time_difference)

You should also report the units of your speeds measured. As it is, they will be KB/s, with the K denoting 1000 (as you divide by that). You should be aware that there is also a different unit, sometimes written KiB/s, where Ki stands for 1024. You should probably use the same definition, which speedtest uses, when it says the file is 100kb big.


Is Lock necessary to make operation thread safe for this scenario

According to information you provided it's not necessary to wrap it with lock.
Let's consider situation you described. You wrote:

There will be multiple threads instantiating this class

So there will be one instance for each thread. There's no synchronisation needed, because only one thread will be accessing your class at a time.
Other scenarios:

Single instance of MyDataProvider class is shared between multiple threads. What does it mean? GetItem() method could be invoked by multiple threads at the same time. In that case you'll need synchronization IF your class have any state that (private field for example) could be accessed and modified from GetItem() method. You don't have such situation, so synchronization is not needed. Also you get connection from '[POOL]' each time anyone is invoking GetItem() instance method.
Single instance of MyDataProvider class is shared between multiple threads AND sqlconnection is a state in it. Then you would need to synchronize it.

Your implementation should be fine.


Increase performance in an R function using a vectorized approach

Your strategy C is probably already nearly optimal. Here is an Rcpp based solution to squeeze out some additional seconds

library('Rcpp')
cppFunction(includes = '#include <math.h>',
            code = 'Rcpp::NumericMatrix strategy_rcpp(const Rcpp::NumericVector& theta,
                                                      const Rcpp::NumericVector& b,
                                                      const Rcpp::NumericVector& a) {
  const int n = theta.size();
  const int m = a.size();
  if (m != b.size())
      Rcpp::stop("a and b must have equal length");
  const double e = exp(1.0);
  Rcpp::NumericMatrix ret(n, m);
  for (int j = 0; j < m; ++j) {
      for (int i = 0; i < n; ++i) {
         ret(i, j) = 1.0 / (1.0 + pow(e, -a[j] * (theta[i] - b[j])));
      }
  }
  return ret;
}')

Benchmarks with your data:

library('microbenchmark')
microbenchmark(times = 1,
               strategy.C(theta, b, a),
               strategy_rcpp(theta, b, a)
)

Unit: seconds
                       expr       min        lq      mean    median        uq
    strategy.C(theta, b, a) 10.996822 10.996822 10.996822 10.996822 10.996822
 strategy_rcpp(theta, b, a)  6.921705  6.921705  6.921705  6.921705  6.921705


var data = [{"code":"456100010011","incrementingnumber":"015-0011-00001"}];

var code = data[0].code,
    inc = data[0].incrementingnumber;
var inc1 = inc.split('-');
inc1[2] = ('00000' + ++inc1[2]).slice(-5);

document.write(inc1.join('-'));

You don't need the code.slice, but you'd still need to split your incrementingnumber value.


Generate all valid combinations of n pair of parentheses

API

The compute_all_parens function requires 4 parameters.
From a user's perspective,
it would be more natural to require only one,
to avoid confusion about what values to pass for the others.
You could use an inner function to encapsulate your implementation details:

def print_all_parens(n):
    def print_parens(left, right, s):
        if right == n:
            print(s)
            return
        if left < n:
            print_parens(left + 1, right, s + "(")
        if right < left:
            print_parens(left, right + 1, s + ")")

    print_parens(0, 0, "")

I also corrected some formatting issues, following PEP8.

Use generators

Instead of printing, it would be nicer to return a generator:

def compute_all_parens(n):
    def compute_parens(left, right, s):
        if right == n:
            yield s
            return
        if left < n:
            yield from compute_parens(left + 1, right, s + "(")
        if right < left:
            yield from compute_parens(left, right + 1, s + ")")

    yield from compute_parens(0, 0, "")

This will give callers the freedom to do whatever they want with the combinations.


Stuff I noticed:

Use next to skip an each-iteration instead of wrapping everything in an if statement
No need for Set. A hash's keys are already a set, so in your compute_jaccard_coefficients method you could just call all_activties = users_for_activities.keys and done. From the raw data, you could do all_activities = parsed_data.map { |user| user['activities'] }.flatten.uniq
I'd absolutely avoid returning a tuple from the compute_jaccard_coefficients method. As illustrated above, getting all the activities isn't difficult; you can do that anywhere. And the method itself doesn't use the set for anything; creating the set is just something it also does, even though it shouldn't be its responsibility. Your code definitely shouldn't rely on a method just randomly doing something
Since your method is checking combinations of activities, you might as well use Array#combination. Give it an argument of 2 and it'll give you an array of pairs activities. Note that it'll also give only unique combinations - i.e. you'll get a pair like ["tennis", "swimming"], but it'll skip ["swimming", "tennis"] since that's the same combination.
Favor methods like any? (or better - as Naklion points out in the comments - empty?) over checking an array's length with arr.count > 0

With the above in mind, the method can be written as

def compute_jaccard_coefficients(hash)
  coefficients = hash.keys.combination(2).map do |a, b|
    union = hash[a] | hash[b]
    weight = union.empty? ? 0 : (hash[a] & hash[b]).count / union.count.to_f
    [[a, b], weight]
  end
  Hash[coefficients]
end

Note that this implementation also gives you a cleaner result (no duplicate combinations) in fewer iterations.

I'm out of time right now, but I'll take a look at the rest of the code later.

Update: It's now "later", and Naklion has provided a very nice answer. Still, I'll give it a go too.

I used combination above, whereas Naklion used permutation. The latter gives an identical result to the original code (i.e. the coefficients hash will have keys for both tennis/rowing and rowing/tennis). Using combination you'll only get unique combinations, and thus fewer coefficient calculations, but lookup gets a bit more complex (which I wasn't considering when just looking at the Jaccard method). Still, since Naklion used permutations, I'll stick to combinations.

One addition, though, is to use Set (after all) to create the keys of the Jaccard hash:

def compute_jaccard_coefficients(hash)
  coefficients = hash.keys.combination(2).map do |a, b|
    union = hash[a] | hash[b]
    weight = union.empty? ? 0 : (hash[a] & hash[b]).count / union.count.to_f
    [Set[a, b], weight]
  end
  Hash[coefficients]
end

This allows us to look up weights without worrying bout the order of the key's elements, since Set[a, b] == Set[b, a].

Naklion provided a nice way (#9 on the list) to transpose the parsed_data from user-indexed activities to activity-indexed users, so I'll skip over that.

So starting with this (and the method above)

all_activities = users_for_activities.keys
coefficients = compute_jaccard_coefficients(users_for_activities)

you can do this

parsed_data.each do |user|
  possibles = all_activities - user['activities'] # activities the user doesn't have already
  recommendations = user['activities'].product(possibles).map do |a, b|
    # a is the user's existing activity, b is the recommended activity
    key = Set[a, b]
    [b, coefficients[key]] if coefficients[key] > 0
  end.compact.sort_by(&:last).reverse

  puts "User #{user[:user]}: #{recommendations}"
end


Here are some things that may help you improve the quality of your code.

Don't handle message parsing in an interrupt

You don't explicitly say it, but from the context, it appears that you're attempting to parse a serially received message in an interrupt handler.  This is usually not a good idea.  An interrupt handler should be fast and do the minimum amount of work possible.  For serial message protocols, this typically means reading each character, putting it into a memory buffer (most often implemented as a circular buffer) and updating pointers.  Then the main routine that is NOT in an interrupt reads the contents of the buffer and does any message parsing/handling.

Don't parse until you have a complete message

In this case the message length appears to be 8 bytes (6 header + 2 trailer) plus the size of the enclosed data. It also appears that there is some kind of special marker for the beginning of the message.  So a quick check for the message parser would be something like this:

are there at least 8 bytes?
is the first character the message marker byte?

If the answer to either question is "no," it can't be a real message and so the data may be left in the buffer until more is received.  If the answer to both questions is "yes," then it might be a message.  The next steps might be:

does the message have at least 8+msg_length bytes?
is the checksum correct?

If the answer to both questions is "yes" then you can actually act on the message (typically by passing it to some higher layer protocol handler).

Use a state machine

The typical way to parse messages like this is to use a state machine. In this case the states might be:

waiting for message marker byte
receiving header
receiving data
receiving trailer

There are also often states for error and for timeout.

Avoid the use of "magic numbers"

This code is littered with "magic numbers," that is, unnamed constants such as 400, 512, 10, 5, etc.  Generally it's better to avoid that and give such constants meaningful names.  That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of "5" and then trying to determine if this particular 5 means an offset into the message structure or some other constant that happens to have the same value.

Beware of buffer overflow

The allocation of a fixed 400 bytes for data might be OK, but if so, then you absolutely need to make sure that the message will fit in that space before copying it.  Failure to do so leads to the possibility of buffer overflow.


A caching strategy is not well thought. There is no clear scenario, whether a cached or a non-cached version should be used. Besides, a cache must have a timeout after which it is considered staled and must be renewed.

There is also a filename issue. With only a filename, which makes a relative path, you will end up with having a cachedFeed.json file in the every directory. The filename must be unique and certain, which means it must include an absolute path to the file.

Another possible issue is a case when 2 feeds are used on the same site. What would happen to a cache file in this case? A filename must be unique. the simplest solution would be just md5() from the feed url.

Other minor issues include excessive naming. your class already have the word Feed in its name, no need to duplicate it in the method names. Also, there are a lot of class variables that a never actually used.

So the final code could be like

<?php
class NewsFeed
{
    protected $url;
    protected $cacheFilename;
    protected $cacheTimeout = 3600;

    public function __construct($url)
    {
        $this->url = $url;
        $this->cacheFilename = $this->buildCacheFilename();
    }

    public function get()
    {
        $json = $this->readCached();
        if(!$json) {
            $json =  $this->download();
        }
        return json_decode($json, true);
    }

    protected function download()
    {
        $xml = simplexml_load_file($this->url, 'SimpleXMLElement', LIBXML_NOCDATA);
        $json = json_encode($xml);
        file_put_contents($this->cacheFilename, $json);
        return $json;
    }

    protected function readCached()
    {
        if (!file_exists($this->cacheFilename)) {
            return false;
        }
        if (filectime($this->cacheFilename) < (time() - $this->cacheTimeout)) {
            return false;
        }
        return file_get_contents($this->filename);
    }

    protected function buildCacheFilename()
    {
        return $_SERVER['DOCUMENT_ROOT'] . "../cache/feed" . md5($this->url);
    }
}

So we have just a single method get() to read the feed contents, which is first checking for the cached version and then reads the feed online if the cache is not available. A timeout is implemented to make sure that the cached data doesn't get too old and outdated.


Private VBA Class Initializer called from Factory

This is not so much an review but a variation of the OP's technique.   As  Mathieu Guindon mentioned in the comments the "logic needs to be encapsulated".  My Caster class does just that.  The Person class is just for testing.
Caster:Class
Attribute VB_Name = "Caster"
Option Explicit

#If Mac Then
    #If VBA7 Then
        Private Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As LongPtr) As LongPtr
    #Else
        Private Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, Source As Any, ByVal Length As Long) As Long
    #End If
#Else                                            'Windows
    'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
    #If VBA7 Then
        Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
    #Else
        Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    #End If
#End If

#If Win64 Then
    Private Const PTR_SIZE As Long = 8
#Else
    Private Const PTR_SIZE As Long = 4
#End If

#If VBA7 Then
    Private SourcePointer As LongPtr
    Private DestinationPointer As LongPtr
#Else
    Private SourcePointer As Long
    Private DestinationPointer As Long
#End If

Public Sub SaveAs(ByRef Source As Object, ByRef Destination As Object)
    DestinationPointer = VarPtr(Source)
    Do
        DestinationPointer = DestinationPointer + PTR_SIZE
        CopyMemory SourcePointer, ByVal DestinationPointer, PTR_SIZE
    Loop Until SourcePointer = ObjPtr(Source)

    CopyMemory ByVal DestinationPointer, ObjPtr(Destination), PTR_SIZE
End Sub

Public Sub Restore()
    CopyMemory ByVal DestinationPointer, SourcePointer, PTR_SIZE
End Sub

Person:Class
Note:  The Init method is just to demonstrate the OP's original concept.  It could be replaced with  m = t.
Attribute VB_Name = "Person"
Attribute VB_PredeclaredId = True

Option Explicit

Private Type Members
    DOB As Date
    Name As String
    Sex As String
End Type

Private this As Members

Public Function Factory(pDOB As Date, pName As String, pSex As String) As Person
    DOB = pDOB
    Name = pName
    Sex = pSex
    Set Factory = Clone
End Function

Public Function Clone() As Person
    Dim Object As Person
    Set Object = New Person

    Dim Caster As New Caster

    Dim t As Members
    t = this
    Caster.SaveAs Me, Object
    Init t
    Caster.Restore
    Set Clone = Object
End Function

Private Sub Init(t As Members)
    this = t
End Sub

Public Property Get DOB() As Date

    DOB = this.DOB

End Property

Public Property Let DOB(ByVal Value As Date)

    this.DOB = Value

End Property

Public Property Get Name() As String

    Name = this.Name

End Property

Public Property Let Name(ByVal Value As String)

    this.Name = Value

End Property

Public Property Get Sex() As String

    Sex = this.Sex

End Property

Public Property Let Sex(ByVal Value As String)

    this.Sex = Value

End Property

Test
Sub TestClone()
    Dim Tom As New Person
    With Tom
        .DOB = #7/26/1970#
        .Name = "Tom"
        .Sex = "M"
    End With

    Debug.Print "TestClone"
    With Tom.Clone
        Tom.Name = "Thomas"
        Debug.Print "DOB: ", .DOB
        Debug.Print "Name: ", .Name
        Debug.Print "Sex: ", .Sex
    End With
    Debug.Print
End Sub

Sub TestFactory()
    Dim Tom As Person
    Set Tom = Person.Factory(#7/26/1970#, "Tom", "M")
    Person.Name = "Thomas"
    Debug.Print "TestFactory"
    With Tom
        Debug.Print "DOB: ", .DOB
        Debug.Print "Name: ", .Name
        Debug.Print "Sex: ", .Sex
    End With
End Sub


Populate list with Excel range and keep formatting

variable names

1-letter variable names are difficult to understand. Correct names for variables, functions and classes goes already a long way to comment the intent of the code.
r is a data range, c is a cell, l is the last row in the range, then call em thus

functions

I would extract the code that is needed to parse 1 cell:

def convert_cell(data):
    """converts a single cell"""
    data_string = str(data)
    if data_string == "0.0":
        return "0"
    if data_string[0] == 0:
        return data_string
    if data_string == "None":
        return ""
    try:
        float(data_string)
        return str(int(data))
    except ValueError:
        return data_string

The advantage is that you cal skip some levels of nesting, and it is really clear what each type of input get transformed to. I also refactored the multiple calls to str(c) to a variable

generator

Instead of starting a list, and appending to it, you can better yield the results.

def convertdata(data_range, last_column):
    for cell in data_range:
        yield convert_cell(cell)
        is_last_column = cell.Column == last_column
        is_last_row = cell.Row - 1 == data_range.Rows.Count
        yield "\n" if is_last_column and not is_last_row else "\t"

data_range = sheet.Range(sheet.Cells(2, 1), sheet.Cells(lrow, lcol))
dataf = ''.join(convertdata(data_range, lcol))


Yeah, sure, I could just get rid of the if's and else's and replace ((Item)list...) with Item item = list... and wrap it all in a single Try{}Catch{}, but I really do hate using Try{}Catch{} unless there is something I am not expecting. And to be honest, using Try{} Catch{} makes me feel lazy and like I'm not doing it properly.

That is true. The best exception is the exception which will be avoided.

That beeing said, I need to tell you that you are using the arrow antipattern here.

How about reversing the conditions by using guard clauses and return early like

if (list.Items.Count == 0)
{
    status.Text = "There are no items in the list.";
    return;
}
if (list.SelectedItems.Count == 0)
{
    status.Text = "You haven't selected an item in the list.";
    return;
}

........

or maybe add a method which returns a string for a not satisfied condition and an empty string for a satisfied condition like so you can place these guard clauses in a separate method.

If I read recording I think about a boolean. Maybe it is only me, but I would rename the variable to audioContent or recordedContent to be more clear.

Avoiding braces {} for single instruction ifand else can lead to serious problems. I would like to encourage you to always use them.

Btw, your method is doing too many things and is therefor violating the single responsibiliy principle. The method is validating conditions, updating the GUI and also playing the audio stream.


Convert letters into numbers (A=1, B=2 etc)

You might try something like:

self.numname = [rosetta[x] for x in self.name]

This creates the list of numbers directly from the letters in the name, using a list comprehension.


Small Python class for Lindenmayer Systems

This is a neat implementation of Lindenmayer systems. I have some suggestions for simplifying and organizing the code.

The docstring for a method or a function comes after the def line (not before, as in the code here). So you need something like:

def evaluate(self, depth):
    """Evaluate system by recursively applying the rules on the axiom."""
    for symbol in self.axiom:
        self.evaluate_symbol(symbol, depth)

and then you can use the help function from the interactive interpreter:

>>> help(LSystem.evaluate)
Help on function evaluate in module LSystem:

evaluate(self, depth)
    Evaluate system by recursively applying the rules on the axiom.

The Symbol class is redundant — it only has one attribute, and doesn't have any methods other than the constructor. Instead of constructing Symbol objects, you could just use functions:

def A():
    print('A', end='')

def B():
    print('B', end='')

and instead of calling symbol.leaf_function(), you could just call symbol().

In the Koch example, you already have functions so you can just omit the construction of the Symbol objects and write:

koch_curve_system = LSystem(
    axiom = [draw_forward, turn_right, turn_right, draw_forward, turn_right,
             turn_right, draw_forward],
    rules = {
        draw_forward: [draw_forward, turn_left, draw_forward,
                       turn_right, turn_right, draw_forward, turn_left,
                       draw_forward],
    }
)

Alternatively, you could rename the functions and leave the definition of the system unchanged.
The code in evaluate is very similar to the code in evaluate_symbol. This suggests that it would result in simpler code if you described the Lindemayer system in a different way, giving an initial symbol instead of an initial list of symbols. (And possibly giving an extra rule mapping the initial symbol to a list.)

If you try this, then you'll find that the LSystem class is redundant too: the only thing you can do with it is to call its evaluate method, so you might as well just write it as a function:

def evaluate_lsystem(symbol, rules, depth):
    """Evaluate a Lindenmayer system.

    symbol: initial symbol.
    rules: rules for evolution of the system, in the form of a
        dictionary mapping a symbol to a list of symbols. Symbols
        should be represented as functions taking no arguments.
    depth: depth at which to call the symbols.

    """
    if depth <= 0 or symbol not in rules:
        symbol()
    else:
        for produced_symbol in rules[symbol]:
            evaluate_lsystem(produced_symbol, rules, depth - 1)

Then the algae example becomes:

evaluate_lsystem(A, {A: [A, B], B: [A]}, 4)

In the snowflake example, there is persistent shared state (the position and heading of the turtle). When you have persistent shared state it makes sense to define a class, something like this:

class Turtle:
    """A drawing context with a position and a heading."""
    angle = 0
    x = 0
    y = WINDOW_SIZE[1]*3/4

    def forward(self, distance):
        """Move forward by distance."""
        start = [self.x, self.y]
        self.x += distance * cos(self.angle)
        self.y += distance * sin(self.angle)
        end = [self.x, self.y ]
        pygame.draw.line(window, LINE_COLOR, start, end, LINE_WIDTH)

    def turn(self, angle):
        """Turn left by angle."""
        self.angle += angle

and then:

turtle = Turtle()
forward = lambda: turtle.forward(1)
left = lambda: turtle.turn(pi/3)
right = lambda: turtle.turn(-pi/3)
initial = lambda: None
rules = {
    initial: [forward, right, right, forward, right, right, forward],
    forward: [forward, left, forward, right, right, forward, left, forward],
}
evaluate_lsystem(initial, rules, 5)


vector<int> potential_cameras;
        for (auto i : indexes){
            for (auto x : dict[i]){
                potential_cameras.push_back(x);
                }
            }
        sort(potential_cameras.begin(), potential_cameras.end());

Let's review the important constraints:

At most 5 brands
At most 10000 cameras
Up to 10000 queries

So this code is executed up to 10000 times, and each time is filtering up to 10000 cameras and then sorting up to 10000 cameras.

Given that each query includes at least one brand out of the five, there are only 31 possible brand combinations. So by pre-computing you could execute this code 31 times rather than 10000 times, and since it's the obvious candidate for the bottleneck that might give you a 300-times speedup.

If that's still not fast enough, then you need to look at linear time median algorithms. But frankly if the queries are evenly distributed then ~300 queries per brand combination is much larger than \$\lg 10000 \approx 13\$, so it's probably faster to quicksort once per combination than to execute a linear time median once per query. If you really want to overkill it then you could create a custom data structure which supports multiple median queries by maintaining state of which ranges of the array have been partitioned around which pivot, but KISS, YAGNI.

Alternatively, but still violating KISS, you could do just five sorts (one per camera) and then some complicated multiple binary chop. I'd still prefer one sort per brand combination.


Is the code prone to SQL injection or to any other kind of threat

SQL injection should not be a problem, as long as you pass any user input to queries through placeholders, which you do.

I have a few other remarks though

Single Responsibility Principle

In the first code snippet you do too much things. You decode request json, you talk to db. you handle the logic, you maintain response structure. It would be wise to separate those things into their own scopes (functions/classes). Of course if this is all you ever intend to have there may be no point. But in general, in future you will want to reuse the individual pieces.

Global Scope vs. Classes and Dependency Injection

You may want to avoid definind global variables. It's generaly considered bad practise for several reason which I'm not gonna repeat here as there is plenty of information sources for this already.

You are probably not very familiar with the concept of OOP, but wrapping those function into class scopes and working with objects may be something for you to learn.

If you want to stick with procedural style, maybe at least get rid of the globals by passing the db connection always as function parameter.

if (clientExists($connection, $clientName)) {...}

It is annoying but it is still better then globals, in some ways anyway.
That where the objects could help if you get used to it.

$users->exists($clientName)

Data Validation

You check that $input['clientName'] is set. Is it enough? What if it is empty? What if it is array or number? Is it ok? What if $input is not an array in the first place? All that should be handled.

Validation is btw, yet another responsibility that might be separated to its own function.

Useless Statements

In the clientExists() function I think you fetch the row for now reason. It should be able to tell count without fetching it.
You can also simplify the select from SELECT clientName to SELECT 1 which is, IMO, cleaner as you could actualy select any of the table's column for it to work and if that column ever changes name this would have to change too.

Public API

At this point your api is public in whichever network in which it is deployed. As this network is probably going to be the internet (I suppose), anyone will be able to call it. Is it ok if any anonymous client can succesfully call this endpoint and so create db entries? You may want to have some way of authentication, but this depends on your use-case.


Importing an Excel document into a project

First of all, better names than columnX would be nice. I guess the indentation is a copying-issue, otherwise this would be the next optimization. Furthermore I have the feeling that mixing the && and the || in your condition without parenthesis is not what you want to do?

col0empty=checkIfColumnisEmpty(r.ItemArray[0])
col1empty=checkIfColumnisEmpty(r.ItemArray[1])
col2empty=checkIfColumnisEmpty(r.ItemArray[2])
col3empty=checkIfColumnisEmpty(r.ItemArray[3])
col4empty=checkIfColumnisEmpty(r.ItemArray[4])
col5empty=checkIfColumnisEmpty(r.ItemArray[5])

if ((!col0empty || !col1empty) && col2empty && col3empty && col4empty && col5empty)
{
    if (col0empty && !col1empty) errorWithEmptyColumn("First");
    else if (!col0empty && col1empty) errorWithEmptyColumn("Second");
    else if (!col0empty && !col1empty)
    {
        //Code after validation
    }
}
else if ((col0empty && col1empty) || !col2empty || !col3empty || !col4empty || !col5empty)
{
    if (col2empty) errorWithEmptyColumn("Third");
    else if (col3empty) errorWithEmptyColumn("Fourth");
    else if (col4empty) errorWithEmptyColumn("Fifth");
    else if (col5empty) errorWithEmptyColumn("Sixth");
    else
    {
        //Code after validation
    }
}
else
{
    throw new ImportBOQException("Error Uploading"); //don't throw raw exceptions
}
// } one to much

private void errorWithEmptyColumn(String columnName) throws ImportBOQException
{
    throw new ImportBOQException("Error importing document: "+columnName+" column is empty");
}

For further optimization it is import to know how similar the code in the two remaining branches is?

You could also extract the condition in an variable and give them a name: i.e. rowTypeX and rowTypeY. Maybe the result is more intuitive if you move the handling of the row types in a method each:

empty=col0empty && col1empty && col2empty && col3empty && col4empty && col5empty
rowTypeX=col2empty && col3empty && col4empty && col5empty;
rowTypeY=col0empty && col1empty;
if ( empty) throw new ImportBOQException("Empty row");
else if (rowTypeX) handleRowTypeX(r);
else if (rowTypeY) handleRowTypeY(r);
else throw new ImportBOQException("Error Uploading");


Extract numbers from a string-Javascript

I used the following regexp to extract numbers from a string:

var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);


Table of Tribonacci sequence using NumPy and PANDAS

You’re using the wrong tool for the job. Basically, you do all the computation in Python, use numpy for intermediate storage and pandas for display.

Instead, you should compute the list of tribonacci numbers and from there on use pandas for anything else as it would be much more efficient / readable. I’d keep building the tribonacci numbers in Python as I don't know enough pandas to be able to come up with an efficient way that wouldn't involve Dataframe.append and also because it can be expressed very nicely as a generator:

def tribonacci_sequence():
    a, b, c = 0, 1, 1
    yield a
    yield b
    while True:
        yield c
        a, b, c = b, c, a + b + c

You can then select the amount of numbers you like using itertools.islice and give them to a pandas.Dataframe.

From there on, you can easily compute the ratio by shifting the dataframe and dividing element-wise:

def compute_tribonacci(upper_limit, skip_first_rows=3):
    tribonacci = list(islice(tribonacci_sequence(), upper_limit + 1))
    df = pd.DataFrame({'Number sequence': tribonacci})
    df['Ratio'] = df['Number sequence'] / df.shift(1)['Number sequence']
    df.index = df.index.map('Number: {}'.format)
    return df.iloc[skip_first_rows:]

Last thing to do is to actually ask for a certain amount of rows. Full code:

from itertools import islice
import pandas as pd

def tribonacci_sequence():
    a, b, c = 0, 1, 1
    yield a
    yield b
    while True:
        yield c
        a, b, c = b, c, a + b + c

def compute_tribonacci(upper_limit, skip_first_rows=3):
    tribonacci = list(islice(tribonacci_sequence(), upper_limit + 1))
    df = pd.DataFrame({'Number sequence': tribonacci})
    df['Ratio'] = df['Number sequence'] / df.shift(1)['Number sequence']
    df.index = df.index.map('Number: {}'.format)
    return df.iloc[skip_first_rows:]

if __name__ == '__main__':
    df = compute_tribonacci(50)
    print(df)


Design

Not sure why you have a virtual function on the worker?

virtual void exec_job(JobItem* job_item) = 0;

The worker is simple he picks up jobs and then does them. What the job is defines what work should be done. So I would have put the virtual function that defines the work on the JobItem.

The run() function of the worker is then simply.

void run()
{
    // You want some way for the thread to eventually exit.
    // You can make that happen by letting the queue return
    // a null object when the object is being shut down.
    JobItem* job;
    while(job = shared_job_queue_->pick())
    {
        job->do();
        delete job;
    }
}

Code Review

Prefer not to use pointers.

Pointers don't have the concept of ownership semantics. So we don't know who is responsible for deleting them. Use a type that conveys ownership semantics so the person reading the code understands the semantics.

 JobQueue* shared_job_queue_;

You always need a job queue. So this can never be nullptr. So rather than a pointer a better choice would have been a reference. Also a reference implies there is no ownership of the object so you are not supposed to delete it.

class JobWorker
{
private:
    JobQueue& shared_job_queue_;
public:
    JobWorker(JobQueue& shared_queue)
        : shared_job_queue_(shared_queue)
    {}

Again in the JobQueue. You push and pop pointers. So there is no concept of ownership.

class JobQueue
{
private:
    queue<JobItem*>                 job_queue_;
public:
    // Definitely I need to use mutex and condition variable here
    JobItem* pick();
    void push(JobItem* job_item);
};

As a user of this class I could easily accidently pass the address of a Job object that is actual an automatic variable. Unless I read the code it is not obvious that the code will blow up. Even worse the code may not blow up for a while since the pointer is not deleted until after the work has been done.

In this case I would use a smart pointer. The obvious one is std::unique_ptr. When you use this as a parameter you are indicating that you are accepting ownership of the object.

class JobQueue
{
private:
    // You are maintaining a queue of owned pointers.
    // You will take responsibility for deleting them when this
    // object is destroyed.
    queue<std::unique_ptr<JobItem>>      job_queue_;
public:
    // This method returns a pointer.
    // More importantly it is returning ownership of the pointer to
    // you uniquely so you are the sole owner of the pointer and the
    // JobQueue is no longer retaining any pointers to this object.
    std::unique_ptr<JobItem> pick();

    // This method accepts a unique_ptr.
    // Because it accepts the unique_ptr by value you are loosing
    // ownership. Once this method is called you will no longer own
    // the object it will be gone from the object you passed.
    void push(std::unique_ptr<JobItem> job_item);
};

Use modern C++

Its 2016. C++11 has been out for 5 years. C++14 has been out for two years. Both have std::thread and the associated parallel libraries.


Smart Pointers with Reference Counting - C++

Review

Issue

My first issues is that using your shared pointer is not safe. Once I give you the pointer. You are responsible for deleting it all situations (especially when exceptions happen).

But if the call to new PointerWrapper(p, 1) fails. ie it throws BadAlloc then you will leak my object. So you need to watch out for that allocation and delete the pointer immediately if you throw.

Missing Feature

You have not implemented move semantics. This is absolutely essential.

Your object is missing a swap function.

Design

I don't think the class PointerWrapper buys you ay functionality or makes the code any easier to write.

nullptr

Prefer to use nullptr over 0 as the non existing pointer. 0 is a number and can easily be converted to other things when you least expect it. nullptr of std::nullptr_t and can only be assigned to pointers and is not auto converted into other things.

General grumbles

I think the assignment operator is overly complex. It would be much simpler to write this as using the standard copy and swap idiom.

    SmartPtr& operator=(const SmartPtr& copyObj)
    {
         SmartPtr  copy(copyObj);
         copy.swap(*this);
         return *this;
    }

This logic seems a bit overly complex.

        unsigned int preReleaseRefCount = ptrWrapper_->getRefCount();
        ptrWrapper_->decrementRefCount();
        if(preReleaseRefCount==1)
        {
          delete ptrWrapper_;
          ptrWrapper_ = 0;
        }

Personally I would have got decrementRefCount() to return true if it deleted the object.

        if (ptrWrapper_->decrementRefCount())
        {
          delete ptrWrapper_;
        }

No point in setting the ptrWrapper_ to nullptr

           ptrWrapper_ = 0;

When the very next statement sets it to another value.

        ptrWrapper_ = copyObj->ptrWrapper_;

Self Plug

These articles are a good read (I wrote them):

Unique Ptr
Shared Ptr
Constructor


Rails controller method to show an optionally scaled image using MiniMagick

Rubocop Report

Conventions

Prefer key? over has_key? (PreferredHashMethods).

if params.has_key?(:thumbnail)

if params.key?(:thumbnail)

Prefer single quoted over double quoted string literals if you don't need interpolation or special symbols (StringLiterals).

image.resize("50x60")

image.resize('50x60')

Complexity

  If block in a separate, private method maybe?

The AbcSize complexity of your method is too high. [19.65/15] So your suggestion to put the following code in a private method, is justified.

 document = identification_document.id_document
 image = MiniMagick::Image.read(document.file.read)
 image.resize("50x60")
 scaled_image_bytes = image.to_blob

Readability

Keep line sizes below 80 characters:

send_data(identification_document.id_document.file.read, filename: identification_document.file_name)