private void ProcessTransactionAsync(Socket socket)

You've mixed the naming conventions a little bit. We add the Async suffix to methods that are awaitable. This one isn't. You could however easily fix it.

private void ProcessTransaction(Socket socket)
{
    Task.Factory.StartNew(() => ProcessTransactionAsync(socket));
}

Rename it and mark it propertly with async. Let its return value be Task. In place of the Task.Factory.StartNew you can use the shortcut Task.Run(someAction):

private async Task ProcessTransactionAsync(Socket socket)
{
    await Task.Run(() => ProcessTransaction(socket));
}

now you can await it in StartListen:

while (!_shutdown)
{
    var socket = await AcceptClient();
    await ProcessTransaction(socket);
}

finally as Ron Beyer wrote you should change the return value of the StartListen method to Task.


Iterating through 128-byte records in a file

There is no particular advantage to using a direct buffer here. You have to get the data across the JNI boundary into Java-land, so you may as well use a normal ByteBuffer. Direct buffers are for copying data when you don't want to look at it yourself really.
Use a ByteBuffer that is a multiple of 512, e.g. 8192, so you aren't driving the I/O system and disk controller mad with reads across sector boundaries. In this case I would think about using 128*512 to agree with your record length.
The .substring(0, numberOfBytes) is unnecessary. After the read and rewind, the ByteBuffer's position is zero and its limit equals numberOfBytes, so the charset.decode() operation is already delivering the correct amount of data.
You're assuming you didn't get a short read from FileChannel.read(). You can't assume that, there is nothing in the Javadoc to support that assumption. You need to read until the buffer is full or you get EOF.

Having said all that, I would also experiment with a BufferedReader around an InputStreamReader around the FileInputStream, and just read 128 chars at a time. You might get a surprise as to which is faster.


There's a few things to comment on:

I'm not a Gmod developer, so I'm not familiar with the spectating abilities built in, but, I'd assume that if any exist, they're probably better to use than re-inventing the wheel.

There's only two states: not spectating, and spectating. What happens if I want to simply switch between players? Do I have to stop spectating, and then select a new player to spectate?

Why can I not just press lmb and go to the next?

util.AddNetworkString( "spectatePlayer" )

You've got extraneous whitespace in your brackets.

print(client:Nick() .. "Started spectating: " .. net.ReadEntity():Nick())
print(playerLocal:Nick().."Finished Spectating")

String concatenation joins the strings, as they are. Meaning, it would read like:

  QuillStarted spectating: James Heald.
  QuillFinished Spectating

Add some whitespace in there.

print(client:Nick() .. " Started spectating: " .. net.ReadEntity():Nick())
print(playerLocal:Nick().." Finished Spectating")

Oh, and you should be keeping the cases (upper and lower) consistent in your messages:

"Started spectating: "
         ^
"Finished Spectating"
          ^


In the end there was no need to retry manually httpclient has a retry handler.

    HttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(6, true);

    httpClient.setHttpRequestRetryHandler(retryhandler);


Most efficient dict filter on key tuple?

filter

Is useless here. It's purpose is to filter out values based on a predicate:

list(filter(f, data))

is the same as:

[d for d in data if f(d)]

Given that, in your case, f is lambda p: (p[0], p[1]), it will always evaluate to True in a boolean context. Thus never filtering anything. I’m not sure what it was you were trying to achieve, but you can remove filter without changing the behaviour:

def get_block_provider(self, provider_lookup):
    for provider_key in  self.__block_providers:
        if provider_lookup in provider_key:
            print("we've found the key: {key}".format(key=provider_key))
            return self.__block_providers[provider_key]

    return None

get_block_provider

I believe this method is to be used in the same kind of way than __getitem__ on dicts. Thus you need to act accordingly; it's the principle of least attonishment: you claim to be somewhat a dict then you get to act like a dict.

First of, remove that print. There is nothing justifying that line in a getter. If the user want to be sure it got something, it's its job to print something. It's not your classe's job.

Second, it might be better to raise a KeyError as a dict would have instead of returning None:

def get_block_provider(self, provider_lookup):
    for provider_key in  self.__block_providers:
        if provider_lookup in provider_key:
            return self.__block_providers[provider_key]

    raise KeyError("No block corresponding to lookup '{}'".format(provider_lookup))

Be a dict

You said that

  It seemed that making multiple dictionaries or multiple entries in a single dictionary pointing to the same value object (ref type) was more maintenance than I wanted to commit to.

But I disagree. Especially since looking at the code and your comments, you’re only expecting 2 different kind of lookups for your blocks: ID and name.

You do not have to entirely expose a dict interface. But you should use its strength. Your for loop in get_block_provider is a complete waste of time: you’re performing an \$O(n)\$ lookup where a dict would have provided an \$O(1)\$ one.

Instead, your lookup should rely on the underlying dictionary one. And you should focus on having only one entry point to update both keys at once:

def register_block_provider(self, provider):
    block = provider()
    blocks = self.__block_providers
    # update both keys at once
    blocks[block.block_id] = blocks[block.name] = block

def get_block_provider(self, provider_lookup):
    return self.__block_providers[provider_lookup]

You can even define

__getitem__ = get_block_provider

to mimic a dict interface.


Simplifying similar functions using a hover state with different div content

The recommended way is to use event delegation:

$('.test, .testx, .testxy, .testxyz')
  .on('mouseover', 'img', function (e) {
    TweenLite.to($(e.delegateTarget).find('span'), 1.5, {opacity:1});
  }).on('mouseout', 'img', function (e) {
    TweenLite.to($(e.delegateTarget).find('span'), 1.5, {opacity:0});
  });

This will add the mouseover and mouseout events to all img tags within your parent elements. When the event is fired e.delegateTarget will be the parent element, so we can easily search for the span.


Adding two values in a map, if they exist

OK, so I taught myself a little scala and here is something a bit more functional than your example:

val _map = Map(1 -> 2, 2 -> 8, 4 -> 13 )

def pickSum(x:Int, y:Int): Either[String,Int] = {

  /* If the map contains the key k, return Right(value)
   * else return Left(key)
   */
  def pick(k:Int): Either[Int,Int] = {
    _map.get(k) match {
      case Some(v) => Right(v)
      case _ => Left(k)
    }
  }

  List(x, y) map { pick } match {
    case List(Right(a), Right(b)) => Right(a + b) // Two matching values: return the sum
    case l:List[Either[Int,Int]] => pick(x + y) match { // At least one failure: try  x+y
      case Right(i) => Right(i)  // x+y is in the map.  Return the value
      // Otherwise, return the list of keys not found in the map
      case e:Left[_,_] => Left( e :: l collect { case Left(i) => i } mkString("Not found in map: ", ",", "") )
    }
  }
}

Testing this in the Scala repl...

scala>  pickSum(1,2)
res0: Either[String,Int] = Right(10)

scala> pickSum(2,4)
res1: Either[String,Int] = Right(21)

scala> pickSum(2,3)
res2: Either[String,Int] = Left(Not found in map: 5,3)

scala> pickSum(1,3)
res3: Either[String,Int] = Right(13)

scala> pickSum(3,7)
res4: Either[String,Int] = Left(Not found in map: 10,3,7)

This does more or less what your code does; it either returns a Right() with the desired Integer value or a Left() containing a string explaining which keys could not be found in the map.  Personally, in the case of failure I had rather just return a Left containing a list of the failed keys, to be handled as some other part of the code saw fit.

The core function, here, is to look for a key in the map and either return the matching value wrapped in a Right() or, if there is no such key, the rejected key wrapped in a Left().  I went straight for Map.get rather than checking with .contains() because the former returns an Option, which allows more concise and expressive code.

You should notice that nowhere in the code do I re-assign a value (hell, I don't even create any vals, let alone vars).  Instead, I return a series of immutable collections, each one derived from the previous one.  This is one aspect of functional programming.

So...

List(x, y) map { pick }

This makes a list out of the given keys and then creates from that a list of the corresponding values or the rejected keys.  I then do some pattern matching

case List(Right(a), Right(b)) => Right(a + b)

If this matches, we have successfully retrieved two values.  Return the sum.  And we're done here.  Otherwise...

case l:List[Either[Int,Int]] => pick(x + y)

So this matches a list but doesn't care what it contains, because we know there was at least one failure or the previous match would have succeeded.  Matching all the permutations of failure in one line is less fragile than listing them all, if there's only one action to take.  So now we look for _map(x + y) and match the result...

case Right(i) => Right(i)

If this matches, _map(x + y) exists so we return it and that's it.  Otherwise...

case e:Left[_,_] =>

OK, (x + y) is not a valid key.  So what the rest of that line does is

Adds Left(x + y) to the head of the list: e :: l
Collects all the invalid keys from the list: collect { case Left(i) => i }
Builds a string containing the invalid keys: mkString
Wraps the resulting string in a Left()

I'm sure this could be done better, since I only learned enough Scala to do this in the last 24 hours.  However, it is (like Yuushi's answer) more idiomatic while also using some functional programming techniques (however modestly).

To genuinely improve my example code, it would help to know why you're doing this slightly odd thing.

To summarise the differences between your example and mine:

All the else if statements make yours very fragile.
Each individual else if statement is almost the same (i.e. using _map.contains()), giving room for error with all that duplication.
You could easily miss a permutation.
You might (in fact you do) have code paths that can never be evaluated.
I avoid duplication almost entirely.
Pattern matching makes it almost certain I catch all the permutations.


Pythonic way to add each previous element in list

In Python 3 itertools gained a new function accumulate that does what you want.
I'd recommend that you instead used this function. Or if you can't if you're in Python 2 to upgrade.
This would single handedly change your code to:

from itertools import accumulate

new_l = accumulate(l)

If you however done this as a learning exercise, then I'd instead use iterators.
I'd first change l to an iterator, via iter.
Which would allow you to use next to remove the default value.
After this I would then loop through the iterator and yield rather than new_list.append the new values.
This can allow you to get something like:

def accumulate_sum(l):
    l = iter(l)
    try:
        total = next(l)
    except StopIteration:
        return
    yield total
    for item in l:
        total += item
        yield total

