var result = new StringBuilder();
for (var i = 0; i < length; i++)
{
    result.Append((char)Marshal.ReadByte(startStr, i));
}

You're working in a tight loop: a StringBuilder looks like a reasonable tool to use.

One thing I would change that could impact performance (depending on the length of the string involved), is the StringBuilder constructor being used:

var result = new StringBuilder(length);

There's no reason not to specify the length of the string you're building if you know it from the start; that will reduce the overhead, since the internals of the builder won't need to manage growth.

The loop is a one-liner. You have this one-liner just a few instructions above:

if (capacity > 15)
    startStr = (IntPtr)Marshal.ReadInt32(address + 4);

Why does the loop have an explicit { } scope, but not the if block? It would be better to be consistent about scoping braces, and have them everywhere:

 if (capacity > 15)
 {
     startStr = (IntPtr)Marshal.ReadInt32(address + 4);
 }

An alternative to the StringBuilder could be to write the bytes into a MemoryStream:

using (var stream = new MemoryStream(length))
{
    for (var i = 0; i < length; i++)
    {
        stream.WriteByte(Marshal.ReadByte(startStr, i));
    }
    return new StreamReader(stream).ReadToEnd();
}

The nice thing with this approach is that you don't need to cast every single byte of the string into a char. On the other hand, you need 2 objects instead of one, and you need to cleanly Dispose of the stream, too - depending on the length of the string, the overhead might just not be worth it, although my guts tell me the stream could be faster... but I think you'd need to race your horses to find out.


Unfortunately I don't know of a better way (but have also not looked into one, tbh). Here are some comments on your pathify method instead.

You are currently checking if i == 0 on every loop iteration, but it is true only once at the beginning. Just special case that one out and do

codes = [Path.MOVETO]
codes += [Path.LINETO for _ in range(1, len(polygon.exterior.coords))]

Even better, lists can be multiplied. Since Path.LINETO seems to be a constant, you can just do

codes = [Path.MOVETO] + [Path.LINETO] * (len(polygon.exterior.coords) - 1)

For the vertices I would use list.extend instead of list addition. This way you don't need to cast it to a list yourself but can let extend handle it. It might even be implemented in such a way that it just consumes an iterable. CPython actually does this, but it guesses the size by which the original list needs to be extended by asking the iterable object. If the object does not return a guess, it uses 8 instead (which might not be the most efficient for e.g. a long generator).

for interior in polygon.interiors:
    vertices.extend(interior.coords)
    codes.extend([Path.MOVETO] + [Path.LINETO] * (len(interior.coords) - 1))

At this point it might make sense to put generating the commands into a function, since we already had to use it twice:

@staticmethod
def generate_codes(n):
    """ The first command needs to be a "MOVETO" command,
        all following commands are "LINETO" commands.
    """
    return [Path.MOVETO] + [Path.LINETO] * (n - 1)

@staticmethod
def pathify(polygon):
    ''' Convert coordinates to path vertices. Objects produced by Shapely's
        analytic methods have the proper coordinate order, no need to sort.

        The codes will be all "LINETO" commands, except for "MOVETO"s at the
        beginning of each subpath
    '''
    vertices = list(polygon.exterior.coords)
    codes = self.generate_codes(len(polygon.exterior.coords))

    for interior in polygon.interiors:
        vertices.extend(interior.coords)
        codes.extend(self.generate_codes(len(interior.coords)))

    return Path(vertices, codes)

You should also probably put your calling code under a if __name__ == "__main__": guard to allow importing from this module without running the example code.


Clock that changes document background color

Questions

I suspect that this code is messy.

It doesn't really look very messy... One great aspect is that the DOM references are cached.

Is there a way the following JS code be made efficient?

I'm not sure it needs to be much more efficient. The code looks similar to many examples one can find searching the internet for a clock in JavaScript. If memory was an issue and you really wanted, perhaps you could create only one date object and merely update that date object with the updated hour, minute and seconds values but you would need to do the bookkeeping manually, which might end up being less efficient.
Suggestions
global variables
The variables created using var are technically global variables, since they are not contained in a function. For a small script like this it likely won't make a difference, but in a larger application that can lead to namespace collisions. It would be wise to wrap the code in a function (perhaps in an IIFE) and use const/let instead of var to keep the scope limited.
Use Date method to get formatted time
It could be simplified by using the Date method toLocaleTimeString() (or alternatively Intl.DateTimeFormat()). See the example below for a demonstration of this.
Edit: I realize after posting it that the 24-hour format was still the default for the hours so I had to add hour12 to the options and an extra call to .replace() to remove the am/pm. Also that doesn't apparently support the 2-digit format well so it also has to additionally add the leading 0 if necessary. Apparently this code suffers from this issue.

(function() { //IIFE
  const clock = document.getElementById('clockElement');
  const color = document.getElementById('hex-color');
  const options = {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: true
  };

  function hexclock() {
    const time = new Date();
    //use preferred locale accordingly
    let clockString = time.toLocaleTimeString('en-GB', options).replace(/[a-z\s]/g, '');
    //add missing 0 - hour12 doesn't work ideally for this scenario
    clockString.length < 8 && (clockString = '0' + clockString);
    const hexColorString = '#' + clockString.replace(/:/g, "");

    clock.textContent = clockString;
    color.textContent = hexColorString;

    document.body.style.backgroundColor = hexColorString;
  }

  setInterval(hexclock, 1000);
  setTimeout(function() {
    console.log('window.clock (global variable)? :', window.clock !== undefined);
  }, 1100);
})(); //end IIFE
body {
  marin-top: 20px;
  text-align: center;
  color: white;
}

#clock {
  font-weight: 300;
  font-size: 60px;
}

00 : 00 : 00

#000000


The core of your code can be replaced by the following code:

url.openConnection()    //you can cast to fail if it isn't https
   .getInputStream()   //same as you
   .reader()          // same as wrapping it in inputStreamReader
   .use { it ->      // start lambda that handles the closing of the reader for you
      it.readText() // note, it's one parameter, so 'it ->' can be omitted
    }

The code above returns the text or throws the exception it got during execution, but always closes the reader, which in turn closes the connection.

The code above is almost the same as the code below btw:

url.readText()

If you want to remove all the variables, you should know that try catch can return a value:

val a = try{ 1 } catch(e: Exception) { 2 }


Let's talk about SRP for the moment (I'm not going to cover anything else but this). SRP (or Single-Responsibility Principle) dictates that each and every component of code should have exactly one responsibility.

So we're going to look at all your code top-to-bottom and determine what responsibilities we have in each method.

We'll start with main:

Output information regarding programme definition to user;
Accept and process user input;
Call appropriate method(s) based on user input;

So that's more than one, but that's fine, we need to finish our analysis to make appropriate decisions on what to do next. Let's look at simple_a1:

Process items in an array;
Accept and process user input;
Add user input to array;
Print array information;
Inform the caller we're going back to the main menu;

That's a lot, and even simple_a2 has more than one responsibility:

Inform the user the feature is not implemented;
Inform the user we are returning to the main menu;

What happens when we're not going back to the main menu again from either of those methods? Now you have multiple places that you have to modify, and in a larger, production application that would mean very possible breakages.

So we're going to eliminate responsibilities until each and every method only has one left.

Let's start with simple_a1:

We can take the following block and extract it to a new method:

System.out.println("Request input for item " + i);
in_num = user_input.nextInt();
a1[i] = in_num;
System.out.println("Got it, next one ");

This does exactly one thing: prompt the user for a number and store it in the array. We won't store it in the array in our sub-method, but we'll extract the prompting out. Let's create a new method:

private static int getNumber(Scanner input, int index) {
    System.out.println("Request input for item " + index);
    int result = input.nextInt();
    System.out.print("Got it");
    return result;
}

Perfect, so this has one responsibility. It's not the prettiest, but it will do. Next we have to implement this in our other method:

for (int i = 0; i < 5; i++) {
    a1[i] = getNumber(user_input, i);

    if (i + 1 < 5) {
        System.out.println(", next one");
    }
}

So now our input prompting is separated from our processing, that's good but we can do better.

The block is now something along the lines of:

int[] a1 = new int[5];
Scanner input = new Scanner(System.in);

for (int i = 0; i < 5; i++) {
    a1[i] = getNumber(input, i);

    if (i + 1 < 5) {
        System.out.println(", next one");
    }
}

Well this whole block has one responsibility: build an array. So we can extract that out further:

private static int[] buildArray(int size) {
    int[] result = new int[5];
    Scanner input = new Scanner(System.in);

    for (int i = 0; i < 5; i++) {
        result[i] = getNumber(input, i);

        if (i + 1 < 5) {
            System.out.println(", next one");
        }
    }

    input.close();

    return result;
}

Good, so now simple_a1 looks like:

private static void simple_a1() {
    int[] a1 = buildArray(5);

    System.out.println("The numbers in a1 are: ");

    for(int i2: a1){
        System.out.print(i2 + " ");
    }

    System.out.println("\nEnd of testing 1, back to main menu...");
}

But we still have three remaining responsibilities:

Build an array;
Print the array;
Inform the user we're going back to the main menu;

Well we can make a printArray method:

private static void printArray(int[] printArray) {
    for (int val : printArray) {
        System.out.print(val + " ");
    }
}

Then we finally finish simple_a1:

private static void simple_a1() {
    int[] a1 = buildArray(5);
    printArray(a1);
    System.out.print("\nEnd of testing 1");
}

So we're down to one responsibility: process an array. It's made up of steps, but the implementation for those steps is not part of simple_a1.

Next we'll fix simple_a2:

private static void simple_a2() {
    System.out.print("This function still under construction");
}

So we don't care where we return to, we only care that we're returning.

Finally, fixing main is easy:

public static void main(String[] args) {
    System.out.println("Welcome to basic array test, please choose your testing subject: ");
    Scanner input = new Scanner(System.in);

    mainMenu(input);

    System.out.println("Program terminated...");
    input.close();
}

private static void mainMenu(Scanner input) {
    int option = 0;

    do {
        System.out.println("Option 1: Simple one dimensional array.");
        System.out.println("Option 2: Simple two dimensional array. (under construction)");
        System.out.println("Option 0: Exit program");

        option = user_option.nextInt();
        System.out.println("current option is: " + option);

        switch(option) {
            case 1:
                //simple array input method
                simple_a1();
                break;
            case 2:
                simple_a2();
                break;
            case 0:
                return;
            // In C# the `case else` is `default`, not sure what Java's is
            default:
                System.out.print("Invalid option: " + option);
                break;
        }

        System.out.println(", back to main menu");
    } while (option != 0);
}

