Check if two numbers are the same in a box

Avoid magic numbers

int box1[3][3];

for (int i = 0; i <= 2; i++){
    for (int j = 0; j <= 2; j++){

Rather than manually strewing 3s and 2s throughout the code, just declare a constant:

const int SQUARE_SIZE = 3;

Then you can say things like

int box1[SQUARE_SIZE][SQUARE_SIZE];

for (int i = 0; i < SQUARE_SIZE; i++) {
    for (int j = 0; j < SQUARE_SIZE; j++) {

Changing the <= to < allows use of the same constant in both places.

Why copy?

if (box1[0][0] != 0){
    if (box1[0][0] == box1[0][1] || box1[0][0] == box1[0][2] || box1[0][0] == box1[1][0] || box1[0][0] == box1[1][1]
        || box1[0][0] == box1[1][2] || box1[0][0] == box1[2][0] || box1[0][0] == box1[2][1] || box1[0][0] == box1[2][2]){
        return true;
    }
}

You copy a bunch of values from board to box1.  Why?

You could just replace all that with

if (board[0][0] != 0) {
    return false;
}

if (board[0][0] == board[0][1] || board[0][0] == board[0][2]
 || board[0][0] == board[1][0] || board[0][0] == board[1][1] || board[0][0] == board[1][2]
 || board[0][0] == board[2][0] || board[0][0] == board[2][1] || board[0][0] == board[2][2]) {
    return true;
}

Or the shorter

if (board[0][0] != 0) {
    return false;
}

for (int i = 0; i < SQUARE_SIZE; ++i) {
    for (int j = ((i > 0) ? 0 : 1); j < SQUARE_SIZE; ++j) {
        if (board[0][0] == board[i][j]) {
            return true;
        }
    }
}

return false;

Of course, that approach only really works on the corners.

Pick a different data structure or structures

You want to be able to answer the question:  is there more than one box with the same number?  So why not save the data in a structure than answers that?  E.g.

const int BOARD_SIZE = 9;

bool available_rows[BOARD_SIZE][BOARD_SIZE + 1];

for (int i = 0; i < BOARD_SIZE; ++i) {
    available_rows[i][0] = false;
    for (int j = 1; j <= BOARD_SIZE; ++j) {
        available_rows[i][j] = true;
    }
}

Then whenever you go to use a number, you say something like

if (available_rows[row][number] && available_columns[column][number] && available_squares[row/SQUARE_SIZE][column/SQUARE_SIZE][number]) {
    available_rows[row][number] = false;
    available_columns[column][number] = false;
    available_squares[row/SQUARE_SIZE][column/SQUARE_SIZE][number] = false;

    board[row][column] = number;
} else {
    // throw exception?  Or otherwise handle an invalid selection.
}

This does more work when selecting a number, but it self-maintains a valid board.  This is a common result in computer science.  It is often better to do work once and store it than to redo the same work repeatedly.

Note:  but not always.  :)

You can also build these structures inside an isValid function if you want.

bool isValid() {
    bool available_rows[BOARD_SIZE][BOARD_SIZE + 1];

    for (int i = 0; i < BOARD_SIZE; ++i) {
        available_rows[i][0] = false;
        for (int j = 1; j <= BOARD_SIZE; ++j) {
            available_rows[i][j] = true;
        }
    }

    bool available_columns[BOARD_SIZE][BOARD_SIZE + 1];

    for (int i = 0; i < BOARD_SIZE; ++i) {
        available_columns[i][0] = false;
        for (int j = 1; j <= BOARD_SIZE; ++j) {
            available_columns[i][j] = true;
        }
    }

    bool available_squares[SQUARES_PER_BOARD_SIDE][SQUARES_PER_BOARD_SIDE][BOARD_SIZE + 1];

    for (int i = 0; i < SQUARES_PER_BOARD_SIDE; ++i) {
        for (int j = 0; j < SQUARES_PER_BOARD_SIDE; ++j) {
            available_rows[i][j][0] = false;
            for (int k = 1; k <= BOARD_SIZE; ++k) {
                available_squares[i][j][k] = true;
            }
        }
    }

    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            if (board[i][j] == 0) {
                continue;
            }

            if (!available_rows[i][board[i][j]] || !available_columns[j][board[i][j]] || !available_squares[i/SQUARE_SIZE][j/SQUARE_SIZE][board[i][j]]) {
                return false;
            }

            available_rows[i][board[i][j]] = false;
            available_columns[j][board[i][j]] = false;
            available_squares[i][j][board[i][j]] = false;
        }
    }

    return true;
}

I'm assuming that this is inside a Board class, since you have direct access to the board variable in your original example.

This is off the top of my head.  As others have noted, there are many more examples of Sudoku implementations that have thought through the ramifications of each choice at greater length.  This is a common pattern that you should know, even if you choose not to use this particular solution here.


The jumble method

In the jumble method, you are looping over the character by having an index going from 0 to the length of the input array.

for (int i = 0; i < text.length(); i++) {
    char ch = text.charAt(i);
    // ...
}

Since you don't use the index apart from retrieve the character, you couls just use toCharArray() and loop directly over the characters:

for (char ch : text.toCharArray()) {
    // ...
}

Then, you are appending characters based on their codepoint. For this, you are doing

out.append((char) ('A' + generator.nextInt(26))); // same for 'a' and '0'

Instead of having this (ugly) cast, you could directly use appendCodePoint with

out.appendCodePoint('A' + generator.nextInt(26));

Additionally, the code path to jumble a character can lead to potential bugs:

if (Character.isLetter(ch)) {
    if (Character.isUpperCase(ch)) {
        // ...
    } else {
        // ...
    }
} else if (Character.isDigit(ch)) {
    // ...
} else {
    // ...
}

The problem is that isLetter returns true for characters that are not only uppercase or lowercase characters. For example, it would return true for all those weird characters classified as "Lo" as per Unicode (and OTHER_LETTER in Java). It would also return true for those classified "Lm" (MODIFIER_LETTER in Java), like "OL CHIKI AHAD" ᱽ. Since I think that, for example, in the case of the Hebrew letter "BET", ב, you don't want to consider it lowercase (which your code would, since it is a letter not uppercase), you can remove that check completely and have:

if (Character.isUpperCase(ch)) {
    sb.appendCodePoint('A' + generator.nextInt(26));
} else if (Character.isLowerCase(ch)) {
    sb.appendCodePoint('a' + generator.nextInt(26));
} else if (Character.isDigit(ch)) {
    sb.appendCodePoint('0' + generator.nextInt(10));
} else {
    sb.append(ch);
}

This way, only character that have case (upper or lower) will be taken into account in those branches. But still, there are a lot of lowercase letters (and uppercase letters) different than a-z, like ῲ or ⅎ or even ⱙ (which is apparently "GLAGOLITIC SMALL LETTER IOTATED BIG YUS"). In those case, they will be replaced by a Latin small character, which may or may not be what you want. If you truly want to jumble only Latin letters, it would be best to test the character against 'a' and 'z' (conversely for uppercase). And you know what? This is not just letters. There are a lot of digits that aren't 0-9, like ٨ (Arabic 8) or ᧗ (New Tai Lue 7) or even ꧓ (which is apparently Javanese 3). Therefore, if you just want to concentrate on Latin letters and Roman digits, you can just use

if (ch >= 'A' && ch <= 'Z') {
    sb.appendCodePoint('A' + generator.nextInt(26));
} else if (ch >= 'a' && ch <= 'z') {
    sb.appendCodePoint('a' + generator.nextInt(26));
} else if (ch >= '0' && ch <= '9') {
    sb.appendCodePoint('0' + generator.nextInt(10));
} else {
    sb.append(ch);
}

The last concern is about the Random object. You are creating one each time this method is executed. It would be preferable to create only one and reuse the same everytime. For example, you can have a constant

private static final Random RANDOM = new Random();

The jumbleEmoteSpeech method

You should always prefer to return early from methods when it is possible. In this case, if there are no quotes in the String, you return it unchanged.

StringBuilder out = new StringBuilder();
int quote1Location = emote.indexOf('"');
if (quote1Location == -1) {
    out.append(emote);
} else {
    // ...
}
return out.toString();

You could write this more concisely with

int quote1Location = emote.indexOf('"');
if (quote1Location == -1) {
    return emote;
}
// ...

This accomplishes two things:

There is no StringBuilder created: we don't need one
The code is more readable because the else part isn't needed anymore: it shifts the rest with one indentation less.

Also, prefer to declare variables at the moment of use. In this case, you are declaring int quote2Location; before the while loop:

int quote2Location;
do {
    quote2Location = emote.indexOf('"', quote1Location + 1);
    // ...
} while (...);

Instead, you can just have:

do {
    int quote2Location = emote.indexOf('"', quote1Location + 1);
    // ...
} while (...);


Bash arrays and case statements - review my script

In showEnv, why do you need to check that envList is empty when you define it right in the program?

I'd write the array elements one-per-line with:

# Show all elements in array
for elem in "${envList[@]}"; do
    echo "$elem"
done

or, more succinctly

printf "%s\n" "${envList[@]}"

In setEnv:

case $1 in
    cold|coles|fc|fcrm|stable|tip|uat|wellmdc)
        FILE_TO_SOURCE="/u2/tip/conf/ctrl/lettus_$1.sh" ;;
    *)  usage; return;;
esac

or, without duplicating the contents of envList:

FILE_TO_SOURCE=""
for elem in "${envList[@]}"; do
    if [ "$elem" = "$1" ]; then
        FILE_TO_SOURCE="/u2/tip/conf/ctrl/lettus_$1.sh"
        break
    fi
done
if [ -z "$FILE_TO_SOURCE" ];then
    usage
    return
fi

You might want to check that the relevant file exists

if [ ! -f "$FILE_TO_SOURCE" ]; then
    echo "missing config file '$FILE_TO_SOURCE'!"
    echo "contact $maintainer for assistance"
    return 1
fi

What is $IS_SOURCED? You might want to document how that environment variable is defined.

You don't need the return at the end of main or at the end of the program.


Edit file name method - run time complexity

Hello and Welcome to Code Review. The runtime complexity in terms of reading characters (n files * m characters) for substitution cannot be improved, you can use the String replace(char oldChar, char newChar) method:

String childName = file.getName();
String childNameNew = "";
for (int i = 0; i < childName.length(); i++) {
    if (childName.charAt(i) == ' ') {
        childNameNew += "-";
    } else {
        childNameNew += childName.charAt(i);
    }
}

You can substitute your block with one line:

String childNameNew = childName.replace(' ', '-');

From Java 7 it is discouraged using File renameTo method, you can use from class Files the move method and you can write the mv file part of your code in this way:

// Calculate oldPath and newPath for your file with Paths.get method
try {
    Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
    System.out.println(oldPath + " File moved successfully to " + newPath);
} catch (IOException e) {
    System.out.println(oldPath + " Failed moved the file to " + newPath);
}