Which funnily enough is almost exactly the same to how it's done in itertools.accumulate.
If you wanted to at a later date use a different function rather than addition, then you could pass that as a function, to call on each iteration.


Your querying practices look secure to me.  Your are using a prepared statement with bound parameters and using password_hash() and password_verify().  It really can be as simple as doing those basic/essential things.
As for other refinements, I recommend writing the failure branches before successful ones, doing early exit()s, and only passing back an empty or populated reason to reduce the data structure to its vital value.

I will assume/hope that the username is a UNIQUE table column, so LIMIT 1 provides no value.
If you want the result set / row to be an object, just tell pdo that that is what you want -- fetch(PDO::FETCH_OBJ).
The result set will either be an object or false, so just check for a falsey result set.  For this reason, you can remove id from the SELECT.
I don't like to give too much specificity when giving failed login responses.  I would tell the user that the credentials generally failed without spelling out which field was the problem.

Recommendation:
public function login(Request $request)
{
    $this->middleware('json_response', $request);
    $this->middleware('xauth_protected', $request);

    if(!$request->has('username') || !$request->has('password')) {
        exit(json_encode(['reason' => 'Please fill in the required fields']);
    }

    $stmt = Database::getInstance()->Prepare(
        "SELECT hash, session FROM _users WHERE username = ?"
    );
    $stmt->execute([$request->username]);
    $rowObject = $stmt->fetch(PDO::FETCH_OBJ);

    if (!$rowObject || !password_verify($request->password, $rowObject->hash)) {
        exit(json_encode(['reason' => 'Invalid credentials']));
    }

    $request->setSession('oauth', $rowObject->session);
    exit(json_encode(['reason' => null]));
}

Then in your js, you can use this:
.then(data => {
    if (data.reason) {
        document.getElementById('login-error').innerHTML = data.reason;
    } else {
        window.location.href = App.__viewFactory.dashboard.view;
    }
})


Sometimes pattern matching over Option could be replaced with fold or map/getOrElse

o.startRank.fold("")(x => s"rank[0]=$x&")

o.startRank.map(x => s"rank[0]=$x&").getOrElse("")

You could notice that url parameters have a pattern key=value joined with &. To leverage this pattern url builder could be split into separate steps:

create a map Map[String,String] of parameters i.e.

Map(
  "rank[0]" -> o.startRank.fold("")(_.toString),
  ...
  "time[0]" -> o.startTime.map(time => time.getTime/1000).map(_.toString).getOrElse("")

join parameters into string

map.filter(_._2.nonEmpty).map {
  case (key, value) => s"$key=$value"
}.mkString("&")


•Is this a bad idea?

It is unnecessary.

  Nobody knows what most of the C++ programmers do but so far I only ever had one use for const_cast: to cast away a const from a type.

You can also use it to partially take away constness:

int do_things(const char* p);

const char* const xyz = "abc";
do_things( const_cast<const char*>(xyz) );

The gain in readability comes from the result type being explicitly specified.

If you have APIs that only work for non-const pointers when they should work for const (this is the most legitimate use for const_cast) you should wrap them and centralize/localize/hide the call to const_cast.

If you find yourself writing const_cast calls again and again, the problem is not poor readability of the code, but bad API design.


C++ wrapper around uniform mt19937 SequenceContainer

gen and dist don't need to be pointers.  Just declare them as members, and use the member initializer list in the constructor to initialize them.

std::random_device rd;
std::mt19937 gen;
std::uniform_int_distribution<T> dist;

EasyRandom(T a, T b): gen(rd()), dist(a, b) {
}

In the operator() that returns a vector, you can reserve space for the vector to avoid memory reallocations during the insertions (v.reserve(n)).  While not an issue with ints, if you use emplace_back rather than push_back that can avoid potential extra copies of a value for non-simple types.

The second question is off topic (code not implemented).


If performance of this code is critical, then it could make sense to avoid heap allocations for Candles. I think the most reasonable way to do that would be make Candle into a struct.

Though mutable value types are evil, so I would also refactor Candle to be immutable. This also means the implementation of _newestCandle would have to change, probably into a pair of double fields (or, alternatively, a separate mutable and resettable class).

I don't see any other potential performance issue in your code. But when it comes to performance, you should always rely on profiling, not your (or someone else's) intuition.

Also, I don't like some names of your methods. Specifically:

ValueUpdated. Method names should usually be in the form “do something”, not “something happened”. So I think a better name would be UpdateValue.
Add, Modify. These are the two fundamental operations of your MovingAverage and I think that those names don't express the meaning well. I would call them something like MoveAndSetCurrent and SetCurrent, respectively. Though such naming indicates that the fundamental operations should rather be Move and SetCurrent.


Converting  tags to horizontal responsive barcharts

I'd recommend you to get rid of class selector here

// Gather
var $targets = $(this).find('.bar-group-item');

because you need you're HTML structure to use specific classes. You'd better find them by finding elements with data attributes inside plugin's target element.

Scalability!


Uses too much memory, and too much time

Your current solution works but uses too much memory.  The problem requirement specifies maximum 16 MB memory to be used.  Your program uses 4 bytes for each number reached including duplicates.  Given the maximum n of 1000000000, maximum caterpillars of 20, and worst case of each caterpillar having value 2, your program would require 40 GB of memory to solve that case.

Also, your program takes too long to run.  Given the worst case scenario mentioned above, your program would need to iterate 10 billion times.  Even at a rate of 1 billion iterations per second, that would take 10 seconds and your time limit is 3.

I will describe some incremental improvements to your solution to fix the memory issue, and then describe a completely different approach that solves the time issue as well.

Slightly better: use sieve approach

Instead of adding reached numbers to a vector and then sorting, you can do better by creating a std::bitset or vector<bool> to store which numbers were reached.  For example, you could create a vector<bool> of size n+1, and then as you reach each number, you set reached[num] = true.  At the end, you scan the vector to count many numbers are unreached.  Assuming that vector<bool> uses 1 bit per element, this solution requires 125 MB of memory, which is still larger than permitted.  However, this at least won't crash your computer if you run it.  Here is a sample solution:

#include <iostream>
#include <vector>
#include <algorithm>

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    std::vector<bool> reached(n);
    for(int i=0;i<k;i++){
        int val = caterpillars[i];
        for(int j=0;j < n;j+= val) {
            reached[j] = true;
        }
    }
    int unreached = 0;
    for(int j=0;j < n;j++) {
        if (!reached[j])
            unreached++;
    }
    std::cout << unreached << std::endl;
    return 0;
}

This program solved the "tough case" 762744433 19 ... in 0.9 seconds on my computer.  However, on the worst case of 1000000000 20 2 2 2 2 ..., it took 16 seconds to solve, which exceeds the time limit of 3 seconds.

Next improvement: use fixed amount of memory

To keep your program within the 16 MB memory limit, you need to do the sieving in segments instead of all at once.  For example, you can compute the solution in segments of 1000000, using only 125 KB of memory for the vector<bool>.  Here is an example of how you can do that:

#include <iostream>
#include <vector>
#include <algorithm>

#define BUFSIZE        1000000

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    std::vector<bool> reached(BUFSIZE);
    int unreached = 0;
    for(int i=0;i<n;) {
        int size = n-i;
        if (size > BUFSIZE)
            size = BUFSIZE;
        std::fill(reached.begin(), reached.end(), false);
        for (int j=0;j<k;j++) {
            int val = caterpillars[j];
            int first = (i % val);
            if (first != 0)
                first = val - first;
            for (int r = first; r < size; r += val)
                reached[r] = true;
        }
        for (int r = 0; r < size; r++) {
            if (!reached[r])
                unreached++;
        }
        i += size;
    }
    std::cout << unreached << std::endl;
    return 0;
}

Similar to the previous program, this program also solved the "tough case" in 0.9 seconds.  It took 14 seconds to solve the worst case, though.  Although there are some optimizations that could be made, it seems that a new algorithm might be needed.

A different approach

This problem is somewhat reminiscent of the FizzBuzz problem.  In FizzBuzz, each number divisible by 3 is Fizz, each number divisible by 5 is Buzz, and each number divisible by both 3 and 5 is FizzBuzz.  If I asked how many numbers between 1 and n are one of Fizz/Buzz/FizzBuzz, you could come up with a \$O(1)\$ solution instead of an \$O(n)\$ solution.

If you think about it a little, n/3 numbers are either Fizz or FizzBuzz, and n/5 numbers are either Buzz or FizzBuzz, and n/15 numbers are FizzBuzz.  So the count of "named" numbers is n/3 + n/5 - n/15.

You can transfer this approach to the caterpillar problem.  Given 2 caterpillars of length a b, the number of leaves eaten is n/a + n/b - n/lcm(a,b), where lcm() is the least common multiple of a and b.

Now you can extend the approach for 3 caterpillars.  With three caterpillars of length a b c, you can have leaves eaten by a, b, c, ab, bc, ac, or abc, where ab means eaten by both a and b.  After doing some reasoning on this, you would come up with the formula:

Leaves eaten = n/a + n/b + n/c - n/lcm(a,b) - n/lcm(b,c) - n/lcm(a,c) + n/lcm(a,b,c)

The formula generalizes to:

Leaves eaten = Sum(n/one) - Sum(n/two) + Sum(n/three) - Sum(n/four) + Sum(n/five) - ...

where Sum(n/five) means the sum of all combinations of the form n/lcm(five caterpillars).

To solve using this method, you need to generate each combination of caterpillars.  With 20 caterpillars, this means you need to go through each of the \$2^{20}\$ combinations, which is actually only 1 million combinations so it should complete quickly.  In general, with \$k\$ caterpillars, this solution solves the problem in \$O(2^k)\$ time.  So you definitely do not want to use this solution with a large number of caterpillars.

I wrote a sample solution that used recursion to generate each combination.  The solve() function tries two cases: including the current caterpillar or not including it, and recurses to the next caterpillar for each case.  You can easily see that this generates 2^k cases.

Here is my solution using this approach:

#include <iostream>
#include <vector>
#include <algorithm>

