C++ lock free, single producer, single consumer queue

Design

The problem with your implementation of pop() is that it can not be implemented in an exception safe manner (for any type of T). This is why the standard implementation implements this as two different methods top() and pop(). The top() function simply returns the value while pop() does not return the value but simply removes the value from head.

So usage would become:

T val = queue.top();
queue.pop();

Code Review

Your code assumes that T has a default constructor.

    std::unique_ptr<T[]> contents;

When you create the content with contents(new T[s]) you are allocating and initializing all the elements in that array using the default constructor.

In addition to this if T is very expensive you have just used a lot of effort to create the items that may never be used (or you wasted resources creating the objects that are just going to be destroyed when overwritten).

I would consider changing this to std::vector<T>. That way you don't create any un-required objects when first created.

This is fine:

    explicit PCQueue(size_t s) : size(s), contents(new T[s]), head(0), tail(0) {}

But you can make it more readable. Remember the point of code is to make the code maintainable.

    explicit PCQueue(size_t s)
        : size(s)
        , contents(new T[s])
        , head(0)
        , tail(0)
    {}

Is this the real definition of the function?

    //num of elements in ringbuffer (size - room())
    size_t count() {
        return (tail + size - head) % size;
    }

I would rename this function to reflect what the function is actually returning. I would also change the formula so it is easy to read. I would call this availableSpace(). The formula is: size - (head - tail).

This would be better named freeSpace().

    //num of free spaces in ringbuffer (size - count())
    size_t room() {
        return (head + size - tail) % size;
    }