Typesetting A* in LaTeX using algorithm2e

Instead of writing \textsc and \text all the time, I prefer semantic markup, such as \func and \var. These simple name changes make the source code easier to read for me. Compare:

\var{p} = \func{prime}(\var{x})
\text{p} = \textsc{prime}(\text{x})

When reading the first line aloud, you will quickly notice any discrepancy between a name and its type.

It looks weird to me that the math mode is closed before the first \Nil and another math mode is opened again immediately after it. This could influence the spacing in subtle ways. It's probably better to write it like this:

$\pi = \{ (s \mapsto \text{\Nil})\}$

This wording feels more natural since there is really only a single math expression here.

The last \caption is not indented properly.


Filter an array of objects, checking only specified properties and child objects

DRY your code You reference element[filterField] quite a few times in filterCallback. It would be nicer to save the value in a standalone variable first - then you can reference that variable instead of doing object property lookup each time.
Nested object bug filterCallback returns a function, but here, if an array or object is found, you're returning a call of filterCallback, which will always be truthy, so the .some will pass, even when it shouldn't:
return filterFields.some((filterField) => {
  if (Array.isArray(element[filterField])) {
    return element[filterField].some(function(childElement) {
      return filterCallback(childElement); // <--- always truthy
    })
  } else if (typeof element[filterField] === 'object') {
    return filterCallback(element[filterField]); // <--- always truthy
  }
  return comparisonFunction(element[filterField], filterTerm); // <--- OK
})

// No items should pass the test, but they do:

//if filterTerm or filterFields are empty, return original list
function filterList(list, filterTerm, filterFields) {
  if (filterTerm && filterFields.length > 0) {
    return list.filter(filterCallback(filterFields, filterTerm));
  } else {
    return list;
  }
}

//use closure to pass filterFields and filterTerm to callback
function filterCallback(filterFields, filterTerm) {
  return function(element) {
    return filterFields.some((filterField) => {
      if (Array.isArray(element[filterField])) {
        return element[filterField].some(function(childElement) {
          return filterCallback(childElement);
        })
      } else if (typeof element[filterField] === 'object') {
        return filterCallback(element[filterField]);
      }
      return comparisonFunction(element[filterField], filterTerm);
    })
  }
}
//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa
function comparisonFunction(fieldValue, filterTerm) {
  return fieldValue &&
    (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) >= 0 ||
      String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) >= 0);
}

arr2 = [{
  name: "a",
  job: "b",
  employees: [{
    name: "z",
    job: "e"
  }]
}, {
  name: "f",
  job: "g"
}];
console.log(filterList(arr2, "d", ["name", "employees"])); //=> [{name: "a", job:"b", employees: [{name: "d", job: "e"}]}]

You need to call filterCallback(filterFields, filterTerm) first to get the filter function, then call the filter function with the value to check, eg:
return filterFields.some((filterField) => {
    const value = element[filterField];
    if (Array.isArray(value)) {
        return value.some(function (childElement) {
            return filterCallback(filterFields, filterTerm)(childElement);
        });
    } else if (typeof value === 'object') {
        return filterCallback(filterFields, filterTerm)(value);
    }
    return comparisonFunction(value, filterTerm); // <--- OK
});

//if filterTerm or filterFields are empty, return original list
function filterList(list, filterTerm, filterFields) {
  if (filterTerm && filterFields.length > 0) {
    return list.filter(filterCallback(filterFields, filterTerm));
  } else {
    return list;
  }
}

//use closure to pass filterFields and filterTerm to callback
function filterCallback(filterFields, filterTerm) {
  return function(element) {
    return filterFields.some((filterField) => {
        const value = element[filterField];
        if (Array.isArray(value)) {
            return value.some(function (childElement) {
                return filterCallback(filterFields, filterTerm)(childElement);
            });
        } else if (typeof value === 'object') {
            return filterCallback(filterFields, filterTerm)(value);
        }
        return comparisonFunction(value, filterTerm); // <--- OK
    });
  }
}
//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa
function comparisonFunction(fieldValue, filterTerm) {
  return fieldValue &&
    (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) >= 0 ||
      String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) >= 0);
}

//EXAMPLE USE:

arr = [{
  name: "a",
  job: "b"
}, {
  name: "c",
  job: "d"
}];
console.log(filterList(arr, "a", ["name"])); // => [{name: "a", job:"d"}]

arr2 = [{
  name: "a",
  job: "b",
  employees: [{
    name: "z",
    job: "e"
  }]
}, {
  name: "f",
  job: "g"
}];
console.log(filterList(arr2, "d", ["name", "employees"])); //=> [{name: "a", job:"b", employees: [{name: "d", job: "e"}]}]

Precise variable names To reduce bugs, best to name variables as precisely as possible - filterCallback isn't actually the callback used in filter or some, but it's a function which creates such a callback. Maybe call it createFilterCallback instead - that probably would've made the problem clearer at a glance.
Implicit return Since you're using ES6, you could consider using arrow functions too - their implicit return can make code much more concise. Less code means less surface area for bugs, and can sometimes make it easier to read.
comparisonFunction If you want to check whether a string includes another, in ES6, better to use .includes(...) than .indexOf(...) >= 0. You also have a potential bug - you do String(fieldValue).toLowerCase() and String(filterTerm).toLowerCase(), implying that you expect that the value or term may not be a string - but then you do .indexOf(filterTerm.toLowerCase()) and .indexOf(fieldValue.toLowerCase()), which will throw if they aren't strings. Make sure to convert them to strings first:
const comparisonFunction = (fieldValue, filterTerm) => {
    const value = String(fieldValue).toLowerCase();
    const term = String(filterTerm).toLowerCase();
    return value && value.includes(term) || term.includes(value);
};

null is an object too, unfortunately, so:
}else if(typeof element[filterField] === 'object'){
    return filterCallback(element[filterField]);
}

will result in a recursive call, even when such a call won't make sense. The code works, but it's confusing flow. Better to only recurse if the value is an object and is not null.
filterCallback The whole filterCallback looks a bit ugly IMO. I'd simplify it a bit by not calling the whole function again recursively, but by declaring the function to filter elements by inside the function before returning it. Then, instead of recursing on filterCallback, recurse on that declared function:
const filterCallback = (filterFields, filterTerm) => {
  const testElement = element => filterFields.some((filterField) => {
    const value = element[filterField];
    if (Array.isArray(value)) {
      return value.some(testElement);
    } else if (value && typeof value === 'object') {
      return testElement(value);
    } else {
      return value && comparisonFunction(value, filterTerm);
    }
  });
  return testElement;
}

In all:

//if filterTerm or filterFields are empty, return original list
function filterList(list, filterTerm, filterFields) {
  if (filterTerm && filterFields.length > 0) {
    return list.filter(filterCallback(filterFields, filterTerm));
  } else {
    return list;
  }
}
//use closure to pass filterFields and filterTerm to callback
const filterCallback = (filterFields, filterTerm) => {
  const testElement = element => filterFields.some((filterField) => {
    const value = element[filterField];
    if (Array.isArray(value)) {
      return value.some(testElement);
    } else if (value && typeof value === 'object') {
      return testElement(value);
    } else {
      return value && comparisonFunction(value, filterTerm);
    }
  });
  return testElement;
}
//comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa
const comparisonFunction = (fieldValue, filterTerm) => {
  const value = String(fieldValue).toLowerCase();
  const term = String(filterTerm).toLowerCase();
  return value.includes(term) || term.includes(value);
};

//EXAMPLE USE:
arr = [{name: "a", job: "b"}, {name:"c", job:"d"}];
console.log(filterList(arr, "a", ["name"])); // => [{name: "a", job:"d"}]
arr2 = [{name: "a", job: "b", employees: [{name: "d", job:"e" }]}, {name: "f", job: "g"}];
console.log(filterList(arr2, "d", ["name", "employees"])); //=> [{name: "a", job:"b", employees: [{name: "d", job: "e"}]}]


Python code to split csv into smaller csvs, not splitting IDs

If I understand correctly, you want to split a file into smaller files, based on size (no more than 1000000 lines) and ID (no ID should be split among files).

If that's the case, I think you're over-complicating things. You don't need pandas and you definitely don't need to keep all data in memory.

You just need two counters, one for the amount of lines you've written and one for the index of the file to write.

Sample code (of course, replace file names with what you need, or move the check after the write to start from 0 instead of 1):

current_id = ''
index = 0
written_lines = 0
max_lines = 1000000

with open('data.csv', 'r') as input_file:
    for line in input_file:
        values = line.split(',')
        if (current_id != values[0]) or (written_lines > max_lines):
            index += 1
            current_id = values[0]
        with open('output_{:08d}.csv'.format(index), 'a') as output_file:
            output_file.write(line)
            written_lines += 1

EDIT: This works assuming the file is sorted or that at least the IDs are grouped together as you said in the comment.


First, Python has an official style-guide, PEP8, which you should follow. It recommends using lower_case for functions and variables.
I would also rename your function, since write_save does not say what this function is doing. I think overwrite_setting or update_value or something similar would be better.
You might want to add a check if any keyword arguments are passed to the function. Either raise an exception (a simple AssertionError might be enough), or at least don't waste time reading the file and writing the same content back.
While open opens a file in read-mode by default, here I think it is actually fine to open it once explicitly with 'r' and then with 'w'.
Your z = yamDict.copy() should be completely unnecessary. Mutating the original dictionary does not do any harm. The updating does not need to be within the with block either.
Finally, you could use or for the check of an empty dictionary.

With all of the above changes, your code would become:

import yaml

def update_value(filename, **kwargs):
    assert kwargs
    with open(filename, 'r') as f:
        yaml_dict = yaml.load(f) or {}
    yaml_dict.update(kwargs)
    with open(filename, 'w') as f:
        yaml.dump(yaml_dict, f)

If you have only one thread, you could skip the reading of the config everytime you want to change a value and instead keep the dictionary in memory (after having it read once at the beginning). You will still want the write to save state, though. For this you might want to have a Config class, derived from dict:

import os

class Config(dict):
    def __init__(self, filename):
        self.filename = filename
        if os.path.isfile(filename):
            with open(filename) as f:
                # use super here to avoid unnecessary write
                super(Config, self).update(yaml.load(f) or {})

    def __setitem__(self, key, value):
        super(Config, self).__setitem__(key, value)
        with open(self.filename, "w") as f:
            yaml.dump(self, f)

    def __delitem__(self, key):
        super(Config, self).__delitem__(key)
        with open(self.filename, "w") as f:
            yaml.dump(self, f)

    def update(self, kwargs):
        super(Config, self).update(kwargs)
        with open(self.filename, "w") as f:
            yaml.dump(self, f)

You might want to define a decorator to add the dumping part to the methods:

import functools