// Returns greatest common divisor of a and b.
static inline int gcd(int a, int b)
{
    while (b != 0) {
        int tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}

// Returns least common multiple of a and b.
static inline long long lcm(int a, int b)
{
    a /= gcd(a, b);
    return (long long) a * b;
}

static int solve(std::vector<int> caterpillars, int curCaterpillar,
        int numUsed, int curLcm, int n)
{
    if (curCaterpillar >= caterpillars.size())
        return 0;

    int val = caterpillars[curCaterpillar];
    int reached = 0;

    // Include current caterpillar:
    long long newLcm = lcm(curLcm, val);
    if (newLcm <= n) {
        if (numUsed & 1)
            reached -= n / newLcm;
        else
            reached += n / newLcm;
        reached += solve(caterpillars, curCaterpillar+1, numUsed+1, newLcm, n);
    }

    // Do not include current caterpillar:
    reached += solve(caterpillars, curCaterpillar+1, numUsed, curLcm, n);

    return reached;
}

int main (int argc, char const* argv[])
{
    long long n , k;
    std::cin >> n >> k;
    std::vector<int> caterpillars;
    std::vector<long long>v;
    int reached = 0;

    for(int i=0;i<k;i++){
        int a;
        std::cin >> a;
        caterpillars.push_back(a);
    }
    n--;
    reached = solve(caterpillars, 0, 0, 1, n);
    std::cout << n - reached << std::endl;
    return 0;
}

This solution solved the "tough case" in 0.01 seconds on my computer, and solved the "worst case" in 0.46 seconds.

There are further optimizations that could be made, such as filtering out caterpillars that are multiples of each other before starting the algorithm.  Such caterpillars can be removed without changing the result.  Using that optimization, the worst time I got for any input I tried was 0.08 seconds.


There are a few optimizations I can see in your code.

creating a new Color every time is a little severe. You can do a few things here, for example, if your color palette is limited, then cache the individual Color instances. I know it sounds petty right now, but, when you add it up there are a lot of new Color instances created.

What you should at minimum do, is track your last Color used, and only create a new one if it is different.
Pull the Iloader.Imagelist.get(0) outside the loop, and have Image image = Iloader.Imagelist.get(0)
Pull calculations outside the loops where you can... and continue/break when you can too.

Image image = Iloader.Imagelist.get(0);
int screenx=-(int)camerax - blocksize;
for (int x = 0; x < sizex; x++){
    screenx += blocksize;
    if (screenx <= -blocksize) {
        continue;
    }
    if (screenx >= gamewidth) {
        break;
    }
    int screeny= -(int)cameray - blocksize;
    for (int y = 0; y < sizey; y++){
        screeny += blocksize;
        if (screeny <= -blocksize)
            continue;
        }
        if (screeny >= gameheight) {
            break;
        }
        if (tiles[x][y][0] > 0) {
            // need to set the color here? g.setColor(new Color( tiles[x][y][1]));
            g.drawImage(image, screenx, screeny, screenx + blockwidth,
                        screeny + blockwidth, graphicsize, 0, graphicsize * 2,
                        graphicsize, null);
        } else {
                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
            g.setColor(new Color( tiles[x][y][1]));
            g.fillRect(screenx,screeny,blockwidth,blockwidth);

        }
    }
}

The above code does not have the mechanism for caching the color. You should figure one out.


Udacity Intro to HTML and CSS layout sample

Unnecessary prefixes

Don't add prefixes unless you actually need them.  When in doubt, you can check can i use.  Otherwise, there are various autoprefixers you can use that will do it for you.

* {
  -ms-box-sizing: border-box; /* no browser supports this */
  box-sizing: border-box;
}

Subheadings marked up using hn elements

  h1–h6 elements must not be used to markup subheadings, subtitles, alternative titles and taglines unless intended to be the heading for a new section or subsection.

Source: http://www.w3.org/TR/html5/common-idioms.html#sub-head

Jane Doette

Front-end Ninja

The W3C recommends either of these markup options for the subheading idiom:

HTML 5.1 Nightly

A vocabulary and associated APIs for HTML and XHTML

Editor's Draft 9 May 2013

Or

Ramones

   Hey! Ho! Let's Go

Poor contrast

The link color is extremely washed out and is barely legible on one of my displays.  Links, by their very nature, must stand out.  Blue is the recommended color for usability reasons, but if you need to change it, you need a good reason for it (and making it less visible than the surrounding content is not a good reason).

I get that this is probably a requirement for the exercise, but it is something you need to be aware of.  If a designer gives this to you, you need to push back and tell them that this is not acceptable (get support from your UX department if you have one).

Semantic class names

For the most part, you did a really good job of using semantic class names (eg.
), which is why it kills me to see so many unsemantic class names thrown into the mix (eg ,
, .col-1, etc.).

Semantic markup

You've got the right idea with your markup, but there's a lot of room for improvement here.  For instance, your screenshots use a lot more markup than they really need and it isn't very semantic.  You can slim this down by using lists and taking advantage of descendant selectors.

Appify

https://github.com/udacity/Appify/

Sunflower

https://github.com/udacity/Sunflower/

Bokeh

https://github.com/udacity/Bokeh/

Can be rewritten like this:

http://codepen.io/cimmanon/pen/ZGGMNM

Markup

      Appify

      Appify

      Appify

CSS

ul.projects {
  display: table;
  width: 100%;
  box-sizing: border-box;
  font-size: 1.3em;
}

ul.projects li {
  display: table-cell;
  width: 33%;
  text-align: center;
}

ul.projects img {
  display: block;
  margin: 0 auto .5em;
}

ul.projects a:after {
  display: block;
  content: attr(href);
  font-size: .769em;
  margin-top: .5em;
}

Depending on the content, though, it might be better to use background images instead of the image element (search for css image replacement to learn more).

Use Flexbox responsibly

Unless the effect you're trying to achieve is difficult or impossible to do without Flexbox, don't use Flexbox.  In this case, you can do the same thing with the table/table-cell display properties (as illustrated above) and it usually requires less CSS to do so.


Factorize All Numbers Up to a Given Number

Timing
The timer thread is unnecessary and an inaccurate way to measure time.

I do now know about this system_clock, system calls might slow down the process (maybe the context switch even more though)

Querying the time costs a bit of time, even if it does not involve an actual system call - which it really may not, there are lots of clever tricks for example clock_gettime uses vDSO on modern Linux and reads from a shared memory location and QueryPerformanceCounter reads the TSC on typical Windows systems, there is no transition into and out of kernel mode. It's never a lot of time relative to what this program is doing, the overhead of getting the time is only an issue when timing very short spans of time. Even if getting the time costs a milisecond (which would be unacceptable and considered a bug in the implementation), it would still be OK for this program.
Performance
Storing the factors in explicit linked lists is a major performance problem, and unlike usual, using vectors wouldn't be great either. There is an alternative: store only one factor of a number. That still gives a complete factorization for any number, because if a number N has a factor factors[N], then you can divide N by that factor and look up a factor of the new (smaller) number and so on, until 1 is reached.
That way the inner loop of the sieve only does a bunch of stores into a vector, nothing heavy-weight like dynamically allocating nodes of a linked list, and the memory usage does not get out hand.
As a convention, I'll use that the lowest factor of a prime is the prime itself. That is the mathematical definition, and it makes iterating over the implicit factor lists easy.
Other
Defining MAX by macro definition and putting local variable declarations at the top of the function are very C things to do. Even C has moved away from "all locals at the top". As general guidelines, I recommend using const variables instead of defines, and limiting local variables with the smallest possible scope. That does not repeatedly incur a cost for "making a variable" because that's not how that happens, any fixed space a function needs is allocated all at once at function entry. Besides, most local variables spend their entire lifetime in registers.
Avoid #include <unistd.h> if possible/reasonable, it does not exist on all platforms.
Pick a brace style and stick to it. There were "same line"-braces and "next line"-braces. There are various opinions on which should be used, but at least they shouldn't be mixed.
In total, the code might come out like this:
#include <iostream>
#include <vector>
#include <math.h>
#include <chrono>

int main() {
    const int MAX = 200000000;
    std::vector<int> factors;

    std::cout << "Initiallizating" << std::endl;
    auto start_time = std::chrono::steady_clock::now();
    factors.resize(MAX);
    std::cout << "Initiallization took "
        << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time).count()
        << " ms" << std::endl;

    std::cout << "Starting calculation" << std::endl;
    start_time = std::chrono::steady_clock::now();
    int upper_bound = sqrt(MAX) + 1;
    for (int i = 2; i < upper_bound; ++i) {
        if (factors[i] == 0) {
            for (int j = i; j < MAX; j += i) {
                factors[j] = i;
            }
        }
    }
    std::cout << "Calculation took "
        << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time).count()
        << " ms" << std::endl;

    std::cout << "Validating results" << std::endl;
    for (int i = 2; i < 20; ++i) {
        std::cout << i << ": ";
        if (factors[i] == i) {
            std::cout << "Is prime";
        }
        else {
            for (int N = i; N > 1; N /= factors[N]) {
                std::cout << factors[N] << ", ";
            }
        }
        std::cout << std::endl;
    }

    return 0;
}

On my PC the sieving takes about 2.5 seconds now. Ideone is a bit slower but the program is fast enough to run there too.


Interop: Return Parameter Method as Void

I don't think there would be too much of a difference. You have to use a reference anyway, because non-native types are stored as references. On x86 processors, returns are placed in register A, which is limited length. So, your C++ program would be either returning a reference to BigObject or modifying an existing instance of it.

The area where I can see a performance hit is in memory allocation. If you are making that call, using the object, and then discarding it, it would be faster to create on single instance in your C# code and use that rather than allocating memory every time. You'll get diminishing returns for small numbers of calls, though; unless you have a couple thousand in a given program run, you probably won't notice the hit either way.


A common practice is to reserve all capital names for constants. As these variables change during the execution of the program, so they should be lowercased instead: PREVIOUS_GUESSES, TRIES, GUESS.

Inside this else, you have a pointless statement:

else:
    GUESS == THE_NUMBER  # <-- just delete this line... or at least comment it out