We've got all our major components separated, and we can clearly see what each section is supposed to do.

Overall, good start, I hope to see more from you here. :)


Yeah it's hard to read and only by looking at the source for RowFilter can you understand that it's injecting props into the child component that is given to it. Instead of passing it in as a child, you should pass it in a component prop.

<RowFilter data={data} component={List} />

Then in RowFilter.js, the render simply looks like this. Note the component prop gets renamed to uppercase.

<Component data={this.state.filteredData} />

Here's an updated example on codesandbox


Execute every Monday that is not the Monday following last Saturday in month

Sometimes, comments aren't the clearest way to make a script readable:

IF (
        (--is it a monday?
            SELECT DATEPART(dw,@now)
        ) = 2

Consider:

declare @MONDAY int;
set @MONDAY = 2;

if (datepart(weekday,@now) = @MONDAY)

Does one need a comment to figure out what's going on? I hope not!

This part however:

DECLARE @now DATETIME = DATEADD(dd,DATEDIFF(dd,'19000101',SYSDATETIME()),'19000101');

If it wasn't of the @now identifier, I'd wonder what this convoluted assignment intends to do.

Why not just do this instead?

declare @now date = cast(getdate() as date);

I mean, why work with a datetime when clearly you're only interested in the date part from that point on?

I find there's way too much whitespace in your code, you need to strike a balance between wall-of-code and air code.

Now, changing @now from a datetime to a date will break your code. The @now-2 here:

DATEDIFF(DAY, @now-2, DATEADD(MONTH,DATEDIFF(MONTH,0,@now-2)+1,0)-1

...is illegal because...

I would extract that bit of logic into its own variable, for readability's sake, and using a dateadd function there would be no issue with subtracting 2 days from that date.


Server side validations and unit testing in MVP

I think you have a typo in the last outside if statement, I assume you meant two different variables when you wrote this:

if((!string.IsNullOrWhiteSpace(this.View.FromCustomerId) && !string.IsNullOrWhiteSpace(this.View.FromCustomerId) && (isValidFromCustomerId && isValidFromCustomerId))
{
    if(parsedFromCustomerId > parsedFromCustomerId)
    {
        errorCodes.Add("ERR_InvalidCustomerIdRange");
    }
}

parsedFromCustomerId will never be greater than parsedFromCustomerId

and the obvious one that won't cause a bug but probably won't give you the intended results is

 (isValidFromCustomerId && isValidFromCustomerId)

I assume you mean to put a different boolean variable in there instead of the same one twice.

this code won't function, correctly.

probably a Typo but you should proofread your code again just to make sure.


My primary concern with this implementation is the fact that it is recursive and thus the amount of stack that you are consuming is directly proportional to the length of the linked list.  If the linked list is something like 10 nodes long, you are likely going to be fine.  However, if it is 1,000,000 nodes long then that is something that you can expect to blow the stack.

I would recommend rewriting the algorithm to not use recursion.  This can be done in the following manner.

node = list->head;
if (node is NULL) then there is nothing to do

for (next = node->next; next != NULL; next = node->next) {
    remove 'next' from the list

    /*
     * the act of removing 'next' from the list will automatically
     * update node->next.  Note that 'node' never changes.
     */

    add 'next' to the head of the list
}

Hope this helps.


Longest common subsequence length and backtracking the string

Yes, you can easily convert the get_path function to an iterative version.

def get_path(a, b, dp, i, j):
    seq = ""
    while(i != 0 and j != 0):
        if a[i-1] == b[j-1]:
            i-=1
            j-=1
            seq += a[i]
        else:
            if dp[i-1][j] > dp[i][j-1]:
                i-=1
            else:
                j-=1
    return seq[::-1]

And now you can merge this function with calculate_lcs_length into one if you want.

I guess you have read this, but I just want to remind you that all described optimizations are still applicable to your code.


Modifying list while iterating during Breadth-first search

I do not know what is considered pythonic, but when doing a BFS, it is preferable to use a while loop. Also, you can use the queue (or Queue in Python 2.7) module for more intuitive operations:

from queue import Queue

def BFS(start=1, adj_dict=None):
    queue = Queue()
    already_seen = set()
    level = {}

    # this is our "seed" at starting level = 0
    queue.put_nowait((start, 0))

    while not queue.empty():
        # get the topmost element of the queue
        curr_node, curr_level = queue.get_nowait()

        # make sure not to process element more than once
        if curr_node not in already_seen:
            already_seen.add(curr_node)
            level[curr_node] = curr_level

            # add all of the current node's neighbors to the queue
            for neighbor_node in adj_dict[curr_node]:
                queue.put_nowait((neighbor_node, curr_level + 1))
    return level


There is already a reverse order Comparator built-in to Java. You could also use Arrays.asList(T...); like,

List<Integer> listOne = Arrays.asList((Integer) 1, 5, 10, 6);
System.out.println(listOne);
Collections.sort(listOne, Comparator.reverseOrder());
System.out.println(listOne);

And if you're using Java 8+, you could do the same with a Stream on one line (assuming you don't need to preserve the reverse sorted List) like

System.out.println(IntStream.of(1, 5, 10, 6).boxed().sorted(Comparator
            .reverseOrder()).collect(Collectors.toList()));


Can't you use a
std::this_thread::sleep_for(std::chrono::milliseconds(x));
or
nanosleep()?

Using any of the two sleeps the cpu will be free to do anything else that needs doing meanwhile this process is sleeping. Also this way it can controls doing the rendering at a specific rate and it´s not a good idea to use a while(true) without any sleep because it eats up all the processing time.


Filter a collection in a PagedCollectionView

If performance is your concern, won't boxing and unboxing the variable unnecessarily add an overhead? Why would you want to do that?

Wouldn't this be much easier?

this.AutoDepRuleList //if this is queryable/enumerable, or convert first
.Where(r => (isDisabled && r.Status.Equals("Disabled")) ||
             (isEnabled && r.Status.Equals("Enabled")) ||
              (!isDisabled && !isEnabled))
//either ToList() if you just need to assign to another list, or ForEach if you want
//to iterate over list and do something
    .ForEach(filterList.Add);

Update: had forgotten the condition where both isDisabled and isEnabled were false.


Yet another Pascal triangle in Python written in functional programming pattern

If you look at the documentation for lru_cache you'll see that it says that it can save time when an expensive or I/O bound function is periodically called with the same arguments. You keep calling pascal_row with different arguments and the cache will miss all the time. This can be seen if you put this at the end of your program the line:

print(pascal_row.cache_info())

Output:

CacheInfo(hits=0, misses=500, maxsize=128, currsize=128)

The only other thing I'd say is that you don't really need the -*- coding: utf-8 -*- line, UTF8 is the default and that's what you're using anyway.


It would help if you format your solution so that it can be copy and pasted into demonstrable code and if you provide a case where it times out.

In general if you're trying to find the shortest path (for example in a GPS) you would prune paths as you go, i.e. if you are trying to find the shortest route from A to E, you might calculate A-B-D and A-C-D, if A-B-D is shorter then you would prune A-B-D from the set of paths under consideration and not bother to calculate A-C-D-E.

That said I would just iterate through each cell calculating the cheapest way there (either from above or the left):

const minPath = (grid, x, y) => {

  function makeArray(width, height) {
    let outputArray = new Array(height);
    let row         = new Array(width);
    for(let iy = 0; iy < height; iy++) {
        outputArray[iy] = row.slice();
    }
    return outputArray;
  }

  function initArrayBorders(outputArray, grid, width, height)  {
    outputArray[0][0] = grid[0][0];
    for (let ix = 1; ix < width; ix++) {
      outputArray[ix][0] = outputArray[ix-1][0] + grid[ix][0];
    }
    for (let iy = 1; iy < height; iy++) {
      outputArray[0][iy] = outputArray[0][iy-1] + grid[0][iy];
    }
  }

  function fillArray(outputArray, grid, width, height) {
    for (let ix = 1; ix < width; ix++) {
      for (let iy = 1; iy < height; iy++) {
        let minWeight = Math.min(outputArray[ix-1][iy],
                                 outputArray[ix][iy-1]);
        outputArray[ix][iy] = minWeight + grid[ix][iy];
      }
    }
  }

  let width = x + 1, height = y + 1;
  let outputArray = makeArray(width, height);
  initArrayBorders(outputArray, grid, width, height);
  fillArray(outputArray, grid, width, height)
  console.table(outputArray);

  return outputArray[x, y];
};

console.clear();
console.log( minPath( [
  [1,2,3],
  [4,8,2],
  [1,5,3],
], 2, 2) );

I'm sure Google would also provide some other solutions.


Overview:

Instantiating a random engine is relatively expensive. Also creating one each loop does not increase your entropy (more likely decreases but I am not a mathamtician so don't homd me to that). BUT it is fine to create it once:

// Do this once at the beginning of the function
std::default_random_engine gen(std::chrono::system_clock::now().time_since_epoch().count());

Modern C++ techniques:

// C++ 03
for (std::vector<std::vector<double>>::iterator c_iter = c.begin(); c_iter != c.end(); ++c_iter)

In C++ 11 we can let the compiler determine the type:

// C++ 11
for (auto c_iter = c.begin(); c_iter != c.end(); ++c_iter)

In C++14 they introduced range based for()

// C++ 14
for (auto& cValue : c) //  Note:: cValue => *c_iter from the above examples.

Looking at the inner loop:

    std::vector<double>::iterator d_iter = (*c_iter).begin();
    while (d_iter != (*c_iter).end()) {
        // STUFF
        ++d_iter;
    }

We replace this while loop with a for loop.

   for (auto d_iter = (*c_iter).begin(); d_iter != (*c_iter).end(); ++d_iter)

Which of course we can then apply all the above transformations on and get the same result:

   for (auto dValue: *c_iter)

We should also note that -> is short hand for (*).

   // eg:
   (*c_iter).begin()

   // written more succinctly as:
   c_iter->begin()

Over Complex

(k % c.size() == 0) ? (subsec = (k + ct) / c.size()) : (subsec = 1 + ((k + ct) / c.size()));

First of that is hard to read. Spread it out:

(k % c.size() == 0)
    ? (subsec = (k + ct) / c.size())
    : (subsec = 1 + ((k + ct) / c.size()));

Second this relies on sideeffects of the expression. This is usually not a good idea. Let expressions by simple (with no side affects). Use the result of the whole thing to do the assignment:

subsec = (k % c.size() == 0)
    ? ((k + ct) / c.size())
    : (1 + ((k + ct) / c.size()));

// Also this:
rout << (norm) ? "normally" : "uniformly";  // from your monstrocity.

I also think I see a common sub expression in there. Extract that and assign it to a meaningful variable name to help document your code:

auto someMeaningfulName = (k + ct) / c.size();
subsec = (k % c.size() == 0)
    ? someMeaningfulName
    : 1 + someMeaningfulName;

OK. Now I can make this even more readable:

auto someMeaningfulName = (k + ct) / c.size();
subsec = someMeaningfulName + ((k % c.size() == 0) ? 0 : 1);

One line per declaration

std::ofstream fout, rout;
fout.open(file_out);
rout.open(file_rpt);

Use one line to declare each variable (and put some more meaningful names on them). Also there is no reason to explicitly call the open() method as this is handeled by the constructor:

std::ofstream fout(file_out);
std::ofstream rout(file_rpt);


A simple game that keeps track of the number of questions asked

You're doing some weird things with the scripts. I consider the first to be better, since especially in the second one, you're doing a lot of things with variables which we have better ways to do. I'll point those out separately - lets first have a look at your first script.

Your first script

Code Duplication

If you find yourself typing the same thing a lot, you're probably doing something wrong. Examples of this are incrementing z and printing the message.

Variable Names

Variables should have short but meaningful names. That means that if you find yourself using variables like z or n, you're probably doing something wrong somewhere.

Loops and termination

We have a really nice command named break in python. It will terminate the inner-most loop. Using this will obsolete all nested loops your currently have.

I'll keep using while loops here, but you might also want to try the following instead:

from itertools import count

for iteration in count(1):
    # do stuff...
    if we_are_done():
        break

this function is basically an infinity list - it's doing exactly the same as:

iteration = 0
while True:
    iteration += 1
    # do stuff....
    if we_are_done():
        break

Which we'll be doing all the time here.

Keeping that all in mind....

iteration = 0
while True:
    command = input("Go Left or Right?")
    if "left" in command.lower():  # Transforms the input to all lowercase. This makes it case-insensitive.
        # We also use "in" as membership test, so that whitespace is ignored, and even an command like
        # "go left" will be considered valid.
        break  # Terminates the loop.
    iteration += 1
    print(f"You lose * {iteration if iteration < 4 else 'infinity'}")
print("\nYou Win!")

This will do the same as your first script. In the loop, we get the input. We decide if we have won yet, and if we do, we break out. Then we increment the iteration variable. Then we print how often we've moved wrong before, or if it's more than 3 times, we instead print we lost * infinity.

If you're confused by the way we put our variable in that string, you should read up on f-strings. If you're confused by how we print that number, read up on ternary expressions. A good python programmer will know both. If the python version allows it, (s)he'll probably also use both.

Now lets dissect your second function...

I'll ignore everything I've already said something about regarding the first script.

Variable instantiation - don't do it unless you have to

v = 0
z = 0
u = 0
x = 0
n = 0

If you find yourself writing something like this, you should ask yourself if you really need all those. Generally, you'll only instantiate variables in python when you need them, and leave them undefined as long as you don't. IF, and this is a big if, you really need them, you'd write it like this:

v = z = u = x = n = 0

How not to loop

Your outer loop should of course be either with count() or while True:. But the first inner loop is just obsolete alltogether. It cannot run more than once, since there's an u == 0 requirement for it to run, and at the end of the loop you unconditionally set it to " ", which is a totally different something. Your second inner loop does the exact same thing, but with v.

For both of these, you should at the least change the loops to if statements. However, if you also do the following paragraph, you can just remove them and unindent your code instead.

Do it just once if you can.

You check for n not in ["left", "Left"] twice. Of course, the first time is to guard against the printing, and the second is to break out of your loop. If you just break at the top, you'll have avoided having to do it twice.


Unisex Bathroom problem without semaphore

System.out.println(sex + " using bathroom. Current employees in bathroom = " + size);

This line is not protected by lock, so it is possible that size can change before the output is generated.

For example, if two 'M' arrive simultaneously, you could get as output:

M using bathroom.  Current employees in bathroom = 2
M using bathroom.  Current employees in bathroom = 2

which omits outputting ... = 1.

inUseBy is left as the last occupant, even when size decreases to 0.  In the constructor, it is initialized to "", implying that the empty string might also indicate the bathroom is available to any gender.  When you decrease size to zero, you should clear inUseBy.


declare the variables inside "rTags.each()" on the outside.  This way there not being declared on each iteration.
The naming of parameters "window" and "Date". I would suggest naming them something different to avoid confusion. This way you can distinguish between the globals from the parameters.
Since you variables are scoped in the functions you can drop the "r" if you wanted too.


Print out symmetric matrix from compactly stored array

I think it the following is a good approach:
//use lowercase on non constant values
void print_symmetric_packed_matrix(double* compact_matrix, int n)
{
    const int entries = N*N;
    for (int i = 0; i < entries;)
    {
        //i++ here avoids i != 0 each iteration
        printf("%f ", compact_matrix[i++]);
        if (i % N == 0) printf("\n");
    }
}

I hope it helped you.


Excel VBA speed up code to hide rows/delete color

Your test for hidden rows suggests you may already have hidden rows.

Nested IF statements could reduce the number of tests to be done.

As you are removing color from all cells, do it before the loop:

Sub Color()
    Dim myRange As Range
    Dim cell As Range
    Application.ScreenUpdating = False
    Set myRange = ThisWorkbook.Sheets("Print version").Range("Print_Area")
        myRange.Interior.ColorIndex = 0
        For Each cell In myRange
            if Not cell.EntireRow.Hidden then
                '  once hidden, no more cell values will be tested on the row
                If cell.HasFormula = True And cell.Value = "" then
                    Rows(cell.Row).EntireRow.Hidden = True
                endif
            endif
        Next
    Application.ScreenUpdating = True
End Sub


Ways of improving/optimizing:

draw_board function.

prefer enumerate(board) over redundant list(range(len(board)))
all conditional branches within for loop have the same common expression to append '  ' + str(board[number]) + '  '. Thus, it can be moved up to reduce conditional branches
prefer flexible f-string formatting over awkward string concatenation combined with casting to str

Now the optimized draw_board function would look as:

def draw_board(board):
    display_board = ''

    for i, v in enumerate(board):
        display_board += f'  {v}  '
        if (i + 1) % 3 == 0:
            if i < 6:
                display_board += '\n—————————————————\n'
        else:
            display_board += '|'

    return display_board

check_win function introduces many repetitive checks all(item == letter for item in board[...]) with the same returned value.
A more flexible way is to create an additional function to check crossed row:

def row_crossed(letter, row):
    return all(item == letter for item in row)

Then, check_win would call any function on generator expression that yields all the needed sub-checks:

def check_win(board, letter):
    return any((row_crossed(letter, board[:3]), row_crossed(letter, board[3:6]),
            row_crossed(letter, board[6:9]), row_crossed(letter, board[::3]),
            row_crossed(letter, board[1::3]), row_crossed(letter, board[2::3]),
            row_crossed(letter, board[::4]), row_crossed(letter, board[2:8:2])))

square dictionary. To reduce quotes mess it can be composed in concise way with zip and range functions:

squares = dict(zip(('nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se'), range(9)))

tic_tac_toe_board easily replaced with tic_tac_toe_board = ['.'] * 9
square.lower() repeats 4 times within main while loop. Instead, extract that expression into a variable at once and refer it:

square = input('Exactly type in the following available directions: {}  > '.format(', '.join(directions)))
square = square.lower()

the whole condition:

if x_turn:
    tic_tac_toe_board[squares[square.lower()]] = 'X'
    x_turn = False
else:
    tic_tac_toe_board[squares[square.lower()]] = 'O'
    x_turn = True

would be simplified as it relies on explicit negation of x_turn flag.Getting  2 lines against 6:

tic_tac_toe_board[squares[square]] = 'X' if x_turn else 'O'
x_turn = not x_turn


UX
Before diving into the code, I have a few points to mention about the user experience of it.

You're not resetting the Application.Statusbar before the procedure exits, which means whenever the code runs to completion, the Excel status bar remains "frozen" with the last processed folder.
You're warning the user that the operation may take a long time, regardless of how many folders/subfolders there actually are.
Message boxes are bare-bones, without a title or an icon, and punctuation is missing from the message strings.

Readability
The code itself reads a bit like a clogged script. Indentation is insufficient and inconsistent, and vertical whitespace is completely inexistent. This code needs to breathe a little - here's your code, without any other changes:
Private Sub PrintFolders()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim i As Integer

    Application.StatusBar = ""

    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Get the folder object
    Set objFolder = objFSO.GetFolder("C:\Temp")

    i = 1
    'loops through each folder in the directory and prints their names and path
    On Error GoTo handleCancel

    Application.EnableCancelKey = xlErrorHandler
    MsgBox "This may take a long time: press ESC to cancel"

    For Each objSubFolder In objFolder.subfolders
        Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
        'print folder name
        Cells(i + 1, 1) = objSubFolder.Name
        'print folder path
        Cells(i + 1, 2) = objSubFolder.Path
        i = i + 1
    Next objSubFolder

handleCancel:
    If Err = 18 Then
        MsgBox "You cancelled"
    End If

End Sub

Comments
There are way too many comments in that code. Good, valuable comments explain why code is doing what it does - the code itself should be self-explanatory about the what.
I would simply remove them... all.

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

Isn't too far from:
'increment i:
i = i + 1

Non-Responsiveness
You're running a pretty tight loop here:
For Each objSubFolder In objFolder.subfolders

    Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
    Cells(i + 1, 1) = objSubFolder.Name
    Cells(i + 1, 2) = objSubFolder.Path

    i = i + 1

Next objSubFolder

You never give Excel a chance to breathe and actually respond to the events you're sending - namely updating the statusbar and listening to ESC keypresses.
This would fix it:
For Each objSubFolder In objFolder.subfolders

    Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
    Cells(i + 1, 1) = objSubFolder.Name
    Cells(i + 1, 2) = objSubFolder.Path

    i = i + 1
    DoEvents

Next objSubFolder

...but it comes with a pretty high price: updating the status bar and listening for keypresses at each and every iteration will considerably slow down execution. How about reorganizing it a little, and only do that once every 10 iterations? Avoid magic numbers, give that value a meaningful name and assign it to a constant:
Const IterationsToUpdate As Integer = 10
For Each objSubFolder In objFolder.subfolders

    Cells(i + 1, 1) = objSubFolder.Name
    Cells(i + 1, 2) = objSubFolder.Path

    i = i + 1

    If i Mod IterationsToUpdate = 0 Then
        Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
        DoEvents
    End If

Next objSubFolder

Now, you're writing to worksheet cells in a loop, while keeping Excel relatively responsive. Are you sure you're writing to the correct worksheet?

Cells(i + 1, 1) = objSubFolder.Name
Cells(i + 1, 2) = objSubFolder.Path

Without an object reference, Cells is referring to the active sheet, which the user is free to change any time as the code runs. This is another UX issue if not a bug.

Performance
I'm willing to bet anything that your biggest bottleneck isn't the FSO, but actually writing to the cells. Of course you need to do that.. but do you need Excel to repaint its grid and verify that nothing needs to be recalculated every time you write to a cell? Of course you don't.
Switch it off:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Now, whenever you do that, you must handle runtime errors appropriately.

Error Handling
Your error handling is copy-pasted from MSDN, which is only an example to illustrate how a specific feature works - these examples are always focused on a very specific feature, and never about best practices.
Your method should fail cleanly, and correctly cleanup whether or not an error is raised - every error-sensitive method should be templated something like this:
Sub DoSomething()
    On Error GoTo CleanFail

    'implementation code here

CleanExit:
    'cleanup code here
    Exit Sub

CleanFail:
    'error-handling code here
    Resume CleanExit
End Sub

In your case, it would look something like this:
CleanExit:
    Application.Statusbar = False
    Application.Cursor = xlDefault
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Exit Sub

CleanFail:
    Const MsgTitle As String = "Operation not completed"
    If Err.Number = 18 Then
        MsgBox "Operation was cancelled.", vbInformation, MsgTitle
    Else
        MsgBox "An error has occurred: " & Err.Description, vbCritical, MsgTitle
    End If
    Resume CleanExit

Abstraction & Maintainability
If you need to change the folder to run it for, you need to change the code: it's screaming for a String parameter containing the root path to start searching in.
The procedure is also doing too many things. To add features you need to add more code to it, making it do even more things.
Consider these concerns:

Knowing what folder to start searching in
Acquiring the folders/subfolders' names
Warning the user about a potentially lengthy operation
Enabling/disabling/toggling screen updating, calculation, statusbar and cursor
Knowing what worksheet to output to
Dropping the folders/subfolders' names onto the output worksheet

Most of these concerns deserve a method of their own. Here's how I would write your code:
Option Explicit

Public Sub RenameMe()

    Dim rootPath As String
    rootPath = GetRootPath
    If rootPath = vbNullString Then Exit Sub

    Dim folders() As Variant
    Set folders = FindAllFolders(rootPath)

    Dim targetSheet As Worksheet
    Set targetSheet = Application.ActiveSheet

    OutputFolders targetSheet, folders

End Sub

Split concerns into small, immutable procedures - a procedure should ideally have no more than one reason to change. Doing that increases the abstraction level of your code, which instantly boosts readability, which in turn automatically reduces the possibility for hidden bugs.

Algorithm
If you noticed, the above snippet separates getting the folders and writing them to a worksheet. You may think "but I'll have to iterate all 6,000 folders twice, this is going to be so much slower!"... but I'll give you a hint: read up on Arrays and Ranges in VBA (bookmark that site!).
The crux is that you don't need to iterate anything other than the folders: you populate a 2D array as you go, and then write that entire array onto the worksheet in a single operation. Then your performance bottleneck will be the FileSystemObject, but at that point your code will be so unrecognizeable that it'll be worth posting another Code Review question! :)


bash script - sed - template file processing

You are parsing a JSON file using some UNIX tools. This is risky, since those can have so many edge cases that you will end up refactoring over and over.

For example, you mention that sed s/\\[Placeholder.A]/${MY_VALUE}/ is giving errors when $MY_VALUE has slashes. This is normal, since this is how it gets expanded:

sed s/\[Placeholder.A]/${MY_VALUE}/
                           ↓
sed s/\[Placeholder.A]/http://aaa.com/
#    ^                ^     ^^       ^

See? Too many slashes for a simple sed 's/find/replace/, thus it fails. You can solve this by using another separator:

$ sed 's/\[Placeholder.A\]/a/' file
{
    "networkMode": "bridge",
    "name": "a"
}
$ MY_VALUE="http://aaa.com"
$ sed "s/\[Placeholder.A\]/$MY_VALUE/" file
sed: -e expression #1, char 27: unknown option to `s'

# Let's use ? as a separator, for example
$ sed "s?\[Placeholder.A\]?$MY_VALUE?" file
{
    "networkMode": "bridge",
    "name": "http://aaa.com"
}

Instead, use jq, a command-line JSON processor. Given your file:

$ cat file
{
    "networkMode": "bridge",
    "name": "[Placeholder.A]"
}

See how easy is to replace the value in the "name" key:

$ jq '.name="a"' file
{
  "networkMode": "bridge",
  "name": "a"
}

If you want to use a variable then you will need to do some quotes-opening-closing:

$ MY_VALUE="http://aaa.com"
$ jq '.name="'$MY_VALUE'"' file
{
  "networkMode": "bridge",
  "name": "http://aaa.com"
}


Writing a generic casting extension-method

This design looks to me like a massive violation of KISS. For a start, I don't see the benefit of CastTo and CastTo<T>. It seems to me that they could be eliminated by tweaking the wrapped conversion methods to work more like int.TryParse with two return values: one to say whether the conversion succeeded, and the other to tell you what the result was. This doesn't necessarily need to use the same pattern of bool return value and out parameter for the result: it could use Tuple and C# 7's tuple unwrapping, for example. But it would simplify the 57 lines of code in the question to 19:

public static T To<T>(this object @this)
{
    if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
    {
        if (@this is string actualStringValue && _tryCastStringToDateTime(actualStringValue, out var result))
            return result;
    }

    else if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
    {
        if (@this is string actualStringValue && _tryCastStringToBoolean(actualStringValue, out var result))
            return result;

        else if (@this is int actualIntegerValue && _tryCastIntegerToBoolean(actualIntegerValue, out result))
            return result;
    }

    return (T) Convert.ChangeType(@this, typeof(T));
}

However, that code still raises red flags. There are situations where you have no choice but to use == typeof(...), but they are rare and mainly related to serialisation. Normally it's a sign that the code should be refactored. This method seems to be actively fighting against the type system. So I would agree completely with the person who told you that it's an abuse of generics. Consider also that if you expose the parse methods as

public static bool ToBool(this string str) { ... }
public static bool ToBool(this int i) { ... }
public static bool ToBool(this object obj)
{
    if (obj is string str) return ToBool(str);
    if (obj is int i) return ToBool(i);
    return (bool)Convert.ChangeType(obj, typeof(bool));
}

then in many actual use cases the compiler will be able to bind directly to the more specific method and skip the runtime checks.

(NB Code not tested, may have compile-time errors, but the principle is the important thing).


You are generally correct in using Application functions (SumIfs and CountIfs) over rolling your own functions, as the built-in functions in Excel should be optimized in the DLL than anything you could write in VBA. The difference in performance is due to the organization of the data.

The key to my example below is to pre-process the input data into a form that reduces the "lookup" time of all the data. For comparison sake, using SumIfs and CountIfs will always be working with your entire data range. Your data set may be large (40k+ rows), so these Excel functions will always take a fixed amount of time. I timed my example to process 45,500 rows in 44.8 seconds. (I'll share a GenerateData sub that I created to set up the inputs for you or anyone else to double-check my work.)

The simple reccommendation for processing large amounts of data is to use a memory-based array. You're already doing this with your arrTotal array. There are two main issues in performance with this: 1) the Excel functions are still accessing the Worksheet object to process SumIfs and CountIfs, and 2) there is no optimization in the arrTotal data to help speed things up. This is where my own example starts.

First, I want to create an array from the input data that is "ordered". In this case, it means a memory-based array with the data sorted first on Agente and then on Fecha Completa. Please note that my code calculates the used area of the spreadsheet in a manner that should always be accurate (see @MathieuGuindon's comment). This function returns an ordered array:

Private Function OrderedInputs() As Variant
    '--- first sort the input data by Agente, then by date
    With Hoja37
        Dim inputArea As Range
        Dim lastRow As Long
        lastRow = .Cells(.Rows.count, 1).End(xlUp).Row
        Set inputArea = .Range("A2").Resize(lastRow - 1, 6)
        With .Sort
            .SortFields.Clear
            .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SetRange inputArea
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply

            '--- now grab the data into a memory-based array
            Dim inputData As Variant
            inputData = inputArea.Value

            '--- assuming the original data was sorted by date, then by Agente
            '    we'll put it back
            .SortFields.Clear
            .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SetRange inputArea
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
    OrderedInputs = inputData
End Function

Having a sorted, ordered set of data is nice, but it's not nearly optimized enough yet. When you're processing this much data, you want to be able to immediately access any given agent's data. The way to do this is a Dictionary, using the agent's name as the key. Associated with each agent, is the date plus FCR1, FCR3, and FCR30 data values -- and there are multiple sets of this data for each agent. So for each agent, we can build a Collection of this data. The best way to do this is to create a simple object class called AgentData.

'--- Class: AgentData
Option Explicit

Public day As Date
Public fcr1 As Long
Public fcr3 As Long
Public fcr30 As Long

All the fields are public because you really don't need to manipulate the data going in or coming out. Building up a Collection of AgentData objects starts with looping through all the (ordered) input data by name, and creating a Collection entry for each date:

Private Function BuildAgentData(ByRef inputArray As Variant) As Dictionary
    '--- we're creating a Dictionary of Agentes for quick lookup
    '    each Item in the Dictionary is an ordered Collection of AgentData
    '    objects, i.e. the objects are in date ascending order
    Dim agentes As Dictionary
    Set agentes = New Dictionary

    Dim i As Long
    Dim thisAgente As String
    Dim aData As AgentData
    Dim allAgentData As Collection
    For i = LBound(inputArray, 1) To UBound(inputArray, 1)
        If thisAgente <> inputArray(i, 1) Then
            thisAgente = inputArray(i, 1)
            '--- create the first entry
            Set aData = New AgentData
            aData.day = inputArray(i, 2)
            aData.fcr1 = inputArray(i, 4)
            aData.fcr3 = inputArray(i, 5)
            aData.fcr30 = inputArray(i, 6)
            Set allAgentData = New Collection
            allAgentData.Add aData
            agentes.Add thisAgente, allAgentData
        Else
            '--- increase the size of the array by one and add the date
            Set allAgentData = agentes(thisAgente)
            Set aData = New AgentData
            aData.day = inputArray(i, 2)
            aData.fcr1 = inputArray(i, 4)
            aData.fcr3 = inputArray(i, 5)
            aData.fcr30 = inputArray(i, 6)
            allAgentData.Add aData
        End If
    Next i
    Set BuildAgentData = agentes
End Function

This reduces the beginning of your test sub to:

Dim sortedInputData As Variant
Dim agentes As Dictionary
sortedInputData = OrderedInputs()
Set agentes = BuildAgentData(sortedInputData)
Debug.Print "There are " & UBound(sortedInputData, 1) & " rows of input data."

There are changes to your Calcula functions, but the main test sub changes very little:

With Hoja4
    Dim arrTotal As Variant: arrTotal = .UsedRange.Value
    Dim fecha As Double
    Dim i As Long
    For i = 2 To UBound(arrTotal)
        fecha = arrTotal(i, 1)
        arrTotal(i, 13) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)
        arrTotal(i, 14) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)
        arrTotal(i, 15) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)
        arrTotal(i, 16) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)
        arrTotal(i, 17) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)
        arrTotal(i, 18) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)
    Next i
    .UsedRange.Value = arrTotal