def dumps(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        ret = func(self, *args, **kwargs)
        with open(self.filename, "w") as f:
            yaml.dump(self, f)
        return ret
    return wrapper

class Config(dict):
    def __init__(self, filename):
        self.filename = filename
        if os.path.isfile(filename):
            with open(filename) as f:
                # use super here to avoid unnecessary write
                super(Config, self).update(yaml.load(f) or {})

    __setitem__ = dumps(dict.__setitem__)
    __delitem__ = dumps(dict.__delitem__)
    update = dumps(dict.update)

You can use this class like a dict, but every change to the dictionary is also dumped to the yaml file. The file is only read once (when the config is initialized), so changes to the file will only be visible when the script is re-started.

cfg = Config("test.yaml")
print(cfg)
cfg['a'] = 3
print(cfg)
cfg.update({"b": 4})
cfg.update(c=5)
del cfg['a']
print(cfg)


Using a closure

You can avoid putting constants in the global scope by wrapping everything in another closure, i.e. the code produced after the compiling process should look something like this:

(function() {
/* all your definitions here */
function ui() {
    // code here
}

function Game(ui) {
    // code here
}

function Graphics(ui) {
    // code here
}
}).call(this);

Thereby all the functions have access to your constants without cluttering the global namespace.

Supporting RequireJS/AMD

RequireJS is a library that aims to give you the possibility to import modules, something JavaScript lacks by default. It does so using 'dependency injection', i.e. passing all the things code requires to execute as parameters to a wrapping function. (You're already doing this in your code - kudos! Even though you seem not to like it, definitely stick to it!) This is considered a best practice in many programming languages - including JavaScript, duh - as it allows for nice modularization of code and great testability by replacing other modules that you don't want to test by mock implementations that might always return the same input, thereby you are able to test just parts of your code and locate errors more quickly. This is called unit testing - something you will never want to miss again.

By supporting RequireJS natively you will save your users from a lot headaches figuring out how exactly to get references to your code.
Doing so is quite easy, you check if the define function exists and use it or release everything to the global scope if it doesn't:

var lib = {
    ui: ui,
    Game: Game,
    Graphics: Graphics
}

if (typeof define === "function") {
    define("mylib", [], function() { return lib; });
} else {
    window.mylib = lib;
}

EDIT: When I wrote this I thought you wrote that you were creating your first library - not application. That being the case you can ignore the last paragraph, the first in this section still applies, though.

Building your library as a set of AMD modules

You can leverage the power of RequireJS/AMD for your own application. Just use any directory structure you like and use dependency injection to seperate them into files nicely. The RequireJS optimizer can then put them in a single file, you would still need RequireJS, though. Meet almond! It is only about 1kb minified+gzipped and defines a subset of the functionality of RequireJS that suffices to still use AMD modules inside a single file, which is ultimately what you want: a single file you  can include in their HTML or load using Require. Now, unfortunately, this introduces another step in going from your source to a distributable JS file.

Using a sophisticated build tool

Because nobody wants to do 10 steps manually each time you change your code and want a new build, sophisticated build tools were created that invoke the compiler(s), do code linting, etc. I personally recommend Grunt. It is IMHO the best and most flexible option out there and big libraries, e.g. jQuery, use it as well.

Don't reinvent the wheel

There already are great libraries that can do some of the heavy lifting for you. While for a first application it is a good idea to do things yourself to learn how they work internally, once you start working on production code you want to rely on existing libraries, because

that leaves you more time to work on your app and make it better
they make your code more error proof:

many libraries have been around for quite a long time and hardly have bugs
bugs that are found will most likely be fixed quickly (and by other people, see (1))

many libraries will make some design decisions for you. While you might think that cuts your freedom as a programmer (it certainly does), it also has a great advantage: Other people have spent a great deal on working out a good concept that will probably make your app easier to maintain in the end. So just choose one you like and go with it...
let's face it: people who dedicate their whole time to working on a library probably have better implementations of stuff than you, so that might make your app faster

Additional Points

I will add further points here with edits, but wanted to give you access to existing sections asap ;)


jQuery dynamic elements like TR and TD, add to HTML table

You could create a function that will add a row to the table based on the number of elements of data you pass to it (which will become columns):

function newRow($table,cols){
    $row = $('<tr/>');
    for(i=0; i<cols.length; i++){
        $col = $('<td/>').append(cols[i]);
        $row.append($col);
    }
    $table.append($row);
}

You can then call this function for every new row you want to make. $table expects a jQuery object, cols expects an array of elements (DOM or jQuery) to append to the row. I've also tidied up the jQuery that creates your elements. Did you know you can use the second parameter in the jQuery function to set element properties?:

jQuery(document).ready(function() {
  $('button[name="new-title"]').on('click', function(){
    var table = $('table[name="errortitle"]');

    var tdId = '-';
    var tdTitle = $('<input />', {'class' : 'form-control formInput', 'type': 'text'});
    var tdCheckBox = $('<input />', {'class' : 'form-control', 'type' : 'checkbox', 'name' : 'check'});
    var tdAction = $('<button />', {'class' : 'btn btn-danger', html:'Usuń'});

    newRow(table,[tdCheckBox,tdId,tdTitle,tdAction]);
  });
});

JSFiddle

Try it with any amount of column data:

newRow(table,[tdCheckBox,tdId,tdTitle,tdAction,'another col','and another','a final col']);

JSFiddle


Converting Integers to roman between 1 and 1000

You asked about optimization, which usually refers either to speed or memory
usage, neither of which apply in this case. Your code has negligible memory
cost. And if we truly cared about the ability to convert large volumes of
numbers at high speed, we would pre-compute a dict mapping every decimal number
of interest to its Roman equivalent.
If I were you, I would focus on optimizing this problem for simplicity of
understanding and code readability. Your current code appears to be fine, and
one can definitely figure it out, but it still requires some puzzling over. The
classic way that I've seen people solve this problem more simply is to build up
the Roman numeral by subtracting away even multiples of each divisor in your
dict mapping divisors to Roman symbols. The trick is to proceed from largest
divisor to smallest. Since Python 3 preserves order in dicts, we can
achieve that simply by reversing the order in which the data is set up.
The basic idea is illustrated below.
def decimal_to_roman(num):
    # The Romans had "integers" too, so this seems like a more
    # accurate function name.

    # You should add a check here to validate that the given decimal
    # number falls within the supported ranged.

    # Relies on Python 3 having ordered dicts.
    divisors = {
        1000: 'M',
        900: 'CM',
        500: 'D',
        400: 'CD',
        100: 'C',
        90: 'XC',
        50: 'L',
        40: 'XL',
        10: 'X',
        9: 'IX',
        5: 'V',
        4: 'IV',
        1: 'I',
    }

    # Build up the Roman numeral by subtracting multiples of
    # each divisor, proceeding from largest to smallest.
    roman = ''
    for div, sym in divisors.items():
        quotient = divmod(num, div)[0]
        roman += sym * quotient
        num -= div * quotient
        if num < 1:
            break
    return roman

When deciding on names for functions, variables, and so forth, aim for accuracy
and clarity in situations where the additional context is needed for
readability. This is a case where slightly longer names are appropriate (for
example, decimal_to_roman, divisors, and quotient). But when the
surrounding context and nearby names provide sufficient clues, you can aim for
brevity to reduce the visual weight of the code -- which also helps with
readability, but from a different direction. For example, within the narrow
context of this function, the short names like num, div, and sym are
easily understood without giving them fully explicit names.
Finally, how do you know your code is correct? If you're trying to learn, you
could consider writing the corresponding roman_to_decimal() function and then
make sure your converters can round-trip the data correctly. Another approach
is to find one of the many Python functions floating around the internet and use
it as your checker. Or you can install the
roman Python package to check
everything, as shown here:
import roman

for n in range(1, 4000):
    exp = roman.toRoman(n)
    got = decimal_to_roman(n)
    if exp != got:
        print(n, exp, got)


Ask the user random questions from a multiple-choice test

Cleanup questionFormat

You don't need the space variable.
The variables answersA, etc. should be answerA, etc.
The type of answerSheet can be int. I also think that correctAnswer is a better name for the member.

struct questionFormat
{
   string question;
   string answerA;
   string answerB;
   string answerC;
   string answerD;
   int correctAnswer;
};

Use an array of questionFormat instead of many arrays of strings

The lines

string questions [20];
string answersA [20];
string answersB [20];
string answersC [20];
string answersD [20];
string answerSheet [20];
string space[20];

can be replaced by

questionFormat questions[20];

Create function for reading data

Create function readData and move the code to read the data from main to readData.

int readData(std::string const& inputFile,
              questionFormat questions[],
              int maxQuestions)
{
   fstream infile("testQuestions.txt", ios::in);
   ...
}

Don't assume file IO succeeded

Always check status of file IO operations. It's never safe to assume that they succeeded.

Change the lines that read the input to:

for (counter = 0; counter < maxQuestions; ++counter )
{
   questionFormat& q = questions[counter];

   if ( !getline (infile, q.question) )
   {
      std::cout << "Failed to read a question.\n";
      return counter;
   }

   if ( !getline (infile, q.answerA) )
   {
      std::cout << "Failed to read answer A to a question.\n";
      return counter;
   }

   if ( !getline (infile, q.answerB)  )
   {
      std::cout << "Failed to read answer B to a question.\n";
      return counter;
   }

   if ( !getline (infile, q.answerC) )
   {
      std::cout << "Failed to read answer C to a question.\n";
      return counter;
   }

   if ( !getline (infile, q.answerD) )
   {
      std::cout << "Failed to read answer D to a question.\n";
      return counter;
   }

   if ( !(infile >> q.correctAnswer ) )
   {
      std::cout << "Failed to read the correct answer to a question.\n";
      return;
   }

   // Ignore two lines of text.
   // The first line corresponds to what's left in the stream
   // after reading the correct answer.
   // The second line is the intentionally left space.
   infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Simplify the find line

The line

if (bool exists = find(begin(testQuestions), end(testQuestions), num) != end(testQuestions))

can be simplified to:

if (find(begin(testQuestions), end(testQuestions), num) != end(testQuestions))

Move the code to conduct the tests to a separate function

void conductTests(questionFormat questions[],
                  int maxQuestions)
{
   ...
}

The contents of conductTests will be different from your posted code due to use of an array of questionFormat to hold the data.

That will simplify main to:

int main ()
{
   questionFormat questions[20];

   srand(time(NULL));

   int numQuestions = readData("testQuestions.txt", questions, 20);

   conductTests(questions, numQuestions);

   return 0;
}

No need to use an array for userAnswer

The value is read and used inside every iteration of the loop. It can be a simple int. Not only that, it can be in the scope of the while loop instead of being in the function scope.

Here's the complete program:

#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <limits>
#include <algorithm>

using namespace std;

struct questionFormat
{
   string question;
   string answerA;
   string answerB;
   string answerC;
   string answerD;
   int correctAnswer;
};

int readData(std::string const& inputFile,
             questionFormat questions[],
             int maxQuestions)
{
   fstream infile("testQuestions.txt", ios::in);

   for (int counter = 0; counter < maxQuestions; ++counter )
   {
      questionFormat& q = questions[counter];

      if ( !getline (infile, q.question) )
      {
         std::cout << "Failed to read a question.\n";
         return counter;
      }

      if ( !getline (infile, q.answerA) )
      {
         std::cout << "Failed to read answer A to a question.\n";
         return counter;
      }

      if ( !getline (infile, q.answerB)  )
      {
         std::cout << "Failed to read answer B to a question.\n";
         return counter;
      }

      if ( !getline (infile, q.answerC) )
      {
         std::cout << "Failed to read answer C to a question.\n";
         return counter;
      }

      if ( !getline (infile, q.answerD) )
      {
         std::cout << "Failed to read answer D to a question.\n";
         return counter;
      }

      // Ignore two lines of text.
      // The first line corresponds to what's left in the stream
      // after reading the correct answer.
      // The second line is the intentionally left space.
      infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

   return maxQuestions;
}

void conductTests(questionFormat questions[],
                  int maxQuestions)
{
   int testQuestions [10] = {99,99,99,99,99,99,99,99,99,99};
   int counter = 0;
   int userCorrect = 0;

   cout << "Welcome to my fantastic test.\nYou will randomly be given 10/20 questions." << endl;

   while (counter < 10)
   {
      int userAnswer;
      int num = rand()%maxQuestions;
      cout << "Current random number: " << num << endl;
      cout << "Counter is: " << counter << endl;
      if (find(begin(testQuestions), end(testQuestions), num) != end(testQuestions))
      {
         continue;
      }
      else
      {
         testQuestions[counter] = num;
         cout << "\nQuestion # " << counter +1 << endl;
         cout << questions [num].question << endl;
         cout << questions [num].answerA << endl;
         cout << questions [num].answerB << endl;
         cout << questions [num].answerC << endl;
         cout << questions [num].answerD << endl;
         cin >> userAnswer;

         if (userAnswer == questions[num].correctAnswer)
         {
            userCorrect++;
         }
         counter++;
      }
   }

   cout << "You got a total of " << userCorrect << " out of 10 correct" << endl;
}

int main ()
{
   questionFormat questions[20];

   srand(time(NULL));

   int numQuestions readData("testQuestions.txt", questions, 20);

   conductTests(questions, numQuestions);

   return 0;
}


Try to determine the complexity of the algorithms you are implementing. The code you wrote above has a complexity of O(N⁹), where N is equal to grid.dimension. This is because you have 6 nested for loops, and then voxels.all{} which itself also has to loop over all three dimensions of the box voxels.

Grouping voxels by their int value is a good idea. You correctly worry about the case of voxels with the same value being spread out. The solution to that is to divide the box into connected voxels with the same int value. For example, if you had only one dimension, then if you have the values [0, 1, 2, 2, 1, 2], then you would divide this into 5 groups: [0], [1], [2, 2], [1] and [2]. It should be possible to do this in O(N³) time.

Now that you have a set of smaller shapes, the function that decomposes those shapes into boxes should run a lot faster. The question is now whether you want to have that function as fast as possible, or as accurate as possible. The function as you wrote does not necessarily result in the least amount of boxes. Apart from the fact that it doesn't actually try out boxes in a strict order from largest to smallest, even trying the largest boxes first won't necessarily result in the least amount of boxes being produced. Take for example this 2D array:

1 0 0 1
1 1 1 1
1 0 0 1

The voxels with value 1 form a H-shape. If you remove the largest possible box, you end up with:

1 0 0 1
x x x x
1 0 0 1

Now you are left with 4 1x1 boxes, so in total this will result in 5 boxes for the H-shape. If instead you would start by taking out the left and right side, you are left with the middle bar, resulting in just 3 boxes. Finding the solution with the least amount of boxes is actually an NP-complete problem, and an algorithm that would produce that solution would take even longer to run that yours. Given that your algorithm already does not give acceptable performance, you should instead focus on implementing the fastest algorithm that produces acceptable results.

The common approach is to start by finding strips of adjacent voxels in the x-direction. Then try to find adjacent strips with the same size and x-position in the y-direction, and merge them into squares. Finally do the same in the z-direction and merge adjacent squares into boxes. This should be O(N³) as well. If you know that some shapes are more common than others, you could tweak this algorithm to reduce the number of boxes.


Removing duplicates from multiple arrays at once

Create a function on Array.prototype that'll accept an array and filter the array by checking if the element is in the other array.

// Define a function on Array prototype
Array.prototype.arrayDiff = function (arr) {
    return this.filter(function (v) {
        return arr.indexOf(v) === -1;
    });
};

function diff(arr1, arr2) {
    // 1. Remove elements that are in arr2 from arr1
    //    i.e. arr1.arrayDiff(arr2)
    // 2. Remove elements that are in arr1 from arr2
    //    i.e. arr2.arrayDiff(arr1)
    // 3. Concat the result of both the arrays

    return arr1.arrayDiff(arr2).concat(arr2.arrayDiff(arr1));
}

// Define a function on Array prototype
Array.prototype.removeDuplicates = function(arr) {
  return this.filter(function(v) {
    return arr.indexOf(v) === -1;
  });
};

function diff(arr1, arr2) {
  return arr1.removeDuplicates(arr2).concat(arr2.removeDuplicates(arr1));
}

var arr = diff([1, 3, 4, 2, 5], [2, 45, 7, 42, 1, 6]);
document.write(JSON.stringify(arr));


Finding the person with the biggest loss

A few things I noticed:

Using the range option of the array index(var allAmounts = currentPersonData[1..];) doesn't really help here.  All that's needed is to use the appropriate indexes of the original array.

It's quite inefficient to use a try block to test if a string is a valid number.  Using the tryParse method is much more efficient.

A hard coded currency symbol means that your output might not format properly on someone else's machine.  I would suggest using the format overload of the ToString method with the currency format.

I appears you're using a StringBuilder to change the name of whichever person has the highest loss.  If I'm not mistaken this will copy the string you already have.  I would suggest just use the string array itself.  This will be assigned by reference and won't require recopying the string.
This:

if (personWithHighestLoss[0].Contains(','))
{
    ReplaceCommaWithAnd(personWithHighestLoss);
}

doesn't really make much sense.  The Split method already removes the commas.  If you're worried about extra commas use the StringSplitOptions.RemoveEmptyEntries option of the Split method.

Here's what the modified code could look like:

public static string FindPersonWithBiggestLoss(string[] peopleAndBalances)
{
    if (IsInValidInput(peopleAndBalances))
    {
        return InValidInput;
    }

    var highestLossEver = decimal.MinValue;
    string[] personWithHighestLoss = new string[] { "" };

    for (int i = 0; i <= peopleAndBalances.Length - 1; i++)
    {
        var currentPersonData = peopleAndBalances[i].Split(',',StringSplitOptions.RemoveEmptyEntries);

        // calculateLoss

        if (currentPersonData.Length < 4)
        {
            return InValidInput;
        }

        for (int j = 1; j < currentPersonData.Length - 1; j++)
        {
            var amount1 = 0.0M;
            var amount2 = 0.0M;
            if (!(decimal.TryParse(currentPersonData[j], NumberStyles.Currency | NumberStyles.Number, null, out amount1) &&
                decimal.TryParse(currentPersonData[j + 1], NumberStyles.Currency | NumberStyles.Number, null, out amount2)))
            {
                Console.WriteLine($"there is not a valid character in the database");
            }

            var lossForCurrentPerson = amount1 - amount2;

            //check if loss is greater then the current highest loss
            if (lossForCurrentPerson > highestLossEver)
            {
                highestLossEver = lossForCurrentPerson;
                personWithHighestLoss = currentPersonData;
            }
        }

    }
    return $"{personWithHighestLoss[0]} lost the most money. -{highestLossEver.ToString("C")}.";
}


IDictionary<string, IDictionary<Levels, IList<ProblemRule>>> is difficult to understand and maintain. I don't know enough about your problem domain to give you reasonably sounding names for classes, but I'll try.

In your LoadProblems method, I see you set the IDictionary<Levels, IList<ProblemRule>> to a variable named problemPackage, so I would create a class ProblemPackage, containing a list of ProblemRules per Level (I would drop the 's' in Levels) and move the related logic there.

In ProblemBaseFactory you end up with a IDictionary<string, ProblemPackage>. ProblemPackage will have a IDictionary<Level, ProblemRules> and the class ProblemRules will be an easy wrapper around a IList<ProblemRule>.

If you try to delegate the work to these classes, the readability will almost certainly go up.


No, this can be written a lot easier.  There is no need to create variables when you are not going to vary the value.  It actually only makes things harder to read.  Assuming you are using PHP 5.3+ consider this:

// It is odd that you aren't using $vars in your method.
// I'll ignore that for now.
function wellies_less_vars( $vars, $handle ) {

    //Necessary for UpTheme Framework
    // This is not nice, but I'll ignore that too.
    global $up_options;

    //Set Less Mixins to Variables above
    // Grab Theme option and check if it's set and use that, otherwise use a
    // default value.
    // Now there is beauty in the alignment IMO.
    return array(
        'linkColor'          => $up_options->linkcolor            ?: '#08c',
        'linkColorHover'     => $up_options->linkcolorhover       ?: '#03c',
        'networkNavBarStart' => $up_options->networknavstartcolor ?: '#333',
        'networkNavBarEnd'   => $up_options->networknavendcolor   ?: '#222',
        'siteNavBarStart'    => $up_options->sitenavstartcolor    ?: '#333',
        'siteNavBarEnd'      => $up_options->sitenavendcolor      ?: '#222');
}

There is a small difference in functionality, but a large difference in readability.  The ?: uses the value on the left if it evaluates to true (generally a set variable except false), or the value on the right if it is not.


Here are a few issues with your code

If older browsers aren't a concern, you can just use fetch instead of XHR. It's built-in and uses promises.
HTTP 200 isn't the only "successful" response status. See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.
Status "0" is a generic network error, not just being offline. It can also be caused by the browser suppressing the request due to some restriction, an extension blocking the request, an insecure connection/invalid certificate.
Send an Accept header with application/json as value. This is because, while the server might support JSON, it might not respond with it by default.
The third argument of xhr.open is by default true. You may omit that third argument.
You can use readystatechange with addEventListener instead of the onreadystatechange property to assign your callback.


Script for recording a country in which a company belongs

TL;DR : My comments won't improve the performances much. Also, I've never used Apps Script.

This being said, here what I did : I decided to change details to make your code more concise (removing variables used only once for instance).

function setRegions() {
      var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var myCompany = mySheet.getDataRange().getValues();
      for(i = 1, start = 2; i < myCompany.length; i++, start++){
        var country_code = myCompany[i][4];
        if (country_code == "ke" ||
            country_code == "ng" ||
            country_code == "ug" ||
            country_code == "za" ||
            country_code == "sn" ||
            country_code == "gh") {
          mySheet.getRange("M" + start).setValue("AFRICA");
        }else if (country_code == "eg" ||
                 country_code == "sa" ||
                 country_code == "ma"){
          mySheet.getRange("M" + start).setValue("MENA");
        }else if (country_code == "br" ||
                 country_code == "ar" ||
                 country_code == "mx" ||
                 country_code == "pe" ||
                 country_code == "co"){
          mySheet.getRange("M" + start).setValue("LATAM");
        }else if (country_code == "my" ||
                 country_code == "th" ||
                 country_code == "id" ||
                 country_code == "ph"){
          mySheet.getRange("M" + start).setValue("APAC");
        }else if (country_code == "in") {
          mySheet.getRange("M" + start).setValue("IN");
        }
      }
    }

Then, you can get rid of the different tests on the country_code by storing what you want in a dictionary :

function setRegions() {
      var dict = {
          "ke" : "AFRICA",
          "ng" : "AFRICA",
          "ug" : "AFRICA",
          "za" : "AFRICA",
          "sn" : "AFRICA",
          "gh" : "AFRICA",
          "eg" : "MENA",
          "sa" : "MENA",
          "ma" : "MENA",
          "br" : "LATAM",
          "ar" : "LATAM",
          "mx" : "LATAM",
          "pe" : "LATAM",
          "co" : "LATAM",
          "my" : "APAC",
          "th" : "APAC",
          "id" : "APAC",
          "ph" : "APAC",
          "in" : "IN",
      };
      var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var myCompany = mySheet.getDataRange().getValues();
      for(i = 1, start = 2; i < myCompany.length; i++, start++){
        var country_code = myCompany[i][4];
        if (dict[country_code])
        {
          mySheet.getRange("M" + start).setValue(dict[country_code]);
        }
      }
    }


Is there a cleaner way to ensure I am not writing duplicate data?

How exceptional is this error? What do you want to do when this happens?

If it's rare and you don't want to do anything, then:

Only catch the actual exception (maybe it's PDOException).
Remove the continue which serves no purpose here and could confuse the reader.
Make sure you don't fail silently when the error is not a violation error.

Your code will look like this:

try {
    $jobRow->save();
} catch (PDOException $e) {
    if(!isAnExpectedViolation()) {
        // I still need to do something about it!
    }
}

If it's really frequent, you may want to check if it's going to violate the constraint before running the query. If it's frequent and you want to tell about it to the user, put it into an if and act accordingly.


Sectioning element choice for main content in HTML5 Bones

I think the section element should be an article element, and the two article elements should be section elements:

Getting Started

Introduction

Instructions

While there are, of course, valid cases where a section element contains article elements, I think this not the case in this example.

The "Getting started" content is without question the main content for this document. The section element can be used for that purpose, but the article element would fit, too. A simple question to ask: Could this whole "Getting started" article be an entry in a feed? If yes, use article.

"Introduction" and "Instructions" are "sub-chapters" for "Getting started". Would it make sense to create separate entries for them in a feed? I don't think so.

However, as this document is meant as a boilerplate and therefor doesn't contain much content, it is hard to decide here. If "Introdcution" and "Instructions" would contain more content, so that these chapters could stand on their own, the current sectioning element choice would be correct.

But then there is the question: What would make more sense for the "typical site" the users of the HTML5 Bones template would create?

I guess you find more documents that need "article > section" than "section > article".

Examples:

a blog: only the front page and the tag pages need section > article, but each blog entry needs article > section.
an "About us" page on a company site: article > section (or section > section)
a shop: only the product listings need section > article, but each product needs article > section

Of course, a template can't make the choice for all users/sites. The users need to know what is right for their content. But I feel like it's dangerous to "default" to this sectioning element choice. If in doubt, one should use rather section than article, because section is what you get anyway (simply by using headings), while article has special meaning.


all appointment based on interval distance

You can greatly simplify things as well as wildly improve performance by using something like the following...
DECLARE
    @start_date date = '2020-09-24',
    @interval_in_days int = 30,
    @appt_count int = 100;

WITH
    cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)),   -- 10
    cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b),                             -- 100
    cte_Calendar (dt) AS (
        SELECT TOP (@appt_count)
            DATEADD(DAY, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1) * @interval_in_days, @start_date)
        FROM
            cte_n2 a CROSS JOIN cte_n2 b                                                    -- 10,000
        )