Using the .get method of dictionaries, for example in PREVIOUS_GUESSES.get('Min') and PREVIOUS_GUESSES.get('Max') can be useful when you're not sure if the keys (Min, Max in this example) exist,
and if they don't exist you don't want a KeyError raised.
In this script these keys are guaranteed to exist,
so you can safely (and consistently) use PREVIOUS_GUESSES['Min'] and PREVIOUS_GUESSES['Max'] everywhere.


Checking battery voltage with ADC and interrupts - which way is best?

First rule when using microcontrollers is:

Do as little as you can in the interrupt function!

Explanation:
Consider having 10 or 100 interrupts configured. Each interrupt function will take 100 or 200 ms to deal with. (Sounds quite low, but when you have a bigger project with a big controller this might be possible)

Then 4 or 5 interrupts will arise and you have to configure the priorities all with priorities that are (maybe) included in microcontroller hardware.

If you don't have this hardware priorities (I this the small Microchip's don't have these?) you can't handle priorities.

Second thing: I don't know which microcontroller you use, but I think it has a flag that shows if the ADC is finished. Use this for ADCrunning (you don't show where you define it).

So my approach would be:

 volatile bool startADC;   // edit: you can use a struct, if there will be too many flags

void TimerInterrupt(void)
{
    startADC = true;
}

void main (void)
{

    int battery_voltage;
    int old_battery_voltage;

    battery_voltage = 0;
    old_battery_voltage = -1;

    StartTimer();

    while(1){
        if (startADC = true) {
            StartADC();
            startADC = false;
        }

        // use the flag as mentioned above
        if (ADCFinished = true) {
            // you might think of using the scale factor
            battery_voltage = ADC_value * scale_factor;
            ADCFinished = false;
        }

        // use unequal instead of the "== else"-construct
        if (battery_voltage != old_battery_voltage) {
            BatteryStateMachine(battery_voltage);
            old_battery_voltage = battery_voltage; // you need this here?
        }
    }
}


Updating an auto-generated invoice (future) when current plan changes

Your code is very readable. Given the provided snippets of code, I won't focus this review on overall architecture (as I'm not sure what the entire system does). I'd like focus on two areas of this code: comments and method names.

When reading your comments I asked my self the following question (taken directly from Code Complete 2).

Do comments explain the code's intent or summarize what the code does, rather than just repeating the code?

# Returns the new adjusted amount
# Iterate through the invoice's items.
# Update the manual_invoice.

These comments repeat what your code does. Removing them would improve the readability and reduce the length of your code.

Next, the following comment and method invocation:

# Set new_amount by taking the new max_users quantity and multiply it
#   by the previous amount. Then divide it by the previous max_users
#   quantity. Finally, divide by payment frequency per term.
new_amount = @subscription.new_amount(max_users, item)

A 3 line comment before a method call such as this is a great opportunity to rename your method name to be more descriptive and possibly avoid a comment altogether. Here is an idea of a possible name:

adjusted_amount = @subscription.adjust_amount(max_users, item)

What other method names would better describe what this method does? Could you move this method to another Model?

Don't be afraid to use 3 or more words to describe a method if that's what it takes. Better to have a long method name instead of a 3-line comment.

I believe you could improve these two lines:

# Guards changing of plan from blowing up if manual_invoice.nil?
if manual_invoice

By replacing them with one line:

unless manual_invoice.nil?

Finally, inside the method new_amount I believe referencing model attributes with self would the improve the readability of your code by differentiating parameters from model attributes.

case self.term_type
# ...
end


Tabs Vs Spaces