End With

Each of the Calcula functions will now use both the sortedInputData and the agentes dictionary as inputs. Instead of being forced to loop through all 40,000+ rows to count and sum for every single agent, the function immediately accesses the collection of data for each agent (via the Dictionary), and then can loop through the Collection (which may have as many entries as needed, but still is far, far less than the original input set).

Private Function CalculaFCR2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _
                             ByVal agente As String, ByVal fecha As Date, _
                             ByVal dias As Long, ByVal columna As Long) As Long
    Dim fechaFin As Date
    fechaFin = fecha + dias
    Dim sum As Long
    If agentDates.Exists(agente) Then
        Dim aData As Variant
        Set aData = agentDates(agente)
        Dim item As Variant
        For Each item In aData
            If (item.day >= fecha) And (item.day <= fechaFin) Then
                Select Case columna
                    Case 4
                        sum = sum + item.fcr1
                    Case 5
                        sum = sum + item.fcr3
                    Case 6
                        sum = sum + item.fcr30
                End Select
            ElseIf (item.day > fechaFin) Then
                Exit For
            End If
        Next item
        CalculaFCR2 = sum
    Else
        '--- error processing if the agente doesn't exist
    End If
End Function

Private Function CalculaLlamadas2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _
                                  ByVal agente As String, ByVal fecha As Date, _
                                  ByVal dias As Long, ByVal columna As Long) As Long
    Dim fechaFin As Date
    fechaFin = fecha + dias
    Dim count As Long
    If agentDates.Exists(agente) Then
        Dim aData As Variant
        Set aData = agentDates(agente)
        Dim item As Variant
        For Each item In aData
            If (item.day >= fecha) And (item.day <= fechaFin) Then
                count = count + 1
            ElseIf (item.day > fechaFin) Then
                Exit For
            End If
        Next item
        CalculaLlamadas2 = count
    Else
        '--- error processing if the agente doesn't exist
    End If
