Read line and combine duplicate entries based on one of the fields

I'm far from a Java expert, but a few things jumped out at me

You forgot to close the reader (br).

Do not close the streams inside of the try. What happens if an exception gets thrown before the close commands are reached? You need a finally block. Or, better yet, if you're using Java 7 or above, use a try-with-resources block.

If you're only error handling is to just print out the message, I'd be tempted to go ahead and let the exception bubble up and kill the program. Unless you're just trying to go for a more simple error, in which case hiding the stack trace could be nice.

I would just let key be null the first time around and check for that instead of using first.

I might try to restructure the for conditions. They're very confusing in the current form. Perhaps loop as long as you successfully read a line, and then handle the last logic outside of the for loop. That way you don't have to have so much going on inside of the loop.

On a minor note, you should try to create the reader before the writer. That way you don't create an output file if you can't open the input one.

The repetition in the last and else blocks should be refactored out into a common case. Based on that they do the exact same thing, I'm not actually sure why last get's special treatment.

I would use Integer.parseInt instead of using unboxing on new Integer(str).

temp is a bad variable name. Name it something descriptive of what it actually is.

Don't bother commenting really obvious things ("Catch exception if any" for example).

Sometimes you use spaces like if (...) and sometimes you don't. Pick one and stick with it (by which I really mean always use spaces :p).