Your code formatting isn't consistent.  Looking at your code, this appears to be because you're using both tabs and spaces for white space.  Which is why you end up with code that looks like this (notice the printf doesn't line up with the exit):

if (s != 0) {
        printf("pthread_barrier_init failied");
    exit(-1);
}

Different people prefer one or the other, but don't mix and match pick one and stick with it.

Termination

It's unclear to me how you're expecting your threads to exit.  Both your consumers and your producers go into while(true) loops, which don't have any break conditions in them.  This is inconsistent with your main, which attempts to join with the consumer and producer threads.

Pointer Assignment

My compiler isn't a huge fan of this line:

buf_write = &act_buf[index]

buf_write is char(*buf_write)[20] and you're trying to assign it to char*[50][20].  I think you should probably be doing this:

buf_write = &act_buf[index][0]

Synchronisation

I think overall, the way you've synchronised between the consumer and producers is fairly tidy, although your variable names could be improved to describe what their function is.  mutex is clearly a mutex, but what's it being used for, how is it different from lock?  For the scenario you've built, having the consumer wait until all of the producers have completed seems to work ok, however in the general case, where producers might take different amounts of time it might make more sense for the consumer to handle information from each producer as it is complete.


Learning C: K&R 1-22: 'fold'. Is this solution very unwieldy?

Instead of reading an entire line, then finding where to break the line, I think I'd read one word, and depending on the length of the line up to that point and the length of the word, decide whether or not to write a new-line before writing that word.

That way, the main loop would come out something like this:

while (getword(buffer, max_len)!=EOF) {
    if (current_length + strlen(buffer) > max_len) {
       print("\n");
       current_length = 0;
    }
    print(buffer);
    current_length += strlen(buffer);
}


You're instantiating a PhotoInput object but never assigning it to a variable. This implies that there's no need for a class at all. You're only instantiating it for its side-effects; you're not interested in the instance itself.

This works, but it's bad form.

Even if you stored the instance somewhere, you still can't really use it for anything. Sure, you could call its methods, like, say, setPreviewRender, but there'd be no point since it's already been called - in fact, it'd probably be a bad idea to call it again.

So don't use a class, just write a function and use closures instead of instance variables:

createPhotoInput = (originalInput) ->
  originalInput = $ originalInput

  # replace original input
  template = ich.image_file_input_template
    fileInput: originalInput.get(0).outerHTML

  originalInput.eq(0).replaceWith template

  # set click handlers
  input = template.find 'input[type=file]:first'
  template.find('#select-file, .file-input-preview').click (event) ->
    input.focus().click()

  # set preview handling
  preview = template.find '.file-input-preview img'
  input.change (event) ->
    preview.attr 'alt', input.val()
    file = input.get(0).files?[0]
    if file?
      reader = new FileReader
      reader.onload = (event) -> previewImage.attr 'src', e.target.result
      result.readAsDataURL file

  # return the template, just in case
  template

$ ->
  $('input[type="file"]').each ->
    createPhotoInput this

You'll note that it also does away with all the scope-handling and fat arrows (=>), since it's just closures.


Listing blog posts, each of which may belong to multiple categories

I am not sure why you are using 2 foreach loops, you should be able to combine them.

foreach ($result as $value) {
    if(empty($resultMap[$value['id']])) {
        unset( $value['name'] );
        $resultMap[ $value['id'] ] = $value;
        $resultMap[$value['id']]['categories'] = array();
    }

    $resultMap[$value['id']]['categories'][] = array(
        'name' => $value['name'],
    );
}


Using Task and actions for simple threading?

You shouldn't usually use Task constructor directly, use Task.Factory.StartNew (or Run).

I also don't understand why you want to have a separate method for starting a task. It is completely superficial. It's just as useless as adding Print method that calls Console.WriteLine instead of using Console.WriteLine directly.

Normally, you just do this:

void SomeUICode ()
{
    Task.Factory.StartNew (() => {
        // This will run on thread pool
        return DoSomeExpensiveWork ();
    }).ContinueWith (result => {
        // This will run on UI thread
        UpdateUI (result);
    }, TaskScheduler.FromCurrentSynchronizationContext ());
}

It's basically  the same thing you wrote, but without abstracting it away doThreadedQuery since there's nothing to abstract away here.

However, if you don't mind using C# 5, you can simplify things with async/await operators:

async void SomeUICode ()
{
    var result = await Task.Factory.Run (() => {
        // This will run on thread pool
        return DoSomeExpensiveWork ();
    });

    // The rest of this method will be scheduled on UI thread:
    UpdateUI (result);
}

Note the await keyword that “splits” the method and schedules the rest of it as a continuation on current synchronization context (exactly the same thing you did manually).

I declared the function as async void but you should only do this for event handlers (which have to be void). In all other cases, declare the function as async Task so the calling code has a chance to wait for it to finish:

async Task SomeUICode ()
{
    // ...
}

On a side note, doThreadedQuery is a rather unfortunate name because

.NET method names should be PascalCase, not camelCase;
There's no “query” being performed, you're just scheduling an operation.


This is a refactoring of the original code. It picks the starting player and then uses a simple toggle ($currentPlayer = ($currentPlayer == 1) ? 2 : 1;) to determine which player goes next for 5 rounds.

$currentPlayer = 1;

if ($player2speed > $player1speed) {

    $currentPlayer = 2;

}

$count = 0;

while ($count < 5) {

    echo $currentPlayer . " turns<br/>";

    $currentPlayer = ($currentPlayer == 1) ? 2 : 1;

    $count ++;
}

Note, the current code fails if both player's speeds are the same.


Remove duplication in Ruby map with conditional entries

This is just a rough thought, so it's untested, but here goes:

A vast majority of the hash is the same every time. So, that vast majority can be stuck into a method. There are two fields that are conditionally added to that hash based on their values ('true' or... not). So, we can create a method which takes a record as an argument and the two 'true'/not options and generates a hash accordingly:

def record_for(record, status: false, requested_by: false)
  record_hash = {
    warning: as_warning(record),
    updated_at: as_time_ago(record.updated_at),
    manager: record.manager.nil? ? "" : record.manager.formal_name,
    first_date: as_date(record.first_date),
    last_date: as_date(record.last_date),
    days: as_number(record.total_days),
    hours: as_number(record.total_hours),
    units: as_number(record.total_units),
    value: as_number(record.total_value),
    comment: as_comment(record.comment),
    actions: as_actions(record)
  }
  record_hash[:status] = as_status(record.status) if status
  record_hash[:user] = record.user.nil? ? "" : record.user.formal_name if requested_by
  record_hash
end

Then, all that remains is to convert the strings to booleans:

def to_bool(str)
  return true if str == 'true'
  false
end

and then iterate over the records:

status = to_bool(show_status)
requested_by = to_bool(show_requested_by)

records.map { |r| record_for(r, status: status, requested_by: requested_by) }

I'd be happy to go more in depth and test the code if you provided a set of test records that I could use or some larger context this code would run in.


Spaceship Operation in for Lexicographic Comparison

[1] By Java convention curly brackets belong in the same line as the preceding statement/expression.

Instead of this:

if
()
{}
else
{}

for
()
{}

do this:

if () {
    ...
} else {
    ...
}

for () {
    ...
}

I suggest you read the Google Java style guide for more tips: https://google.github.io/styleguide/javaguide.html

[2] You don't have to introduce an intermediate variable for holding chars, you can directly assign the result of charAt() method to an int variable: intChar1 = (int) str1.charAt(i);

[3] You don't have to do all those substring operations to make the strings the same length. Rewrite the main for loop to do as many iterations as there are characters in the shorter string. Written more succinctly: min(length(A), length(B) iterations

[4] To lexicographically compare two strings, you have to find the first different character in both strings and handle the remaining edge cases after the main for loop. Some pseudocode:

for i = 0; i < (min(length(A), length(B)); i++
    if A[i] != B[i]
        if A[i] < B[i] return -1
        else return 1

// If you didn't return from the method at this point, there are only three options left
String A is shorter than string B - return -1
String B is shorter than string A - return 1
String A and string B are equal - return 0


Enhancing parser for 8 byte command string (expect problems with type conversions) for Arduino/Radio communication

I don't know exactly why (maybe radio, maybe I caused unexpected behavior because of type conversions here).

Can you keep statistics on how many checksum errors there are?

If there are many that implies that the communications link is noisy
If there are few or none then it's more probably something else (e.g. a software error)

I'm not sure that you're using a good checksum algorithm.; you might like to use a CRC instead.

You're only using 7 of your 8 bytes so you could have a 2-byte CRC (or checksum).

You could compress your data better:

'1 - 9'
'0 - 99' => 10 bits to store 0..999 throttle
'-45° - 45°' => 7 bits to store 90 angle values
'-45° - 45°' => 7 bits to store 90 angle values
'-1 || +1'
'yaw angle in degrees 180°' => 9 bits to store 360 angle values

10+7+7+9 => 37 bits = 5 bytes.

Alternatively 999 * 90 * 90 * 360 = 2913084000 which is less than 232. So you could fit your data into 4 bytes and use a 4-byte CRC.


To determine the result you're after, it is necessary to group by the id and hold a temporary map of the grouping operation.

You can make it a bit simpler, and not have a second Stream pipeline, by using the collectingAndThen built-in collector, which gives the ability to pass a finisher operation to the result of another collector.

Collection<Foo> result =
    matchedFoos.stream()
               .collect(groupingBy(Foo::getId, collectingAndThen(toList(), this::mergeFoos)))
               .values();

This code still collects all the foos having the same id into a list, but the use of collectingAndThen enables us to directly pass that list to mergeFoos and return the wanted Foo. Then, it is possible to retrieve the values by invoking values().

This will return a Collection<Foo> as values() is defined to return that. If you really want a List, you can convert it easily to an ArrayList for example, with:

List<Foo> mergedAndMatchedFoos = new ArrayList<>(result);

Note that the current code stores every foo having the same id in a list. This is a bit inefficient since, for the end result, we're interested in a single Foo where the inputs are all input of the foos in the list. So, instead, we can use the toMap(keyMapper, valueMapper, mergeFunction) collector and directly build the intermediate Map<String, Foo> instead a Map<String, List<Foo>>.

The key mapper returns the id of the foo; the value mapper returns a new Foo from a given one, and the merge function adds all inputs from one foo to the other.

Map<String, Foo> result =
    matchedFoos.stream()
       .collect(Collectors.toMap(
          Foo::getId,
          Foo::new,
          (foo1, foo2) -> { foo1.getInputs().addAll(foo2.getInputs()); return foo1; }
       ));

List<Foo> mergedAndMatchedFoos = new ArrayList<>(result.values());

This assumes that we have a copy-constructor Foo(Foo foo) constructing a Foo from another Foo (which is what the Foo::new method-reference refers to). The mutation of foo1 inside the merge function is safe to do since we're working on the new instance, constructed with the copy constructor.


Sample scraping Project Gutenberg using Beautiful Soup and requests

Easy stuff

There are a lot of stylistic issues (indentation, spacing between operators, etc.) that violate PEP 8, you can use tools like pylint to find what they are.

Moving on

 r_html = r.text

Do you really need this? You don't save any characters (not that it is always about saving characters) and you use r_html once. I would just get rid of the line.

I would also say the same about:

url = "https://www.gutenberg.org/ebooks/"

Just get rid of it. Also, in this instance in particular I would get rid of it, because when I read it, I believe there might be a way to abstract it. "Maybe let the user change the url, somehow?") There isn't a particularly good way to "abstract" this url out in particular.

Furthermore, it is considered good practice to use format instead of the addition of strings so:

"https://www.gutenberg.org/ebooks/" + str(book_no)

Becomes:

"https://www.gutenberg.org/ebooks/%d" % book_no

This on the other hand:

"C:\\Users\\syed\\Documents\\Gutenberg\\Book"

Seems like it can be abstracted, what if the user wants to change the location? Maybe by default use this location, but allow the user to change it. Create a default argument to "C:\\Users\\syed\\Documents\\Gutenberg\\Book" but give the user the option to specify it.

Same with:

for chunk in g.iter_content(10000):

What is 10000? Maybe make a default argument for this with the value of 10000 and the name of (possibly) chunk_size?


Is calling file write in the dispose acceptable?

I think it is good idea to use existing classes, I've already made some of the refacorings along with some design choices. For additional info, please read this book:

Design Patterns

EDIT: I think that explicit command calls (open log, write something and close it) before dispose the log object are much more readable, easy to understand and maintain later, than impementing the dispose pattern in another object (so you will get at least two objects to control lifecycle: custom class, and StreamWriter class - that will break the Einstein rule, - it's just not good to control 2 objects, when you could simply control one). In particular, that is going to be true when the new contracts will be applied later to the code. Disposable pattern is to heavy for such simple task. Additionally, as an advantage of using one object to control, and - consequently, - very simplified logic, it's easier to control log writer object's lifetime. At second, simple class with a good and clead design can be extended easily to supprt for an additional logic and do will not likely contains any of the caveats in the future.

public interface IHTMLLogger
{
    ILogWriter CreateHTMLLogWriter(string filePath);
}

public interface ILogWriter : IDisposable
{
    void OpenLog();
    void WriteLog(string message);
    void CloseLog();
}

public class HtmlLogger : IHTMLLogger
{
    public class HTMLLogWriter : StreamWriter, ILogWriter
    {
        public HTMLLogWriter(string filePath)
            : base(filePath)
        {
        }
        public void WriteLog(string message)
        {
            base.Write(string.Format("
{0}
", message));
        }
        public void OpenLog()
        {
            base.Write("");
        }
        public void CloseLog()
        {
            base.Write("");
        }
    }

    public ILogWriter CreateHTMLLogWriter(string filePath)
    {
        return new HTMLLogWriter(filePath);
    }
}

EDIT: As you see, I can easily integrate new encoding logic to encode any string data:

public interface IHTMLEncoder
{
    string Encode(string message);
}

public interface IHTMLLogger
{
    ILogWriter CreateHTMLLogWriter(string filePath);
}

public interface ILogWriter : IDisposable
{
    void OpenLog();
    void WriteLog(string message);
    void CloseLog();
}

public class HtmlLogger : IHTMLLogger
{
    public class HTMLEncoder : IHTMLEncoder
    {
        public string Encode(string message)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(message.ToCharArray()));
        }
    }
    public class HTMLLogWriter : StreamWriter, ILogWriter
    {
        private IHTMLEncoder _encoder;
        public HTMLLogWriter(string filePath, IHTMLEncoder encoder)
            : base(filePath)
        {
            _encoder = encoder;
        }
        public void WriteLog(string message)
        {
            base.Write(string.Format("
{0}
", _encoder.Encode(message)));
        }
        public void OpenLog()
        {
            base.Write("");
        }
        public void CloseLog()
        {
            base.Write("");
        }
    }
    public ILogWriter CreateHTMLLogWriter(string filePath)
    {
        return new HTMLLogWriter(filePath, new HTMLEncoder());
    }
}

Sample:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.IO;
using System.Diagnostics;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private static IHTMLLogger logger = new HtmlLogger();
        private ILogWriter logWriter;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            logWriter = logger.CreateHTMLLogWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html.log"));
            logWriter.OpenLog();

            this.Location = UserSettings.Default.FormLocation;
            this.Size = UserSettings.Default.FormSize;
            this.textBox1.Text = UserSettings.Default.ProcessPath;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UserSettings.Default.FormLocation = this.Location;
            UserSettings.Default.FormSize = this.Size;
            UserSettings.Default.ProcessPath = this.textBox1.Text;
            UserSettings.Default.Save();

            logWriter.CloseLog();
            logWriter.Dispose();

            MessageBox.Show(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "html.log")));
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            UserSettings.Default.ProcessPath = this.textBox1.Text;
            logWriter.WriteLog(this.textBox1.Text);
        }
    }

    [SettingsSerializeAs(SettingsSerializeAs.Xml)]
    [Serializable]
    public sealed class UserSettings : ApplicationSettingsBase
    {
        private const string FormLocationProperty = "FormLocation";
        private const string FormSizeProperty = "FormSize";
        private const string ProcessPathProperty = "ProcessPath";

        private UserSettings() { }

        private static UserSettings _defaultInstance = new UserSettings();

        public static UserSettings Default { get { return _defaultInstance; } }

        [UserScopedSetting()]
        [DefaultSettingValue("0, 0")]
        public Point FormLocation
        {
            get { return (Point)(this[FormLocationProperty]); }
            set { this[FormLocationProperty] = value; }
        }

        [UserScopedSetting()]
        [DefaultSettingValue("300, 300")]
        public Size FormSize
        {
            get { return (Size)this[FormSizeProperty]; }
            set { this[FormSizeProperty] = value; }
        }

        [UserScopedSetting]
        [DefaultSettingValue("")]
        public string ProcessPath
        {
            get { return (string)this[ProcessPathProperty]; }
            set { this[ProcessPathProperty] = value; }
        }
    }
}