End Function

I added a software timer class to measure execution time on my laptop (Intel Core i5-6300, 2.40GHz) and received the following results:

There are 4550 rows of input data.
Time to build ordered inputs: 0.078 seconds
Total Run Time: 4.407 seconds

There are 45500 rows of input data.
Time to build ordered inputs: 0.484 seconds
Total Run Time: 44.797 seconds

For reference, here are the three code modules you need to add:

Class: AgentData

'--- Class: AgentData
Option Explicit

Public day As Date
Public fcr1 As Long
Public fcr3 As Long
Public fcr30 As Long

Class: StopWatch

Option Explicit
'--- from https://stackoverflow.com/a/939260/4717755

Private mlngStart As Long
Private Declare Function GetTickCount Lib "kernel32" () As Long

Public Sub StartTimer()
    mlngStart = GetTickCount
End Sub

Public Function EndTimer() As Long
    EndTimer = (GetTickCount - mlngStart)
End Function

Code Module: Module1

Option Explicit

Sub Test()
    Dim sw As StopWatch
    Set sw = New StopWatch
    sw.StartTimer

    Dim sortedInputData As Variant
    Dim agentes As Dictionary
    sortedInputData = OrderedInputs()
    Set agentes = BuildAgentData(sortedInputData)
    Debug.Print "There are " & UBound(sortedInputData, 1) & " rows of input data."
    Debug.Print "Time to build ordered inputs: " & CDbl((sw.EndTimer / 1000#)) & " seconds"

    With Hoja4
        Dim arrTotal As Variant: arrTotal = .UsedRange.Value
        Dim fecha As Double
        Dim i As Long
        For i = 2 To UBound(arrTotal)
            fecha = arrTotal(i, 1)
            arrTotal(i, 13) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)
            arrTotal(i, 14) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)
            arrTotal(i, 15) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)
            arrTotal(i, 16) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)
            arrTotal(i, 17) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)
            arrTotal(i, 18) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)
        Next i
        .UsedRange.Value = arrTotal
    End With
    Debug.Print "Total Run Time: " & CDbl((sw.EndTimer / 1000#)) & " seconds"
End Sub

Private Function CalculaFCR2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _
                             ByVal agente As String, ByVal fecha As Date, _
                             ByVal dias As Long, ByVal columna As Long) As Long
    Dim fechaFin As Date
    fechaFin = fecha + dias
    Dim sum As Long
    If agentDates.Exists(agente) Then
        Dim aData As Variant
        Set aData = agentDates(agente)
        Dim item As Variant
        For Each item In aData
            If (item.day >= fecha) And (item.day <= fechaFin) Then
                Select Case columna
                    Case 4
                        sum = sum + item.fcr1
                    Case 5
                        sum = sum + item.fcr3
                    Case 6
                        sum = sum + item.fcr30
                End Select
            ElseIf (item.day > fechaFin) Then
                Exit For
            End If
        Next item
        CalculaFCR2 = sum
    Else
        '--- error processing if the agente doesn't exist
    End If
End Function

Private Function CalculaLlamadas2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _
                                  ByVal agente As String, ByVal fecha As Date, _
                                  ByVal dias As Long, ByVal columna As Long) As Long
    Dim fechaFin As Date
    fechaFin = fecha + dias
    Dim count As Long
    If agentDates.Exists(agente) Then
        Dim aData As Variant
        Set aData = agentDates(agente)
        Dim item As Variant
        For Each item In aData
            If (item.day >= fecha) And (item.day <= fechaFin) Then
                count = count + 1
            ElseIf (item.day > fechaFin) Then
                Exit For
            End If
        Next item
        CalculaLlamadas2 = count
    Else
        '--- error processing if the agente doesn't exist
    End If
