Find items in a table that match a set of conditions in another table

This is the standard logic to find subsets, but 15 minutes for two not really big tables is really a lot.

The join might return a huge result intermediate set (it's a m-n-join), you can check it using:

SELECT COUNT(*)
FROM   #TABLE1 AS T1
JOIN   #TABLE2 AS T2 ON T2.EXPORT = T1.EXPORT

Your query can be simplified a bit using a Group Count before the join:

WITH cte AS
 (
   SELECT *,
      COUNT(*) OVER (PARTITION BY SETID) AS cnt
   FROM #TABLE1
 )
SELECT SETID, COUNTRY
FROM cte
JOIN #TABLE2 AS T2
  ON T2.EXPORT = cte.EXPORT
GROUP BY SETID, COUNTRY
HAVING COUNT(*) = MAX(cte.cnt)
ORDER BY SETID

But I don't expect this to improve runtime (unless the optimizer did a very stupid plan before)

Edit:

As expected, most of the runtime is caused by the huge number (1,500,000,000) of rows in the intermediate result set. For a similar problem (exactly matching two sets) I used a solution based on joining comma-delimited strings of all values in a group (which was very efficient on a Teradata system). This logic can be modified for subsets, but I don't really know about efficiency.

This is the algorithm:

For each country create a comma-delimited list like this:

,FOOD,,GARMENT,,STEEL,,TECHNOLOGY,

For each set create a comma-delimited list like this:

%,GARMENT,%,TECHNOLOGY,%

And then simply join using a LIKE (the additional commas are needed to prevent matching partial values, e.g. 'TECHNO' matching 'TECHNOLOGY'):

WITH cte1 AS
 (
   SELECT SETID,
      STUFF((SELECT ',%,' + EXPORT
             FROM  #TABLE1 AS t2
             WHERE t.SETID = t2.SETID
             ORDER BY EXPORT
             FOR XML PATH('')) + ',%', 1, 1, '') AS x
   FROM #TABLE1 AS t
   GROUP BY setid
 )
,cte2 AS
 (
   SELECT COUNTRY,
      (SELECT ',' + EXPORT  + ','
       FROM  #TABLE2 AS t2
       WHERE t.COUNTRY = t2.COUNTRY
       ORDER BY EXPORT
       FOR XML PATH('')) AS x
   FROM #TABLE2 AS t
   GROUP BY COUNTRY
 )
SELECT cte1.SETID, cte2.COUNTRY
FROM cte1 JOIN cte2
ON cte2.x LIKE cte1.x
;


Few habits to learn early in life.

passing big arguments by references. ( bool& visited[] )
deleting unused memory. (delete visited)
proper indentation always makes it better.

Here is the complete code.

#include<bits/stdc++.h>
using namespace std;

class Graph
{
    int V;
    list<int> *adj;
    void DFSUtil(int v, bool& visited[]);
    public:
    Graph(int V);
    void addEdge(int v, int w);
    void DFS(int v);
};

Graph::Graph(int V)
{
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
}

void Graph::DFSUtil(int v, bool& visited[])
{
    visited[v] = true;
    cout << v << " ";
    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i, visited);
}

void Graph::DFS(int v)
{
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
    DFSUtil(v, visited);
    delete visited; // avoids memory leaks
}

int main()
{
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);

    for(int i = 0; i < 4; i++) {
        g.DFS(i);
        puts("");
    }
    return 0;
}

Apart from these your code is very optimized possible.


You don't really need a tooltip class on your target element. Since you already have a data-tooltip attribute, that's enough to find the relevant elements:

$("[data-tooltip]") // find all elements with a data-tooltip attribute

This will also let you use the tooltip class for the actual tooltip, which makes more sense, given the name.

You call $(this) multiple times instead of calling it once and storing it a variable, e.g.

var target = $(this);

You're also creating an element in your code, yet you're fetching it back through jQuery. That really isn't necessary, since that can go in a variable too. And you can use jQuery to your advantage a bit more.

var tooltip = $("

")
  .hide()
  .addClass("tooltipbox")
  .appendTo(document.body);

then, when positioning it, it might be nice with yet more variables, just to improve clarity a bit

var top  = offset.top - tooltip.outerHeight() - 3,
    left = offset.left - (tooltip.outerWidth() - target.width()) / 2;

tooltip.css({
  left: left,
  top:  top
});

Also, you may want to not hide the tooltip, if the user mouses over it. Doing so will require more trickery, though, so it's a bit out-of-scope for this answer. But the point is that right now, moving over the tooltip causes it to disappear, which can cause a bunch of flickering, since it's being displayed practically where the cursor already is.

Lastly, it'd be better to use a div or span for the tooltip. While not strictly necessary, the div element is a better fit, because it's semantically neutral, and span just means "a run of text". A p element means paragraph, but a tooltip is usually just a tiny snippet; not really a paragraph in and of itself. There's nothing preventing you from using a p or any other element, but that also means you might as well use a more appropriate element than p.


void Rebuild(std::size_t NewSize, bool FromFront = false)
{
    const std::size_t OldSize = Size;

    Datatype* NewStorage = new Datatype[NewSize];

Rather then creating a temporary array and copying the existing data into it, just create the new array and copy into that.

    int CopyLength = std::min(OldSize, NewSize);

We start by determining how many elements we will actually copy

    if( FromFront )
    {
        std::copy(BasePointer + OldSize - CopyLength, BasePointer + OldSize,
                  NewStorage + NewSize - CopyLength);
    }
    else
    {
        std::copy(BasePointer, BasePointer + CopyLength, NewStorage);
    }

I use std::copy to avoid having to write a copying for loop myself.

    delete[] BasePointer; // Delete the main array...
    BasePointer = NewStorage;
    Size = NewSize; // Size is used in other methods.

delete the current array and replace it with my new array

}


I'd simply flip it around:

if( !(this.properties.width > 0 && this.properties.height > 0) ) {
  return;
}

This will catch null, undefined, NaN, etc., etc.. It will allow numeric strings (provided they can be coerced to a number greater than zero), and of course it'll allow straight-up positive, non-zero numbers.

Update: There's one edge-case I've come across: Arrays. It's some unfortunate JavaScript weirdness to do with type coercion:

[] > 0;     // => false (so far so good)
[0] > 0;    // => false (as it should be)
[1] > 0;    // => true  (what?)
[1, 1] > 0; // => false (WHAT?)

So an array with just a single numeric element will be treated as a number when comparing.

Well, actually, as far as I can tell, the array is coerced to a string by coercing each element to a string, and joining them with a comma, and the joined string is then compared lexicographically coerced to a number in order to be compared. (Thanks to Robert in the comments for the correction)

[1] + 0;    // => "10"
[1, 1] + 0; // => "1,10"
"0" > 0;    // => false
"1" > 0;    // => true
"1,1" > 0;  // => false

I love JavaScript, but sometimes... jeez...


The inputs have to be limited with constraints you have listed, then

use a TreeSet to store the N objects in it
remove the K first
print the Set

few lines in Java (no malloc problem, memory managed by JVM):

read the first input
use String.split() the line,
use Integer.valueOf(String) to convert
compare N,K and stop if not correct or if negative
use a while(<N) for input,
test limits of input whith if and negative values
you can use toString() to print the Set, but you have to use a
foreach to sum the result
print result


avoid importing namespaces

You have using namespace std;. You are obviously working in a .cpp where it is usually fine to do this; but I (and many others) don't like to remove the std::. It is short enough to write it every time you are trying to access a function/class or whatever of the std scope. Use it; it makes things clearer (at least for me ;))

use free functions over member functions

Herb Sutter described it nice in one of his articles; please forgive me that I am not able to provide you with a short text but on stackoverflow there are plenty of topics like this.
E.g. click me

It is more generic to use the std::begin and std::end functions than the container specific one. Technically it is totally the same; it just makes it easier to change the container type.

keep things local

I think you know that you should keep your objects as local as possible. I don't see a good reason here to declare your matrix objects in the global scope.

lambdas

The lambdas are fine. You could use a lambda for the isAllZeroRow() function instead of declaring a free function for this, but this is also fine.

You can declare the lambda parameters as auto. You don't have to define types explicitly anymore. This safes us from some annoying typing and redundancy and - one of my most loved arguments - it's more generic.

You could also delete the other free function, too, and just create a local lambda object.

int main() {
    std::vector<std::vector<int>> matrix1 = {{1, 2}, {0, 0}, {1, 1}};

    auto firstAllZeroIndex = [](const auto& m) {
        return std::distance(std::begin(m), std::find_if(std::begin(m), std::end(m), [](const auto& row){
            return std::all_of(std::begin(row), std::end(row), [](int x){return x==0;});
        }));
    };
    assert(firstAllZeroIndex(matrix1) == 1);
}

more meaningful return type

You should use a return type which offers you the possibility to return an invalid statement. In c++17 we'll get the comfortable type std::optional, but for now we can use a std::pair<int, bool> statement. In this case, the int of the type has a valid value as long as the bool of the pair is true. I recommend this, because it makes the code more self-descriptive.

some praises

You are using the c++ headers; <cassert> is the right one, as every other header with the c prefix and without the .h. Good job :D

From my point of view your solution looks almost perfect (at least with the given requirements). You should be aware of the fact, that in this example you could use std::array types instead of std::vector and that it could be possible to resize your matrix objects which could lead to different row sizes in one matrix object. In the end I would write a class for this, to prevent me (and others) from doing such dumb stuff and getting frustrated ;)


A few simple comments :

Listen to your compiler

The compiler can give you a lot of really interesting information. Activate all warnings (I use gcc -Wall -Wextra -std=c99 cipher.c -o cipher_out) and you'll see a few things to fix :

