Computing sums of weird pattern in 2D array as efficiently as possible

Drat. My super pretty NumPy solution which is probably efficient doesn't get accepted because HackerRank apparently doesn't support NumPy here. Oh well, here it is anyway, maybe interesting/amusing for someone.
import sys
import numpy as np

a = np.loadtxt(sys.stdin, dtype=np.int8)

h = a[0:4, 0:4] + a[0:4, 1:5] + a[0:4, 2:6]     + \
                  a[1:5, 1:5]                   + \
    a[2:6, 0:4] + a[2:6, 1:5] + a[2:6, 2:6]

print(h.max())

Or with less code repetition:
import sys
import numpy as np

a = np.loadtxt(sys.stdin, dtype=np.int8)

i, j, k = (slice(i, i+4) for i in range(3))

h = a[i,i] + a[i,j] + a[i,k]     + \
             a[j,j]              + \
    a[k,i] + a[k,j] + a[k,k]

print(h.max())

The 4x4 submatrix a[0:4, 0:4] contains the top-left value for each of the 16 hourglasses, a[0:4, 1:5] contains the top-middle value for each of the 16 hourglasses, etc. So adding them computes a 4x4 matrix containing the 16 hourglass sums.


htaccess with compression, caching, and rewrite rules for SEO

The first question I always ask when considering using an htaccess file is - does this really need to be in an htaccess file?  By that I mean ask yourself a few questions:

Do you have the ability to configure Apache on your host? (i.e. you are not in some shared hosting where htaccess is your only recourse.)
Is this configuration common to all directories in your application?
Can you restart Apache upon any necessary configuration changes?

If you answered "yes" to all of these questions, you should have this configuration in your main Apache server config, rather than in a directory context, and simply turn off directory overrides. This eliminates the performance hit of checking every directory for an htaccess file on every request that hits this server.  This is the best way of "improving" most htaccess files. Site performance can impact your SEO.

As long as you answered "yes" to the first question, you should still probably consider moving this configuration into Apache config as long as you don't have unusual needs such as not being able to restart server without complications (either on your site or possibly other sites on same servers) or having a high  frequency of change to this configuration logic such that you would be restarting the server too frequently.

You can also enter directory-specific configuration in the main Apache config, so typically just because you have different configs for different directories, this alone should not be a reason to stick with htaccess.

If you are using eTags and have multiple host serving traffic, turn of the iNodes component in generating the eTags so you get more consistent eTag values across servers, so long as your are appropriately deploying or "touching" your files to match modification times across servers.

i.e.

FileETag MTime Size

Also, if you are not using eTags, you might consider it such that, even if a cached item has passed expiry, the browser still may not need to download the item if the eTags haven't changed.

If you are worried about server bandwidth and overall performance consider:

moving your static assets onto a CDN which is better suited for delivery of the content to end user browsers;
minifying all applicable assets (i.e. don't have some JS that is not minified). Minification is different that deflation of course and more effective regarding overall download size.
using much longer expiry times for your static assets (i.e. many years) along with an asset versioning strategy to deal with browser caching behavior issues. Think in terms of when you are deploying a static asset, you are deploying it forever (file storage is cheap).
cusing SVG as part of your suite of tools for replacing iconography, sprite sheets, and other vector-friendly images. I know this is getting more into application design. :)


Retrieving the first occurrence of every unique value from a CSV column

You've given us a small piece of your problem to review, and Janne's suggestion seems reasonable if that piece is considered on its own. But I have the feeling that this isn't the only bit of analysis that you are doing on your data, and if so, you probably want to think about using a proper database.

Python comes with a built-in relational database engine in the form of the sqlite3 module. So you could easily read your CSV directly into a SQLite table, either using the .import command in SQLite's command-line shell, or via Python if you need more preprocessing:

import sqlite3
import csv