End Function

Private Function OrderedInputs() As Variant
    '--- first sort the input data by Agente, then by date
    With Hoja37
        Dim inputArea As Range
        Dim lastRow As Long
        lastRow = .Cells(.Rows.count, 1).End(xlUp).Row
        Set inputArea = .Range("A2").Resize(lastRow - 1, 6)
        With .Sort
            .SortFields.Clear
            .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SetRange inputArea
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply

            '--- now grab the data into a memory-based array
            Dim inputData As Variant
            inputData = inputArea.Value

            '--- assuming the original data was sorted by date, then by Agente
            '    we'll put it back
            .SortFields.Clear
            .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _
                            Order:=xlAscending, DataOption:=xlSortNormal
            .SetRange inputArea
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
    OrderedInputs = inputData
End Function

Private Function BuildAgentData(ByRef inputArray As Variant) As Dictionary
    '--- we're creating a Dictionary of Agentes for quick lookup
    '    each Item in the Dictionary is an ordered Collection of AgentData
    '    objects, i.e. the objects are in date ascending order
    Dim agentes As Dictionary
    Set agentes = New Dictionary

    Dim i As Long
    Dim thisAgente As String
    Dim aData As AgentData
    Dim allAgentData As Collection
    For i = LBound(inputArray, 1) To UBound(inputArray, 1)
        If thisAgente <> inputArray(i, 1) Then
            thisAgente = inputArray(i, 1)
            '--- create the first entry
            Set aData = New AgentData
            aData.day = inputArray(i, 2)
            aData.fcr1 = inputArray(i, 4)
            aData.fcr3 = inputArray(i, 5)
            aData.fcr30 = inputArray(i, 6)
            Set allAgentData = New Collection
            allAgentData.Add aData
            agentes.Add thisAgente, allAgentData
        Else
            '--- increase the size of the array by one and add the date
            Set allAgentData = agentes(thisAgente)
            Set aData = New AgentData
            aData.day = inputArray(i, 2)
            aData.fcr1 = inputArray(i, 4)
            aData.fcr3 = inputArray(i, 5)
            aData.fcr30 = inputArray(i, 6)
            allAgentData.Add aData
        End If
    Next i
    Set BuildAgentData = agentes
End Function

And at the bottom of Module1 is the bonus sub to create the input data:

Sub GenerateData()
    Dim names() As String
    '--- from http://listofrandomnames.com/
    names = Split("Lori,Norah,Valorie,Evita,Alden,Tressa,Carrol," & _
                  "Leeanna,Alexia,Marlyn,Wilhemina,Lanell,Kari," & _
                  "Rose,Arianne,Lesa,Royal,Maura,Sherie,Lahoma", ",")
    Const START As Date = #1/1/2020#
    Const FINISH As Date = #3/31/2020#
    Const LOGINS_PER_DAY As Long = 500

    '--- output setup
    Dim entry As Range
    Dim day As Date
    Dim i As Long
    Dim index As Long
    With Hoja4
        .Cells.Clear
        .Range("A1").Value = "Fecha"
        .Range("B1").Value = "Login"
        .Range("F1").Value = "Centro"
        .Range("F1").Value = "Centro"
        .Range("M1").Value = "Encuestas 1"
        .Range("N1").Value = "FCR 1"
        .Range("O1").Value = "Encuestas 3"
        .Range("P1").Value = "FCR 3"
        .Range("Q1").Value = "Encuestas 30"
        .Range("R1").Value = "FCR 30"
        Set entry = .Range("A2")
        For day = START To FINISH
            For i = LBound(names) To UBound(names)
                entry.Cells(1, 1).Value = day
                entry.Cells(1, 2).Value = names(i)
                Set entry = entry.Offset(1, 0)
            Next i
        Next day
    End With

    '--- input setup
    With Hoja37
        .Cells.Clear
        .Range("A1").Value = "Agente"
        .Range("B1").Value = "Fecha Completa"
        .Range("D1").Value = "FCR 1"
        .Range("E1").Value = "FCR 3"
        .Range("F1").Value = "FCR 30"
        Set entry = .Range("A2")
        For day = START To FINISH
            For i = 1 To LOGINS_PER_DAY
                index = CLng((UBound(names) - LBound(names)) * Rnd() + LBound(names))
                entry.Cells(1, 1).Value = names(index)
                entry.Cells(1, 2).Value = day
                entry.Cells(1, 4).Value = IIf(Rnd() > 0.5, 1, 0)
                entry.Cells(1, 5).Value = IIf(Rnd() > 0.5, 1, 0)
                entry.Cells(1, 6).Value = IIf(Rnd() > 0.5, 1, 0)
                Set entry = entry.Offset(1, 0)
            Next i
        Next day
    End With
End Sub


Let's see how your code computes out...

You loop for every position in the input string. Then, you find each possible string starting from there. So, for 1000 characters, that's 1000 + 999 + 998, etc. Which turns out to be \$\frac{1000^2}{2}\$ - or a half-million strings that you check.

Now, for each of those string values, you then check to see if they are a palindrome. Presumably, for each of those strings, in the isPlaindrome method, you compare the string to the reverse of the string, which means checking each character again.

That's another few iterations of each string, meaning your code ends up with a complexity in the order of cubic: \$O(N^3)\$.

Shavings

Now, there's ways to improve the code quite easily, for example, there's no point in checking (or even substringing) anything that's shorter than the current longest palindrome. In other words, why test 5 letter substrings if you've already found a 6 letter one? That will reduce the work you do, but, it will still be pretty slow.

Creating a string instance for each candidate is also not a great solution - you should find a way to do the palindrome checking on the original string, without making copies of sub-parts.

Still, I can't help but feel that the better solution is to reduce the computational complexity a lot, which makes scaling the code much better.

Algorithm

My suggestion is to change the algorithm. Your current one checks every possible substring in the input to find a palindrome. A better solution would be to only test strings which are "almost known" to be palindromes.

A palindrome is a word where the last half is a reflection of the first (in terms of letters). This implies that there is a middle of the reflection. If you can start at the middle of the reflection, and work outwards, until the reflection is broken, then you can compare what works with what you have already found, and move on.

Since there are even and odd sized palindromes, there are two types of "middle": two characters at the middle for even, and 1 character for odd sized palindromes.

There can be just one "middle" at each character in the input. If you can determine how wide the palindrome is spanning each middle, then you are one step ahead. At worst case, if the string is entirely 1 letter, like aaaaaaaaaaaaa, then you will have to check a lot of palindromes, and the worst-case performance is \$O(n^2)\$ (which is still a bunch better than your cubic approach). On the other hand, a reasonably random input will typically have mostly 1-letter palindromes, and they will test out very quickly, so a best-case complexity is just \$O(n)\$

I took the liberty of writing up a solution using the approach I describe:

std::string largestPalindrome(std::string input) {
    std::string largest = "";
    // offset is O or 1 for odd, and even sized palindromes.
    for (int offset = 0; offset <= 1; offset++) {

        for (int mid = 0; mid + offset < input.length(); mid++) {

            // max is the space between the mid and the end
            int max = input.length() - offset - mid;
            // ... unless the mid is closer to the beginning than the end.
            max = max > mid ? mid : max;

            for (int i = 0; i < max; i++) {
                if (input[mid - i] == input[mid + offset + i]) {
                    if (i + i + offset + 1 > largest.length()) {
                        largest = input.substr(mid - i, i + i + offset + 1);
                    }
                } else {
                    break;
                }
            }
        }
    }

    return largest;
}

Note, the mid-loop runs only twice (once for even, once for odd). The inner i loop will tend to be pretty small because it only runs while the strings centered on the mid point are actually palindromes.... and large palindromes will be the exception, not the rule.

There's only 1 big loop, in other words.

Additionally, substr is only called when there's a larger palindrome than previously seen... it's an uncommon call.

The above code runs the example str input in 3 milliseconds on my computer (and you can see it running in ideone too)


A few things that catch my eye, just skimming over your code:

Unconventional method names:

Java method names are supposed to be named strictly in camelCase. You're using some bastardized camel-snake-pascal-case which is something I'd expect when mixing together PHP, Python and C++... ~shivers
Use of outdated API:

Stack is a class in Java retroactively added to the Collections API, but it should've been officially deprecated since Java 1.5. It's been officially replaced by Deque, which is an interface that supports all stack-operations, see also Stack's javadoc:

  A more complete and consistent set of LIFO stack operations is
  provided by the Deque interface and its implementations

Returning a Collection from a method which begins with print

A method name should not lie. For a method named print... I'd expect to give something to be printed and some output channel (e.g. BufferedOutputWriter) with no return value. Instead you should name it something like traverseLevelOrder.
Overcomplicated helper method:

For a recursive traversal it's definitely not necessary to have a method that takes two nodes. Instead of relying on the caller to maintain the Stack you have, you may want to give the Stack (or better the Deque) into the recursive traversal for a level-order traversal. Also it's a significant difference whether you only want to traverse the nodes or also keep the traversal results in memory...
General recursive approach:

It might be a better option to actually do the level-order traversal with an "iterative" approach, by maintaining the nodes you still have to traverse in a queue that builds up by level and just process them back again. Following code should give you an idea:

void traverse(Node node) {
    Queue<Node> traversalQueue = new LinkedList<>();
    traversalQueue.add(node);
    while (!traversalQueue.isEmpty()) {
        // add nodes to queue by level
        // and pop the current:
        traversalQueue.add(node.left); // null-checks omitted
        traversalQueue.add(node.right);
        // use node.data
    }
}


Checking for culture in comma separated list, any suggestions?

I would do it like this (WARNING - not tested):

public static void SampleUsage()
{
    IsCurrentCultureIncluded("*", "*", Thread.CurrentThread.CurrentCulture.Name);
}

public static bool IsCurrentCultureIncluded(string includedCultures, string excludedCultures, string currentCultureName)
{
    return !CheckIncl(currentCultureName, excludedCultures) &&
            CheckIncl(currentCultureName, includedCultures);
}

private static bool CheckIncl(string currentCultureName, string includedCultures)
{
    if (includedCultures.IndexOf("*") != -1)
        return true;

    var includedCulturesSplit = includedCultures.Split(new[] { ',' });
    return includedCulturesSplit.Any(includedCulture => string.Equals(currentCultureName, includedCulture, StringComparison.InvariantCultureIgnoreCase));
}


Two approaches to print all permutations - returning versus passing through the “result” list

I think the question you are asking is:  Given a recursive algorithm, is there an inherent difference between diving deep and capturing a result at the deepest level of the recursion, vs. passing that result back up the chain to be captured at the shallowest level of recursion.

Inherently, there should not be much difference.

If we look specifically at your implementation though, there are big performance issues that far outweigh any difference in the method of recursion.

In your first code example, this operation is essentially an O(N^2) operation.

    int[] remnums = new int[nums.length-1];
    int j = 0;
    for(int cur : nums){
        if(cur != first){
            remnums[j] = cur;j++;
        }
    }

In each recursive call, you are copying the N items (and removing one), resulting in a total of N * N/2 copies.  (N/2) is the average number of items copied, as we copy N-1 items in the first level, and 1 item in the last level.

Then notice:

    for(List<Integer> t : tmp){
        t.add(0,first);
    }

Adding to the front of an ArrayList must shift everything else over.  So this is another O(n^2) operation.  (or is this actually n^3, given all of the lists?)

In the second code example, this is an O(n^2) operation:

   if(tempList.contains(nums[i])) continue; // element already exists, skip

This is an O(n) linear search, for each N.

So, (at least in this example) it's not the recursion that's a problem.  It's the choice of algorithm and data structures.


Well, if you are interested in number-theoretical solutions, take a look at the wiki page referenced in one of the comments to your question. It does not apply directly to your problem,  but you can lift some useful insights from it.

As to your "brute force" solution, first of all, note, that, when looking for divisors you only need to test values up to Math.sqrt(number), there is no need to go higher, because everything you can find there can be obtained easier by diving number by one of the divisors found so far.
Further, if a number is odd, it cannot have any even divisors, so once a test for number % 2 fails, there is no need to test 4 or 6 or 8 ... Same goes for other divisors: once you test and fail for number % 3, you can exclude 6, 9, 12 etc.

What this boils down to is that to find all divisors of a number you only need to test its divisibility by every prime number between 1 and Math.sqrt(number). If you find and hardcode a large enough list of first N primes, your program can be much faster, at least, for input numbers up to the last of your primes squared.


Iterating through an array and staying within bounds

You can use % remainder operator to be sure the value will be within bounds:

if (directionMoved == MoveDirection.Left) currentPageIndex--;
if (directionMoved == MoveDirection.Right) currentPageIndex++;

currentPageIndex += objectArray.Length;
currentPageIndex %= objectArray.Length;

This wiil allow you iterate in a circular way between 0 and objectArray.Length - 1.


Inserting JSON array data into a MySQL database using PHP

You are open to SQL Injection. To prevent this, use prepared statements.

You also should not mix mysql_ and mysqli_ functions; always use mysqli_ (or PDO).

Having variables that are only accessed once is only useful in a limited number of cases, eg when you want to give something a nice name to increase readability. But this is not the case with your variables, so they are really not needed and actually decrease readability. Jut use $inv->custInfo etc directly. This will also severely shorten your code.


Implementing Multi Producer Multi Consumer Simple Thread Safe Class