I don't see any reason to limit this to Integers.  The solution can be trivially genericized.

IteratorOfIterator is a clumsy name.  By analogy with Python's itertools.chain(), I suggest calling this class ChainIterator<T>.  You can rename the iteratorOfIterator private variable accordingly, too.

I suggest adding an alternate constructor that takes an Iterable<Iterator<T>>, for convenience.

The hasNext() method seems fine.  As for next(), the message in the NoSuchElementException that you throw seems a bit weird; I would just omit it.

With not much extra effort, you can add support for remove().

public class ChainIterator<T> implements Iterator<T> {

    private final Iterator<Iterator<T>> chain;
    private Iterator<T> currentIterator;
    private Iterator<T> lastIterator;

    public ChainIterator(Iterable<Iterator<T>> iterable)  {
        this(iterable.iterator());
    }

    public ChainIterator(Iterator<Iterator<T>> iterator)  {
        this.chain = iterator;
    }

    @Override
    public boolean hasNext() {
        while (currentIterator == null || !currentIterator.hasNext()) {
            if (!chain.hasNext()) return false;
            currentIterator = chain.next();
        }
        return true;
    }

    @Override
    public T next() {
        if (!this.hasNext()) {
            this.lastIterator = null;         // to disallow remove()
            throw new NoSuchElementException();
        }
        this.lastIterator = currentIterator;  // to support remove()
        return currentIterator.next();
    }

    @Override
    public void remove() {
        if (this.lastIterator == null) {
            throw new IllegalStateException();
        }
        this.lastIterator.remove();
    }
}


Caching all the prepared statements in thread safe way

public BoundStatement getStatement(String cql) {
    Session session = TestUtils.getInstance().getSession();
    PreparedStatement ps = holder.computeIfAbsent(cql, s -> session.prepare(s));
    return ps.bind();
}

According to computeIfAbsent's Javadoc:

  The entire method invocation is performed atomically, so the function is applied at most once per key.

I also suggest that you declare holder of type ConcurrentHashMap instead of Map so that it becomes unambiguous for anyone reading getStatement that the synchronisation in computeIfAbsent is guaranteed.


Structuring objects for proper MVVM in Knockout

This looks good me, just as it looked good for the SO reviewers.

Some thoughts;

Consider 'use strict';
Consider naming your anonymous functions
It is not clear how SearchResultModel deals with failed calls
var self = this; is only needed for closures, you don't need it in ns.Models.SearchResultModel

All in all, pretty solid.


If you have two simultaneous file uploads db.Pictures.Count(); will return same number. So you will get a name clash.

If db.Pictures is a database then you can create and auto increment identity field and use it to save the file.

If there is no option with database you can use two more approaches:
Use GUID instead of picture name

[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
    if (fileData != null && fileData.ContentLength > 0)
    {
        string extension = Path.GetExtension(fileData.FileName);

        string renamedImage = null;
        do
        {
            renamedImage = Server.MapPath("~/Content/Images/Categories/cat" + System.Guid.NewGuid().ToString("N") + extension);

        } while( /*verify that renamedImage file does not exist*/ );

        fileData.SaveAs(renamedImage);
        return Json(Path.GetFileName(renamedImage));
    }
    return Json(false);
}

The drawback of this approach is that it is possible to upload same pictures to the server.

To mitigate that you can try using hash of the image as a file name. Before writing file contents to the disk check if that file already exists. Note: the check and file save operation must be made in thread-safe manner.


Deep copy linked list with arbitrary nodes

Var

Use the var keyword when defining local variables where the right hand side of the definition makes the type obvious. This looks cleaner and saves time when it comes to changing types during refactoring.

e.g.

LinkedListArbitraryPointer list = new LinkedListArbitraryPointer();

should be

var list = new LinkedListArbitraryPointer();

You actually do use var at points, but not consistently.

Naming

Avoid using shortened names for your variables, at a glance res is not entirely clear what it refers to, prefer actual or deepCopiedList instead. The same goes for ArbNode.

Definitely don't name your test methods TestMethodX! Find a naming style you like that's concise, detailed and consistent and stick with it.

Comments

Your comments seem to describe what you're doing (which is the job of your code) and not why you are doing it. I often find if there is some chunk of code that needs a comment explaining what it does, it can often be refactored to its own method, or made clearer somehow.

Design

The property 'Root' seems entirely out of place and unused by your code, remove it.

Additionally, I would consider making ArbNode implement IEnumerable so you can replace all your:

        ArbNode temp = root;
        while (temp != null)
        {
            ...
            temp = temp.Next;
        }

with a cleaner:

foreach(var node in root)
{
    ...
}


3 versions of SQL query to find students with simultaneous classes

They are all messy.   And please don't use old style joins.

Two is the least messy as it goes at it more directly.

But you can do it with joins

select st.sname, cl.meets_at
from Student st
join Enrolled en
  on en.snum = st.snum
join Class cl
  on cl.cname = en.cname
group by st.sname, cl.meets_at
having count(*) > 1

That will return more than one row per sname if they have more than one class that has overlapping times.  But that is the most direct approach to the logic (in my opinion).

This would be a clean way to go at single sname

select st.sname
from Student st
where exists ( select 1
               from Enrolled en
               join Class cl
                 on cl.cname = en.cname
               where en.snun = st.snum
               group by cl.meets_at
               having count(*) > 1
             )

another - this might be the best efficiency

select st.sname
from Student st
join  ( select cl.snum
        from Enrolled en
        join Class cl
          on cl.cname = en.cname
        group by cl.snum
        having count(*) > 1
      ) cl2
 on st.snum = cl.snum


Clustering markers on Google map on zoom

Naming and Comments

The postfix underscore is quite strange to me, and I don't understand it at all.  It matches no convention I've ever seen or heard of, and it's just not obvious to me what's gained by sticking out there.  What's it for?

In your 93 lines of code, the only comments to be found are on the first 3 lines:
float lastZoomLevel_; // last zoom value on last zoom
BOOL forceRecalculateMap; // when new data arrives I use this to force repositioning
NSArray *pointsArrayV_; // Array of BankPoint instances, object that holds location and description of marker

And these comments are almost completely unnecessary.  And if they are to be considered necessary, then we easily make them unnecessary by improving the naming of the variables.
CGFloat _lastZoomLevel;

Needs no comment.
BOOL forceRecalculateMap;

Probably needs no comment.  Worst case scenario, we might leave a comment on any line that sets this variable.  Though the implications of this being set to YES should be pretty clear based on the variable name.
NSArray *pointsArrayV_;

This "needs" a comment, and therefore, it probably simply needs a better variable name.  Why not just call it _bankPoints?  This should make it sufficiently clear what sorts of objects the array is intended to contain.  And we needn't comment here about what those objects do.  If someone wants to know what a BankPoint instance does, they can go to BankPoint.h or BankPoint.m, or any documentation you've provided about the BankPoint class.

The bigger crime though is that there are no comments at all in this method:
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position

That wouldn't be so terrible if the method were simpler.  But it's a complicated method, and it's hard to understand what it's trying to do--which makes it hard to optimize.
You say you iterate over arrays three times per method call.  That's not actually true.  One over your fast iteration loops is nested.  You run the nested loop once per iteration of the outer loop.
A better plain-English description of exactly what this method is trying to do along with some embedded comments will already make this method significantly better even if it still performs exactly the same.  Single lines of code don't generally need comments.  I can read a single line of code and know what that line does.
What we need comments for are the bigger picture things.  What does that specific line do in context of the current scope?  In context of the method as a whole?  In context of the class as a whole?  Use comments to give your code more clear context.  This way, when we get lost in the line-by-line details, there's always a helpful comment to re-orient us to the context.
Adding these comments will help you remember the big picture and that can help you come up with a better algorithm for doing whatever it is you're doing.


1. Bug

You don't properly synchronize the set and the heap in all cases. For example, when taking a union:

>>> a = OpenList()
>>> a |= set([1,2,3])
>>> a
OpenList([1, 2, 3])
>>> a._heap
[]

If you insist on your class being a subclass of set, then you probably ought to intercept every method that modifies the set (and there are quite a few: __isub__, __ior__, __ixor__, __iand__, discard, difference_update, intersection_update, symmetric_difference_update, update, and clear, not to mention copy) and ensure that the heap is modified in a corresponding fashion.

But this would be overkill for what ought to be a fairly simple class. What I would do instead would be to inherit from object instead of set, and implement the set as an instance member _set, in the same way that you have _heap as an instance member. With this approach, you can ensure that operations on _set always have corresponding operations on _heap so that they cannot get out of sync.

2. Other issues

Your class is not as general as it could be. In particular, it can only be used to store objects which have a get_path_score method. Why not allow the user to pass in a key function that gets the score for an object? (As in sorted and heapq.nlargest and similar functions.)
You call the superclass method directly via set rather than via the super() function. This means that it's not possible for someone to create a new class that subclasses both your class and some other class C. (Because the method resolution order will go directly from your class to set instead of via the other class C.)
In the remove method, you replace the removed item with a placeholder. This takes time O(n) because you have to find the item in the heap. But removing the item from the heap and re-heapifying would also take O(n), and it would be simpler (because then there would be no need to handle the placeholder item in the pop method). So it's not clear to me that your approach is worth it.

You should think about what you are trying to achieve: if you really want to have fast removal of items, then you need to be cleverer about how you find the removed item in the heap; but if you're happy for removal to be O(n), then you can simplify the code by just deleting the item from the heap and re-heapifying the remainder.

3. Naming and documentation

The data structure used by the A* search algorithm is usually known as a priority queue: that is, a collection of items each of which is associated with a priority (or score), and which can be retrieved in order of their priority. So I think you could choose a better name than OpenList for your class.
Your docstring for the class is written with the wrong audience in mind. It contains implementation details ("uses a heap ... also uses a set") but this is not helpful for users of the class, who want to know what it is for and how to use it.
Your class is a good candidate for a doctest or two.
The method name pop_node_with_lowest_path_score is absurd. Why not just pop?