cipher.c: In function ‘decode_text’:
cipher.c:13:16: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
  for (i = 0; i < strlen(text); i++) {
                ^
cipher.c: In function ‘main’:
cipher.c:37:2: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
  char* text = (char*)malloc(sizeof(char)*TEXT_SIZE+1);
  ^
cipher.c:37:22: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
  char* text = (char*)malloc(sizeof(char)*TEXT_SIZE+1);
                      ^
cipher.c:47:3: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
   printf("format is: '%s' [-d|-i]\n", argv[0]);
   ^
cipher.c:47:3: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
cipher.c:48:3: warning: implicit declaration of function ‘exit’ [-Wimplicit-function-declaration]
   exit(1);
   ^
cipher.c:48:3: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
cipher.c:53:2: warning: implicit declaration of function ‘fgetc’ [-Wimplicit-function-declaration]
  for(i = 0, ch = fgetc(stdin); i < TEXT_SIZE && !feof(stdin); i++, ch = fgetc(stdin)){
  ^
cipher.c:53:24: error: ‘stdin’ undeclared (first use in this function)
  for(i = 0, ch = fgetc(stdin); i < TEXT_SIZE && !feof(stdin); i++, ch = fgetc(stdin)){
                        ^
cipher.c:53:24: note: each undeclared identifier is reported only once for each function it appears in
cipher.c:53:2: warning: implicit declaration of function ‘feof’ [-Wimplicit-function-declaration]
  for(i = 0, ch = fgetc(stdin); i < TEXT_SIZE && !feof(stdin); i++, ch = fgetc(stdin)){
  ^
cipher.c:65:16: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
  for (i = 0; i < strlen(text); i++) {
                ^
cipher.c:112:2: warning: implicit declaration of function ‘fprintf’ [-Wimplicit-function-declaration]
  fprintf(stderr, "\n%s\n", ALPHABET);
  ^
cipher.c:112:2: warning: incompatible implicit declaration of built-in function ‘fprintf’ [enabled by default]
cipher.c:112:10: error: ‘stderr’ undeclared (first use in this function)
  fprintf(stderr, "\n%s\n", ALPHABET);
          ^
cipher.c:116:2: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
  printf("\n%s\n", newtext);
  ^

You are missing :

#include <stdio.h>
#include <stdlib.h

And you should define i and j as unsigned int.

Format your code

The indentation seems a bit off in your question. I don't know if it's because you pasted the code in a wrong way or whatever but your favorite text editor can fix this easily.

Tell what you want to do

You are not describing anywhere how your program works : format is: program_name [-d|-i] is not enough if you don't explain what the options are for.

Also, it should be described somewhere that your program will affect only letters for instance.

Move variables to the smallest possible scope

It keeps things easier to understand and to split into smaller functions.

At this stage, the code looks like :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TEXT_SIZE 100000  // Note, the longer the text the more likely you will get a good decode from the start.
#define ALEN 26         // Number of chars in ENGLISH alphabet
#define CHFREQ "ETAONRISHDLFCMUGYPWBVKJXQZ" // Characters in order of appearance in English documents.
#define ALPHABET "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

/* Decode the given text using the given map and store the result in newtext */
void decode_text(char* text, char* newtext, char map[][2]) {
    for (unsigned int i = 0; i < strlen(text); i++) {
        // If the current character in text is not a letter, copy it to newtext as punctuation and digits should be maintained.
        if (!isalpha(text[i])) {
            newtext[i] = text[i];
            continue;
        }
        for (unsigned int j = 0; j < ALEN; j++) {
            if (text[i] == map[j][1]) {
                newtext[i] = map [j][0];
            }
        }
    }
}

char upcase(char ch){
    if(islower(ch))
        ch -= 'a' - 'A';
    return ch;
}

int main(int argc, char **argv){
    // first allocate some space for our input text (we will read from stdin).
    char* text = (char*)malloc(sizeof(char)*TEXT_SIZE+1);
    char opt;
    int tmpi;

    // Check the CLI arguments and extract the mode: interactive or dump and store in opt.

    if(!(argc == 2 && isalpha(opt = argv[1][1]) && (opt == 'i' || opt == 'd'))){
        printf("format is: '%s' [-d|-i]\n", argv[0]);
        exit(1);
    }

    // Now read TEXT_SIZE or feof worth of characters (whichever is smaller) and convert to uppercase as we do it.
    {
        unsigned int i;
        for(char ch = fgetc(stdin); i < TEXT_SIZE && !feof(stdin); i++, ch = fgetc(stdin)){
            text[i] = (isalpha(ch)?upcase(ch):ch);
        }
        text[i] = '\0'; // terminate the string properly.
    }

    // Assign alphabet to one dimension of text frequency array and a counter to the other dimension
    char textfreq[ALEN][2];
    for (unsigned int i = 0; i < ALEN; i++) {
        textfreq[i][0] = ALPHABET[i];
        textfreq[i][1] = 0;
    }

    // Count frequency of characters in the given text
    for (unsigned int i = 0; i < strlen(text); i++) {
        for (unsigned int j = 0; j < ALEN; j++) {
            if (text[i] == textfreq[j][0]) textfreq[j][1]+=1;
        }
    }

    //Sort the character frequency array in descending order
    for (unsigned i = 0; i < ALEN-1; i++) {
        for (unsigned j= 0; j < ALEN-i-1; j++) {
            if (textfreq[j][1] < textfreq[j+1][1]) {
                tmpi = textfreq[j][1];
                char tmpc = textfreq[j][0];
                textfreq[j][1] = textfreq[j+1][1];
                textfreq[j][0] = textfreq[j+1][0];
                textfreq[j+1][1] = tmpi;
                textfreq[j+1][0] = tmpc;
            }
        }
    }

    //Map characters to most occurring English characters
    char map[ALEN][2];
    for (unsigned int i = 0; i < ALEN; i++) {
        map[i][0] = CHFREQ[i];
        map[i][1] = textfreq[i][0];
    }

    // Sort the map lexicographically
    for (unsigned int i = 0; i < ALEN-1; i++) {
        for (unsigned int j = 0; j < ALEN-i-1; j++) {
            if (map[j][0] > map[j+1][0]) {
                char tmpc = map[j][0];
                char tmpc2 = map[j][1];
                map[j][0] = map[j+1][0];
                map[j][1] = map[j+1][1];
                map[j+1][0] = tmpc;
                map[j+1][1] = tmpc2;
            }
        }
    }

    char newtext[TEXT_SIZE];
    if(opt == 'd'){
        decode_text(text, newtext, map);
    } else {
        // do option -i
    }

    // Print alphabet and map to stderr and the decoded text to stdout
    fprintf(stderr, "\n%s\n", ALPHABET);
    for (unsigned int i = 0; i < ALEN; i++) {
        fprintf(stderr, "%c", map[i][1]);
    }
    printf("\n%s\n", newtext);

    return 0;
}

Split your code into re-usable functions

I just realised that vnp comment explains this already. nothing to add here.

A few tiny code comments

You don't need to use malloc in your case.

Also, you don't need a continue in your decode function : an else would do the trick here.


Generating random and secure CSRF tokens

If CSRF stands for Cross Site Request Forgery, then it's hard to imagine why I should help.

In any case, simply doing a cryptographic Whirlpool hash of a user-supplied string with a random seed value should be sufficiently random for most every purpose.  The rest is just obfuscation and doesn't add to security.


Finding the states with the three most populous counties

nlargest could help, it finds the maximum n values in pandas series.

In this line of code, groupby groups the frame according to state name, then apply finds the 3 largest values in column CENSUS2010POP and sums them up. The resulting series has the unique state names as index and the corresponding top 3 counties sum, applying nlargest gets a series with the top 3 states as required

return census_df[census_df['SUMLEV'] == 50].groupby(
    'STNAME')['CENSUS2010POP'].apply(
    lambda x: x.nlargest(3).sum()).nlargest(
    3).index.values.tolist()


1. Bug

The algorithm in three_sum is not correct (at least not in the usual version of the 3SUM problem):

>>> three_sum([1, -2])
{(-2, 1, 1)}

In the call two_sum(nums, -n) there's nothing to stop two_sum from using the number n in its pair, even though n is also needed to make up the triple.

2. Review

two_sum and three_sum have similar names, so you might guess that they do similar things, but two_sum return at most one pair adding up to an a given target whereas three_sum returns a list of triples adding up to zero. When writing a group of similar functions it's worth taking care that they have similar interfaces — this makes them easier to use reliably.

In this case the difference in implementations means that it's not clear exactly what three_sum does — we can't say that it returns all the triples adding up to zero, because when it calls two_sum it gets at most one result, and this might cause it to miss some triples. This is quite unsatisfactory — we can't use this function if we want all the triples, but if we only want one triple then we have to wait longer than we need to.

(This observation is similar in spirit to the zero one infinity rule — we often need functions that find one thing, or find all the things, but very rarely do we need functions that find some of the things.)
There are no docstrings. What do these functions do? What do they return? (I think that if you had written docstrings then you might have spotted the problem in point 1 above.)
In two_sum, it's not clear what the name d means. (I guess d stands for dictionary, but a dictionary containing what?) I would use a more descriptive name like seen. Similarly, instead of key I would use a name like remainder.


Performing calculations with updated integer

How about something like this?

import time

def add_num(x):
    added_int = int(raw_input("What number would you like to add to your integer (%s) by?" % x))
    outcome = x + added_int
    print("\nThe sum of %s + %s is %s" % (x, added_int, outcome))
    return outcome

def sub_num(x):
    sub_int = int(raw_input("What number would you like to subtract to your integer (%s) by?" % x))
    outcome = x - sub_int
    print("\nThe subtract of %s - %s is %s" % (x, added_int, outcome))
    return outcome

def mul_num(x):
    mul_int = int(raw_input("What number would you like to multiply your integer (%s) by?" % x))
    outcome = x * mul_int
    print("\nThe multiplication of %s * %s is %s" % (x, added_int, outcome))
    return outcome

def div_num(x):
    div_num = int(raw_input("What number would you like to divide your integer (%s) by?" % x))
    outcome = x / float(div_num)
    print("\nThe divider of %s / %s is %s" % (x, added_int, outcome))
    return outcome

def main():
    op_map = {"1":add_num, "2":sub_num, "3":mul_num, "4":div_num}
    number = 0
    print("The current integer is set at %s ." % number)
    while True:
        prompt = raw_input("Would you like to change the number? (Y/N)").lower()
        if prompt == "y":
            number = int(raw_input("Insert the new integer here: "))
            print("\nYou have changed the integer to %s .\n\n" % number)
            time.sleep(1)
            print("1. Add / 2. Subtract / 3. Multiply / 4. Divide\n")

            op = raw_input("What would you like to do with your new integer? (Choose a number) \n")
            if op is not None:
                operation = op_map.get(op)
                number = operation(number)

        elif prompt == "n":
            print("The integer will stay the same.")
            time.sleep(2)
            raw_input("Press enter key to exit...")
            break
        else:
            print("Invalid response")

if __name__ == '__main__':
    main()


Parsing Windows Bitmap header information

First of all, don't use underscores in fields names. Fields like header_size, pixel_width and so on should be renamed to headerSize, pixelWidth. You should use camelCase for private fields, parameters and local variables. Also don't shorten parameters. Use binaryReader instead of br.

All methods in C# should be PascalCased. It means you should change show to Show.

I'm personally not a fan of passing streams and readers in constructors to initialize an instance of some class. In my opinion constructor should be as simple as possible, without reading from streams and heavy calculations. Ideally it should take only parameters that will be stored to fields or properties.

In you case I would change this code:

public BMPFileHeader(BinaryReader br)
{
    br.BaseStream.Seek(0, SeekOrigin.Begin);
    header_field[0] = br.ReadChar();//1
    header_field[1] = br.ReadChar();//2
    file_byte_size = br.ReadUInt32();//6
    br.ReadUInt16();//8
    br.ReadUInt16();//10
    pixel_start = br.ReadUInt32();//14
}

to

private const int HeaderFieldSize = 2;

private char[] _headerField = new char[HeaderFieldSize];
private uint _fileByteSize;
private uint _pixelStart;

public BMPFileHeader(char[] headerField, uint fileByteSize, uint pixelStart)
{
    _headerField = headerField;
    _fileByteSize = fileByteSize;
    _pixelStart = pixelStart;
}

public static BMPFileHeader Read(BinaryReader binaryReader)
{
    binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);

    var headerField = binaryReader.ReadChars(HeaderFieldSize);
    var fileByteSize = binaryReader.ReadUInt32(); // 6

    binaryReader.ReadUInt16(); // 8
    binaryReader.ReadUInt16(); // 10

    var pixelStart = binaryReader.ReadUInt32(); // 14

    return new BMPFileHeader(headerField, fileByteSize, pixelStart);
}

And the same approach I would apply in BMPHeaderReader.

Instead of this code:

Console.WriteLine("Header size");
Console.WriteLine(header_size);
Console.WriteLine("Pixel Width");
Console.WriteLine(pixel_width);
Console.WriteLine("Pixel Height");
Console.WriteLine(pixel_height);
Console.WriteLine("Pixel Depth");
Console.WriteLine(pixel_depth);
Console.WriteLine("Pixels");
Console.WriteLine(pixels);
Console.WriteLine("Row size");
Console.WriteLine(row_size);
Console.WriteLine("Padding bits");
Console.WriteLine(padding_bits);
Console.WriteLine("Padding bytes");
Console.WriteLine(padding_bytes);

you can write

Console.WriteLine(string.Join(Environment.NewLine,
                              new object[]
                              {
                                  "Header size",   headerSize,
                                  "Pixel Width",   pixelWidth,
                                  "Pixel Height",  pixelHeight,
                                  "Pixel Depth",   pixelDepth,
                                  "Pixels",        pixels,
                                  "Row size",      rowSize,
                                  "Padding bits",  paddingBits,
                                  "Padding bytes", paddingBytes
                              });


Find largest connected cells of value 1 or greater

You have a lot of global variables. Almost all of them, actually. I only see two var declarations, and those two are probably the ones that matter least (though all declarations matter - don't skip 'em).

You're lucky you're not calling functions with loops from inside other loops. Otherwise they'd both be using the same i variable, and things would get weird. Or rather, get broken.

So fix that first! Try running your code through jshint, for instance, to get some basic refactoring/bug checking.

Secondly, while I applaud striving for object-oriented JS, it seems overwrought in this case.

If the task is indeed to find cells with a 1 in them, and all other cells have a 0, then there's a shortcut to take. Since zero is false'y, and one is truth'y, they can pull double-duty as the visited flag: If a cell is zero, it's either been visited or is not worth visiting. In other words, we can ignore every cell that's false'y.

So if you just set cells to 0, false, or null along the way, they'll be ignored later on. Same effect as your visited, but without the need for instantiating objects.

As for recursion, that's definitely an option here. Here's one such implementation:

function largestGroup(matrix) {
  var counts = [0];

  // count connected cells, starting with cell i,j
  function countConnected(i, j) {
    if(matrix[i][j]) {
      matrix[i][j] = null;
      return neighborsOf(i, j).reduce(function (sum, coord) {
        return sum + countConnected(coord[0], coord[1]); // recursion
      }, 1);
    }
    return 0;
  }

  // get neighbor coordinates of i,j
  // (ignores those that are false'y)
  function neighborsOf(i, j) {
    return [
      [i-1, j], [i+1, j],     // up and down
      [i, j-1], [i, j+1],     // left and right
      [i-1, j-1], [i-1, j+1], // diagonally up
      [i+1, j-1], [i+1, j+1]  // diagonally down
    ].filter(function (coord) {
      // keep only those coordinates that match cells that
      // a) exist, and
      // b) contain something thruthy
      return matrix[coord[0]] && matrix[coord[0]][coord[1]];
    });
  }

  // copy matrix to avoid modifying the original
  matrix = matrix.slice().map(function (row) {
    return row.slice();
  });

  // look for cells with something in 'em, and
  // start counting connected cells from there
  for(var i = 0 ; i < matrix.length ; i++) {
    for(var j = 0 ; j < matrix[i].length ; j++) {
      if(matrix[i][j]) {
        counts.push(countConnected(i, j));
      }
    }
  }

  return Math.max.apply(null, counts);
}

It starts by copying the matrix, since it's going to be modifying it, and we don't want to modify the input - other code may hold references to it.

After that, it starts looping through its copy, looking for the first truth'y cell. It then calls countConnected with that cell's coordinates, which, in turn, calls itself on each neighboring cell that's of interest (i.e. not zero). Any cell that's visited gets set to null, which, like zero, is false'y. Thus visited cells are ignored.

Each truthy cell that's visited by countConnected will add 1 to the count; any false'y cells will add zero. And since cells are set to null the first time they're counted, they won't be counted twice.


Create table that lists worksheet visibility

I don't think there is a StringBuilder() class in VBA, only some tricks using Mid.

Const DELIMIT As String = "|", COLSPAN As Long = 2
Dim HEADER As String

This is a little confusing, UPPERCASE should indicate a constant, which is does with DELIMIT - but Header is not (cannot) be a constant. And that leaves me without a Dim or a Const for COLSPAN. Try to be a little more consistent with that - it will be much easier to tell what variables are what.

Dim ASU as Boolean
ASU = Application.ScreenUpdating
Application.ScreenUpdating = False
Application.ScreenUpdating = ASU

Now, I know ASU can't be a constant. Maybe screenIsUpdating? But then again, I think using a variable to store this is overkill unless you are trying to save the settings of the user - which you aren't

Dim screenIsUpdating as Boolean
screenIsUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False
Application.ScreenUpdating = screenIsUpdating

This way you store the user's settings, but still turn it off for your procedure.

These variables could use better names, even if i and j -

Dim Rw As Long, Col As Long
Dim Ws As Worksheet

Ws works, but I don't recommend it, it will start to look pretty messy once you have a lot going on. Also, local variables should start with a lowercase letter Standard VBA naming conventions.

Dim tblVisibility As Range, rngFormulas As Range, rngConstants As Range

I see tblVisibility and think "oh, must be a boolean" - but it's a range. And rngFormulas and rngConstants seem to have the same issue, which is why they are prefixed with rng - yeah?

tableRange
formulaRange
constantRange

But, what is constantRange? If it's constant, it doesn't need a range.

Cells(Rw, Col).Value2 = Value

You did a good job qualifying most things, but this Cells isn't qualified - it should be inputCell.Parent.Cells - or just give that target sheet a variable.

If MsgBox(Msg, vbYesNo + vbCritical, "Your attention please!") = vbNo Then End

Here's an End again, try to avoid those. Also I think Msg (as well as some other fixed strings) could be a Const.

Rw = inputCell.Row + 1
Col = inputCell.Column
Dim Value As String
For Each Ws In ActiveWorkbook.Worksheets
    Value = Join(Array(Ws.Name, Ws.Visible), DELIMIT)
    Cells(Rw, Col).Value2 = Value
    Rw = Rw + 1
Next

This loop is pretty confusing to me. You are iterating up the rows, but have a loop for the sheets?

For index = 1 to Thisworkbook.Worksheets.Count
   targetSheet.Cells(index+1,tableColumn) = Join(Array(Worksheets(index).Name,Worksheets.Visible), DELIMITER)
Next

But, for that Join string, I would probably do it a different way -

Dim index As Long
Dim tableArray() As String
Dim sheetCount As Long
sheetCount = ThisWorkbook.Worksheets.Count
ReDim tableArray(1 To sheetCount, 1 To 2)
For index = LBound(tableArray) To UBound(tableArray)
    tableArray(index, 1) = ThisWorkbook.Worksheets(index).Name
    tableArray(index, 2) = ThisWorkbook.Worksheets(index).Visible
Next

Arrays are faster and you can just Transpose it into your table range. Or maybe just convert the array into a table.

Oh, and your procedure name

Public Sub ListWorksheetVisibilityInActiveWORKBOOK()

Good job on being descriptive, but it's a bit much. CreateSheetVisibilityTable() maybe?


Optimising multiple string splits and concatenations

I would use generic list to store messages history and Linq extension methods. If I understood correctly I would append new messages and crop to predefined maximum size. Could you test this solution if it has sufficient performance?

private List<string> _history = new List<string>();

public void Print(params string[] msgs)
{
    _history.AddRange(msgs.Where(m => !string.IsNullOrWhiteSpace(m)));
    _history = _history.Skip(Math.Max(0, _history.Count - MAX_HISTORY)).ToList();
    history.text = string.Join(Environment.NewLine, _history);
}

If you need messages ordered from newest to latest, you can add Reverse() method:

_history = _history.Skip(Math.Max(0, _history.Count - MAX_HISTORY)).Reverse().ToList();


Fetch text values from JSON and Display pop onclick text

Your code is very prone to errors, since you write all your html tags and content as a single string. Containing html and javascript in that way is extremely unsafe.

I would suggest creating your elements with document.createElement() and then using the JSON to set all the attributes. In the function you could just pass the id, and then find the correct json data for that id.

Concept code

function buildPopup(id) {
  let layer = findJsonData(id)

  let popup = document.createElement("div")
  popup.classList.add("txtContainer")
  popup.id = layer.name
  popup.style.left = layer.x + "px"
  popup.style.top = layer.y + "px"
  popup.style.fontFamily = layer.font
  popup.innerHTML = layer.text

  // adding a close button
  let btn = document.createElement("button")
  popup.appendChild(btn)
  btn.addEventListener("click", ()=>{
      closePopup(layer.name)
  })

  document.body.appendChild(popup)
}

Example for calling this function

 Open popup

Example for getting the json by id

 // this function will find the right json data for this id
 function findJsonData(id){
     return {
      "font" : "Arian",
      "x" : 201,
      "y" : 461,
      "src" : "180ef82d1.otf",
      "width" : 679,
      "type" : "text",
      "text" : "Good Food",
      "name" : "edit_good_1"
    }
 }

I realise this is a bit conceptual but hopefully it will point you in the right direction!

JSFiddle


The code wastes quite a few cycles rejecting palindromes less than lo_bound. It is not hard to find the smallest palindrome above lo_bound, and start from there.
If you are not comfortable constructing such palindrome, consider lifting the lead-in into the separate loop:
    long num = 1;
    while (num < lo_bound) {
        num = make_next_palindrome(queue);
    }

The entire business around queue is very non-obvious, and it takes a great mental effort to realize that it iterates palindromes. I recommend to factor this logic out into a class of its own, along the lines of
class palindrome_iterator {
    std::queue<...> queue;
    // length, W, etc as necessary
public:
    palindrome_iterator(long start_num);
    long next();
};

This way the main loop is streamlined into
    palindrome_iterator p_i(lo_bound);
    for (long num = p_i.next(); num < hi_bound; num = p_i.next()) {
        superpalindromes += is_palindrome(num * num);
    }

An additional (and possibly more important) benefit of such refactoring is that it enables unit testing of palindrome generation logic (which really sreams to be unit tested).

I strongly advise against -~length trick. length + 1 is much more clear, and for sure not slower.


Your naming convention doesnt aid legability. e.g, rename p to port.

Don't do carte blanche exception handling. Be more specific, e.g.:

try:
    ...
except (ValueError, KeyError)
    ...

You are also a miser with your spaces. White space is important for legibility.

explicit is better than implicit so replace ipscan('.'.join(map(str,start)),p) with ipscan(start2='.'.join(map(str,start)), port=p)

Consider replacing while end>start with while end >= start as it allows scanning of a single IP address..

I cans see how the ordering of 3,2,1,0 is important so replace

for i in (3,2,1,0):
     if start[i]==255:
         start[i-1]+=1 #what if
         start[i]=0

with

for i, val in enumerate(start):
    if val == 255:
        start[i] = 0
        start[i-1] += 1

Also, what if item at index 0 == 255? that will cause start[i-1] += 1 to raise an Index Error.

Also, it is not clear why that transformation is being done, so some documentation will be great. Future you will thank present you for it too. Just simply #this does x because of y can suffice.

replace

of=open('Output.txt','w')
for ip in ok:
    of.writelines(ip+'\n')
of.close()

with context and join

with open('Output.txt','w') as of:
    of.write('\n'.join(ok))


Find the lowest and second lowest values in an array of numbers

Because Array lets you put repeated elements of same value, I believe that the two lowest elements in [1, 2, 1] are [1, 1], not [1, 2]. This is the very same behavior one would face if sorting the array and getting the two first elements.
Also I believe that in [1] there is a lowest and no 2nd lowest (also, the very same behavior if sorting and getting the first two).

With this in mind, I changed your code to obey these premises (and make it a bit more readable if I may say). Take a look.

def two_lowest arr
  # if arr has no elements, there is no answer
  # If arr has only one element, this is the lowest
  if arr.size < 2 then
    return arr.first, nil
  end

  lowest, second_lowest = nil, nil

  arr.each do |n|
    if lowest.nil? or n < lowest
      # if we have no lowest or we found an element lower than current lowest,
      # update our lowest and 2nd lowest
      second_lowest = lowest
      lowest = n
    elsif second_lowest.nil? or n < second_lowest
      # if we have no 2nd lowest or we found an element between lowest and 2nd
      # lowest, update our 2nd lowest
      second_lowest = n
    end
  end

  return lowest, second_lowest
end

If you want to test it

tests = [
  [],
  [1],
  [1, 1],
  [1 ,2],
  [1, 2, 1],
  [1, 2, 3],
  [1, 1, 2, 3],
  [3, 2, 1, 1],
]

for test in tests
  puts "In #{test}:"
  puts "#{two_lowest test}"
  puts
end


Overall, your code doesn't look bad.  You have good use of white space and indentation.  I found your variable names to be a little confusing (what's the difference between totalDays and days?  Without actually digging into the code, it's not obvious).

I like that you are using StringBuilder for concatenating strings, that is a good habit to get into.

I think you are doing too much manipulation on the years and days.  I was able to take your 5 lines of code to calculate the years and days, and make it 3

var totalDays = Math.Floor(lengthValue.TotalDays);
var years = totalDays / DaysInAYear;
var days = totalDays % DaysInAYear;

Years will be totalDays divided by the number of days in a year.  Days will be the remainder of the same division.

I would move the pluralize out into its own method.  There is no need to use an anonymous method in this instance.

You are repeating yourself when you are creating the string.  If you look closely, the code is almost identical.  The differences are easily passed in as variables.  The way I corrected this is to create a method called CreateWords.  This method returns the formatted string from variables passed in:

private string CreateWords(int value, string measure)
{
    if (value == 0) return string.Empty;

    return string.Format("{0} {1}{2}",
                value,
                measure,
                PluralSuffix(value));
}

private string PluralSuffix(int value)
{
    return value > 1 ? "s" : string.Empty
}

Your main method would then call:

builder.Append(CreateWords(years, "year"));
builder.Append(CalculateSpaceCharacter(days));
builder.Append(CreateWords(days, "day"));

where CalculateSpaceCharacter would look like:

private static string CalculateSpaceCharacter(int value)
{
    return value > 0 ? " " : string.Empty;
}

And finally, there is no need to assign the length variable at the end.  Just return builder.ToString()


Finding perimeters of right triangles with integer-length legs, up to a limit

You can rewrite it with two separate comprehensions.  One to generate the values and one to filter them out.  You can use itertools.product to get the cartesian product.

a = [x for x in (i + j + (i**2 + j**2)**0.5
                 for i, j in itertools.product(range(1, limit+1), repeat=2))
     if x <= limit]


Yeah, I'd probably redo it with an actual condition. That way, intent looks clear and is not dependent on internal code to break, continue, etc.

const int NumberOfRetries = 3;
var retryCount = NumberOfRetries;
var success = false;
while(!success && retryCount > 0)
{
   try
   {
      AttemptToConnect();
      success = true;
   }
   catch(TimeoutException tex)
   {
      retryCount--;

      if (retryCount == 0)
      {
          throw; //or handle error and break/return
      }
   }
}


Remotely collect server data using Net::OpenSSH Perl

Looks good to me. Kudos for the "... or die" idiom. More informative output would be "unable to run df on $s" or "unable to run svmon on $s".

You don't have to do tail or grep on the far end, as a line of perl could do that. But it is a perfectly clean and sensible approach, which I advocate keeping.

If you wind up with many such monitoring commands, you may find it convenient to move the post-processing into perl commands that can be refactored out as utility functions.


C++ code to find distance between line and point

Include all headers

Since you're using std::sqrt() and std::abs() you need to #include <cmath>.

Line objects can be put in an invalid state

You seem to understand that a line requires two distinct points because you say

  the code assumes that the user specifies a line by providing two distinct points

Still, it's probably better for your code to make sure start is not the same point as finish so that you can handle the error (e.g. by throwing an exception) as soon as you encounter it. This can make it easier to debug a program using your code -- as it is, I could construct a Line with the same two points and not notice later until the distance calculation returns a nonsensical result.

To make sure start != finish, make them private and provide getter and setter member functions. The setter functions should check that start and finish are not the same point. Both the setter functions and the constructor should check for this error condition.

Similarly, because all members of Line are public it's possible to break your distance calculation. Consider a slight modification to main():

int main() {
    Point p1(1, 1);
    Point p2(2, 6);
    //construct two points to form line
    Point p3(3,3);
    //construct point to find distance to line
    Line l1(p1, p2);

    // Evil
    l1.direction_vector = Vector(p2, p2);

    //make line from two points
    double res = distance_line_point(l1, p3);
    std::cout << res << std::endl;
    return 0;
}

The result is now -nan because distance_line_point() just uses Line::direction_vector without checking its validity. Not only do you need to check that Line::direction_vector uses the correct points defined by Line::start and Line::finish, you need to check that the Vector is non-zero.

The solution would be the same as before: make Line::direction_vector private and provide getter and setter functions for it (or perhaps just a getter, and re-calculate it when start or finish is modified). The setter functions for all three members of Line would need to ensure the validity of the other two.

That said...

Line should not have the member direction_vector

Two (distinct) points are all that is required for a line. You seem to be providing Line::direction_vector just so that distance_line_point() can determine the vector between the two points that define the Line. However, you can easily calculate that vector in distance_line_point(). With Line defined as you have it, you can replace

Vector AB = l.direction_vector;

with

Vector AB(l.start, l.finish);

Now you can remove Line::distance_vector.

Operator overloading

See C++ Operator overloading on Stack Overflow for general guidelines on how to overload operators. You seem to be following those guidelines pretty well for the operators you've overloaded.

However, consider adding some additional overloads that make sense. For example, these operators would come in handy if you modified Line to make sure that its two points are not the same:

inline bool operator==(const Point& lhs, const Point& rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

inline bool operator!=(const Point& lhs, const Point& rhs) {
    return !operator==(lhs, rhs);
}

Also, since you've defined * for your Vector class it would make sense to define the other operators that make sense for vectors: *=, +, +=, etc. I would be surprised to be able to multiply two Vector objects but not add them.


A few notes:

Why aren't you using stdbool.h?  Use that instead of rolling your own.
Why are you using recursion?  If you're looking for efficiency, you will use iteration in almost every single circumstance.
Why are you constraining yourself to just ints as palindromes if you are already accepting a string with your helper?  If you want to stay true to this you could keep your method that you have (with a few changes):

bool isIntPalindrome(int n)
{
    // palindromes only apply to the natural numbers
    if (n < 0) return false;

    // INT_MAX == 32767 + '\0' -> 6
    // double that to be safe on weird machines
    char temp[12];
    sprintf(temp, "%d", n);
    return isPalindrome(temp);
}

Here's my take on your problem, should be faster.  I'll provide speed test results in a bit

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>

bool isPalindrome(char* str)
{
    size_t len = strlen(str);
    for (char *ptr1 = str, *ptr2 = str + len - 1; ptr2 >= ptr1; ptr1++, ptr2--)
    {
        // not super strict check, just test if same lowercase ASCII value
        if(tolower(*ptr1) != tolower(*ptr2)) return false;
    }
    return true;
}

int main(void)
{
    puts(isPalindrome("123454321") ? "true" : "false");
    puts(isPalindrome("12") ? "true" : "false");
    puts(isPalindrome("racecar") ? "true" : "false");
    puts(isPalindrome("test") ? "true" : "false");
}

Output:

$ time ./op
true
false
# had to exclude string examples

real  0m0.025s
user  0m0.011s
sys   0m0.012s

$ time ./syb0rg
true
false
true
false

real  0m0.006s
user  0m0.001s
sys   0m0.002s

Now the resulting time differences aren't that big, but my code didn't try and put the method to its limits to really see how it would perform with something a bit bigger for example.  But in the end mine is a bit faster!


You could batch by tiletype, so that the number of buffers submitted is only n (where n is the number of tile types).

e.g.

Dictionary<TileType,List<Tuple<int,int>>> tiles = new Dictionary<TileType,List<Tuple<int,int>>>();

for (int x = Convert.ToInt32(xPos / 2) - 30; x < Convert.ToInt32(xPos / 2) + 30; x++)
{
    for (int y = Convert.ToInt32(yPos / 2); y < Convert.ToInt32(yPos / 2) + 50; y++)
    {
        if (mapXtile > 0 && mapYtile > 0 && mapXtile < Globals.mapsizex && mapYtile < Globals.mapsizey)
        {
            int currentTile = Globals.levelArray[level, mapXtile, mapYtile].TyleType;

            if(!tiles.ContainsKey((TileType)currentTile))
            {
                tiles.Add((TileType)currentTile, new List<Tuple<int,int>>());
            }
            tiles[(TileType)currentTile].Add(new Tuple<int,int>(x*2,y*2));
        }
        mapYtile = mapYtile + 1;
        //mapYtile++;
    }
    mapXtile = mapXtile + 1;
    mapYtile = Convert.ToInt32(yPos / 2);
}

foreach(var tileCoords in tiles[TyleType.grass])
{
    //You would have to modify this to append to the buffer
    createCubeVertices(tileCoords.Item1, tileCoords.Item2, 1, 0f, count, grassVertices);
    SetUpBufferIndices(count, grassIndices);
    count++;
}

foreach(var tileCoords in tiles[TyleType.water])
{
    //You would have to modify this to append to the buffer
    createCubeVertices(tileCoords.Item1, tileCoords.Item2, 1, 0f, count, waterVertices);
    SetUpBufferIndices(count, waterIndices);
    count++;
}

CopyToBuffers(grassVertices, grassIndices);
CopyToWaterBuffers(waterVertices, waterIndices);

While this does involve additional looping, the extra looping will be considerably faster than clearing / sending buffers redundantly.

On the other hand since you seem to be rendering the same couple of meshes multiple times. have you considered Instanced Rendering? That will be a significant speed up, even over batching, and should result in some cleaner code too.


Simple HttpClient usage for integration tests in .NET Core

First of all I would like to say that, in my opinion, testing API in a such way is wrong, because how does such unit test behave when:

developer machine does not have Internet connection?
developer machine does not have proper certificates?
machine that run test does not have acces to such domain?
external API URL changed?
some new requirements (headers, parameters, body) occure (assume that external API is still under development)?
external API has Internet/electricity/domain problem?

The answer is simple - it will fail. And it could lead to BROKEN WINDOWS THEORY which basically means that someone can say "ok that unit tests does not pass, so we can ignore it" or even worse: "(...) add new failing tests!".

So if you want to test external API you should use some monitoring tool and health check it. If any problem occur - contact with API owner to make him solve the problem.

Secondly, you integrate external API with some kind of version - all responses are in JSON for example. The most important thing is to stub all its possible responses - correct ones with corrupted/correct data, without any data, empty response, timeouts, responses in other formats (HTML) etc. to test whether or not your code works correctly and predictable for all these cases. If API contract will change then new use cases you will add to your integration test.

My proposition is to wrap your communication method (HttpClient) into some kind of Facade, let's name it 'ICommunicatorFacade'. Let the parameters be single your custom Request, and let it return your custom Response type (which wraps what you need from HttpClient).

interface ICommunicatorFacade
{
    Task<CustomResponse> Get(CustomRequest request);
}

That you can easily stub with NSubstitute Moq and other libraries. Also you can check whether or not your facade received correct paramters and of course how does ICommunicator user (method that invokes Get method) behave for all use cases I mentioned above.

Good luck!


Here are my observations:
LogLevel

LogLevel: Usually the industry calls this Severity Levels. I would suggest to try to follow these and do not re-invent the wheel.
In some cases it might worth to differentiate these two concepts:

Log Severity: The seriousness / weight / riskiness of a given event.
Log Level: Usually there is a particular order between the levels. The logger should log everything which is at a given level or above

For example: if you have this ordering: Debug > Information > Warning
and you set the level to Information then Debug logs will be omitted
from persistence.

Msg

Msg: Please try to avoid using abbreviations or short-forms in case of class names.
msgList: Please try to avoid Hungarian notation.
Msg.msgList: This seems quite clumsy and stuttering.

Please try to come up with better naming and encapsulation.

LogHelper

LogHelper: This is a LoggerFactory. If you have only just static members then mark your class static as well. By the way this is more like an abstract factory than a factory method.

Please read this related discussion.

throw new NullReferenceException: It is really rare to throw NullReferenceException manually. And fortunately this is not needed at all. You have at least two options:
single return statement:

ILog logger;
switch (logPlace)
{
    case "DB":
        logger = new LogDB();
        break;
    case "File":
        logger = new LogFile();
        break;
    case "Both":
        logger = new LogBoth();
        break;
    default:
        logger = new LogFile();
        break;
}

return logger;

or switch expression (in case of C# 8):
return logPlace switch
{
    "DB" => new LogDB(),
    "File" => new LogFile(),
    "Both" => new LogBoth(),
    _ => new LogFile(),
};

ILog

ILog: This should be ILogger to be precise.
void WriteLog(string msg): Usually here should the logger receive the log level / severity. Or it has several overloads with different severity levels, like LogInformation, LogWarning, LogError, etc.

Usually loggers can accept any arbitrary data (in a form of object) to give the ability to include/attach any useful information to the event.

void ExecWrite(LogLevel logLevel): Usually this is called Flush.

And usually there are some automation behind the scenes, which calls
this periodically or when the logs count reaches a given threshold.
Here you could consider to make this function asynchronous to take
advantage of async I/O (file and database writes are usually support
async I/O)

LogDb

LogDb: Yet again naming: DatabaseLogger would be way better in my opinion.
Msg.msgList.Clear(): This could be quite error-prone if you call it inside the ctor. Image the following situation: You have created a LogDb and wrote some log into it then you create a LogFile. Now all your logs are now gone.
LogDb'sExecWrite: It might make sense to use NotSupportedException if you have no willing to implement it. But in that case the whole class does not make too much sense.

LogFile

LogFile: FileLogger as a naming alternative.
LogFile' ExecWrite: This whole retry logic is quite naive. For example if the file path is invalid (pointing to a non-existing file or folder) then retrying the same action would not change anything.

With the current implementation of LogDb your catch block does
not make any sense.
Also you are swallowing the exception
without logging the fact that something went wrong.

WriteToFile: What if the file does not exists? Why do you use FileShare.ReadWrite? Why don't use async I/O?
DateTime.UtcNow.AddHours(08): This hard-coded time-zone handling makes your utility hard to maintain and even harder to make it reusable.

Also please bear in mind that all events will have the same timestamp
that are written to the file at the same time. A better approach
would be to add the timestamp to your log message at the time when
the consumer of your API calls the WriteLog method.

LogBoth

LogBoth: DatabaseAndFileLogger as a naming alternative.
LogBoth's ExecuteWrite: Here you have determined the ordering. If you have to change that then you have create a new class or create an overload.

If you would use async I/O then you could take advantage of concurrent persistence calls.
In the industry standard loggers there is no such thing like this. The consumer of your API can set up multiple sinks (persistence storage) in configuration file and the logger will take care of them.
It is quite challenging to implement it in the right way, because what should happen if either of them fails?


There are two major issues I see with your implementation, one functional, and one performance.

You have implemented the equals() method and, additionally, you have implemented the hashCode() method too. It is good that you are implementing them both, but, they are broken.

The hashCode() method only calculates the hashCode of the root node (if any), and it does not calculate it off the value in the node, but off the node itself.

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((root == null) ? 0 : root.hashCode());
    return result;
}

You do not override the hashCode of TreeNode, so the result is just a somewhat unique number, and thus, even if you have two trees with the same value at the root, they will have different hashCode values. If you override equals, you have to override hashCode, but, if you override hashCode, do it properly!

The Performance issue relates to the core addItem method. Your method is an \$O(n)\$ operation, scanning almost the entire tree, to get to the last item added.

A better algorithm would be to maintain a stack of the path to the most recently added node's parent. This would be maintained at the same time as the root node.... consider:

Deque<TreeNode<T>> insertPoint = new LinkedList<>();
TreeNode root = null;

Then, when you add an item:

/**
 * Adds item, such the tree is a complete binary tree.
 *
 * @param item the item to be added.
 */
public void addItem(T item) {

    if (root == null) {
        root = new TreeNode<T>(item);
        return;
    }

    if (!insertedAt.isEmpty() && insertedAt.peek().right != null) {
        TreeNode<T> kid = insertedAt.pop();
        while (!insertedAt.isEmpty() && kid == insertedAt.peek().right) {
            kid = insertedAt.pop();
        }
        if (!insertedAt.isEmpty()) {
            kid = insertedAt.peek();
            kid = kid.right;
            insertedAt.push(kid);
            while (kid.left != null) {
                kid = kid.left;
                insertedAt.push(kid);
            }
        }
    }

    if (insertedAt.isEmpty()) {
        // filled the leaf row, go down the left edge again.
        TreeNode<T> node = root;
        while (node != null) {
            insertedAt.push(node);
            node = node.left;
        }
    }

    TreeNode<T> node = insertedAt.peek();
    TreeNode<T> toadd = new TreeNode<>(item);
    if (node.left == null) {
        node.left = toadd;
    } else {
        node.right = toadd;
    }

}

What the above code does, is keep the most recently added-to node at the top of the stack. Then, if the node can still be added to, it fills it.

If the node is now full, it goes back up the tree, looking for the next insertion point, which may nto exist on this level. If it does not then it goes all the way down the left edge and starts a new level....

This means that, for many inserts (half of them?), the performance is \$O(1)\$ and for the worst case, when you have just completed a level of the tree, and you have to start over again at the left, it requires one walk up the right edge, and back down the left edge, in an \$O(\log{n})\$ operation.

So, this brings the process from a \$O(n)\$ operation with \$O(\log{n})\$ space complexity, to a worst-case \$O(\log{n})\$ operation with \$O(\log{n})\$ space as well.


Somewhat obvious rule: the good way to avoid repetition is always to factorize as much as possible.

Here this can be achieved for all but page-flickity of your targets, which are almost identical: only involved elements and added/removed class-names vary.
It already reduces the code to add listeners, like this:

function customCursor() {
  const
    todo = {
      'previous': [false, 'previous'],
      'next': [false, 'next'],
      'brand-logo': [false, 'hidden'],
      'nav-button': [false, 'hidden'],
      'carousel-cell__link': [true, 'link']
    },
    events = {'mouseover': true, 'mouseleave': false},
    cursorContainer = this.cursorContainer,
    cursorOffset = {left : 50, top  : 50};

  document.querySelector('.page-flickity').addEventListener(
    'mousemove',
    function (e) {
      cursorContainer.style.left = (e.pageX - cursorOffset.left) + 'px';
      cursorContainer.style.top = (e.pageY - cursorOffset.top) + 'px';
    },
    false
  );

  var className, action, elements, i, n;
  for (className in todo) {
    action = todo[className];
    elements = action[0]
      ? document.querySelectorAll(className)
      : [document.querySelector(className)];
    for (i = 0, n = elements.length; i < n; i++) {
      for (var event in events) {
        elements[i].addEventListener(
          event,
          () => cursorContainer.classList.toggle(action[1], events[event])
        )
      }
    }
  }
}

The first important point is the todo object, where we register all targets:

each key is the class-name to operate querySelector[All] on
the corresponding value states true/false to indicate if all elements must be selected or not, and the class-name which will be added/removed when the mouse events occur

Based on that we iterate this object, then for each target we iterate the collection of involved elements (note that the unique element returned by querySelector is turned into an array).

Then it becomes pretty easy to adapt it for also removing them.
This is achieved by introducing a "listeners archive", populated when adding listeners, then returned by the function:

function customCursor(listeners) {
  const
    todo = {
      'previous': [false, 'previous'],
      'next': [false, 'next'],
      'brand-logo': [false, 'hidden'],
      'nav-button': [false, 'hidden'],
      'carousel-cell__link': [true, 'link']
    },
    events = {
      'mouseover': true,
      'mouseleave': false
    },
    cursorContainer = this.cursorContainer,
    cursorOffset = {left : 50, top  : 50};

  document.querySelector('.page-flickity').addEventListener(
    'mousemove',
    function (e) {
      cursorContainer.style.left = (e.pageX - cursorOffset.left) + 'px';
      cursorContainer.style.top = (e.pageY - cursorOffset.top) + 'px';
    },
    false
  );

  addListeners = !listeners;
  listeners = listeners || [];

  var className, action, elements, element, i, n;
  if (addListeners) {
    for (className in todo) {
      action = todo[className];
      elements = action[0]
        ? document.querySelectorAll(className)
        : [document.querySelector(className)];
      for (i = 0, n = elements.length; i < n; i++) {
        element = elements[i];
        for (var event in events) {
          listener = function() {
            cursorContainer.classList.toggle(action[1], events[event])
          };
          element.addEventListener(event, listener);
          listeners.push([element, event, listener]);
        }
      }
    }
    return listeners;
  } else {
    for (i in listeners) {
      listener = listeners[i];
      listener[0].removeEventListener(listener[1], listener[2]);
    }
  }
}

(please note: I didn't do anything about the "lonely" event about page-flickity element; you may do your own here)

Then it's up to you to pass this archive in to the function when you want to remove these listeners:

// add listeners:
var listeners = customCursor();

// remove listeners:
customCursor(listeners);


I think you have misunderstood the part about "assume that the string has sufficient space at the end", and as a result, you have some memory management issues.  I think that the intention is to assure you that your replaceChars() function will be handed a buffer of sufficient size such that you may write the result in place, without allocating more memory.

In that light, your solution and tests look a bit confused — and in fact the code is wrong in the general case.  If the input is "Mr␠John␠Smith␠␠␠␠", and you countSpaces() without taking the true length (13) into account, then countSpaces() would report that there are 6 spaces rather than 2.  To compensate for the overestimate, you then use the formula int stringLength = length + x - x/3; — allocating roughly \$\frac{2}{3}\$ of an additional byte for each space, rather than two extra bytes per space.  And you are also relying on that dubious estimate of the result length to terminate your loop, with while (i < stringLength).

Suggested solution

#include <stdlib.h>
#include <assert.h>
#include <string.h>

// Count the spaces in the first n bytes of str
int countSpaces(const char* str, int n) {
  int count = 0;
  while (n --> 0) {
    if (*str++ == ' ') {
      count++;
    }
  }
  return count;
}

char* replaceChars(char* str, int length) {
  int spaces = countSpaces(str, length);
  char *in = str + length - 1,
       *out = str + length + 2 * spaces;
  *out-- = '\0';
  while (in != out) {
    if (*in == ' ') {
      out -= 3;
      in--;
      *(out + 1) = '%';
      *(out + 2) = '2';
      *(out + 3) = '0';
    } else {
      *out-- = *in--;
    }
  }
  return str;
}

int main() {
  const char *test1 = "Mr John Smith";
  char buf1[18] = {0};
  strcpy(buf1, test1);
  replaceChars(buf1, strlen(test1));
  assert(strcmp("Mr%20John%20Smith", buf1) == 0);

  const char *test2 = "lol  lol lol";
  char buf2[19] = {0};
  strcpy(buf2, test2);
  replaceChars(buf2, strlen(test2));
  assert(strcmp("lol%20%20lol%20lol", buf2) == 0);

  const char *test3 = "";
  char buf3[1] = {0};
  strcpy(buf3, test3);
  replaceChars(buf3, strlen(test3));
  assert(strcmp("", buf3) == 0);
}


Initializing entity framework context in constructor

It is safe to use the context the way you are using it. However, I don't think you will be able to write unit test. This isn't bad in itself. It does become an issue when your business logic is middle tier. Also why aren't you all using the rest standard instead of your perform method? Rest leaverages http to make your api more clear and interoperable.


A simple AngularJS application for counting the number of gallons of paint

Feedback
The code looks pretty good, and thus I only found a few things that I could change (listed below). I like how the bootstrap text-center class can be applied once to affect all sub-elements.
Suggestions
CSS
Move the in-line styles to the stylesheet to reduce redundancy - e.g. the number inputs have a specific width, which can be put into a CSS rule-set, like this example:
input[type="number"] {
  width: 90px;
}

Or apply a class name to those elements and utilize that class name in the selector. Also, the width of the container (i.e. 500px) can be moved into a rule-set.
JavaScript
Declaring the Constant
The idiomatic way of declaring a constant in AngularJS is to use .constant() and use dependency injection to inject that constant in the controller.
.constant('SQUARE_FEET_FOR_ONE_GALLON', 350)

Then that value will be available for injection in the controller (this example uses the implicit format:
.controller('paintCalculatorController', function($scope, SQUARE_FEET_FOR_ONE_GALLON){

If nobody else is planning to work on this small amount of code with you, then using a plain JavaScript constant should be fine.
Slight redundancy
Gerrit0 is correct in the comment: "maybe using $scope.square in $scope.countGallon"
The function countGallon() can be updated to updated to utilize the count() function. The formula for the square footage likely won't change anytime soon, but if it did, then that could be updated in a single place instead of both places. This complies with the Don't Repeat Yourself principle.
return Math.ceil($scope.count() / squareFeetForOneGallon);


Determine which range a character falls into

Those "parent groups" look a lot like regular expressions, specifically character sets.  You could perform regular expression matches for patterns like ^[A-F].

function parentGroup(char) {
    var groups = ['A-F', 'G-M', 'N-R', 'S-Z', '0-9'];
    for (var i = 0; i < groups.length; i++) {
        if (char.match('^[' + groups[i] + ']')) {
            return groups[i];
        }
    }
}

document.getElementById('in').addEventListener('keyup', function(e) {
    document.getElementById('out').textContent = parentGroup(e.target.value);
});

Enter text, starting with a digit or uppercase letter: <input id="in" type="text" size="10">

Parent group:


What stands out to me is that you initially perform a check against every grade range and insert true into the map in the right one. By that point, you've already found which grade is right. But then you initiate another loop to start searching for the grade corresponding to true.

I think instead, you ought to alter your method to output a Grade enum, and delegate the string handling to another function. I feel that it's better practice to return a Grade Enum from the first method because of the strong typing-- you may want to use this information for other methods besides finding the grade name. In fact, Enums are particularly nice because you can use a switch on them.

public Grade gradeBy(int grade) {
    if (grade < 50) return Grade.F;
    if (grade < 61) return Grade.D;
    if (grade < 71) return Grade.C;
    if (grade < 81) return Grade.B;
    if (grade<=100) return Grade.A;
    return Grade.F;
}
public String gradeName(Grade g) {
    return g.name()
}

Notice how as soon as the grade matches the range corresponding to something in the Grade Enum, the method immediately returns. Now an example of how you might use that switch:

public String gradeComment(Grade g) {
    switch(g) {
        case F:
        return "You need to work harder!";
        case D:
        return "I think you can do better.";
        case C:
        return "Satisfactory.";
        case B:
        return "Nice job.";
        case A:
        return "Well done!";
        default:
        return "N/A";
    }
}

Not that you need these grade messages, but that's an example of the power of holding on to the Enum type rather than converting the int grade directly into a String.

Sorry if I've made syntax errors as I've not used Java in a while.

Edit: Just realised that you might like to put gradeBy, gradeName and gradeComment into the Grade Enum itself as static methods.


Check database for item and create it if it doesn't exist

You don't need the empty if branches. An if without an else automatically returns unit. So you can simplify it to:

let saveTag question =

    if question.Tag <> null then
        let tagCount =
            query{
                for row in db.Tags_Tags_Tags do
                where (row.Tag = question.Tag)
                select row
                count
            }

        if tagCount = 0 then
            let tagToSave =
                dbSchema.ServiceTypes.Tags_Tags_Tags(
                    Tag = question.Tag
                )
            insertRowIn db.Tags_Tags_Tags tagToSave
            saveToDb()


Let me make a few comments:

F# has a good system of type inference. You don't need to specify the type explicitly, the compiler in many cases will do it for you. You can read more about it here.
In function getValue. Usually, matched with None|Some value:

match Map.tryFind position memory with
    | None  -> 0
    | Some value -> value

Although you can rewrite this code with using defaultArg

let getValue position memory =
    defaultArg (Map.tryFind position memory) 0

In function updateIndex you can check the value with 0 in match:

let updateIndex (code:string) index value =
    match code.[index], value = 0 with
    | '[', true  -> findMatch code ']' '['  1 (index + 1) 0
    | ']', false -> findMatch code '[' ']' -1 (index - 1) 0
    | _      -> index + 1

The helper functions better write as nested:

let interpret (code:string) =
    let rec interpretHelper index memory position =

You can read more about it here
In function interpretHelper, use if-then-else instead of PM:

let rec interpretHelper index memory position =
    if code |> String.length = index  then
        memory
    else ...


public bool TryAdd(T value)

A method that intentionally doesn't work when there is contention? I don't see how would that be ever useful.

internal BoxItem<T> Next
{
    get { return _next; }
    set { _next = value; }
}

You could have used an autoproperty here.

yield break;

Adding yield break; at the end of iterator method is the same as adding return; at te end of a normal void method: the method would work exactly the same without it.

public IEnumerable<T> ToEnumerable()

I don't see how would this method be useful. Especially since there already is AsEnumerable() extension method that does exactly the same thing.


Initializing a variable with a function reference (PHP)

Clean Code, Chapter 3. Functions has some guidance:

  Have No Side Effects

  Side effects are lies. Your function promises to do one thing, but it also does other hidden
  things.

  [...]

  Anything that forces you to check the function signature is equivalent to a double-take. It’s
  a cognitive break and should be avoided.

The side effect here is that the function changes the argument. A more readable approach would be returning the API version (instead of true/false) or throwing an exception in case of errors.

$app->soapAPIVersion($apiVersion);
$_SESSION['apiVersion'] = $apiVersion;

Note that the code should check the return value of soapAPIVersion and handle false somehow.
The soapAPIVersion name is unclear. What does it do with the API version? From Clean Code, Chapter 2: Meaningful Names:

  Method Names

  Methods should have verb or verb phrase names like postPayment, deletePage, or save.
  Accessors, mutators, and predicates should be named for their value and prefixed with get,
  set, and is according to the javabean standard.

I'd rename it to getApiVersion or fetchApiVersion.

Note the camelCase too which is usually easier to read. From Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions:

  While uppercase may be more common,
  a strong argument can made in favor of capitalizing only the first
  letter: even if multiple acronyms occur back-to-back, you can still
  tell where one word starts and the next word ends.
  Which class name would you rather see, HTTPURL or HttpUrl?


Roll the dice - to give a random output with a die

@janos already covered this a little bit, but if you want to use the built-in random(x, y) used in Processing.JS, I'd do something like this:

var numberOfDots = random(1, 6);

But, we need to do one more thing. Since the random(x, y) function in Processing.JS can return non-integer results, we need to use the floor function to round the returned value down, and then add one. This means that your calculation simply becomes this:

var numberOfDots = floor(random(1, 6)) + 1;

Now you should be able to generate random numbers from 1-6 in a cleaner, and more readable manner.

I've also noticed that you're repeating a lot of code. @Caridorc already touched on this a little bit, but I'm going to expand on it a bit further. Rather than keeping it in the mouseClicked override, you can simply put it at the top of your code like this:

fill(245, 242, 242);
rect(100, 100, 200, 200);

mouseClicked = function() {
    ...
}

This is a good thing to remember when you're doing graphics programming. If there's no need to re-draw something every frame, or click, then don't. In this case, you don't need to re-draw and fill the rectangle, so it can be moved entirely out of the mouseClicked override. In the case of this program though, I felt that the rectangle wasn't needed, so I just removed it altogether.

Expanding on the subject of code repetition, you're also repeating a lot of ellipse calls. I'd highly suggest implementing a function that automatically draws x amount of circles for you. This is what I came up with:

var drawDiceDots = function(dotPositions, dotDiameter) {
    for(var i = 0; i <= dotPositions.length - 1; ++i) {
        ellipse(dotPositions[i][0], dotPositions[i][1], dotDiameter, dotDiameter);
    }
};

To use this function, you supply a list of x-y positions in the format [[x, y], ...]. For example, in order to render the dots on the 6-dot side of a die, you'd do this:

drawDiceDots([
    [150, 150],
    [150, 250],
    [250, 250],
    [250, 150],
    [250, 200],
    [150, 200]
], 45);

Finally, rather than using a chain of if statements, I'd recommend using a switch/case construct. A typical switch/case construct looks something like this:

switch(someVariable) {
    case someValue:
        ...
        break;

    ...
}

But, we can get better than a chain of if statements. We can either use a JavaScript object or a list. In this case, I'm going to use a list. To do this, you'd first create a list that looks like this:

var possibleDiceFaces = [
    [100, [200, 200]],
    [70, [150, 150], [250, 250]],
    [60, [150, 150], [200, 200], [250, 250]],
    [60, [150, 150], [150, 250], [250, 250],[250, 150]],
    [60, [150, 150], [150, 250], [250, 250], [250, 150], [200, 200]],
    [45, [150, 150], [150, 250], [250, 250], [250, 150], [250, 200], [150, 200]]
];

The first value of each list is the diameter of the circles, and the rest are positions. The nice thing about this is that it's easily expandable, rather than having to add a new case or if statement each time you want to add a "side".

In addition, thanks to the tips from @Jonah, I'd also recommend the following things:

Separate responsibilities, e.g, simply call a dice drawing function in the mouseClick override, rather than having a huge pile of case statements.
Use more domain-oriented names for things, rather than implementation-oriented.

After making all these changes, plus a few more, I ended up with the following, improved (hopefully) code:

/**
 * Draw x amount of dots given a list of positions
 * for a dice.
 * @param {list[][]} dotPositions - A list of dot positions in the form [x, y].
 * @param {number}   dotDiameter  - The diameter of the dots.
 */
var drawDiceDots = function(dotPositions, dotDiameter) {
    for(var i = 1; i <= dotPositions.length - 1; ++i) {
        fill(0, 0, 0);
        ellipse(dotPositions[i][0], dotPositions[i][1], dotDiameter, dotDiameter);
    }
};

/**
 * Draw the fact of a dice. By default, there are 6 different faces,
 * but this number can be changed to add more.
 */
var drawDiceFace = function(rolledNumber) {
    var possibleDiceFaces = [
        [100, [200, 200]],
        [70, [150, 150], [250, 250]],
        [60, [150, 150], [200, 200], [250, 250]],
        [60, [150, 150], [150, 250], [250, 250],[250, 150]],
        [60, [150, 150], [150, 250], [250, 250], [250, 150], [200, 200]],
        [45, [150, 150], [150, 250], [250, 250], [250, 150], [250, 200], [150, 200]]
    ];

    if(rolledNumber in possibleDiceFaces) {
        drawDiceDots(possibleDiceFaces[rolledNumber], possibleDiceFaces[rolledNumber][0]);
    }
    else {
        throw "The rolled number specified is not valid.";
    }
};

mouseClicked = function() {
    background(255, 255, 255);
    var rolledNumber = floor(random(1, 6)) + 1;
    drawDiceFace(rolledNumber);
};

Finally, I'd just like to nitpick a few things:

Generally you should write braces in JavaScript on the same line as the declaration, due to evil things like automatic semicolon insertion.
You should properly indent everything, including comments.
Don't use comments when your code is self-explanatory.

Other than that, nice work! :)


Modification of javascript inheritance framework

Easy question first : Is it written correctly?

Class.prototype.set = function(attrs) {
  for (var attr in attrs) {
    //if exist setter function this.on_change{key of wrap: function(key of wrap, new value)
    if(this.on_change[attr])this.on_change[attr].call(this,attr,attrs[attr]);
    else this[attr] = attrs[attr];
  }
  return this;
};
if(!Class.prototype.on_change)Class.prototype.on_change={};

attrs is not a good name, it does not contain a list of attributes, but a list of name/value pairs, I would suggest the Spartan o for Object or maybe map.
Dropping the curly braces in your if statement is ok, dropping the newlines not so much
The one line of comment is not very helpful :\
You could use the following for initialization of on_change :
Class.prototype.on_change = Class.prototype.on_change || {};
on_change is not lowerCamelCase -> onChange would be more idiomatic.

I would counter suggest:

Class.prototype.set = function( map ){
  for ( var attributeName in map ) {
    var value  = map[attributeName],
        setter = this.onChange[attributeName];
    if( setter )
      setter.call( this, attributeName, value );
    else
      this[attributeName] = value;
  }
  return this;
};
Class.prototype.onChange = Class.prototype.onChange || {};

Hard question: Can you see some undesired behavior?

Yes.

Providing onChange is old skool, real events use addEventListener.
There are now 2 ways to change a property, thru set and thru changing properties directly. The setter functions only work for set, this will introduce bugs.
You are counting on the setter to do the assignment,  another possible source of bugs. I would do the assignment regardless, rename setter to listener and then execute the listener:

this[attributeName] = value;
if( listener )
  listener.call( this, attributeName, value );


title

It’s better for usability to use "page-title - site-name" instead of "site-name - page-title".

But for the homepage, you might want to omit the page-title ("Home"), as the site/domain name only typically represents the homepage.

<title>SigmaCubes</title>

Error messages

You shouldn’t use a heading element for the content, as this creates an outline that’s not useful. Use p instead. And to convey the importance of the error, you could use the strong element.

Error

Old Internet Explorer is not supported

You should add the hidden attribute to your error messages, and remove it as soon as the error becomes relevant. Otherwise the markup affects your outline (i.e., you have all possible errors listed at the top of the document outline).

(For the error about disabled JavaScript, you’d need to add the hidden attribute via JS itself, of course.)

alt for logo

The alt attribute for a logo shouldn’t contain the term "logo" (unless that’s part of the name, of course). Just use the site name.

alt="SigmaCubes"

Navigation

Use the nav element for the navigation.

Use a ul element for the navigation links (without a list, you should use some kind of textual delimiter separating the navigation links, e.g. for text browsers).


First, I'd like to echo @Mat'sMug's distaste for your multi-lined Dim statements.  There's absolutely no reason to do this at all having them prefixed with Dim makes it completely obvious that I'm looking at a declaration block.  It took me a good minute to realize that it wasn't a continuation of Sub declaration, because the Dim literally disappears into a huge wall of code. You aren't saving any time typing it either - last time I checked, Dim and , _ were both 3 characters, and the former is a lot easier to type on a qwerty keyboard.

The other answers hint around the performance, but I'll just come right out and say it.  Your Sub should really be named the AntiPerfWrap.  First, every single call that Application.Run makes is late bound - even for Excel objects.  It has to be, because like CallByName, it is forced to call IDispactch.GetIDsOfNames on itself.  This is always slower than an early bound call - period, end of discussion.

You always cache the ActiveWorkbook and ActiveSheet regardless of whether it is necessary or not.  I would guess that roughly 1% of all the code I've written requires this.  Same thing with .Calculation.  Same thing with .EnableEvents.  Do I write another PerfWrapWithEvents if I need that turned on?  Or maybe PerfWrapWithEventsAllowCalculation?  None of this work is free, and it seems like a jumbled collection of "this will make your code go faster anecdotes" collected from SO comments.  The cargo cult has found thier messiah in this wrapper.

DoEvents is not free.  In fact it's the complete opposite.  It yields the processor to every other thread that needs to clear it's event queue.  It also makes absolutely no sense to call DoEvents when you've explicitly disabled 95% of the functionality that would make the call useful.

Brass tacks time - let's see how much overhead this wrapper really adds.  This is the called routine:

Public Sub UnderTest()
    Dim i As Long
    For i = 1 To 10
        Debug.Print i
    Next
End Sub

And the baseline benchmark:

Public Sub BenchmarkOne()
    Dim starting As Single
    starting = Timer

    Dim i As Long
    For i = 1 To 100
        Sheet1.UnderTest
    Next

    Debug.Print "Unwrapped: " & Timer - starting
End Sub

  Unwrapped: 0.8515625

Public Sub BenchmarkTwo()
    Dim starting As Single
    starting = Timer

    Dim i As Long
    For i = 1 To 100
        PerfWrap "Sheet1.UnderTest"
    Next

    Debug.Print "Wrapped: " & Timer - starting
End Sub

  Wrapped: 6.492188

Ouch.

Conclusion - Burn it.  Burn it with fire.  The premise behind the code is that there is a common set of operations that you can do to "speed up" code.  In fact, this is never true.  In reality, you are turning off Excel functionality that can slow down code.  There's a big difference.  If you approach performance issues by looking outside of code that you've written, you're starting out looking in the wrong direction.  A catch-all "solution" for performance simply doesn't exist, so I wouldn't pretend to be providing it.  The best way to look at it is to imagine that any code under performance review to be copied and pasted in place of this...

If ArgumentsToPass <> vbNullString Then
    Application.Run SubNameToRun, ArgumentsToPass
Else
    Application.Run SubNameToRun
End If

...then do a code review on the entire thing.  Ask yourself, "In the context of the full Sub, what is the reason for every single line of code other than part above"? I'm guessing that in roughly 99.99% of cases, there won't be a good answer for all of them.


Counting Ways to Make Change -- Is this good functional/Lisp style?

Well, I could try to rewrite it to not use mutation, but it looks like the mutation is just there as a memoization optimization.  You could either pass the vector as an argument into calculate, or you could abstract the memoization via something like define/memo provided in memoize.plt, or just roll your own customized one as done here, which I think is just fine.

There are some surface changes you can make as well.  For starters, the search-for function doesn't do anything with its arguments, so they can be removed.  Next, defines have an explicit begin around the body, so the begin in update can be removed as can the begin near what your comments call the entry point.

The (init-table 4) is an optimization (works without it) that I'm not sure is even worth putting in; especially since I think it deserves a comment to explain that the magic number 4 is because (make-change n) should return 1 for 1 <= n <= 4. If you decide to leave it in, at least replace it by (vector-fill! v 1 0 4) assuming your using srfi-43.  It might be different if your scheme dialect has it's own vector libs.

Finally, mapping coin number to value could use case  instead of cond for a little less syntax as in:

(define (coin-value n)
  (case n
    ((1) 1)
    ((2) 5)
    ((3) 10)
    ((4) 25)
    ((5) 50)))


A DRYer version of your code could be:

function prepare(elem, rate, width) {
    var width = 0;
    return function frame() {
        if (width >= 100) return;
        width += rate;
        elem.style.width = width + '%';
        setTimeout(frame, 5);
    }
}

function move() {
    ['ribbon-part-1', 'ribbon-part-2', 'ribbon-part-3', 'ribbon-part-4', 'end-ribbon'].forEach(function(id, i) {
            var el = document.getElementById(id);
            setTimeout(prepare(el, i == 0 ? 1 : 2), i * 300);
    });
}

jsFiddle: https://jsfiddle.net/wLwo0vs6/

I use the ids of the elements to determine how many parts/things that has to move and like that I don't have to hard code stuff. You could also get them from the DOM knowing the starting button that was pressed. This way you could use the exact same code for all the places you have.

But I don't like the animation not being synced properly, the correct for me would be that when one section reached 100% the next section would start the animation. So I suggest a modification that could be done like this:

function prepare(elems, width) {
    var width = 0;
    var elem = elems.shift();
    return function frame() {
        if (width >= 100) {
            elem = elems.shift();
            if (!elem) return;
            width = 0;
        } else {
            width++;
            elem.style.width = width + '%';
        };
        setTimeout(frame, 5);
    }
}

function move() {
    var elements = ['ribbon-part-1', 'ribbon-part-2', 'ribbon-part-3', 'ribbon-part-4', 'end-ribbon'].map(function(id) {
        return document.getElementById(id);
    });
    setTimeout(prepare(elements), 300);
}

jsFiddle: https://jsfiddle.net/db8hbpry/

The missing part is the logic for accelerating. If you know what you want there I can adjust.

More than this, small things could be more pressed, but I think it would reduce readability.


ObservingCache - scheduled task executor that returns a result

Class is open to modification

ObservingCache should be closed for modification, this is the OCP principle. If it's not, its behaviour can be altered (by inheritance for example) and can lead to an unpredictable behaviour which make it rather difficult to test and maintain.

How to achieve that ? Mark ObservableCache final.

Executor never shutdowned

Once started, the executor can never get shutdown, which causes the task to be run indefinitly.

How to achieve that ? Create a method:

/**
 * Once called, the cached value won't be updated anymore.
 */
public void stopObserving() {
    executor.shutdownNow();
}

firstRunBlocking

This parameter is the thing that bothers me the most in your class, and also the one who gave me the most trouble when trying to remove it.

Why does it bothers me ? Everytime you have a boolean in a method (or constructor), it's a sign of poor design because the class/method should do 2 things now (one for each boolean's value), therefore violating the single responsibility principle. It makes your code hardest to test and to maintain because of the conditionnal logic flow.

If I understand correctly, the purpose of this flag is to avoid client code retrieving a null when calling getItem because the cache has not been updated at least once. I would rather resolve this problem by blocking in getItem as long as the cache has not been computed once. In Java, one have the CountDownLatch who is a thread-safe class able to fulfill this responsibility by blocking only until the cache is computed the first time.

I came up with the following wrapper to achieve that:

public class BlockingHolder<T> {
    private T value;
    private final CountDownLatch barrier = new CountDownLatch(1);

    public T get() {
        try {
            barrier.await();
            return value;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void set(T value) {
        this.value = value;
        barrier.countDown();
    }
}

Final solution

All these remarks put together, I came up with the following solution. Note that BlockingHolder is an inner class because it doesn't have to be known in the outside world.

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public final class ObservingCache<T> {
    private final BlockingHolder<T> holder;
    private final ScheduledExecutorService executor;

    /**
     * The cache will be refreshed every 10 minutes
     */
    public ObservingCache(Supplier<? extends T> syncFunc) {
        this(syncFunc, 10 * 60 * 1000);
    }

    public ObservingCache(Supplier<? extends T> syncFunc, int refreshIntervalMillis) {
        this.holder = new BlockingHolder<>();
        this.executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(() -> holder.set(syncFunc.get()), 0, refreshIntervalMillis, TimeUnit.MILLISECONDS);
    }

    /**
     * Blocks until the cached value has been computed at least once
     */
    public T getItem() {
        return holder.get();
    }

    /**
     * Once called, the cached value won't be updated anymore.
     */
    public void stopObserving() {
        executor.shutdownNow();
    }

    private static class BlockingHolder<T> {
        private T value;
        private final CountDownLatch barrier = new CountDownLatch(1);

        public T get() {
            try {
                barrier.await();
                return value;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        public void set(T value) {
            this.value = value;
            barrier.countDown();
        }
    }
}

Update: taking into account firstRunBlocking

This is how I would fully replace a boolean into a business class. It looks like overkill but in reality it's not. Each class has a single responsibility, is testable and maintainable.

ObservingCache is now abstract because the "blocking" behaviour can't be defined here but only in suclasses.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public abstract class ObservingCache<T> {
    /**
     * 10 minutes
     */
    public static final int DEFAULT_CACHE_REFRESH_INTERVAL = 10 * 60 * 1000;

    private final ScheduledExecutorService executor;

    public ObservingCache(Supplier<? extends T> syncFunc, int refreshIntervalMillis) {
        this.executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(() -> setItem(syncFunc.get()), 0, refreshIntervalMillis, TimeUnit.MILLISECONDS);
    }

    public abstract T getItem();

    protected abstract void setItem(T value);

    /**
     * Once called, the cached value won't be updated anymore.
     */
    public final void stopObserving() {
        executor.shutdownNow();
    }
}

BlockingCache contains only notion of blocking until the value is not computed. How the value is computed is totally abstracted here.

import java.util.concurrent.CountDownLatch;
import java.util.function.Supplier;

public final class BlockingCache<T> extends ObservingCache<T> {
    private final BlockingHolder<T> holder;

    public BlockingCache(Supplier<? extends T> syncFunc, int refreshIntervalMillis) {
        super(syncFunc, refreshIntervalMillis);
        this.holder = new BlockingHolder<>();
    }

    /**
     * Blocks until the cached value has been computed at least once
     */
    @Override
    public T getItem() {
        return holder.get();
    }

    @Override
    protected void setItem(T value) {
        holder.set(value);
    }

    private static class BlockingHolder<T> {
        private T value;
        private final CountDownLatch barrier = new CountDownLatch(1);

        public T get() {
            try {
                barrier.await();
                return value;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        public void set(T value) {
            this.value = value;
            barrier.countDown();
        }
    }
}

And finally, the cache that doesn't block but can return null (that I personnaly would never use):

import java.util.function.Supplier;

public final class NonBlockingCache<T> extends ObservingCache<T> {
    private volatile T value;

    public NonBlockingCache(Supplier<? extends T> syncFunc, int refreshIntervalMillis) {
        super(syncFunc, refreshIntervalMillis);
    }

    /**
     * Never blocks. Returns null if the value has not been computed !
     * Otherwise, returns the cached value.
     */
    @Override
    public T getItem() {
        return value;
    }

    @Override
    protected void setItem(T value) {
        this.value = value;
    }
}


Sheriff voice: Halt! You are breaking the laws!

Your monad breaks the right- and left-identity law of >>=:

k        >>= return = k   -- right identity
return a >>= f      = f a -- left  identity

Suddenly, it makes a big difference whether I call return at the end of my function:

do
   replicateM 9 actions        -- fine

do
   k <- replicateM 9 actions
   return k                     -- fails

That simply breaks to much. Your Monad is also missing its Functor and Applicative instances, which would make it easy to "cheat". And if you implemented a fmap that limits the number of fmaps, you start to break Functor laws. Note that due to the Monad/Functor laws, we should be able to rewrite

limitedFactorial :: Int -> Limiter Int
limitedFactorial 1 = return 1
limitedFactorial n = do
    recursive <- limitedFactorial (n - 1)
    return $ n * recursive

to

limitedFactorial :: Int -> Limiter Int
limitedFactorial 1 = return 1
limitedFactorial n = fmap (n *) $ limitedFactorial (n - 1)

If you were to limit that, you would break fmap id = id immediately.

But even without all of these quirks, at long last, there's nothing preventing the user to use recursion:

example :: Limit Int
example = return 1      -- fine

evil :: Int -> a -> Int
evil x _ = if x > 0 then 1 + evil (x - 1) undefined else 0

do
    liftM (evil 100000000) example -- recursion!

So conceptionally, your Monad is broken, unfortunately.

Further review

Your code uses names from your imports. state is a function defined in Control.Monad.State, so it makes your instance slightly hard to read.
You use increment only once, so it makes sense to inline it.