You have entered in the realm of concurrency. So there will be one or more functions which are competing to be executed. In other words there is no guarantee that your code will run in parallel.
If there is enough executor (CPU cores) then the runtime might schedule several threads to different cores. If there is not sufficient resource to be utilized then scheduler might use context switching.
Context switching will execute one portion of T1 and then it suspends T1 in order to avoid thread starvation (a single thread consumes all the available resources, while other threads remain idle). One portion of T2 is executed then it will be suspended. Now scheduler goes back to T1 to resume (hopefully finish) its current function.
These concepts are crucial to understand because these can cause strange behaviours for those that are used to program in a single threaded environment. Let me share with you a simple example:
Example

Let's suppose there is one item in the queue
Also let's assume that there are two consumers (T1 and T2) and they are both checking queue's length before they try to dequeue
So T1 and T2 are at the same line of where they are checking the queue's length
Scheduler suspends T1 after it successful checked the queue length
T2 dequeues the item from the queue
Scheduler resumes T1, which is in that belief that the queue has an item in it (which is not true, because T2 has already dequeued that)
T1 tries to dequeue item from the queue but it will fail because it could not get data from an empty queue

The problem here is that the check and the dequeue functionalities are not treated as atomic. If they were treated as atomic then T1 could not be suspended (by the scheduler or by the GC) between the two queue method calls.

Back to your code, there are several ways to improve it. (I'll respect your intent to learn so I will not suggest alternatives that are already done this)

Please do not use Task for the generic parameter name. It is a well-known structure in the .NET world. Please prefer either Job or Computation or what so ever.
As I can see you would like to use the keepRunning for signaling (either for cancellation or for completion). Unfortunately it is declared as false then set to true in the initialization phase and then it is never modified.
For locking the best practice is to introduce a private static readonly object lockObject = new object(); to avoid accidental exposure of your lock object. In your case the queue is protected, which means in a derived class it could be exposed publicly and a consumer of that derived class can add an extra lock for that. In that case the lock is out of your control.
Please prefer TryDequeue over Count check and Dequeue.
Please consider to use ConcurrentQueue or Synchronized Queue to avoid explicit locking.
5.1) As always measure implementations with different workloads, ConcurrentQueue vs Queue performance
According to my understanding holdTaskQueueItem will hold either one or zero item in it. A single Task or (Job/Computation) variable would be sufficient
Whenever you allow to your consumer to pass any function (in your case ConcumerCallback) then be very-very careful. What if it runs for minutes? What if it deadlocks because it also contains a lock inside it?


Implementing delegate methods in an UIView class

I personally separate my code in my view controllers using the comment //MARK: - which adds shortcuts to your code in the top navigation bar (the one that shows what file you're currently at). I would keep @IB related properties in your original view controller rather than make a extension for the @IBActions.

Also, making an extension for delegates is good practice because it helps separate your code from Apple's delegate methods. I don't see anything wrong with this approach since you can either make an extension to your view, or add it within the original class declaration, but as far as MVC goes, this would be the ideal approach.

As long as you're not doing heavy data/logic/algorithms going on, then you're good.

as for the delegate.doSomething() call, I don't see the point of using delegate since the scroll view delegate code is in an extension of the view, which means doSomething() is already accessible.


PHP form validation for name, email, and Twitter handle

Here are just few things I noticed.

Class names
I always try and use uppercase first letters, so DataException rather than dataException.

Exception
The errorMessage() method is redundant, as it just does the same as getMessage(), and it's also not used anywhere.

Function name
test_input doesn't really describe what the function does, as it doesn't actually test, so I renamed it clean_input, which better describes it.

Possible bug
The line if(str_word_count($name) != 2){ would give the error message FirstName and LastName is required if the user enter Homer J Simpson, so I change to see if the count is lower than 2, anything else is fine.

Unused variables
The $*Error variables are echoed, but never have a value assigned to them other than the empty string, so removed references to those.

Checking for data
This maybe more personal preference than anything, but when checking for POST data, I use if(!empty($_POST)).

<!DOCTYPE html>

    <title>PHP Form Validation</title>

    <?php
    $name            = '';
    $email           = '';
    $twitter         = '';

    class DataException extends Exception {}

    try {
        if(!empty($_POST)){
            if(empty($_POST["name"]) && empty($_POST["email"])){
                throw new DataException('Name and Email are required');
            }
            if(empty($_POST["name"])){
                throw new DataException('Name is required');
            } else {
                $name = clean_input($_POST["name"]);
                // check name only contains letters and whitespace
                if(!preg_match("/^[a-zA-Z ]*$/", $name)){
                    throw new DataException('Only letters and white space allowed');
                } else {
                    if(str_word_count($name) < 2){
                        throw new DataException('FirstName and LastName is required');
                    }
                }
            }
            if(empty($_POST["email"])){
                throw new DataException('Email is required');
            } else {
                $email = clean_input($_POST["email"]);
                // check if e-mail address syntax is valid or not
                if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)){
                    throw new DataException('Email is invalid');
                }
            }
            //checked vs internet.
            $twitter = clean_input($_POST['twitter']);
            if(!isset($_POST['twitter']) || $_POST['twitter'] === ''){
                $twitter = '';
            } else {
                if(!preg_match('/^(\@)?[A-Za-z0-9_]+$/', $twitter)){
                    throw new DataException('Invalid twitter handle');
                }
            }
        }
    } catch(DataException $e){
        echo 'Caught exception: ', $e->getMessage(), "\n";
    }

    function clean_input($data){
        $data    = trim($data);
        $data    = stripslashes($data);
        $data    = htmlspecialchars($data);
        return $data;
    }

    //php code ends here
    ?>

    <form action="" method="post">
        Name (FirstName and LastName):
        <input type="text" name="name" value="<?php echo htmlspecialchars($name); ?>">
        *

        E-mail:
        <input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>">

        Twitter:
        <input type="text" name="twitter" value="<?php echo htmlspecialchars($twitter); ?>">

        <input type="submit" name="submit" type="submit" value="Submit">
    </form>


Calculate grades based on pass/fail percentage

The function's parameters are implicitly passed by reference, which probably isn't the intent since none of the parameters are assigned/returned to the caller.

Signature should pass its parameters by value, like this:

Public Function Grade(ByVal Points As Integer, ByVal MaxByVal As Integer, ByVal Cesuur As Double) As Double

maxGrade and minGrade are only ever assigned once - they're essentially constants and could be declared as such:

Const MAXGRADE As Integer = 10
Const MINGRADE As Integer = 1

I would suggest to declare variables closer to their usage, and perhaps only assign the function's return value in one place.

Variables restPoints and restPass are only ever used with a passing grade, in that Else block. VBA doesn't scope variables at anything tighter than procedure scope, so you could extract a method to calculate a passing grade, but that's borderline overkill - here's what it would look like, with parameter casing to camelCase:

Option Explicit
Private Const MAXGRADE As Integer = 10
Private Const MINGRADE As Integer = 1