All in all, my Java is a bit rusty, so take this with a grain of salt, but, I would do something like this:

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Usage: CombineKeys InputFile OutputFile");
        System.exit(1);
    }

    BufferedWriter out = null;
    BufferedReader br = null;

    try {
        out = Files.newBufferedWriter(Paths.get(args[1]), StandardCharsets.UTF_8);

        br = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.UTF_8);

        String key = null;
        int links = 0;
        String qID = null;

        while ((line = br.readLine()) != null) {
            String[] entry = line.split(",");

            if (entry[0].equalsIgnoreCase(key)) {
                int tmpLinks = Integer.parseInt(entry[1]);
                if (links < tmpLinks){
                    links = tmpLinks;
                    qID = entry[2];
                }
            } else {
                if (key != null) {
                    out.write(key + "," + qID + "\n");
                }
                key = entry[0];
                links = Integer.parseInt(entry[1]);
                qID = entry[2];
            }
        }
        if (key != null) {
            out.write(key + "," + qID + "\n");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    } finally {
        if (br != null) {
            br.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

I don't really like the repetition of the outputting, but I can't figure out a way around that. Also, due to the nesting level, I would probably pull the actual processing into a new method that takes in the two already opened streams.


int is IMO not an appropriate type in this domain. I would use ulong or maybe BigInteger

If you for instance run the following test, both CombinationFact() and CombinationFast() runs out of range:

  n = 52;
  k = 9;
  Console.WriteLine($"Combin({n}, {k}) = {CombinationFact(n, k)}");
  Console.WriteLine($"Combin({n}, {k}) = {CombinationFast(n, k)}");

I would use throw new ArgumentOutOfRangeException(nameof(n));

instead of throw new IndexOutOfRangeException();

You don't need the extra variable combinations:

  int combination = (int)(Factorial(n) / Factorial(k) / Factorial(n - k));
              return combination;

Just return the result of the calculation:

  return (int)(Factorial(n) / Factorial(k) / Factorial(n - k));

Both of your algorithms is rather limited in use due to the int-conversion, but you could change the fast version to something like:

public ulong CombinationFast(ulong n, ulong k)
{
  ulong count = n;

  for (ulong x = 1; x <= k - 1; x++)
  {
    count *= (n - x);
    count /= x;
  }

  return count / k;
}

Update

Because 10!/(4!(10-4)!) == (10!/6!(10-6)!) it is possible to optimize the calculation for k > n/2:

public ulong CombinationFast(ulong n, ulong k)
{
  if (k > n / 2)
    k = n - k;

  ulong count = n;

  for (ulong x = 1; x <= k - 1; x++)
  {
    count *= (n - x);
    count /= x;
  }

  return count / k;
}

The above algorithms is an implementation of this expression.

A more literal version should maybe be:

public ulong CombinationFast(ulong n, ulong k)
{
  if (k > n / 2)
    k = n - k;

  ulong count = 1;

  for (ulong x = 0; x < k; x++)
  {
    count *= (n - x);
    count /= (x + 1);
  }

  return count;
}


Checking for spelling errors with a trie

Node

Raw arrays:

std::shared_ptr<Node> child[ALPHABETSIZE];

are really awkward. There's little reason to prefer to use one here. Use a std::array instead:

std::array<std::shared_ptr<Node>, ALPHABETSIZE> children;

Also I pluralized your array name. Seems to make more sense. You also want to make sure that a default-constructed Node is valid, so I find it clearer to just add data member initializers:

struct Node {
    bool isEnd = false;
    int prefixCount = 0;
    std::array<std::shared_ptr<Node>, ALPHABETSIZE> children;
};

Now you don't have to worry about default/value initialization.

You current construct your head via:

head = std::make_unique<Node>();

But head is a shared_ptr so you should do:

head = std::make_shared<Node>();

And with the added data member initializers, that's all we need to do in our constructor. Done!

insertion

Prefer a range-based for loop anytime you want to loop over everything in a container without needing the iterator. It expresses intent better:

for (char c : word) {
    int letter = c - 'a';
    ...
}

Also, what if word contains anything other than a lower-case letter? What if it's a capital letter or a space or a hyphen? This does no error checking here, so leaves open the possibility of undefined behavior due to invalid memory access.

Choice of data structure

Does having 26 children for each node make sense? That could be very memory intensive if our data set is sparse! I'd expect something more like:

std::unordered_map<char, std::shared_ptr<Node>>

with which this would just look like:

auto& next = current->children[letter];
if (!next) next = std::make_shared<Node>();
next->prefixCount++;
current = next;

searching

I would rename search() to contains(), and same points apply about sanity checking your inputs and using a range-based for loop.

wordsWithPrefix

Note that your search and wordsWithPrefix do the same thing: we walk the length of the string, break early if we run out of children, and do something with the result. That suggests adding a helper function:

std::shared_ptr<Node> atPrefix(const std::string& prefix) const;

which does that work for us. With that function, we can implement:

bool contains(const std::string& word) const
{
    auto node = atPrefix(word);
    return node && node->isEnd;
}

unsigned int wordsWithPrefix(const std::string& prefix) const
{
    auto node = atPrefix(prefix);
    return node ? node->prefixCount : 0;
}

Trie construction

You may want to add a constructor that will iterate over and insert a bunch of words. Maybe take two iterators, same as the other standard containers.

cin and getline

Be careful about mixing those two. It doesn't always work.

Also, don't do this:

std::string word = " ", input;

Space isn't at a premium, you can declare your variables on separate lines.

main()

What is input? I don't understand your usage here. Are you mandating a sorted dictionary.txt for this to work? Some comments indicating this would be helpful.

final loop

at() vs operator[] just does range-checking. You don't need that here, so simply use operator[]. Also if what you want to do is divide input, you don't need a second argument to substr() - just the one will automatically print the remainder of the string from there on out. Besides, your length argument is incorrect anyway.

Prefer:

std::string x;
for (char c : input) {
    x += c;
    if (trie.wordsWithPrefix(x) == 0) {
        std::cout << x << '<' << input.substr(x.size());
        break;
    }
}

file.close()

Unnecessary. The ifstream destructor will take care of itself. RAII for the win.


Directory tree representation with double linked list

Not sure this question is valid, but there is reviewable code:

node is a constructor, it should be named with an uppercase N
curretnChild is not properly spelled, and not used anywhere, drop it
Since you set parents to [], you might as well return parents when if(components.length > 0){ is not true
You should declare your vars on top in parseParents, the scope of newParent and currentParent is the whole function anyway
Your reliance on root.type is a bug in waiting, find a better way to figure out what the type should be.
addChild should be part of Node.prototype, it does not make sense for every instance of Node to have it's own version of this function
Your code in addChild does not take care of dupes, that should be addressed

For fun, I  wrote this, it creates a double linked list and takes most of my comments in to consideration, except for the last one ( does not take care of dupes ).

function Node( path , type )
{
  var parts = this.cleanPathParts( path.split("/") ),
      part  = parts.pop();
  //Set the basics
  this.name = part;
  this.type = type;
  //Do we still have parts left ?
  if( parts.length ){
    this.parent = new Node( parts.join('/'), this.DIR );
    this.parent.children = [ this ];
  }
}
//Ignore blanks and `..` strings
Node.prototype.cleanPathParts = function( parts )
{
  return parts.filter( function(part){
    return !!part && part != "..";
  });
};
//Get the ultimate parent, usefull for adding path children
Node.prototype.getRoot = function()
{
  var root = this;
  while( root.parent )
    root = root.parent;
  return root;
};
//Add a child, either a simple node or a path
Node.prototype.addChild = function( part , type )
{
  if( this.type != this.DIR ){
      throw new Error('A file node cannot have any children');
  }
  var node = (new Node( part, type )).getRoot();
  node.parent = this;
  this.children = this.children || [];
  this.children.push( node );
};
//Constants
Node.prototype.DIR  = 'dir';
Node.prototype.FILE = 'file';

var a = new Node('/usr/local/foo', 'dir');
a.addChild('1/2/test', 'file');
a.addChild('test', 'file');
console.log(a);


DRY

I'm sorry to say this but this solution is needlessly complicated. You are doubling up on your divisibility checks. This is a well known interview question where the goal is to really just to check that you can order your if statements correctly. It is kind of cool that you never really do a i % 3 == 0 && i % == 5 check (or i % 15 == 0), but at what cost?

What is the purpose of this language? Is FizzBuzz really suppose to show off the language?

I hate to sound this harsh, but I am not really feeling this language. Is it probably a useful educational experience? Sure, but I:

Don't think this example really showcases anything about your language, except for maybe the pipe operator.
(Maybe better for your other question) Not sure about the goal of the language.
I feel like most of the stuff (maybe not all, but most) could be simulated with macros. Hence, instead of creating a whole new language, you could use something like SweetJS to emulate most of the stuff you have done.
Not really sure how template literals showcase anything about your language, Javascript does it nearly identical to your way.

I know this is discouraging. I remember someone saying something along the lines of getting the urge to make a programming language and then laying down for a while until the urge wears off.

Before I become too discouraging, however, maybe you should really think about code you disliked in Javascript and analyze it closely. Then write it the way you want it to look like and then consider what you want. Maybe if you want to use template literals so badly, you can find a way to describe them easier in FreezeFlame?


Toward optimized functionality and design

since all crucial attributes x, y, x_mean, y_mean are initialized on LinearReg instance creation (within __init__ method) - no need to duplicate and define them as class attributes (x = [] ... y = []), those should be removed as redundant
raise Error - Error is not Python exception class. Use Exception or ValueError
axis_mean(self, axis) function does not use self context and deserves to be just a @staticmethod
sum_of_deviation_products/sum_of_x_deviation_squared functions
Substitute algorithm: instead of going with external variable result + range(len(..)) + for loop - apply a convenient combination of sum + enumerate functions:

def sum_of_deviation_products(self):
    return sum((self.x[i] - self.x_mean) * (y - self.y_mean)
            for i, y in enumerate(self.y))

A good (or better) alternative would be sum + zip approach: sum((x - self.x_mean) * (y - self.y_mean) for x, y in zip(self.x, self.y))
get_b_zero method is redundant as it's just return a public attribute self.b_zero (which is accessed directly)
get_slope method
Instead of storing and reassigning self.slope attribute on each method invocation - as it's recalculated each time, it deserves to be a computed attribute using @property decorator:

@property
def slope(self):
    return self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()

Now, it's simply accessed with self.slope.
fit_best_line method
Instead of unreadable string concatenation like ... + "%.2f" % self.slope + "x + " + "%.2f" % self.b_zero use flexible f-string formatting:

print(f"The best line equation is: {self.slope:.2f}x + {self.b_zero:.2f}").

The conciseness and flexibility are obvious.
Also, in case if b_zero attribute/property happen to be only actual in context of fit_best_line call - it can be eliminated and declared as just local variable.

The final optimized approach:

class LinearReg:
    def __init__(self, x, y):
        if len(x) != len(y):
            raise ValueError("Both axis must have the same number of values")

        self.x = x
        self.y = y
        self.x_mean = self.axis_mean(self.x)
        self.y_mean = self.axis_mean(self.y)
        self.b_zero = 0

    @staticmethod
    def axis_mean(axis):
        return sum(axis) / len(axis)

    def sum_of_deviation_products(self):
        return sum((self.x[i] - self.x_mean) * (y - self.y_mean)
                   for i, y in enumerate(self.y))

    def sum_of_x_deviation_squared(self):
        return sum((x - self.x_mean) ** 2
                   for x in self.x)

    @property
    def slope(self):
        return self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()

    def fit_best_line(self):
        self.b_zero = self.y_mean - (self.slope * self.x_mean)
        print(f"The best line equation is: {self.slope:.2f}x + {self.b_zero:.2f}")


Finding the closest data point in a sequential list

Bug

Suppose list[0] = 0, list[1] = 1, and val = 2.  After doing the binary search, you are left with min = 1 and max = 2.

When we get here:

if (max != list.Count && min != 0)

the block is skipped because max == list.Count.  This is correct because you don't want to deference list[max].  However, you end up returning ret which was never set and still contains 0.  The correct index to return would be 1.

I believe you can fix your function by eliminating the ret variable and returning min instead.  In other words:

private int FindClosestPoint(double val, List<Double> list)
{
    int max = list.Count;
    int min = 0;
    int index = max / 2;

    while (max - min > 1)
    {
        if (val < list[index])
            max = index;
        else if (val > list[index])
            min = index;
        else
            return index;

        index = (max - min) / 2 + min;
    }

    if (max != list.Count &&
            Math.Abs(list[max] - val) < Math.Abs(list[min] - val))
    {
        return max;
    }
    return min;
}

Strange way to initialize an int

Also I noticed this strange line:

int ret = new int();

I'm not sure why you didn't just initialize ret the same way as you did with min:

int ret = 0;

The two statements are equivalent but since int is a value type, the former statement is odd because it makes it look like you are trying to allocate an object.


I am not an expert in cryptography by any stretch of the imagination but I am pretty sure an IV should be randomly generated.

  " In cryptography, an initialization vector (IV) or starting variable (SV)[1] is a fixed-size input to a cryptographic primitive that is typically required to be random or pseudorandom. Randomization is crucial for encryption schemes to achieve semantic security [...] " -

  https://en.wikipedia.org/wiki/Initialization_vector


How can I further improve my approach?

  Is there a better way to solve this question?

Let's start by making some observations about the problem description and the possible inputs:

The star elements will always be a strictly decreasing sequence
There will always be one star element: the rightmost one
The leftmost star may or may not be a super star

The posted code uses a map to find the star elements.
This is unnecessary, a list would be fine.
The loop you already have going from right to left could prepend the found star element to the list of stars.

After finding the stars, you need to check if the first star is a super star or not.
This is easy to verify, for example by a second scan of the array,
checking that precisely one element is equal,
and all other elements are strictly less than the leftmost star.

In this verification step,
you could avoid scanning the entire array if you know the index of the leftmost star, but such optimization is not really important,
because the order of time complexity of the solution will be the same.

This proposed solution uses fewer redundant data structures (a single list instead of a map and a set), and performs faster (no sorting).

  Are there any grave code violations that I have committed?

The findElems method does too many things.
It finds the stars and super stars and prints them.
It would be better to organize programs in a way that one method does one thing.
Following the suggested sketch above,
there could be one function to find the stars,
one to verify if an element is a super star,
and one to print.
When organized that way,
the logical steps will be easier to understand,
and the solution will be much easier to test.

  Can space and time complexity be further improved?

The suggested sketch above is better because it eliminates the sorting of the stars. That would be a significant improvement when the input set is a strictly decreasing sequence, where all elements are stars. In this extreme case the time complexity would be reduced from \$O(n \log n)\$ to \$O(n)\$.
However, since the problem description says there are maximum 106 elements, this improvement would be hardly measurable, insignificant.

  Is my code very redundant?

As mentioned earlier, the map and set can be replaced with a single list,
if you change the approach as I outlined.


Strategy for avoiding threadpool starvation while performing cpu bound jobs in a queued fashion

I think a much easier solution is to just increse the number of threads available in the thread pool by calling ThreadPool.SetMaxThreads().

Also, if you have this many threads, then it means that:

either you're not going to get any performance improvements from parallelization, because all your cores are busy
or most of your threads are blocked, which means a better approach would be to actually solve the problem by using asynchronous waiting (possibly with the help of C# 5 async-await), instead of working around the problem.


A few things.
for (int i = 0; i < numbers.length-1; i++)

Also, look up quick sort.  Worst-case performance O(n^2) with a best-case of O(nlogn).  By randomizing the pivot in the quick sort you can enhance the best case scenario.
Psuedo for recursive Quicksort:
partition(arr[], low, high)
    pivot = arr[high]
    i = low
    for j:= low to high-1
        if arr[j] <= pivot
            swap arr[i] with arr[j]
            i = i+1
   swap arr[i] with arr[high]

random(arr[], low, high)
    r = a random number from low to high
    swap arr[r] and arr[high]
    return partition(arr, low, high)

quickSort(arr[], low, high)
    if low < high
        p = random(arr, low, high)
        quickSort(arr, low , p-1)
        quickSort(arr, p+1, high)


both methods, runScriptWithParameters and getScriptReturnWithParameters have a lot of code in common which should be extracted to a separate method.
using string concatenation by using += will create each time a new string because strings are immutable. A better way would be to use a StringBuilder instead.
based on the .NET naming guidelines methods should be named using PascalCase casing.
the check for if (parameters.Count > 0) is not needed, because if you get the enumerator and there are no items to enumerate over, the loops is just ending.
you don't do any null validation on the methods parameters of your public methods. Omitting these will leak implementation details.
you should use the var type whenever the type is obvious form the right hand of the assignment.

Implementing some of the mentioned points will lead to

private string ComposeUrlParameters(Dictionary<string, string> parameters)
{
    var builder = new StringBuilder(1024);
    var firstParameter = true;
    foreach (var parameter in parameters)
    {
        if (firstParameter)
        {
            builder.Append("?");
            firstParameter = false;
        }
        else
        {
            builder.Append("&");
        }
        builder.AppendFormat("{0}={1}",parameter.Key, parameter.Value);
    }

    return builder.ToString();
}

which then can be called like so

public void RunScriptWithParameters(string url, Dictionary<string, string> parameters)
{
    if (url == null) { throw new ArgumentNullException("url"); }
    if (parameters == null) { throw new ArgumentNullException("parameters"); }

    var urlToRun = url + ComposeUrlParameters(parameters);
    RunScript(urlToRun);
}

You could compose the url parameters with linq as well like so

private string ComposeUrlParameters(Dictionary<string, string> parameters)
{
    if (parameters.Count == 0)
    {
        return string.Empty;
    }

    var builder = new StringBuilder(1024);
    var firstParameter = parameters.First();

    builder.AppendFormat("?{0}={1}",firstParameter.Key, firstParameter.Value);

    foreach (var parameter in parameters.Skip(1)
    {
        builder.AppendFormat("&{0}={1}",parameter.Key, parameter.Value);
    }

    return builder.ToString();
}


Replace values in R data frame according to values in other data frame

Code Review

One change I would make to your solution is to directly modify the row names as below (instead of modifying gene and then setting the row names equal to gene).

for (i in 1:nrow(df)){
  if (rownames(df)[i] %in% annotation$gene) {

    rownames(df)[i] = annotation$name[which(annotation$gene == rownames(df)[i])]

  }
}
df$gene <- NULL

df
#        sample_1 sample_2
# name_1        0        0
# name_2        0        0
# gene_3        0        0

This solution is similar to the original, but iterates over row numbers (1-3 in this case) instead of row names. This allows direct modification of the row names and makes the code slightly more concise. This version doesn't use gene at all.

That's how I'd modify the existing solution, but overall I wouldn't use a for loop. for loops can be slow since they iterate over every element (and your data set has 10^5 rows). Below is another approach using the dplyr library.

Another Approach

library(dplyr)
library(tibble)

df <- left_join(df, annotation, by = "gene") %>%        # Join "annotation" and "df"
mutate(gene = if_else(is.na(name), gene, name)) %>%     # Convert "gene" to "name" when "name" is valid
column_to_rownames(var = "gene") %>%                    # Set row names to "gene"
select(-name)                                           # Remove "name"

df
#        sample_1 sample_2
# name_1        0        0
# name_2        0        0
# gene_3        0        0

This syntax may look unfamiliar but it's doing 3 main things:
  - left-joining df and annotation by the gene field. It has to be a left-join so all rows of df are preserved!
  - changing the value of gene to name only when name is non-null
- setting the row names equal to gene

The pipe operator %>% passes the data through these operations without needing to repeatedly type df <-. These are all vectorized operations and so are faster than a for loop, especially for large data sets.

dplyr syntax can be intimidating at first, but it's an extremely popular (and I believe intuitive) paradigm to manipulate data. Here is a handy intro on dplyr syntax.


With the manifest constant being assigned to a const variable, you now have two ways of referring to the same value. In principle, this is superfluous, and should therefore be avoided. In practice, with manifest constants always being globally visible in C++, this is a rather moot point, but it can still be used for making a decision in lack of any other point. So, if there are any other considerations not immediately evident in the code, such as the need to be able to redefine the manifest constant AND at the same time the need to have the constant strongly typed, then by all means, it should be kept, and preferably documented.

The try statement used as a function body looks mighty weird, which means that the average C++ programmer looking at it will go "WTF?".  At the same time it does not accomplish any mighty feat that will make one add "--oh, I see why it is done that way, cool!". It is okay for a coding technique to have a certain WTF factor to it, as long as it accomplishes something neat, the neatness of which is proportional to its WTFness, so as to justify it. All that the try-statement-used-as-a-function-body accomplishes is to spare us from having to type an additional --but expected-- pair of curly brackets. Therefore, it should definitely be avoided.


Bouncing ball - for swing event handling tutorial

Swing GUIs should be built inside the EDT, e.g. using SwingWorker.invokeLater(). See http://leepoint.net/JavaBasics/gui/gui-commentary/guicom-main-thread.html for details.
I think calling a JPanel descendant "Ball" is just confusing. If you really want that a panel can handle only one Ball, call it BallPanel or so. But it would be more flexible if you had a DrawPanel, which accepts a number of objects to draw, and the objects themself. That makes it much easier to extend the system later:

.

public class DrawPanel {
   private List<Drawable> drawables = new ArrayList<Drawable>();
   ...
   public void addDrawable(Drawable d) { drawables.add(d); }

   public void paintComponent(Graphics g){
     super.paintComponent(g);
     for(Drawable d : drawables) {
        d.draw(g, getWidth(), getHeight());
     }
   }
   ...
   //for animation a timer task, calling Drawable.update
}

interface Drawable {
   public void draw(Graphics g, int width, int height);

   //when you need animation
   public void update(long ms);
}

public class Ball implements Drawable {
  ...
}

This is only one possibility to split view and model, the "right" way depends on your needs. But keeping both model and view in one class is a receipt for trouble.


Circuit-Swap mechanism on going (BMP->PPM)

Magic numbers

What is the significance of 18, 19, 22 and 23? They must be defined in terms of bitmap file header and bitmap info header
Correctness

According to a spec, bitmap width and bitmap height are 4 byte integers. The code accounts only for 2 bytes.
The code completely ignores colour depth.
The code is unable to deal with palette-based bitmaps.
The code completely ignores possible DIB compression.

Style

All-uppercase words are usually reserved for macros. Normal variable's identifiers should be in snake_case or camelCase.
What is the purpose of typedefing DWORD?
You should at least make your snippet into a function. Otherwise it is completely useless.


Input checking is missing. You should throw an IllegalArgumentException if max is less than zero instead of the NegativeArraySizeException.

Result of Math.sqrt(max) doesn't change, so maybe it's would worth to extract out to a local variable but maybe the JVM already optimize this for you.

Anyway, it's fine. I made some renaming and formatting, here is the result:

public boolean[] sieveOfEratosthenes(final int max) {
    if (max < 0) {
        throw new IllegalArgumentException("max cannot be less than zero: " + max);
    }
    final boolean[] primeCandidates = new boolean[max]; // defaults to false
    for (int i = 2; i < max; i++) {
        primeCandidates[i] = true;
    }

    final double maxRoot = Math.sqrt(max);
    for (int candidate = 2; candidate < maxRoot; candidate++) {
        if (primeCandidates[candidate]) {
            for (int j = 2 * candidate; j < max; j += candidate) {
                primeCandidates[j] = false;
            }
        }

    }
    return primeCandidates;
}


"So just after some thoughts on this really... good or bad?"

Bad, really bad, I'm afraid. You're trying to make the language do something it doesn't want to do, or even: can't do. You're gluing feathers to a fish's fins, and throwing it up into the air, so it can mimic a bird's behaviour.
Your test code shows a dramatic decrease of speed (after switching to strstr, still ~5 times slower than usual). And you're only testing your code with valid input. Besides, have you even checked if you can get this function to return what it needs to return, and to Where?

The simple fact of the matter is this: each function call with your improvised (hacked) type-hints will issue an error, even if the type is correct.
It will, however, issue a notice in these cases, too:

function test(integer $foo)
{
    return $foo;
}
test('123');

How will you recover from this error? Are you going to add:

if (settype($argument, $expected) == $argument)
{
    call_user_func_array($function, array($argument));
}

to your error handler? and how are you going to deal with functions that take arrays of ints, or what if the user passes null?
There's just too many things to consider here.

Your approach also poses problems when you scale things up a little: Have you thought about what would happen if you used this code in tandem with a framework, that uses namespaces, sets all sorts of handlers all over the place, and uses complicated autoloading trickery?
Even simple autoloading would mean that PHP sets out to look for this integer class. That means calling the autoloader, when that turns out to be unsuccessfull, PHP will of course use the include paths, and a lot of I/O disk access is the result. Disk I/O is a speed killer, as we all know.

Note that lookups of files that aren't found are not cached!, so each type-hint will result in disk access. Whomever is hosting this code, if it ever got used in even a medium traffic site, will not be happy.
Perhaps this has changed with PHP5.5, but most hosting services are yet to upgrade.

Each function call, in your simple example, is already approx. 5 times slower than a normal one. Add the overhead of a custom autoloader, several layers of error/exception handlers to that, and you'll see the avg time per function call drop even more (probably converging on the initial times you had). Simply because autoloaders often access the disk, too, with file_exists calls, using the include path to scan for files who's name resembles that of the class that needs to be loaded, only to fail, and have PHP do the same disk operations again.
Then, like the example I listed: getting ints from a db, or user input means that these numbers are all passed around as strings, but are perfectly castable/usable as integers.

Suppose you were able to get the called function, cast the arguments accordingly and call the function again, what would happen? Well, the function gets called again, so another error is triggered, and your handler, which is now the caller of the function will be called twice.
Of course, the second time, owing your intervention, the types will match this time, but that's 4 function calls (5 including call_user_func_array) + 2 errors being raised to complete a single call:

Original caller           /->fails, PHP====\\
 \\              //``!AUTOLOADER!``<=\\    ||
  \\             ||                   \\   \/
   \=======> function -------> error   \==>DISK I/O !!TWICE!! per call
    \|            /\              \\
    ??            ||               \==> handler, type checking + casts
    ||            ||                    ||   /\
    ||            ||call_user_func_array||    |
    ??            |======================|    |
    ||                 \\    error2           |
    ||                  \----------------------
    ||                         ||
    ??                         \/
    ||      suppose it returns, still disk I/O and
    ||                                         ||
    ||           good luck getting back there  //
    \\=========================================/

An that's just assuming no intern gets the brilliant brain-wave to actually create a string or integer class or interface!

Even if you manage to get all of this working, a recoverable error isn't guaranteed to have anything to do with your special-case type-hints. Your handler was created with a specific type of error in mind, which -logic dictates- should be an E_USER_NOTICE.

Of course, you can't force the language to emit such an error when a non-custom error is encountered.

Ah well, you could try to work on this a bit more, if you want to, but I'd say you're better of spending that time to refactoring your functions like so:

/**
 * my test func - EXPECTS INTEGER
 * Any decent IDE uses these doc-blocks
 * @param int $integer
 * @return int
 **/
function test($int)
{
    $int = (int) $int;//cast to be sure
    //code
    return ++$int;
}

That'd be a better way to spend your time, and just ensure people you work with have a decent IDE, that parses the doc-blocks.


Your code is vulnerable to sql-injection.  For example, if $quest contains a ' character, your INSERT will break.


Hashing 2 strings to an int and adding to HashMap

The indentation looks a little a bit off, but it might be the case that the code did not paste from your editor properly, so I will omit this topic.
There are two methods in your code, and each of them does a lot of different things. It's not a good practice. One method should do one thing.
Let's take a look at the addToMap method. It computes the hash and then puts it's to the map. I would recommend to factor out a separate method for hash computation. You can also make the code more concise by using the getOrDefault method (to avoid the if statement at the end of the method. It applies only if you're using Java 8).
The main method is even bigger. Firstly, it does some input preprocessing (removing punctuation marks, splitting and so on). This part is definitely a candidate for its own method. Iterating over a list with an index-based loop is less readable (and, for some types of lists (not the case for ArrayList), is much slower than a Collection-based for): you could just write something like: for (String currentWord : wordList) ....
You may also consider making logging more flexible and separating it from the code that performs computations (print statements in the main method look quite arbitrary).
It is conventional to surround all binary operators with whitespaces.
It's not common to have more than one statement per line as it makes the code less readable: goodWords.add("good");goodWords.add("increase");goodWords.add("excellent");... doesn't look good, does it?
It's better to store "magic" constants (like 11 and 31 in your code) in final variables with meaningful names to minimize confusion(int hash=11; looks sort of arbitrary to me. What does 11 mean? int hash = INITIAL_HASH_VALUE or something like this is easier to understand).


std::unordered_map<std::string, int> is an overkill. Since you only need to track of a presence - which is naturally boolean - std::set<std::string> is enough. As a perk benefit, notice that std::set::insert indicates whether the insertion was successful or not (this is an anomaly), and std::set::erase return a number of elements erased (0 means the key was not there, another anomaly):

    std::set<std::string> registry;
    bool UserEntered(const std::string& user) {
        return !registry.insert().second;
    }
    bool userExited(const std::string& user) {
        return registry.erase(user) == 0;
    }

Now both methods return the anomaly:

    bool anomaly;
    if (action == "entered") {
        anomaly = userEntered(user);
    } else if(action == "exited") {
        anomaly = userExited(user);
    } else {
        // handle error here
        return;
    }
    LogAction(....);


compare the difference and extract the differences into parameters.
you can look at this.

function createMatrix(domId) {
    var i, j;
    var htmlElements = "";
    var matrixWidth = parseInt(document.getElementById(domId).value, 10);
    var matrixHeight = parseInt(document.getElementById(domId).value, 10);

    if (matrixWidth <= 7 && matrixHeight <= 7) {
        matrix = new Array(matrixHeight);
        for (i = 0; i < matrix.length; i++) {
            matrix[i] = new Array(matrixWidth);
        }
        for (i = 0; i < matrix.length; i++) {
            htmlElements += "
";
            for (j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = "
<input type=\"number\" class=\"form-control\" id=\"b" + (i + 1) + (j + 1) + "\" placeholder=\"b" + (i + 1) + (j + 1) + "\" >
";
                htmlElements += matrix[i][j];
            }
            htmlElements += "
";
        }
        document.getElementById(domId).innerHTML = htmlElements;
    } else {
        document.getElementById(domId).innerHTML = "
Maximum matrix size is 7x7.
";
    }
}

createMatrix('matrix-width-a');
createMatrix('matrix-width-b');


Since you're on NUnit, why don't you just use its built-in TestCase attribute? Your test would then look like this:

[<TestCase("123", true)>]
[<TestCase("Foo", false)>]
[<TestCase("123Foo123", false)>]
let ``IsNumericTest``(candidate : string, expected : bool) =
    let actual = isNumeric candidate
    actual |> should equal expected

xUnit.net (a better unit testing framework for .NET) has a similar feature.


You wished for some style and cleanliness advice, so here are a few things you may improve in that area:

Don't include gcd in you class because it is actually completely unrelated. Instead, write a separate non-class function for it.
Name your parameters. Things such as Fraction add(Fraction); usually imply that the parameter is ignored, and even if the user understands that this is not the case here, it remains unclear what your parameter actually represents.
Include all the headers that you use. Your code is currently missing a #include <string>.
Do some error checking and assure that parameters are valid. For example, what happens when somebody passes 0 for d to the constructor? You will end up in an infinite loop because your gcd function does not verify that its arguments are not 0.
Avoid C-style casts. C++ offers a variety of casts with clearly defined purposes, whereas the C cast covers a lot of different conversions, some of which you may not want. In your particular case, don't write (double)numerator; write static_cast<double>(numerator) instead (same for denominator, of course).
Instead of having add, subtract, multiply and divide, you should overload the corresponding operators (e.g. operator+ for add). You should also consider adding more operators, such as operator+=, operator-= and so on and so forth.
Don't use std::endl where a simple '\n' would suffice (which is almost always). The reason for this is that std::endl also flushes the underlying buffer which can seriously harm performance when doing lots of IO and is seldom required.
fraction is a bad name for a function that returns a string representation of your class. You could call it to_string for example, or even choose to implement explicit operator std::string().
You can safely omit return 0; at the end of main, the compiler is nice enough to add it automatically.
Currently, your constructor calculates gcd(n, d) twice. You should calculate the value once and then divide set numerator = n / gcd_value and denominator = d / gcd_value instead.
You should consider adding adding a default value of 1 to the second parameter to the constructor to enable construction of fractions from whole numbers easily, i.e.

Fraction::Fraction(int n, int d = 1);
...
Fraction f {3}; //f represents the fraction 3/1

Don't treat single characters as strings when you don't need to. In your case, replace "/" by '/' in fraction. There is an operator+ in std::string that handles single chars.
Fix the unnecessary whitespace in Fraction (int, int). Judging by how you defined your other methods, it should instead read Fraction(int, int) (I suppose this is just a typo).

Edit: As JPhi1618 pointed out in the comments, it is better to not get into the habit of relying on implicit construction when assigning values to objects. Instead, one should make use of explicit construction and uniform initialization. Accordingly I changed last line of the code sample of point 11 from Fraction f = 3; to its current representation.


Checking login from associative array vulnerabilities

In this response, I assume that you are making a little script for yourself and some friends, i.e. not a large or critical system (e.g. that could delete other files). So you want some security, but not to extreme measures.
Passwords in Plain Text
As pacifist mentioned, storing passwords as clear text is always a bad idea. If you're just making a little page for yourself and some friends, at least store the passwords hashed with a salt (a random string per user). You could then store your login data the following way:
$logins = array(
 'user' => array('hash' => 'ae092...', 'salt' => 'a7#(ad~I$...'),
);

Checking for a valid login would then be used the following way (using PHP's crypt() to make SHA-256 hashes):
// Added trim() so something like "user " becomes "user"
$user = strtolower(trim($_POST['user']));
$pass = $_POST['password'];

if(isset($logins[$user]) && crypt($logins[$user]['salt'].$pass, 'SHA-256') == $logins[$user]['hash']) {
   // valid login!
}

This is not much more difficult and already provides you a little more safety. This is still not sufficiently safe for critical applications – you can read all about password hashing over at Security StackExchange. The linked answer covers a lot of aspects and is a great starting point.
Again, the above code is a simple way of handling logins for a small, non-critical page.
At the very worst, if you can't be bothered to give an individual salt to every user, add a global prefix/suffix to each password – a so-called pepper. You'll still be better off (preventing online rainbow table look-ups), because it doesn't take any knowledge at all to search the SHA-256 hash of "admin" and look up the results. However, searching the hash of admin!OTdf-u23;)(#$@_!#Rlf (where the text after admin would be your pepper) will most likely not return any results.
Brute Force
OK, but now let's assume your hashes/passwords don't ever leak. So, if I would want access, how would I proceed? I would just send probable passwords to the login form. You have no protection against abusive login attempts, so I can try as many passwords as I please. After the plain text storage of passwords, this is your weakest point, IMHO.
If it's a small, trivial script, it's probably not worth implementing anything to block that as no one will bother, though if there could be some substantial damage, it might be best to block invalid login attempts after a while. You know how things are now, but maybe you'll pick a fight with the wrong guy later on, or an automatic script will pick up on your login form.
A quick & dirty blocking mechanism is to keep an array of the number of invalid login attempts per IP address ($logins = array('127.0.0.1' => 3)). Once it reaches a certain number, you either block it permanently (if it's a small script and your friend is affected, he'll contact you) or you log the time and block it for a day or so.
Issues with Warnings
I recommend you output all warnings at least during development; this could help you find some issues. This can be done by adding error_reporting(E_ALL) to your login page.
A few issues that will arise is the direct reference to $_POST without checking first; use isset($_POST['user']) to see if the key you're asking for exists in the first place.
If you want to take it a step further, you could also do a check with is_scalar(), as sending an array as $_POST['pass'] will make crypt() issue a warning. This is something a lot of websites tend not to cover, which allows an attacker to find out the full path of your server and possibly the inner workings of your scripts (say, if the error comes from /hidden_include_folder/validator.php, this file will be shown in the error).
Working with Files
You need to account for concurrent file modifications. Again, if this is just a little fun script, it's a risk you can take, but anything of substantial size and/or importance should really be handled with a database like MySQL, which accounts for concurrent modifications and handles them for you automatically.
Note that keeping data in a file does not scale well; if you think the amount of data you're storing could grow a lot, consider setting up a database. I've seen it happen more than a few times that PHP reads a large file, then runs out of memory while writing to it, and the file ends up being empty – not a fun situation.


Calculating user efficiency on a time period with Linq

Don't one line things that shouldn't be one lined. Just because you can do something, doesn't mean that you should.
Extract the duplicated query into a method of it's own that returns an IQueryable
Don't query the database twice for the same count, execute the query and store it in a variable.

private IQueryable<foo> ExecutorOrdersInLast30Days(ApplicationUser e)
{
    return e.ExecutorOrders.Where(x => x.Added >= DbFunctions.AddDays(SqlFunctions.GetUtcDate(), -30));
}

private decimal EfficiencyPercent(ApplicationUser e)
{
    var nonDeletedOrders = ExecutorOrdersInLast30Days(e).Count(x => x.Status != Order.OrderStatus.Deleted);
    if ( nonDeletedOrders > 0)
    {
        return nonDeletedOrders / ExecutorOrdersInLast30Days(e).Count();
    }
    else
    {
        return 0;
    }
}


I would suggest that you read these pieces from MSDN:

Basic Dispose Pattern,
 Implementing a Dispose Method

Some things that immediately stand out from your example:

Replace your GC.Collect() with GC.SuppressFinalize(this)
Check your resources aren't null before attempting to dispose them.
Check that your objects haven't already been disposed.

All of this is easily done by following the dispose pattern.


Is the following service layer correctly implemented with multiple repositories?

Business Model/Logic

These are two distinct things: your model and your logic should be implemented in separate  classes - the business model defines a Car class, and the business logic consumes it. In other words, I think your Car class is breaking SRP.

The way I see it (could be wrong) is pretty much like this (assuming MVC):

In other words, CarController only needs to know about a CarService, which gives it a model that contains everything the view needs to know - the CarService "puts the pieces together" so that the business logic "layer" can do its part.

I think having a dependency on IFileSystemService in your Car class makes that class be more than just a model.

Also, in "repository 2":

public Car GetPictureForCar(int carId)

I don't think it makes much sense to return a whole Car from a method called GetPictureForCar - I'd expect that method to return an Image.

This is even more surprising:

Car myCar = this.GetFileForCar(carId);

I'd expect GetFileForCar to return either a File class, or a string with the file's name.

Same here:

Image imgfile = _Repository.GetPhysicalFileLocation(carId);

A method that's called GetPhysicalFileLocation should be returning a string with the file's name. And to follow C# naming conventions, _Repository should be _repository (assuming it's a private field).


Extracting an integer command-line argument and printing a sum of numbers up to that limit

This is the code you're looking for:

main = do
  args <- getArgs
  let arg1 = head args
  let n = (read arg1) :: Int
  putStrLn . show $ sum [1..n]

Think of the <- operator as "extract". It "pulls" a value out of a monad.

But once you've pulled args out of the IO monad, you've now got a pure list of strings. It's not in the IO monad, so you can't extract from it. let instead just does a pure binding like you're used to in non-monadic code, which is what you need here.


symbols = ['O','X']

This will not change, so it doesn't need to be mutable. It's better represented as a string:

symbols = 'OX'

This:

def createBoard():
    a = ['', '', '']
    b = ['', '', '']
    c = ['', '', '']
    return [a, b, c]

can simply be

def create_board():
    return [['']*3 for _ in range(3)]

Note that the convention for Python is snake_case, not camelCase.

getMove can be made more efficient. You do not need a dictionary.

i = int(input('Please enter the number of the '
              'spot to place your move > ')) - 1
return i%3, i//3

You're using board as a global, which is a code smell. Most of these methods, along with the board member, should be put into a class.

This:

if currentPlayer.number == 0:
    return 1
else:
    return 0

can be:

return 1 - current_player.number

Your boolean game variable is unnecessary. Rather than setting it to false, simply break out of the loop.

At the top of the file, there should be a shebang:

#!/usr/bin/env python3


For your argc <- return $ length args , the reason the compiler is telling you to use the return is because in do notation, monadic binding lines must be the form:

binding <- value wrapped in whatever monad you're using

So length args just returns an Int, but Haskell wants an IO Int. By doing return $ length args, you lift the value returned by length args into the IO monad.

You are correct in smelling something funny here. Haskell provides a much cleaner way of assigning non-monadic values to be used inside of do notation with the let keyword.

You can replace those two lines with:

let argc = length args
    destination = last args

Note that bindings must have the same indentation level within a let assignment block.

But really, there is more to improve! In Haskell, the four most common list partitions are:

First element (head)
Last element (last)
Everything but the first (tail)
Everything but the last (init)

So with init we can eliminate the need for argc, changing your main to

main = do
    args <- getArgs
    let destination = last args
    concatFiles destination $ init args

But really, the word destination is longer than the function call last args, and doesn't really add much clarity, so we can change that, too, removing the need for the let entirely!

main = do
    args <- getArgs
    concatFiles (last args) (init args)

And if you really wanted to become more intimately familiar with how do notations and monads in general work, we can actually remove the do notation and replace it with a >>= operator by doing

main = getArgs >>= \args -> concatFiles (last args) (init args)

So as a quick recap of what is happening here, we are calling getArgs, which returns a list of arguments wrapped in the IO monad. The >>= (bind) operator takes that IO value, extracts the value inside, and sends it into the function on the right side of the >>= operator, where it gets bound to the argument args.


You asked, "Can you think of any disadvantages of this approach?" One obvious problem is that this requires you to construct a new class each time the wrapper is called, which potentially ends up wasting a lot of memory. So you would want to cache and reuse these classes.

class Wrapper(object):
    # A map from (value type, wrapper class) to wrapped class
    __cache = {}

    def __new__(cls, value):
        value_type = type(value)
        bases = value_type, cls
        try:
            wrapper_class = cls.__cache[bases]
        except KeyError:
            wrapper_class = type(value_type.__name__, bases, {})
            cls.__cache[bases] = wrapper_class
        return wrapper_class(value)

Note that this is a rare case where we actually want to use a private name — the idea is to avoid a name clash when wrapping a class that already has a cache (or _cache, or whatever name we pick) attribute.

I can't help feeling, though, that Martijn Pieters is right in the Stack Overflow version of this question: if you just want to proxy a dictionary key, then you just need to proxy the __eq__ and __hash__ special methods. Keep it simple!


Armstrong numbers in a given range using Java 8 (Follow Up)

Looking at the code for Integer.toString, it seems to be a lot of work to convert an integer to a string. At the moment, you're doing the conversion twice.

However, getting the length of a string, via String.length, is a simple getter. As such, you'd probably be better off with storing the string representation in a variable, and calling .length() on that.

public static void main(String[] args) {
    IntStream.range(1, 10_000_000)
            .filter((n) -> {
                final String number = Integer.toString(n);
                return number.chars()
                        .map(d -> d - '0')
                        .mapToDouble(v -> Math.pow(v, number.length()))
                        .sum() == n;
            }).forEach(System.out::println);
}

Also, good job coming up with the idea of substracting '0' from each character to cast it back to a number: that's a far better idea than what I had in mind (using complicated parse functions).

You could, in theory, perform this step at .mapToDouble, via Math.pow((v - '0'), number.length()) but I'm not sure whether that helps the readability. It does make things a lot shorter, I guess.

A potential performance upgrade after this would be to consider storing the result of Math.pow in a lookup table; whenever you surpass the current digit length, multiply each value of the lookup table by its index and continue. Right now, this doesn't seem very relevant to me, but later, this might be an issue.


I took a look and came up with a couple of suggestions:

Extend rather than wrap

I think it will be more useful if you extend the Point2D.Double class, instead of writing a wrapper around it. This way you will be able to use your custom point class everywhere that a normal Point2D.Double is expected. It also spares you from implementing and overriding many of the Double's methods like getX() and the hashCode() and toString() methods.

Use static method for construction from line

When subclassing Double it is not possible to have a constructor that takes a line, does some calculations and then calls super(), as super has to be the first call in the constructor. Therefor we need to add a static utility class to create a Point from a line. See the fromLine() method below.

I think this is not a problem, as it leads to very readable line:

Point start = Point.fromLine(line);

Documentation

Your code does not include any documentation in form of comments, so that for example the input format for the fromLine() function is not entirely clear. Also it only uses one point from a line (which should be two points?), so maybe it should be called fromLineStart() or fromLineEnd() depending on which you mean.

Class Naming

The current name Point doesn't tell us a lot about what the class does. Maybe use something a little more descriptive like PointDouble2D? Maybe add some indication as that it does more than the normal Point2D.Double, by naming it: PointDouble2DAdvanced or something like that, not totally sure myself :)

Final Result

Here is the entire code example, without documentation comments:

import java.awt.geom.Point2D;

public class PointDouble2D extends Point2D.Double {

    public Point(double x, double y) {
        super(x, y);
    }

    public boolean dominates(Point2D.Double point) {
        return (getX() <= point.getX() && getY() < point.getY())
                || (getY() <= point.getY() && getX() < point.getX());
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append('(').append(getX()).append(", ").append(getY())
                .append(')');
        return builder.toString();
    }

    public static PointDouble2D fromLineStart(String line, String delimiter) {
        line = line.trim();
        String[] lineArray = line.split(delimiter);
        double x = java.lang.Double.parseDouble(lineArray[0]);
        double y = java.lang.Double.parseDouble(lineArray[1]);
        return new PointDouble2D(x, y);
    }
}

What do you think?


You follow a lot of standard practices well, so the code is actually quite easy to read, but there are some ways to consolidate a bit that'll make it even simpler.

You while loop while the guess is incorrect, but you also break when the answer is correct, nullifying the need for the condition. This also has the unintended side effect that, if their answer is correct in their first guess, you never enter the loop, and therefore never congratulate the user for winning. Change this into while True: or, much better, provide some maximum number of guessed then do for _ in range(max_num_guesses):

You repeat the input/print/int call many times, but this could just be the first part of the loop instead. It alters the formatting very slightly, but makes for much more readable/maintainable code.

global variables aren't usually a good idea in the long run; consider making num a parameter instead, then call randint wherever it is you call this function.

Some last minor tweaks I would suggest: move the "guess again?" logic to outside this function--recursion isn't the most intuitive solution in this case, and could get you into trouble (recursion limits, memory "leaks", etc.); use elif when chaining mutually-exclusive if statements; convert user input to lower case when checking if they input y, especially since your input message explicitly tells them that 'Y' is a valid, expected input.

The final code looks something like the following:

def user_guess(num, max_num_guesses=10):
    for _ in range(max_num_guesses):
        guess = int(input("Guess a number between 1 and 100: "))
        print("Your guess was {}".format(guess))

        if guess < num:
            print("Your guess was too low: guess again!")
        elif guess > num:
            print("Your guess was too high: guess again!")
        elif guess == num:
            print("Correct! Well done!")
            return

    print("Sorry, you ran out of guesses.")

if __name__ == '__main__':
    while True:
        user_guess(random.randint(1, 100))

        again = input("Would you like to play again? (Y or N): ")
        if again.lower() != "y":
            print("Ok, goodbye")
            break


Your logic is incorrect in a few places.  The first problem is that you are modifying word inside the loop so you probably want to cache the size before you use it in the loop indices.  This is one of those insidious bugs.

int size = word.size();

for (int i = 0; i <= size / 2; i++) {
    s.push(word[0]);
    word.erase(0, 1);
}

if (word.size() > s.size()) {
    word.erase(0, 1);
}

I'm going to assume from here on that the cached size code above is what you intended the behavior of this program to be.  Moving on to the next problem.  Consider when word.size() is even, say 8.  i will iterate from 0 to 4 inclusive.  So s will have 5 characters and word will have 3.  If word.size() was 9 then i would iterate from 0 to 4 as well, leaving word with 4 characters.  Hence, after the loop, word.size() will never be greater than s.size().  In trying to handle the odd case you produced a bug in the even case.  The loop bound you are looking for is:

for (int i = 0; i < size / 2; i++)

Here is the updated code for the first half:

int size = word.size();

for (int i = 0; i < size / 2; i++) {
    s.push(word[0]);
    word.erase(0, 1);
}

if (word.size() > s.size()) {
    word.erase(0, 1);
}

Now you can verify that word.size() and s.size() will always be the same at this point.  This means that inside the while loop you can remove the following check since s.size() and word.size() will both reach 0 at the same time:

if (s.size() == 0 || word.size() == 0) {
    return true;
}

Now the only way you can exit the loop is if all the letters on the stack and in the second half of the word were indeed the same.  Which of course means that word is a palindrome.  So just put a return true at the end.

You can now remove the following check before the while loop too since in this case the loop won't run and you will jump down to return true:

if (s.size() == 0) {
    return true;
}

With all of that said I think the code is a bit too complex.  There is no need to modify word.  With some integer arithmetic you can use two loops to iterate through word without deleting anything.

I will print out the loop indices for three looping methods you can use.

Method 1:

int i;
for(i = 0; i < n/2; i++)s.push(word[i]);
if(n % 2) i++; // skip the middle index if n is odd
for(; i < n; i++)  compare_stuff();

Method 2:

for(int i = 0; i < n/2; i++)s.push(word[i]);
for(int i = (n+1)/2; i < n; i++) compare_stuff(); // skip the middle index if n is odd

Method 3:

for(int i = 0; i < (n+1)/2; i++)s.push(word[i]);
for(int i = n/2; i < n; i++) compare_stuff();  // check the middle index against itself if n is odd

Method 2 is probably the best for this problem since it allows for local loop indices and doesn't check the middle value unnecessarily.

My code would be:

bool isPalindrome(const std::string& word)
{
    uint n = word.size();
    std::stack<char> s;

    for(uint i = 0; i < n/2; i++)
    {
        s.push(word[i]);
    }

    for(uint i = (n+1)/2; i < n; i++)
    {
        if(s.top() != word[i])
        {
            return false;
        }

        s.pop();
    }

    return true;
}


Pythonic solution to display multi-dimensional tuple as a tree

Neither the code provided in the question or the top voted answer work correctly. This is as you're making unreasonable assumptions on how the data is formed.

>>> print(showtree('(A)'))
└─A
>>> print(showtree('(1, ((2)), (3, 4, (5)))'))
┬─1
├─┬─└─2
├─┬─3
│ ├─4
│ ├─└─5
>>> print(tree_string_to_display_string('(1, ((2)), (3, 4, (5)))'))
┬─1
├─┬─└─2
├─┬─3
│ ├─4
│ ├─└─5

Your code is also doing two things at once, parsing a string and building a tree. And so I will only take a tuple as input. If you need to take a string then you can build the parser separately.

Make the code work with one item.

To do this should be fairly simple, we take the tuple ('1',) and return ──1.

def build_tree(root):
    return '\n'.join(_build_tree(root))

def _build_tree(node):
    yield '──' + node[0]

>>> print(build_tree(('1',)))
──1

Make the code work with 1, 2 or more items.

This is fairly simple, we check node's length and use the above code if it's 1. Otherwise we make:

The first item start with ┬─.
The last item start with └─.
All other items start with ├─.

This is as simple as using tuple unpacking, and then iterating over the middle.

def _build_tree(node):
    if len(node) == 1:
        yield '──' + node[0]
        return

    start, *mid, end = node
    yield '┬─' + start
    for value in mid:
        yield '├─' + value
    yield '└─' + end

>>> print(build_tree(('1',)))
──1
>>> print(build_tree(('1', '2')))
┬─1
└─2
>>> print(build_tree(('1', '2', '3')))
┬─1
├─2
└─3

Get the code to work if you only enter a value, no tuples.

This is simple, since we're only allowing tuples as the nesting datatype, then we can just add an if not isinstance(node, tuple). We will convert this to a string now to help our future selves.

def _build_tree(node):
    if not isinstance(node, tuple):
        yield str(node)
        return

    if len(node) == 1:
        yield '──' + node[0]
        return

    start, *mid, end = node
    yield '┬─' + start
    for value in mid:
        yield '├─' + value
    yield '└─' + end

>>> print(build_tree('1'))
1

Get the code to work recursively with the same input as (2). To check this we will change the input to integers.

This is simple. We run _build_tree on all the values in node, if it's a tuple. From here we only work on these values. We know these values are going to be iterators with only one value. This means we can just use next for now.

def _build_tree(node):
    if not isinstance(node, tuple):
        yield str(node)
        return

    values = [_build_tree(n) for n in node]
    if len(values) == 1:
        yield '──' + next(values[0])
        return

    start, *mid, end = values
    yield '┬─' + next(start)
    for value in mid:
        yield '├─' + next(value)
    yield '└─' + next(end)

>>> print(build_tree((1,)))
──1
>>> print(build_tree((1, 2)))
┬─1
└─2
>>> print(build_tree((1, 2, 3)))
┬─1
├─2
└─3

Get the code working recursively.

We know all the current yields work the same way, and so this calls for a new function. This should take three values:

The value to add to the first item. (This is what we're doing right now)
The value to add on all other items.
This is important as if a node is only one large. But has nested data that is larger than one value then we will add '  ' to the output.
The nested data.

This is really simple to build:

def build_lines(first, other, values):
    yield first + next(values)
    for value in values:
        yield other + value

Finally we adjust the current yields so they are yield from functions.

def build_tree(root):
    return '\n'.join(_build_tree(root))

def _build_tree(node):
    if not isinstance(node, tuple):
        yield str(node)
        return

    values = [_build_tree(n) for n in node]
    if len(values) == 1:
        yield from build_lines('──', '  ', values[0])
        return

    start, *mid, end = values
    yield from build_lines('┬─', '│ ', start)
    for value in mid:
        yield from build_lines('├─', '│ ', value)
    yield from build_lines('└─', '  ', end)

def build_lines(first, other, values):
    yield first + next(values)
    for value in values:
        yield other + value

>>> print(build_tree(('01', ('02',  '03', '04'), '05', (('06', '07'), '08'), ('09', ('10', '11'), ('12', '13'), '14'), '15')))
┬─01
├─┬─02
│ ├─03
│ └─04
├─05
├─┬─┬─06
│ │ └─07
│ └─08
├─┬─09
│ ├─┬─10
│ │ └─11
│ ├─┬─12
│ │ └─13
│ └─14
└─15
>>> print(build_tree(('A', 'B multi-word item', ('C', 'D'), ('E', '', 'F'), 'G')))
┬─A
├─B multi-word item
├─┬─C
│ └─D
├─┬─E
│ ├─
│ └─F
└─G
>>> print(build_tree((1, ((2,),), (3, 4, (5,)))))
┬─1
├─────2
└─┬─3
  ├─4
  └───5


Destructure array and use object shorthand assignment

I discovered that array destructing has the capability of providing default values.

const [, id = '', text = ''] = match;
return { id, text };

Array Destructuring


Let's start with the trivial stuff...

A few minor stylistic points that are pretty much universal:

The type IO () is always written with a space between IO and (), never IO().
Similarly, multiple constraints are written as a comma-separated list:

(Fractional a, Ord a) => ...

rather than a chained list (Fractional a) => (Ord a) => ...
For do-blocks, even though the syntax permits:

do
firstLine
secondLine

they are almost never written this way.  It's either:

do firstLine
   secondLine

or else:

do
  firstLine -- w/ your standard choice of indentation, usually 2 or 4
  secondLine

It's often considered acceptable to write:

someother expression $ do
  contentsOf
  theDoBlock

so the contents can be unindented or negatively indented with respect to the do keyword in this case.

For the specific do-block in your main function, because a standalone let statement is permitted in do-notation, you don't need the nesting at all, so this would be more standard:

main = do
  ...
  let shift_size = decrypt (map toLower $ filter isAlpha encrypted)
  print shift_size
  writeFile (filename ++ "_DECRYPTED") (shift (negate shift_size) encrypted)
  hClose handle

(This is despite the fact that shift_size is only needed in the following two lines and not the last.)

I find that idiomatic Haskell tends to use where in preference to let ... in ... statements, so for example:

decrypt :: String -> Int
decrypt text = minShift frequencies $ map (flip (/) len) freq
  where len = fromIntegral $ length text
        (_, freq) = unzip $ toList $ fromListWith (+) [(c, 1.0) | c <- text]

The motivation here is that the definition of decrypt text is given immediately following the =, and if the helper functions like len and freq have sufficiently self-evident names, the reader can mostly ignore the where ... details.

More controversially, some people like to write the most general type signatures possible.  In my opinion, unless you're writing a library or actually need the generality, I don't think there's much point.  The polymorphic type signatures and Fractional constraints clutter up your code, and if you turned on -Wall, which you should be doing anyway, you'd see that GHC is defaulting your type to Double, a default that would be better to make explicit anyway.  Personally, I'd replace most of the Fractional a => ... a ... with Doubles.  (Well, except oneCycle and shiftList, which are probably clearer with unconstrained type signatures.)

Now to the less trivial stuff...

In minShift, consider the definition of norms:

norms = map (\x -> norm freq1 (shiftList freq2 x)) [0..25]

This calculates shiftList freq2 x for every x from 0 to 25, but shiftList works by generating the full list iterate oneCycle freq and then selecting element x, so you would have been better off writing:

norms = map (norm freq1) (take 26 $ iterate oneCycle freq2)

Actually, a more common way of calculating all "cycles" of a list is:

cycles :: [a] -> [[a]]
cycles xs = zipWith (++) (tails xs) (inits xs)

which many Haskellers take great pride in writing using implicit reader monad/applicative:

cycles :: [a] -> [[a]]
cycles = zipWith (++) <$> tails <*> inits

Also, finding the minimum with minimum and then getting its index with elemIndex would be frowned upon because it traverses the list twice (or, on average, one and a half times in the absence of duplicate minimums), and even though it's ridiculous to worry about performance on a 26-item list, I guess folks would be more likely to use a trick like:

minimumIndex :: (Ord a) => [a] -> Int
minimumIndex xs = snd . minimum $ zip xs [0..]

Note that I'm breaking my own rule here about not overgeneralizing functions.  In this case, it just "feels" right.  Anyway, the way this works is by using zip to add an index, so that the list xs = [5,4,6,1,8] becomes:

[(5,0),(4,1),(6,2),(1,3),(8,4)]

Because tuples are sorted lexicographically, finding the minimum will pick up the element (1,3), and we use snd to grab the index "3".

So, now minShift looks like this:

minShift :: [Double] -> [Double] -> Int
minShift freq1 freq2 = minimumIndex $ map (norm freq1) (cycles freq2)

with helpers minimumIndex and cycles as above.

For the top-level norm function, your foldl is really a sum, and you can use zipWith to combine the zip with the calculation of the term:

norm :: [Double] -> [Double] -> Double
norm xs ys = sum $ zipWith (\x y -> (x-y)^2) xs ys

With -Wall on, this warns you that 2 is defaulting to Integer.  I'd probably write:

norm :: [Double] -> [Double] -> Double
norm xs ys = sum $ zipWith (\x y -> (x-y)*(x-y)) xs ys

just to get rid of this warning.

In decrypt, the flip can be replaced with a section:

decrypt text = minShift frequencies $ map (/ len) freq

However, there's a bug in your freq calculation.  The map it builds will only have keys for the letters that actually appear in the input text, so the freq and frequencies lists won't generally line up.  Anyway, I'd pull it out into a separate function:

{-# LANGUAGE TupleSections #-}
import qualified Data.Map.Strict as Map

freq :: String -> [Int]
freq inp
  = Map.elems $ Map.unionWith (+) initMap . Map.fromListWith (+) . map (,1) $ inp
    where initMap = Map.fromList . map (,0) $ ['a'..'z']

This uses Map.unionWith and an all-zeros map initMap to ensure the keys 'a' through 'z' will be in the map.  It also uses Map.elems in place of let (_, freq) = unzip $ Map.toList $ ....

Finally, note that I've used Data.Map.Strict.  This is good practice for "counting" maps, so that large inputs don't cause a memory leak.

My decrypt now looks like:

decrypt :: String -> Int
decrypt text = minShift frequencies $ map (/ len) $ map fromIntegral $ freq text
  where len = fromIntegral $ length text

Also, shiftLetter would probably be clearer to write with separate cases and a helper in place of bool.

shiftLetter :: Int -> Char -> Char
shiftLetter offset c
  | isAsciiLower c = go 'a'
  | isAsciiUpper c = go 'A'
  | otherwise      = c
  where go a = chr $ (ord c - ord a + offset) `mod` 26 + ord a

Note that the isAscii... versions are safer than isLower and isUpper because these allow unicode letters.

For shift, some typical simplifications are possible.  So:

shift s input = map (shiftLetter s) input

can be rewritten (using "eta reduction") as:

shift s = map (shiftLetter s)

Some people might go farther and write:

shift = map . shiftLetter

though this isn't particularlyclear.  Maybe this would be a nice compromise:

shift :: Int -> String -> String
shift offset = map shift1
  where
    shift1 c
      | isAsciiLower c = go 'a' c
      | isAsciiUpper c = go 'A' c
      | otherwise      = c
    go a c = chr $ (ord c - ord a + offset) `mod` 26 + ord a

allowing us to eliminate shiftLetter completely.

In main, for quick-and-dirty argument parsing, you can write:

[filename] <- getArgs

This has the advantage over filename:_ <- getArgs of raising an exception if more than one argument is supplied.

The openFile / hClose pairs is more properly written using a withFile clause.  But, if you're opening a file just to read its contents, it's better to use readFile anyway.

encrypted <- readFile filename

so my final main looks like:

main :: IO ()
main = do
  [filename] <- getArgs
  encrypted <- readFile filename
  let shift_size = decrypt (map toLower $ filter isAlpha encrypted)
  print shift_size
  writeFile (filename ++ "_DECRYPTED") (shift (negate shift_size) encrypted)

The final thing that bothers me is that freq has to pass through the String once to calculate the counts, and then decrypt passes through it again to count the full text length.  I'd like to do it in one pass, so I'd rewrite freq to calculate the full text length, too, and return the fractional frequencies directly.  This also allows us to pull the filtering into freq which is safer, since the above version of freq will break if it gets fed input that isn't restricted to the characters from 'a' to 'z'.

freq :: String -> [Double]
freq str = let (tot', mp') = foldl' step (0::Int, initMap) . getLower $ str
           in  divlist (Map.elems mp') tot'
  where
    -- get ASCII letters, converted to lowercase
    getLower = filter isAsciiLower . map toLower
    -- initial map of all-zero counts for 'a' to 'z'
    initMap = Map.fromList . map (,0::Int) $ ['a'..'z']
    -- for each `c`, add one to `tot` and count a `c`
    step (tot, mp) c = (tot+1, Map.insertWith (+) c 1 mp)
    -- divide each element of xs by n
    divlist xs n = map (/ fromIntegral n) (map fromIntegral xs)

This works with the following versions of main and decrypt:

main :: IO ()
main = do
  [filename] <- getArgs
  encrypted <- readFile filename
  let shift_size = decrypt encrypted
  print shift_size
  writeFile (filename ++ "_DECRYPTED") (shift (-shift_size) encrypted)

decrypt :: String -> Int
decrypt text = minShift frequencies (freq text)
  where len = fromIntegral $ length text

Note that negate can be written - as long as you stick in some parentheses.  Some people hate this because this - is Haskell's only unary operator and looks weird, so they might stick with negate anyway.

Finally, I think I'd rearrange minShift a bit to make things easier to test.  Also, Data.Char and some others (Data.List and Data.Foldable) are commonly imported in full without explicit import lists, and Data.Map.Strict is commonly imported qualified without an explicit import list, so I'd probably write my imports as:

import System.Environment (getArgs)
import Data.List
import Data.Char
import qualified Data.Map.Strict as Map

This gives the final program:

{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -Wall #-}

import System.Environment (getArgs)
import Data.List
import Data.Char
import qualified Data.Map.Strict as Map

main :: IO ()
main = do
  [filename] <- getArgs
  encrypted <- readFile filename
  let shift_size = decrypt encrypted
  print shift_size
  writeFile (filename ++ "_DECRYPTED") (shift (-shift_size) encrypted)

decrypt :: String -> Int
decrypt text = minimumIndex $ norms english (freq text)

-- English letter frequencies from A to Z
english :: [Double]
english = [0.0812, 0.0149, 0.0271, 0.0432, 0.1202, 0.023, 0.0203, 0.0592, 0.0731, 0.001,
           0.0069, 0.0398, 0.0261, 0.0695, 0.0768, 0.0182, 0.0011, 0.0602, 0.0628, 0.091,
           0.0288, 0.0111, 0.0209, 0.0017, 0.0211, 0.0007]

norms :: [Double] -> [Double] -> [Double]
norms freq1 freq2 =  map (norm freq1) (cycles freq2)

norm :: (Fractional a) => [a] -> [a] -> a
norm xs ys = sum $ zipWith (\x y -> (x-y)*(x-y)) xs ys

freq :: String -> [Double]
freq str = let (tot', mp') = foldl' step (0::Int, initMap) . getLower $ str
           in  divlist (Map.elems mp') tot'
  where
    -- get ASCII letters, converted to lowercase
    getLower = filter isAsciiLower . map toLower
    -- initial map of all-zero counts for 'a' to 'z'
    initMap = Map.fromList . map (,0::Int) $ ['a'..'z']
    -- for each `c`, add one to `tot` and count a `c`
    step (tot, mp) c = (tot+1, Map.insertWith (+) c 1 mp)
    -- divide each element of xs by n
    divlist xs n = map (/ fromIntegral n) (map fromIntegral xs)

shift :: Int -> String -> String
shift offset = map shift1
  where
    shift1 c
      | isAsciiLower c = go 'a' c
      | isAsciiUpper c = go 'A' c
      | otherwise      = c
    go a c = chr $ (ord c - ord a + offset) `mod` 26 + ord a

minimumIndex :: (Ord a) => [a] -> Int
minimumIndex xs = snd . minimum $ zip xs [0..]

cycles :: [a] -> [[a]]
cycles = zipWith (++) <$> tails <*> inits

If I run hlint on this, I get one suggestion:

Caesar2.hs:43:20: Suggestion: Use map once
Found:
  map (/ fromIntegral n) (map fromIntegral xs)
Perhaps:
  map ((/ fromIntegral n) . fromIntegral) xs

In this case, I think the way I have it is clearer.

In this form, it's pretty easy to test:

> freq "It's pretty easy to test"
[5.263157894736842e-2,0.0,0.0,0.0,...]
> norms english (freq "It's pretty easy to test")
[8.694623493074792e-2,0.14473570861495846,0.17156728756232686,...]
> minimumIndex $ norms english (freq "It's pretty easy to test")
0
> decrypt "huk hjabhssf dvyrz xbpal dlss lclu vu zovya aleaz."
7
> shift (-7) "huk hjabhssf dvyrz xbpal dlss lclu vu zovya aleaz."
"and actually works quite well even on short texts."


Do I need to use a callback function here, or is there another way?

I would suggest to take a different approach. It is complicated to get a callback for the complete loading of a CSS stylesheet loaded dynamically: see this Stack Overflow question for reference:

Is there anyway to listen to the onload event for a  element?

Do not use JavaScript to set the content position: it is part of styling and should be done in CSS instead. Isn't the role of your CSS skins to modify the appearance of the page?


Translating words from one language to another

Personally, I would have the translate call return a Promise rather than a callback and make use of async/await (presuming the version of Node you are using Node 6+) e.g.

var express = require('express');
var request = require('request');

var router = express.Router();

router.post("/", async (req, res, next) => {
  try {
    const translated = await translate(req.query.source, 'en', req.query.content);
    const result = await translate('en', req.query.target, translated);
    // presume you intend on returning something from your API?
    return res.json({ result });
  } catch (e) {
    return next(e);
  }
})

const translate = (source, target, content) =>
  new Promise((resolve, reject) =>
    request(`https://api-platform.systran.net/translation/text/translate?input=${content}&source=${source}&target=${target}&key=xxxxxxxx-783f-4f90-aea4-7fb357016647`, (err, data, body) => {
      if (err) return reject(err);

      try {
        return resolve(JSON.parse(body));
      } catch (e) {
        return reject(e);
      }
    })
  );

module.exports = router;


I don't have any good feed back on the technical aspects of your api calls, which look fine to me.  Being that this is code review here is my code review.

I would set a variable to your req.query parameter, which will make the code look cleaner.

Your ternaries can be shortened to:

req.query.limit || 25;

An undefined variable throws an Error, an undefined object property is falsy.

Always use === over ==

Parse Int must always have a radix, otherwise we cannot guarantee consistent performance. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)

parseInt(order, 10) //Assuming this is sent in decimal

Always return res.send while you are using in fine in this context, adding the return is a safety measure for the future, all you need is someone to change the logic, not properly test error cases and you have a double callback that sometimes can be hard to debug.

So that results in:

var listSort = ['time','request'];
var defSort = listSort[0];
var listOrder = ['-1','1'];
var defOrder = listOrder[0];

router.get('/', function(req, res){
   var rQuery = req.query || {};
   var limit = rQuery.limit || 25;
   var page = rQuery.page || 1;

   var sort =  listSort.indexOf(rQuery.sort) === -1 ? defSort :  rQuery.sort;
   var order = listOrder.indexOf(rQuery.order) === -1 ? defOrder : rQuery.order;
   var querySort = {};
   querySort.sort = parseInt(order, 10);

   var timeBegin = isNaN(Number(rQuery.timeBegin)) ? undefined : Number(rQuery.timeBegin);
   var timeEnd = isNaN(Number(rQuery.timeEnd))  ? undefined : Number(rQuery.timeEnd);
   var request = rQuery.request;
   var queryFind = {};

   if(timeBegin || timeEnd){
       queryFind.time={};
       if(timeBegin)
           queryFind.time['$gte']=timeBegin;
       if(timeEnd)
           queryFind.time['$lte']=timeEnd;
   }

   if(request){
       queryFind.request =  new RegExp(request, 'i');
   }

   Log.find(queryFind).sort(querySort)
   .limit(limit).skip(limit*(page-1), function(err, logItems) {
       if (!err) {
         return res.json(logItems);
       } else {
         return res.send({error: err});
       }
   })});


The last piece is: Whoever is calling that callback: function itself may be passing params to it, which need to be repackaged into a genuine array from their source in the (implementation deficient) arguments array, before they can be passed to method via apply which is essentially tacking on the method method to this and calling it.


Answers to your questions

Is my use of enable_if_t appropriate and idiomatic?

Yes, it is appropriate, and I believe idiomatic for C++17 as well. In C++20 the idiomatic way would be to use concepts of course.

Is the use of static_cast for one_over_5 and one_over_239 the "best" solution here? Neccesary, and appropriate?

It's necessary to cast at least a few constants to ensure the expression has the right type. However, in this case I would use the constructor syntax instead, and only do it for the minimum number of constants necessary, to keep the expression concise and legible:
return (4 * arctan(T{1} / 5) - arctan(T{1} / 239)) * 4;

Also note that you don't need to specify <T> here, it can be automatically deduced, and since this is so short there is no need to declare temporary variables one_over_5 and one_over_239.

How about the use of decltype, ::epsilon and ::digits10?

The use of T::digits10 is fine here. However, using T::epsilon() is always very dangerous. It works here only because you are trying to calculate something close to 1, or if you wanted to calculate the arctangent from a very small number you have the advantage that \$\lim_{x\to 0} \arctan x = x\$. In general, if you want to calculate a value using some converging expansion and want to stop if further steps are no longer giving you any increase in precision, you can do that by checking if there is any change in the floating point value:
while (res + std::fabs(term) != res) {...}

Or perhaps using std::nextafter(), to keep in the spirit of T::epsilon():
while (res + std::fabs(term) > std::nextafter(res, res + 1)) {...}

Although for std::nextafter(), it might even be hard to come up with the correct second argument.
Again, your method works fine in this case, it produces the same output as both methods above.

Accuracy: How about sign =* -1 and den += 2.0 and ... = sign * ...? These are integer operations but use the floating point type.

Currently those are floating point operations because the left hand side is a floating point type, and if the other side is an integer it would be promoted to the floating point type before the operation is performed. Note that you can replace all the constants in arctan() with integers and the result will still be correct.
You could change the type of sign and den to be an integer type, but it is not necessary. Multiplying floating point sign by -1 will not make it drift away from 1/-1 over time, and since integers up to \$2^{24}\$ can be represented exactly by a float, you will not have any problems with den either, unless the loop would run for more than 8388607 iterations, which would mean you have bigger problems.

My choice to force the user of pi() to specify a T?

It forces the user to give the correct type, which might result in less errors and/or more optimal code. You could consider making it double by default:
template <typename T = double, ...>
T pi() {...}

Note that C++20 introduces std::pi_v<> which also doesn't not have a default type.
Make the functions constexpr
You can and should make the functions constexpr. Interestingly, the compiler would be free to calculate the results of pi_float, pi_double and pi_long_double at compile time regardless, however GCC and Clang don't without constexpr. With constexpr, GCC does calculate the result at compile time, but Clang still emits a lot of code.


Font and color checker chrome extension in JavaScript

Just some random comments from a quick read through:

1) Does this work if someone defines their colors using hex or name style (#fff, #ffffff, white, rgba(255,255,255,1)?

2) Walking the DOM and creating a huge array is probably not a good idea for anything but a small web page. After that you have another 3 separate loops. I would suggest that you create a function that walks the dom and calls a function for each node (function walkDom(start_element, callback) { .... Then you only need to store nodes that fail the test. Also combine ll those loops into one test.

3) Rather than comparing the nodetype with 1 I would use if (element.nodeType === Node.ELEMENT_NODE) ...

4) Rather than a do...while loop and nextSibling it is probably simpler just to get the childNodes and loop through them.

5) Or even better look into the TreeWalker api https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker

6) This loop doesn't make sense:

for (elem in arr) {
  stylesContainer[arr[elem].tagName] = ...;
}

If you have two <div>'s in your tree the second one will over-write the first one.

7) A few things here:

if (brandColor.indexOf(stylesContainer[element]) > -1) {
  //pass
} else if (document.querySelector(element).childNodes.length == 1) {
  document.getElementsByTagName(element)[0].style.border = "2px solid red";
  ...

}

Firstly don't use an if with an empty block, use a negated if :

if (brandColor.indexOf(stylesContainer[element]) < 0 &&    document.querySelector(element).childNodes.length == 1) {

Also why only highlight elements with a single child and not those with two children or no children? Also consider using includes instead of indexOf And again this:

document.getElementsByTagName(element)

will return the first tag of that type in the document. It might not be the one with the issue.

8) Don't mix styles. You use for ... in in some places and forEach in others. If you're using ES6 use let and const instead of var.

9) It is unnecessary to compare to true. if (fontNotMatch == true) { can be written as just if (fontNotMatch) {

10) If you check color you might want to check background-color and the various border-color's too.


Finding all contiguous sublists such that each member appears an even number of times

The algorithm can be slimmed by tracking only those numbers for which the number of occurrences in the current window is unbalanced (i.e. odd). Whenever this auxiliary structure is empty, everything is balanced and the current window can be added to the set of solutions. Here's some pseudo code to illustrate the approach:

static void print_balanced_contiguous_subsequences (int[] a)
{
    var unbalanced = new HashSet<int>();

    for (int i = 0, e = a.Length - 1; i < e; ++i)
    {
        unbalanced.Clear();

        for (int j = i; j <= e; ++j)
        {
            if (unbalanced.Contains(a[j]))
                unbalanced.Remove(a[j]);
            else
                unbalanced.Add(a[j]);

            if (unbalanced.Count == 0) // print the newly found sequence
                for (int k = i; k <= j; ++k)
                    Console.Write("{0}{1}", a[k], k < j ? ' ' : '\n');
        }
    }
}

However, this algorithm is still quadratic in n (20 ms for 1000 elements, 2 seconds for 10000) and the key idea for a proper solution still eludes me...

The original problem description might contain a clue, or some restriction that can be leveraged to design a faster solution. It would be nice if it could be quoted verbatim in the question, or at least linked (even if it is not in English).


Building array keys using a span of numbers for like values

I like the idea of putting the discount steps into an array, but stating a discount for every possible quantity seems too much.

$leg_directory_discount = array(
    0 => 0,
    6   =>  .50,
    11  =>  1,
    21  =>  1.5,
);

This is the discount configuration - can later be stored in a config file or database.

This function gets the discount to be used:

function getDiscount($qty, $leg_directory_discount) {
  $return = 0;
  foreach ($leg_directory_discount as $amount => $discount) {
    if ($qty >= $amount) {
      $return = $discount;
    }
  }
  return $discount;
}


querySelector can return null. So while you are checking button, you aren't checking for iframe. You will possibly get Assigning property src to undefined or something like that.

classList is one of the newer properties. If you see your code being used in older browsers, you should watch out. Check the compatibility table for support.

A practice used by jQuery and other libraries is to use sets. It's where you put results in an array and for each item, operate on it. If no items are on the set, no code executes.

// Use querySelectorAll to get elements. querySelectorAll returns a
// NodeList. To use array methods, we convert it to an array with
// slice.
const buttons = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--thumbnail'));
const iframes = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--iframe'));

// forEach runs the callback for each item in the array. If no items
// reside, no loop runs, therefore no code executes.
button.forEach(function(button){
  button.addEventListener('click', function(){
    button.classList.add('video-poster--hidden')
    iframe.forEach(function(iframe){
      iframe.getAttribute('data-src');
    });
  }, false)
});


If this is the first thing that loads on every page, then the chance of any of these constants being already defined is very small. Why then define them conditionally? These are constants, they should always have the same value. Therefore you can change:
defined("CONSTANT2") or define("CONSTANT2", CONSTANT1 . "/constant2");

to:
define("CONSTANT2", CONSTANT1 . "/constant2");

One of the reasons to define constants conditionally is that you don't want to overwrite constants that are part of PHP. In my opinion there is a better way to prevent this: Choosing longer constant names. So instead of calling a constant HEAD, you could call it TEMPLATE_HEAD. That way the chance of a naming collision is reduced.
Since PHP 5.3 from 2009 is has been possible to define global constants this way:
const CONSTANT2 = CONSTANT1 . "/constant2";

I know it is purely subjective, but I prefer this syntax. Later, when you start using OOP this will be the only syntax for class constants.
Given the above your code could look like this:
// 04.
const FOLDER_MODULES            = FOLDER_RESOURCES . '/modules';
const MODULE_FUNCTIONS          = FOLDER_MODULES . '/functions.php';
const FOLDER_AUTH               = FOLDER_MODULES . '/authentication';
const AUTH_CONTROL              = FOLDER_AUTH . '/auth-control.php';
const AUTH_SIGN_UP              = FOLDER_AUTH . '/sign-up.php';
const AUTH_SIGN_IN              = FOLDER_AUTH . '/sign-in.php';
const FOLDER_FORMS              = FOLDER_MODULES . '/forms';
const FORM_CONTROL              = FOLDER_FORMS . '/form-control.php';
const FORM_ERRORS               = FOLDER_FORMS . '/form-errors.php';
const FORM_VALIDATION_FUNCTIONS = FOLDER_FORMS . '/form-validation-functions.php';
const IMAGE_UPLOAD              = FOLDER_MODULES . '/upload-image.php';

// 05.
// Templates Folder
const FOLDER_TEMPLATES          = FOLDER_RESOURCES . '/templates';
// Main Templates
const FOLDER_MAIN_TEMPLATES     = FOLDER_TEMPLATES . '/main-templates';
const TEMPLATE_HEAD             = FOLDER_MAIN_TEMPLATES . '/head.php';
const TEMPLATE_HEADER           = FOLDER_MAIN_TEMPLATES . '/header.php';
const TEMPLATE_BANNER           = FOLDER_MAIN_TEMPLATES . '/banner.php';
const TEMPLATE_FOOTER           = FOLDER_MAIN_TEMPLATES . '/footer.php';
const TEMPLATE_JAVASCRIPT       = FOLDER_MAIN_TEMPLATES . '/js-files.php';
// Content Templates
const FOLDER_CONTENT_TEMPLATES  = FOLDER_TEMPLATES . '/content-templates/';
// Form Templates
const TEMPLATE_FORM             = FOLDER_TEMPLATES . '/form-tmp';

Somehow I find this much easier on the eyes.


Why fail at all? Isn't success better than failure? A shorter version is thus:

main :- writeln('Hello world!').

Also, why even have side effects? Isn't a declarative solution much better:

message('Hello World').

This way, you can also reason about the message within the program itself. This is not possible if it only appears as output on the terminal. You can ask on the toplevel whether there is any message:

?- message(M).
M = 'Hello World'.

File endings and shebang-lines are technicalities that are pretty unrelated to the program itself. A Prolog program that is intended as a shell script will often have an initialization/1 directive somewhere in the file, like:

:- initialization(run).

This is a standardised feature, whereas placing arbitrary queries in the file is not.


CurrentItem = ItemList[ItemList.IndexOf(mi)];

can just be

CurrentItem = mi;

You could also use FirstOrDefault:

var item = ItemList.FirstOrDefault(i => i.Menu == Back[0].Menu);
if (item != null)
{
    CurrentItem = item;
}


Read numbers between 1 and 5, then print the minimum and maximum

If you make the Scanner object outside of the prompt method and use that object in the prompt method when you want to get an input then you won't be creating a new instance of Scanner every time you call the prompt method.