SELECT
    c.dt
FROM
    cte_Calendar c;

You can even even create an inline table function to make life a little easier...
SET QUOTED_IDENTIFIER ON;
GO
SET ANSI_NULLS ON;
GO

CREATE FUNCTION dbo.tfn_CalculateAppointmentDates
/* ===================================================================
09/22/2020, Created: Calculates all future appointment dates based
                on a start date, specified interval and number of
                requested appointments.
=================================================================== */
--===== Define I/O parameters
(
    @start_date date,
    @interval_in_days int,
    @appt_count int
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
    WITH
        cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)),   -- 10
        cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b),                             -- 100
        cte_Calendar (dt) AS (
            SELECT TOP (@appt_count)
                DATEADD(DAY, (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1) * @interval_in_days, @start_date)
            FROM
                cte_n2 a CROSS JOIN cte_n2 b                                                    -- 10,000
            )
    SELECT
        c.dt
    FROM
        cte_Calendar c;
GO


The change I'd make, respecting your overall design, is to refactor chrToNum as this:

chrToNum :: [(Char, Int)]
chrToNum = zip "0123456789" [0..]

Apart from that, if we are willing to slightly alter the design, I would separate the string validation from the computation of the Int represented. The string validation can be done using mapM :: (a -> m b) -> [a] -> m [b] (this way we avoid explicitly writing the recursion).