Public Function Grade(ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double

    Dim passPoints As Integer
    passPoints = cesuur * maxPoints

    Dim passGrade As Double
    passGrade = (MAXGRADE + MINGRADE) / 2

    Dim base As Double
    base = MAXGRADE - passGrade

    Dim result As Double

    If points < passPoints Then
        result = 1 + (passGrade - MINGRADE) * points / passPoints
    Else
        result = CalculatePassingGrade(MAXGRADE, base, points, maxPoints, cesuur)
    End If

    Grade = Round(result, 1)

End Function

Private Function CalculatePassingGrade(ByVal base As Double, ByVal points As Integer, ByVal maxPoints As Integer, ByVal cesuur As Double) As Double

    Dim restPoints As Integer
    restPoints = maxPoints - points

    Dim restPass As Double
    restPass = mxPoints * (1 - cesuur)

    CalculatePassingGrade = MAXGRADE - restPoints * base / restPass

End Function


It would be great if the code could be simplified using dynamic imports.  I haven't tried this myself but if the image names could be put into an array then something like the following might work, where the exported images are set as properties on an object that can be exported. When this SO answer to Create a loop to import files dynamically in React was written only Chrome and Safari supported that feature but since then it appears that Edge and Firefox now offer support as well.
const images = {};
const nums = [1, 2];
for (const format of  ['png', 'webp']) {
  for (const num of nums) {
    const key = `image${num}` + format === 'webp' ? 'webp' : '';
    images[key] =  await import( `./assets/image-${num}.${format}`);
  }
}

But according to the Hacks blog post by Jason Orendorff ES6 In Depth: Modules

For a dynamic language, JavaScript has gotten itself a surprisingly static module system.

All flavors of import and export are allowed only at toplevel in a module. There are no conditional imports or exports, and you can’t use import in function scope.
All exported identifiers must be explicitly exported by name in the source code. You can’t programmatically loop through an array and export a bunch of names in a data-driven way.

So the function code above could be exported in an async function:
export async function getImages() {
    const images = {};
    //...set keys on images
    return images;
}

Then that function can be imported:
import { getImages } from './assets.js';

But to use that function it would need to be run in an async function:
(async () => {
  const images = await getImages();
  //use images
})();

Other approaches are listed in answers to this similar post on freecodecamp.org - e.g. from this answer by Dan Couper:

One pretty simple solution:

// images.js
const images = [
  { id: 1, src: './assets/image01.jpg', title: 'foo', description: 'bar' },
  { id: 2, src: './assets/image02.jpg', title: 'foo', description: 'bar' },
  { id: 3, src: './assets/image03.jpg', title: 'foo', description: 'bar' },
  { id: 4, src: './assets/image04.jpg', title: 'foo', description: 'bar' },
  { id: 5, src: './assets/image05.jpg', title: 'foo', description: 'bar' },
  ...etc
];
export default images;

// MyComponent.js
import images from './images'
//...snip
{ images.map(({id, src, title, description}) => <img key={id} src={src} title={title} alt={description} />)

You’re basically writing a database of images that match the ones in assets.
Then you can be clever in images.js to pull the correct prefix based on the environment if you want. There will be a WebPack plugin that kinda does this as well if you have a google around (you want it to take a directory of files and generate an iterable set of paths to them).
The import as described is more for importing one-off images (logos etc) rather than importing lots of images from a directory.

Regarding the pseudocode at the end of the post:

export const toWEBP = (src) => {
  const location = src.split(".")
  return `${location}.webp`
}

if src contained an extension (e.g. png) then webp would be appended to that existing extension. One option would be to use pop to remove the existing extension and also push webp onto the array before using it in the return value.


Use reflection to check for class methods with a custom attribute

It's true that reflection is fairly slow, but for one-time operations the performance isn't usually a deal-breaker.

This method runs once-per-type, "some time before the view model is instantiated"

// optional type alias for clarity in this post
using MethodMap = System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<System.Reflection.MethodInfo>>;

public class ViewModelBase : ...
{
    protected readonly MethodMap ExecuteOnPropertyChangedMap;

    const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
    protected static MethodMap GetMethodMap<T>() where T : ViewModelBase
    {
        // slight variation on your code here
        var t = typeof(T);
        var map = new MethodMap();
        // This is up to personal preference, but I recommend using 'var' and a constant for Flags to make your code as human readable as possible
        foreach (var method in t.GetMethods(Flags))
        {
            foreach (var execAttribute in method.GetCustomAttributes(typeof(ExecuteOnPropertyChangedAttribute), true))
            {
                if (execAttribute == null) continue;
                foreach (string propertyName in execAttribute.PropertyNames)
                {
                    if (!map.ContainsKey(propertyName))
                        map.Add(propertyName, new List<MethodInfo>());
                    map[propertyName].Add(method);
                }
            }
        }
        return map;
    }

    // ...

    protected ViewModelBase(MethodMap map)
    {
        ExecuteOnPropertyChangedMap = map;
    }
}

Then in each of your view model types, you could add

public class MyViewModel : ViewModelBase
{
    private static readonly MethodMap map = GetMethodMap<MyViewModel>();

    public MyViewModel : ViewModelBase(map)
    {
        // ...
    }
}

You can put the logic for reflection and building your map in your base class - but your base class doesn't know about its sub types. So each of your sub types is responsible for passing info about itself up to the base class to provide it with an instance-level reference to the sub types map.

By setting a private static readonly in the sub type we ask C# to 'calculate this some time before we need it but we don't care exactly when',
as opposed to putting it in your constructor. If you put the call to the reflection code in your constructor it happens every time you construct the object (like you pointed out). With this it only happens once, 'some time' before you instantiate the first MyViewModel. In practice, the field will usually be set right before the first MyViewModel constructor is called.


Use a swap function rather then repeating the three lines required to swap elements three times
Put spaces around your operators
You avoid recursing for the second partition. I don't think the performance gain from this is sufficient for the extra complexity in your code.

Rather then swapping before/after for the element equal to the pivot, count the number of elements equal to the pivot. Then when you sort the subarray make the one subarray shorter so as not to sort the elements equal to the pivot.

Another issue as Rafe has noted is that there are other issues besides duplicate keys that can cause a O(n^2) behavior. Your code doesn't handle any of those.


Reimplementation of a Hashtable and hash function

Your container isn't what most people would call a hash table.  It doesn't use a deterministic hash function of its contents, and it doesn't give the expected performance.  That said, here are some other comments on your "container".

myHashtable.myHashFunction(elements, myHashtable.slots);

This is a strange name for the function that adds elements to your container.

private Object[] slots;
slots = new String[size];
public void myHashFunction(Object[] elements, Object[] slots)

Your class acts like it can work on any Object, but it will fail if given anything other than a String.

Arrays.fill(slots, "-1")

This is a strange string to use as your empty sentinel.  What happens if someone wants to add "-1" to your container?  What's wrong with null as an empty marker?


NullPointer Exception handling in the code

The general rule is:
never return null except it is a valid member of the result set.
Usually it is not as in your example.
Instead of returning a null after the IOException occurred you should either return an empty List or throw your own (Runtime-) Exception. Whch option to choose depends if havin no users is an expected use case whithin your application (e.g. resulting in an empty list presented to the user)  or if it is an error condition with the user gets presented as an explicit error message.
Your class Data should look like this:
public class Data {

    private static final Operations<User> operations = new FileOperations<User>();

    private static final List<User> users = new ArrList<>();

    public static List<User> getUsers() {
        users.clear();
        try {
            users.addAll(operations.get());
        } catch (IOException e) {
            e.getMessage();
        }
        return users;
    }
}

BTW:
avoid the use of static
declaring your methods static has a lot of Problems.
It makes your code inflexible, had to change and to maintain. It also throws away polymorphism which is the most powerful feature of OOP.
If you refure to work with objects you should ask yourself why you chose an OO language...


Getting a substring of a string in JavaScript

You don't need to over-complicate things. The myuser part will always come at the end of the string, after \\ if it's there.

All you need is this:

username.split("\\").pop();

Even if the username is entered like the third version, the myuser will be returned.


The best practice for dealing with temporary files is simply not to use them in the first place.  Many things can go wrong with temporary files:

Lack of permissions to write to a directory
Lack of disk space
Read-only filesystem
File or symlink already exists
File or symlink didn't exist when you checked, but got created immediately after, in a race condition
Script crashed, such that it created a temporary file but didn't get a chance to clean it up

Though there are ways to mitigate these risks, I see no reason to use a temporary file here at all.  For that matter, cat and the first grep are also superfluous.

#!/bin/sh

awk -F= '
    BEGIN {
        TABLE_FMT = "%-18s | %-58s"
        row = sprintf(TABLE_FMT, "ALIAS", "COMMAND");
        print row;
        gsub(".", "-", row);
        print row;
    }
    END {
        print row;
    }

    /^alias/ {
        gsub(/\s+/, " ", $0);  # Condense consecutive whitespace
        printf TABLE_FMT "\n", $1, $2;
    }
' < "$HOME/.zshrc" | grep --color '#.*\|$'

I can't tell for sure, but it looks like the second grep is meant to highlight comments.  Unfortunately, it actually ends up stripping out all uncommented lines, including the header and footer.

Instead of parsing the $HOME/.zshrc configuration file, you might want to query the live alias definitions in the current shell instead.  In that case, you should write a shell function that processes the output of the bare alias command.


Simple use of mouse clicks to position a ball

You can get the bounding rectangle for a canvas. Consider:

function click(evt) {
    'use strict';
    var bound = canvas.getBoundingClientRect();
    ball_pos[0] = evt.clientX - bound.left;
    ball_pos[1] = evt.clientY - bound.top;
}

This should help you to avoid walking up the stack of objects to find the relative position.

See it working here:

var canvas, context, ball_pos;

var BALL_RADIUS = 15;

function start() {
    'use strict';
    canvas = document.getElementById('c');
    context = canvas.getContext('2d');
    ball_pos = [canvas.width / 2, canvas.height / 2];
}

function draw() {
    'use strict';

    // draw background
    context.fillStyle = "rgb(248,248,248)"; // off white
    context.fillRect(0, 0, canvas.width, canvas.height);

    // draw ball
    context.strokeStyle = 'black';
    context.lineWidth = 1;
    context.fillStyle = 'red';
    context.beginPath();
    context.arc(ball_pos[0], ball_pos[1], BALL_RADIUS, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
    context.stroke();
}

function animate() {
    'use strict';
    window.requestAnimationFrame(animate);
    draw();
}

function click(evt) {
    'use strict';
    var bound = canvas.getBoundingClientRect();
    ball_pos[0] = evt.clientX - bound.left;
    ball_pos[1] = evt.clientY - bound.top;
}

// register event handlers
window.onclick = click;

start();
animate();
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <canvas id="c" width="600" height="400"></canvas>
</body>
</html>


A few notes:

Right now you are using int[]s to represent the sieve.  However, the int data type is internally stored as 32-bits, which is a waste of space.

Use java.util.BitSet to represent the sieve. It provides a vector of bits that grows as needed. All bits start out as 0, and we can set and clear a bit at any index. It uses only one bit per entry. This requires slightly more computation per access for address computation and bit manipulation, but is much more compact, and utilizes the data cache more efficiently. For larger ranges of integers, we expect memory access time to dominate computation time, making this the ideal solution to represent the sieve.

To save additional space and time, at the cost of some additional complexity, we can choose not to represent even integers in our sieve (since they are divisible by 2). Instead, the element at index k will indicate the primarily of the number 2k + 3. We abstract this complexity away by wrapping BitSet in a class exposing special indexer methods.

Right now you are using i = i + 2, which could be simplified to i += 2.

Final code:

import java.util.BitSet;
import java.util.List;
import java.util.ArrayList;

public class Sieve
{
    private BitSet sieve;

    public Sieve(int size)
    {
        sieve = new BitSet((size + 1) / 2);
    }

    public boolean isComposite(int k)
    {
        assert k >= 3 && (k % 2) == 1;
        return sieve.get((k - 3) / 2);
    }

    public void setComposite(int k)
    {
        assert k >= 3 && (k % 2) == 1;
        sieve.set((k - 3) / 2);
    }

    public static List<Integer> sieveOfEratosthenes(int max)
    {
        Sieve sieve = new Sieve(max + 1); // +1 to include max itself
        for (int i = 3; i * i <= max; i += 2)
        {
            if (sieve.isComposite(i)) continue;

            // We increment by 2*i to skip even multiples of i
            for (int multiplei = i * i; multiplei <= max; multiplei += 2 * i)
                sieve.setComposite(multiplei);
        }

        List<Integer> primes = new ArrayList<Integer>();
        primes.add(2);
        for (int i = 3; i <= max; i += 2)
            if (!sieve.isComposite(i)) primes.add(i);
        return primes;
    }
}


Note that a substitution only occurs if there is a match, and then it will return the number of substitutions it makes. This means that a true value is returned if a match/substitution happens.

With that in mind, you don't need the m/.../ in addition to the substitution. You can also make use of or to achieve the short-circuiting that you had with the if ... elsif ... else ... statements.

foreach (@grafs) {
    unless (defined $g_html_blocks{$_}) {
        $_ = _RunSpanGamut($_);
        s/^([ \t]*\?[ \t]*)/
/
            or
        s/^([ \t]*\![ \t]*)/
/
            or
        s/^([ \t]*%[ \t]*)/
/
            or
        s/^([ \t]*)/
/;
        $_ .= "
";
    }
}

For the image floating, you could use a hash instead of if ... else ...:

my %float = (
    '<' => 'float: left',
    '>' => 'float: right',
    '%' => 'clear: both'
);
if (defined $align) {
    $result .= " style=\"$float{$align}; margin: 0 ${padding}px ${padding}px 0;\"";
}

A minor point: I also removed the parens from the defined checks because they're not needed and it gives you a little more white space to reduce a little clutter.