4. Rewrite

Here's how I'd rewrite the class to fix all the issues discussed above, assuming that you really do want fast removal of items. I'll let you reverse-engineer it to figure out how it works!

from heapq import heappush, heappop

class PriorityQueueElement(object):
    """
    A proxy for an element in a priority queue that remembers (and
    compares according to) its score.
    """
    def __init__(self, elem, score):
        self._elem = elem
        self._score = score
        self._removed = False

    def __lt__(self, other):
        return self._score < other._score

class PriorityQueue(object):
    """
    A priority queue with O(log n) addition, O(1) membership test and
    amortized O(log n) removal.

    The `key` argument to the constructor specifies a function that
    returns the score for an element in the priority queue. (If not
    supplied, an element is its own score).

    The `add` and `remove` methods add and remove elements from the
    queue, and the `pop` method removes and returns the element with
    the lowest score.

    >>> q = PriorityQueue([3, 1, 4])
    >>> q.pop()
    1
    >>> q.add(2); q.pop()
    2
    >>> q.remove(3); q.pop()
    4
    >>> list(q)
    []
    >>> q = PriorityQueue('vext cwm fjord'.split(), key = lambda s:len(s))
    >>> q.pop()
    'cwm'
    """
    def __init__(self, *args, **kwargs):
        self._key = kwargs.pop('key', lambda x:x)
        self._heap = []
        self._dict = {}
        if args:
            for elem in args[0]:
                self.add(elem)

    def __contains__(self, elem):
        return elem in self._dict

    def __iter__(self):
        return iter(self._dict)

    def add(self, elem):
        """
        Add an element to a priority queue.
        """
        e = PriorityQueueElement(elem, self._key(elem))
        self._dict[elem] = e
        heappush(self._heap, e)

    def remove(self, elem):
        """
        Remove an element from a priority queue.
        If the element is not a member, raise KeyError.
        """
        e = self._dict.pop(elem)
        e._removed = True

    def pop(self):
        """
        Remove and return the element with the smallest score from a
        priority queue.
        """
        while True:
            e = heappop(self._heap)
            if not e._removed:
                del self._dict[e._elem]
                return e._elem


Replace $number with $number+1 in std::string

Few observations.

I. You don't need to scan the whole string, character-by-character. str.find('$') will do it for you (and remember to start the second search, and all subsequent ones, from the last reference detected.)

II. Rather than taking substrings, parsing them, erasing and inserting—why not increment in-place? You know exactly your number span (from the one past '$' to the one past the last digit.) If this string only consists of '9's, insert a single '1' right after '$' and change all nines into zeroes. If there are digits less than nine, increment the rightmost non-nine, and change all the subsequent nines into zeroes, if any, no insertion/erasure required. Proceed with the next search.

III. As @AJNeufeld mentioned, string reconstruction can be done in a separate buffer, though vast testing is needed to decide if this is a faster option.


Binary Search Tree implementation using smart pointers

please do not using namespace std;
why has Bst::findmin no prefix _?
why do you use std::shared_ptr<> at all? std::shared_ptr is ment to represent shared ownership. This makes no sense for tree nodes, you're not going to have two trees with the same nodes. std::unique_ptr<> is a better candidate.
it is generally good to separate the data structure from its serialization. Make print a separate function and also handle the member printing outside of the class.

Edit
As you had trouble getting the unique_ptr running, here's what works for me.

Modify the node to use unique_ptr:

struct node
{
    int val;
    std::unique_ptr<node> left;
    std::unique_ptr<node> right;

    // c'tor left out
};

