Refactor a subroutine that divides date range into quarters.

I am a bit lost in terms of what you are actually trying to accomplish, but I can give some pointers.

First, leap years do not particularly impact quarters unless you truly have some unique rules. Under normal behaviors, February 29 will be in the same quarter as February 28, and would solidly fall inside quarter 1 in your given scenario.

Secondly, a quick way to figure out the quarter of a given date (if your quarter system starts at January 1) is the following formula

Dim currentQuarter as Integer = currentDateTime.Month \ 3 + 1

Similarly, you can perform operations to arrive at quarter beginning and ending dates.

Dim quarterStart = new DateTime(currentDateTime.Year, 3 * (currentQuarter - 1) + 1, 1)
Dim quarterEnd = quarterStart.AddMonths(3).AddSeconds(-1)

For example, using today as the base, you could test the code

Dim currentDateTime = DateTime.Now

Dim currentQuarter = currentDateTime.Month \ 3 + 1
Dim quarterStart = new DateTime(currentDateTime.Year, 3 * (currentQuarter - 1) + 1, 1)
Dim quarterEnd = quarterStart.AddMonths(3).AddSeconds(-1)

Console.WriteLine(currentQuarter)
Console.WriteLine(quarterStart)
Console.WriteLine(quarterEnd)

And see these results

2
4/1/2011 12:00:00 AM
6/30/2011 11:59:59 PM


Calculating work using dot product in C++

using namespace std should be avoided

Not much more to say than that. Just don't do it. The worst case is putting it into a header. Next is using it outside any namespace, so you've done the second worst possible incarnation of this particular problem.

Typing std::cout instead of cout really isn't going to cause you a lot of problem, I promise.

Don't Repeat Yourself

You have essentially identical code for entering the two input vectors. You probably want to use a function to enter the values for a vector, and just call it once for each input vector.

Use the Library

As a general rule, I'd avoid using built-in arrays when at all reasonable. In this case, you can use std::array instead:

std::array<double, 3> F;
std::array<double, 3> s;

The standard library already provides std::inner_product to do exactly the calculation you're doing. You might as well use it:

double W = std::inner_product(F.begin(), F.end(), s.begin(), 0.0);


Initializing object variables

  private Map<String, ArrayList<Consumer<?>>> topicsSubscribers =
      new HashMap<String, ArrayList<Consumer<?>>>();

The standard is to set the types as the interfaces, like Map and List.

    private final Map<String, List<Consumer<?>>> topicSubscribers = new HashMap<>();

Also, you don't need to specify the contents of <> in the implementation instantiation.  The compiler will work that out for you.

Initializing class variables

  private static PubSub pubSubSingleton = null;

  public static PubSub getInstance() {
    if (pubSubSingleton == null)
      pubSubSingleton = new PubSub();

    return pubSubSingleton;
  }

You don't have to do it this way.  You can simply say

    private static final PubSub pubSubSingleton = new PubSub();

    public static PubSub getInstance() {
        return pubSubSingleton;
    }

    private PubSub() {
    }

This saves the null check each time while still only initializing once.

However, Singleton is generally considered an anti-pattern now.  You may want to consider alternatives.  One possibility would be a separate instance for each message type.

Your original code does not make the constructor private.

The Java standard is four column indents rather than the two you are using.

Formatting

    if (subscribers == null)
      return;

If you are going to use the statement form, you should probably keep it one line:

    if (subscribers == null) return;

If it's too complicated to fit into one line, you should probably use the block form instead.

I actually use the block form consistently regardless.

    if (subscribers == null) {
        return;
    }

Factor out the common

    if (subscribers == null) {
      subscribers = new ArrayList<Consumer<?>>();
      subscribers.add(subscriberCallback);
      this.topicsSubscribers.put(topicName, subscribers);
    } else {
      subscribers.add(subscriberCallback);
    }

This could be

    if (subscribers == null) {
        subscribers = new ArrayList<Consumer<?>>();
        topicsSubscribers.put(topicName, subscribers);
    }

    subscribers.add(subscriberCallback);

You don't have to do the add before the put.  It's the same object either way.  Otherwise, you'd have to do the put after the add in the non-null case.


Preprocess HTML input and generate word count

If I may suggest, using a tool like Beautiful Soup can greatly help you get around html elements in a simple way

http://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup/

Here you have a very brief example on how it operates

from bs4 import BeautifulSoup
import requests

r  = requests.get("http://any_url_you_want.com")

data = r.text

soup = BeautifulSoup(data)

for text in soup.find_all('text'):
    # Here you do whatever you want with text

You can adapt your methods to use the functions depending on the tags, or however you want

Check also this article, explains quite well what you can do with it and is accessible for beginners

https://www.digitalocean.com/community/tutorials/how-to-scrape-web-pages-with-beautiful-soup-and-python-3


For beginner code, that's reasonably good.

Instead of calling setTimeout() yourself, why not let jQuery handle the animation for you with .animate()?
Your indentation is wrong, as evidenced by

  }
  }
}

at the end.  I believe that two spaces is too stingy for readability, and also encourages excessive nesting, which is poor programming practice.  For example, the entire doMove() function should do nothing unless key == "on", so you could eliminate one layer of nesting by returning early:

function doMove() {
    if (key != "on") {
        return;
    }
    ...
}

You use magic numbers 4 and 100.  Don't hard-code 4; detect it as menuID.length instead.  You should be able to detect the height as well; it not, then hard-code 100 as a named constant rather than being casually embedded as a loop limit.
Storage of state feels clumsy.  Use booleans (true and false) instead of strings ("on" and "off").  Naming could be better — I suggest menuElements rather than menuID, and animationPosition rather than menuState.  You should be able to use fewer variables.  For example, key and menuKey could be collapsed down to one scalar called activeMenuItem.

var activeMenuItem;
var menuElements = [];
var animationPosition = [0, 0, 0, 0];

$(document).ready(function () {
    init();
    $('.menu').mouseenter(function () {
        activeMenuItem = this;
        doMove();
    });
    $('.menu').mouseleave(function () {
        activeMenuItem = null;
    });
});

function doMove() {
    var check = false;
    for (var i = 0; i < menuElements.length; i++) {
        if (menuElements[i] == activeMenuItem) {
            if (animationPosition[i] < 100) {
                animationPosition[i] += 2;
                menuElements[i].style.backgroundPosition="0px " + animationPosition[i] + "px";
            }
            check = true;
        } else if (animationPosition[i] > 0) {
            animationPosition[i] -= 2;
            menuElements[i].style.backgroundPosition="0px " + animationPosition[i] + "px";
            check = true;
        }
    }
    if (check) {
        setTimeout(doMove, 1); // call doMove in 20msec
    }
}

Initialization of menuID scales poorly with additional menu items.  Try selecting all $('.menu') instead of individually named elements.


First of all, I'd use RecursiveDirectoryIterator, removed globals and corrected formatting.

Then used Xdebug + CacheGrind to try different versions.


A shorter version, functionally equivalent to yours:

def dict_zip(*dicts):
    return {k: [d[k] for d in dicts] for k in args[0].keys()}

That's assuming all dicts have the same keys, or more exactly, all dicts have at least all the keys present in the first dict.

To make it more robust and handle cases when dicts don't have the same keys:

def dict_zip(*dicts):
    all_keys = {k for d in dicts for k in d.keys()}
    return {k: [d[k] for d in dicts if k in d] for k in all_keys}

Regarding type hints: not sure, but it might be something based on typing.MutableMapping. But that's Python 3.

EDIT

To add padding for keys which are not present in all dicts:

def dict_zip(*dicts, fillvalue=None):
    all_keys = {k for d in dicts for k in d.keys()}
    return {k: [d.get(k, fillvalue) for d in dicts] for k in all_keys}

If you have to use Python 2 (if you can, upgrade to Py3 for your own good):

def dict_zip(*dicts, **kwargs):
    fillvalue = kwargs.get('fillvalue', None)
    all_keys = {k for d in dicts for k in d.keys()}
    return {k: [d.get(k, fillvalue) for d in dicts] for k in all_keys}

Notice that you could just do kwargs.get('fillvalue') and if 'fillvalue' is not in kwargs, get would return None anyways. But explicit is better than implicit.


Count combinations of positive and negative that sum to target number

The question as asked by OP left out one crucial piece of information: The constraints of the problem. Listed below:

  Note: The length of the given array is positive and will not exceed
  20. The sum of elements in the given array will not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer.

And herein lies a big hint: The sum of all elements will not exceed 1000 (and all input values are positive). This is the creators of the problem telling you that you can trade fixed size memory for speed, which wouldn't be possible if this constraint was not present.

Note that that "The result will fit in a 32 bit integer" is redundant and over estimated, as there can be max 20 elements only 2^20 combinations of +- exist and thus only 20 bits are needed to store the result, incidentally this means that you only need to try 1 million combinations of +- to brute force the problem which shouldn't take much more than 20 numbers*1 million combinations*instructions per number, which would be at most a second or so on a modern machine unless you botch the implementation.

Because addition and subtraction commutes you can sort the array without affecting the result. The individual solutions may change but not the number of solutions. This together with bounding of the largest possible remaining sum can be used to prune some branches from the search to improve upon brute force.

In general, the constraints are such that the brute force solution implemented efficiently should be enough, but we can do better if we use some memory.

Imagine an array A which can be indexed by values -1000 to 1000 (just offset the index by +1000 in your code, mapping the range -1000...1000 to 0...2000).

Then, for each index I we store a value V which is how many ways we can compute a sum of I. So when we are done, the answer to the problem: "In how many ways can you assign +- to the input values so that their sum in S", will be A[S].

Pseudo-code:

Create two arrays A and B, indexable from -1000 to 1000 and set all elements to 0.
Take the first value from the input, call it: a
And set A[a] = 1 and A[-a] = 1
Take the next value from the input, call it: b
For every index i, where A[i] is non-zero do: B[i+b] += A[i], B[i-b] += A[i], A[i] = 0
Swap A and B
Repeat from 4 until no more input is available
Return A[S]

The above procedure will take 20 iterations of 4. to 7. with the maximum problem size. Step 5 requires a scan through A meaning 2000 loop iterations. So all in all for the max problem size 40k iterations of the inner most loop are needed. Lets estimate the inner loop body to be 10 instructions putting us at around 400k instructions which is around two orders of magnitude less than brute force.

The observant reader will note that there is a lot of wasted time in scanning through A in step 5 to find the non-zero entries. There is a way to avoid this by using an auxiliary array to store non-zero indexes for the next iteration to speed this up. The details of this are left as an exercise for the reader.