validateString :: String -> Maybe [Int]
validateString = mapM readChr

Then, you can define a function computing the Int represented by a list of digits (I use foldl' which requires you to add import Data.List but you can equally well use reverse + foldr as you originally did)

represents :: [Int] -> Int
represents = foldl' (\ ih z -> 10 * ih + z) 0

Finally, putting it all together we get:

readNum :: String -> Maybe Int
readNum = fmap represents . validateString


Performance review
Your code.
You have a few inefficiencies. When implementing the same function many times with many iterations within the function, reducing the number of steps will provide worth while performance gains.
Some suggestions.
Use === rather than == as it is a little quicker
Change the sign of dy, that means that the test if(e2 > -dy)  can be changed to if(e2 > dy) saving the need to negate dy each step.
Change the lines
 // Change
 dy = Math.abs(y1 - y0)
 // to
 dy = -Math.abs(y1 - y0)

 // Change
 err = dx - dy;
 // to
 err = dx + dy

 // Change
 if (e2 > -dy) {
   err -= dy;
   x0 += sx;
 }
 // to
 if (e2 > dy) {  // removes the - operation
   err += dy;
   x0 += sx;
 }

Remove the double array index and use a column reference for the bitmap
// just before the loop
var column = bitmap[x0];

// then in the loop you only need to index the row
if (column[y0] === 1) {
  return 1;
}
if (e2 > dy) {
  err += dy;
  x0 += sx;
  column = bitmap[x0]; // and update the column only when x0 changes.
}

Not a performance thing, just a style note. You have left out the ; after the return 0 and the locals declaration e2.
Better yet
You could also flatten the bitmap array and use an index rather than a coordinate. You change the y step to a modulo size. This reduces the number of tests and eliminates the need to index into a 2D array.
// using bitmap as a flat array with width as the pixel width
// Assuming coords are ints
function collision(x0, y0, x1, y1, width) {
  const dx = Math.abs(x1 - x0);
  const dy = -Math.abs(y1 - y0);
  const sx = x0 < x1 ? 1 : -1;
  const sy = y0 < y1 ? width : -width;
  const endIndex = x1 + y1 * width;
  var e2, err = dx + dy;
  var index = x0 + y0 * width;

  // loop through line drawing
  while (index !== endIndex) {
    if (bitmap[index] === 1) { return 1 }
    e2 = err << 1;
    if (e2 > dy) {
      err += dy;
      index += sx;
    }
    if (e2 < dx) {
      err += dx;
      index += sy;
    }
  }
  return 0;
}

Peformance
The function is out of context so performance improvements can not be suggested.
As a random line an improvement would be to step over a quad tree. But this would be a very complex bit of code and would depend on the content of the bitmap and how many pixels you are sampling. It would make major improvements when the ratio of "on" pixels is low and clumped, but poor as the ratio of "on" pixels approaches 50% and the distribution is non clumpy.
The are many other solutions but they all depend on what the line is looking for, how one line is related to the rest, and the distribution and content of the bitmap.


Some quick comments:

Const correctness

You really should make your code const correct.

For example at least these functions could be const declared:

    bool hasChildren();
    bool hasParent();

    TreeNode* getParent();
    TreeNode* getChild(int pos);

    int childrenNumber();
    int grandChildrenNum();

    std::string getTextContent();
    std::string getTagName();

Use references to avoid copies

This:

TreeNode(std::string iTextContent, std::string iTagName);

should be:

TreeNode(const std::string& iTextContent, const std::string& iTagName);

otherwise you are creating temporary copies of the strings when you pass them in.

These functions should return by const reference:

    std::string getTextContent();
    std::string getTagName();

Like so:

    const std::string& getTextContent() const;
    const std::string& getTagName() const;

Otherwise you will be creating unnecessary memory copies each time the function is called even if you just want to look at the value.

Memory leak galore?

Your API requires that you pass in raw pointers and store them in the node. There is no documentation of the ownership of the pointers. Who is responsible for freeing them? Right now all I see is a memory leak waiting to happen.

In your main code you allocate the nodes with new but C++ is NOT a garbage collected language. You will need to pair each new with a delete to free the memory otherwise you will run out of memory faster than you can say "Holy memory management batman!".

Now, this keeping track of new/delete gets error prone very quickly so since C++11 you are recommended to use smart pointers. A.k.a. std::unique_ptr and std::shared_ptr for just about everything. See also std::make_unique and std::make_shared. There are places where you could/should use pointers, but as I gather that you are new to C++ I will not go into those detail because you can get away with just using smart pointers everywhere for now.

Also you might be interested in reading up on Resource Acquisition Is Initialisation (RAII). We ❤❤❤ RAII in C++.


How to reduce execution time for this clustering computation?

There are three methods for computing a great circle distance between two points that are specified by latitude and longitude:

You used the spherical law of cosines, which is the most straightforward method based on mathematical principles.
The haversine formula yields better accuracy for small distances, though at a greater computational cost.
An approximation can be obtained by using the Pythagorean theorem on an equirectangular projection.

For the purposes of clustering, an approximation of the great circle distance might be good enough.  I would also declare this function private static final as a very strong hint that it can be inlined — as it should, since it's a pure mathematical function.

private static final double approxDistanceGeo(double lat1, double lon1, double lat2, double lon2)
{
    if (lat1 == lat2 && lon1 == lon2)
    {
        return 0;
    }
    else
    {
        double x = deg2rad(lon1 - lon2) * Math.cos(deg2rad((lat1 + lat2) / 2));
        double y = deg2rad(lat1 - lat2);
        double dist = Math.sqrt(x * x + y * y);
        dist = dist * 60 * 1.1515 * 1.609344;
        return dist;
    }
}

Working directly in radians could save a few deg2rad() conversions.


Coding Practice - Float* -> Vector3* cast

I would go with a 3rd option that is closest to option 2. But instead of taking the three parameters separately in the constructor, take an array of floats.

struct vec {
    float x,y,z;
    vec(float fv[]) : x(fv[0]), y(fv[1]), z(fv[2]) {}
};

int main() {
    float verts[] = {1,2,3,4,5,6,7,8,9};

    for (int i = 0; i < 9; i += 3) {
        const vec a(&verts[i]);
        // ...
    }

    return 0;
}


You will have to test performance, but a GROUP BY should help:

SELECT playerName, MAX(points) AS points /*[, other columns]*/
FROM game
WHERE date >= date_sub(CURDATE(),INTERVAL 1 MONTH)
GROUP BY playerName /*[, other columns]*/
ORDER BY points DESC
LIMIT 0, 20


VBA: Calling one sub repeatedly and scope of variables

Public Const fRowType As Long = 4
Public Const fRowClosing As Long = fRowType + 1
Public Const fRowLoan As Long = fRowType + 4
'[there are about 30 of those fRow variables; they are needed in another _
 module, that's why they are public]

First of all, they're not "variables" they're "constants".

Second, that's screaming for an array or scripting.dictionary to hold them instead of a hoard of Const. They could even be pulled into a class that can easily be initialized provided with Getter properties (if the values are as fixed as Const would indicate) then the class can be passed around wherever it's needed.


Correctness

Your function does not work correctly. In my experience, memory manipulating functions almost never work correctly as they are written the first time. (At least when I'm writing them.) If you need to go down into that rabbit hole, be sure to do so with an extensive set of unit-tests. In your case, you are lucky. You have two functions you can compare your results with:

The existing memcmp function from the standard library and
the naïve implementation of a for loop that compares one byte after the other.

When I'm writing optimized functions, I usually start with the naïve implementation. Then I write a comprehensive set of tests for it to make sure I got it right. (For the naïve version, this is usually easy.) Then I start optimizing the function and after each change, run the test suite again. Should one of my optimizations introduce a correctness bug, I'll notice.

Also be sure to run your unit tests trough Valgrind and compile test programs with sanitizers added. For GCC and Clang, all you have to do is pass the -fsanitize=WHAT switch where WHAT is one of address, memory or undefined. (memory is only supported by Clang yet.)

Cast the pointer, not the value

Have a look at this piece.

if ((int) *_bufA != (int) *_bufB)
  return false;

What does it do? It dereferences the pointers _bufA and _bufB which are of type byte * (which I assume is an alias for char *). Now, only after that, you cast the result (which is of type byte) to an int. In effect, you're only looking at each forth byte.

What you have to do instead is casting the pointer before dereferencing it.

if (*((int *) _bufA) != *((int *) _bufB))
  return false;

Watch out for off-by-one errors

Your second loop is off-by-one.

while (--n) { … }

If I call your function with n == 1, it'll never look at any byte. If chux decides to call it with n == 0, it will explode. The correct version would be to use post-decrement.

while (n--) { … }

On the other hand, your first loop could use

while (n >= 4) { … }

instead of

while (n > 4) { … }

even though this “bug” doesn't cause the function to produce a wrong answer, it is probably not what you've meant.

Do memory operations on unsigned types

While I don't think it would cause a problem in this particular case, using signed integer types can lead to all kinds of surprises. If you don't treat the values as numbers but as a bunch of bytes, stay with unsigned types.

Beware of undefined behavior

The C standard does not allow you to cast a pointer to another type (except char) to access the memory it points to. (This is a simplified explanation, search for “strict aliasing rules” for more information.) Therefore, your function invokes undefined behavior and this cannot be fixed other than by using the standard library functions.

That said, I think that this is a case where you can get pretty far with (extremely) carefully blundering the line of undefined behavior if you know what you are doing.

On many machines, memory must be aligned. That is, an object o of type T must have an address such that ((uintptr_t) &o) % alignof(T) == 0 where alignof(T) is called the alignment of type T. Unfortunately, alignof is not an operator in C (unlike in C++ since C++11). A safe estimate is to use the maximum of sizeof(T) and 8. Even on those machines where an unaligned memory access does not cause an exception, it might be slow.

Therefore, what you should do is check whether both pointers can be word-aligned by advancing both of them by the same number of bytes. If so, first do a short loop that aligns the buffers, then cast to a machine word type and compare the bulk. Finally, compare the remaining bytes with a byte-for-byte loop again.

-fsanitize=undefined can warn you about mis-aligned reads.

Portability

Don't make assumptions on sizeof(int)

Your function silently assumes that sizeof(int) == 4. This will not be true on all platforms. Instead of hard-coding such values, use sizeof(int). You can store it in a constant if repeating it seems too much typing.

Performance

Prefer longs over ints

In absence of any reason to do otherwise, unsigned long is your best bet to get a type that directly maps to a machine-word and will therefore give you optimal performance. Once I made this change to your code, I got significant speedup on my 64 bit machine from 2.9 GiB/s to 4.3 GiB/s!

Consider exiting early

If you anticipate that your function might regularly be called with aliasing pointers, it might be worthwhile to check for this.

if (p1 == p2)
  return true;

It doesn't cost much if the condition is false and will be an enormous short-cut if the pointers do alias.

Be sure to measure

Doing low-level optimization without measuring is a waste of time. You should compare your function with (at least) two alternatives:

the naïve byte-for-byte approach and
at least one highly optimized standard library implementation.

Before you do any optimization, be sure to compare those two approaches when compiled with all compiler optimizations turned on. If they don't differ much, you're probably done. Otherwise, deploy one optimization at a time and see how the performance of your implementation goes from “naïve” to “standard library”. If it goes below “naïve”, you're doing something wrong. If it goes above “standard library”, you did something awesome (or your function has a bug and doesn't do the same thing as the standard library version).

Writing good benchmarks is very hard. As a general rule, don't look at a single input but measure how the run-time scales with the input size. Also investigate the inevitable statistical errors your measurements will contain. I like to fit regressions to the data series and get a statistically more significant result from the fit parameters. Be sure to test large enough inputs so to reduce noise. Timings in the sub-millisecond range as you reported them are hardly significant.

I did this for your problem and got this result on my machine. Your version (with the fixes discussed above and using unsigned long) is not doing bad. Note, however, that the benchmark always tests the lucky case where the buffers can be aligned. I'll leave it as an exercise to you to test the more realistic case, too.

I'm dumping the code I've used to produce this data without any explanation here only so you can repeat the experiments on your hardware if you want to. It is a quick-and-dirty solution and I'm not particularly proud of the coding style but I believe that it tests accurately.

main.c:

#define _XOPEN_SOURCE 500  // random, srandom

#include <assert.h>        // assert
#include <math.h>          // isfinite, sqrt
#include <stdbool.h>       // bool, false, true
#include <stddef.h>        // size_t
#include <stdio.h>         // FILE, fopen, fclose, fprintf, snprintf, stderr
#include <stdlib.h>        // NULL, EXIT_{SUCCESS,ERROR}, malloc, free, random, srandom
#include <string.h>        // memcpy
#include <time.h>          // CLOCKS_PER_SEC, clock_t, clock

#include "memcmp.h"

// Tells the compiler that all previous changes to memory shall be visible.
#define CLOBBER_MEMORY()   __asm__ volatile ( "" : : : "memory" )

// Tells the compiler that the value of VAR shall be visible.
#define USE_VARIABLE(VAR)  __asm__ volatile ( "" : : "rm"(VAR) : )

// Type of the function to benchmark.
typedef bool (* memcmp_type)(const void *, const void *, size_t);

// Unsigned integer type that refers to a machine word.
typedef unsigned long word_type;

// Size of a machine word.
static const size_t word_size = sizeof(word_type);

// Global error message.
static const char * errmsg;

// Average value and statistical error of a statistical data sample.
typedef struct
{
  double average;  // average value (eg mean)
  double error;    // statistical error
} timing_result;

// Computes the square of a number.
static double
square(const double x)
{
  return x * x;
}

// Computes mean and standard deviation of the `n` data points in the array
// `datapoints`.  `n` must be at least 3.  The mean is stored at
// `resultptr->average` and the standard deviation at `resultptr->error`.
// Returns 0 on success.  On error a negative number is returned and `errmsg`
// is set.
static int
do_statistics(const double *const datapoints,
              const size_t n,
              timing_result *const resultptr)
{
  assert(n >= 3);
  double accu = 0.0;
  for (size_t i = 0; i < n; ++i)
    accu += datapoints[i];
  const double mean = accu / n;
  if (!isfinite(mean))
    {
      errmsg = "non-finite mean";
      return -1;
    }
  accu = 0.0;
  for (size_t i = 0; i < n; ++i)
    accu += square(datapoints[i] - mean);
  const double stdev = sqrt(accu / (n - 1));
  if (!isfinite(stdev))
    {
      errmsg = "non-finite standard deviation";
      return -1;
    }
  resultptr->average = mean;
  resultptr->error = stdev;
  return 0;
}

// Randomly maybe changes a single byte in the word pointed to by `wp`.
// Returns whether any byte was changed.
bool
maybe_change_byte(word_type *const wp)
{
  assert(wp != NULL);
  unsigned char bytes[word_size];
  const word_type before = *wp;
  memcpy(bytes, wp, word_size);
  const size_t index = random() % word_size;
  if ((random() % word_size) != 0)
    bytes[index] = (unsigned char) random();
  memcpy(wp, bytes, word_size);
  return (*wp != before);
}

// Runs a single benchmark for the function `funcptr` on an input of
// approximately `input_size` bytes.  The function will be called one more than
// `repetitions` times and the execution time of all but the first run will be
// collected statistically and stored in the record pointed to by `resultptr`.
// `repetitions` must be at least 3.  `buff1st` and `buff2nd` must be buffers
// of at least `input_size` bytes that can be accessed as arrays of
// `word_type`.  The buffers must not overlap.  They will be used internally as
// work-space.  On success, 0 is returned.  On error, a negative number is
// returned and `errmsg` is set.
static int
run_benchmark(const memcmp_type funcptr,
              const size_t input_size,
              const size_t repetitions,
              word_type *restrict const buff1st,
              word_type *restrict const buff2nd,
              timing_result *const resultptr)
{
  assert(funcptr != NULL);
  assert(repetitions >= 3);
  assert(buff1st != NULL);
  assert(buff2nd != NULL);
  assert(buff1st != buff2nd);
  assert(resultptr != NULL);
  const size_t words = input_size / word_size;
  const size_t bytes = words * word_size;
  double timings[repetitions + 1];
  for (size_t i = 0; i < words; ++i)
    {
      const word_type w = random();
      buff1st[i] = w;
      buff2nd[i] = w;
    }
  for (size_t i = 0; i <= repetitions; ++i)
    {
      const clock_t no_clock = (clock_t) -1;
      const bool expected = (words >= 2)
        ? !maybe_change_byte(buff2nd + words - 2)
        : true;
      const size_t skip = (words >= 1) ? (random() % word_size) : 0;
      CLOBBER_MEMORY();
      const clock_t t0 = clock();
      const int actual = funcptr((const char *) buff1st + skip,
                                 (const char *) buff2nd + skip,
                                 bytes - skip);
      USE_VARIABLE(actual);
      const clock_t t1 = clock();
      if (actual != expected)
        {
          errmsg = "function returned wrong result";
          goto label_catch;
        }
      if ((t0 == no_clock) || (t1 == no_clock))
        {
          errmsg = "cannot get CPU time";
          goto label_catch;
        }
      timings[i] = (double) (t1 - t0) / CLOCKS_PER_SEC;
      if (words >= 2)
        buff2nd[words - 2] = buff1st[words - 2];
    }
  if (do_statistics(timings + 1, repetitions, resultptr) < 0)
    goto label_catch;
  resultptr->error += 1.0 / CLOCKS_PER_SEC;  // systematic error
  goto label_finally;
 label_catch:
  assert(errmsg != NULL);
 label_finally:
  return (errmsg == NULL) ? 0 : -1;
}

// Runs all benchmarks and for randomly chosen input sizes and writes the
// results to text files named `timing_${tag}.dat` in the current working
// directory where ${tag} identifies the benchmarked function.  Progress
// information is printed to standard error output.  Returns 0 on success.  On
// error, a negative number is returned and `errmsg` is set.
static int
run_all_benchmarks()
{
  const size_t repetitions = 10;
  const size_t datapoints = 50;
  const size_t max_size = 99 * (1ULL << 20);  // \lessapprox 100 MiB
  const size_t candidates = 3;
  const memcmp_type cand_funcs[] = {memcmp_naive, memcmp_stdlib, memcmp_yamiez};
  const char *const cand_names[] = {"naive", "stdlib", "yamiez"};
  assert(candidates == sizeof(cand_funcs) / sizeof(cand_funcs[0]));
  assert(candidates == sizeof(cand_names) / sizeof(cand_names[0]));
  word_type *const buff1st = malloc(max_size);
  word_type *const buff2nd = malloc(max_size);
  if ((buff1st == NULL) || (buff2nd == NULL))
    {
      errmsg = "out of memory";
      goto label_catch_outer;
    }
  for (size_t candidx = 0; candidx < candidates; ++candidx)
    {
      FILE * fh = NULL;
      fprintf(stderr, "%-12s ", cand_names[candidx]);
      char filename[128];
      const int status = snprintf(filename, sizeof(filename), "timing_%s.dat",
                                  cand_names[candidx]);
      if ((status < 0) || ((size_t) status >= sizeof(filename)))
        {
          errmsg = "error in snprintf";
          goto label_catch_inner;
        }
      fh = fopen(filename, "w");
      if (fh == NULL)
        {
          errmsg = "cannot open output file";
          goto label_catch_inner;
        }
      if (fprintf(fh, "# %22s %24s %24s\n\n", "n", "average / s", "error / s") < 0)
        {
          errmsg = "I/O error";
          goto label_catch_inner;
        }
      for (size_t j = 0; j < datapoints; ++j)
        {
          size_t n = random() % max_size;
          timing_result result = {0.0, 0.0};
          if (run_benchmark(cand_funcs[candidx], n, repetitions, buff1st, buff2nd, &result) < 0)
            goto label_catch_inner;
          if (fprintf(fh, "%24zu %24.10e %24.10e\n", n, result.average, result.error) < 0)
            {
              errmsg = "I/O error";
              goto label_catch_inner;
            }
          fputc('.', stderr);
        }
      goto label_finally_inner;
    label_catch_inner:
      assert(errmsg != NULL);
    label_finally_inner:
      if (fh != NULL)
        {
          if (fclose(fh) != 0)
            errmsg = "error closing output file";
        }
      fprintf(stderr, "  %s\n", (errmsg != NULL) ? "failed" : "done");
      if (errmsg != NULL)
        goto label_finally_outer;
    }
  goto label_finally_outer;
 label_catch_outer:
  assert(errmsg != NULL);
 label_finally_outer:
  free(buff1st);
  free(buff2nd);
  return (errmsg != NULL) ? -1 : 0;
}

// Seeds the global pseudo random number generator via `srandom` and runs all
// benchmarks.  Progress information and error messages are printed to standard
// error output.  Benchmark results are written to text files in the current
// working directory.  Returns `EXIT_SUCCESS` on success or `EXIT_FAILURE` on
// error.
int
main()
{
  srandom((unsigned int) clock());
  if (run_all_benchmarks() < 0)
    {
      if (errmsg == NULL)
        errmsg = "unknown error";
      fprintf(stderr, "error: %s\n", errmsg);
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

memcmp.h:

#ifndef MEMCMP_H
#define MEMCMP_H

#include <stdbool.h>  // bool
#include <stddef.h>   // size_t

#ifdef __cplusplus
extern "C" {
#endif

bool
memcmp_stdlib(const void * s1, const void * s2, size_t n)
  __attribute__ ((hot));

bool
memcmp_naive(const void * s1, const void * s2, size_t n)
  __attribute__ ((hot));

bool
memcmp_yamiez(const void * s1, const void * s2, size_t n)
  __attribute__ ((hot));

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // #ifndef MEMCMP_H

memcmp_naive.c:

#include "memcmp.h"

bool
memcmp_naive(const void *const s1, const void *const s2, const size_t n)
{
  const unsigned char *const c1 = s1;
  const unsigned char *const c2 = s2;
  for (size_t i = 0; i < n; ++i)
    {
      if (c1[i] != c2[i])
        return false;
    }
  return true;
}

memcmp_stdlib.c:

#include "memcmp.h"

#include <string.h>  // memcmp

bool
memcmp_stdlib(const void *const s1, const void *const s2, const size_t n)
{
  return memcmp(s1, s2, n) == 0;
}

memcmp_yamiez.c:

#include "memcmp.h"

#include <stdint.h>  // uintptr_t

bool
memcmp_yamiez(const void *const s1, const void *const s2, size_t n)
{
  typedef unsigned char byte_type;
  typedef unsigned long word_type;
  const size_t word_size = sizeof(word_type);
  const size_t word_align = (word_size >= 8) ? word_size : 8;
  const uintptr_t align_mask = word_align - 1;
  const byte_type * buf1 = s1;
  const byte_type * buf2 = s2;
  const uintptr_t addr1 = (uintptr_t) s1;
  const uintptr_t addr2 = (uintptr_t) s2;
  if ((addr1 & align_mask) == (addr2 & align_mask))
    {
      const uintptr_t skip = word_align - (addr1 & align_mask);
      for (uintptr_t i = 0; i < skip; ++i)
        {
          if (*buf1++ != *buf2++)
            return false;
          --n;
        }
      const word_type * wbuf1 = (const word_type *) buf1;
      const word_type * wbuf2 = (const word_type *) buf2;
      while (n >= word_size)
        {
          if (*wbuf1++ != *wbuf2++)
            return false;
          n -= word_size;
        }
      buf1 = (const byte_type *) wbuf1;
      buf2 = (const byte_type *) wbuf2;
    }
  while (n--)
    {
      if (*buf1++ != *buf2++)
        return false;
    }
  return true;
}

Here is the Makefile I have used to compile the benchmarks.

CC = gcc
CPPFLAGS = -DNDEBUG
CFLAGS = -std=c11 -Wall -Wextra -Werror -pedantic -O3
LDFLAGS =
LIBS = -lm

compile: main

all: plot.png

plot.png: plot.gp timing_stdlib.dat timing_naive.dat timing_yamiez.dat
    gnuplot $<

timing_stdlib.dat timing_naive.dat timing_yamiez.dat: main
    ./$<

main: main.o memcmp_stdlib.o memcmp_yamiez.o memcmp_naive.o
    ${CC} -o $@ ${CFLAGS} $^ ${LDFLAGS} ${LIBS}

main.o: main.c memcmp.h
    ${CC} -c ${CPPFLAGS} ${CFLAGS} $<

memcmp_stdlib.o: memcmp_stdlib.c memcmp.h
    ${CC} -c ${CPPFLAGS} ${CFLAGS} $<

memcmp_yamiez.o: memcmp_yamiez.c memcmp.h
    ${CC} -c ${CPPFLAGS} ${CFLAGS} $<

memcmp_naive.o: memcmp_naive.c memcmp.h
    ${CC} -c ${CPPFLAGS} ${CFLAGS} $<

mostlyclean:
    rm -f fit.log *.o

clean: mostlyclean
    rm -f main *.dat plot.png

.PHONY: compile all mostlyclean clean

And here is the Gnuplot script plot.gp that produces the graphic shown above.

#! /usr/bin/gnuplot

## If you set the environment variable INTERACTIVE to a positive integer, the
## script will show the plot in an interactive Gnuplot window instead of
## writing to a file 'plot.png'.

interactive = 0 + system('echo "${INTERACTIVE-0}"')

if (!interactive) {
   set terminal png size 800,600
   set output 'plot.png'
}

set key top left
set xlabel 'size / MiB'
set ylabel 'time / ms'

set xrange [0 : *]
set yrange [0 : *]

set format y '%.0f'
set ytics add ('0' 0)

## Colors are taken from the Tango palette.
## See http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines .

set style line 1 lt 2 lw 2.0 ps 1.0 linecolor '#3465a4'
set style line 2 lt 1 lw 2.0 ps 1.0 linecolor '#cc0000'
set style line 3 lt 3 lw 2.0 ps 1.0 linecolor '#73d216'

## Prefix constants

kilo = 1000.0
mebi = 1048576.0

## Converts a regression constant 'c1' in milliseconds per byte to a throughput
## in gibibytes per second.

c2gibps(c1) = kilo / (c1 * 1024)

## Computes the maximum of two numbers.

max(x, y) = (x < y) ? y : x

## Converts a size in bytes to a size in mebibytes.

b2mib(n) = n / mebi

## Converts a time in seconds to a time in milliseconds.

s2ms(t) = kilo * t

regression_naive(x)  = c1_naive  * x
regression_stdlib(x) = c1_stdlib * x
regression_yamiez(x) = c1_yamiez * x

fit regression_naive(x)                                                       \
    'timing_naive.dat'  using (b2mib($1)):(s2ms($2)):(s2ms($3))               \
    yerror via c1_naive

fit regression_stdlib(x)                                                      \
    'timing_stdlib.dat' using (b2mib($1)):(s2ms($2)):(s2ms($3))               \
    yerror via c1_stdlib

fit regression_yamiez(x)                                                      \
    'timing_yamiez.dat' using (b2mib($1)):(s2ms($2)):(s2ms($3))               \
    yerror via c1_yamiez

plot 'timing_naive.dat' using (b2mib($1)):(s2ms($2)):(s2ms($3))               \
         with yerror ls 1                                                     \
         title sprintf('%s (%.2f GiB/s)', "naive", c2gibps(c1_naive)),        \
     regression_naive(x) notitle ls 1,                                        \
     'timing_stdlib.dat' using (b2mib($1)):(s2ms($2)):(s2ms($3))              \
         with yerror ls 2                                                     \
         title sprintf('%s (%.2f GiB/s)', "stdlib", c2gibps(c1_stdlib)),      \
     regression_stdlib(x) ls 2 notitle,                                       \
     'timing_yamiez.dat' using (b2mib($1)):(s2ms($2)):(s2ms($3))              \
         with yerror ls 3                                                     \
         title sprintf('%s (%.2f GiB/s)', "yamiez", c2gibps(c1_yamiez)),      \
     regression_yamiez(x) notitle ls 3

if (interactive) {
   print "Hit RET to quit ..."
   pause -1
}

Learn from the giants

There has been massive interest in optimizing memory functions and standard libraries have evolved highly optimized versions. If you want to learn from them, have a look at their code. For example, look at the version in the GNU C library. If reading that code gives you a headache, you are in good companion.

Coding Style

Use the proper types

In C, a read-only buffer of arbitrary data should be passed as const void *. The size of a buffer should be passed as size_t.

Be const correct

Since your function only ever reads the data from the buffer it is passed, it should be declared const.

Don't use identifiers that begin with an underscore

Identifiers that begin with an underscore followed by an upper-case letter and identifiers containing two adjacent underscores are reserved for the implementation. I recognize that your variables don't match this pattern but _bufA still looks bogus. Just drop the underscore.

Avoid confusing notation

I find this hard to read.

if (*bufA != *bufB)
  return false;
++bufA, ++bufB;

How about the commonly used form?

if (*bufA++ != *bufB++)
  return false;

Less typing and easier to understand. In general, I'd avoid putting more than one statement on a single line and not chain multiple statements together with the comma operator.


Function that returns index of Forex candle according opening hours (weekly session)

The code overall is readable and well documented. Of course, there is always something to improve, here are some things:

the frequencies are currently hardcoded in the function and the "assert" is not actually a strong check and would not prevent an invalid freq value to be used if Python compilation is optimized. I'd define frequencies in an Enum class:

from enum import Enum

class Frequency(Enum):
     HOURLY = "H1"
     MINUTELY = "M1"

Then, as a bonus, if you would use variable type annotations, your IDE would warn you if you would pass an invalid frequency to the weektag_from_time() function.
use day, hour and minute in place of more questionable d, h and m - remember, we are writing programs for people to read, not computers
I would improve on the "is market closed" check defining individual conditions in separate variables (the "Extract Variable" refactoring method), something like

is_saturday = day == 5
is_late_friday = day == 4 and hour > 21
is_early_sunday = day == 6 and hour < 22

market_closed = is_friday or is_late_thursday or is_early_saturday

or, may be even easier and more understandable would be to define an open market time range and reverse the logic. And, it might be a good idea to extract this check into a separate reusable function (I'm sure you have this kind of check in other parts of your project).
now, we may use an early "return" if market is closed and omit the "else" part decreasing the nestedness:

if market_closed:
    return 0

offset = (24 * day) + 2 if day < 6 else -22
hour += offset

# set result according granularity
if freq == Frequency.HOURLY:
    return hour
elif freq == Frequency.MINUTELY:
    return (hour * 60) + minute

according to PEP8, you should have spaces around operators
the offset calculation logic probably needs more explanation - consider adding an extra comment explaining the idea behind calculating it


A simple queue implementation in Haskell

While this is some pretty idiomatic haskell, you definitely didn't implement the challenge the way it was intended to be solved. Either way: here's some minor comments I'd want to put out anyways:

The type-signature of pop implies, that the queue returned can basically be Nothing.
If it can be, what queue did you call this on in the first place? I'd prefer the following signature:

pop :: Queue a -> (Maybe a, Queue a)

The implementation should be pretty straightforward :)
I'd not use a for both the type-variable and the variable in all your functions. Consider explicitly differentiating between types and values:

push x (Value value tail') = Value value (push x tail')
pop (Value value tail') = Just (value, tail')
peek (Value value _) = Just value

This makes the differentiation more clear. Note that I've renamed pointer to tail'. One could also argue for a rename of Value to Element to make the distinction more clear as well.

The naming changes are mostly nitpicks, though.

Now let's examine how to "correctly" solve this challenge. As cole outlines in their comment:

  This queue takes \$O(n)\$ time to enqueue, unlike the common queue implementation which uses a doubly linked list. You can get an amortized \$O(1)\$ time for enqueues if you implement it with two stacks (which is probably what you were getting at with the stack comment). A stack can be implemented using a singly linked list, which is what lists in haskell are. You can either make an abstract data type for a stack and use that in your queue ADT or just use lists
  minor formatting by me

So how would we implement a queue using two stacks, or rather two haskell lists that take the function of stacks? The basic idea of this challenge is to realize that packing two LIFO data structures can make for a FIFO datastructure. Take an "input" stack and an "output" stack. push (or more semantically correctly push_back) will just push a value to the "input" stack.

pop (and peek) are a little more complex. They need to handle the case of an empty output stack. If the output stack is empty, the input stack is moved to the output stack using the basic LIFO operations. Note that this "reverses the order" in the stack, which explains how two LIFO datastructures turn into a FIFO datastructure.

Unfortunately this means something for the interface you've outlined there. We can't assume that peek does not modify the internal state of the Queue anymore. It's simply speaking "not idempotent" anymore, since an empty output stack requires moving the input stack to it.

Now let's look at some type definitions

type Queue a = ([a], [a])

push :: a -> Queue a -> Queue a
pop :: Queue a -> (Maybe a, Queue a)
peek :: Queue a -> (Maybe a, Queue a)
empty :: Queue a -> Bool

Now to implement this:

push x (input, output) = (x:input, output)

pop ([], []) = (Nothing, ([], []))
pop (input, []) = (Just val, ([], new_out))
  where (val, new_out) = fromJust $ uncons $ reverse input
pop (input, (o:os)) = (Just o, (input, os))

peek ([], []) = (Nothing, ([], []))
peek (input, []) = (Just val, ([], new_out))
  where
    new_out = reverse input
    val = head new_out
peek (input, output@(o:_)) = (Just o, (input, output))

empty ([], []) = True
empty _        = False

For whatever it's worth: I liked your implementation better :)


Find the minimum number of operations to convert 1 into n, and print the sequence of numbers

Given the problem description, I'm not entirely sure why x is a parameter of min_operations. Could you not hard-code 1?

        val_times_2 = val * 2
        if val_times_2 <= y and val_times_2 not in visited:
            visited.add(val_times_2)
            new_sequences.append(s + [val_times_2])

        val_times_3 = val * 3
        if val_times_3 <= y and val_times_3 not in visited:
            visited.add(val_times_3)
            new_sequences.append(s + [val_times_3])

        val_plus_1 = val + 1
        if val_plus_1 <= y and val_plus_1 not in visited:
            visited.add(val_plus_1)
            new_sequences.append(s + [val_plus_1])

There's some common code here which could certainly be refactored. Perhaps

        for successor in [val + 1, val * 2, val * 3]
            if successor <= y and successor not in visited:
                visited.add(successor)
                new_sequences.append(s + [successor])

However, the approach of storing the full path for each visited element doesn't scale particularly well. All you really need is to find the predecessor: provided you store all of the predecessors, you can work your way back up the chain. One way to do that would be a dictionary (which could also take the place of visited).

def min_operations(y):
    predecessors = dict()
    new_elements = [1]

    while True:
        next_new_elements = []
        for e in new_elements:
            if e == y:
                return unchain(e, predecessors)

            for successor in [val + 1, val * 2, val * 3]
                if successor <= y and successor not in predecessors:
                    predecessors[successor] = y
                    next_new_elements.append(successor)

        new_elements = next_new_elements

def unchain(e, predecessors):
    chain = [e]
    while e in predecessors:
        e = predecessors[chain[-1]]
        chain.append(e)
    return list(reversed(chain))

An alternative way of doing it would be to use lru_cache to find the predecessors on the fly, handing off the caching to the library. Here it is necessary to track the depth as well as the predecessor.

@lru_cache(maxsize=None)
def predecessor(y):
    if y == 1:
        return (0, 0)

    candidates = []
    (decr, _) = predecessor(y - 1)
    candidates.append((decr + 1, y - 1))

    for divisor in [2, 3]:
        if y % divisor == 0:
            (divided, _) = predecessor(y // divisor)
            candidates.append((divided + 1, y // divisor))

    return min(candidates)

Then min_operations is essentially unchain but calling predecessor instead of doing a lookup in a map. This is arguably slightly more elegant, but does run into problems with stack overflow if y is too large.


Is there a proper way to query ExpandoObject?

First, I don't see any reason for using ExpandoObject in your code. The same result could be achieved with cleaner code using JObjects.

Second, what would help if you could express your query using “LINQ to null”. Basically, treat null as an empty collection and any other value as a collection containing just that value. (The technical term for this is the Maybe monad.)

With both of these changes, your code could look something like this:

var jsonObject = JsonConvert.DeserializeObject<JObject>(json);

string result =
    from o in jsonObject.ToNullWrapper()
    from data in o["data"]
    from children in data["children"]
    from child in children.FirstOrDefault()
    from data2 in child["data"]
    from score in data2["score"]
    select score.ToString();

Note that (ab)using LINQ like this is not idiomatic and probably very confusing. But I think it results in very clean code.

To make this work, you need the implementation of LINQ to null:

public struct NullWrapper<T>
    where T : class
{
    public T Value { get; private set; }

    public NullWrapper(T value)
        : this()
    {
        Value = value;
    }

    public static implicit operator T(NullWrapper<T> wrapper)
    {
        return wrapper.Value;
    }
}

public static class NullExtensions
{
    public static NullWrapper<T> ToNullWrapper<T>(this T value)
        where T : class
    {
        return new NullWrapper<T>(value);
    }

    public static NullWrapper<TResult>
        SelectMany<TSource, TIntermediary, TResult>(
        this NullWrapper<TSource> source,
        Func<TSource, TIntermediary> intermediarySelector,
        Func<TSource, TIntermediary, TResult> resultSelector)
        where TSource : class
        where TIntermediary : class
        where TResult : class
    {
        if (source.Value == null)
            return new NullWrapper<TResult>();

        var intermediary = intermediarySelector(source.Value);

        if (intermediary == null)
            return new NullWrapper<TResult>();

        return resultSelector(source.Value, intermediary).ToNullWrapper();
    }
}