def load_flight_csv(db_filename, csv_filename):
    """
    Load flight data from `csv_filename` into the SQLite database in
    `db_filename`.
    """
    with sqlite3.connect(db_filename) as conn, open(csv_filename, 'rb') as f:
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS flight
                     (id INTEGER PRIMARY KEY AUTOINCREMENT, fid TEXT)''')
        c.execute('''CREATE INDEX IF NOT EXISTS flight_fid ON flight (fid)''')
        c.executemany('''INSERT INTO flight (fid) VALUES (?)''', csv.reader(f))
        conn.commit()

(Obviously you'd need more fields in the CREATE TABLE statement, but since you didn't show them in your question, I can't guess what they might be.)

And then you can analyze the data by issuing SQL queries:

>>> db = 'flight.db'
>>> load_flight_csv(db, 'flight.csv')
>>> conn = sqlite3.connect(db)
>>> from pprint import pprint
>>> pprint(conn.execute('''SELECT MIN(id), fid FROM flight GROUP BY fid''').fetchall())
[(1, u'20110117559515'),
 (4, u'20110117559572'),
 (7, u'20110117559574'),
 (8, u'20110117559587'),
 (9, u'20110117559588')]


There is an error in how you implement the Price property: according to the description your get for the price should return the number of words times 0.09. As it is, the Price will always return 0 as there is never a value assigned to it.

Try adding Console.WriteLine(Article.Price); inside your Main method for demonstration.

You can add this inside your class:

private const decimal pricePerWord = 0.09M;

Notice the use of decimal (including the M suffix) instead of double, which is a more appropriate type for currency/money values.

Then your get becomes:

public decimal Price
{
    get
    {
        return Words * pricePerWord;
    }
}

I would also recommend to make a constructor for ClassifiedAd that takes the number of words, since a classified ad without words would be nonsensical.

public ClassifiedAd(int words)
{
    this.words = words;
}

Also as suggested by Roman Gräf, a ToString override method would be a nice addition:

override public string ToString()
{
    return string.Format("The price of a {0} word classified ad is {1}\n", Words, Price);
}

Then your Main method can do everything by only using what your ClassifiedAd class provides:

static void Main(string[] args)
{
    ClassifiedAd ad = new ClassifiedAd(583);
    Console.WriteLine(ad.ToString());
    // The price of a 583 word classified ad is 52.47

    ad.Words = 900;
    Console.WriteLine(ad.ToString());
    // The price of a 900 word classified ad is 81.00
}


Don't name things str.
Use a list comprehension to build substr.
s+str[i+1:j] would be simpler as str[i:j].
Iterate through num, rather than the range(q)
Your can wrap your print keywords with (), so this is a bit more Python 3 compatible.

This can get:

S = raw_input()
q = int(raw_input())
nums = map(int, raw_input().split(' '))

substr = [
    S[i:j+1]
    for i in range(len(S))
    for j in range(i, len(S))
]

for i in nums:
    try:
        print(substr[i-1])
    except IndexError:
        print(-1)

However this uses \$O(S^3)\$ of memory. So about \$10^{15}\$, or 1 petabyte of storage. So your code doesn't feasibly work.
Instead work things in the reverse order.

If you have the number \$5\$, you know it's \$5 \gt 3\$, \$5-3 = 2\$, \$2 \le 2\$, and so is S[1:1+2]. And so I'd use:

S = raw_input()
q = raw_input()
nums = map(int, raw_input().split(' '))

for num in nums:
    for i, s in enumerate(reversed(range(1, len(S)+1))):
        if num <= s:
            print(S[i:i+num])
            break
        num -= s
    else:
        print(-1)

Which is still better than yours in terms of time complexity, as it's \$O(nS)\$, \$~10^8\$, rather than \$O(n + S^2)\$, \$10^3 + 10^{10}\$.


Come around limitation of CSingleLock don't accept NULL

Sure, that seems fine.

Obviously you should be using std::unique_ptr<CSingleLock> (and std::make_unique) instead of raw new and delete.
If you have access to C++17, Folly, or Boost, consider using std::optional<CSingleLock> to eliminate the heap allocation.
If you're not using unique_ptr, you might want to =delete your copy constructor and copy assignment operator (or in C++03, make them private), to ensure that nobody accidentally creates a copy of your object — which if they did would lead to a double-free.

You've also made your member variable _singleLock public, presumably by accident. If you actually want it to be public, consider giving it a more user-friendly name. It's best to keep it private, though.

A simpler approach would be to create a dummy lock, which (assuming either CSingleLock or CMutex is immovable) would actually fix the copyability problem as well.

class CSingleLockEx
{
    CMutex dummy_;
    CSingleLock lk_;
public:
    CSingleLockEx(CSyncObject *obj, bool initialLock = false) :
        lk_((obj ? *obj : dummy_), initialLock)
    {}
};

This way you end up locking something either way (and unlocking something in the destructor as well), but at least when obj==nullptr the "something" you're locking will definitely be uncontended. So I wouldn't expect a noticeable performance hit.


The pattern you have implemented is basically a reduction or foldLeft method.
Compare it to the Stream#reduce method in Java, it is very similar.

To answer your question about the complexity of the lambda to put into the method: There is no limit. You can do everything you like in there. A lambda expression is nothing more than an implementation of the single-method interface you have created. And there is no limit on the complexity of a class implementing an interface.

Now for some real code review:

Use proper and understandable names and use built-in types

Your interface is simply named func. This probably means "function" but you don't have to save on characters, Java is already quite verbose.
What you have, is a special kind of BiFunction or more precisely, BinaryOperator. Now I know that generics don't allow you to specify primitive types for the generic arguments, but your func interface is not necessary and  can be replaced by a BinaryOperator<Integer>.

Your run method has a very generic name. Sure, there is code that is run, but it doesn't explain, what this method does.
It would be more precise to call your method reduce or foldLeft or something similar, that explains in the name, what this method does.

Make your method do one thing

Currently your method calculates a result and, in addition to that, prints the value of result for every iteration. What if you or someone who uses your method does not want to have every single intermediate result printed to them?

If you want to print the intermediate values, do so in your lambda.

You wanted to think about the future

Your method currently only works with primitive integer arrays. Nothing stops you from making it work with generic types or even lists.
And if you go that far, you'll probably use streams anyway.


Reading multiple csv files in a single dataframe

Ultimate optimization

avoid calling pd.DataFrame.append function within a loop as it'll create a copy of accumulated dataframe on each loop iteration. Apply pandas.concat to concatenate pandas objects at once.

no need to gzip.open as pandas.read_csv already allows on-the-fly decompression of on-disk data.

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’

avoid hardcoding filepathes with path+"/"+filename. Instead use suitable os.path.join feature: os.path.join(dirpath, fname)

The final optimized approach:
import os
import pandas as pd

dirpath = 'path_to_gz_files'   # your directory path
df = pd.concat([pd.read_csv(os.path.join(dirpath, fname))
                for fname in os.listdir(dirpath)], ignore_index=True)


You can do more conversion as you read the data. The magic is done by the colClasses parameter to read.delim(). That parameter allows you to (1) convert the DateTime whilst reading and (2) drop unwanted columns.
Now I don't know what your data looks like, but here's a rough outline of how to read a datetime (untested). Note that you can do the + years(98) within the data-parsing class as well.
library(methods)
setClass("myDateTime")
setAs("character",
      "myDateTime",
      function(from) as.DateTime(from, format="%Y-%m-%d %H:%M:%S", tz=Sys.timezone())) + years(98)

d = read.delim(..., colClasses = c(..., "myDateTime", ...))

For the columns you want to drop, code them as "NULL" (note the quotes).
d = read.delim(..., colClasses = c("numeric", "myDateTime", "NULL", ...))

This not only shortens your code, but by explicitly telling read.delim() the datatype of each column the read is 2x faster. And of course there aren't two copies of the data in memory after the parsing.
You might also want to look at the skip= and col.names=c() parameters as they allow you to decide the names of the variables, rather than having those decided by the input file. If you decide to use colCLasses=c() you'll almost certainly want to skip the column headings rather than program a class which reads strings for row 1 and a different datatype for the remaining rows.
BTW, if you have to do complex manipulation of input data, then the tidyverse's readr and dplyr libraries have useful improvement over the shipped R libraries. Regardless of your use or not of Tidyverse, its book is worth reading if you are an R programmer: https://r4ds.had.co.nz/


Reduce the redundancy in my pandas highlight function

Your highlight_max function can be simplified a bit by passing the rows to mark as an argument (possibly with a default value), and putting it all into a list comprehension right away:

def highlight_max(column, to_mark):
    return ['background-color: yellow' if i in to_mark else '' for i in column.index]

Note that this takes the actual column as input. Yours took the df from the global scope, disregarding the input, which means that all things you did before the apply will probably be ignored.

Use it like this:

ROWS = {634, 636, 638, 640, 642, 644, 648, 649, 650, 651, 656}

if __name__ == "__main__":
    df = pd.read_excel('N:\Temp\filename.xlsx', index_col=False)
    df.reset_index(drop=True, inplace=True)
    styles = [{'selector': 'th,td',
               'props': [('border-style','solid'), ('border-width','1px')]}]
    html = df.style.set_table_styles(styles)\
             .apply(highlight_max, to_mark=ROWS)\
             .hide_index()\
             .render(index=False)

    with open('N://temp//test.html', 'w') as f:
        f.write(html)

I also made ROWS a set instead of a list for faster checking of in (not that it matters too much for such a small list, but it will if it gets bigger), used a style that makes the long chain of functions for html easier to read IMO, used the fact that any additional parameters passed to apply are passed along to the function to pass the rows to mark and wrapped the main code under a if __name__ == "__main__": guard to allow importing from this script without it running.


URL resolver for Users, Lessons, and Series

I might as well post this then:

def resolve_url(url)
    # Resolver library now returns a hash of objects
    # Using this helper method to preserve the old functionality of returning a single object
    # Order of old return types is Lesson -> Series -> User
    only = [Lesson, Series, User]
    objects = Resolver.resolve(url, :only => only)
    objects.values_at(*only).compact[0]
  end
end

So first get only the necessary fields (reusing the list from the resolve call), remove nils with compact and finally return the first value; if it's empty you still get nil back.

I've also removed my comment since you've updated your post.  FWIW you could also use something like objects[Lesson] or objects[Series] or Objects[User] instead.


String reverse and pairing reversed words

Reverse

Your Reverse function is functional, but there are some improvements I could suggest:

if you use the StringBuilder approach (which is OK), then you should at least initialize the size of the internal capacity so that resizes are not needed later (for performance reasons). Use StringBuilder s = new StringBuilder(str.Length);
While looking at that, why have the variable name s ... that's a poor choice.
Consider using a char[] array for the reverse as it reduces some more overheads (again, performance). StringBuilders are useful for many things, but their biggest benefit comes from their dynamic nature. In this case, that nature is not needed.

If it was me, I would have:

    public string Reverse(string forward)
    {
        char[] chars = forward.ToCharArray();
        var last = forward.Length - 1;
        for (int i = last / 2; i >= 0; i--)
        {
            char temp = chars[i];
            chars[i] = chars[last - i];
            chars[last - i] = temp;
        }
        return new String(chars);
    }

Matching Anagrams

Your code is not matching anagrams. Your code matches words with the reverse of the word. An anagram is any rearranged form of the word. So, you have batel and lateb in your list, but it should also match table. Your code will not do that.

The trick to solving this problem would be to reduce each word to its sorted array of characters. For example, to have a function like:

    public string SortedString(string word)
    {
        char[] chars = word.ToCharArray();
        Array.Sort(chars);
        return new String(chars);
    }

Or, if Linq is your thing:

        return String.Concat(word.OrderBy(c => c));

With the char-sorted words, you can use the sorted version as the key of a dictionary, something like:

Dictionary<string,List<string>> anagrams = ....

And you can then populate that dictionary with lists of words that have the same sorted-char anagram key.

Once you have that, you can return all words that are anagrams of each other.


Function for accessing regression output

Your function has several problematic assumptions for the object names in the environment (get()) and the number of objects (fixed length in the for loop).

In base R it would be more idiomatic and flexible to use some function from the *apply family, which operate on a list of objects, e.g.

do.call(rbind, lapply(list(fit3a, fit3b, fit3c),
                      function(x) summary(x)$coefficients["x", ]))
     Estimate Std. Error t value Pr(>|t|)
[1,]  0.01512    0.02927  0.5164   0.6067
[2,]  0.01530    0.02985  0.5127   0.6093
[3,]  0.01732    0.02899  0.5975   0.5516

t(sapply(list(fit3a, fit3b, fit3c),
         function(x) summary(x)$coefficients["x", ]))
     Estimate Std. Error t value Pr(>|t|)
[1,]  0.01512    0.02927  0.5164   0.6067
[2,]  0.01530    0.02985  0.5127   0.6093
[3,]  0.01732    0.02899  0.5975   0.5516

Output of get.coef1(3) (with set.seed(1)):

        [,1]    [,2]   [,3]   [,4]
[1,] 0.01512 0.02927 0.5164 0.6067
[2,] 0.01530 0.02985 0.5127 0.6093
[3,] 0.01732 0.02899 0.5975 0.5516


Tests

It's a good thing you've provided tests and expected output so that one can check the behavior, it is even better if one can run the tests without having to check that the output is correct. Only a tiny bit of reorganisation is required to get :

# my_string not blank, my_key is new
assert my_function('hello', 'test4') == {'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'hello': None}}

# my_string not blank, my_key exists
assert my_function('hello', 'test0') == {'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'hello': None}, 'test1': {}}

# my_string blank, my_key exists and its value is not empty
assert my_function('', 'test3') == {'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}}

# my_string blank, my_key exists and its value is empty
assert my_function('', 'test0') == {'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {'NULL': None}, 'test1': {}}

# my_string blank, my_key is new
assert my_function('', 'test4') == {'test2': {}, 'test3': {'a_key': 'a_value'}, 'test0': {}, 'test1': {}, 'test4': {'NULL': None}}

# New test from Sjoerd Job Postmus's comment
assert my_function('something not empty', 'test3') == {'test1': {}, 'test0': {}, 'test3': {'something not empty': None}, 'test2': {}}

Improvements

if my_string != '': could be rewritten more concisely : if my_string:.

Also, you could use get to retrievement elements in a "safe" way.

Thus, the code becomes :

if my_string:
    d[my_key] = {my_string: None}
else:
    if not d.get(my_key):
        d[my_key] = {'NULL': None}
return d

Also, your dict initialisation could be done with a dictionnary comprehension. Then, your whole function would become:

def my_function(my_string, my_key):
    d = {'test' + str(i): {} for i in range(3)}
    d['test3'] = {'a_key': 'a_value'}

    if my_string:
        d[my_key] = {my_string: None}
    elif not d.get(my_key):
        d[my_key] = {'NULL': None}
    return d

Is this as simple as it can be ? Not quite ? The check for d.get(my_key) is actually to distinguish "test3" from the other values. It could be easier to just do the obvious thing instead of trying to retrieve stuff from the dict :

def my_function(my_string, my_key):
    d = {'test' + str(i): {} for i in range(3)}
    d['test3'] = {'a_key': 'a_value'}
    if my_string:
        d[my_key] = {my_string: None}
    elif my_key != 'test3':
        d[my_key] = {'NULL': None}
    return d


Queue != Stack

Queue behaviour is FIFO.  Stack behaviour is LIFO.  Currently your datastructure is called Queue, but it implements Stack, has stack error messages etc.  This is very confusing.

Magic Numbers

There are three main numbers you're using for manipulating your stack 5, 4 and -1.  Out of context, it's not immediately obvious what they mean.  Replacing them with constants would make the code easier to read.

Undefined behaviour

As has been hinted at by @Quuxplusone, this:

_myarr[5]={0};

Isn't doing what you're expecting it to.  Rather than initializing all 5 of the elements in the array, which is what I suspect you expected, it is attempting to initialize the element with index 5.  Since arrays are index from 0 and it only contains 5 elements, you're overflowing the array.  This may or may not work, depending on how lucky you get.

Return Values

You've declared PUSH,POP,TOP all returning type T, however you're never returning anything.  Depending on your compiler + switches this may or may not actually compile.  PUSH probably doesn't need to return the value it's added anyway...

Console Output

Console output is great for testing your code to see if it's doing what you're expecting, however writing it into your classes gives the console access to private data members. Try to avoid putting console interaction in your data structures.  If you had written the console interactions outside of the class, you would have noticed that POP etc didn't return values a lot earlier in the cycle.

Error Conditions

If I pop from an empty stack, you write to the console, however the caller has no way to know that they haven't retrieved a value. Worse, if I push onto a full stack you simply throw the value away.  You should notify the user that there has been a failure, possibly by throwing an exception.

Exit

"Any other button" isn't a great hint that you need to press 4 or above to get out of the application.  Help your users, be explicit.

using namespace::std

Is generally frowned on, be explicit.

Indentation

Indentation matters, be consistent, it's a lot easier to read.

Putting it all together

I'm sure there's still room for improvement, however combining all of the above, the Stack would look a bit more like this:

#include<iostream>
#include<iomanip>
#include <exception>

template<class T>
class Stack {
private:
    static const int stack_size = 5;
    static const int stack_full = stack_size - 1;
    static const int stack_empty = -1;

    T arrays[stack_size] = {};
    int i = stack_empty;
public:
    void PUSH(T item)
    {
        if (i == stack_full)
        {
            throw std::runtime_error{ "Stack is full" };
        }

        i++;
        arrays[i] = item;
    }
    T POP()
    {
        if (i == stack_empty)
        {
            throw std::runtime_error{ "Stack is empty" };
        }

        T &removed = arrays[i];
        i--;
        return removed;
    }
    T TOP()
    {
        if (i == stack_empty)
        {
            throw std::runtime_error{ "Stack is empty" };
        }

        return arrays[i];
    }

};

int main()
{
    Stack <int> Q;
    int option, push;
    do {
        std::cout << "Select any of the following option" << std::endl;
        std::cout << "1.Push\n2.Pop\n3.Top\n4.Exit" << std::endl;
        std::cin >> option;

        try {
            switch (option)
            {
            case 1:
                std::cout << "Which element to push" << std::endl;
                std::cin >> push;
                Q.PUSH(push);
                break;
            case 2:
            {
                int removed = Q.POP();
                std::cout << removed << " has been popped" << std::endl;
                break;
            }
            case 3:
            {
                int top = Q.TOP();
                std::cout << "Element at top of stack is " << top << std::endl;
                break;
            }
            case 4:
                break;
            default:
                std::cout << "Error!" << std::endl;
                break;
            }
        }
        catch (std::runtime_error error) {
            std::cout << error.what() << std::endl;
        }
    } while (option < 4);
}


Generate binary image using coordinate vectors

auto
Automatic type deduction is especially welcoming for iterators, as their types are bulky. We can rewrite to
std::vector<std::vector<double>> x;
std::vector<std::vector<double>> y;

// fill x and y

std::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));

auto iter_row_x = x.cbegin(); //note cbegin to get const_iterator
auto iter_row_y = y.cbegin();

for (; iter_row_x != x.end(); ++iter_row_x, ++iter_row_y) {
    auto iter_col_x = iter_row_x->cbegin(); // iter_row_x[0].cbegin() = iter_row_x->cbegin()
    auto iter_col_y = iter_row_y->cbegin();
    for (; iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {
        auto i = static_cast<unsigned int>(*iter_col_x); // be explicit about which cast you are using. Now you do not need to specify the type twice.
        auto j = static_cast<unsigned int>(*iter_col_y);
        M[i][j] = 1;
    }
}

But it's still wordy. Having separate vectors for x and y seems unnecessary, since it is expected that they should be of same length. Better create a structure for xy and create only one vector.
struct Point
{
    double x;
    double y;
}

Then we have
std::vector<std::vector<Point>> xy;

// fill xy

std::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));

for (auto iter_row_xy = xy.cbegin() ; iter_row_xy != xy.end(); ++iter_row_xy) {
    for (auto iter_col_xy = iter_row_xy->cbegin(); iter_col_x != iter_row_x[0].end(); ++iter_col_x, ++iter_col_y) {
        auto i = static_cast<unsigned int>(*iter_col_xy.x);
        auto j = static_cast<unsigned int>(*iter_col_xy.y);
        M[i][j] = 1;
    }
}

But we can do even better by using for range:
std::vector<std::vector<Point>> xy;

// fill xy

std::vector<std::vector<unsigned int>> M(n_rows, std::vector<unsigned int>(n_cols));

for (const auto& elements : xy){
    for (const auto& point : elements){
        auto i = static_cast<unsigned int>(point.x);
        auto j = static_cast<unsigned int>(point.y);
        M[i][j] = 1;
    }
}


Style

Species Parents[popSize];
Species Children[popSize];

It's more common for variables to start with lower case letters.

Species parents[popSize];
Species children[popSize];

That way you can easily tell that Species is a type while parents is a variable.  As it is, I have no way to tell why Parents is capitalized and parentA, etc. are not.

for(int gen = 0 ; gen < 100 ; gen++){
for(int i = 0; i < popSize ; i ++)
{

You're mixing two styles here.  Both are valid, but it's generally preferred to pick one and use it consistently throughout your code.  More of the code is using { on a separate line, so it may be best to standardize on that.  Personally, I prefer it the other way, but as I said, both are valid.

for (int gen = 0; gen < 100; ++gen)
{
    for (int i = 0; i < popSize; ++i)
    {

Also, you indent inside the inner loops but not the outer.  It's unclear if this was intentional or a copy/paste error.  Note that if you indented the outer lines extra to make them appear in a code block, that it's often better to select the whole code and use Ctrl+K to indent them.  That will increase the indent of the entire code, not just the outermost lines.

I also changed the spacing to a more common form.

Preincrement may be defined more efficiently than postincrement.  It's a tiny difference, but some people prefer always using preincrement when either would work functionally.  Note that a compiler may compile out the difference entirely anyway.

< versus !=

A comment argued that it is more common to use != rather than <, but I think that they missed the point.  C++ favors using iterators in this situation.  Since many iterators don't have a meaningful < operator, they use something that looks sort of like

for (auto i = iterator.begin(); i != iterator.end(); iterator++)

However, that doesn't apply if your for loop is over an int.  Because int values do have meaningful <, these are more robust.  There's no need to maintain consistency at the price of robustness.  Consider

for (int i = 0; i != 5; i +=2)

This code will crash with an integer overflow (or loop forever) because i will never equal 5.  And this code might otherwise be a sensible replacement for

for (int i = 0; i < 5; ++i)
{
    if (i % 2 == 0)

Note that if you were using std::array or std::vector and C++11, you could use the new range-based for loop.

for (auto child : Children)

Then you don't have to manually manage your iteration at all.

Missing code

You use Parents[i] but you never set it to anything.  Perhaps chooseParent or crossOver does that for you, but it's not clear.  It's also not clear why you transfereGenes (should that be transfer rather than transfere?) with Children[i] and Parents[i].  Why are those two related now when they weren't earlier?

This is probably also a violation of the Single Responsibility Principle.  Initialization of the Parents and Children arrays presumably occurs somewhere.  But since it doesn't happen here or in a method called something like initialization, it's not obvious where.  Nor is it obviously correct.  We're essentially relying on the function implementations being correct.  But I don't even know what they are supposed to do.  I can guess a bit from the names, but this code won't work at all unless one of them handles initialization.

Is your code correct?  Without knowing what the code it calls does, I have no way of knowing.  If you want more of a review, you may want to post a new question with more context.  Preferably with runnable code.

    crossOver(Parents[parentA] , Parent[ParentB] , Children[i]);

Is this a typo?  Should it be

    crossOver(Parents[parentA], Parents[ParentB], Children[i]);

I can't be sure.  Maybe the missing code has a Parent array as well.  And of course if not, a runnable version would find that trivially with a compile.


Basic arithmetic calculator in JavaScript

I would go with the second one. Not because eval here is insecure -- you're validating the arguments -- but because it's overkill. eval is designed to parse and run any JavaScript code, so it is slow (compared to normal JavaScript code); engines do a lot of optimisation before running code, but they can't optimise if the code is in a dynamic string which changes at runtime. It probably won't maker much difference for you here, but if you're building a larger app, blocking JavaScript can be noticeable.

Here are the changes I would make to calculate2:

'use strict'; // Strict mode === good

function calculate2(num1, num2, operator) {
  // Number.parseFloat is new in ES6
  // (it's identical to window.parseFloat, so you can use either)
  num1 = Number.parseFloat(num1);
  num2 = Number.parseFloat(num2);
  operator = operator.trim();

  // Avoid `var`. ES6 brings `let` and `const`, which:
  //   - are block scoped
  //   - work with destructuring
  //   - prevent redeclaration in the same scope
  //   - aren't hoisted
  // Note that `const` doesn't freeze object properties
  // If you need frozen properties, use Object.freeze
  const calculations = {
    // Shorter names, it's clear from the context what they do.
    '+' : (a, b) => a + b,
    '-' : (a, b) => a - b,
    '*' : (a, b) => a * b,
    '/' : (a, b) => a / b, // You can use trailing commas in object and array literals if you want.
  }; // If you use semicolons, use them all the time.

  // Detailed error messages.
  //
  // Number.isNan is also new in ES6,
  // however it's not quite the same as window.isNan.
  // Here it won't make a difference which you use.
  //
  // `throw new Error` rather than `throw Error`
  // as you're using the Error constructor.
  if (Number.isNan(num1)) throw new Error(
    `Expected first argument to calculate2 to be a String valid for Number.parseFloat but got ${num1}.`);
  if (Number.isNan(num2)) throw new Error(
    `Expected second argument to calculate2 to be a String valid for Number.parseFloat but got ${num2}.`);

  // Don't bother maintaining a separate regex of valid operators
  // Just check the calculations object
  if (!calculations[operator]) throw new Error(
    `Expected third argument to calculate2 to be one of ${Object.keys(calculations).join(' ')} but got ${operator}.`);

  return calculations[operator](num1, num2);
}


For starters, indent your code consistently — the standard in Ruby is two spaces.  That includes indenting the contents of your begin-rescue-end blocks.

Normally, I don't like to make such a huge fuss about indentation, but in this case I think it's highly important, because:

Your program has a highly unusual outline (infinite loops and a function definition(!) inside an infinite loop)
The stakes are high: if you misbehave, you could make a lot of people upset.  Therefore, good software engineering practices should be used.

An outline like this would be more idiomatic for Ruby:

class AnswerBot
  ROOT = 'http://stackexchange.com'
  CHAT_ROOT = 'http://chat.stackexchange.com'

  def initialize(options)
    @agent = Mechanize.new
    @options = options
  end

  def login
    # Do stuff with @agent
    login_form = $agent.get('https://openid.stackexchange.com/account/login').forms.first
    login_form.email = @options[:email]
    # ...
    @fkey = @agent.get(CHAT_ROOT + '/chats/join/favorite').forms.last.fkey
  end

  def fetch_answers
    # Make request to api.stackexchange.com
    # ...
    data['items'].each { |event| yield event }
    return (data['backoff'] || 0).to_i
  end

  def send_message(text, retries=5, backoff=40)
    # ...
  end
end

bot = AnswerBot.new(:access_token => ...,
                    :room_number = 12723,
                    :site => 'codereview',
                    :email => ...,
                    :password => ...)
loop {
  begin
    bot.login

    do
      backoff = bot.fetch_answers do |event|
        if ['answer_posted'].include?(event['event_type']) # <-- Is that right?
          bot.send_message(...)
        end
      end
    while sleep(40 + backoff)
  rescue => e
    puts "An error occurred."
    p e
  end
  puts "Bot restarted."
}


Just a few notes about print, I see you're not using parenthesis so i'm guessing you're using python 2.x.  I would urge you to switch to python 3.5+ now, as python 2.x is at end of life.  However if you insist on using it

-Keep consistent on using parenthesis

-You can use \n inside the string to add a newline:

print "Hello World!\n"

If you switch to python 3.x you can use the print function and pass in the end parameter to append a new line after your string:

s = "Hello World!"
print(s, end='\n') #NOTE: @Coal_ points out this is the default
# so if you didn't want there to be a newline you'd have to overwrite
# print(s, end=' ')
# @Solomon, and if you wanted a space between your outputs,
# print(s, end='\n\n')

That way you don't have seemingly useless print statements everywhere.


I have a few pointers,

Use libraries when possible,  you are currently reinventing the wheel of itertools.permutations
You could use a set() to have \$O(N)\$ lookup when finding items that are already seen.
You should use generators instead of keeping everything in a list, this avoids high memory usage when working with large numbers

Reinventing the wheel

class Solution:
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        def unique_perms(elements, unique):
            if len(elements) <=1:
                yield elements
            else:
                for perm in unique_perms(elements[1:], unique):
                    for i in range(len(elements)):
                        next_perm = perm[:i] + elements[0:1] + perm[i:]
                        if tuple(next_perm) not in unique:
                            unique.add(tuple(next_perm))
                            yield next_perm

        return list(unique_perms(nums, set()))

Using modules

from itertools import permutations

def permute_unqiue(nums, r):
    return list(set(permutations(nums, r)))

This works by making a set() of the permutations. That removes all duplicate values, since they will hash to the same thing. Afterwards you can return the list() of unique permutations.


Rehashing a hash table in c++ with quadratic probing

Rreplace the inner for loop of rehashing with a call to put. put has an average runtime of \$\mathcal{O}(1)\$ . So, rehashing has an average runtime of  \$\mathcal{O}(n)\$ since it is \$n\$ put operations.

It would look something like this:

void rehashing() {
  int oldCap = cap;
  sze = 0;
  cap = NextPrime(cap * 2);

  HashNode** oldArr = arr;
  arr = new HashNode*[cap]();

  for (int i = 0; i < oldCap; ++i) {
    if (oldArr[i] != nullptr) {
      put(oldArr[i]->value);
      delete oldArr[i];
    }
  }

  delete[] oldArr;
}

Also, it might be useful to refactor put to have a private overloaded put member function which accepts a HashNode. The public put would just allocate a HashNode and call the private put. Then, for rehashing, one could use the private put and wouldn't need to delete the previous HashNode. This would save memory allocation and deletions.


Project Euler #10 and #12 in Java - Prime Numbers

You could make use of the Sieve of Eratosthenes, which would give you all the speed you need. There's a lot of such code here on CR, so let's gop to the review.

long sum = 0;// 2 is also a prime
for (int i = 2; i < 2000000; i++) {

Right, but

long sum = 1;// 2 is also a prime
for (int i = 3; i < 2000000; i+=2) {

does the job as well. No big improvement as the evens get tested very fast.

    long n_t = Sumk(i);

This is a terrible name, but maybe OK in math code.

    int d = getDivisorCount(n_t);

What do we know about divisors of a product? Right, you could simply "add" them.1 No advantage here, but a big speed up for big numbers (coming in later Euler problems).

As you count the divisors of a * (a+1) and then (a+1) * (a+2), you could reuse the divisors for (a+1) for a speedup factor of 2.

public static long Sumk(int n) {

Method names always start with lowercase.

public static boolean isPrime(int n) {
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

That's fine. Just note that (i & 1) is a faster way of computing i % 2 for non-negative i.

public static int getDivisorCount(long n) {
    int d = 1;
    for (int i = 2; i <= n;) {
        if (isPrime(i)) {

And that's the culprit! You're doing an expensive operation (isPrime) in order to save a much cheaper one (division)!

Actually, the whole method is confusing, so let's go through:

public static int getDivisorCount(long n) {
    int d = 1;

But d is not a nice name. I'd suggest to call it simply result.

    for (int i = 2; i <= n;) {

Here, you could use a test like i * i < n again, couldn't you?

        if (isPrime(i)) {

My above point was about efficiency. Actually, in order for the below computation (d *= (d2 + 1)) to work, it's necessary to use only primes here. However,

when you get a divisor of the (reduced) n here
it's always the least divisor
and the least multiple is always a prime

        int d2 = 0;
        while (n % i == 0) {
            ++d2;
            n /= i;
        }
        d *= (d2 + 1);
    }
    if (i == 2) {
        ++i;
    } else {
        i += 2;
    }

That's OK, but I'd handle 2 specially. There's a nice trick (irrelevant here) for getting out all powers of two:

int d2 = Integer.numberOfTrailingZeros(n);
n >>= d2;

    }
    return d;
}

OK. Btw., my solutions to these problems take nearly one second. That's not fast, but I don't care as there's enough to optimize when working on the harder problems.

My divisorCount

It takes 0.12 seconds and could surely be improved via memoization or a precomputed list of primes (a list up to Math.sqrt(Integer.MAX_VALUE) can be easily found in internet).

private int divisorCount(int x) {
    int result = 1;
    {
        final int d2 = Integer.numberOfTrailingZeros(x);
        result *= d2 + 1;
        x >>= d2;
    }
    for (int i=3; i*i <= x; i+=2) {
        int d2 = 0;
        while (x%i == 0) {
            ++d2;
            x /= i;
        }
        result *= d2 + 1;
    }
    if (x!=1) result *= 2;
    return result;
}

1 I was wrong here. The prime factors list (multiset) can simply be concatenated. The number of divisors can be computed easily using them. Let's say that this is what I meant by "add" (it's not, I was plain wrong, but don't tell it further).


Applying an id attribute based on a variable's value

Don't change IDs. IDs are supposed to identify a specific element, regardless of any state. "Active" should be a class.

The .mainmenu class should probably also be an ID. It's the "main menu" - that's its identity. Classes are for when you have multiple elements that are "of the same class", i.e. they share some functionality or styling. (If you have multiple things called "main menu", you have other problems.)

Using an active class will also let you use the IDs to find the link you want make active.

$("#mainmenu a.active").removeClass("active")
$("#" + menulink).addClass("active");

Basically: Find the currently active link, and remove the "active" class from it. Then find the link with the ID you're looking for, and set that to active by adding the class.


Since we're doing this in assembly language, it makes sense to do it much more efficiently than is typically done in high level languages.  Otherwise, why bother with assembly language? So with that said, there are ways that this can be made much, much more efficient.
Avoid division
The div instruction in x86 is one of the slower instructions possible.  Since we already know that we're looking for numbers divisible by 3, 5 or both, what would make far more sense is to simple keep countdown counters for both.  Your initialization currently says:
    xor cx, cx

It could be easily expanded to say:
    xor cx, cx
    mov bx, 0503h  ; set bh = 5 counter, bl = 3 counter

Then instead of dividing, simply decrement:
    inc cx
    cmp cx, 100
    jg done
;  instead of this...
;    dec bh
;    dec bl
;    cmp bx, 0
; per suggestion from @Chris Jester-Young use this:
    sub bx, 0101h
    je print_fizzbuzz
    test bl, bl
    je print_fizz
    test bh, bh
    je print_buzz
print_other:

Naturally the various print_... routines would have to reset bh, bl or both as well as printing.
Improve formatting
Generally speaking, assembly language code is not indented in the way you have your code indented.  It's much more linear, with the only indentation for assembly language statements or directives.
Consider better I/O
Your output routines are not shown, but it's likely that it would be more efficient to keep the numeric output in string form, incrementing each ASCII digit and emitting the string, rather than repeatedly converting from binary register contents to a string value.


This is really the exact use-case for indexed full-text search engines.

Since you're running this code server-side on a website, I'd suggest you seriously consider writing a simple worker that polls your FS for new documents and adds them to a database that has full text searching enabled.

If you're using SQL Server: https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search

If you're using MySQL: http://www.w3resource.com/mysql/mysql-full-text-search-functions.php

This way, you'd not only get your results back much more quickly than scanning each document manually, you'd also avoid the onerous network traffic involved in streaming every file from the FS for every request.

To do this, you can pretty easily either write a page in your site or a new console app (preferable) that is called by a cron job (linux) or scheduled task (windows) on the server every so often. That interval would be however often you expect there to be new documents added to the FS or whatever your tolerance is for stale data.

At that point, the page/app would pull the list of documents already cached in the database, query the FS for its contents, and compare the lists of filenames or file dates to see what needs to be added/updated. At that point, you can only stream in the files you actually need to add and you don't really care how long it takes.

The database would then take care of the indexing of the new documents. Your webpage then becomes a dumb pipe for searching those indexed documents.

If storing the texts in a database isn't an option, you might consider mirroring the files on your own server. It'd still remove the slowest part of your algorithm (the network traffic).

You'd still need your cron/scheduled task worker to do that mirroring but it'd be a simple matter of copying the new files from the FS to your local disk.

If you mirror locally or can't do either, your best bet is parallelization. You can do some refactoring but your local operations aren't your real bottleneck.

For instance, if you can mirror locally, you could use this in place of your existing code:

// ToUpper() your search string outside of the loop,
// rather than in each passs.
string txtBasicSearch = "My Search String".ToUpper();

// Use Parallel.ForEach over every docx file in our directory.
Parallel.ForEach(Directory.EnumerateFiles(directoryPath, "*.docx"), (string file) =>
{
    string docText = string.Empty;

    try
    {
        // Try to dispose of our streams as soon as possible to avoid
        // holding memory unecessarily. Also, avoid copying Streams
        // to different types. A generic Stream works just fine.
        //
        // As well, only open with read perms to avoid unecessary locks and
        // any delays that may cause.
        using (Stream str = File.OpenRead(file))
        {
            using (WordprocessingDocument wpd = WordprocessingDocument.Open(str, false))
            {
                using (StreamReader sr = new StreamReader(wpd.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }
            }
        }

        // Search the haystack for the needle.
        if (docText.ToUpper().Contains(txtBasicSearch))
        {
            // No need for a counter variable. Just user
            // hearingArrayList.Count() at the end.
            hearingArrayList.Add(file);
        }
    }
    catch (Exception ex)
    {
        // Do whatever error handling here.
        return;
    }
});

Timing that parallel version against the same version using a regular foreach loop with a small directory on my local NAS showed that the parallel version was typically 3-6 times faster.

If you can't mirror locally, you can still parallelize the file streaming but will need to be cognizant of the limits the server may place on the number of connections you can open at once.

The HttpClient class will probably serve you better here than the WebRequest class. https://msdn.microsoft.com/en-us/library/hh696703(v=vs.110).aspx

There, you can query the files within the remote directory then iterate through them, making an async call with HttpClient.

So, that might look like:

string txtBasicSearch = "My Search String".ToUpper();

HttpClient client = new HttpClient();

// Use client to populate myFileList with the remote files.

foreach (string file in myFileList)
{
    client.GetStreamAsync(file).ContinueWith((Task<Stream> result) =>
    {
        if (result.Status != TaskStatus.RanToCompletion)
        {
            // Error handling.
            return;
        }

        string docText = string.Empty;

        try
        {
            using (WordprocessingDocument wpd = WordprocessingDocument.Open(result.Result, false))
            {
                using (StreamReader sr = new StreamReader(wpd.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }
            }

            if (docText.ToUpper().Contains(txtBasicSearch))
            {
                hearingArrayList.Add(file);
            }
        }
        catch (Exception ex)
        {
            // Do whatever error handling here.
            return;
        }
    }
}

The HttpClient class will take care of rate limiting you. By default, I believe it allows three connections at any time, but you can easily change that to your liking.

Enumerating the files on the remote server would be a different topic, depending on how that remote is being accessed. I'd suggest searching other SO answers like https://stackoverflow.com/questions/124492/c-sharp-httpwebrequest-command-to-get-directory-listing

(If your file server is just a NAS on your intranet, save yourself the pain an just use the System.IO.Directory and .File classes to query the files)


soo... going from top to bottom:

public interface IMapFromCsv{

superfluous I before name, missing space before opening curly brace

public default <T> Map<String, T> getMap(String FILE_TO_LOAD, Function<String, T> convertValue){

FILE_TO_LOAD should be named according to naming convention: fileToLoad. Next step is making it a Path because a String is not a File and File is superseeded by Path, because it sucked.

Also missing a space before the opening curly again.

    Map<String, T> mapResult = new HashMap<>();
    File f = new File(FILE_TO_LOAD);

so far so good. did I mention that File is crap?

    try (Scanner sc = new Scanner(f)) {
        while (sc.hasNextLine()) {
            String tmp = sc.nextLine();
            String[] tmp2 = tmp.split(";");
            mapResult.put(tmp2[0], convertValue.apply(tmp2[1]));
        }
    }

Bonus points for using try-with-resources, deductions for using tmp and tmp2 as variable names. How about we simplify this a bit?

try (Stream<String> lines = Files.lines(fileToLoad)) {
    return lines.map(s -> s.split(";"))
        .collect(Collectors.toMap(line -> line[0]
            , line -> convertValue.apply(line[1])));
}

Note that this only returns either the full map, or currently nothing. If something goes wrong while reading the map, I'd suggest using Collections.emptyMap() as a sensible default result.

    } catch (FileNotFoundException fntf) {

This exception is one of the reasons File is crap. The good part is: You get a unified Exception API from the java.nio.Path and related, which is: IOException.

At this point I'm asking myself the question why this is a default method on an interface. Methods in an interface are meant to be overwritten to modify them. The method instead takes parameters to configure it. IMO this would be much nicer as a static method in some IO module or something.

Last but not least: Why are AreaMapFromCsv named like they'd be Methods? Let's reconsider this for a second. You're trying to implement something that will hold information on Maps of your choosing, namely where they are saved, and what value you're currently assigning to them.

I'm not clear on why that needs to be two separate classes (or actually singleton enums), or where the singleton comes into this.

From my PoV it seems like you heard that Singletons are an acceptable solution when you try to handle global state. Tip: they aren't.

The correct solution for global state is a properly encapsulated statically accessible instance of a proper class. Consider this instead:

public class MapHolder<T> {

    // consider making this final
    private Map<String, T> map;
    private final String mapPersistenceLocation; // this is a Path...
    private final Function<String, T> converter;

    public MapHolder(String parameterName, Function<String, T> converter) {
        this.mapPersistenceLocation = parameterName;
        this.converter = converter;
        reload();
    }

    public void reload() {
        // if map is final, replace by map.clear(); map.putAll(...);
        map = IOHelper.readMap(mapPersistenceLocation, converter);
    }

    public Map<String, T> get() {
        // consider returning a readonly copy, if modifications should be disallowed
        return map;
    }
}

Which can now be used as follows:

public final class GlobalContext {
    public static final MapHolder<Double> CURRENCY = new MapHolder<>("resources/currencyMap.csv", Double::parseDouble);
    public static final MapHolder<String> AREA = new MapHolder<>("resources/areaMap.csv", Function.identity());

    // prevent instantiation
    private GlobalContext() {}
}


Your Either-monad suffers from a fatal flaw:
It is impossible to return an Either which might be either possibility.
You can only return a Left or a Right, an Either must per force be a pointer or reference to one of those.
Without help from the compiler in automatically deducing a return-type of Either<T, U> if it finds returns of a combination of Either<T, U>, Left<T> and Right<U> sufficient to deduce T and U, or at least adding pattern-matching, Left and Right are pretty much useless.
In the end, that just leaves Either, which is now only a poor-mans substitute for full-fledged std::variant of two.


addClass and removeClass in a switch case

I would probably add a class/something to use as a selector (in this case I added girls) to make lookup easier. You can do this in other ways such as getting the values of the actors map so do it as you will.

Also your default case is calling removeClass on a string as selection is the current contents of whatever the event is hooked to.

// Actor name -> the corresponding element selector on the page
var actorsIdMap = {
    'Monica Bellud': '#Bellud',
    'Lea Seydoux': '#Seydoux',
    'Ursula Andress': '#Andres'
}

var showImage = function() {
    var selection = $(this).val();

    if (selection in actorsIdMap) {
        // Hide the other actors
        $('.girls').removeClass('hide show');
        $(actorsIdMap[selection]).addClass('show');
    } else {
       // Default case what do?
    }
}


Can this FindString function be optimized further, in terms of speed?

Some comments to add to the first two of @200_success:

strstr does a good job. Why reinvent?
sizes are often passed as size_t rather than int
modifying the loop variable within the loop is generally considered bad
practice
i -= j executes on every loop unless there is a match.  Mostly in this
case j is zero so the line has no effect, but it still executes
if fstr is an empty string it returns the wrong result (1)
add some spaces around operators and after if, for


The organization of your code seems strange to me: should to_arabic be class or instance method of the String class or maybe neither? The method lies outside of the String class bracket, yet references private hash roman_mapping and self. My JRuby 1.7.18 throws a runtime error while trying to execute it.

Then the code doesn’t properly handle invalid (non-roman) characters, it stops recursion because for the first invalid character the mapping will fail, in this case not the result of the canversion up to that point but the array of the roman_mapping’s values will be returned, which is supposedly not what you want to achieve.

After putting to_arabic within the class frame and adding public before it for the code to execute:

p "MCMPIII".to_arabic2

  ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]

Next you have a hash map but do not use it as such, just iterating over values. Even then you could use:

roman_mapping.each_pair do |value, roman|

to spare on the invert call.

At the end I’d suggest reverting the keys and values of the mapping hash (because you start from roman characters), using symbols instead of strings as keys and replacing recursion with a loop: like this:

class String
  private
  ROMAN_MAPPING =
    { :M => 1000, :CM => 900, :D => 500, :CD => 400,
      :C => 100, :XC => 90, :L => 50, :XL => 40, :X => 10,
      :IX => 9, :V => 5, :IV => 4, :I => 1 }.freeze

  public

  def to_arabic()
    return 0 if empty?

    str = self
    result = 0
    while !str.empty?
      roman = str[0..1]
      value = ROMAN_MAPPING[roman.to_sym]
      if !value.nil?
        result += value
        str = str[roman.length, str.length]
        next
      elsif roman.length == 2
        roman = str[0]
        value = ROMAN_MAPPING[roman.to_sym]
        if !value.nil?
          result += value
          str = str[roman.length..-1]
          next
        end
      end
      raise "Invalid roman character %s in #{self}" % roman
    end
    result
  end

end

Here exemplary outputs:

p "MCMIII".to_arabic

  1903

p "MCMPIII".to_arabic

  RuntimeError: Invalid roman character P in MCMPIII

I admit it is longer, but behaves better raising error on erroneous input and is faster – on my machine benchmarked against your code was regularely almost 3 times faster.

UPDATE

@200_success Thanks for asking - besides the performance gain there are two more reasons for using symbols instead of strings as keys.

Never use mutable objects as keys in hash tables

This is reason enough - mutable objects as keys are evil, if they change unpredictable things can happen, since values are placed in buckets of a hash table based on hashcode of the keys, now you can imagine that changing the keys of pair after it has been placed into a hash map is never a good idea. And strings in Ruby are mutable!

I admit though, that this will rather not happen in our case, yet it would be a bad practice anyway and should be avoided just to keep the code clean. And it seems that in fact Ruby copies and freezes the strings if used as keys in hash maps in case we forget about this rule :-). Nevertheless we have our performance gain by using symbols.

roman_mapping is in fact an immutable constant

Neither keys nor values would ever change. So it is logical to use an immutable class for the keys - like symbols. Now numbers are immutable, too, but the hash maps are not. So while we are talking this, we should make roman_mapping also immutable using freeze, and while doing this we can also replace the method roman_mapping with a frozen constant.

To make roman_mapping immutable all these steps are necessary - simple freezing the hash map wouldn't be enough. If a reference to its keys leaks into the outside word it still could be changed.

I've just updated the code above. A new benchmark on my machine shows now even more performance gain: the new code is more than 10 times faster than the original:

                user     system      total        real
new to_arabic   0.700000   0.010000   0.710000 (  0.717587)
old to_arabic   9.200000   0.050000   9.250000 (  9.427725)


Class in a DLL to extract data from a file via many accessors

I think you can use templates to good use to simplify the user interface and still retain the flexibility.

I would suggest declaring some structs instead of using enum class DataTypes.

struct DataType_1;
struct DataType_2;
struct DataType_3;
struct DataType_4;

You may define them to be empty structs but that is not necessary for what I am going to suggest.

// This is OK too but not necessary.
struct DataType_1 {};
struct DataType_2 {};
struct DataType_3 {};
struct DataType_4 {};

Then create template class that captures the notion of traits corresponding to the above structs.

template <typename T> struct DataTypeTrait;

template <> struct DataTypeTrait<DataType_1>
{
   using type = int;
};

template <> struct DataTypeTrait<DataType_2>
{
   using type = int;
};

template <> struct DataTypeTrait<DataType_3>
{
   using type = float;
};

template <> struct DataTypeTrait<DataType_4>
{
   using type = char const*;
};

Create a wrapper class around the traits class.

template <typename T> struct DataType
{
   using type = DataTypeTrait<T>::type;
};

I understand that you have some concerns about using containers from the standard library. However, it's OK to use of member function templates described below since they don't involve use of standard library containers in the interface of the member functions.

Here's how I see FileLoader to look like:

class FileLoader
{
   public:
      FileLoader(const char* path);

      int GetIterationCount();

      // This is all you need in the public interface.
      template <typename T>
         typename DataType<T>::type getData(int iteration) const
         {
            return getData(iteration, (T*)nullptr);
         }

   private:

      // The dummy arguments allows the function overloading to
      // work seamlessly from the member function template.

      int getData(int iteration, DataType_1* dummy) const;
      int getData(int iteration, DataType_2* dummy) const;
      float getData(int iteration, DataType_3* dummy) const;
      char const* getData(int iteration, DataType_4* dummy) const;
};

User code

char const* filepath = "some/file/path";
FileLoader loader(filepath);
int val1 = loader.getData<DataType_1>(0);
float val2 = loader.getData<DataType_3>(0);
float val3 = loader.getData<DataType_4>(0); // Error.
char const* val4 = loader.getData<DataType_4>(0);


LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers II

Some remarks
A_DECIMAL and it's use
A_DECIMAL = 65
# [...]
indices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}

there is nothing wrong with
ord('A')

which you can use inline without defining a global (which it is not in the required Solution context).
You can even get rid of the ord math by enumerating.
indices = {char: divmod(idx, WIDTH) for idx, char in enumerate(string.ascii_uppercase)}

Names
def get_coordinates(left: int, right: int) -> int:
    if not left or not right:
        return 0

    x_left, y_left = indices[left]
    x_right, y_right = indices[right]

    return abs(x_left - x_right) + abs(y_left - y_right)

does in no way return coordinates, it returns a distance.
Also left and right was misleading me, I thought of the two finger positions.
Also you claim the parameters are ints. Actually you pass characters. That is sloppy.
dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)

is near to obfuscation. get_coordinates delivers a distance, word_a is not a word but a character where one finger is on, and what get_dp delivers cannot be guessed from the name nor is a docstring existing.
Algorithm
You use depth first search (DFS) while for finding the shortest path typically breadth first (BFS) is the better approach. With DFS you have to search the whole tree. By introducing an lru cache you found a nice trick to shortcut some branches. Still you cannot find the shortest path early but have to check the whole tree.
While the fingers are exchangeable you handle them as if they could not be swapped. So you find two optimal paths, one starting with the left finger, one starting with the right. Identical sequence, only the fingers are swapped. Also the cache does not match swapped fingers.
Cache
As already said, your cache does not match swapped fingers. By sorting the fingers you could match them. You do the lru cache on a function in a function. As the inner function is only existing while the outer is running also your cache is working for a single word only. Another call with the same word cannot be served from cache. If you pull the function on class level and change the signature to hold the remaining word instead of the index you could reuse cached "endgames".
A function that would greatly benefit from a lru cache is get_coordinates (read get_distance)
Hostile test cases
You should implement a BFS with priority queue. Then you do some logging and timing on tests like "FY"*150. While the minimum distance is 0, your DFS evaluates branches at a distance of near 2700. A BFS would register nodes at a max distance of 9 but would never follow them.
Other
The line
chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)

would deserve an explanatory comment or a nice function name.


I think your code is very well written, and understandable (even for me, although I'm currently only beginning to learn Lua, and I heard about ECS for the first time now :) )

I would suggest some minor improvements:

Document your methods, including parameters and return types.
In getComponentsTable add a comment explaining, why you break the loop if you hit a nil value (that was not clear for me, how we know that there are for sure no interesting values after this point)
Some parameters are ensured against nil (using or {}), but this is not the case for entity/entities. I suggest, either doing the same, or adding an explicit check for nil at the beginning of the method (and raising an error in case of nil).
The each function iterates indefinitely, until it finds a nil value in the array (I suppose, this means that it reads past the last element). Instead of this, why not just iterate over all the elements of the array, with a normal for loop? I don't see any good reason, but if there is one, I'd document it in a comment.
In some of the for loops, the variable i is not used. The Lua Style Guide recommends using underscores (_) for such cases.

Finally, one more thing: it is really useful that you have a working example for your system. However, I suggest to consider also adding unit tests, for more reasons:
- they ensure correctness if you need to do changes
- they help other to understand the code better
- it is possible them to run/verify them in an automated way (which is not the case for the example)


Is there more efficient way of processing my XML file in PHP?

Add a break to that if statement to stop looping once you've found the correct node.


First of all, method and variable docblocks are recommended. Provide a description of each method, its parameters and their return values.

I would give your getter function Variable::variables() an active name like getVariables() and rename your Variable::get() method to getVariable(). Consistency is important and you want to avoid confusion with the magic getter __get().

Are you intentionally using the non-magic method Variable::destruct instead of the PHP magic method __destruct()?

This is more of a syntax preference, but I would use array_key_exists() instead of isset() when referring to the property static::$vars since I find the verbage more aligned with what you are testing.

The docblocks are the only important thing. Good work.


Speed up a function that checks for a sequence

Here is a vectorized version:
yes.seq <- function(dat, pat) {
  paste(dat[dat %in% pat], collapse = "") == paste(pat, collapse = "")
}

yes.seq(dat, pat)
# [1] TRUE
yes.seq(dat, rev(pat))
# [1] FALSE


Generic Extension Method To Count Descendants

Peter already pointed out the main problem with your code: you're doing linear searches when looking for child-nodes, which will blow up to \$O(n^2)\$ for worst-case inputs (very deep trees). Indeed, a lookup table that maps a parent ID to child IDs is much more efficient, and ensures that your method remains \$O(n)\$ for all sorts of input.

Another problem is that your method does not guard against cyclic inputs - it'll run indefinitely. You may want to throw an exception instead, or otherwise prevent the start item from being added to the stack again. It's also a good idea to document this behavior.

Other notes:

There's no need to perform input validation in a separate method here: Count does not use yield, so the input validation will be performed immediately. Note that a modern alternative is to move the yielding part to a local function instead of to a separate method.
When throwing argument-related exceptions, it's better to use nameof(parameterName) instead of "parameterName". This lets the compiler protect you against typos, and works well with code refactoring tools.
I would rename T to TKey, selfReference to keySelector and parentReference to parentKeySelector. I think that better describes their purpose, and it's consistent with other Linq methods.
Use var to cut down on type name repetition: var variableName = new LongTypeName(...); is equivalent to LongTypeName variableName = new LongTypeName(...);.
As Peter already mentioned, there's no need for that keys set: you're only adding items with a known parent ID to the stack, so there's no point in verifying whether their parent ID is known.


Filtering a collection by an async result

There are several ways to achieve what you're after and it depends on whether you want the results drip fed to you as they're available or whether you're happy to have them all in one bang.
The way you've implemented your method gives it all in one bang - which is fine.

A shorter implementation could be

public static async Task<IEnumerable<T>> WhereAsync2<T>(this IEnumerable<T> items, Func<T, Task<bool>> predicate)
{
    var itemTaskList = items.Select(item=> new {Item = item, PredTask = predicate.Invoke(item)}).ToList();
    await Task.WhenAll(itemTaskList.Select(x=>x.PredTask));
    return itemTaskList.Where(x=>x.PredTask.Result).Select(x=>x.Item);
}

It builds a list of an anonymous type where the type contains the item and the Task.
It then waits for all of the tasks to complete.
It then goes through that list from (1) and picks out the items that had a true result from the Task.

The other advantage is that you get rid of all of that counter and ElementAt() stuff.  Either way still builds a complete List for the items in the given Enumerable...

Aside: You could investigate something like Rx if you wanted the results via an IObservable<T> instead.  The result wouldn't even be async Task - it would just be an IObservable.


As noticed by mmm a solution might be (if applicable) to slice results. Anyway, here is my suggestion for the process to be as thrifty as possible.

// First create a specific model version appropriate to current results structure
$curModel = [];
$resultSample = reset($results);
foreach ($model as $attribute => $ope) {
  // keep only useful attributes
  if (array_key_exists($attribute, $resultSample) {
    // flip params list to have param as key
    $curModel[$attribute] = [
      'function' => $ope['function'],
      'params' => array_flip($params),
    ];
  }
}

// Then work:
// . without having to check if some attribute applies
// . with the ability to use array_intersect_key() to provide params
foreach ($results as &$itemResult) {
  foreach ($curModel as $attribute => $ope) {
    $function = $ope['function'];
    $itemResult[$attribute] =
      $function(array_intersect_key($itemResult, $ope['params']));
  }
}

It's based on the attempt to move as much work as possible, from the loop where it's repetitively executed, to a preparatory work executed once:

build a version of $model strictly suitable for the current results structure (so we don't have to check it further)
invert the nested iterations: rather than iterate on $model attributes and look if applicable, now we know that the $model contains only applicable attributes, so for each one we can directly work with the current record contents

At the same time, I chose to simplify the transformer function invocation: passing a unique array argument avoids using call_user_func_array(). Note that it needs the adaptation of the transformer functions, but it should be quite easy.

A few more little things:

I stopped using a temporary copy of $itemResult, which is useless
I used as much PHP specific functions as possible (instead of a sequence of statements) to reduce processor consumption: array_flip(), array_intersect_key()


Shell script to display environment variables

Readability

Just because Bash let's you cram a lot of statements on a single line doesn't mean you should.
I recommend to split this up to multiple lines,
and also to put spaces around |, like this:

#!/bin/bash

PAGER=more
if less >/dev/null; then
    PAGER=less
fi
echo $PAGER

if [ -z ${1+x} ]; then
    printenv | "$PAGER"
else
    printenv | grep "$1" | "$PAGER"
fi

But if you like compact writing style,
a reasonable compromise is to replace the first if statement with an alternative writing style using && like this:

less >/dev/null && PAGER=less

Error handling

I'm not sure if it's intentional,
but if the less command doesn't exist (but in most systems it does),
this line will emit an error message:

if type less >/dev/null

To avoid errors, you want to suppress stderr too in addition to stdout:

if type less >/dev/null 2>&1

Prefer simple solutions

This is hacky, cryptic:

if [ -z ${1+x} ]; then

I suggest a much more readable, simple equivalent:

if [ -z "$1" ]; then

Don't repeat yourself

The printenv command is repeated in both branches of the last if statement.
You could move it in front of the if, like this:

printenv | \
if [ -z "$1" ]; then
    "$PAGER"
else
    grep "$1" | "$PAGER"
fi

However, in this writing style it's important that the \ on the line before the if is the last character on the line directly in front of the line break.


Comments
While the code is mostly simple to follow, it would be good to add comments to document what decisions you made. Even if you are the only one maintaining this code your future self might not remember what considerations you had in the past. At least document the input, output and purpose of functions. Some style guides call for comments to be in certain formats - e.g. JSDoc in Google style guide.
Nesting Levels
The nesting levels gets a bit deep towards the end of logon.js- some might describe it a bit as “callback hell”. callbackhell.com has some good tips for keeping code shallow- like naming anonymous functions so they can be moved out (also may allow for use in unit and/or feature tests), modularize (which is already done somewhat with logon.js), etc.
Variable name format
It would be best to use consistent formatting of variable names. I have worked on a PHP codebase that makes quite extensive use of hungarian notation but I am not fond of it and I haven't seen it used very often with JavaScript code. I happened to recently see this Stack Overflow question about Hungarian notation and while it is marked as off-topic it does have many answers. The top voted answer contains a link to an article by Joel Spolsky, CEO and co-founder of Stack Overflow: Making Wrong Code Look Wrong. I know realize that much of the code throughout that codebase is “Systems Hungarian”.
It appears there are two variables named using Hungarian notation (i.e. oSrv and oSrvCli) while most all other variables are all lowercase or camelCase. There seems to be one other outlier: durl- which seems to be the discovery URL. One could name that as discoveryURL, or take the server URL/host name out of it and make it a real constant - e.g. const DISCOVERY_PATH = '/.well-known/openid-configuration'; , which can be appended to process.env.srvurl when used.
Async functions
As was mentioned in a comment, the async keyword has likely been applied to more functions that necessary. For example, only functions that contain the await keyword need to be declared as asynchronous- e.g. the function assigned to module.exports, the callback to req.login()).
Error handling

By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked.1

passport.authenticate('oidc', async (err, user) => {
    if (err) {
        console.log(`Authentication failed: ${err}`);
        return next(err);
    }

This error handling seems fine. Would it be helpful to log the user object in the callback to the call to passport.authenticate()? If so, consider sanitizing any sensitive information that may be attached. You could also consider an error logging service.
It appears your code follows the Custom Callback option for passport.authenticate(). The sample under that section Custom Callback checks for err and when it is anything other than false-y it will return next(err)

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }

If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.

It may be useful for you to read other reviews about nodeJS and passport as well as nodeJS and error-handling. The posts below might also be helpful:

Express Passport (node.js) error handling
How to show custom error messages using passport and express

Promisifying passport.authenticate()
This Stack overflow post might be interesting if you want to use await with the call to passport.authenticate():

I've been failing to get passport.authenticate to work at all inside of an async/await or promise pattern. Here is an example I feel should work, but it fails to execute passport.authenticate().

const passport = require("passport");
let user;
try {
   user = await __promisifiedPassportAuthentication();
   console.log("You'll never have this ", user);
} catch (err) {
   throw err;
}
function __promisifiedPassportAuthentication() {
    return new Promise((resolve, reject) => {
        console.log("I run");
        passport.authenticate('local', (err, user, info) => {
             if (err) reject(err);
             if (user) resolve(user);
         });
    });
}

The self-answer claims that the OP needed to invoke the function returned by the call to passport.authenticate() passing req and res, which likely need to get passed to __promisifiedPassportAuthentication().


Down with the underscore
I find the naming of printPdf_xxxx functions confusing, because if that code is/were in a class module they should be private, and the class would say Implements printPdf, where printPdf would be a class with VoidedNewItems and  ComsNotFed members... or it could be that there's a private field called printPdf that's declared WithEvents and the functions are event handlers made public.
Avoid underscores in procedure & function (/method) names, the language has a meaning for identifiers with an underscore.

Initializing once
If you scratch that code and implement it in a class instead, and run initialisation in the... Class_Initialize method, which can be thought of as a parameterless constructor that runs when you create the object. Not too crazy about spawning a UI prompt in that handler though, but then the methods wouldn't have to worry about whether or not Initialize has executed.


Querying list of servers with PS to report on Scheduled Tasks

Fan-out remoting

Calling Invoke-Command with an array for -ComputerName is perfectly fine. Note that it's going to call them one by one. If it can't reach some, there will be errors, but it's fine. It's sort of like doing:

$list | ForEach-Object {
    Invoke-Command -ComputerName $_ -ScriptBlock { ... }
}

The above can be useful for helping you with progress, like if you wanted to do something like:

$list | ForEach-Object {
    Write-Verbose $_ -Verbose
    Invoke-Command -ComputerName $_ -ScriptBlock { ... }
}

Or you could turn it into a for loop instead so you know the index, then you can calculate percentage and use Write-Progress to get some really nice progress info.

As for how effective it is, well, very, as long as you don't have a lot of servers and/or don't care how long it takes, since it's not going to run in parallel on all the machines.

Other options for parallel remoting

Workflows

You could use a PowerShell workflow, which has capability to process things remotely and in parallel, but to be honest it's a little weird at first, and probably not necessary.

Jobs

Probably the easiest way to implement parallel jobs is to use PSJobs. You would basically add the -AsJob parameter to Invoke-Command, but then its output is the job object. You have to retool things a bit to then wait on and receive the jobs and the data they return.

Jobs are a bit heavy though; they're technically entirely separate PowerShell processes, so if you have 2,000 servers, it might not be a good idea to suddenly spawn 2,000 powershell processes on your workstation to host the jobs, so be weary of that. Jobs would mostly be useful if you have ~100 or fewer machines, a good workstation, and maybe a lot of the servers timeout (so they take longer than the remote process needs to even run, and choke the whole thing).

Runspaces

PowerShell MVP Boe Prox has a module called PoshRSJob that use runspaces as a more efficient way of multithreading in PowerShell, and it supports throttling too.

Just don't

Since you're just trying to generate a report that you'll look at later, I'd say keep it simple and just don't do it in parallel.


I think your names could be simplified.  For instance, the ShapeType enum could be:

public enum ShapeType { Square, Circle, Triangle }

Because ShapeType.SquareShape sounds redundant, whereas ShapeType.Square still clearly indicates that the square is a shape type.

The ShowArea method is not needed.  It would most likely be used to display console writes, but your shape classes should not concern themselves with writing to the console.  You could modify ShowArea to return a string, but that string would be nothing more than the numeric area converted to a string.

CalculateAndShowArea should be in the client, as it issues several calls and it - not the respective IShape instance - should take care of console writes.

But most importantly, the area calculation should be done within the shape classes.  The problem with your code as posted is it lacks many critical things that help distinguish among different shape types.  For instance, a circle would be defined at the very least by a radius, and you may consider a center XY point along with a radius.  This allows you to calculate the circle's area.  Likewise, a square should be defined by a length of one of its sides.  And again, a square could then calculate its area.

A triangle is a different creature.  There are different ways to construct a triangle.  One way is passing in 3 non-colinear points.  Another way might be passing in 3 line segment lengths.  But a triangle constructor would also have to contain validation that whatever was passed in creates a truly valid triangle.

Which makes a singular factory method to generate 3 very different shapes fairly useless, unless you imposed a restriction that it would be a circle with radius 1, a square with side length of 1, and a triangle with 2 sides of length 1.  But if you do that, you've reduced the flexibility of the specific shape classes.

Also, the method name CalculateArea is bit long.  A more standard name would be GetArea, but many people would really choose to have a readonly property named Area.

Example

public interface IShape
{
    double Area { get; }
    string Name { get; }
}
public class Square : IShape
{
    // May consider Length be a double
    public int Length { get; }
    public Square(int side)
    {
        Length = side;
    }
    public double Area => Length * Length;
    public string Name => "Square";
    public override string ToString() => $"{Name}: Length={Length}";
}
public class Circle : IShape
{
    // Might consider making this a double
    public int Radius { get; }
    public Circle(int radius)
    {
        Radius = radius;
    }
    public double Area => Math.PI * Radius * Radius;
    public string Name => "Circle";
    public override string ToString() => $"{Name}: Radius={Radius}";
}
// Triangle class is left to you.

This makes your shape constructor more tailor made for each specific shape, but it also means you may not be able to construct it via a singular factory method without some significant changes.

UPDATE

As noted by Jesse Slicer in the comments, each class could identify itself better.  Jesse suggests having each class could have a Shape property that would echo its ShapeType.  It a decent idea but one that I would modify slightly.  I see the ShapeType enum as belong to the factory method.  I think a design should allow for the possibility of a shape that isn't specified in the enum but that implements IShape.  Thus I would have each class implement its type, and we can ditch the Name property.

public interface IShape
{
    double Area { get; }
    Type Type { get; }
}
public class Square : IShape
{
    // May consider Length be a double
    public int Length { get; }
    public Square(int side)
    {
        Length = side;
    }
    public double Area => Length * Length;
    public Type Type => GetType();
    public override string ToString() => $"{Type.Name}: Length={Length}";
}
public class Circle : IShape
{
    // Might consider making this a double
    public int Radius { get; }
    public Circle(int radius)
    {
        Radius = radius;
    }
    public double Area => Radius * 2 * Math.PI;
    public Type Type => GetType();
    public override string ToString() => $"{Type.Name}: Radius={Radius}";
}


Get an integer as input and display Pi rounded to that amount of decimal places

There are several issues with this piece of code:

    do
    {
        string digitAsString = Console.ReadLine();
        roundTo = ConversionLoop(digitAsString);
    }
    while(roundTo == 0 && counter != 5);
    if(counter == 5)
    {
        throw new FormatException();
    }
    else
    {
        double piRounded = Math.Round(Math.PI, roundTo);
        Console.WriteLine(piRounded);
        Console.ReadLine();
    }

Problems:

"ConversionLoop" is a meaningless name. The function parses a string to an integer, so a better name would be toInt
The handling of invalid input and incrementing the counter are not visible here. At first look I didn't see how the counter can advance, and it seemed you don't tell the user about invalid results. I had to look at the ConversionLoop to find out, but it was not logical to do so. The responsibility of getting valid input should not be split between two methods, it would be clearer to handle in one place, and have all the elements of the logic easily visible.
If the user fails to enter valid input 5 times, the code throws new FormatException()

FormatException is not appropriate for this. The problem is not invalid format, but failure to enter valid input within a reasonable number of retries. It's a different kind of error, and should be captured by a different exception class
Creating an exception without a text message explaining the problem makes debugging difficult

After throwing an exception in the if branch, the program exits from the method, so you can simplify the else

A bug

I think you have a bug: if the user enters 0 as input,
the ConversionLoop method doesn't print an error and returns 0 normally,
but the program will still wait for another try.
Without a message, this will be confusing to the user.
I doubt you intended it this way.

Suggested implementation

With the above suggestions, the code becomes:

class UserInputException : Exception
{
    public UserInputException(string message) : base(message)
    {
    }
}

public static int MAX_TRIES = 5;

static void Main(string[] args)
{
    Console.WriteLine("Welcome to the Pi-Rounder! Find Pi to up to 15 decimal places!");

    int roundTo = ReadIntegerInput();
    double piRounded = Math.Round(Math.PI, roundTo);
    Console.WriteLine(piRounded);
    Console.ReadLine();
}

static int ReadIntegerInput()
{
    Console.WriteLine("Please enter the number of decimal places you'd like to round to.");
    int counter = 0;
    while (true)
    {
        string digitAsString = Console.ReadLine();
        try
        {
            return Convert.ToInt32(digitAsString);
        }
        catch(FormatException)
        {
            if (++counter == MAX_TRIES)
            {
                throw new UserInputException("Too many invalid inputs. Goodbye.");
            }

            Console.WriteLine("That was not a valid number. Please try again.");
        }
    }
}


Very clean code indeed, there's not much to be said here.

PEP8

I'm sure you've been lectured on this before, but there's an official style guide for Python called PEP8. It states that module-level class definitions should be separated by two lines:

import tkinter as tk
import datetime

class Countdown(tk.Frame):
    ...

You also leave the first line of every method blank (or make it a docstring). If a function is undocumented, I wouldn't bother adding a blank line:

def foo():
    do_stuff()

If you decide to add a docstring, I'd recommend the following structure:

< function definition >
    < docstring (may span multiple lines) >
    < blank line >
    < function body >

For example:

def bar():
    """I'm a docstring!
    Blah, blah.
    """

    do_stuff()

Private attributes

It's good that you marked _timer_on as private. Why not do the same for seconds_left and the helper methods? This clearly tells other developers: 'I'm not part of the API. Don't rely on me for backwards compatibility.'. (Added bonus: you don't have to document private functions).

class Countdown(tk.Frame):
    ...

    def show_widgets(self):
        < docstring >

        ...

    def create_widgets(self):
        < docstring >

        ...

    def _countdown(self):
        ...

    def _start_button(self):
        ...

    def _stop_timer(self):
        ...

    def _convert_seconds_left_to_time(self):
        ...

Basically, any method, property, or attribute that isn't useful for end users, should be private.

OOP

convert_seconds_left_to_time could be a staticmethod. A static method does not receive an implicit first argument. You should make a method static if it doesn't interact with the instance of the class, but is still strongly related to the class.

I'd then rename it to _get_timedelta_from_seconds:

class Countdown(tk.Frame):
    ...

    def countdown(self):
        """Update the label based on the time left."""

        self.label["text"] = self._get_timedelta_from_seconds(self.seconds_left)

    @staticmethod
    def _get_timedelta_from_seconds(seconds):
        return datetime.timedelta(seconds=seconds)


The function signature strikes me as difficult to read, thanks to the constraint std::same_as<std::byte> auto... and the trailing "return type" std::unsigned_integral auto. I might rather write something like
constexpr auto bytes_to_uint(std::initializer_list<std::byte> bytes) {

...Ah, but then you couldn't use bytes.size() as a constant expression; I see.
So I'd think about writing an overload set, like this:
constexpr std::uint8_t bytes_to_uint(std::byte a) {
    return a;
}
constexpr std::uint16_t bytes_to_uint(std::byte a, std::byte b) {
    return (a << 8) | b;
}
constexpr std::uint32_t bytes_to_uint(std::byte a, std::byte b, std::byte c, std::byte d) {
    return (a << 24) | (b << 16) | (c << 8) | d;
}

But I guess this is messy because you need 16 different overloads. You can't even use default function arguments, because you want bytes_to_uint(a,b,c) to be equal to bytes_to_uint(0,a,b,c) and not bytes_to_uint(a,b,c,0). Of course you could still write
#define B std::byte
constexpr std::uint8_t bytes_to_uint(B a)
  { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,a); }
constexpr std::uint16_t bytes_to_uint(B a, B b)
  { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,0,a,b); }
constexpr std::uint32_t bytes_to_uint(B a, B b, B c)
  { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,0,a,b,c); }
constexpr std::uint32_t bytes_to_uint(B a, B b, B c, B d)
  { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,0,a,b,c,d); }
constexpr std::uint64_t bytes_to_uint(B a, B b, B c, B d, B e)
  { return bytes_to_uint(0,0,0,0,0,0,0,0,0,0,0,a,b,c,d,e); }
[...22 more lines...]
#undef B

but I bet you don't want to do that. Okay, let's stick with the templatey thing you did.

using result = std::tuple_element_t<N, types>;

I'd rather see this dependent typedef use CamelCase (like a template parameter) or suffixedwith_type (like an STL member typedef). Calling it result makes it look too much like a variable, and makes it hard to pick out the one place where you use it.
Instead of spending 13 lines and a <tuple> dependency, I'd rather just do
using ResultType = std::conditional_t<
    (N == 1), std::uint8_t, std::conditional_t<
    (N == 2), std::uint16_t, std::conditional_t<
    (N <= 4), std::uint32_t, std::uint64_t>>>;

Which reminds me, you need something like
static_assert(N <= 16);

to stop you from trying to handle an argument list of 17 bytes or more.
And I didn't even notice until I tried it in Godbolt, but, you've got an off-by-one bug here! You meant tuple_element_t<N-1, types>. Remember that indexing always starts at zero (everywhere except <regex>).

If you don't like conditional_t, another option is to use plain old ifs. Factor out the computation while it's still parameterized on ResultType, and then use an if-else chain to decide on the right type to plug in for ResultType later:
auto do_it = [&]<class ResultType, std::size_t... S>(ResultType, std::index_sequence<S...>) {
    return ((static_cast<ResultType>(bytes) << CHAR_BIT * (N - S - 1)) | ... );
};
if constexpr (N == 1) {
    return do_it(std::uint8_t{}, std::make_index_sequence<N>{});
} else if constexpr (N == 2) {
    return do_it(std::uint16_t{}, std::make_index_sequence<N>{});
} else if constexpr (N <= 4) {
    return do_it(std::uint32_t{}, std::make_index_sequence<N>{});
} else if constexpr (N <= 8) {
    return do_it(std::uint64_t{}, std::make_index_sequence<N>{});
}

Even better, permit the compiler to do the math at its preferred bit-width (which is 64 bits on all the desktop platforms I care about) and then truncate it at the end. This produces similar codegen and reads nicer yet:
std::uint64_t result = [&]<std::size_t... S>( std::index_sequence<S...>) {
    return ((static_cast<std::uint64_t>(bytes) << CHAR_BIT * (N - S - 1)) | ... );
}(std::make_index_sequence<N>{});
if constexpr (N == 1) {
    return std::uint8_t(result);
} else if constexpr (N == 2) {
    return std::uint16_t(result);
} else if constexpr (N <= 4) {
    return std::uint32_t(result);
} else {
    return std::uint64_t(result);
}

You have another bug when N == 1 (besides the off-by-one bug). When N == 1, the fold-expression has no | operations at all, and so it's just a uint8_t shifted by zero. That shift expression has type int. Which is not an unsigned integral type. So your return-type-constraint fails!
This is just another reason to do all the math first in uint64_t, and then cast down to uint8_t right before you return, as shown in my last example above.
Writing any test cases would have caught both this bug and the off-by-one bug. Test cases are always important! Especially when you're planning to put the code up for public review. (Or for review by coworkers, for that matter.)

Finally, I recommend parentheses to clarify the precedence of x << CHAR_BIT * y. In context it's obvious what you expected the precedence to be; but as a reader, I'm not sure you're right. Put the parentheses so that I don't have to think about it even for a second.
However, in this context, that's a very minor point, because you clearly aren't expecting anybody to read the expression ((static_cast<result>(bytes) << CHAR_BIT * (N - S - 1)) | ... ). It's a "trust me" line of code.
It's also silly to pretend that CHAR_BIT is relevant here. This code explodes spectacularly if CHAR_BIT is anything other than 8. So just write 8; and if you are compelled to work in a reference to CHAR_BIT, do so by writing
static_assert(CHAR_BIT == 8);

at the top of the function.


Streamlining series of try-except + if-statements for faster loop processing in Python

It's not 100 % clear what exceptions you expect, but I presume you are trying to handle the case when the regex does not match. I suggest handling it this way:

    #Transformation #1
    match = re.match(pattern, inword)
    result = match.group() if match else None

"after processing a few files, the script slows down" Have you considered the possibility that a particular file, or even a particular line is slow to process? A possible explanation to that would be that regexes can suffer from catastrophic backtracking.