There is another optimisation that can be made to get rid of the cost of offsetting the indexes in the inner most loop, can you find it?


Well, following conventions helps making your code more understandable. One convention is, for methods that return a boolean, using a predicate as a name, or as said in this answer, using a question.

So to begin with, I'd name the method isAlreadyUsed.

A second improvement by following conventions would be using accessor methods:

node.getParent() instead of node.parent. But that depends on the scope of Node.

Item 14 in Joshua Bloch's Effective Java:

  In public classes, use accessor methods, not public fields


Randomly split a vector into N bins of random lengths

np.random.choice can just take an int, so that can simplify your code - no need to build up a range():

splits = sorted(1 + x
    for x in np.random.choice(len(vector)-1, nbins-1, replace=True))

When you build up the bins, you don't need a try/except (you know up front what the size is). You just need to iterate over the actual splits:

bins = []

last = 0
for split in splits:
    bins.append(permutation[last:split])
    last = split
bins.append(permutation[split:])


JS how to optimize function that finds the text value in gematria

The shortest approach is to parse the character with a base of 36 and get the delta of 9 for summing.

function gematria(text) {
    return [...text].reduce((s, c) => s + parseInt(c, 36) - 9, 0);
}

console.log(gematria("someText"));


You can make good use of std::adjacent_find. Like this:

std::string range_creator(std::vector<int> & vec)
{
    auto first = std::begin(vec), last = std::end(vec);
    if(first == last)
        return "";
    std::sort(first, last);
    std::stringbuf buffer;
    std::ostream os (&buffer);
    while(true)
    {
        auto mid = std::adjacent_find(first, last,
                [](int x, int y){ return x + 1 != y; });
        if(mid == last)
            break;
        if(first == mid)
            os << *first << ",";
        else
            os << *first << "-" << *mid << ",";
        first = ++mid;
    }
    if(first == --last)
        os << *first;
    else
        os << *first << "-" << *last;
    return buffer.str();
}

I think my code is still subject to further improvements, but I'm no expert, so I'll leave it to the community.


Updating state with React and Websockets

This seems reasonable. The most important part is that you do not mutate the react state in-place. By doing let currentUser = [...users]; you copy the state and instead mutate the copy, then assign it as the updated state.

An alternative would be to use .map and .filter to make your changes. I see this pattern more often than the state copy approach.

Example:

ws.on("feed", response => {
  const { new_val: next, type } = response; // Use destructuring and inline renaming.

  setUsers(users => {
    switch (type) {
      case "add":
        return [...users, next];

      case "change":
        return users.map(u => {
          // Only change the user specified in the message
          if (u.id === next.id) return {...u, name: next.name }
          return u;
          // or return users.map(u => u.id !== next.id ? u : ({...u, name: next.name})) if you prefer one-liners
        })

      case "remove":
        return users.filter(u => u.id !== next.id);

      default:
        return users;
    }
  });
});


The main problem is that elem traverses list and that is slow. It is better to use Data.Set or HashMap as this data structures allow sub-linear membership checking.

import qualified Data.Set as Set

hamx :: [Integer] -> [Integer] -> [Integer]
hamx ls = reverse . Set.toList . loop (Set.fromList ls)
  where
    loop res [] = res
    loop res (x:xs)
     | even x        && Set.member (div x 2) res = loop (Set.insert x res) xs
     | mod  x 3 == 0 && Set.member (div x 3) res = loop (Set.insert x res) xs
     | mod  x 5 == 0 && Set.member (div x 5) res = loop (Set.insert x res) xs
     | otherwise = loop res xs

Or a bit shorter (but less readable) version:

import Data.List (foldl')
import qualified Data.Set as Set

hamx :: [Integer] -> [Integer] -> [Integer]
hamx ls = reverse . Set.toList . loop (Set.fromList ls)
  where
    loop = foldl' (\res x -> if predicate res x then Set.insert x res else res)
    predicate res x = any (\y -> mod x y == 0 && Set.member (div x y) res) [2, 3, 5]

Using IntSet instead of Set is several times faster, but Daniel Fischer's solution is still several orders of magnitude faster.

I put a project with criterion benchmark here.


Creating an iOS form with many similar text field cells

As far as I can tell, the only difference between these objects is the placeholder text, right?  I'm not sure how valuable it is that we have so many text fields and don't have a way of accessing them individually (to know what the user input in each... but nonetheless...).

So all we need is an array with the placeholder strings, and a for in loop.

NSArray *placeholders = @[@"business_name", @"contact_name", @"address", @"city", @"region"];

NSMutableArray *textFields = [NSMutableArray arrayWithCapacity:placeholders.count];

for (NSString *placeholder in placeholders) {
    BPFormInputTextFieldCell *textField = [[inputTextFieldClass alloc] init];
    textField.backgroundColor = cellBgnd;
    textField .textField.placeholder = placeholder;
    textField.mandatory = YES;
    textField.textField.delegate = self;
    textField.customCellHeight = 40.0f;
    [textFields addObject:textField];
}

self.formCells = textFields;

So much copy-and-pasting should almost always be a red flag for needing a loop.


Not feeling 100% about my Controller design.

The logic for reading the Excel file (i.e. everything from var connectionString until before the return) belongs in a model method, not the controller.

You might also want to handle the case when the uploaded file isn't an Excel file or it doesn't have the columns you expect it to. Depending on how you use this or who uses it, this might not be necessary, but if normal users are allowed to upload files, they might very well upload the wrong file even if you tell them not to. And in that case a meaningful error message leads to a better user experience.

Regarding the question in your comment: As I said, I don't know how this is going to be used, but I can't think of a situation where it would be helpful for the user to be able to re-upload the file by hitting the refresh button. So yes, redirecting to an UploadComplete action makes sense.


Preventing resubmission of form using timestamp

I see how this stops the user from taking too long to fill out the form (which is not necessarily something you want to stop), but I don't understand how this prevents double submits at all.  Typical reasons for double submits:

The user clicks submit, the website response slowly, they click submit again
After submitting, if no redirect happens (you said you don't want redirects), the person can hit back and be presented with "Must resubmit data". If they refresh on this screen a second submit will happen.

In both cases the second submit can happen just moments after the first, so I don't understand how a time-based limit can stop either kind of double submit.

In the past when I've wanted to prevent double submits without using redirects I've done so by keeping track of a unique key in the session everytime I displayed the form.  When the form came back up, the unique key came with it (in a hidden input like yours), and I marked that unique key as "used".  Anytime a submit came up I checked its key against the list of "used" unique keys.  If the key in the form was marked as used, then I knew it was a double submit, and returned an error to the user letting them know.

As an aside, the need to send out a unique key with each form happens to also be a requirement for CSRF protection, so I actually just rolled both bits of functionality into one and killed two birds with one stone.


Discrete random number generator in Python

Is there a reason why you start off with numpy, then switch to lists and a for loop?

If you are given lists, you could convert them to numpy arrays and refactor your sampleValue() function to be done entirely in numpy. Otherwise, keep your generated values as numpy arrays instead of converting them to list and refactor your sampleValue() function to be done with numpy anyway.

probabilities = np.array(np.random.dirichlet(np.ones(N),size=1).tolist()[0])

def sampleValue2(possible_values, probabilities):
    U = random.random()
    return possible_values[np.argmax(np.cumsum(probabilities)>U)]

This reduces function simulation time from

1.18 s ± 9.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

to

486 ms ± 8.59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Then if you know how many random #s you want you can ditch the list comprehension by creating a probability matrix:

cum_probs = np.tile(np.cumsum(probabilities),(num_test,1))

Apply the function we rewrote over the entire matrix instead of by row:

indices = np.argmax(U<cum_probs,axis=1)
return np.array(possible_values)[indices]

to write a new function:

def sampleValue3(possible_values, probabilities):
    U = np.random.random(size=(num_test,1))
    cum_probs = np.tile(np.cumsum(probabilities),(num_test,1))
    indices = np.argmax(U<cum_probs,axis=1)
    return np.array(possible_values)[indices]

And that gives me a simulation time of:

65.9 ms ± 502 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Since you are just doing a lot of numeric operations, your algorithm could be sped up a lot just by keeping everything within numpy arrays/matrices.

Alternatively, from your problem definition, I don't see any reason why you can't just use numpy's random choice:

def sampleValue5(possible_values, probabilities):
    return np.random.choice(possible_values,p=probabilities,size=100000)

which is the fastest of these at:

36.8 ms ± 315 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


Java controller to farm out concurrent tasks

Hints

I would have named the generic types properly.

Maybe I would have divided Logging from processing with help of a listener pattern.

I would have expected the input parameter to never be null, so returning null is obsolete.

I would have extracted some methods to have parts of code be named.

Code

On a very high level view I would have expected exactly what you described what the code should do. Splitting an input in parts, processing these parts in parallel, collect the results and aggregate them. This should have been expressed in the "process"-method.

public class Controller<INPUT, RESULT, PARTIALINPUT, PARTIALRESULT> {

    ...

    public RESULT process(INPUT input) {

        PARTIALINPUT[] partialInputArray = preprocessor.split(input);

        List<Future<PARTIALRESULT>> partialResultFutures = processAsynchronously(partialInputArray);
        List<PARTIALRESULT> partialResults = collectPartialResults(partialResultFutures);

        RESULT result = postprocessor.aggregate(partialResults);

        return result;
    }

    private List<PARTIALRESULT> collectPartialResults(List<Future<PARTIALRESULT>> partialResultFutures)
            throws InterruptedException, ExecutionException {

        List<PARTIALRESULT> partialResults = new ArrayList<>();

        for (Future<PARTIALRESULT> future : partialResultFutures) {
            partialResults.add(future.get());
        }

        return partialResults;
    }

    private List<Future<PARTIALRESULT>> processAsynchronously(PARTIALINPUT[] partialInputArray) {

        List<Future<PARTIALRESULT>> partialResultFutures = new ArrayList<>();

        for (PARTIALINPUT partialinput : partialInputArray) {
            Future<PARTIALRESULT> future = processAsyncronously(partialInput);
            partialResultFutures.add(future);
        }

        return partialResultFutures;
    }

    ...

}


Calculating infix expression with no parenthesis

It is common, when processing things like this, to use a chain-of-responsibility pattern.

In this case, you can create an operator interface, or abstract class:

public interface BinaryOperator {
    public boolean isOwner(String operator);
    public double operateOn(double left, double right);
}

Then, you create an instance of that interface for each operator you support like the following for 'add':

public class AddOperator implements BinaryOperator {
   public boolean isOwner(String op) {
       return "+".equals(op);
   }

    public double operateOn(double left, double right) {
       return left + right;
    }
}

Then, you create an instance for all your supported operators, and then put them in to an array, in precedence order (if you support precedence).

It will look like:

private static final BinaryOperator OPERATORS = {
    new MultiplyOperator(),
    ....
    new AddOperator(),
    new SubtractOperator()
}

and, in your parsing/handling code, you do the following:

public double handle(double left, String parsedOp, double right) {
    for (BinaryOperator op : OPERATORS) {
        if (op.isOwner(parsedOp)) {
            return op.operateOn(left, right);
        }
    }
    throw new UnsupportedOperationException("Can't handle " + parsedOp);
}

This will drastically simplify your code, and it will make it much easier to support other operations too.


For the first loop, there is a neat little function called enumerate() which allows you to iterate through an object and access both the element and the iteration number.

You can also remove various parenthesis, for the returned value and also for the while loop (although for big conditions it's handy to keep the parenthesis sometimes).

def get_pos(format, letter, number):
    it_number = 0
    # it_pos = 0 <--- not needed anymore because of the
    for it_pos, char in enumerate(format): # <--- enumerate
        if char == letter:
            it_number += 1
            if it_number == number:
                return it_pos
        # it_pos += 1 <--- same thing here
    return -1

For the second function I would suggest to use while True and break so that you don't have to declare pos=-2 beforehand.

def format_loop(string, old_format, letter):
    new = ''
    # pos = -2 <--- replaced by a break
    it = 1
    while True:
        pos = get_pos(old_format, letter, it)
        if pos == -1:
            break
        elif pos >= 0:
            new += string[pos]
        it += 1
    return new

Also, I don't know if there is an official recommendation on that, but I like to use very explicit return values for special cases, for example the string "not found" instead of -1. That makes the code more English than Python when you read if pos=="not found": break and I rather like that.


You can simplify your area generators, as well as your code to append the paths, using an each to append the paths or an object to define the x and y methods in the area generator.

However, there is an simpler alternative: you are facing all those difficulties because of the structure of your data. If you change your data's structure for a more adequate one you can create a code which is way more idiomatic, therefore easier to read and, the most important, easier to maintain.

Right now, this is your data structure:

var periodReturns = [{
    pectile99: [x, y],
    pectile90: [x, y],
    pectile50: [x, y]
}, {
    pectile99: [x, y],
    pectile90: [x, y],
    pectile50: [x, y]
}, {
    etc...
}];

You will bend over backwards to create a multiarea chart with a data structure like this, because:

The data() methods accepts a data array in which each object is a datum;
You cannot easily get the objects' keys;

So, let's change that data structure. We'll created a nested data, with a key/value pair for the name, conveniently called name, and a key/value pair (containing an array) for the points, conveniently called values:

var data = [{
  pectile99: [0, 10],
  pectile90: [0, 40],
  pectile50: [0, 100]
}, {
  pectile99: [100, 40],
  pectile90: [100, 140],
  pectile50: [100, 30]
}, {
  pectile99: [200, 110],
  pectile90: [200, 10],
  pectile50: [200, 100]
}, {
  pectile99: [250, 90],
  pectile90: [250, 70],
  pectile50: [250, 140]
}, {
  pectile99: [300, 10],
  pectile90: [300, 30],
  pectile50: [300, 150]
}];

var nestedData = Object.keys(data[0]).map(function(d) {
  var obj = {
    name: d,
    values: []
  };
  for (var i = 0; i < data.length; i++) {
    obj.values.push(data[i][d])
  };
  return obj;
});

console.log(nestedData)

Now, since all the points can be accessed using the same property name, we can easily write just one area generator. Also, since each object in nestedData corresponds to just one area, we can write a single enter selection!

var areaGenerator = d3.area()
    .x(function(d) {
        return d[0]
    })
    .y1(function(d) {
        return d[1]
    })
    .y0(150);

var areas = svg.selectAll(null)
    .data(nestedData)
    .enter()
    .append("path")
    .attr("fill", function(d, i) {
        return color(i)
    })
    .attr("opacity", 0.5)
    .attr("d", function(d) {
        return areaGenerator(d.values);
    })

Here is the demo:

var data = [{
  pectile99: [0, 10],
  pectile90: [0, 40],
  pectile50: [0, 100]
}, {
  pectile99: [100, 40],
  pectile90: [100, 140],
  pectile50: [100, 30]
}, {
  pectile99: [200, 110],
  pectile90: [200, 10],
  pectile50: [200, 100]
}, {
  pectile99: [250, 90],
  pectile90: [250, 70],
  pectile50: [250, 140]
}, {
  pectile99: [300, 10],
  pectile90: [300, 30],
  pectile50: [300, 150]
}];

var svg = d3.select("svg");

var color = d3.scaleOrdinal(d3.schemeCategory10)

var prop;

var nestedData = Object.keys(data[0]).map(function(d) {
  var obj = {
    name: d,
    values: []
  };
  for (var i = 0; i < data.length; i++) {
    obj.values.push(data[i][d])
  };
  return obj;
});

var areaGenerator = d3.area()
  .x(function(d) {
    return d[0]
  })
  .y1(function(d) {
    return d[1]
  })
  .y0(150);

var areas = svg.selectAll(null)
  .data(nestedData)
  .enter()
  .append("path")
  .attr("fill", function(d, i) {
    return color(i)
  })
  .attr("opacity", 0.5)
  .attr("d", function(d) {
    return areaGenerator(d.values);
  })
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>


Property Mapping with Reflection efficiency

Well to start with reflection is incredibly slow.  And second I'm not even sure why you're using reflection to begin with since you have the strongly typed Location.  Don't use reflection.  I don't think you need to compare every single property.  Pick only the ones that could possibly match.

If you insist on using reflection here's a faster impl:

private static readonly locationProperties = typeof(Location).GetProperties();

foreach (PropertyInfo propertyInfo in locationProperties)
{
    var value = propertyInfo.GetValue(location);
    if (value != null)
    {
        LocationLookupModel model = allLocations.FirstOrDefault(a.Code == value.ToString());
        if (model != null)
        {
            modelList.Add(model);
        }
    }
}

Without reflection:

private static List<LocationLookupModel> PopulateLocation(Location location)
{
    List<LocationLookupModel> allLocations = new List<LocationLookupModel>();
    if (HttpContext.Current.Session["LocationModel"] == null)
        HttpContext.Current.Session["LocationModel"] = allLocations = new LocationModel().LocationList;
    else
        allLocations = List<LocationLookupModel>)HttpContext.Current.Session["LocationModel"];
    return allLocations.Select(x => x.Code == location.city || x.Code == location.country || x.Code == location.county || x.Code == location.locality || x.Code == location.metro || x.Code == location.region || x.Code == location.state || x.Code == location.zipcode).ToList();
}


Read and sort 100 numbers from a text file

File in = new File("input.txt");

Do not shorten variable names, it makes the code harder to understand and maintain.

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = input.nextInt();
        }

I'm a very persistent advocate that you're only allowed to use single-letter variable names if you're dealing with dimensions. Even for simple for loops one should use index or counter or something similar descriptive.

    try {
        Scanner input = new Scanner(in);

Could have used a try-with-resources instead.

System.exit(1);

Just as a note, that is not "let's exit the application" kind of call, it's "let's end the JVM abruptly" kind of call. When calling System.exit, not even finally blocks will be executed.

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

You could use a for-each instead.

            System.err.printf("File name does not denote an existing, writable regular file %n"
                            + "and a new regular file of that name cannot be created%n"
                            + "Or another error occured creating/writing to the specified file.%n"
                            + "Exiting with code: 2");

That's completely unhelpful error handling and is on the same level as Microsoft Windows' infuriating "Your PC had a problem :)" message. Never throw away error information that you have, it will make debugging a lot harder. Printing the exception message would be a minimum that you should do because from that error message, even though you did put a lot of thought and work into it, it's completely impossible to deduce the actual error and what to do to remedy it.
Short story time: I've been working with a third-party service lately and that service tries to contact yet another service. Whenever there is a problem with the communication with the other service, the service will spew out the log message "Failed to communicate with that other service, is the other service really already started?" followed by the exception message that clearly shows that an HTTP response was received. Not helpful, because you know that somebody will get hung up at some point on that message even though the question is bogus.

Coming around to your actual question, if you put your logic into a method of its own, your question simply goes away.
public static final void sortContent(File inputFile, File outputFile) throws IOException {
    // TODO Add verification that inputFile is not null.
    // TODO Add verification that outputFile is not null.

    int[] numbers = new int[100];

    try (Scanner scanner = new Scanner(inputFile) {
        // Logic goes here.
    }

    // Rest of logic goes here.
}

Now all you need to worry about is closing the resources correctly, which the try-with-resources will do for you. The IOException will simply being thrown and bubble up until it is being handled. For example in your main method:
public static final void main(String[] args) {
    try {
        sortContent(new File("input.txt"), new File("output.txt"));
    } catch (IOException e) {
        ex.printStackTrace();
    }
}

If you feel especially inclined to provide more information, you can always wrap the thrown exception.
public static final void sortContent(File inputFile, File outputFile) throws IOException {
    // ...

    try (Scanner scanner = new Scanner(inputFile) {
        // ...
    } catch (IOException e) {
        throw new IOException("Failed to read from input file <" + inputFile.toString() + ">.", e);
    }

    // ....
}

Notice that we do not throw away the original exception, but instead use it as cause for the one we are throwing.

Optional appendix: Why are one letter variable names not so good and should be avoided if possible?
Good code is expressive, as it is with the spoken language, expressiveness tends to depend on three things:

More letters
More words
The correct terms

If we only use few letters to communicate something, we are not very expressive, example "ltns gr8 cu 2d asap". Of course this is readable to some, but not as widely as if it would be a written as "long time no see, great idea, see you tonight as soon as possible".
If we only use few words to communicate something, we are not very expressive, example "tomorrow margaritas". Again, we can deduce the meaning if we are familiar with the context, but without the necessary context we have a hard time understanding "We'll meet tomorrow at your place, I bring the margaritas".
If we use the incorrect terms to communicate something, we are note very expressive, example "you can use our typewriter". Again, it will take use much longer to figure out that "typewriter" is used her interchangeably with "printer".
So we can establish the simple rule: The more expressive, the better.
Let's map this to code. We do not always have the luxury of being aware of the complete context of the code we are looking at. Here is a simple example:
a[i] = a[i] + 5;

We can deduce from this line the following assumptions:

a is an array, very likely int.
i is very likely a loop counter.
5 is added to the value at the index i.

There's a good chance that these assumptions would be correct. However, we still do not know what a is, or what range i has (spoiler: we'll never know, actually), or why 5 is being added to these values. So if we look at the same snippet with better naming, at least the first question becomes clear:
readValues[index] = readValues[index] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;

Notice how index still doesn't tell us much besides "it's most likely a loop over the whole array, otherwise it would have a better name". But if we swap out index with counter, we suddenly have a completely different meaning of this line:
readValues[counter] = readValues[counter] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;

We know that it is very likely not a loop over the whole array, but instead over a different range, maybe this is not even a for loop, but a while loop. So with a simple name change we can already transport some meaning. Let's build up a larger example:
// Assume a to be non-null int[]

for (int i = 0; i < a.length; i++) {
    for (int j = a.length - 1; j > i; j--) {
        if (a[i] == a[j]) {
            storeForLater(a, i, j);
        }
    }
}

Additionally, because the code was refactored the names carried over into the function that we call inside the loops, storeForLater(int[] a, int i, int j). And I believe at this point we can all agree that the names are not that good. Also notice how I sneakily extended the scope of the argument by introducing the refactored method. Let's see if we can improve that with proper names:
for (int leftIndex = 0; leftInex < readValues.length; leftIndex++) {
    for (int rightIndex = readValues.length - 1; rightIndex > leftIndex; rightIndex--) {
        if (readValues[leftIndex] == readValues[rightIndex]) {
            storeForLater(readValues, leftIndex, rightIndex);
        }
    }
}

Now that's quite a mouthful, but every line on its own has become much more expressive. Let's have an isolated look at the if:
if (a[i] == a[j]) {

if (readValues[leftIndex] == readValues[rightIndex]) {

Given the more expressive names in the second if, we can make quite a few assumptions more about the code and what it is supposed to do and what it is about.
Let's do another quick example, assume the following line of code:
    s[j][i] = getValueFromExternalSource(i, j);

Speed question: What is i and j?
Yes, "a loop counter" is also a correct answer I guess.
    spreadsheet[column][row] = getValueFromExternalSource(row, column);

As we can see, that one cleared it up quite nicely.
I earlier said  that "you're only allowed to use single-letter names when dealing with dimensions", what I meant are "x", "y" and "z" (possible "w" and "v", if you need another two), because these are on their own expressive enough and there is not really a more expressive way:
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        process(data[x][y]);
    }
}

That's as good as it gets when you simply deal with two dimensional data, or more dimensions. So there is no really a point in enforcing "dimensionX" or "indexX" or something like that. Yet I still feel the need to point out that if you're working on data that is consisting of rows and columns, row and column would be the preferred names for the loop.
We've already seen that the gains are not world-changing, but still quite interesting and in some cases can be significant. Now let's move on the whole point of the exercise: Production code. Does it matter whether or not you use i in your exercise snippets? No, it does not. Does it matter whether you use i in your production code? Given that I have seen code that is 40 years old and still is maintained, I'd say yes, yes it does. The worst example in this regard was a 250 line logic that was something like this:
// Lots of setup code.

for (int x = 0; x < someArraySize; x++) {
    // Some logc goes here.

    for (int a = 0; a < someOtherValueCantRemember; a++) {
        // More logic goes here.

        for (int b = someValue; b < yetAnotherValue; b++) {
            // The main part of the logic.
        }

        // A little bit of logic here.
    }

    // Some more logic here.
}

Again, we can all agree that this code is already badly structured, I believe it was something around 8 years or so old and the programmer long since gone. But especially in this case every name counts to make sure that you're able to follow the code. On my 1920x1080 screen I can see ~65 lines of code at once, in this case it means the logic was 4 pages long. That's quite some scrolling you have to do if you need to look up what a variable does because "a" tells you exactly nothing. And no, x had nothing to do with a dimension, it was a normal index loop.
Short interjection for everyone who now wants to say "At my work we throw that away and rewrite it": Great for you! Our customers pay for features, and redoing work our own company has done is not a feature.
Short interjection for everyone who now wants to say "Maybe you should find a better place to work, yours sucks": Great, thank yo! In the mean time I'd like to pay rent and buy food.
Back on topic, code like this is very, very common in software that had some point a deadline and a release. There are heaps and heaps of it, and the likelihood that you will encounter this than properly structured code is very good. What we can do, what we should try every day, is not to add to this pile, by writing the best code we can. And in my opinion, we should do our best to make every single line stand on its own as could as we can, without as much context as we can, because if the project is non-trivial, this line might be the only thing another programmer sees from our logic. If somebody is for example following a stacktrace, they will not want to familiarize themselves with every single piece of code on the way (who's got the time?). So every single line must be as expressive as possible.
Last but not least, I said it does not matter what you use in your exercises, so why to I raise the point in this review? Habit. Humans are pieces of habit. Making exceptions to a rule is always a bad thing, because you now have a special case at your hand that you need to deal with, that you need to remember, that you need to honor. Not making exceptions to a habit is much easier.


Overall, your code looks pretty decent. The indentation is spot-on, the variable names make sense, the code is clear and easy to read. But there are some big issues with your code.

The first thing that popped in my eyes was this:

if (typeof(stop)==='undefined'){

Please, don't use typeof to check if it is defined or not. You have a very interesting object called arguments.

Try this instead:

if (arguments.length < 3){

A few lines below, you have this:

if (stop === null){

What if I pass undefined or false?

You need to predict those, since they are valid values and, somewhat, in context. And yes, it is possible to pass undefined to a function, in one of these ways:

range(1, undefined, 3); //simply pass undefined
range.call({}, 1, undefined, 3); //mostly the same
range.apply({}, [1,,3]); //it may happen!
//... more similar variants ...

You need to take care of those.
This is one of a few examples.

You have the following function:

function str_sorted(num){
    num = num.toString();
    arr = Array();
    for (index in num){
        arr.push(num[index]);
    }
    return arr.sort().join('');
}

Let's focus on the following bit:

arr = Array();

There are 2 wrong things here:

This is a local variable without var
You are using the Array constructor as a function
You either use [] or use new Array()

The fix is simple:

function str_sorted(num){
    var arr = [];
    num = num.toString();
    for (index in num){
        arr.push(num[index]);
    }
    return arr.sort().join('');
}

But you still have something there that's bothering me:

    num = num.toString();
    for (index in num){
        arr.push(num[index]);
    }

Why are you converting it to a string and then iterating it? Is it to sort the numbers in the string? If that's the case, here's the whole function:

function str_sorted(num){
    return num.toString().split('').sort().join('');
}

Using string.split('') will split a string by each character, making an array of numbers.
Let's check your permuted() function.

It also suffer from a tiny flaw:

function permuted(num){
    tmp = str_sorted(num);
    return tmp == str_sorted(num * 2) &&
           tmp == str_sorted(num * 3) &&
           tmp == str_sorted(num * 4) &&
           tmp == str_sorted(num * 5) &&
           tmp == str_sorted(num * 6);
}

I have no idea what you are trying to do, but here is the mistake:

tmp = str_sorted(num);

There, you forgot a var.

Change it to this:

var tmp = str_sorted(num);

Lets take a look at the find function.

This one isn't too bad:

function find(iterable, fn){
    for (num in iterable){
        if (fn(num)){
            return num;
        }
    }
}

Just more of the same:

for (num in iterable){

You forgot a var there.

Change it to this:

for (var num in iterable){

I'm not sure if this is part of the code to be reviewed or not.

But let's analyze the last line:

print(find(range(1, null), permuted));

Please, don't use print. It isn't even a standard! It's just supported in some consoles (like Chrome). Use console.log() instead.

For now, I will leave the review as is. If I find any more issues, in the future, I will check on them.


Hacking a SecureString based on std::basic_string for C++

The only thing special about SecureZeroMemory (the Windows version) is that it uses volatile to prevent optimization. Therefore there's no reason to write your own. Just defer to standard algorithms:

std::fill_n((volatile char*)p, n*sizeof(T), 0);

You will probably want to call the global delete:

::operator delete [] p;

Add noexcept:

template <class U> secure_allocator(const secure_allocator<U>&) noexcept {}


Best practice for cleaning Pandas dataframe columns

This is not too bad. It's a good thing you use keyword arguments for the replace method
I always try to keep my original data in its original state, and continue with the cleaned dataframe.
fluent style
This lends itself very well to a kind of fluent style as in this example. I use it too, and use a lot of df.assign, df.pipe, df.query...
In this example I would do something like
df_cleaned = df.assign(
    col2=(
        df["col2"]
        .str.lower()
        .str.strip()
        .replace(to_replace="[^a-zA-Z ]", value="", regex=True)
    )
)

So definately no inplace replacements


It's quite good, I especially like the $current_state explanatory variable. Actually, I'd create another one to remove some duplication:

$transitions = $transition_table[$current_state];
if (isset($transitions[$character])) {
    $current_state = $transitions[$character];
    $states[] = $current_state;
}

Some other notes:

The code currently ignores invalid transitions. You could break the loop immediately if a transition is invalid:

foreach (str_split($input_string) as $character) {
    $transitions = $transition_table[$current_state];
    if (isset($transitions[$character])) {
        $current_state = $transitions[$character];
        $states[] = $current_state;
    } else {
        break;
    }
}

Inverting the isset would make the code flatten a little bit:

foreach (str_split($input_string) as $character) {
    $transitions = $transition_table[$current_state];
    if (!isset($transitions[$character])) {
        break;
    }
    $current_state = $transitions[$character];
    $states[] = $current_state;
}

$s2 is unused, I guess you could remove it:

$s2 = 'S2';

  Are there something that I've missed?

The linked page mentions classes and I guess it should have been an object oriented solution. Check the Wikipedia article about the Java implementation, it shows a great example.


Your question is unclear, though I can tell that your code is broken.

Your code here:

  public static boolean isBalanced(BinaryTreeNode n) {
    // if height = (|hl - hr|) <=1
    int leftHeight = n.left != null ? n.left.height() : -1;
    int rightHeight = n.right != null ? n.right.height() : -1;
    return leftHeight - rightHeight <= 1;
  }

Should return true if the tree is balanced, but, it takes a node in, computes the height of the left and right sides, and compares the differences.

This method is broken.... Just because the height of each side of the tree (left, and right) are similar, does not mean that each side is also balanced. Consider a tree like:

    //             0
    //            / \
    //           1   4
    //          /   /
    //         2   5
    //        /   /
    //       3   6

When you test the root, you will determine that both sides have the same height, yet, the tree is far from balanced.


Searching an entire workbook for keywords and then printing the results on another worksheet

Here are some of the changes I'd make

Use Option Explicit at the top of the module

Eliminate all errors found by compiling the code (Debug -> CompileVBA Project)
(declare all variables, first of all)

Remove the empty Sub ComboBox1_Change() declaration if you don't inded to use it
Replace string comparisons such as PageName <> "" with

PageName <> vbNullString (faster)
Len(PageName) > 0 (even faster)

As pointed out in the comment, generalize the lastRow and totalValues statements

From:

  lastRow = Sheets(PageName).Range("A65536").End(xlUp).Row

To

With Sheets(PageName)
    lastRow = .Range(.Rows.Count, 1).End(xlUp).Row
End With

To reduce total lines of code and make it a bit easier to maintain I'd replace the three Select statements with one separate Function, and use it like this:

Private Sub CommandButton1_Click()
    TextBox1.Value = GetSelectedLetter(TextBox1.Value)
End Sub

Sub UpdateSearchBox()
    ...
    searchColumn = GetSelectedLetter(ComboBox2.Value)
    If InStr(searchColumn, "Please") > 0 Then MsgBox searchColumn
    ...
End Sub

Sub FindOne()
    ...
    searchColumn = GetSelectedLetter(ComboBox2.Value)
    If InStr(searchColumn, "Please") > 0 Then MsgBox searchColumn
    ...
End Sub

Public Function GetSelectedLetter(ByVal sel As String) As String
    Select Case sel
        Case "G", "EQUIPMENT NUMBER":   GetSelectedLetter = "A":    Exit Function
        Case "B", "EQUIPMENT NAME":     GetSelectedLetter = "C":    Exit Function
        Case "E", "DUPONT NUMBER":      GetSelectedLetter = "F":    Exit Function
        Case "F", "SAP NUMBER":         GetSelectedLetter = "G":    Exit Function
        Case "D":                       GetSelectedLetter = "E":    Exit Function
        Case "SSI NUMBER":              GetSelectedLetter = "H":    Exit Function
        Case "PART NAME":               GetSelectedLetter = "I":    Exit Function
        Case "C":                       GetSelectedLetter = "D":    Exit Function
        Case "A":                       GetSelectedLetter = "B":    Exit Function
        Case vbNullString:
            GetSelectedLetter = "Please select a value for what you are searching by."
    End Select
End Function

(not the standard indentation, but I find it visually easier to work with)

Performance

One improvement: start the search after moving all data to arrays (array of arrays specifically)

Example:

Public Sub SearchAllSheetsArrayOfArrays()
    Const SRC_VAL = "Test"

    Dim ws As Worksheet, arr() As Variant, i As Long, j As Long, tc As Long, tw As Long
    Dim r As Long, c As Long, lbr As Long, ubr As Long, lbc As Long, ubc As Long

    i = 1
    tw = ThisWorkbook.Worksheets.Count
    ReDim arr(i To i + tw - 1)  'Place all data from each sheet in Variant sub-arrays

    For Each ws In ThisWorkbook.Worksheets
        If ws.UsedRange.Cells.Count > 1 Then
            arr(j + 1) = ws.UsedRange
            j = j + 1
        End If
    Next

    tw = j
    ReDim Preserve arr(i To tw) 'Trim the main Array if there are empty sheets

    For i = 1 To tw     'tw = total worksheets
        lbr = LBound(arr(i), 1): ubr = UBound(arr(i), 1)    'dimension 1 (rows)
        lbc = LBound(arr(i), 2): ubc = UBound(arr(i), 2)    'dimension 2 (cols)
        For r = lbr To ubr
            For c = lbc To ubc
                If Len(arr(i)(r, c)) > 0 Then
                    If InStr(arr(i)(r, c), SRC_VAL) > 0 Then tc = tc + 1 'collect vals
                End If
            Next
        Next
    Next
    Debug.Print tc
End Sub

Ps. I used very short variable names to make the code fit in its window without scroll bars, but more descriptive names should be used - like in your posted code, but try to keep naming conventions consistent: all variables start with lower case letters, all procedures start with upper case letters


Avoid catching all exceptions

Do not use catch (Exception e) as this will also catch NullPointerException, ArrayIndexOutOfBoundsException and a whole lot of other ones. Only catch the Exceptions you need to catch, such as IOException. It is said that one should be specific in throws clause, but that applies for catch as well.

And as stated in the comments to your question, System.err.println(e) does not give full information about the exception. If you don't have a logger system nearby that can handle exceptions completely, at least use e.printStackTrace();. It is however recommended that you should handle and exception, and not only report it. For example by displaying a more accurate error message to the user.

Also, I would say that your line if(br != null) try { br.close(); } catch (Exception fe) {} should be on multiple lines. Even if it increases line count, it improves readability.

if (br != null) {
    try {
       br.close();
    }
    catch (Exception fe) {
    }
}


Printing alternating characters of a string using Java 8 streams

The main issue with your code is that it operates with side-effects by leveraging the forEach operation. If you were to run your code in parallel, it would be broken and you wouldn't have the expected result. In this case, what you want is to use a mutable reduction approach, that is collect elements into a container.

All propose solutions hardcodes the fact that we reindex even and odd indexes. However, it would be possible to make them generic easily.

The first simple approach is to use 2 Stream pipeline (as you have done). The first one creates the first part of the String and the second one creates the second. Instead of using forEach to add elements to a StringBuilder, we collect the elements into a new StringBuilder. As such, each index is mapped to the character at that index and accumulated into a new StringBuilder with appendCodePoint. The 3 arguments to the collect call corresponds to:

the supplier of the mutable container, (StringBuilder::new);
the accumulator of each element into the container (appending the code point of the character);
a combiner combining two containers into one (used in parallel processing).

private static String reindex(String input) {
    StringBuilder result = new StringBuilder(input.length() + 1);
    result.append(filter(input, index -> index % 2 == 0));
    result.append(' ');
    result.append(filter(input, index -> index % 2 == 1));
    return result.toString();
}

private static StringBuilder filter(String input, IntPredicate predicate) {
    return IntStream.range(0, input.length())
             .filter(predicate)
             .map(input::charAt)
             .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append);
}

The duplicate logic has been extracted to a utility method that filter the indexes matching the given predicate and collects the filtered characters into a StringBuilder.

But the issue is that it loops around the String two times when such an operation should be possible using a single traversal. This is a bit more complicated to do and I would first measure the performance of the first solution before doing this one: it is possible that your concerned String do not have a length big enough to warrant such an approach.

A possible solution is to collect the elements inside an array of StringBuilder. The array to append the current character to is determined by the result of i % 2: when i is even, this will be 0 and it will append it to the first array; when i is odd, it will append it to the second array.

private static String reindex(String input) {
    StringBuilder[] result =
        IntStream.range(0, input.length())
             .collect(
                () -> new StringBuilder[] { new StringBuilder(), new StringBuilder() },
                (b, i) -> b[i % 2].appendCodePoint(input.charAt(i)),
                (b1, b2) -> {
                    b1[0].append(b2[0]);
                    b1[1].append(b2[1]);
                }
             );

    return result[0] + " " + result[1];
}


I think your implementation of the logic is fine. But the variable "isAdjList" should be defined for each of the graph for which you are going to detect cycles . Make sure that you have either an adjacent list or an adjacent matrix for a particular graph and not both.


Calling Web API from MVC generic way of approach

I agree as some others have said that in this case, having a layer between Angular and your API is simply bloat / overhead unless there are specific reasons for the extra abstraction.  I understand that you are late in the project development so my review will reflect that but as an aside I have to point out that your management should have a COMPLETE understanding of the technical debt incurred by any potential "Escalation of Commitment" mistakes made by them.  Especially considering Web API will eventually be deprecated: https://blog.tonysneed.com/2016/01/06/wcf-is-dead-long-live-mvc-6/

That being said, your code for the most part is fine but I would suggest a couple of architectural changes.

1. Keep your controllers thin

Controllers only responsibility should be to retrieve data and pass that data to the view.  In this case, your view is JSON, so your controller should ONLY make a cal to get data.

As the code currently is it is also more difficult to test than it needs to be.

2. Encapsulate methods

As you have pointed out, you are winding up with a lot of duplicate code.  I would suggest solving both problems by introducing another layer of indirection.

Example Code

  Controller Code

public class MyController : Controller {
    private IApiClient _apiClient;

    public MyController() : this(new WebApiClient()) {
        // Poor-man's DI in case you don't have an IoC container.
        // If you do, do not include this constructor
    }

    public MyController(IApiClient apiClient) : base() {
        this._apiClient = apiClient; // assign injected dependency
        // This injected dependency streamlines your testing process
        // because the results are more easily mocked than direct access
        // to the HttpContext as was done in the actions before
    }

    public async Task<ActionResult> GetStates() {
        string relativePath = "api/Admin/GetStates";
        return await this.ApiGet(relativePath);
    }

    public async Task<ActionResult> GetClients() {
        string relativePath = "api/Admin/GetClients";
        return await this.ApiGet(relativePath);
    }

    public async Task<ActionResult> Roles() {
        string relativePath = "api/Roles";
        return await this.ApiGet(relativePath);
    }

    protected async Task<ActionResult> ApiGet(string relativePath) {
        ApiResponse response = await this.ApiClient.GetAsync(relativePath);
        ActionResult result = response.IsSuccessful ? new ContentResult { Content = response.Data, ContentType = "application/json" } as ActionResult : new JsonResult();
        return result;
    }

    protected IApiClient ApiClient {
        get {
            return this._apiClient;
        }
    }
}

  The ApiResponse class

[Serializable]
public class ApiResponse {
    private bool _successful;
    private string _data;

    public ApiResponse() {
        this._data = string.Empty;
        this._successful = false;
    }

    public string Data {
        get {
            return this._data;
        } set {
            this._data = value;
        }
    }

    public bool IsSuccessful {
        get {
            return this._successful;
        } set {
            this._successful = value;
        }
    }
}

  The IApiClient and WebApiClient types

public interface IApiClient {
    Task<ApiResponse> GetAsync(string relativePath);
}

public class WebApiClient : IApiClient {
    private System.Net.Http.HttpClient _httpClient;

    public WebApiClient() {
    }

    protected Uri BuildCompleteUri(string relativePath) {
        // Using a URI will help us to validate the URL before making an invalid call.
        Uri returnUri = new Uri(VirtualPathUtility.Combine(this.Client.BaseAddress.ToString(), relativePath));

        return returnUri;
    }

    public async Task<ApiResponse> GetAsync(string relativePath) {
        Uri completeUri = this.BuildCompleteUri(relativePath);
        ApiResponse response = new ApiResponse();
        HttpResponseMessage apiResponse = await this.Client.GetAsync(completeUri);
        if (apiResponse.IsSuccessStatusCode) {
            string responseData = apiResponse.Content.ReadAsStringAsync().Result;
            if (!string.IsNullOrWhiteSpace(responseData)) {
                response.IsSuccessful = true;
                response.Data = responseData;
            }
        } else {
            // TODO: Log Errors
        }

        return response;
    }

    public HttpClient Client {
        get {
            if (this._httpClient == null) {
                this._httpClient = HttpContext.Current.Items["httpclient"] as HttpClient;
            }

            return this._httpClient;
        }
    }
}

The above code structure keeps your controllers thin, reduces code duplication, allows for extension points if you need to add more information of your own to the ApiResponse type, and dramatically simplifies your unit testing process because the IApiClient type is easily mocked.

You could even take it a step further and use the DI container to register a factory method that injects the HttpClient instance into the WebApiClient type, which would also simplify the testing process of the WebApiClient.

I also renamed your controller actions so they are consistent with the API method they invoke.


Plugin for finding placed blocks and if they are in a certain sequence

As it is mentioned in the comments, It seems your code is exactly same as the below. So that is the first suggestion.

main = block.getType();
up1 = block.getRelative(BlockFace.UP, 1).getType();
up2 = block.getRelative(BlockFace.UP, 2).getType();
down1 = block.getRelative(BlockFace.DOWN, 1).getType();
down2 = block.getRelative(BlockFace.DOWN, 2).getType();

if ((main == Material.JUKEBOX && up1 == Material.DIAMOND_BLOCK && up2 == Material.IRON_FENCE)||
   (main == Material.DIAMOND_BLOCK && up1 == Material.IRON_FENCE && down1 == Material.JUKEBOX) ||
   (main == Material.IRON_FENCE && down1 == Material.DIAMOND_BLOCK && down2 == Material.JUKEBOX)) {
    System.out.println("Antenna Created");
    player.sendMessage("Antenna Created");
}

Now, as far as extendibility goes, You need to add newer conditions, it is not a good idea. What you have coded here is just an FSM (A state machine).

The easiest method to capture a state machine is to turn that into a regular expression. In this case, Say, the ordering is

up1 up2 main down1 down2

The conditions are

DIJ.. | I.DJ. | ..IDJ

So this captures your state machine fully. Adding future conditions is just as simple as adding to the above regular expression.

The code would look like

first(var) {
  return first_char(var)
}
string = { first(up1.toS()), first(up2.toS()),
           first(main.toS()),
           first(down1.toS()), first(down2.toS())};
re = new Regexp('DIJ..|I.DJ.|..IDJ')
if (re.match(string)) {
  player.send('Antena Created');
}


I would like to remove these switch statments in the same time

[Flags]
public enum StatusCode{
    codeX = 1,
    codeY = 2,
    codeZ = 4,
    codeA = 8,
    editable = codeX | codeZ,
    deleteable = codeY | codeZ
}

Key points

Use the Flags attribute
enum values are powers of 2 - NOT multiples of 2
bit-wise AND, OR provides the magic!

Edit

addressing the comments:

public static class StatusCodes {
    private Dictionary<StatusCode, int> values;
    private Dictionary<int,StatusCode> keys;

    static StatusCodes() {

        values = new Dictionary<StatusCode, string> {
            {StatusCode.A, 10},
            {StatusCode.B, 20},
            // and so on
        }

        keys = new Dictionary<in, StatusCode> {
            {10, StatusCode.A},
            {20, StatusCode.B},
        }
    }

    public static int GetValue(StatusCode theStatusCodeKey) {} // don't forget error trapping!
    public static StatusCode GetKey(int theIntValue) {}  // ditto

    public static bool Editable(StatusCode thisCode) {
        return (StatusCode.editable & thisCode) == thisCode;
    }

    public static bool Editable(int thisValue) {
        return Editable( GetKey(thisValue));
    }
}

The definition of the codes is all in one place - that's SOLID (D = DRY, don't repeat yourself)
The definitions are in its own class - that's SOLID (S = single responsibility)
editable and deleteable can be removed from Message - that's very SOLID (S = single responsibility)
We know what all those integers mean - thats.. well, just good programming.
The StatusCodes are available anywhere and everywhere in the application - That's SOLID, an attribute of being DRY.
I'm not sure what "status code values might not be fixed" in the comments means. Surely the set of status codes is finite.

Edit

Define "editability" in StatusCodes
Use above to express Message is editable
Address issue of exposing StatusCode.editable "as if it were a valid code"
Adhere to Single Responsibility
Adhere to DRY principle

...

public static class StatusCodes
{
    private static Dictionary<StatusCode, int> values;
    private static Dictionary<int,StatusCode> keys;

    static StatusCodes() {

        values = new Dictionary<StatusCode, int> {
            {StatusCode.A, 10},
            {StatusCode.B, 20},
            {StatusCode.C, 30},
            {StatusCode.D, 40}
            // and so on
        };

        keys = new Dictionary<int, StatusCode> {
            {10, StatusCode.A},
            {20, StatusCode.B},
            {30, StatusCode.C},
            {40, StatusCode.D}
        };
    }

    [Flags]
    enum Fungability
    {
        Editable = StatusCode.A | StatusCode.B,
        Deleteable = StatusCode.B | StatusCode.D
    }

    public static int GetValue( StatusCode theStatusCodeKey ) {
        int retVal;

        values.TryGetValue( theStatusCodeKey, out retVal );
        return retVal;
    } // don't forget error trapping!

    public static StatusCode GetKey( int theIntValue ) {
        StatusCode retVal;
        keys.TryGetValue( theIntValue, out retVal );
        return retVal;
    }  // ditto

    public static bool Editable( StatusCode thisCode )
    {
        return ( (StatusCode)Fungability.Editable & thisCode ) == thisCode;
    }

    public static bool Editable( int thisValue )
    {
        return Editable( GetKey( thisValue ) );
    }

}

public class Message
{
    public StatusCode myStatus;

    public Message( int statusCode = 20 ) { myStatus = StatusCodes.GetKey(statusCode); }
    public Message( StatusCode statusCode = StatusCode.A ) { myStatus = statusCode; }

    public bool Editable
    {
        get { return StatusCodes.Editable( myStatus ); }
    }

    public bool Deleteable
    {
        get { return StatusCodes.Deleteable( myStatus ); }
    }
}

Take Away

Structure data in an OO way
Expose the data adhering to the Single Responsibility principle
You get DRY as a side effect
Structure yields simplicity, coherence, clarity. Editable is implemented with only one line of code!
Message.Editable went from originally "calculating" if the status code was editable, to simply asking the StatusCode "are you editable?"


Verifying the type of an AggregateException's inner exception in a unit test

I am blocking the call using AsTask().Result, is this the most appropriate method?

Can't you use await? Most testing frameworks (apparently including MSTest) support async tests. That way, you could work directly with the inner exception instead of the AggregateException.

if (ae.InnerException.GetType() == typeof(InvalidOperationException))
{
    Assert.IsTrue(true);
}
else
{
    Assert.Fail("There was no InvalidOperationException.");
}

I think this should be shortened to just:

Assert.AreEqual(typeof(InvalidOperationException), ae.InnerException.GetType());

Or maybe:

Assert.AreEqual(
    typeof(InvalidOperationException), ae.InnerException.GetType(),
    "There was no InvalidOperationException.");

  Exceptions thrown in an asynchronous chain return AggregateException so I want to inspect that it throws the exception which I defined as "you are not logged in".

But you're not doing that, you're just checking that it's InvalidOperationException. If you want to test for this, maybe you should use a custom exception type?


The reason you needed the '[' and ']' was to put the array around the records.  A better way of doing it is building the array of records in php and then encoding that.  Here is what I would do:

$fname = "subjects.csv";

if (($handle = fopen($fname, "r")) === FALSE) {
    exit;
}

$records = array();

/* First line is header with keys */
$keys = fgetcsv($handle);

while (($data = fgetcsv($handle)) !== FALSE) {
   $data[0] /= 2;
   $records[] = array_combine($keys, $data);
}

fclose($handle);

echo json_encode($records);


Semantically, I would suggest using HTML5 elements more.

For example, instead of...

Use instead: (the ID can stay if you want it to)

This would change your CSS from #header {} to just header {}

It is common to see multiple  tags in complicated templates.  So something like this might be appropriate if that is the case...

CSS would be:

header.site-header {}

Consistency, consistency, consistency.

Most of your class and ID names are completely lowercase.  However a few classes use camelCase like: #site3Container

Make your naming conventions consistent.  Either use all camelCase or use all lowercase or all UPPERCASE etc.

Typically, I use lowercase for HTML and CSS (faster to write).  I use camelCase for PHP.  This is no rule however.

Positioning

Absolute positioning has its uses.  It's almost never used for basic layout however.

Your exact layout can be achieved without the use of ANY position: absolute;.  It is my general recommendation to avoid position: absolute; at almost all times.  If you are finding you need to use it for something, chances are you don't actually need to, you just don't know how else to do it yet.  Consult someone.

Here is a JSFiddle of your current html and css

Here is a JSFiddle demonstrating the same layout, without positioning.

*Note that the description text now has a maximum width of 960px (common site width, though 1140 is becoming more common).  The description divs are also center so there will always be equal space on left and right sides.

My modifications above also feature one particular additional CSS selector:

* { margin: 0; padding: 0; }

The asterisk * is a wildcard, it essentially means ANY element.  The selector above resets the margin and padding of every element to 0.  This is usually done via something called a "reset stylesheet".  Which leads me to my next subject...

Reset Stylesheets

Reset stylesheets contain CSS code which standardizes what your website will look like across all browsers.  It sets all padding and margins to 0 for instance, so that no default styling is added to your site that you potentially, or even probably, don't want.

A quick Google search lands us at this website: http://www.cssreset.com/

There, you can see many popular reset stylesheets, all with their own different sort of caveats and specialities.  I personally recommend Normalize.css  It keeps and standardizes some typical styles you may not necessarily want to reset to 0.  It also contains some standard typography styling, so your text looks great without you having to do any work.  Reset stylesheets should always be the very first .css file you link.  So you would include yours like this for instance:

    <title>Site Title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/reset.css"/>
    <link rel="stylesheet" href="css/basecss.css"/>

Classes over ID's

An ID is specific, they can be used once.  It IS this "thing" and it is only ever this "thing".  A class can be just as specific, or as broad as you would like.  A class can be applied to multiple elements on the same page.  An example, expanding from the JS Fiddles above, would be to combine the styles for the description divs.

We start with this CSS:

#site1desc
{
    width: 100%;
    max-width: 960px;
    margin: 0 auto;
}

#site2desc
{
    width: 100%;
    max-width: 960px;
    margin: 0 auto;
}

#site3desc
{
    width: 100%;
    max-width: 960px;
    margin: 0 auto;
}

By modifying the HTML so that every
 is now this:
 We can drastically cut down on our total CSS code.  Our full HTML now looks like the below...

Site description goes here.

Site description goes here.

Site description goes here

The only CSS we need changes from the 3 selectors above to just this:

.contentdesc
{
    width: 100%;
    max-width: 960px;
    margin: 0 auto;
}

JSFiddle Demo of the above

***Note: CSS classes are referenced with a period  .className is different from #idName


Print the upper half triangle of a matrix

When looking at your code I just want to say: Please reconsider your indentation!. This code should be rather easy to read, but you've complicated it quite a bit by not using braces around the blocks of the if statements, and leaving them at the same indentation, and why the excessive amount of indentation with the for loops?

So here are some style suggestions:

Keep indentation consistent at 4 spaces – Don't change indentation between different blocks, but keep it the same all the time
Always indent after if, for, while – Don't skip it like you've done in your inner loop
Add space after , and ;, and between operators – Having the blocks like for(i=0;i<r;++i) makes your code hard to read. Use spaces like in for (i=0; i<r; ++i) or if (j == (c-1)))
Use descriptive variable names – Whilst i and j is common as loop variables, please use more descriptive names like row, column, or matrix for the other variables to describe what they represent
Use braces around the blocks – Your code is prime example of the need to use braces around the blocks of if, for and while. By always adding braces around your code blocks, you are sure that the correct code is executed (and your 'faulty' indentation) won't give you any surprises!

And here are some code suggestions:

Use the if statement properly as suggested by ratchet freak – Either use it directly, or depending on which triangle you want to output a loop where you avoid the if completely. i.e. for (j=0; j<i && j < c; ++j), possibly with an indentation before that if needed and not zero based. If you don't understand this, do go with the suggestion by ratchet freak
Bug/Feature: If you enter r or c larger than 10, it fails miserably – You should add error handling if the input is outside of your intended range, or you should make your code more dynamic allowing for larger ranges.


Generating 3D voxel terrain with Perlin Noise

I don't know much about Unity, but one of the Unity operations must be the bottleneck here if it takes 1.5 seconds to process 40k cubes.  I'd focus on reducing the number of Unity operations you're doing (manipulating the game objects).  For example, you're first placing all the cubes at y=0, then moving them later.  Instead, try generating the Perlin Noise first into an array, and then place the cubes at the correct height on the Instantiate call.

Also consider this line:

cube.renderer.material.color = new Color(cubeHeight / 5, cubeHeight, cubeHeight / 5);

You have 40k cubes but only about 20 colors.  Is there some way of sharing materials (or even renderers) between the cubes?  You may be asking Unity to manage many copies of identical materials.  Look into other ways to share resources; is there some way to only create a few cubes with different colors, and render one entire height-layer with copies of it?

As for general coding style:

You have public GameObject cube; as an instance variable, but you also use the word cube all over the place for local variables.  Is there a better name you could give this, like templateCube?

This is comment is not necessary:

/// <summary>
/// Sets the color of the cube based on the cube's height.
/// </summary>
/// <param name="cube">Cube.</param>
/// <param name="cubeHeight">Cube height.</param>
public void SetCubeHeightColor(Transform cube, float cubeHeight)

This takes up a lot of lines to give me the same information as your method signature ... although when my eyes see "SetCubeHeight" I assume you're setting the cube's height, but you're actually setting the color.  Consider SetCubeColorByHeight instead.

Usually, everything that your class needs to function properly should be an argument in its constructor.  This may not be possible with a Unity MonoBehavior, but I thought I'd throw it out there.


The game of life with a truly infinite board

Edit: This answer was given when the reviewed code looked quite differently.

Any specific questions? Here's what stands out for me:

Why do toList in emptyNeighbors, then go back to Set again? You could simply use Data.Set.map there.
countNeighbor is very inefficient: the filter operation always iterates over all life cells, and you are calling it three times per existing cell! That's unneeded, as you only ever care about a handful of neighbourhood cells.

My idea to fix issue 2 would be to build a Map of the neighbour count of every cell. If you represent the board as a Map with only 1 cells in it, that can be done pretty efficiently using mapKeysMonotonic and unionsWith:

type Coo = (Int, Int)
type Board = Map Coo Int

moveBoard :: Coo -> Board -> Board
moveBoard (dx,dy) = M.mapKeysMonotonic (\(x, y) -> (x+dx, y+dy))

countNeighbours :: Board -> Board
countNeighbours b =
  unionsWith (+) [ moved (-1) (-1), moved 0 (-1), moved 1 (-1)
                 , moved (-1)   0 ,               moved 1  0
                 , moved (-1)   1 , moved 0   1 , moved 1  1   ]
 where moved dx dy = moveBoard (dx,dy) b

Note that usage of mapKeysMonotonic is only safe because the order of coordinates doesn't change when we add a constant. Effectively, this means that the library can simply replace the concrete coordinates without any internal resorting.

The iteration is then a simple matter of using filter, map and intersection over the result:

lifeIteration :: Board -> Board
lifeIteration b = M.union birth survive
 where neighbours = countNeighbours b
       birth      = M.map (const 1)  (M.filter (==3) neighbours)
       survive    = M.intersection b (M.filter (==2) neighbours)

Changing your formulation slightly by having a life cell with 3 neighbours "rebirth" instead of survive, as that's a bit simpler to write.

Also note that this is a bit "clever" by taking advantage of the fact that intersection always returns the value of the first Map, therefore I don't need to do another M.map (const 1) step in there.

I hope this is helpful to you.


jQuery hide and show option value from a dropdown

The primary things I would recommend here are

avoid polluting the global namespace
avoid unintentionally creating globals
cache your DOM element lookups to increase performance and also decrease filesize

Here is the code reflecting these considerations:

// Wrap this in a self-executing, anonymous scope, or in a document.ready
// this way you can avoid polluting the global (window) namespace
(function(){

  // Cache this DOM element in the main scope because you look it up in both of your functions.
  var $public = $('#public');

  /* use "var" or publicFormValidation becomes a wild global */
  var publicFormValidation = function(){
    // Cache DOM elements that you're going to call multiple times, like ".add_many_fields"
    // DOM lookups are very expensive operations (depending on the size of the DOM)
    var $addManyFields = $('.add_many_fields'),
        $fileUpload = $('.field_type option[value="file_upload"]'),
        $contacts = $('.field_type option[value="contacts"]');

    $public.change(function(){
      if(checkForm()){
        $fileUpload.hide();
        $contacts.hide();
        $addManyFields.on('click',function(){
          setTimeout(function(){
            $fileUpload.hide();
            $contacts.hide();
          }, 500);
        });
      }else {
        $contacts.show();
        $file_uploads.show();
          $addManyFields.on('click',function(){
            setTimeout(function(){

              /* You definitely don't want to do this:

              var $contacts = $('.field_type option[value="contacts"]');
              var $file_uploads = $('.field_type option[value="file_upload"]');

              you're actually overwriting variables you've already defined in the parent scope - you
              already have these references, so no need to do another DOM lookup.
              */
              $contacts.show();
              $file_uploads.show();
          }, 500);
        });
      };
    });
  }

  /* Use var here as well to get rid of globals */
  var checkForm = function(){
    var public_val = $public.val();
    return (public_val == "true");
  }
}());


Algorithm to add all lucky numbers under [N] to a Vector

It is fairly straightforward to generate a vector with all the values.  First, you should treat all the same length numbers as a group.  The values 4 and 7 would be in a singledigit vector.  To get the twodigit vector, simply go through the previous vector, multiplying each by 10 and then adding 4 to push back a value and add 7 to push back another value.

vector<int> lucky;
vector<int> current;
vector<int> next;
current.push_back(4);
current.push_back(7);
lucky.push_back(4);
lucky.push_back(7);
int value=0;
while(value < N)
{
   for(unsigned int i=0;i<current.size();++i)
   {
       value=current[i]*10+4;
       next.push_back(value);
       lucky.push_back(value);
       value=current[i]*10+7;
       next.push_back(value);
       lucky.push_back(value);
   }

   current=next;
   next.clear();
}


Handling templates for a web application

To answer just the question in the title;
Your solution seems fine to me; addMultiplePlaceholders() is a utility method that acts as a wrapper for addPlaceholder()

Note there's a bug in your code; addMultiplePlaceholders() calls addPlaceholder() without $this-> 'prefix', so your code won't work

However, there is room for improvement. I'll try to summarize what I'd do differently.

Remove redundant information from your Exception messages

Exceptions are 'smart' messages in that they already contain all the meta-information you need to find where they occurred (e.g. line number, file etc). Don't clutter your messages with that information, It'll only complicate your code (for example the preg_replace). Just include the bare error-message. See the documentation on Exceptions.

If your going to output a message, make sure they cannot be mis-interpreted. Being consistent in your messages will prevent confusion and make it easier to debug your code later on, for example:

throw new Exception('The placeholder string cannot be empty');

Is confusing; What is the placeholder string? The name ($k)? Value ($v)?

Outputting the meta-information can be done when printing the exception, for example;

Just use this to throw your exception;

throw new Exception('Placeholder name cannot be empty');

And output it in your Exception-handler with this;

printf(
    "An Exception has occurred: '%s' in file '%s' on line '%s',
    $e->getMessage(),
    $e->getFile(),
    $e->getLine()
);

// --> An Exception has occurred: 'The placeholder string cannot be empty' in file 'Template.php' on line '52'

Since you're no longer including the name of the Class/Method in your messages, you can completely remove the 'try/catch' from your 'addMultiplePlaceholders'.

Use the right 'type' of Exception

To be more expressive/specific when throwing Exceptions, consider using special Exceptions for a situation, for example, the SPL Exceptions. In this case an InvalidArgumentException will be appropriate

Consider what really is an exception

Inside addPlaceholder, you're throwing an exception if a key is already set. Personally, I wouldn't do this (it does feel like 'business logic'). Technically, overwriting the value of a placeholder that was already set won't cause any problem. Disallowing overwriting existing placeholders may limit you in situations that you want to overwrite a placeholder.

However, renaming addPlaceholder to setPlaceholder may be more appropriate, to indicate that you can both 'add' or 'update/replace' a placeholder.

Use descriptive variable/argument-names

The arguments for addPlaceholder are not very descriptive. Additionally, the variable names you're using seem to be picked based on the the 'inner workings' of the method (key/value pairs), which should be of no interest when using that method. I'd suggest something more describing the purpose of the arguments, for example:

public function addPlaceholder($name, $value)
{
    //...
}

Likewise, replace '$array' to something more describing its purpose, for example

public function addMultiplePlaceholders($nameValuePairs)
{
    //...
}

// or..

public function addMultiplePlaceholders($placeholders)
{
    //...
}

If you want to explicitly indicate you're expecting an array (and have PHP check this for you), you can add a type-hint, like this:

public function addMultiplePlaceholders(array $placeholders)
{
    //...
}

Finally, naming this method addMultiplePlaceholders may be a bit verbose. Since the method is plural, it's probably already clear that it is used to add multiple placeholders, so simply calling it addPlaceholders may be clear enough.

Remove 'comment' clutter. Add PhpDoc in stead

Do not describe code that is self-explanatory. In general, try to omit inline comments in all cases, unless a piece of code really is confusing.

In most cases, don't describe the code, but describe the purpose / intent of a function/method inside a PhpDoc comment.

For example:

if(!is_associative($array)){ // if `$array` is not an associative array throw exception
    throw new Exception("The supplied parameter value is not an associative array");
}

This comment is just repeating the code! Also, inline code is not used by IDE's and will not be included in automatically generated documentation (e.g. phpdocumentor). It's best to move relevant information to a PhpDoc block

For example:

/**
 * Adds placeholder(s) passed as an associative array ('name' => value)
 *
 * Name should be a string, value can be any type of value
 *
 * This method is a wrapper for @see addPlaceholder()
 *
 * @param array $nameValuePairs
 *
 * @throws InvalidArgumentException if $nameValuePairs is not an associative array
 *                                  or an empty name is used for a placeholder
 * @return void
 */
public function addMultiplePlaceholders(array $nameValuePairs)
{
    //...
}

Modified code

This is the code after applying my suggestions

/**
 * Adds or updates a placeholder
 *
 * @param string $name  Name of the placeholder. Cannot be empty
 * @param mixed  $value Value of the placeholder
 *
 * @throws InvalidArgumentException if $name is invalid (empty)
 *
 * @return void
 */
public function setPlaceholder($name, $value)
{
    if (empty($name)) {
        throw new InvalidArgumentException('Placeholder $name cannot be empty.');
    }

    $this->placeholders[$name] = $value;
}

/**
 * Adds or updates placeholder(s), passed as an associative array ('name' => value)
 *
 * Name should be a string, value can be any type of value
 *
 * This method is a wrapper for @see addPlaceholder()
 *
 * @param array $placeholders placeholder(s), passed as an associative array ('name' => value)
 *
 * @throws InvalidArgumentException if $placeholders is not an associative array
 *                                  or an empty name is used for a placeholder
 * @return void
 */
public function setPlaceholders(array $placeholders)
{
    if (!is_associative($nameValuePairs)) {
        throw new InvalidArgumentException('Parameter $placeholders is not an associative array');
    }

    foreach (placeholders as $name => $value) {
        $this->addPlaceholder($name, $value);
    }
}


Please read over PEP 8 as your naming style is unidiomatic, and would cause programmers to be confused when seeing your code in the wild.
I would move getting and setting a node by index into their own functions.
if self.value >= 0 only hinders your code, the value -1 is perfectly valid in binary trees. It also means that you're limiting value to types that can be compared to integers, meaning you can't enter strings.
Using recursion in addNode is a good idea, but I find the non-recursive alternate to be easier to understand.
Your code doesn't care if I enter addNode([0, 2], 1). This seems fishy as if this were a Trinary Tree that would mean something completely different. I recommend raising a ValueError in this case.
Your printTree is pretty good.
I'd change the level argument in printTree to be a keyword argument only. This is because then it's explicit that it's changing the level, and it's something normal code shouldn't accidentally change.
Personally I think if self.left is not None is better here than if self.left, but as Node can't be falsy it doesn't matter too much.
I've added some basic docstrings, defined in PEP 257.
I have also added some typing to your code.
By using typing and mypy I found that addNode can error when the specified path doesn't exist. It would be better in these cases to raise an error telling the user why.
You can use a if __name__ == '__main__': guard to prevent code running on import. This means if you later import this code in another module then the testing code won't run.

from __future__ import annotations

from typing import Any, Optional, Sequence

class Node:
    """Test binary tree."""

    def __init__(
            self,
            value: Any,
            right: Optional[Node] = None,
            left: Optional[Node] = None,
    ):
        """Initialize binary tree, with specified children nodes."""
        self.value = value
        self.right = right
        self.left = left

    def _get_index(self, index: int) -> Optional[Node]:
        """Get node via integer index."""
        if index == 0:
            return self.left
        elif index == 1:
            return self.right
        else:
            raise ValueError(f'Invalid index {index}')

    def _set_index(self, index: int, value: Node) -> None:
        """Set node via integer index."""
        if index == 0:
            self.left = value
        elif index == 1:
            self.right = value
        else:
            raise ValueError(f'Invalid index {index}')

    def add_node(self, parents: Sequence[int], value: Node) -> None:
        """Add the provided node to the tree."""
        node: Optional[Node] = self
        for index in parents[:-1]:
            if node is not None:
                node = node._get_index(index)
        if node is None:
            raise ValueError("Parent node doesn't exist.")
        node._set_index(parents[-1], value)

    def add_value(self, parents: Sequence[int], value: Any) -> None:
        """Add the provided value to the tree."""
        self.add_node(parents, Node(value))

    def print_tree(self, *, level: int = 0) -> None:
        """Print the tree."""
        print('  ' * level + str(self.value))
        for child in (self.left, self.right):
            if child is not None:
                child.print_tree(level=level + 1)

if __name__ == '__main__':
    tree = Node(0)
    tree.add_value([0], 1)
    tree.add_value([1], 1)
    r"""
    Graph looks like
       0
      / \
     1   1
     """

    tree.add_value([0, 0], 3)
    tree.add_value([0, 1], 8)
    tree.add_value([1, 0], 4)
    tree.add_value([1, 1], 7)
    r"""
    Graph looks like
               0
             /   \
            1      1
           / \    / \
          3  8    4  7
    """
    tree.print_tree()


If you're going to roll your own allocator in C++17, you can save yourself a lot of grief by just leaving everything to default. The only things you need to include are value_type, allocate(), deallocate(), and operators == and !=.

In fact, I believe by not using the defaults, you've introduced a nasty little bug. Try doing this: auto v = pod_vector<int>(5, 42);. This should create a vector with five ints, all set to 42. But without construct() properly defined, who knows what will happen?

My advice:

Your allocator should be 4 lines.

the static_assert
value_type
allocate()
deallocate()

(And you need the == and != comparisons too.)

At the very least, either remove construct() or give it a sensible implementation (i.e., placement new). With destroy() it's less of an issue because you're only dealing with PODs.

AFTER EDIT 1: I'd wager the reason you're seeing better code generation for malloc() than new is that new throws std::bad_alloc automatically when it can't allocate.

I suspect if you changed your allocate() function to:

auto allocate(std::size_t num)  {
    auto const p = (T*) malloc(sizeof(T) * num);
    if (!p)
        throw std::bad_alloc{};
    return p;
}

you'd see a very different code gen situation.

As it stands, if you get an allocation failure, you're just returning a null pointer... which will lead to undefined behaviour, because allocate() must return a pointer to allocated memory.


Laravel dropdown list without empty values

I'm assuming that you are using the whereNotNull() because in addition to allowing empty strings, you allow null values?

That being said, you could always modify your code to use the specific where() clause. This can take an array as input and you can specify both the empty string and NULL.

$city = DB::table('contacts')->distinct('city')->lists('id', 'city')->where(function($query) {
    $query->where('contacts.city', '!=', '')
        ->orWhere('contacts.city', '!=', null);
})

There's a very good SO post here about multiple where clause queries.


Comparing screen captures using unsafe / API calls

There are a few things I see at a glance:

If you have to enclose a section of code within a method in region
tags, you should be pulling that code out into a helper method.  You
could probably split this method into several.  Don't worry about
overhead of extra method calls -- the compiler will likely re-inline
them anyways.
Split the body of your if/else on "Big" and "Small" into a helper method that takes in a file name.  That's the only difference I see in each block.
There are a lot of lines where you are declaring and assigning variables.  When you do that, it is likely more readable to declare as var, because you indicate what type it is immediately to the right of the assignment operator.
Rather than converting your elapsed times with ToString ().Remove () calls, I would instead suggest storing them as TimeSpan types and using a string format in your message boxes.
Move "Big", "Small", "testBig4BenchViaChaos.bar", and "testSmall4BenchViaChaos.bar" into constants.
If this is just a utility that is not client-facing, move your other strings to constants.  Otherwise, move them into a resx so they can be localized.
Naming - you should use longer, more descriptive names.  You are not saving much by using a name like OrgArr instead of the longer OriginalArray.  You should also be consistent in capitalization.  Some of your local variables are camel case, and some are pascal case.  The standard for the framework is camel case for local variables.
You are overwriting testBig4BenchViaChaos.bar with OrgArr, but then comparing the bytes in testBig4BenchViaChaos.bar with OrgArr.  Am I missing something, or should this always return a match because the data is the same?  Though, on that note, you are doing == with byte arrays, so you should really always mis-match due to object reference comparison.
Your quickest way to compare the two byte arrays is probably going to be using a for loop (single-threaded) or possibly PLINQ using SequenceEqual.  As always, benchmark to be sure because test results are worth a thousand expert opinions.