Also, use a unique_ptr for root. You'll receive heavy compiler complaints,
because a unique_ptr cannot be simply copied (one of the instances must go invalid, as it's unique). I suggest altering the private functions:

void _insert(std::unique_ptr<node>& curr, int val);
void _del(std::unique_ptr<node>& curr, int val);

Sample implementation for _insert:

void Bst::_insert(std::unique_ptr<node>& curr, int val)
{
    if (!curr)
    {
       curr = std::make_unique<node>(val);
       return;
    }

    if (val < curr->val)
    {
        _insert(curr->left, val);
    }
    else
    {
        _insert(curr->right, val);
    }
}

Your public insert method would be something like:

void insert(int val)
{
    _insert(root, val);
}

Also: add a find function to see if an element is in the tree. Use the find function to write some simple tests. You may rename del to erase to be closer at the standard naming.

Edit 2 Separate output from data storage:

A friend function is relatively inflexible, as you cannot easily exchange the printing algorithm. You may implement iterators (hard) or provide a traverse function. I'd go for the second approach, as you already have the algorithm in _print: rename print to traverse and pass it a function pointer, then replace the output to std::cout by a call to the function pointer.

class Bst
{
...
    // traverse with function pointer
    void traverse(void (*func)(int));
};

int main()
{
    Bst b;
    // insert data ...

    b.traverse([](auto v){ std::cout << v << " "; });
    std::cout << "\n";
}


Your implementation fails to adhere to some important Object Oriented principles.

Encapsulation

The state of your singleton can be modified by others.

package a;

public class Cat implements Dog {

    static {
        State.age = 17;
    }

    public int age() {
        return Cat.getAge.f(null);
    }

    public void setAge(int age) {
        State.age = age;
    }

    public static void main(String[] args) {
        System.out.println(new Cat().age());
    }
}

Polymorphism

This is basically a problem that comes with the singleton pattern itself. However, a                             more conventional approach to implementing a singleton can deal with this issue :

package b;

public interface Dog {

    String getName();

    void die();

    void woof();
}

and the singleton implementation :

package b;

public enum SingleDog implements Dog {
    INSTANCE;

    private String name;
    private boolean dead;

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void die() {
        System.out.println("X_X");
        dead = true;
    }

    @Override
    public void woof() {
        if (dead) {
            throw new IllegalStateException("cannot woof when dead");
        }
        System.out.println("woof");
    }
}

This way clients can depend on the interface and not the singleton implementation. i.e. that there can only be one instance is now an implementation detail, and not an unchangeable design decision.

If you want to do functional programming, Java is probably not the language you should be using.


Laravel generate category list from product results

Your search query will not be able to leverage an index on the fields you are searching within.  This is because you have a wildcard at the beginning of the search string and a default B-Tree index only works for prefix match use cases.  So when the LIKE condition has a wild card at the beginning, you will need to perform a full table scan.  Full table scans are REALLY bad from a performance standpoint.

It looks like you use case would work best with natural language full text search (MySQL link here - http://dev.mysql.com/doc/refman/5.7/en/fulltext-natural-language.html ).  This would require change to both your query and the database schema.

You also do a lot of individual single table queries here.  My guess is that you can possibly optimize this by utilizing joins to get date across table with a single (or fewer queries) vs. reading data from one table, then another based on that result, then another based on that next result, etc.


As promised, here are some comments on the actual code you posted.

General:

don't define multiple variables on the same line.
is there a good reason to redefine log levels in tp_log_level rather than
use the levels Syslog defines?
you have two arrays, level_txt and level_syslog that are dependent upon
the values of tp_log_level but nothing ties these together.  In such a
small program, this is unlikely to be a problem, but this sort of loose
dependency tends to break with time - someone appends (or even inserts!) a
value to one part without adjusting the other.  Do you really need to log
the level text, "DEBUG" etc?  Syslog doesn't.  Why complicate the job?  If
you just use syslog constants, both these arrays could be discarded.  If you
really must use them, make a structure holding a level and a text and make
an array of these; then at least you only have one dangling dependency...
I personally don't have any dogmatic objection to multiple returns.  Some
coding standards object to them on the grounds that they make functions
unclear.  I would argue the contrary: they can, if used well, make functions
clearer.

In tp_write

why using raw write (as opposed to stdio)?  The fact that you test for
interrupted writes makes me think that you intend to log to a socket or a
serial port etc...  Is that so?
you should get compiler warnings about comparisons and conversions between
size_t and ssize_t.  Since the function only has two return values, -1 and
len, and the caller knows the value of len anyway, it seems unnecessary
to return anything but an int: 0 for success, and -1 for failure.  That way
you can avoid using a ssize_t and the warnings it generates.
you need braces in the if/else statements: the compiler has to assume
that the else belongs to the inner if.  Using braces even when not
strictly necessary is generally considered good practice.  But they can be
ugly...
might be better coded as:

ssize_t tp_write(int fd, const void *buf, size_t len)
{
    const char *p = buf;
    const char *end = p + len;

    while (p < end) {
        ssize_t ret = write(fd, p, (size_t) (end - p));
        if (ret > 0) {
            p += ret;
        }
        else if (errno != EINTR) {
            return -1;
        }
    }
    return 0;
}

In tp_log_init

mode would be more logically of type tp_log_mode
I don't use asserts much.  You are relying on the asserts to find problems
that the subsequent code does not handle (eg. the switch has no
default).
But another approach is to allow the code to fail if the parameters are
wrong by falling back on syslog.  This works even when NDEBUG is defined
(asserts disabled):

void tp_log_init(enum tp_log_mode mode, enum tp_log_level level, int fd)
{
    log_level = level;
    if (mode == TPLM_FILE) {
        if (fd >= 0) {
            log_fd = fd;
            log_mode = TPLM_FILE;
            return;
        }
        /* print an error or abort() if you like */
    }
    openlog(TPL_IDENT, LOG_PID|LOG_CONS, LOG_DAEMON);
    log_mode = TPLM_SYSLOG;
}

 In tp_vlog_write

MAX_TIME_LEN and MAX_MSG_LEN seem generous for a log message.  Remember that
msg is on the stack and if you are in a restricted environment, 1500 bytes
might be too much.  ctime uses 26 bytes for the time/date, so I doubt your time
format needs 512.
level seems like it should be a enum tp_log_level
the switch could be done with if/else
I would extract the creation of a time string into a separate function.
Also, why abort if localtime fails?  This makes your code more fragile
than it needs to be - just don't call strftime() if tm == NULl.
your assert(log_fd) fails if log_fd == 0.  This should apply to the
TPLM_FILE mode only.
as I said before, printing the level text seems unnecessary.  If you need
it, use strcpy instead of snprintf.
printing "\n" could be done with strcpy(msg+len, "\n")
Personally, I have no objection to the use of varargs in this code.  @Lundin
is right that it is not type-safe, but sometimes it has its uses.  This
seems a legitimate use to me.

 In tp_log_close

your assert fails if log_fd == 0.
if/else would be clearer.


Stack implementation with StackInterface

There isn't really much to optimize here, but there are definitely improvements you can make regarding usability and coding style.

use generics instead of Object, otherwise the stack is difficult to use in practice.
in practice, you would probably want a stack to increase its size automatically instead of throwing an exception.
your indentation is not consistent, making your code difficult to read.
you need more vertical whitespace, for example before a new method
your variable names could use improvement. What's a sz? What's an a? What's an Astack?


Please, please, don't rename NULL, uint8_t and uint64_t. It makes your code super hard to read. If you really don't want to type all that out then do a find replace after you're done coding.
Well aware that checking if(!x) is the same as if(x == NULL) and if(x == 0). But ultimately, I have to favor the explicit versions for readability.
Also
for(int x=0; x< MEMORY_LOOKUPS; x++) {
    uint8_t* x = requestMemoryChunk(MEMORY_BLOCK_SIZE - 1 - x);
    freeMemoryChunk(x, MEMORY_BLOCK_SIZE - 1 - x);
}
uint8_t* y = requestMemoryChunk(2);
// you just lost 99.99% of your memory

If this example is too extreme, consider
for(int x=0; x< MEMORY_LOOKUPS; x++) {
    uint8_t* x = requestMemoryChunk(10000 - x);
    freeMemoryChunk(x, 10000 - x);
}
uint8_t* y = requestMemoryChunk(2);
// you just lost ~10000 bytes of memory

Consider snapping the requests to block sizes (eg powers of 2) to avoid these kinds of pathological requests. Further consider keeping the lookups sorted by size.
Stylistically things are ok. There are some unnecessary parentheses in the if conditions but (... y'know lisp exists)
Ultimately, people code in c for efficiency and control. One expects to lose some readability doing clever things. But there's no reason to not explain the clever stuff in comments.


Creating SOLID immutable and mutable Location types

It doesn't make sense to have setters in an immutable location.
Consider this alternative:

interface Location {
    int getX();
    int getY();
}

class MutableLocation implements Location {

    private int x;
    private int y;

    public MutableLocation(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void adjustX(int x) {
        //adjust x
    }

    public void adjustY(int y) {
        //adjust y
    }
}

final class ImmutableLocation implements Location {
    private final Location location;

    public ImmutableLocation(int x, int y) {
        location = new MutableLocation(x, y);
    }

    @Override
    public int getX() {
        return location.getX();
    }

    @Override
    public int getY() {
        return location.getY();
    }
}

Your questions

  I'm not sure if the enum is an overkill

Not necessarily. Maybe it is, maybe it isn't. It will depend on the rest of the code in your project. From here it can go both ways.

  If the setters are a violation of SOLID; I'm not sure how else I should do it.

They violate SOLID, in particular the interface segregation principle:
the immutable class inherits setters but doesn't need them.
See my proposed cleaner alternatives above.

  If UnsupportedOperationException is best fit for the adjust method

For unsupported operations, this is fine, but your purpose is not clear.
Do you intend to add values in this enum without implementing adjust?
If yes, then your solution is fine.
But if you never intend to add values without implementing adjust,
then it would be better to make the method abstract.
Also you should use @Override in the implementations:

enum IncrementOperation {
    INCREASE {
        @Override
        public int adjust(int target, int amount) {
            return target + amount;
        }
    },
    DECREASE {
        @Override
        public int adjust(int target, int amount) {
            return target - amount;
        }
    };

    public abstract int adjust(int target, int amount);
}


Reading a binary file containing periodic samples

data = in_f.read(12)
    num_samples, sample_period, sample_size, param_kind = unpack('>iihh', data)
    A = B = 0
    if compressed:
        A = array('f')
        A.fromfile(in_f, sample_size/2)
        B = array('f')
        B.fromfile(in_f, sample_size/2)
        #The first 4 samples were the matrices
        num_samples -= 4

And so on


Forcing array of promises to complete before returning

forEach vs map

When using map function, we're supposed to return something back from the function parameter. In the code above you do map and populate the promises collection by pushing to it. If you want to have the external collection as it is now, a forEach should be more readable than a map.

With map, the function may look like this. Also, notice that this allows joining the declaration and the assignment of promises array within the body of then(...):

let records = {}
nosqldb.get().listCollections().toArray()
  .then(collectionList => {
    const promises = collectionList.map(collection =>
      nosqldb.get().collection(collection.name).count().then(count => { records[collection.name] = count; })
    );
    return Promise.all(promises);
  })
  .then(() => res.status(200).json(records))
  .catch((err) => res.status(500).send(err));

Side note

You may want to limit the number of collections in which you do .count(). If you have dozens or hundreds or even more collections, you this function may attempt to open as many connections (IDK the details). Also, the function execution time will be really long.

A typical solution in limiting is pagination and/or filtration of the things being counted.


Array-like data structure for fixed sized types with non-machine-word sizes

using namespace std; is a bad practice.

The code is plain C. You have two options:

Admit this fact, change your #includes to the C-style, and declare your functions as extern "C". This way they are callable from both C and C++ code.

Make a class, and overload operator[](std::size_t) and operator[](std::size_t) const. The width shall be a class member. Much more C++ish.

An A parameter to getindex should be const-qualified.

Declare variables as close to use as possible. E.g. instead of
      uint64_t mask1;
      ....
      if () {
          ....
      } else {
          mask1 = ....;
      }

do
      ....
      if () {
      } else {
          uint64_t mask2 = ....


The general approach is sound, but the xor-ing is unnecessarily complex and actually causes it to give an incorrect answer in some cases.  If I've worked through it correctly, it will report that the empty string is equal to the string with the single byte 1.  The simple approach would be to just increment @result when the strings differ at position @i.

There's another concern that I'm not qualified to comment on for T-SQL, but that I know applies to C# or C++: the algorithm that you've specified should be constant-time, but that is before it gets run through any compilers or optimizers.  If you switch to an algorithm that increments a counter, it's conceivable that an optimizer would realize that once @result is not zero the return value is 1, defeating your efforts.


Iterate between dates and INSERT values in a performant way

Instead of a loop which inserts one row after the other you should use generate_series to create all timestamps at once.

Untested:

DO $$
DECLARE --Variables
    NODE_ID         bigint      :=  11;   -- The node id of the datapoint
    TIMESTAMP_START TIMESTAMP   := '2018-12-06 22:00:00';
    TIMESTAMP_END   TIMESTAMP   := '2018-12-10 00:00:00';
    TS_STEP         INTERVAL    := '30 minute';

    MAX_VALUE integer := 100;

BEGIN
    INSERT INTO datapoint_values (dp_id, ts, datatype, source, int_value, float_value)
    SELECT (NODE_ID, x, 2, 0, floor(random()*(MAX_VALUE+1)), 0)
    FROM generate_series(TIMESTAMP_START, TIMESTAMP_END, TS_STEP) t(x);
END $$;


JAVASCRIPT

Calling function before defining it

Invoking CheckForUpdate() before actually defining it, while perfectly valid in JavaScript, is generally a bad practice and it makes code harder to follow. It can also cause troubles in some rare cases.

Style

Function names should follow camelCase convention.
Use strict equality / identity operator (===) instead of regular equality operator (==). That way no type conversion will be performed and following this practice, you are less likely to hurt yourself in the future.
Spaces around +.

onreadystatechange property

Use addEventListener() with readystatechange argument instead. That way you could define multiple listeners of that type if necessary.

setTimeout() function

Firstly, escaping CheckForUpdate() into anonymous function to pass it as an argument to setTimeout() is unnecessary. This

setTimeout(function() { CheckForUpdate() }, 50000);

could be simply written as

setTimeout(CheckForUpdate, 50000);

Lastly, instead of setting timeout at every function call, you could call setInterval() once, outside the function.

Encode

Use encodeURI() function to encode whatever you pass as URL parameters.

Approach of constant querying the server

Constantly querying the server to know whether update is necessary or not, is rather far from the best possible thing to do. It would be way better to be able to get the message directly from the server, once it is necessary. This is where WebSockets come in handy. After linked MDN (emphasis mine):

  WebSockets is an advanced technology that makes it possible to open an
  interactive communication session between the user's browser and a
  server. With this API, you can send messages to a server and receive
  event-driven responses without having to poll the server for a reply.

Respond with JSON (ᴀʀɢᴜᴀʙʟᴇ)

If you responded with {"update": true} instead of TRUE, you could use it later as if (JSON.parse(this.responseText).update) instead of if (this.responseText == "TRUE"). That way you could access values of response as properties of an object in the future. If this doesn't seem necessary, it may be an overkill, though.

Rewrite

After applying all the above suggestions (and more), the code could look like this:

function onUpdateStateChange() {
  if (this.readyState === 4 && this.status === 200) {
    if (JSON.parse(this.responseText).update) {
      return document.location.reload(true);
    }
    console.log(this.responseText);
  }
}

function checkForUpdate() {
  var request = new XMLHttpRequest(),
      address = '/IsPageUpdated.php?URL=' + window.location + '&CurrentVersion=' + CurrentWebpageVersion;

  request.open('GET', encodeURI(address), true);
  request.addEventListener('readystatechange', onUpdateStateChange);
  request.send();
}

setInterval(checkForUpdate, 50000);

PHP

Potential SQL injection

$URL = mysqli_real_escape_string($DBConnection, $_GET['URL']);
$Query = "SELECT ID, URL, CurrentVersion FROM PageUpdates WHERE URL = '$URL'";

Well, mysqli_real_escape_string() is not the preferred method of passing variables to SQL statements. You could hurt yourself, e.g. if you didn't explicitly defined character set to the right one. Use prepared statements and mysqli_prepare() instead.

Style

You have a few style problems, i.a. indentation and naming issues.