You pass the parameter by value.

    void push(T t) {

This causes a copy to be made to pass it to the parameter. You should pass this by const reference (so there is no copy). If you want to get more advanced you could also pass by r-value reference which would allow you to move the object into your buffer rather than copying it.

    void push(T const& t) {   // Pass by const reference
    void push(T&& t) {        // Pass by r-value reference

The problem with the pop() as written you can not guarantee a clean removal. This is because you need to make several copies and if those copies fail you can leave the container in a bad state.

    T pop() {
        T ret = contents[head];              // Here is a copy.
        size_t newHead = (head + 1) % size;
        head = newHead;
        return ret;                          // Here is another copy.
    }

You did not define T so you don't have control over the copy assignment constructor. That is why it is usually split into two functions.

    // Return by reference
    // That way we can avoid any un-needed copies.
    T const& top() const {
        return contents[head];
    }
    // Simply remove the head item in the pop.
    void pop() {
        size_t newHead = (head + 1) % size;
        head = newHead;
    }


I'll edit this once it's posted what the code is supposed to do.

The code is extremely cryptic. There are no comments; the variable & membervariable names are all abbreviations. Someone else looking at this code will have no idea what is supposed to be happening. At the very least there should be docstrings at the start of each function/method that describe what the function is used for and the purposes of each variable.

The only possible performance improvement I see is to combine the __par, __csz, and __root members since they all have the same keys. That way the same element doesn't need to be hashed multiple times. The data structure, instead of being split between three dictionaries each of which being a member variable/field, would just have one dictionary with appropriate keys and the values being a list of [parent, csz, root].

def __init__(self, s=set()):
  self.__data = {x: [x, 1, x] for x in s}

def add(self, x):
  if x not in self.__data:
    self.__data[x] = [x, 1, x]

If you need one of the members you just refer to self.__data[x][0] or whatever.


Hold a list of items stored in recursive class?

Well, it's not a tree, it's a linked list, and it won't work properly for more than seven items. After that you will overwrite the SubLeaf variable in the first node, and previously added items will be removed from the list, and AllItems will contain lost items with disowned nodes.

To make the list work you have to check if the node has a next node before creating a new one.

public class Node {

  private Node _next;
  private List<object> _items;

  public Node Previous { get; private set; }

  public Leaf (Leaf previous) {
    _previous = previous;
    _next = null;
    _items = new List<object>(6);
  }

  public void Add(object obj) {
    if (_items.Count == 6) {
      if (_next == null) {
        _next = new Leaf(this);
      }
      return _next.Add(obj);
    }
    _items.Add(obj);
    return this;
  }

}

Note: Consider using an array in the node instead of a list. Creating a list that uses lists seems redundant...

Also, keeping a reference to the last node in the handler would help when you want to add nodes, so that you don't have to loop through all nodes each time.

Putting the objects and their nodes in a list is not needed for looping through them, as you already have all the nodes and the objects. Adding the list would roughly tripple the memory usage and the time to add an item. You would only need another list if you need two completely different ways of accessing the items, for example both predictable enumerating and hash lookup.

To enumerate the list as pairs of objects and nodes, you can put an enumerator in the Node class which gets all objects and their nodes from the current node and forward, so you just use it on the first node to get all objects:

public IEnumerable<KeyValuePair<object,Node>> GetAll() {
  Node node = this;
  while (node != null() {
    foreach (object obj in node._items) {
      yield return new KeyValuePair<object,Node>(obj, node);
    }
    node = node._next;
  }
}


func readIntegers() -> Int {
    return Int(readLine()!)!
}

Now this is confusing! A function called  readIntegers which returns
a single integer? readInteger() or readInt() would be an
appropriate name.

The forced unwrapping is acceptable because the input comes from a
programming challenge with well-defined input. However, finding
errors in your code is easier if you check the optionals explicitly
and print an descriptive error message if the input does not
match the expectations.

And with a short description (using the "markdown format" which is
recognized by the Xcode "Quick Help inspector") it
becomes a reusable function for this and future programming
challenges:

/// Returns an integer read from one line of standard input.
func readInteger() -> Int {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    guard let i = Int(line) else {
        fatalError("Invalid integer in input")
    }
    return i
}

The same for reading a single string:

/// Returns a string read from one line of standard input.
func readString() -> String {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    return line
}

I am (usually) not a fan of adding type information to a variable
name, arrayOfStrings should just be named strings (as in the
description of the challenge).

Instead of starting with an empty array and adding elements one
can create the array with map(). This also allows us to declare the array as a constant:

let numOfStrings = readInteger()
let strings = (0..<numOfStrings).map {
    _ in readString()
}

singleString is better named query, and arrayOfSingleString
is the array with all strings matching the query:

let numOfQueries = readInteger()
for _ in 0..<numOfQueries {
    let query = readString()
    let matchingStrings = strings.filter { $0 == query }
    print(matchingStrings.count)
}

We are only interesting in the count of matching elements.
To improve the performance, determine the count without creating
an intermediate array:

    let matchingCount = strings.reduce(0) { (accum, str) in
        accum + (str == query ? 1 : 0)
    }
    print(matchingCount)

Another speed-up could be achieved by

Sorting the given strings, this needs to be done only once.
Use binary search to find a query string in the array.
If the string is found, traverse forward and backward through
the array to determine how many strings are equal to the query string.


One thing that I see that I would change is the if statement

    if (String.Equals(action, currentAction as string,
              StringComparison.OrdinalIgnoreCase)
        &&
       String.Equals(controller, currentController as string,
               StringComparison.OrdinalIgnoreCase))
    {
        builder.AddCssClass("active");
        return MvcHtmlString.Create(builder.ToString());
    }

I personally don't like having a conditional that spans over multiple lines,  so the first thing that I would do is to take the boolean conditions and make them into boolean variables and then use them inside the conditional.  I think it would be easier to read.

bool isCurrentAction = String.Equals(action, currentAction as string,
          StringComparison.OrdinalIgnoreCase);
bool isCurrentController = String.Equals(controller, currentController as string,
           StringComparison.OrdinalIgnoreCase);
if (isCurrentAction && isCurrentController)
{
    builder.AddCssClass("active");
    return MvcHtmlString.Create(builder.ToString());
}

And since you are returning builder immediately after the if statement, there isn't really a reason to return inside the if statement, it is rather redundant.  Just delete that from the if block

bool isCurrentAction = String.Equals(action, currentAction as string,
          StringComparison.OrdinalIgnoreCase);
bool isCurrentController = String.Equals(controller, currentController as string,
           StringComparison.OrdinalIgnoreCase);
if (isCurrentAction && isCurrentController)
{
    builder.AddCssClass("active");
}


You should name your function more descriptively, maybe acronym.
You should wrap your code under a if __name__ == "__main__": guard to allow importing parts of your script from other scripts.
You should separate the user input from the logic.
Use docstrings to describe what functions do.
Use str.join together with a generator expression to join multiple strings.
Use the new f-strings introduced in Python 3.6.

Taking this gives you:

def user_input():
    """Get the user input for a phrase"""
    return input("Enter the phrase: ")

def acronym(words):
    """Turn a list of words into an acronym"""
    return "".join(word[0] for word in words).upper()

def main():
    words = user_input().split()
    print(f"The acronym for your phrase is {acronym(words)}.")

if __name__ == "__main__":
    main()


Measure a given method's execution time - follow-up

while (Watch.Elapsed.Milliseconds < minimumTime)

It probably won't affect this code, but Milliseconds doesn't do what you probably think it does. I think you want TotalMilliseconds.

public static Task<Time> Measure(Action action, int? iterations = null, int times = 1)
{
    return Task.FromResult(iterations)
        .ContinueWith(async t => t.Result.GetValueOrDefault(await GetIterations(action)))
        .Unwrap()
        .ContinueWith(t =>
        {
            var iters = t.Result;
            TimeSpan timeTaken = TimeSpan.MaxValue;
            for (int i = 0; i < times; ++i)
            {
                timeTaken = MeasureTime(action, iters).Min(timeTaken);
            }
            return new Time(timeTaken.Ticks*100/iters);
        });
}

Generally speaking, if you can use await, you don't need ContinueWith().
What's the point of using Task.FromResult().ContinueWith()? Task.Run() would make much more sense here.
There is actually no reason to use Task and async-await here. You should use that only for truly asynchronous IO operations. If the caller wants to run your long-running CPU-bound code on a separate thread, they can easily do it themselves.
For performance-related code, it feels weird that you're calling GetIterations() even when it's not needed.


find the index of subarray from a parent array

Advice 1

Your method is a little bit overdone. Consider this:

public static int getSubArrayIndexV2(int[] haystack, int[] needle) {
    outer:
    for (int i = 0; i <= haystack.length - needle.length; ++i) {
        for (int j = 0; j < needle.length; ++j) {
            if (haystack[i + j] != needle[j]) {
                continue outer;
            }
        }

        return i;
    }

    return -1;
}

Advice 2

This is actually pattern matching in "strings" consisting of integers instead of characters. As such, you can use, say, Knuth-Morris-Pratt algorithm that runs in time \$\mathcal{O}(n + m)\$ (where \$n\$ is the length of the integer array to search in, and \$m\$ is the length of the integer array to search for). The complexity of your solution is worst-case \$\mathcal{O}(nm)\$.

(Take a look at this program.)


A few things which came to my mind while reading your code:

The Show instance for CellState might be a bit nicer by not writing out the case expression manually but rather using

instance Show CellState where
    show Dead  = "_"
    show Alive = "#"

You could shorten initializeGrid by using mapM_:

initializeGrid :: GridState ()
initializeGrid = mapM_ (\(x, y) -> setPositionToColor x y Alive)
    [(0,0),(1,1),(1,2),(2,0),(2,1),(4,4),(5,4),(6,4),(5,5),(5,4),(5,6)]

take n [0,1..] is the same as [0,1..n] (looking at createGrid).
callCellState could be shortened by only explicitely testing the conditions determining whether the cell becomes (or remains) alive:

calcCellState :: Bool -> Int -> CellState
calcCellState living livingNeighbours
    | living && livingNeighbours `elem` [2,3] = Alive
    | not living && livingNeighbours == 3     = Alive
    | otherwise                               = Dead

On a more general note, seeing how long the updateCell function is and how you had to roll your own next and previous function I do suspect that lists are not the most appropriate data structure for this kind of problem. A vector may be easier to work with.


Guess user number between 0 and 100 (Binary Search)

Your calculation of count is incorrect in two ways:
 1. You don't count your last guess;
 2. You count invalid user input.

I would separate the input validation from the input processing. And I would add some logic to handle user input that leads to trying the same guess repetitively, for this the user has to lie, but who guarantees us they won't?


Is there a more optimal way to approach some of these bitwise functions?

The comment \\ basically sizeof(int) using bit manipulation
is wrong. sizeof(int) gives the number of bytes (technically, "storage units"), but your function gives the number of bits.

If you change the name of the function to something descriptive like bits_in_int(), you might not need the comment.

The C language says that a char must always be a storage unit.  If you know how many bits are in a char, you can just multiply by sizeof(int) to get the number of bits in an int.  And there's a constant, CHAR_BIT, in header <limits.h> which is the number of bits in a character.  So your whole int_size() function could be reduced to the compile-time expression sizeof(int) * CHAR_BIT;

If you really want to figure it out yourself, instead of using language-defined tools, your function could still use better style.  First, a for loop shouldn't try to put everything in the loop header.  The header should concern itself with the iteration.  Everything else should either go before the loop, or in the loop body.  I would replace your loop with:

for (unsigned int i = ~0u; i > 0; i >>= 1)
{
    size++;
}

size has nothing to do with controlling the loop, so I moved it to the body. I changed ~00u to ~0u.  I see no reason to use an octal zero (00) instead of a decimal zero (0).

(Incidentally, I suggest never writing a single-statement loop or if statement without the braces.  The typing you save doesn't make up for the increased risk of introducing an error in the future.)

This loop:

for(int i = 0; i < int_size(); i++)
     printf("%X",bit_get(data,i));

is inefficient.  You're computing int_size() each time through the loop.  This is better:

const unsigned int size = int_size();
for(int i = 0; i < size; i++)
{
    printf("%X",bit_get(data,i));
}

(You're calling int_size() more than once in other functions; I won't keep mentioning it.)

Get in the habit of declaring things const whenever possible.  It makes the code clearer to the reader.  It sometimes helps the compiler do a better job optimizing. And it makes you more aware of stuff that you can move out of loop bodies.

If a function returns an unsigned int, it probably doesn't make sense to return -1 to mean "invalid input" (function bitpat_get) or "not found" (function bitpat_search).  -1 converts to an unsigned int filled with 1 bits (at least on a two's complement machine).  This is probably a valid result for some input, so the calling code can't reliably extract the meaning from the return value.

Does bitpat_search() behave reasonably if the caller lies?  What if the value passed in n is wrong for the given pattern?  If the caller is supposed to do n = bit_width(source), why not do the calculation inside bitpat_search() instead of making the caller pass n?


General tips

Avoid defining your own loops. This is especially true with R because the chances are that there is another more elegant way to solve the problem using highly optimized functions.
Avoid rbind function inside loops especially if your are using it as an appending mechanism. This function creates a new empty data frame with a number of rows equal to number or rows of the old plus the number or rows of the new. Then it will copy the old and the new into this newly created data frame. This operation can be really expensive if you have large dataset. An optimizing solution can be achieved by creating an empty data frame with right size once outside the loop and populate it with the results using i index e.g all_results[i] = new_results inside the loop.
Avoid subset inside loops. The function documentation states that this is only a convienet function and should only be used in interactive setting.It also recommends that you use [ for subsetting.

Warning
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like [, and in particular the non-standard evaluation of argument subset can have unanticipated consequences.

Moreover, it has the same issue as in the tip #2 since you are writing a new data frame minus the processed row in every go inside the loop.
Alternative solution
The problem can be solved using much less code than provided. Also it will only involves where the real data is the per_game table.
First you need to breakdown winner column in 3 for each winner. Since you seem familiar with the tidyverse family packages I will use functions from these packages.
library("tidyr")
library("dplyr")

per_game %>%
# Here we breakdown the winner columns into 3 using `spread()` function from tidyr
spread(winner, total_matches) %>%
# Then we add the black and white columns into new column called `victories`
rowwise() %>% # to ensure summation excute on per row.
mutate(victories  = sum(black, white,na.rm = TRUE))

# the results should look like this

# Rowwise:
   white_id           black_id           black  draw white victories
   <chr>              <chr>              <dbl> <dbl> <dbl>     <dbl>
 1 --jim--            "voodooo"              1    NA    NA         1
 2 -1-jedi_knighl_-1- "erik123678"          NA    NA     1         1
 3 -1-jedi_knighl_-1- "kaY\\ran0098"         2    NA     2         4
 4 -1-jedi_knighl_-1- "pav1ngt"              1    NA    NA         1
 5 -mati-             "astronavtearl101"    NA    NA     1         1
 6 -pavel-            "hishamtheman"        NA    NA     1         1
 7 1063314            "dccbc,ss"            NA    NA     1         1
 8 1111112222         "crusova_ 33"          1    NA    NA         1
 9 1111112222         "steelviper"           1    NA    NA         1
10 1240100948         "aa22bb"               1    NA    NA         1


A simple assembly program to count the number of ones in a register

For some more advanced ideas, check out https://stackoverflow.com/a/109025/2189500.

But expanding on CWallach's code, how about:

mov edx, 255 ; setup edx with test value
xor eax, eax ; count

start_loop:
bt edx, 0 ; sets carry flag if bit 0 is set
adc al, 0 ; add with carry
shr edx, 1 ; drop off bit
jnz start_loop ; exit if edx is now 0

xor is a smaller instruction for setting a register to zero.
bt sets the carry flag for use in
adc adds 0 to al, but also includes the contents of the carry flag.

And once you've got your head wrapped around that, how about:

mov edx, 255 ; setup edx with test value
xor eax, eax ; count

shr edx, 1 ; move rightmost bit to carry flag
start_loop:
adc al, 0 ; add with carry
shr edx, 1 ; move rightmost bit to carry flag
jnz start_loop ; exit if edx is now 0
adc al, 0 ; count last bit

This takes advantage of the fact that when shr shifts, it moves the shifted bit into the carry flag.  And while there are more instructions overall (5 vs 6), there are fewer within the loop (4 vs 3).


Insert dynamic parameters to sqlite database statements

I would create an object to model my dynamic parameters using the following interfaces:

{ //reduced format
    clause: string,
    params: an array of parameters if more than one is used
}
{ //simple entry format
    clause: string
    param: the parameter if only one is used
}
{ //or format
    or: an array of dynamic parameter interfaces to be joined as part of an or clause
}
{ //and format
    and: an array of dynamic parameter interfaces to be joined as part of an and clause
}

From here I could use the following functions:

function reduce(param) {
    var clause = [], params = [], nest, nestType;
    if (param.clause !== undefined && param.params) {
        //already in reduced format
        return param;
    }
    if (param.clause !== undefined && param.param !== undefined) {
        //convert simple format to reduced
        return { clause: param.clause, params: [param.param] };
    }
    if (param.clause) {
        //special case (clause without additional parameter)
        //parameters without clause would be done by using empty string
        return { clause: param.clause, params: [] };
    }
    //convert nested forms (and and or)
    if (param.and) {
        nest = param.and;
        nestType = ' AND ';
    } else if (param.or) {
        nest = param.or;
        nestType = ' OR ';
    } else {
        throw new Error('Invalid dynamic parameter found');
    }
    nest.forEach(function (p) {
        p = reduce(p);
        clause.push(p.clause);
        params.push.apply(params, p.params);
    });
    return {
        clause: '(' + clause.join(nestType) + ')',
        params: params
    };
}

function executeDynamicSql(tx, base, dynamicparameter, onSuccess, onError) {
    var reduction = reduce(dynamicparameter);
    tx.executeSql(base + reduction.clause, reduction.params, onSuccess, onError);
}

And call it (in your test case) like so:

executeDynamicSql(tx, 'SELECT Data from Table Where ', {
    clause: 'something = ?',
    param: anyvariable
}, successFn, errorCB);

What is nice about this function is that it can handle a far more complex where clause such as:

var dynamicwhere = {
        or: [
            {clause: 'something = ?', param: somethingid},
            {clause: 'somethingelse = ?', param: somethingelse},
            {clause: 'somedate between ? and ?', params: [d1, d2]},
            {
                and: [
                    {clause: 'amt > ?', param: min},
                    {clause: 'amt < ?', param: max},
                ]
            }
        ]
    };

executeDynamicSql(tx, 'SELECT Data from Table Where ', dynamicwhere, successFn, errorCB);

Ultimately executing:

SELECT Data from Table Where (something = ?
                           or somethingelse = ?
                           or somedate between ? and ?
                           or (amt > ? and amt < ?))

With the in order parameter list:

[somethingid, somethingelse, d1, d2, min, max]

You could do something more fancy using a regex replace or whatever, but I don't think it should be necessary.


Interchange all occurrences of a character and its predecessor

You want to do a string replacement operation, so use preg_replace().  The key is to use backreferences in the replacement.  Also, since you seem to be interested in processing Unicode, be sure to use the u flag for the regex.

If, as you say, 'b' is just an example, then you can make it a default parameter.

function punjabi_alternate($string, $char='b') {
    return preg_replace("/(.)($char)/u", '\2\1', $string);
}


Your code looks very clean to me and I already like it very much. A few minor remarks.

Assuming that you'll probably want to provide this functionality in a header file, you should declare all your functions as inline. Even if they're not in a header file, it doesn't hurt to do so.
Consider declaring your functions as noexcept, too.
I'd prefer to see the implementation details hidden in a “detail” namespace to make it clear that only hashCString is supposed to be used directly. (Or is this assumption incorrect?)
ct::hashCString is not the most descriptive name. I'd prefer if the name somehow indicated the implemented hash algorithm.
You don't actually need the length of the string. Just replace length != 0 with *cstr != '\0' in hashImpl and figure out the length as you go. This will save you one function.
It seems to me that “plus” or “add” would be more consistent with “xor” than “sum” as the emphasis is on the operation.
Your code assumes that char is an 8 bit integer. It would also be nice if you could hash arrays of signed and unsigned chars alike. Something like the following might do.

template <typename CharT>
constexpr typename std::enable_if<std::is_integral<CharT>::value && (CHAR_BIT * sizeof(CharT) == 8), std::uint8_t>::type
hashCString(const CharT *const s) noexcept;

Instead of requiring CHAR_BIT * sizeof(CharT) == 8, you could relax it to (CHAR_BIT * sizeof(CharT)) % 8 == 0 and manually loop over each octet in wider types. Smells like overkill, though.
Another possible generalization would be to provide the classical interface that takes a pair of “begin” and “end” iterators. This might be handy for hashing sub-strings, strings with embedded zeros or strings that are not terminated with a 0 byte. You can still provide your single-argument version as a convenience overload.


Spring: Creating a Mutable Common Command Object or Controller Interceptor

I don't like the idea of modeling a common set of properties (or as you say "... for just about every API call..." probably a mostly common set of properties) as a superclass. IMO inheritance should be used to capture common business aspects, not common technical aspects. Or in other words, this feels somewhat like identifying a set of real world objects which have a lock, and then creating a HavingLock superclass with subclasses House, Car, Desk, ... - this simply does not sound right.

Then, the CommonRequestCommand has the ring of something that is a pure data holder. It has a set of parameters and maybe even a specific execution logic that is tied to the service you call. Tying this this to the lookup logic in your own application will make this a hard-to-test mess.

Thus, I agree that an immutable class will probably be the best, and furthermore recommend that you make that immutable class just a field in your commands. For the mutablility, you can always create a copy.

All in all:

put your parameters in a RequestParameters class, which is immutable and which does not contain business logic
for a request coming from the UI, check whether you have all parametes, look up the ones missing, and create such a RequestParametes object. This should be done in a business class in you application
After you created the RequestParameters object, create the concrete Command, passing the RequestParametes in.
Continue processing the command.


You say 'Doctest'  but then you format them badly with unecessary newlines and you do not actually run the tests.
Your code is much more complex than it should be.
When writing a programme remember that it should be the simplest possible.

The function down below behaves exactly like yours but:

It is 3 lines of code instead of 50.
The doctest is properly formatted so that you can actually run it.
The doctest is actually run when the script is executed as the main file.

:

import doctest

def find_missing(integers_list,start=None,limit=None):
    """
    Given a list of integers and optionally a start and an end, finds all
    the integers from start to end that are not in the list.

    'start' and 'end' default respectivly to the first and the last item of the list.

    Doctest:

    >>> find_missing([1,2,3,5,6,7], 1, 7)
    [4]

    >>> find_missing([2,3,6,4,8], 2, 8)
    [5, 7]

    >>> find_missing([1,2,3,4], 1, 4)
    []

    >>> find_missing([11,1,1,2,3,2,3,2,3,2,4,5,6,7,8,9],1,11)
    [10]

    >>> find_missing([-1,0,1,3,7,20], -1, 7)
    [2, 4, 5, 6]

    >>> find_missing([-2,0,3], -5, 2)
    [-5, -4, -3, -1, 1, 2]

    >>> find_missing([2],4,5)
    [4, 5]

    >>> find_missing([3,5,6,7,8], -3, 5)
    [-3, -2, -1, 0, 1, 2, 4]

    >>> find_missing([1,2,4])
    [3]

    """
    start = start if start is not None else integers_list[0]
    limit = limit if limit is not None else integers_list[-1]
    return [i for i in range(start,limit + 1) if i not in integers_list]

def _test():
    doctest.testmod()

if __name__ == "__main__":
    _test()


There doesn't seem to be a need for separate Male and Female structures as they hold the same exact data.  Instead, just have one named Person and create male and female instances of it.

You also don't need classes if you're not going to have any private data; just use structs.

struct Person
{
    bool isMarried;
    int salary;

    Person() : isMarried(false) {}
};

Person males[MALES];
Person females[FEMALES];

Regarding the use of C++11, you can start by removing both std::srand() and std::rand() and replacing them with functionality from the <random> library, particularly std::shuffle().


Code review

Not bad, code is nice and clean, and naming is good.

Game play has some logic flaws in the way you handle the keyboard and collisions.

Some code style points.

Use constants for variables that do not change.
Learn to add semicolon to the end of lines. Don't rely on automatic semicolon insertion as that has some traps.
Separate operators with spaces to make the codes easier to read. EG if(ball.x<0||ball.x>480 ){  should be if (ball.x < 0 || ball.x > 480) {
KeyboardEvent.keyCode is a depreciated property and could be removed at any time. Use KeyboardEvent.key or KeyboardEvent.code
Never use setInterval to time rendering as it is not synced to the display refresh. Use requestAnimationFrame instead.
Add "use strict"; as the first line of the JavaScript to tell JavaScript to run in a stricter and more performant mode.
You have let bricks = [length]; this does not create an array of length, it creates an array with the first item length. To set an array's length use the length property bricks.length = length;
window is the default object, there is really no reason for you to reference it. You don't use it for window.document, window.setInterval, or any of the variables you declare in global scope so why use it for window.addEventListener

Code design and logic

See the rewrite for more details regarding the points below.

The update function has taken on too much responsibility. Try to limit what a function does to one thing only.
Keyboard logic is incorrect. You assume only one control key to be down at any one time. Players will sometimes hold one direction and tap the other. Your code does not allow this giving the illusion that the first key down no longer works. It is better to just hold the key state of each key.
Your paddle/ball collision has some logic flaws. A general rule of game collisions is to NEVER allow the game state to enter an impossible state. In this case the ball and paddle overlapping.

As you have the code the ball will on occasion get stuck to the paddle.

When you do a collision remember that it happens over a period of time between the previous and current frame. You need to work out when the ball hit during that frame and where it will be at the start of the next frame (usually some distance from the collision as it is already moving away)
Objects can also hold functions. It is easier to manage the various parts of a game if you encapsulate functionality into the game objects as well. In the rewrite you will see the main object, ball, paddle and bricks all contain the functions they need to draw, update, init/reset and various other functions as needed.
You can inherit properties of existing types using Object.assign, or the spread operator ... allowing you to setup properties and functions that are the same for many different objects. The bricks are an Array with properties added to draw, etc. Each array item is a brick with its own properties and functions.
Rather than have a semaphore to indicate if a brick is showing or not you can remove the brick from the array and that will save you iterating many bricks that are not showing.
Having many magic numbers spread in your code you can create a settings object to hold everything in one place. This makes it much easier to change the game settings, saving the hassle of going over the code to find every instance of a setting. In the rewrite the object game has everything needed to set up the game.
The order of actions for a game is usually move everything , test collisions and adjust position of everything, then draw everything

The rewrite.

The rewrite is as an example only. There are many ways to organised the code for an app, each has it pros and cons. These will vary with the individual, with the best style being one that best suits your way of thinking. Don't let code dogma spoil the fun of writing a game.

The rewrite has added some things.

I needed to test if it was all working, and being lazy, playing the game to find problems was too much effort, so I added an autoplay that plays the game at many time normal speed so that I could make sure all was OK. Check the game.autoPlay  to turn off.

I also added a few more bricks.

I have change all the collision logic to a more robust form that takes in account the object's travel during the previous frame. As there are 4 types of collision Ball / Paddle, Ball / Wall, Ball / Brick, and Paddle/Wall each somewhat different in needs, thus the code base has grown somewhat.

I was tempted to add ball hit deviation depending on where the ball hit the paddle, but left that out in the end.

"use strict";

requestAnimationFrame(mainLoop); // request first frame. This will only happen after all the code below has been evaluated

// I am using direct reference to the canvas by its ID
//const canvas = document.getElementById("mainCanv");
const ctx = canvas.getContext("2d");

var score = 0;

/*===========================================================================================
  all game constants and settings
  ============================================================================================*/
const game = {
    backgroundColor : "black",
    autoPlay : true,
    auto : {
        playSpeed : 10, // Number of autoplay frames per 60th second Note one extra normal frame is also rendered
        follow : 0.7, // how well auto play ball follows 1 is perfect, 0.8 will always hit, < 0.8 ocational miss to 0 wont move
    },
    paddle : {  // details for the paddle
        init : {  // this is added directly to the paddle object
            w : 80,
            h : 15,
            color : "green",
        },
        fromBottom : 40, // these are added programmatic
        speed : 5,
    },
    ball : {
        init : { // this is added directly to the ball object
            w: 20,
            h: 20,
            x: 200,
            y: 200,
            color : "red"
        },
        dir : 0.6, // these are added programmatic
        speed : 4,
    },
    brick : {
        init : { // this is added directly to each brick object
            w : 20,
            h : 20,
            color : "blue",
        },
        spacingX : 40, // these are added programmatic
        spacingY : 40,
        top : 60,
        rowCount : 14,
        count : 14 * 4,
        value : 10, // points its worth
    },
    score : { // where to put the score and its color
        x : 20,
        y : 20,
        color : "white",
    },
}

/*===========================================================================================
  helper Function
  ============================================================================================*/
function doRectsOverlap(rectA, rectB){ // both rectA, and rectB must have properties x,y,w,h
    return ! (
        rectA.y > rectB.y + rectB.h ||
        rectA.y + rectA.h < rectB.y ||
        rectA.x + rectA.w < rectB.x ||
        rectA.x > rectB.x + rectB.w
    );
}
/*===========================================================================================
  Common object properties and functions
  ============================================================================================*/
const rectangle = {
    draw() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.w, this.h);
    }
}

/*===========================================================================================
  The main animation loop
  ============================================================================================*/
function mainLoop() {
 ctx.fillStyle = game.backgroundColor;
 ctx.fillRect(0, 0, canvas.width, canvas.height)
    inPlay();
    requestAnimationFrame(mainLoop); // request next frame
}

/*===========================================================================================
  When in play
  ============================================================================================*/
function inPlay() {
    if (ball.outOfBounds) {
        reset(); // reset game when out of bounds
    }
    // auto play loops over main game draws everything but bricks
    // at a faded alpha level
    if (game.autoPlay) {
        ctx.globalAlpha = 1 / (game.auto.playSpeed /4);
        for (let i = 0; i < game.auto.playSpeed; i++) {
            ball.update();
            paddle.update();
            bricks.update();

            paddle.testBall(ball);
            paddle.draw();
            ball.draw();

        }
        ctx.globalAlpha = 1;
        if (keys.any) {
            game.autoPlay = false;
        }
    }
    // main render for normal play at alpha = 1;
    ball.update();
    paddle.update();
    bricks.update();

    paddle.testBall(ball);

    paddle.draw();
    ball.draw();
    bricks.draw();

    if (bricks.length === 0 && paddle.hitBall) { bricks.init() }
    paddle.hitBall = false;
    drawScore();
}

function reset(){
    ball.reset();
    bricks.init();
    paddle.reset();
    keys.clear();
    score = 0;
}

function drawScore(){ // does the score thing
 ctx.fillStyle = game.score.color;
 ctx.fillText("Score: " + score, game.score.x, game.score.y)
}

/*===========================================================================================
  Keyboard state and event handler
  ============================================================================================*/
const keys = {
    ArrowLeft : false,
    ArrowRight : false,
    any : false,
    event(event) {
        if (keys[event.code] !== undefined) {
            keys[event.code] = event.type === "keydown";
        }
        keys.any = event.type === "keydown" ? true : keys.any;
    },
    clear(){
        for(const key of Object.keys(keys)) {
            if (typeof keys[key] !== "function") { keys[key] = false }
        }
    }
};
addEventListener("keydown", keys.event);
addEventListener("keyup", keys.event);

/*===========================================================================================
  Brick related code
  ============================================================================================*/
// Assign some functions to an array of bricks
const bricks = Object.assign([], { // The array to get some more properties
    init() {
        this.length = 0; // zero length
        for (let i = 0; i < game.brick.count; i++) {
            this.push({
                ...rectangle,
                ...game.brick.init,
                x: (i % game.brick.rowCount) * game.brick.spacingX,
                y: game.brick.top + (i / game.brick.rowCount | 0)  * game.brick.spacingY,
            })
        }
    },
    draw() {
        for (const brick of this) { brick.draw() }
    },
    update() {
        var i;
        for (i = 0; i < this.length; i ++) {
            const brick = this[i];
            if (ball.testBrick(brick)) { // check ball against brick remove brick if hit
                this.splice(i--, 1); // remove brick
                score += game.brick.value;
            }
        }
    }
});

/*===========================================================================================
  Ball related code
  ============================================================================================*/
const ball = {
    ...rectangle,  // assign common
    ...game.ball.init,  // assign ball init values
    dx : 0, // common name for speed is delta so I use deltaX, and deltaY shortened to dx,dy
    dy : 0,
    outOfBounds : true, // this forces reset at start of game
    reset() {
        Object.assign(this,
            game.ball.init, {
                dx : Math.cos(game.ball.dir) * game.ball.speed,
                dy : Math.sin(game.ball.dir) * game.ball.speed,
                outOfBounds : false,
            }
         );
    },
    update() {
        this.x += this.dx;
        this.y += this.dy;
        if (this.x <= 0) {
            this.x = -this.x; // the ball will have moved away from the wall the same distance it has moved into the wall
            // MUST MOVE AWAY +
            this.dx = Math.abs(this.dx); // Set the direction as always positive. If you do -this.dx it may stuff up when you have
                                         // the ball and paddle interacting at the same time
        } else if (this.x > canvas.width - this.w) {
            this.x = (canvas.width - this.w) - (this.x - (canvas.width - this.w));
            // MUST MOVE AWAY -
            this.dx = -Math.abs(this.dx);
        }
        if (this.y < 0) {
            this.y = -this.y;
            this.dy = Math.abs(this.dy);
        }
        if (this.y > canvas.height) { // ball out of bounds
            this.outOfBounds = true;
        }

    },
    checkbrickTopBot(brick){
        if (this.dy < 0) { // moving up
            this.y = (brick.y + brick.h) + ((brick.y + brick.h) - this.y);
            this.dy = -this.dy;
            return true;
        }
        // must be moving down
        this.y = brick.y - ((this.y + this.h) - brick.y) - this.h;
        this.dy = -this.dy;
        return true;

    },
    checkbrickLeftRight(brick){
        if (this.dx < 0) { // moving up
            this.x= (brick.x + brick.w) + ((brick.x + brick.w) - this.x);
            this.dx = -this.dx;
            return true;
        }
        // must be moving down
        this.x = brick.x - ((this.x + this.w) - brick.x) - this.w;
        this.dx = -this.dx;
        return true;
    },

    testBrick (brick) { // returns true if brick hit

        if (doRectsOverlap(this, brick)) {
            // use ball direction to check which side of brick to test
            // First normalize the speed vector
            var speed = Math.sqrt(this.dx * this.dx + this.dy * this.dy);
            var nx = this.dx / speed;
            var ny = this.dy / speed;
            var xDist,yDist;
            // now find the distance to the brick edges in terms of normalised spped
            if (this.dx < 0) {
                xDist = ((this.x - this.dx) - (brick.x + brick.w)) / nx;
            } else {
                xDist = ((this.x - this.dx + this.w) - brick.x) / nx;
            }
            if (this.dy < 0) {
                yDist = ((this.y - this.dy) - (brick.y + brick.h)) / ny;
            } else {
                yDist = ((this.y - this.dy + this.h) - brick.y) / ny;

            }
            // the edge that is hit first is the smallest dist
            if (xDist <= yDist) { // x edge first to hit
                return this.checkbrickLeftRight(brick);
            }
            return this.checkbrickTopBot(brick);
        }
        return false;
    },

};

/*===========================================================================================
  Paddle related code
  ============================================================================================*/
const paddle = {
    ...rectangle,  // assign common
    ...game.paddle.init, // assign startup
    x: (canvas.width / 2 - game.paddle.init.w / 2) | 0,  // | 0 floors the result (same as Math.floor)
    y: canvas.height - game.paddle.fromBottom,
    hitBall : true,
    leftEdge : 0,
    rightedge : canvas.width -  game.paddle.init.w,
    reset() {
        this.x =  (canvas.width / 2 - game.paddle.init.w / 2) | 0;  // | 0 floors the result (same as Math.floor)
        this.y = canvas.height - game.paddle.fromBottom;
    },
    update() {
        if (game.autoPlay) {
            keys.ArrowRight = false;
            keys.ArrowLeft = false;
            if (Math.random() < game.auto.follow) {
                var x = ball.x + ((Math.random()- 0.5) * this.w * 2);
                if (ball.x > this.x + this.w * (3/4)) { keys.ArrowRight = true }
                if (ball.x < this.x + this.w * (1/4)) { keys.ArrowLeft = true }
            }
        }
        if (keys.ArrowRight) { this.x += game.paddle.speed }
        if (keys.ArrowLeft) { this.x -= game.paddle.speed }
        this.x = this.x < this.leftEdge ? this.leftEdge : this.x;
        this.x = this.x >= this.rightEdge ? this.rightEdge : this.x;
    },
    testBall(ball) {
        if (doRectsOverlap(this, ball)) {
            // we now know that the ball must be hitting the paddle.
            var cx = (ball.x + ball.w / 2); // get ball x center
            // check for side hits. If so ball goes away from edge
            if (cx < this.x) { // hits paddle left side
                ball.y = this.y - ((ball.y + ball.h) - this.y) - ball.h;
                ball.x = this.x - ball.w;
                ball.dy = -Math.abs(ball.dy); // Must be negative
                ball.dx = -Math.abs(ball.dx); // Must be negative
                this.hitBall = true;

            } else if( cx > this.x + this.w) { // hits paddle right side
                ball.y = this.y - ((ball.y + ball.h) - this.y) - ball.h;
                ball.x = this.x + this.w;
                ball.dy = -Math.abs(ball.dy); // Must be negative
                ball.dx = Math.abs(ball.dx); // Must be positive
                this.hitBall = true;

            } else { // must be hits bat top or have run over the ball too lat
                if (ball.y > this.y + this.h / 2) { // if ball is more than halfway through the bat too lat to rescue so let it continue on
                    return;
                }
                ball.y = this.y - ((ball.y + ball.h) - this.y) - ball.h;
                ball.dy = -Math.abs(ball.dy); // Must be negative
                this.hitBall = true;
            }
        }

    },
}
<!-- the id is used to reference the element canvas -->
<canvas id="canvas" width="540" height="400"></canvas>


For the first function you can address the OS to find out for you:

unsigned long long fsizeof_full(FILE *fp) {
    struct stat size;
    fstat(fileno(fp), &size);
    return size.st_size;
}

You'll need to include the following headers for it to work.

#include <sys/types.h>
#include <sys/stat.h>

Or you can simply seek to the end of the file (with fseek(fp, 0, SEEK_END)) and use ftell

Besides that files nowadays can easily exceed 4 gigabytes which will overflow the int, both posix and windows have (differently named) variants on ftell that returns a 64 bit number.


On case-preserving but case-insensitive filesystems, renaming like that might not work, as the source and destination paths are the "same".  You may need to rename to an intermediate filename first, using mktemp.


There are a ton of good template rendering libraries out there, but I'd leave it to you to figure out if they are better suited to your needs than hand rolled code.

Assuming you still want to write this yourself, I'd look for ways to make the code more completely data driven and also to make it more readable.

On the data driven side, you might want save your design as an html file.  That way you can use whatever styling or graphic layout tools you want to produce the layout. You merely need to leave template placeholders where you want the data to go and apply the substitutions.  Django's templating system offers a great example of what you'd expect: vanilla html data with placeholders where the data's gonna go.

Going data driven will reduce a ton of the code here (since so much of it is just string assembly).  You can do some nice syntactic tricks to clean up things like writing html tags, for example

 tag = lambda t, c : "<%s>%s></%s>" % (t,c,t)

 tag('footer','footer goes here')
 >  footer goes here

And you you could also use a context manager for tag nesting (example here) to keep things neat

Lastly, use string.Template to allow for keyword or dictionary based replacement you can do things like

header = Template("$text</header")
header.subsitute(font='sans-serif',text='hello world')

that would make it easier to clean up the series of temp = temp.replace... lines.  Python is a great language for this sort of thing - it should be easy to cut this down by half or more with built in tools.


Maintaining state while walking a tree structure

At first step I've removed hardcoded into function input data, so it's become testable.
   ...
   walkImpl (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])

walk ()

let walk n =
    ...
    walkImpl n

walk (Children ...)

Than get rid of type which exists only for one function and replaced it with anonymous record.
    let initialState = {| oneFound = false; fourFound = false |}

Afterwards comes hardest part of refactoring: remove mutability. In order to use mutable state in functional way we have to use recursion and pass state as parameter to function which must return updated state, so signature should be State -> State instead of () -> () (curNode omitted for clarity).
      | Value n ->
            let patched =
                match n with
                | 1 -> {| state with oneFound = true |}
                | 4 -> {| state with fourFound = true |}
                | 9 ->
                    if state.oneFound && state.fourFound then
                        printfn "Found a good 9"
                    else
                        printfn "Found a bad 9"
                    state
                | _ -> state
            printfn "Node value %d" n
            patched

Now we have part of function that matches over curNode and transforms state if Value branch is evaluated. We also must transfer state when walking across different children while iterating list. List.fold is function that iterates over list while keep tracking of state changes. All list function may be implemented with fold, such a powerful abstraction.
        | Children c -> c |> List.fold walkImpl state

Now we have complete working example without mutations
type N = Value of int  | Children of N list

let walk n =
    let rec walkImpl (state : {| oneFound: bool; fourFound: bool |}) curNode = // explicit type required here
        match curNode with
        | Value n ->
            let patched =
                match n with
                | 1 -> {| state with oneFound = true |}
                | 4 -> {| state with fourFound = true |}
                | 9 ->
                    if state.oneFound && state.fourFound then
                        printfn "Found a good 9"
                    else
                        printfn "Found a bad 9"
                    state
                | _ -> state
            printfn "Node value %d" n
            patched
        | Children c ->
            c |> List.fold walkImpl state

    let initialState = {| oneFound = false; fourFound = false |}
    walkImpl initialState n
    |> ignore // don't care about state, because it's for internal use only

[<EntryPoint>]
let main argv =
    walk (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])
    0


C++ Stack implementation using std::list

C++ std::cin and std::cout are both tied together and and tied to C stdin and C stdout respectively. This causes a lot of performance problems when dealing with std::cin and std::cout.

You can help the situation by using:

std::ios_base::sync_with_stdio(false);   // Disconnect from C IO
std::cin.tie(NULL);                      // Disconnect in from out (otherwise they flush).

If you change the code to use std::fstream (rather than std::cin/std::cout) you can get even better performance.

I did some experiments and reading a line and parsing the line separately improves things even more.

 std::getline(std::cin, line);
 if (line[1] == 'O') {
     // STUFF
 }
 else {
     int  val;
     std::stringstream  linestream(&line[5]);
     linestream >> val;
     // STUFF;
 }

Also you should be using vector rather than list. It has two advantages: 1) You can allocate all the space you need in advance. 2) Spacial locality can make access faster.

Times:

 As written:  real  0m5.119s   user  0m4.751s   sys  0m0.362s
 Use vector:  real  0m4.906s   user  0m4.585s   sys  0m0.325s
 Un Tie:      real  0m4.247s   user  0m4.233s   sys  0m0.017s
 std::getline real  0m1.559s   user  0m1.546s   sys  0m0.017s
 std::fstream real  0m0.804s   user  0m0.766s   sys  0m0.022s

 C Version    real  0m0.434s   user  0m0.422s   sys  0m0.016s


Firstly:

Close your DataReaders!!!

Secondly:

You may want to consider abstracting boilerplate code like this:

  Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("CeConnectionString");
  IDataReader rdr = db.ExecuteReader(CommandType.Text, "SELECT * FROM Book");

Into some helper methods.


At a quick glance it would appear that your code is likely getting slowed down by the use of Linq as well as conversion between List<byte> and byte[]. Only profiling and determining a reasonable amount of time for this code to execute is going to tell you the real answer, but here are some things you can try:

Don't use Skip and Take. Both of these methods operate on IEnumerable, meaning Skip may iterate from 0-currentPixelStart despite the fact that the array can be accessed by index directly. It's possible that this optimization is done by these extension methods, but some quick searching seems to indicate it is not (and you don't want to rely on it's implementation sticking that way).
Don't use List<byte>. For starters, one of the benefits of using a List is that it can dynamically grow based on elements that are added. In most cases it does pretty well managing the overhead of resizing the internal collection, but if you need the absolute best performance you can just use a byte array. You can already calculate how big the resulting byte array will be, so just allocate the proper size from the start. This also means avoiding the result.ToArray() call since result will already be an array.
Make bytesPerPixel a const. This one isn't likely to gain you anything noticeable in the performance department, but other methods could make use of this value and right now it's hidden away in this method.
Don't recalculate the new row size on every height iteration (ie: move width * bytesPerPixel outside the loop since it won't change).


Injecting an object in each function in Go

Usually, when you have a lot of functions operating on the same data, it's worth considering making those functions methods on this data:

type UserDB struct {
    *gorm.DB
}

func (udb *UserDB) Create(name, username string) error {
    user := User{
        Name:     name,
        Username: username,
    }

    return udb.Create(&user).Error
}

// etc.


Check a string for any occurrences of certain character classes

I think your way of calling the methods is just fine. Readable and succinct. My problem is with the names check_funs and fun. Why are we having fun here?

Generally it's best not to use a function or an abbreviation of functions as a name. At the very least, use func as a much clearer abbreviation for function. Even though it is a somewhat relevant name here, it's not important that they're functions. What matters is what they do or what they're for. I'd cut it down to just checks and then for check in checks. Even aside from that though, make sure an abbreviation is clear and not just removing letters. If I was asked what fun was short for, function would be low down on my list. I could only follow in this instance because I knew that you were actually putting functions in the list.


Your complexity analyses look correct to me.  I would just say, in short, that this function works in O(n2) time.

Note that this is an awkward exercise to do in Python, or any language in which strings are immutable.  Since you can't perform the substitutions in place, you have to return a copy, which means that the minimum space requirement is O(n).  In that case, you might as well do either:

def urlify(in_string, in_string_length):
    return in_string[:in_string_length].replace(' ', '%20')

… or:

def urlify(in_string, in_string_length):
    return ''.join('%20' if c == ' ' else c for c in in_string[:in_string_length])

… which should also be O(n) space, O(n) time, and much simpler to implement!

That said, if we were to reinterpret the exercise to work on a buffer in place, I think that a better approach would be to make one pass to count the spaces in the input, to figure out the length of the output.  Then, copy characters to construct the result, working backwards from the end.  That algorithm should take O(n) time and O(1) space.

In summary, depending on how you interpret the exercise, the solution should either be simpler or faster than what you wrote.


Looks like there are no Americans here. 30 degrees Celsius is about 90 degrees Fahrenheit, so something must be wrong in the conversion. Indeed, (9/5) is evaluated (at compile time) as an integer division, yielding 1. Change it to (9.0/5.0).


A few things jump me here:

1. Class Names

Your class name is queer. The Java standard is to use PascalCasing for class names. You use Pascal_Snake_Case. That's kinda funny ;) Also you named your class after what it contains somewhere deep down, and not what it's responsible for. I'd instead probably name it Program. As it's nothing else, than that. I'd expect a class named  Quadratic_Equations to be an enum containing different Equations.

2. checkIfValidNumber

I like the name. It's good, it could describe what it does. I don't like the print-statement and that you have a loop in there. This is one of these "side-effects". Your function name makes me expect something different.
I expect a function applying some constraint to a number and returning true or false depending on the validity of that number to the constraint.

You also hide your whole process behind that. Also: why should a user not enter -1.0 for your quadratic equation? It makes no sense to use a number within the valid range to check for validity. instead use boolean return type in your tryParse and make use of the out-parameter.

3. Reading user input.

double a = tryParse(sc.nextLine());
  a = checkValidNumber(a);

This makes no sense. You should also move the first tryParse(sc.nextLine()); into a method.

Instead I would expect:

double a = promptUserUntilValidInput("Please enter a:");

You can move the whole reading to this method.

private double promptUserUntilValidInput(String prompt){
    boolean valid = false;
    double value = 0.0;
    while(!valid){
       System.out.println(prompt);
       //this is the c# attempt...
       valid = tryParse(sc.nextLine(), out value);

       //You would need to do something like this in java
       Double result = tryParse(sc.nextLine());
       valid = result != null;
       value = (double)result;
    }
    return value;
}

tryParse would then (in C#) return true, when parsing the number was successful. You'd just need to assign to an out parameter before returning in the method:

private boolean tryParse(String text, out double val){
     try{
        val = new Double(text);
        return true;
     }
     catch (NumberFormatException e){
        return false;
     }
}

This way you also eliminate all checks for -1.0.

But as this is java we need to make it a little more complicated. I'm here heavily relying on @Uri Agassi's answer

private Double tryParse(String text){
    try{
       Double value = new Double(text);
       return value;
    }
    catch (NumberFormatException e){
       if(text.matches("/^quit$/gi"))
           Application.Exit;
       else
         return null;
     }
}


Helper method to check if 3 numbers match some of the valid results

You could use a look up table, as follows:

var obj = { 'XXX': 2, '-XX': 3, 'X-X': 4, 'XX-': 5, '--X': 6}
var match = ""+ matches[0] + matches[1] + matches[2];

and then

if(match === 'XXX' && myBool){ return 1; } else { return obj[match]; }

This assumes that each position in your matches will be either an X or a -.


Very simple calculator with four basic operations using only if/else statements

You need to check for input validity and have a mechanism for retry. Users can enter all sorts of things
Your variable names aren't consistent. number and secondNumber. I would go with firstNumber and secondNumber in your scheme, but I would not use your scheme.
Your variable names are too verbose: secondNumberConversion. How about n1 and n2?
A simple, elegant, maintainable and extensible solution is to use a Dictionary.

Not addressing 1. here is my version:

Console.WriteLine("Welcome to the simple calculator!"
                  + " The four operators of this calculator are "
                  + "+, -, *(multiply), and /(divide)");

Console.Write("First Number: ");
Int64 n1 = Int64.Parse(Console.ReadLine());

Console.Write("Second Number: ");
Int64 n2 = Int64.Parse(Console.ReadLine());

Console.Write("Operator: ");
string operatorType = Console.ReadLine();

var operatorsFuncMap = new Dictionary<string, Func<Int64, Int64, Int64>>
{
    {"+", (a, b) => a + b},
    {"-", (a, b) => a - b},
    {"*", (a, b) => a * b},
    {"/", (a, b) => a / b},
};

Console.WriteLine(operatorsFuncMap[operatorType](n1, n2));


Let me restate the problem, because it wasn't 100% clear to me from what you've written. I personally think you've left out a bit too much code. I'll state my assumptions of what is going on, but ideally this should be clear from what is posted. Firstly, I assume EntityDatabase is a class, not a namespace. Secondly, I assume ItemDatabase is declared as something like:

EntityDatabase<Item> ItemDatabase;

Further, I assume you have some kind of inheritance hierarchy that looks something like:

class Item
{
    Item();
    virtual ~Item();
    //....
}

class Weapon : public Item
{
    //...
}

class Armor : public Item
{
    //...
}

The problem then is that ItemDatabase.find(...) (I assume it's meant to be ., not ::) will return a std::unique_ptr<Item> when you want a std::unique_ptr<Weapon> or some other derived class of Item.

This seems less a problem of unique_ptr and more the fact that you're kind of abusing polymorphism. Let's assume you didn't return a unique_ptr, just a normal Item*:

template <typename DataType>
DataType* EntityDatabase<DataType>::find(EntityId const& entityId)

The only thing that would change then is that armor_ would be declared as Armor* instead of std::unique_ptr<Armor>, so it would become:

 armor_ = static_cast<Armor*>(ItemDatabase::find(armorId));

Hence, the only things that really change are the calls to release and reset. This is not significantly less ugly than what is already there. If armour_ were declared as std::unique_ptr<Item> then you could of course do the following:

armor_ = std::move(ItemDatabase::find(armorId));

Again, this is all built on a lot of assumptions since there is quite a bit of context missing.

For fixes, I suppose the options are:

Leave it as is. It's fairly ugly, but not that much uglier than the code you'd have for raw pointers.
Fix your inheritance hierarchy. The fact that you're having to cast things back and forth suggests that perhaps polymorphism isn't the correct solution here. Does each item need to know its specific type? Is there a virtual function you can add to Item that will fix this? I don't know, there's not enough context from the code you've posted.
Finally, make a function to limit the uglyness to one spot:

template <typename T, typename U>
void recast(std::unique_ptr<T>& ptr1, std::unique_ptr<U>&& ptr2)
{
    static_assert(std::is_base_of<U, T>::value, "U is not a base type of T");
    ptr1.reset(static_cast<T*>(ptr2.release()));
}

....
auto armorId  = getValue<EntityId>(jsonInventory, "Armor");
recast(armor_, ItemDatabase::find(armorId));

This is still pretty ugly, but if used often, might be slightly less offensive.


Infix expression (with negative numbers) to postfix

The two most common approaches to evaluating simple mathematical expressions are :

Parse the expression into an Abstract Syntax Tree, and then evaluate the tree.
Process the expression using Dijkstra's Shunting-yard algorithm.


I would move the operations on the web service out to their own class:

public class AccountRepository
{
    private readonly void _webService;

    public AccountRepository()
    {
        //authentication header

        var header = new AuthenticationHeader
                              {
                                  header.UserName = "";
                                  header.Password = "";
                              }

        _webService = new WebService
                              {
                                   ws.AuthenticationHeaderValue = header;
                              }
    }

    public IEnumerable<AccountResult> SearchByEmail(string email)
    {
         return ConvertXmlToResultsList(_webService.getAccountIDbyEmail(email, "247"));
    }

    private IEnumerable<AccountResult> ConvertXmlToResultsList(XmlDocument xmlDocument)
    {
         // logic to convert xml to account results
    }

    public void UpdateAccount(/* parameters */)
    {
         _webService.Subscribe(/* parameters */);
    }

    public void CreateAccount(/* parameters */)
    {
         _webService.createAccount(/* parameters */
    }
}

Doing this gets rid of most of the housekeeping code out of the event handler.

I would also consider creating two classes: Account, and SearchResult.

Account should be obvious, it contains all the functionality and data that an account requires.  This would be instantiated in the Repository on the search, and also in the event handler when you need to create a new Account.

The SearchResult class I would use to return the results of the search.  It would contain the Account from the search, and the status of the search.  You could also put stuff like error checking, or anything else you see as being relevant.  You will also see a ResultCode variable type.  ResultCode is an enum that contains all of the possible codes returned from the search.

public enum ResultCode
{
     Error,
     UpdateAccount,
     CreateAccount,
}

public class SearchResult
{
    private readonly Account _account;
    private readonly ResultCode _code;

    public SearchResult(Account account, int resultCode)
    {
         _account = account;
         _code = DetermineCode(resultCode);
    }

    private static ResultCode DetermineCode(int resultCode)
    {
         switch(resultCode)
         {
              case 100:
                  return ResultCode.UpdateAccount;
              case 200:
                  return ResultCode.CreateAccount;
         }

         return ResultCode.Error;
    }
}

The final result of all this is an event handler that looks like:

protected void Button1_Click(object sender, EventArgs e)
{

     var results = _accountRepository.SearchByEmail(TextBox1.Text);

     foreach (var result in results)
     {
         switch (result.ResultCode)
         {
             case ResultCode.UpdateAccount:
                 result.Account.Update(/* parameters */);
                 _accountRepository.Update(result.Account);

                 Label1.Text = "account exists";
                 break;
             case ResultCode.CreateAccount:
                 var account = new Account("x", "5", email, "x", "x", "x", "01-01-1998", "1", "yes");

                 _accountRepository.Create(account);

                 Response.Redirect("/thankyou.aspx");
                 break;

         }
     }
 }

There are a few more points I'd like to make.

Calling .ToString() on a .Text property of a TextBox is counterproductive.  TextBox.Text returns a string, no need to make it a string.

In your code, I would move ResultStatus magic numbers into constants.  This will better describe what they represent.  Of course, if you take my code suggestions, no need to worry about this.

I don't know who wrote the web service, but the method names follow java naming conventions, not C#.  This is just a btw, ignore if the web service is written in Java.

Finally, there is quite a bit more clean-up to do on the code, even what I have posted, but this is a good start.  Hopefully you can pick up some tips from it.

Cheers.


Avoiding a large 'switch' call in the main loop

Function pointers

You want to use function pointers: http://www.newty.de/fpt/fpt.html

typedef void (*Command)(char const* args);  // Modify as required
                                            // But something like this
struct built_in_commands
{
    char const*   command;
    // int        commandID;   // Remove this you don't need it.
    char const*   man;
    Command       function;    // Add this: A pointer to a function
};

Then your switch becomes:

parse_command (commandline, &cmd);
if (cmd != NULL)
{    (*cmd->function)(commandline);      // Call the function associated with
}                                        // command (assuming you find it in the list)

Other Notes:

Basically, all of your function would have the same signature, and then be referred to inside of your struct instead of the number. Then you could call the function pointer from the struct and away you'd go.

        case EXIT_CMD:
            free (commandline);
            commandline = (char *)NULL;
            closelog ();
            return 0;

This appears to be the only place you free commandline. But you allocate it everytime you get a command. This means that you have a leak. There actually isn't much of a point in freeing the memory here because it will all be free as soon as the process terminates anyways.


if your aim is to:

copy the value in cell "B4" of worksheet "Sheet1"
and paste it in worksheets "Sheet2" from cell "A1" downwards in iterations cells

then simply use:

Dim iterations: iterations = 1000
Worksheets("Sheet2").range("A1").Resize(iterations).value = Worksheets("Sheet01").range("B4").value

if your aim is to:

copy the value from cell "B4" of worksheet "Sheet1" and down to iterations cells
and paste them in worksheets "Sheet2" from cell "A1" downwards in iterations cells

then simply use:

Dim iterations: iterations = 1000
Worksheets("Sheet2").range("A1").Resize(iterations).value = Worksheets("Sheet01").range("B4").Resize(iterations).value


Only 2 things:

Why do you have this? This makes your code a bit unclear and confusing. Remove this if you do not want to use it as it might make your actual code look messy.

# def reverse_num(num):
#   rev = 0
#   while(num > 0):
#     rev = (10*rev)+num%10
#     num //= 10
#   return rev

It is discouraged to use for i in range(100): in Python.


The promise just allows you to act when the asynchronous call has been completed. So all you need to do in your 'Then' is say what to do with the result when it is there. Nothing stops you from calling a nice function in there that handles the result. ;) You've got two functions in there at least: process the result of the GetUser call, and then open the Edit dialog. So split those out and things will start to look much better.


Use more functions
You have a function calculate(), but if you see it does much more than just calculate, this makes your code look unreasonably clunky. But there is a very simply solution, use more functions. What if your main-loop could look like
while True:
    number1,number2,operand = take_input()
    result = calculate(number1,number2,operand)
    print(f"Answer : {numebr1} {operand} {number2} = {result}")
    if input("Do you want to play again? (y/n): ").lower() == 'n':
        break

This makes it easier to maintain your program.
continue when there is an error
try:
    number1 = float(input("Enter the first number : "))
except ValueError:
        print("Incorrect value")
        exit()

Ask yourself, why would a program terminate if the user enters invalid input? Give him a another chance xD
Maintain consistent indentation
try:
    number2 = float(input("Enter the second number : "))
except ValueError:
            print("Incorrect value")
            exit()

Try to maintain consistent indentation, since you have used 4 spaces earlier, there is no good reason to use 8 later, it might just confuse people who read the code later.
Code logic 1
Let's consider this sample input
Enter the first number : 1
Enter the operation symbol (+,-,/,*,%) : I like python
Enter the second number : 2
Incorrect symbol

Clearly, the symbol is wrong. Why did I have to enter the second number, just to find out I made a mistake while entering the symbol? It should've told me right away that my symbol was incorrect, so I could've corrected it.
Just move the if symbol not in operands statement so it sits right next to the input.
eval
Eval in Python
This would be the biggest improvement in your program, since it converts about 10-15 lines of code, into one.

The eval() function evaluates the specified expression, if the
expression is a legal Python statement, it will be executed.

That sounds familiar, aren't we basically evaluating simple expressions?
Using eval, your calculation part would look like
result = eval(f"{number1}{operand}{number2}")

Example, number1 = 5,number2 = 10, operand = '+'
This is what is basically happening
result = eval("5+10")

Final
Here is the code with the improvements
def take_input():
    err_msg = "Invalid input"
    operands = ['+','-','*','/','%']
    try:
        num1 = float(input("Enter number 1: "))
    except Exception:
        print(err_msg)
        return take_input()
    try:
        num2 = float(input("Enter number 2: "))
    except Exception:
        print(err_msg)
        return take_input()

    print("Operands: " + ', '.join(x for x in operands))
    try:
        operand = input("Enter operand: ")
    except Exception:
        print(err_msg)
        return take_input()

    if operand not in operands:
        print(err_msg)
        return take_input()

    return num1,num2,operand

def calculate(num1,num2,operand):
    return eval(f"{num1}{operand}{num2}")

def mainloop():
    while True:
        num1,num2,operand = take_input()
        result = calculate(num1,num2,operand)
        print(f"Answer: {result}")
        if input("Do you want to play again? (y/n): ").lower() == 'n':
            break

mainloop()


Abstracting async hooks out from components

The general approach looks just fine. The logic behind data retrieval isn't entirely related to the rendering of components, so putting it into a custom hook instead makes good sense, especially if other components might need the data as well.
A few suggestions:

React recommends that the function names of custom hooks start with use, to clearly indicate that it's a hook and that other hooks (like useEffect) can be used inside it.
If other components might need to use the summaries as well, or if this component may get completely unmounted and then re-mounted again, consider whether you can use the summaries that were retrieved previously instead of fetching them again. (Or maybe you do want to fetch them again regardless - think about what you want.)
There doesn't really appear to be error handling, other than setSummaries([]). It would be more user friendly to indicate to the user if there's an error (and, at least in the development environment, to log the error).
Having both a ContentListContainer and a ContentList seems odd, since ContentListContainer is empty except for the custom hook call. If you aren't planning to add more stuff to the container, consider removing ContentListContainer entirely and putting the hook call into ContentList instead.


How to create a validation loop for multiple inputs

Your revised code in on the right track. You can simplify the function a fair bit:
def get_integer_input(prompt):
    while True:
        try:
            # Just return directly. No need for an invalid_input flag.
            return int(input(prompt))
        except ValueError:
            print('Invalid input')

# Where you see repetition in your code, consider using a data structure to
# address it. There are libraries that will give you the ordinals. Personally,
# I would just rephrase the input() prompt so that the ordinals are not needed.
ORDINALS = ('1st', '2nd', '3rd')

# Get the integers.
fmt = 'Enter {} number: '
a, b, c = [get_integer_input(fmt.format(o)) for o in ORDINALS]
print(a + b + c)

# Or if you care only about the total, just get it directly.
tot = sum(get_integer_input(fmt.format(o)) for o in ORDINALS)
print(tot)


Convert "String" sqrt(#) into numerical value

I found the use of Sqrt[...] to be cumbersome, why have the case in that format, and why have the [] style braces?

I would normally not recommend this, but a simple solution, if you trust, or can sanitize your inputs, is to just use the eval function.

for $_ ( @rootList ){
    $_ =~ s/Sqrt\[(.+)\]/sqrt($1)/;
    $_ = eval($_);
    $@ and die $@;
}

That does it..... all of it. Convert Sqrt[...] to sqrt(...), and eval the result.


Return from the parent process code or common code

As for all these functions:  Take a look at the man page.  It states
that execvp (respectively execve) will return on error with return
value -1 and with errno set.

Since you are already handling such errors with fork you might as
well do it here and either exit(1), or fall through to the end.


Fetching of JSON data through an API with AngularJS

Your loop is only executed after the data has been fetched, so improving it will not have any effect on how long it takes for the data to be fetched.

JavaScript doesn't have block scope but does have function scope, so variables declared within a function are hoisted to the top of that function. So the fact that you declare your variables inside the for loop has no effect on the speed of your loop.

function foo () {
    var fruits = ["apple", "banana", "cherry"];

    for (var i = 0; i < fruits.length; i++) {
        var fruit = fruits[i];
        console.log(fruit);
    }
}

is the same as

function foo() {
    var fruits = ["apple", "banana", "cherry"];
    var fruit;

    for (var i = 0; i < fruits.length; i++) {
        fruit = fruits[i];
        console.log(fruit);
    }
}

I think your problem is that you are fetching large amounts of data. Displaying 30000 results in one go is not good practice. Does the api you are calling support paging in any way? Can you specify an offset (or something similar) in the request? For example, can you do

$http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25&offset=0") // get results 1-25

$http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25&offset=25") // get results 25-50

$http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25&offset=60") // get results 60-85

If you can't restrict the number of results returned that way, you can at least make sure that you only display a manageable number of results in one go. I.e don't add all the results to the DOM at once, only add them when the user clicks "Next" (if you add some paging controls), or scrolls down far enough (if you implement an "infinite scrolling" solution).

Having said the above, there a couple of small improvements you can make to your loop i.e. cache response.tracks.length and response.tracks[i].

function fetch(){
    $http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25000").success(function(response){
        $scope.songs = [];
        $scope.details = response;

        for(var i=0, numOfTracks = response.tracks.length; i < numOfTracks; i++){
          var track = response.tracks[i];
          var labelName = track.label_fk;
          var labelLow = labelName.toLowerCase();
          var resultUrl = "http://APIcall.com/stream_music_file.php?lbl="+labelLow+"&alb="+track.album_num+"&trk="+track.track_num+"";
          var imgUrl = "http://www.APIcall.com/online/music/display_album_cover/"+labelLow+"/"+track.album_num+"";

          var allTracks = {
              id: track.track_id,
              lbl_fk: track.label_fk,
              alb_num: track.album_num,
              track_num: track.track_num,
              track_descr: track.description,
              track_dur: track.duration,
              title: track.primary_title,
              artist: track.composers,
              img: imgUrl,
              url: resultUrl
          };

          $scope.songs.push(allTracks);
      }
  });
}

Seeing as I don't think the loop is the bottleneck, I would be tempted to use map which arguably results in more readable code.

    var trackToSong = function (track) {var labelName = track.label_fk;
          var labelLow = labelName.toLowerCase();
          var resultUrl = "http://APIcall.com/stream_music_file.php?lbl="+labelLow+"&alb="+track.album_num+"&trk="+track.track_num+"";
          var imgUrl = "http://www.APIcall.com/online/music/display_album_cover/"+labelLow+"/"+track.album_num+"";

          return {
              id: track.track_id,
              lbl_fk: track.label_fk,
              alb_num: track.album_num,
              track_num: track.track_num,
              track_descr: track.description,
              track_dur: track.duration,
              title: track.primary_title,
              artist: track.composers,
              img: imgUrl,
              url: resultUrl
          };
    }

    function fetch(){
      $http.get("http://www.APIcall.com/phrase=" + $scope.search + "&perpage=25000").success(function(response){
            $scope.details = response;
            $scope.songs = response.tracks.map(trackToSong);
          }
      });
    }


Indeterminate-length big-endian to little-endian conversion in Python

To calculate number of bytes, better use:

numbytes = math.ceil(value.bit_length() / 8)

And then you can just:

def be_to_le(value: int) -> int:
    numbytes = math.ceil(value.bit_length() / 8)
    return int.from_bytes(value.to_bytes(numbytes, byteorder="little"), byteorder="big")


This looks very clean to me. Except perhaps:

imgvw - that's disemvoweling. nd t's bd. Not to mention it's breaking your camelCasing convention for locals.
drawit - while the name says what the function does, I would avoid DoThatThing names and perhaps go for a more sober render method name, if not just draw.

Lastly, I don't know Java well enough to know if it's convention, but I wouldn't use that m prefix.


Visualization showing overlays of points

Overall you have a pretty nice code for someone who is "fairly new to D3", good on you.

The proposed changes here are few:

The big circle

You have just one big circle (the blue one). Therefore, you don't need that mix of d3.range and map for its datum. Also, you don't need an enter selection, since that's just one circle.

So, you can do:

var circleDatum = {
    x: width / 2,
    y: height / 2
};

And:

var circle = svg
    .append("circle")
    .datum(circleDatum)
    //etc...

Mind the fact that you're using circle as the name for two different things!

Don't re-select the same thing again...

Inside the dragged function you have this:

var inside = d3.selectAll("circle.point").style("fill", function(d){
    //etc...

Which basically re-selects all .point circles again. I wrote re-select because you already have a selection for them: points.

Therefore, just do:

points.style("fill", function(d){

Use selectAll(null) in your enter selections

If you don't plan to update the chart, that is, if you don't want to have an update and exit selections, you don't need to select anything in your enter selections.

That being said, you can do:

var points = svg.selectAll(null)
    //etc...

By using selectAll(null) you'll have a cleaner and faster code (not noticeable since you have soo few elements here).

For reading more about selectAll(null) have a look my explanation here: Selecting null: what is the reason behind 'selectAll(null)' in D3.js?.

Minor changes

Instead of putting all the d3.drag inside the call, you can do:

var drag = d3.drag()

And then:

.call(drag)

If you don't use the second argument (the index), don't write the parameter. So, instead of:

function dragged(d, i) {

Just do:

function dragged(d) {

If you like ternary operators, the whole if can be just:

return dis <= Math.abs(unitRadius - radius) ? "green" : "red";

You can use Math.hypot for the hypothenuse (note: this doesn't work on IE)

var dis = Math.hypot(x, y);

Also, if you don't mind old IE versions, you can use let and const (accordingly) instead of var.
Sometimes users don't know that they can interact with the visualisation, and a lot of people don't read the instructions/description. So, adding a visual clue may be useful. For instance, changing the cursor when you hover over the big circle helps to indicate that it is draggable:

.style("cursor", "pointer")

Demo

Here is your code with those changes:

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height"),
  radius = 8,
  unitRadius = 64,
  drag = d3.drag();

var points = d3.range(10).map(function() {
  return {
    x: Math.round(Math.random() * (width - radius * 2) + radius),
    y: Math.round(Math.random() * (height - radius * 2) + radius)
  };
});

var circleDatum = {
  x: width / 2,
  y: height / 2
};

var points = svg.selectAll(null)
  .data(points)
  .enter()
  .append("circle")
  .attr("class", "point")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", radius)
  .style("fill", "red");

var circle = svg.append("circle")
  .datum(circleDatum)
  .attr("class", "overlay")
  .attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("r", unitRadius)
  .style("fill", "blue")
  .style("cursor", "pointer")
  .call(drag.on("start", dragstarted)
    .on("drag", dragged)
    .on("end", dragended)
  );

function dragstarted(d) {
  d3.select(this)
    .raise()
    .classed("active", true);
}

function dragged(d) {
  d3.select(this)
    .attr("cx", (d.x = d3.event.x))
    .attr("cy", (d.y = d3.event.y));

  points.style("fill", function(p) {
    var x = d.x - p.x;
    var y = d.y - p.y;
    var dis = Math.hypot(x, y);
    return dis <= Math.abs(unitRadius - radius) ? "green" : "red";
  });
}

function dragended(d) {
  d3.select(this).classed("active", false);
}
.overlay {
  fill-opacity: 0.1;
}
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<svg width="960" height="500"></svg>


if you already use jQuery for something else in your page, it doesn't bother if you use jQuery or not.

if it's the only JQuery in your page, I suggest to change it to "vanilla" javascript, because you won't need to load the jquery library.

Some may say that often the jquery library is already in the browser cache, but still there's no need to add a library/framework for just one call.


You should first check if the response is null. If not, then check for a success or error response.
You can use a try-catch block to check if it is valid JSON:

Try{
    JSON.parse(response);
    catch(Exception){
    console.log("Not valid json");
    handle();
}

If what you are expecting from the server to be in a constant format you could use the callback code again and again in different functions.


Parsing length of work experience using Composite design pattern

You wrote this:

    Pattern p = Pattern.compile("\\d+miesi[e|ę]cy|\\d+ miesi[e|ę]cy");

but it would be more natural to express it without alternation:

    Pattern p = Pattern.compile("\\d+\\s*miesi[e|ę]cy");

I wonder if you maybe wanted to throw in a CASE_INSENSITIVE | UNICODE_CASE flag.

public interface ExperiencePattern {

Many projects would choose to spell this IExperiencePattern.

DRY - don't repeat yourself. It seems odd that you have a pair of copy-n-pasted identical classes with different Pattern constants, rather than one class that accepts a Pattern parameter.

        tmp = tmp.replaceAll("\\D", "");

Thank you for teaching me about the "non-digit" pattern. But the more natural way to express your intent would be to delete this, and put a capture group in your regex:

    Pattern p = Pattern.compile("(\\d+)\\s*miesi[e|ę]cy");

Then Integer.parseInt(m.group(1)) gives you exactly what you want.

        if (x < 40) {
            result = x * 12;

Ok, I guess in a straight refactor you would need to pass in two parameters, a Pattern and also maxAcceptableValue. But it's probably better to stick with a single parameter and let the caller do range checking.

public interface Algorithm <T> {

    public T calc(String textToLower);

Both of those identifiers are hopelessly vague. Give the Gentle Reader a clue, please. Also, adding some /** javadoc */ would help.

public ExperienceAlg0(List<ExperiencePattern> list){
    listPatterns = list;
}

It is customary in a ctor to explicitly mention "this": this.listPatterns = list;

    for(ExperiencePattern ep : listPatterns) {
        result.add(ep.getPattern(text));
    }

This is perfectly lovely. But generalizing to exactly 2 cases is maybe on the small side. Rather than this loop, I encourage you to hoist the range check test up to this location, which will feature a pair of nearly identical calls using each of your patterns.

    Collections.sort(result, new DescendingComparator());
    return result.get(0);

That's cool. I like it. Very clean way to discard chaff.

You asked if the design is OK according to OOP. Well, that would be easier to evaluate if you added one-sentence javadocs at top of each class, explaining the single responsibility of that class, especially for any interface classes. That would e.g. help a reader pin down which layer the range-checking belongs in.


Unusual undo redo
Your undo and redo operations have a strange behavior in that they are them selves undo-able. Generally undo and redo operations are themselves not undo-able.
Bug?
Unknown commands will throw the error TypeError: this.operations[operation] is not a function
SEMICOLONS!
I think I mentioned semicolons last time I reviewed your code. If you do not wish to use them you should be familiar with ASI
Identifiers
Try to avoid string identifiers as they are memory hungry ad can be much slower depending on the number and similarity of identifiers.
One method of creating unique identifiers is via an enumeration object.
Example
const operators = {
    append: 0,
    undo: 1,
    redo: 2,
    backspace: 3,
}

The rewrite uses a function Enum that returns an object containing named integer Identifiers.
Encapsulation
Protect the state of the object. All properties of an object exposed to other code can not be trusted. Without a trusted state you can not guarantee that your code will run as expected.
A well designed encapsulated object (once tested) can NOT fail.
JavaScript has an excellent OO encapsulation model.

Closure is used to encapsulate state within the Object that do not require additional language tokens to access (eg this)
Object functions

Object.freeze will set all properties to writable: false, and the object to immutable.
Object.seal properties remain writable but the object is set to immutable.

Using closure to hold the objects state, you then create an interface to provide an interface to the state. The interface is just an object (frozen or sealed) that uses getters, setters, and functions to access state and control behavior
Be efficient
Always write code to be as efficient as possible.
Yes this is a balance between productivity and code efficiency but with a constant eye on efficiency  you become more adept at writing efficient code
Inefficient undo buffer
Your undo is expensive as it stores the complete text for every action that can be undone. You need only store each operation and associated data in the undo buffer.
This will make your code more complex but for large documents it will run much quicker and use far less memory. Clients don't see or care how things are done, they only care about what it does, if that include slow response and power hungry it is never a plus.
Rewrite
The rewrite adds a little functionality to help demonstrate some of the points above regarding the interface getters and setters.
Usage remains the same
Behavior is a little different

Undo and redo are not undo-able commands

It uses an named integer values to identify operations. Which is a static property of TextProcessor.operators and internally accessed via operators

The function TextProcessor.process ensures input is an array, filters out non arrays to avoid errors, and checks for valid operation before attempting to call the operation, again to avoid throwing errors.

For every undo-able operation there is an equivalent redo operation. This means that only the operation and operation data need be stored in the undo buffer.

All objects accessible by unrelated code are frozen to ensure that state can be trusted and maintained.

Individual operations are not available via the interface but would be easy to add if needed.

const Enum = (baseId, ...names) => Object.freeze(
    names.reduce((obj, name, i) => (obj[name] = i + baseId | 0, obj), {})
);
const TextProcessor = (() => {
    function TextProcessor() {
        const undos = [];
        const undoOperations = {
            [operators.APPEND](txt) { text = text.slice(0, -txt.length) },
            [operators.BACKSPACE](txt) { text += txt },
            [operators.CLEAR](txt) { text = txt },
        };
        const  undoable = (operation, ...data) => {
            undos.length = undoPos++;
            undos.push({operation, data});
        }
        const redoUndoable = () => undoPos++;
        const operations = {
            [operators.APPEND](txt) {
                txt = "" + txt;      // forces txt to be a string
                addUndoable(operators.APPEND, txt);
                text += txt;
            },
            [operators.BACKSPACE]() {
                addUndoable(operators.BACKSPACE, text[text.length - 1]);
                text = text.slice(0, -1);
            },
            [operators.CLEAR]() {
                addUndoable(operators.CLEAR, text);
                text = "";
            },
            [operators.UNDO]() {
                if (undoPos) {
                    const op = undos[--undoPos];
                    undoOperations[op.operation](...op.data);
                }
            },
            [operators.REDO]() {
                if (undoPos < undos.length) {
                    const op = undos[undoPos];
                    addUndoable = redoUndoable;
                    operations[op.operation](...op.data);
                    addUndoable = undoable;
                }
            }
        };
        var undoPos = 0, text = "", addUndoable = undoable;
        return Object.freeze({
            get text() { return text },
            set text(txt) {
                operations[operators.CLEAR]();
                operations[operators.APPEND](txt);
            },
            process(input) {
                if (Array.isArray(input)) {
                    input = input.filter(operation => Array.isArray(operation));
                    for (const [opName, data] of input) {
                        operations[operators[opName]]?.(data);
                    }
                }
            }
        });
    }
    const operators = Enum(1, "APPEND", "BACKSPACE", "UNDO", "REDO", "CLEAR");
    return Object.freeze(Object.assign(
        TextProcessor,
        operators
    ));
})();

const textProcessor = TextProcessor()
textProcessor.process([
  ['APPEND', 'Hey'],
  ['APPEND', ' there'],
  ['APPEND', '!'],
  ['BACKSPACE'], ['BACKSPACE'], ['BACKSPACE'], ['BACKSPACE'],
  ['APPEND', '$'],
  ['UNDO'], ['REDO'],
  ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO']
  ['REDO'], ['REDO'], ['REDO'], ['REDO'], ['REDO'], ['REDO'],
  ['UNDO'],
  ['APPEND', 'e'],
  ['APPEND', 'r'],
  ['APPEND', 'e'],
  ['APPEND', '$'], ['UNDO'],
  ['APPEND', '!'],
  ['CLEAR'],
  ['UNDO'],
]);

console.log("'" + textProcessor.text + "'" + " === 'Hey there!' " + (textProcessor.text === "Hey there!"));