Simplify double AJAX request for jQueryUI's autocomplete widget

Regarding to readability, the code structure is actually great and it's easy to read the code.

The only thing, regarding to readability, is that you have mixed quotes everywhere.

But still, your code has things you can change:

Javascript:

You are using the autocomplete plugin with a request to the server.

You can skip that whole trouble and simply use the source option.
This will save you a lot of time.

If you don't like it (for whatever reason it is), you should do something on the error event on your $.post call.
Displaying an error message is better than doing nothing.
Ultimately, you can implement a caching system, but this is arguable.

If you still don't want to use the source option, you should remove the var $egysegar.
That var is completely useless.
This line:

$($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text($egysegar);

Can be safely replaced by this one:

$($elem).parent().parent('.ujtermek_wrapper').find('td.egysegar').text(data.egysegar);

Of even shorter:

$($elem).parents('.ujtermek_wrapper').find('td.egysegar').text(data.egysegar);

PHP:

On your php file, you have this line:

if(isset($_POST["term"]) && !empty($_POST["term"])) {

According to the php documentation for the function empty():

  Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
  The following things are considered to be empty:
  - "" (an empty string)
  - 0 (0 as an integer)
  - 0.0 (0 as a float)
  - "0" (0 as a string)
  - NULL
  - FALSE
  - array() (an empty array)
  - $var; (a variable declared, but without a value)

This is a terrible idea!
If the search term is "0", it won't provide any results.
Replace your code with this:

if(isset($_POST["term"]) && $_POST["term"] !== "") {

This will solve the issue by verifying if the term isn't an empty string by using a strict comparison.

Right below, you have this:

require_once "../includes/constants.php";
require '../includes/class.db.php';

You mixed the quotes and you used 2 different instructions to include files.
I assume you can safely use require here, unless you include it on the file class.bd.php.
This will reduce the overhead of checking if the file was included before or not.
More yet (as a sidenote): you can use include instead! (assuming the file will always exist).

On the next line, you have this block:

$searchTerm = trim($_POST["term"]);

$db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

$bind = array(
    ":term" => "%$searchTerm%"
);

$results = $db->select(TERMEKEK_TABLE, "nev LIKE :term", $bind, "nev, egysegar");

echo json_encode($results);

The code itself is fine, but why you store trim($_POST["term"]) in a variable to use it inside a string?
This makes readability a bit hard and it is a terrible idea on this code.
Remove that variable and concatenate it with the "%" string.
This is the result:

$bind = array(
    ":term" => "%".trim($_POST["term"])."%"
);

This is the right way to do it.

Edit (2014/12/01):

Since you are using the LIKE clause, you should escape the % character or it will return funky results.
You should escape it.
A great suggestion can be found here: How to escape literal percent sign when NO_BACKSLASH_ESCAPES option is enabled?
Using that brilliant idea, your code would be like this:

$bind = array(
    ":term" => "%".str_replace('%','|%',trim($_POST["term"]))."%"
);

$results = $db->select(TERMEKEK_TABLE, "nev LIKE :term escape '|' ", $bind, "nev, egysegar");

Or similar.

Outside the scope of the review, you can replace the whole block with only 2 lines:

$db = new db(CONNECTION_STRING, DATABASE_USERNAME, DATABASE_PASSWORD);

echo json_encode( $db->select(TERMEKEK_TABLE, "nev LIKE :term escape '|' ", array( ":term" => "%".str_replace('%','|%',trim($_POST["term"]))."%" ) , "nev, egysegar") );


Login and create username and password program

I have some suggestions, some regarding the code and some regarding the logic of it. Generally this is a nice code.
Let's begin, logical suggestions:

First of all, the code does not run. SyntaxError: name 'newUser' is used prior to global declaration. You should put the global keyword before declaring the variables.
Use the __main__ function. Usually when writing a good python code you do not write logic outside of functions. This will make your code more readable. You can than put the logic in a while True loop and keep accept users forever and not just twice.

Coding suggestions:

Magic numbers. The number of time you can accept a wrong password is 3, make it a constant: NUMBER_OF_ERROR = 3.
You do not need to declare x outside of the login function.
Instead of x += 5 just use break, it makes much more sense.
Do not call the login function at the end of login. It creates unnecessary recursion.

That's it.
Good luck and have fun


When you'll look at this code a number of years months (weeks?) from now, the first thing that will jump at you and make you want to rip your eyes off, is the indentation.

The idea is that code blocks add a level. What's a code block you'll ask? A Sub or a Function defines a scope - as such, the only thing you should see at the same indentation level as the words Public Sub, is the words End Sub - and labels, because the VBE wants them unindented.

Declaring a variable does not constitute a code block. These lines should all be at the same indentation level:

Dim SourceRange As Range, DestRange As Range
Dim DestSheet As Worksheet, SourceSheet As Worksheet
Dim LastRowDestSheet As Long, i As Long, LastRowSourceSheet As Long
    Set DestSheet = ThisWorkbook.Worksheets("Accepted Change Requests")
    Set SourceSheet = ThisWorkbook.Worksheets("All Change Requests")

        LastRowDestSheet = DestSheet.Cells(DestSheet.Rows.Count, "A").End(xlUp).Row
        LastRowSourceSheet = SourceSheet.Cells(SourceSheet.Rows.Count, "E").End(xlUp).Row

            For i = 2 To LastRowSourceSheet

Like this:

Dim SourceRange As Range, DestRange As Range
Dim DestSheet As Worksheet, SourceSheet As Worksheet
Dim LastRowDestSheet As Long, i As Long, LastRowSourceSheet As Long
Set DestSheet = ThisWorkbook.Worksheets("Accepted Change Requests")
Set SourceSheet = ThisWorkbook.Worksheets("All Change Requests")

LastRowDestSheet = DestSheet.Cells(DestSheet.Rows.Count, "A").End(xlUp).Row
LastRowSourceSheet = SourceSheet.Cells(SourceSheet.Rows.Count, "E").End(xlUp).Row

For i = 2 To LastRowSourceSheet

I would avoid declaring multiple variables in a single instruction. You've done it right though - every variable has a type and that's good (common beginner mistake is to only specify a type for the last one, making all but the last one Variant variables)... but things are simply easier to read (and to maintain!) when each declaration has its Dim statement.

A With block however, is a block, and as such warrants an indentation level. Same with For and If blocks, which you all got right.

The parentheses are not needed here, and can play bad tricks on you if you make it a habit:

MsgBox ("There was an error adding this Change Request")

Method calls in VBA don't require parentheses - these brackets actually force an expression evaluation, that's all they're doing. And in other contexts this forced evaluation can introduce hard-to-find bugs.

Good error messages have proper punctuation, but the problem isn't much with the message, than with how the error is handled:

Resume Next

This takes execution back to the line after the one that blew up. Normally you resume next when you know you've recovered from the error and that everything is stable enough to just resume with the next instruction - it's not the case here. This handler is basically On Error Resume Next with a message box between the error and the resume next. Bad things can happen - if an error occurred and you don't know what caused it, nor whether you can actually recover from it, it's usually best to simply exit the procedure, aborting the process.

Note that in VBA the colon (:) is an instructions separator (except when it's identifying a label), used for stuffing multiple instructions on the same line. Hence, it's completely superfluous here:

On Error GoTo errorHandler:

Because the "next instruction" is a line terminator, a non-instruction.

I merely scratched the surface here, there's a lot to say about this code - I'll leave some for other reviewers :)


First of all you must understand that validation and sanitization are not synonyms. But completely different processes that have very little in common.
Whereas sanitization indeed does prevent the malicious use, validation is merely for your and/or your customer's convenience. A properly sanitized data do not require any validation to be safe.
Sanitization
Speaking of the former, there is not so much to sanitize in this form. At least from the list you was able to gather:

there is no HTML output, so it makes no sense convert html characters.
empty spaces do no harm whatsoever
stripslashes always has been useless in the business of preventing any malicious use, while nowadays it's absolutely useless at all

I don't know what harm could be done to the code like this - may be it's better to ask on the security-related site of the network. May be it would be useful to check the input data length and to validate the email address.
Validation
Is another matter. You could validate the email address, so it won't allow a bogus email. Same goes for the date - whether it is correct and could be understood.
But, as it was said before, it's entirely up to you, whether to bother with validation or not.


It seems to me more logical that the declaration of all services is done in your "main" rather than in "core". It is better to separate as much as possible the dependencies between modules of the same level.

In addition, the module "core" and "shared" are quite close in philosophy, they allow to share basic code in your project. I think that in the future it will be confusing.

Maybe renamed core to "home" or just a part of your application and just use "shared" to share modules.

Then, personally I will pass the definition of routes in the module file.


Finding the number of times a query string appears in a vector of strings c++

You start by sorting both the queries and the strings to search, but you don't seem to make a whole lot of use of the fact that afterwards they're sorted. Fortunately, parts of the standard library make it fairly easy to take better advantage of that as well.
It looks like you've preceded your code by something like using namespace std;. This is generally considered a poor idea, and should usually be avoided.
When you just want to know if one string equals another, it's often simpler and more readable to use something like if (a == b) than if (!a.compare(b)).
The single biggest thing I see here is that the standard library already provides most of the functionality you want, so using it can make the code quite a bit simpler.

I'd probably write the code something on this general order:

[edit: modified code to optimize for unique queries, as OP stated in comment.]

std::unordered_map<std::string, int> matchingStrings(std::vector<std::string> &strings,
                                                     std::vector<std::string> &queries)
{
    std::sort(strings.begin(), strings.end());
    std::sort(queries.begin(), queries.end());

    std::unordered_map<std::string, int> counts;

    auto start = strings.begin();

    for (auto const &q : queries) {
        auto p = std::equal_range(start, strings.end(), q);
        counts[q] = p.second - p.first;
        start = p.second;
    }
    return counts;
}

std::equal_range looks for a range (in a sorted sequence) of objects that are equal to one that's specified. It can use a binary search to find the beginning and end of the range, so if the number of strings being searched is large, it can potentially save quite a bit of time. It returns an std::pair--the first item is an iterator to the beginning of the range, and the second an iterator to the beginning of the range. So, we use that to find all the strings that match a given query, and count them by subtracting the two.


What is slow is to create seq(q_start,number,1). Take the example where  number is 298,716,239: you are asking R to create a vector of nearly 300 million integers. It chokes. Instead of looping over sequences created in memory, it is easier to just keep the current value, increment and limit in memory. See for example:

TM <- function (n) {

   n <- as.integer(n)
   r <- sqrt(n)
   p <- as.integer(floor(r))
   q <- as.integer(ceiling(r))

   while (p >= 1L & q <= n) {
      if (p * q == n) return(c(p, q))
      if (p * q > n) { p <- p - 1L } else { q <- q + 1L }
   }
   stop("hmm... we should not be here...")
}

TM(1900)
TM(298716239)

Now that's a start... If you try with a large prime, e.g. 298716247, it will take a very long time to converge towards 1 * 298716247 though. So you will have to get more creative to make it converge faster. At least, you should be fixed about why your original code was so slow.

Edit: here is an idea I got for making it converge faster where you update both p and q at each iteration. I hope the math checks out and I did not leave a corner case:

TM2 <- function (n){

   n <- as.integer(n) # everything is faster with integers
   r <- sqrt(n)
   p <- as.integer(floor(r))
   q <- as.integer(ceiling(r))
   while (p >= 1L & q <= n) {
      if (p * q == n) return(c(p, q))
      if (p*q > n) {
         p <- p - 1L
         q <- as.integer(floor(n / p))
      } else {
         q <- q + 1L
         p <- as.integer(ceiling(n / q))
      }
   }
   stop("hmm...")
}

TM2(1900)
TM2(298716239)
TM2(298716247)


Implementation of a shift operation for Set in JavaScript that emulates the one for arrays

Another way to do it is via the iterator function.

function shifySet(set) {
    const first = set[Symbol.iterator]().next().value;
    set.delete(first);
    return first;
}

I was going to check if there was an item, but it seams pointless. Works the same as your function shifts the first entry, returning it, or undefined if not found.

I would make a slight change to your version

function shiftSet(set) {
    for (const res of set) {
        set.delete(res);
        return res
    }
}


Can't add a comment, so I'm going to try to answer the question.

If I'm understanding the question correctly, you don't want the responsibility of validation to be in the Upsert method. If that is the case then you can invert the control to another class by passing a 'Validator'. Which I think is what you are alluding to in the second part of the question but I would recommend the following implementation.

In a nutshell what you do is create a class which is responsible for validation which is injected into the main class. This makes this testable as well.

private readonly IValidator _validator;

public Constructor(IValidator validator)
{
  _validator = validator;
}

public void Upsert(List<Object> items)
{
    var existings = _db.Get().Where().ToList();
    foreach (var item in items)
    {
        var existing = existings.FirstOrDefault(x => x.Id == item.SomeId);
        if (existing == null)
        {
            _validator.ValidateEntity(existing);
        }
        else
        {
            // update existing
        }
    }
    _db.Save();
}

Example Implementation of the IValidator interface would be

public Validator : IValidator
{
  void ValidateEntity(object existing)
  {
    if (item.Property != 645)
    {
      throw new EntityNotFoundException();
    }
  }
}

You could take this further and use generics and allow the Validator class to decide what the object is and what needs validating.


Generating all possible permutations of the string

There are quite a few ways this code can be improved:

All class names should start with a capital, and be in CamelCase. Specifically, the class permutations should be Permutations. The way it doesn't look like a variable, as in here:

permutations p = new permutations();

performPermutations method

Why does it declare a return type of ArrayList<String>? Is there anything special about the implementation of the list? It should just be List<String>.
You have an unnecessary if-else structure, since each if statement returns a value. You can remove all of the elses.
In the first if statement, you return null. This is a bad idea in many cases. An empty list would be more favorable, just in case any calling code wants to operate on it immediately afterwards. (Notice that your main method would fail with a NullPointerException if the passed in list was empty).
You can combine the first and second if statements into one. This would be your "base" case:

if (s == null || s.isEmpty() { return arrayList; }

Never compare a list length to 0, use isEmpty() instead. Also, s is a poor name for a method parameter. Try to be creative and descriptive. Finally, there's no need to add an empty string if the list is empty.
There's a lot of existing posts on string permutations you may find interesting. Seeing a recursive call embedded in two for loops is probably unnecessarily complex.

How this method could look (but can still be improved):

public List<String> performPermutations(final String s){

    final List<String> result = new ArrayList<String>();

    if (s == null) {
        return result;
    }

    for (int i = 0; i < s.length(); i++) {
        final List<String> remaining = performPermutations(s.substring(0, i) + s.substring(i + 1));
        for (int j = 0; j < remaining.size(); j++) {
            result.add(s.charAt(i) + remaining.get(j));
        }
    }

    return result;
}


You could make the Meeting class generic with the T : IComparable<T> constraint. Thus you'll be able to use any type as a time value:

[DebuggerDisplay("{Start} .. {End}")]
public sealed class Meeting<T>
    where T : IComparable<T>
{
    // You can replace these readonly fields with the auto-properties { get; private set; }:
    public readonly T Start;
    public readonly T End;

    public Meeting(T start, T end)
    {
        Start = start;
        End = end;
    }
}

Next you need a comparer:

public sealed class MeetingComparer<T> : IEqualityComparer<Meeting<T>>
    where T : IComparable<T>
{
    public bool Equals(Meeting<T> x, Meeting<T> y)
    {
        // We can use only 2 sequential comparisons to check for the intersection:
        return x.Start.CompareTo(y.Start) >= 0
            ? x.Start.CompareTo(y.End) <= 0
            : y.Start.CompareTo(x.End) <= 0;
    }

    public int GetHashCode(Meeting<T> obj)
    {
        // Make all meetings have the same hash code.
        // In this case the Equals method will be called for each object.
        return 1;
    }
}

And finally you could use LINQ to find the intersecting meetings:

private static IEnumerable<Meeting<T>> FindIntersections<T>(IEnumerable<Meeting<T>> list1,
    IEnumerable<Meeting<T>> list2)
    where T : IComparable<T>
{
    return list1.Join(list2, p => p, p => p,
        (a, b) => new[] { a, b }, new MeetingComparer<T>())
            .SelectMany(p => p);
}

Sample:

var list1 = new List<Meeting<int>>
                {
                    new Meeting<int>(0, 1),
                    new Meeting<int>(100, 111),
                    new Meeting<int>(20, 41),
                    new Meeting<int>(10, 11)
                };
var list2 = new List<Meeting<int>>
                {
                    new Meeting<int>(2, 3),
                    new Meeting<int>(105, 106),
                    new Meeting<int>(40, 41),
                    new Meeting<int>(15, 16)
                };

var intersection = FindIntersections(list1, list2);

EDIT
Try this code to find intersections of the sorted sets. It has complexity \$O(N+M)\$:

private static IEnumerable<Meeting<T>> FindIntersections<T>(IEnumerable<Meeting<T>> listX,
    IEnumerable<Meeting<T>> listY)
    where T : IComparable<T>
{
    var iteratorX = listX.GetEnumerator();
    var iteratorY = listY.GetEnumerator();
    Meeting<T> lastX = null;
    Meeting<T> lastY = null;
    iteratorX.MoveNext();
    iteratorY.MoveNext();
    while (iteratorX.Current != null && iteratorY.Current != null)
    {
        Meeting<T> x = iteratorX.Current;
        Meeting<T> y = iteratorY.Current;

        // Move iterators if needed:
        if (x.End.CompareTo(y.Start) < 0)
        {
            iteratorX.MoveNext();
            continue;
        }
        if (y.End.CompareTo(x.Start) < 0)
        {
            iteratorY.MoveNext();
            continue;
        }

        // Add items to the resulting set, if the items aren't already there:
        if (lastX != x)
        {
            yield return x;
            lastX = x;
        }
        if (lastY != y)
        {
            yield return y;
            lastY = y;
        }

        // Determine which iterator should be moved first:
        if (y.End.CompareTo(x.End) >= 0)
        {
            iteratorX.MoveNext();
        }
        else
        {
            iteratorY.MoveNext();
        }
    }
}

The method above:

Returns a set of the unique Meeting<T>s.
Supports case if one range overlaps several ranges in another set.


Your method visits mosts nodes twice: Here

int leftDiameter = DiameterOfBinaryTree(root.left);
int rightDiameter = DiameterOfBinaryTree(root.right);

int leftHeight = Height(root.left);
int rightHeight = Height(root.right);

calling DiameterOfBinaryTree on the left and right subtree determines the height of both subtrees, and then calling Height on the subtrees computes those heights again.

This can be improved by defining a helper function which (recursively) computes both height and diameter of a tree rooted at a node:

private (int height, int diam) HeightAndDiameter(TreeNode root)
{
    if (root == null)
    {
        return (0, 0);
    }

    var (leftHeight, leftDiam) = HeightAndDiameter(root.left);
    var (rightHeight, rightDiam) = HeightAndDiameter(root.right);

    return (Math.Max(leftHeight, rightHeight) + 1,
            Math.Max(Math.Max(leftDiam, rightDiam), leftHeight + rightHeight));
}

C# (named) tuples are used here to return both values to the caller. The main function then becomes

public int DiameterOfBinaryTree(TreeNode root)
{
    return HeightAndDiameter(root).diam;
}

Each node is visited exactly once now.


Bugs - Program that Creates a Directory in C

There is a potential buffer overflow - the length of argv[1] may be up to ARG_MAX, which is likely larger than PATH_MAX.

The "File Exists" message may be misleading, mkdir can also fail because of permissions, out of space, invalid characters in the name, ...

It's good practice to put { } around all conditionals, including the else.


Possible bug:

If you get the value, targetAsInterface is initialized. One can then set the value to something that is not a Component. Like null.

If you then get the value again, you'll get the old value of target recasted to TInterface. Seems to me that this violates what get and set are supposed to do.


Exercism assignment word-count in Python

My first advice is stop writing classes if you don't need to : your class has only two methods an init and a proper method. This could probably be written as a simple function.

def word_count(phrase):
    word_dict = {}
    for word in phrase.strip().lower().split():
        word_input = ''.join(e for e in word if e.isalnum()).strip()
        if word_input:
            word_dict[word_input] = word_dict.get(word_input, 0) + 1
    return word_dict

Also, a lot of string processing you are doing is not useful, complicated and/or potentially wrong :

On phrase, as noticed by Gareth Rees, there's not point calling strip() since you call split().

As I wasn't aware that the result would be the same, here a proof of concept :

a='  this  is    a little      test'
a.split() == a.strip().split()
-> True

and here's a link to the documentation for strip and split.

On individual words : the way you get word_input from word looks a bit convoluted to me. Among other things, there's no point in calling strip() on a string that only contains alphanumerical characters. Also, just removing "special" characters does not sound like the best option : it's and its will be considered the same way, its annoying :-). Maybe some characters like ' should be taken into account during the splitting. Maybe, depending on the language you are to handle, other characters like - should be kept (for instance in French, "basketball" is "basket-ball" but neither "basket" nor "ball" are French words so splitting would be quite awkward and so would be removing the dash).

Except for that, your code looks go to me!

However, if you wanted to make things even more pythonic, you could use defaultdict. This example will probably look familar to you.


Performance tips:

ujson can bring more speed
since both simplejson and xlrd are pure-python, you may get performance improvements "for free" by switching to PyPy
you may (or not) see speed and memory usage improvements if switching to openpyxl and especially in the "read-only" mode
in the excel_to_json function, you are accessing the same values from row_values by index multiple times. Defining intermediate variables (e.g. defining name = row_values[6] and using name variable later on) and avoiding accessing an element by index more than once might have a positive impact
I'm not sure I completely understand the inner for r in range(1, mw.nrows) loop. Can you break once you get the if row_values[0] == rowe[0] evaluated to True?
are you sure you need the OrderedDict and cannot get away with a regular dict? (there is a serious overhead for CPythons prior to 3.6)
instead of .dumps() and a separate function to dump a JSON string to a file - use .dump() method to dump to a file directly - make sure to use with context manager when opening a file

Code Style notes:

follow PEP8 guidelines in terms of whitespace usage in expressions and statements
properly organize imports
if row_values[6]=="": can be simplified to if not row_values[6]: (similar for some other if conditions later on)
the generate_json() call should be put into the if __name__ == '__main__': to avoid it being executed on import
the excel_to_json() function is not quite easy to grasp - see if you can add a helpful docstring and/or comments to improve on clarity and readability

Other notes:

improve variable naming. Variables like sh, mw, rowe are very close to being meaningless. I would also replace wb with a more explicit workbook
have you considered using pandas.read_excel() to read the contents into the dataframe and then dumping it via .to_json() (after applying the desired transformations)?


Program to test for divisibility of numbers

for loop

i = MAX+1;
while(--i) {

This should be converted to a for loop, it will become more readable.

Smallest scope possible

Maybe in this challenge C99 is not an option, but I would like to reccomend declaring variables in loop declarations, like:

for(int i=1;i<MAX;i++)

Avoiding repetition

Please, avoid repetion:

p[0]=0;
p[1]=0;
p[2]=0;
p[3]=0;
p[4]=0;
p[5]=0;
p[6]=0;
p[7]=0;
p[8]=0;
p[9]=0;

Should be:

for (int i = 0; i <= 9; i++) {
    p[i] = 0;
}

and it becomes so much clearer (think what would have happened if you had to set 100 of such items).


Formatter for converting links in a legacy markup to markdown

The magic numbers used to check the diff, e.g., diff[0][0] == 1 && diff[1][0] == 0

One small improvement is that fast_diff exports enum values that can be used instead, eg:
differencesArr[0][0] === diff.INSERT
differencesArr[1][0] === diff.EQUAL

The looping in formatLinks, which is really only useful if the word has a suffix which is also a link

The whole looping mechanism looks quite suspicious to me:

Only the first $$$ is replaced by the .replace(/\${3}/, '') - if the word contains multiple $$$s, those beyond the first will be left in place

Inside formatLinks, you perform tests on and examine only the first element of the diff array, which is strange if there happen to be multiple matches

Then you have to clean the string afterwards - eg OneMatch$$$TwoMatch$$$ThreeMatch turns into [One Match](OneMatch) Two Match Three MatchOne Match [Two Match](TwoMatch)One Match Two Match [Three Match](ThreeMatch), which needs to be transformed again. Seems inelegant and error-prone.

If there is a better way to tackle the problem.

It looks like there are two fundamental categories a substring can fall into:

One which is escaped, and no []()s should be produced, like the whole span of E$$$scapeMatch
One which is not escaped, like the whole span of OneMatch$$$TwoMatch

To put each substring into one of these categories, I'd split by $$$ which split true, unescaped matches. For example:
OneMatch$$$TwoMatch -> ['OneMatch', 'TwoMatch']
E$$$scapeMatch -> ['E$$$scapeMatch']

Then you can iterate over each possible match, transforming the normal matches to their proper format, and leaving the escaped matches alone (save for removing their $$$s). Join the array of results, and there'll be 2 things left to do:

Add spacing at the edges of match brackets, if they're next to a prefix or suffix (which can be done with a simple regex)
Insert spaces between each word outside of brackets (which can be done with a simple regex)

const parseInput = input => input
    // Split into an array containing separate unescaped matches, escaped sequences, or prefixes/suffixes:
    .split(/\${3}(?=[A-Z]|s?$)/)
    // Add []() brackets around unescaped matches and remove all $s:
    .map(transformSubstr)
    .join('')
    // Add spacing around brackets:
    .replace(/(?<=\w)\[/g, ' [')
    // Except right before an "s" suffix:
    .replace(/\)(?!s)(?=\w)/g, ') ')
    // Add spaces between each word outside of brackets:
    .replace(
        /(?!s$)\w+(?=\[|$)/g,
        words => words.replace(/\B[A-Z]/g, ' $&')
    );

const transformSubstr = (substr) => {
    const normalWordsMatch = substr.match(/\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b/g);
    // If this section is an escaped match, a prefix, or a suffix, there won't be a match
    if (!normalWordsMatch) return substr.replace(/\$/g, '');
    const words = normalWordsMatch[0].match(/[A-Z][a-z]+/g);
    return `[${words.join(' ')}](${words.join('')})`;
};

const tests = [
  "OneMatch{a1fc471a-9483-4af3-8960-7104aa8d3b97}$TwoMatch{183d6425-9d46-4c32-8ce1-55b02e15b3c1}$scapeMatch"                       // Escape Match
, "SimpleMatch"                          // [Simple Match](SimpleMatch)
, "Prefixed{12abb1ad-bc6b-49b9-af33-314c963350ac}$Suffix"              // [Match Match With](MatchMatchWith) Suffix
, "MatchesWithPlural{d63f36d7-04f1-446b-80d3-6c09885cb6f3}$Gets$$$Escaped"                // This Gets Escaped
]

const parseInput = input => input
    // Split into an array containing separate unescaped matches, escaped sequences, or prefixes/suffixes:
    .split(/\${3}(?=[A-Z]|s?$)/)
    // Add []() brackets around unescaped matches:
    .map(transformSubstr)
    .join('')
    // Add spacing around brackets:
    .replace(/(?<=\w)\[/g, ' [')
    // Except right before an "s" suffix:
    .replace(/\)(?!s)(?=\w)/g, ') ')
    // Add spaces between each word outside of brackets:
    .replace(
        /(?!s$)\w+(?=\[|$)/g,
        words => words.replace(/\B[A-Z]/g, ' $&')
    );

const transformSubstr = (substr) => {
    const normalWordsMatch = substr.match(/\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b/g);
    // If this section is an escaped match, a prefix, or a suffix, there won't be a match
    if (!normalWordsMatch) return substr.replace(/\$/g, '');
    const words = normalWordsMatch[0].match(/[A-Z][a-z]+/g);
    return `[${words.join(' ')}](${words.join('')})`;
};
for (const input of tests) {
  console.log(parseInput(input));
}

I don't see any need for either of the external libraries anymore.

A couple nitpicks about your original code, if you were to keep using it:
Always use const when you can, which should be possible 95% of the time - only use let to warn future readers of the code that you may be reassigning the variable in the future.
Avoid sloppy comparison with == and != - better to use === and !==, whose rules are much easier to understand.
Always declare variables before using them - with for (match of matches), you're implicitly creating a global match variable. (Use for (const match of matches) instead)
parseWord name? There can be multiple words inside the variable passed to parseWord, eg SimpleMatch (though there's no space). Maybe call it something like parseInput.
Single-letter match? The current pattern being used in all the code here so far requires words to contain at least two characters. Is that really desirable? Consider, for example, what you'd want to happen given markup of ACuteCat$$$ADog. If that's permitted, you'd just need to change the [a-z]+ to [a-z]*.


Implementing pthread barrier for Mac OS/X

No problems found
As they say, "no news is good news".  I read your code all the way through with an eye towards finding any possible errors, but I didn't find anything to criticize.
Instead I'll point out the things I liked about your code.
Use of restrict keyword
I must admit, I don't use restrict but I should learn to, as it can only help the compiler.  I already advocate using const when appropriate, and this is similar.
Proper error checking
You check for errors and set errno appropriately.
Correct barrier operation
I tried to find any concurrency flaw in your barrier wait function but it looked correct.
The one weird thing
The one thing I thought was strange was that you used a do {} while loop without the curly braces:
    do
        pthread_cond_wait(&barrier->cond, &barrier->mutex);
    while (phase == barrier->phase);

I've never seen that before but I guess if you like to do that it's fine.  I think people throw in the curlies because it doesn't waste any lines, whereas with a while loop or an if block it would add an extra line:
    while (condition) {
        foo();
    }                       // <-- Wasted line

    do {
        foo();
    } while (condition);    // <-- No waste


Optimisation

  I use a Stack where I push my Squares.

A stack is the correct data structure when you want last-in-first-out behaviour. Is that the behaviour you need here?

  It works great until 106 (takes 5 minutes to run).

That is a long way from "great". 106 shouldn't take 10 seconds. Use the right data structure for the task, which here is something with amortised constant time insertion and lookup.

Other notes

public class Square {
        public int x, y;
        // White = 0, Black = 1
        public int color = 0;
}

Why are all of the fields mutable? Why is there no explicit constructor? Rather than using a 32-bit type to store a single bit and needing to document the legal values, why not use a 1-bit type (i.e. bool isBlack)?

int color = 0;

Does this need such a wide scope?

for (int i = 0, counter = 0; i < 10000000; ++i, ++counter)

What is the purpose of counter? As far as I can tell, it isn't used anywhere.

        squares.Push(new Square() { x = 0, y = 1, color = 1 });

...

        squares.Push(CreateSquare(x, y, 1));

Why the discrepancy?

        orientation = Rotate(orientation, color == 0 ? true : false);

condition ? true : false is an unnecessarily long way of writing condition.

    if (orientation == Orientation.NORTH) y += 1;
    if (orientation == Orientation.EAST) x -= 1;
    if (orientation == Orientation.WEST) x += 1;
    if (orientation == Orientation.SOUTH) y -= 1;

This is precisely the kind of thing that switch statements were invented to handle.

    // if null create one and rotate
    if (s == null)
    {
        squares.Push(CreateSquare(x, y, 1));
        orientation = Rotate(orientation, true);
        steps.Add(orientation);
    }else if(s.color == 1)
    {
        s.color = 0;
        orientation = Rotate(orientation, false);
        steps.Add(orientation);
    }else
    {
        s.color = 1;
        orientation = Rotate(orientation, true);
        steps.Add(orientation);
    }

Don't repeat yourself. This could be refactored as

    if (s == null)
    {
        s = new Square { x = x, y = y, color = 0 };
        squares.Push(s);
    }

    orientation = Rotate(orientation, s.color == 0);
    steps.Add(orientation);
    s.color = 1 - s.color;

            blackSquaresAt100k = squares.Where(sqa => sqa.color == 1).Count();

Count has an overload which takes a condition, so enumerable.Where(foo).Count() can be refactored to enumerable.Count(foo).


Improving project Euler solutions is usually done by improving the algorithms itself rather than just optimising the code.

First things first, your divisors() function is wrong and does not work for perfect squares.  To fix this, you need to take care of the sqrt(n) case separately:

def divisors(n):
    number_of_factors = 0
    for i in xrange(1, int(math.ceil(math.sqrt(n)))+1):
        if n % i == 0:
            number_of_factors +=2
        if i*i==n:
            number_of_factors -=1
    return number_of_factors

Now we come to the main part of the code. The important observation to improve your code is that the nth triangular number is given by T(n) = n(n+1)/2. Now, n and n+1 are coprime. If a and b are coprime numbers, the number of divisors of a*b is just the product of number of divisors of a and b.

This suggests the following improvement for the main part of the code:

for n in xrange(1,1000000):
    Tn=(n*(n+1))/2
    if n%2==0:
        cnt=divisors(n/2)*divisors(n+1)
    else:
        cnt=divisors(n)*divisors((n+1)/2)
    if cnt >= 500:
        print Tn
        break

The improvement this provides is very significant. You can improve the performance further by modifying the divisor function to use the same technique:

def divisors(n,start):
    if n==1:
        return 1
    for i in xrange(st, int(math.ceil(math.sqrt(n)))+1):
        if n % i == 0:
            cnt=1
            while(n%i==0):
                n/=i
                cnt+=1
            return divisors(n,i+1)*cnt
    return 2

Essentially, we find p, the first prime factor of n. If p^k is the maximum power of p that divides n, (k+1)*divisors(n/p^k) is the number of divisors of n. start is just a starting point for checking prime divisors.

Overall, these modifications seem to reduce running time from ~5s to 0.15s on my laptop.


Determining a digit on a given position in the A002260 sequence

Frankly I have been staring at the code for ... 20 minutes, and I can't figure out your algorithm. I can't even throw out a good guess as to whether the result is right, or not.

There are some style-related issues that do not help:

Cumulative is not spelled with 2 m's, and no e as you have it in doublyCummulativLength
The self-referential comments are not useful if you can't figure out where the logic/code should start from. Building up on the algorithm would be more possible if the right starting point was given. In other words, your comments assume too much about what people reaing your code will know (or otherwise I am too dumb to see the obvious stuff so the comments are not helping me).
You reference the class LongMath but that class is not included in the code.
Your comments mention things like: // ... and occur on the average count2/2 times What does that mean? How can you be accurate to an exact digit with reasoning like that?
Code like:

    final long count2 = 2*n - (min+max) + 2;
    result += i * (max-min+1) * count2 / 2;

makes little, or no sense to me. count2? What does that mean? max and min are not great either. Lots of constants too.

In general, the code is not primed for a sight-unseen review. I would need you sitting beside me so I can ask questions as I go through. That is not really suitable for Code review.

As an aside, I believe having a class that represents the sequence that is being used would make a really big difference for this code. You need to extract out the class, and iterate it to find 'the spot'.

I played around with this problem, and specifically targetted an overflow-safe solution, so that digitAt(Long.MAX_VALUE) will work. This is the code I have.

Note that I use a class, which allows me to keep a state, and then add to the state.

On my computer the test for digitAt(Long.MAX_VALUE) returns 4 in less than 2.5 seconds. I do not know if this is a good result, or not.

Also, I compared my results with a naive implementation for relatively small values.

Make of this what you will:

import static org.junit.Assert.*;
import org.junit.Test;

public class Seq2260 {

    public static char digitAt(final long index) {
        if (index < 1) {
            throw new IllegalArgumentException("No such position " + index);
        }
        Seq2260 sequence = new Seq2260();
        sequence.incrementPast(index);
        // OK, spans have been added until the current span contains the index.
        // locate the actual digit in the current span.
        return sequence.seekChar(index - sequence.nextOffset);
    }

    // SCALES indicate the number of digits in each scale, and the value where the scale changes too.
    // for example, SCALES[1] are 1-digit values, and when you hit the value 10, you are no longer
    // in SCALES[1].
    // SCALES[0] is only there to make the indexes line up.
    // The Long.MAX_VALUE is only there to make the range end.
    // Note that only Scales up to SCALES[9] will actually be used.
    // by the time you reach SCALES[10] (10,000,000,000) each number is 10 digits long
    // and the cumulative effect means that the index is now huge.
    private static final long[] SCALES = {0L, 10L, 100L,
        1_000L, 10_000L, 100_000L,
        1_000_000L, 10_000_000L, 100_000_000L,
        1_000_000_000L, 10_000_000_000L, 100_000_000_000L,
        1_000_000_000_000L, 10_000_000_000_000L, 100_000_000_000_000L,
        1_000_000_000_000_000L, 10_000_000_000_000_000L, 100_000_000_000_000_000L,
        1_000_000_000_000_000_000L, Long.MAX_VALUE
    };

    //number of digits in a number
    private int scale = 1;
    // how far along the next span will start
    // start at 1 to be 1-based
    private long nextOffset=1;
    // how long the current span is.
    private long length = 0;
    // the last value in the span
    private long span = 0;

    private void incrementPast(final long index) {
        // this is an overflow-safe compare
        // nextOffset could hypothetically be a very small negative number (wrapped). The math
        // here is safe though, because a very large number subtract a very negative number
        // will overflow again and still be less than length.
        while (index - nextOffset >= length) {
            extendSpan();
        }
    }

    private void extendSpan() {
        if (nextOffset < 0) {
            // we have previously overflowed our limit. We only support a single overflow.
            throw new IllegalStateException("Attempt to extend mapping beyond Long.MAX_VALUE");
        }
        span++;
        if (span == SCALES[scale]) {
            scale++;
            if (span == Long.MAX_VALUE) {
                throw new IllegalStateException("Overflowed Long in a span....");
            }
        }
        // for large values, this will overflow. That is the limit of where we can map to.
        // we can handle one overflow (a negative offset). After that, we fail.
        nextOffset += length;
        length += scale;
    }

    private char seekChar(long seek) {
        int sc = 1;
        long pos = 0;
        long val = 0;
        while (pos <= seek) {
            val++;
            if (val == SCALES[sc]) {
                sc++;
            }
            pos += sc;
        }
        // OK, so val includes the char, and it is....
        int charfromright = (int)(pos - seek);
        String value = String.valueOf(val);
        return value.charAt(value.length() - charfromright);
    }

    public static void main(String[] args) {
        System.out.printf("Confirm %s is %s%n", Seq2260.digitAt(1000), "" + smallGet(1000));
        System.out.printf("Confirm %s is %s%n", Seq2260.digitAt(10000), "" + smallGet(10000));

    }

    @Test
    public void testNaieveMatch() {
        for (int i = 3; i < 64 * 1024; i += 19) {
            assertTrue(smallGet(i) == Seq2260.digitAt(i));
        }
    }

    @Test
    public void testNaieveSequential() {
        for (int i = 1; i < 4 * 1024; i++) {
            assertTrue(smallGet(i) == Seq2260.digitAt(i));
        }
    }

    private static char smallGet(int i) {
        StringBuilder sb = new StringBuilder(i + 10);
        sb.append("-");

        int oldmax = 1;
        int current = 0;
        while (sb.length() <= i) {
            current++;
            sb.append(current);
            if (current == oldmax) {
                current = 0;
                oldmax++;
            }
        }
        return sb.charAt(i);
    }

    @Test
    public void testGetDigitAt() {
        assertEquals('1', Seq2260.digitAt(1));
        assertEquals('1', Seq2260.digitAt(2));
        assertEquals('2', Seq2260.digitAt(3));
        assertEquals('1', Seq2260.digitAt(4));
        assertEquals('2', Seq2260.digitAt(5));
        assertEquals('3', Seq2260.digitAt(6));
        assertEquals('1', Seq2260.digitAt(7));
        assertEquals('2', Seq2260.digitAt(8));
        assertEquals('3', Seq2260.digitAt(9));
        assertEquals('4', Seq2260.digitAt(10));

        assertEquals('5', Seq2260.digitAt(20));
        assertEquals('5', Seq2260.digitAt(33));

        assertEquals('9', Seq2260.digitAt(54));
        assertEquals('1', Seq2260.digitAt(55));
        assertEquals('0', Seq2260.digitAt(56));

        assertEquals('0', Seq2260.digitAt(67));
        assertEquals('2', Seq2260.digitAt(99));
    }

    @Test
    public void testLongMax() {
        assertEquals('4', Seq2260.digitAt(Long.MAX_VALUE));
    }

}


Building a string from multiple inputs with some variations

String.Format("{0}{1}{2}{3}{4}{5}{6}", ...);

Since you are just doing concatenation, string.Concat is more appropriate here.

if (!String.IsNullOrEmpty(model.Seed.GID) && !String.IsNullOrEmpty(model.Seed.Clone))
{
    SeedRefId = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}",
    model.Customer.CustomerCode.TrimEnd(), model.Seed.CollectionCodeId.TrimEnd(), model.Seed.SpeciesId.TrimEnd(),
    model.Seed.Zone.TrimEnd(), model.Seed.Elevation.TrimEnd(), model.Seed.ColYear.TrimEnd(), model.Seed.OrchardId, model.Seed.GID.TrimEnd(), model.Seed.Clone.TrimEnd());
    return SeedRefId;
}

Between your ifs and else, there is a lot of repeated code. And, we can observe a pattern there:

The first 7 elements are always present.
The last 2 elements are present if it is not null/empty
The elements are always in the same order.

The method can be reduced to this:

private string ConstructSeedReference(SeedViewModel model)
{
    var reference = string.Concat(
        model.Customer.CustomerCode.TrimEnd(),
        model.Seed.CollectionCodeId.TrimEnd(),
        model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(),
        model.Seed.Elevation.TrimEnd(),
        model.Seed.ColYear.TrimEnd(),
        model.Seed.OrchardId);

    if (!string.IsNullOrEmpty(model.Seed.GID))
    {
        reference += model.Seed.GID.TrimEnd();
    }

    if (!string.IsNullOrEmpty(model.Seed.Clone))
    {
        reference += model.Seed.Clone.TrimEnd();
    }

    return reference;
}

EDIT: Just reread your question, if your concern is only about the NullReferenceException. You can simply use null-coalescing operator ?.:

private string ConstructSeedReference(SeedViewModel model)
{
    return string.Concat(
        model.Customer.CustomerCode.TrimEnd(),
        model.Seed.CollectionCodeId.TrimEnd(),
        model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(),
        model.Seed.Elevation.TrimEnd(),
        model.Seed.ColYear.TrimEnd(),
        model.Seed.OrchardId,
        model.Seed.GID?.TrimEnd(),
        model.Seed.Clone?.TrimEnd());
}


Turning 1D array to 2D array in TicTacToe

Matrices ... 1D or 2D format

In computing it is common to have matrix-like problems. Graphics, mathematics, and Tic-Tac-Toe.

It is often easier to have the matrix data stored as a 1D array, or 'flattened'.

Whether you have it as a 1D or a 2D array does not really matter for the functional aspect, but it can often have a really big impact on the readability.

A matrix of M x N dimension would be stored, for example, as :

int[][] matrix = new int[M][N];

To 'visit' all members of that matrix you need to:

for (int r = 0; r < M; r++) {
    for (int c = 0; c < N; c++) {
        // do someting with matrix[r][c];
    }
}

As a flattened matrix, it would be:

int[] matrix = new int[M * N];

To visit the members, it is:

for (int i = 0; i < matrix.length; i++) {
    // do something with matrix[i];
}

When you have complicated indexing, the flattene system can be more efficient.

Additionally, the flattened matrix has interesting memory properties that often leads to better performance on High-Performing Computational clusters.

Converting from one format to the other is relatively simple.

final int width = 3;
matrix1D[row * width + col] = matrix2D[row][col];
matrix2D[i / width][i % width] = matrix1D[i];

Review

In your case, your matrix is small, and you should chose whichever format makes the code most readable.

If you choose a 2D implementation, you should make sure your winning combinations array is expressed as a 2D format....

int[][][] winningcombinations = {
  { {0, 0}, {0, 1}, {0, 2} }, // Top
  { {1, 0}, {1, 1}, {1, 2} }, // Middle
  { {2, 0}, {2, 1}, {2, 2} }, // Bottom
  { {0, 0}, {1, 0}, {2, 0} }, // left
  .......
}

Magic Numbers

Java arrays have a length property. Use it. You have the code:

for(int i=0; i<=7; i++){ .... }

This should be:

for (int i = 0; i <= winCombinations.length; i++) { .... }

Code Style

In Java recommended code style puts spaces around operators and reserved words.

for(int i=0; i<=7; i++){ .... }

should be (ignoring the 7)

for (int i = 0; i <= 7; i++) { .... }


Using deque for composing a string from 2 alternating stacks

There is no need to read the whole string into a deque. Just iterate over the strings using iterators. The only gotcha is handling the fact that either of the strings can be empty at the beginning and that one can be exhausted before the other.

def _morgan(a, b):
    a, b = iter(a), iter(b)
    try:
        x = next(a)
    except StopIteration:
        yield from b
        return
    try:
        y = next(b)
    except StopIteration:
        yield x
        yield from a
        return
    while True:
        if x <= y:  # `<=` because that's what `min` does
            yield x
            try:
                x = next(a)
            except StopIteration:
                yield y
                yield from b
                return
        else:
            yield y
            try:
                y = next(b)
            except StopIteration:
                yield x
                yield from a
                return

def morgan(a, b):
    return "".join(_morgan(a, b))

Note that both the original strings and the resulting string still need to fit into memory for this to work. If you only need to iterate over the resulting string, use only the private function. In that case the original strings still need to fit into memory, unless you also have them as generators (e.g. by streaming the contents from the URLs):

import requests

def stream(url, chunk_size=1000):
    with requests.get(url, stream=True) as r:
        for chunk in r.iter_content(chunk_size=chunk_size, decode_unicode=True):
            yield from iter(chunk)

if __name__ == "__main__":
    a = stream("https://pastebin.com/raw/pebMbcA6")
    b = stream("https://pastebin.com/raw/bwNEqJcr")
    c = _morgan(a, b)
    while (chunk := "".join(islice(c, 1000))):
        print(chunk, end='')
    print()

This works on my machine with the given strings, but so does the morgan function I defined above.

Note that you need Python 3.8+ for the walrus operator :=. With earlier Python versions it is slightly more verbose:

 if __name__ == "__main__":
    a = stream("https://pastebin.com/raw/pebMbcA6")
    b = stream("https://pastebin.com/raw/bwNEqJcr")
    c = _morgan(a, b)
    chunk = "".join(islice(c, 1000))
    while chunk:
        print(chunk, end='')
        chunk = "".join(islice(c, 1000))
    print()


Consistent implementation of PHP class constants (arrays not allowed)

See PHP Constants Containing Arrays? .  I think both are valid and also your current approach is fine. It's only important that you stick with one solution in your whole project.

Personally I think I would stay with your current solution.


You can call chose.lower without the if statement without any consequences as far as I know. I don’t have any experience with using something like while choose ==“a”, bit it looks to me like if choose ==“a” would work just the same way, and be more readable.


Finding number of solutions nqueens 14 by 14 chessboard

Here's my take on it.
Translate columns 1-14 to 0-13 for internal use and translate back on output.
state keeps track of where the queens are.  state[0] is the row of the queen in column 0, etc.  A None indicates the column is empty.
nQueens() searches state for an empty column and then checks each row in that column for a valid move.  If a move is valid, state is updated and nQueens() is called with the new state. After the recursive call is made, revert the change in state. That avoids the need to make a copy of the state.
The code yields the solutions rather than keeping a list.
printboard() is just to help with visualizing what is going on.  Uncomment some of the calls if you're curious...but only do one of the smaller test cases because there is a lot of output.
I think your imvalid() might be off?
Put the driver code in main().
SIZE = 14

def nQueens(state):
    #printboard(state)

    # find an empty column (row==None)
    for col, row in enumerate(state):
        if row is None:
            break

    # all columns filled. so it is a solution
    else:
        yield state

    for row in range(SIZE):
        # check if row taken
        if not valid(state, row, col):
            continue

        # make the move
        #print(f"col[{col+1}] = {row+1}")
        state[col] = row
        yield from nQueens(state)

        # revert the move to continue the search
        state[col] = None

def valid(state, row, col):
    # is there a queen in this row
    if row in state:
        return False

    # is there a queen on a diagonal
    for c,r in enumerate(state):
        if r is None:
            continue

        if col-row == c-r or col+row == c+r:
            return False

    return True

def printboard(state):
    print('  '+' '.join(str(i%10) for i in range(1, SIZE+1)))
    for r in range(SIZE):
        print((r+1)%10, end=' ')
        for c in range(SIZE):
            if state[c] == r:
                print('Q', end=' ')
            else:
                print('.', end=' ')
        print()

def main(data):
    num_cases = int(data.readline())

    for case_num in range(num_cases):
        # initialize state to all Nones.
        # None means the corresponding column is empty
        state = [None]*SIZE

        # fill in the preset queens
        preset = data.readline().split()
        while preset:
            row = int(preset.pop(0)) - 1
            col = int(preset.pop(0)) - 1
            state[col] = row

        #printboard(state)

        # count the number of solutions
        for n,sol in enumerate(nQueens(state)):
            #printboard(sol)
            pass

        print(n+1)

Test it like so:
test = """
3
1 1 2 9 3 6 4 10
1 9 12 8 8 5 2 7
2 10 10 3
""".strip()

main(io.StringIO(test))

Or call it like:
main(sys.stdin)


Is this a correct way to utilize classes and methods in JAVA?

You seem to be under the impression that efficient code and good design are two separate things.  A good design will help you write efficient code.

In this particular case, you need to learn about separation of concern.  Specifically what is the user concerned about and what should be handled by the class?

The user basically just wants the words in the supplied string swapped.  Everything else should be handled inside the class.

In the class itself, you don't really need all those properties and helper methods.  The main purpose of the code can easily be summed in one function.  I would suggest a utility class(StringUtils?) with a public static function to swap the words and return a string.

The solution could look like this:

Main.java

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    String sentence;
    System.out.println(
        "Please enter a sentence.\nFirst word will be swapped with the last one.\nSecond word will be swapped with second to last\netc.");
    try (Scanner sc = new Scanner(System.in)) {
      sentence = sc.nextLine();
    }
    String swapped = StringUtils.swapWords(sentence);
    System.out.println(swapped);
  }
}

StringUtils.java

public class StringUtils {

  public static String swapWords(String input) {
    String[] usersWords = input.split(" ");
    if(usersWords.length < 2){
      inputError();
    }
    String[] words = new String[usersWords.length];
    int mid = (words.length / 2) + 1;
    for (int front = 0, back = words.length - 1; front < mid; ++front, --back) {
      words[front] = usersWords[back];
      words[back] = usersWords[front];
    }
    return String.join(" ", words);
  }

  private static void inputError(){
            System.out.println(
                    "You have entered an insufficient number of words. Enter at least 2 words for program to swap them");
            System.out.println("Exiting now");
            System.exit(0);
  }
}


Avoiding nested conditionals and comparing strings

I would propose to use data attributes. E.g. icons have data-section-id attribute.

if $(this).hasClass('green') // all should become greynow
{
    $('div.section').show(); // show all sections
    $(this).removeClass('green');
}
else // we turn one sectio on
{
    $('div.section').hide(); // show all sections
    $('#'+ $(this).data('sectionId')).show(); // show a corresponding section
    $('li.icon').removeClass('green'); // turn all icons off
    $(this).addClass('green'); // turn current one on
}

But of course, that requires some changes in HTML structure.


Resize iframe & textarea in reverse directions

Perhaps add overflow:hidden; to the CSS of the textarea and iframe, and add scrolling="no" as an attribute of the HTML iframe element: because otherwise, a scrollbar will appear when the slider is very big or very small.

Maybe a scrollbar is what you want (for usability); but a scrollbar makes a small visual artifact in an empty textbox or iframe, when the element is shorter than one line.


Adding 1 to Date while binding using KnockoutJS

One way would be to move the date display logic to your view model.

function vm(){
    var self= this;

    self.TimeByDay = ko.observable(new Date("December 17, 1995 03:24:00"));

    // fn extention of ko.observable
    ko.observable.fn.AddOneDay = function(){
        return new Date(this().setDate(this().getDate()+1))
    };

    self.AddOneDay = function(TimeByDay){
        return new Date(TimeByDay().setDate(TimeByDay().getDate()+1))
    };
}

And then in your view you can have

Or

Use the extention fn method if your application requires 1 day added to date frequently. Read this for more.

Jsfiddle: https://jsfiddle.net/newuserjs/oLh6u67z/4/


Concurrent use of map

Quote from Golang FAQ:

  Map access is unsafe only when updates are occurring. As long as all goroutines are only reading—looking up elements in the map, including iterating through it using a for range loop—and not changing the map by assigning to elements or doing deletions, it is safe for them to access the map concurrently without synchronization.

Since your functions modify sessions and are running in different routines you need to introduce some locking. Take look at sync package.

Also see question at StackOverflow.

sessionExists function

if _, exists := sessions[cookie.Value]; !exists {
    return false
}

return true

exists already holds the desired bool.
Let's simply this part and return exists directly.

_, exists := sessions[cookie.Value]
return exixts

Also you may take advantage of named return values and simplify your function:

func sessionExists(req *http.Request) (exists bool) {
    cookie, err := req.Cookie("id")
    if err == nil {
        _, exists = sessions[cookie.Value]
    } else if err != http.ErrNoCookie {
        log.Println(err)
    }

    return
}

Now let's take a look at func (*Request) Cookie source code:

func (r *Request) Cookie(name string) (*Cookie, error) {
    for _, c := range readCookies(r.Header, name) {
        return c, nil
    }
    return nil, ErrNoCookie
}

The only possible results are c, nil and nil, ErrNoCookie so there is no point in logging errors:

func sessionExists(req *http.Request) (exists bool) {
    cookie, err := req.Cookie("id")
    if err == nil {
        _, exists = sessions[cookie.Value]
    }

    return
}


So, this is the PHP that causes you to have your 'aml' processing here.

I think people must have confused you by saying not to echo.  You are correct, you do have to communicate by printing something out.  The best way to communicate with Javascript is by using JSON.  JSON stands for JavaScript Object Notation.

You should also check for success or failure from the database query.  Below is untested code (I have no idea what your database::query returns so my error check may not be appropriate):

$query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");

if ($query_return === false)
{
    echo json_encode(array('Success' => false));
    return;
}

$results = array('Data'    => array(),
                 'Success' => true);

while($row = mysqli_fetch_assoc($query_return))
{
    $results['Data'][] = $row;
}

echo json_encode($results);

So now you will receive an array of rows from your database that your javascript code can deal with nicely.  It will be a valid javascript object so you can check it with:

if (response.Success)
{
    // Do stuff with response.Data here.  Probably a loop over the results.
}


HackerRank: Left Array Rotation in Python

This is the easiest way I can think of to do a "shift" on a list in Python:

def shift_list(array, s):
    """Shifts the elements of a list to the left or right.

    Args:
        array - the list to shift
        s - the amount to shift the list ('+': left-shift, '-': right-shift)

    Returns:
        shifted_array - the shifted list
    """
    # calculate actual shift amount (e.g., 11 --> 1 if length of the array is 5)
    s %= len(array)

    # uncomment this line to reverse the shift direction
    # s *= -1

    # shift array with list slicing
    shifted_array = array[s:] + array[:s]

    return shifted_array

my_array = [1, 2, 3, 4, 5]

# negative numbers
shift_list(my_array, -7)
>>> [4, 5, 1, 2, 3]

# no shift on numbers equal to the size of the array
shift_list(my_array, 5)
>>> [1, 2, 3, 4, 5]

# works on positive numbers
shift_list(my_array, 3)
>>> [4, 5, 1, 2, 3]

If you need this to shift backwards (to the left) with negative numbers, add the following to the beginning of the shift list function:

s *= -1

I think the above documentation is sufficient to describe everything without being too wordy.

I have added this to the Stack Overflow Python docs.


Refactor nested foreach loop based on object property

You can create "fallback" version of nested array in the case when $show->flexget_titles_array is empty and handle it with the same nested foreach loop:

...
foreach ($shows as $show) {
    ($arr = $show->flexget_titles_array) || ($arr = array($show->title));
    foreach ($arr as $title) {
        // calculate the distance between the input string filename,
        // and the current show name
        $lev = levenshtein(strtolower($clean_name), strtolower($title));
        // if this distance is less than the next found shortest
        // distance, OR if a next shortest distance to the word has not yet been found
        if ($lev <= $shortest || $shortest < 0) {
            // set the closest match, and shortest distance
            $matchedShow = $show;
            $shortest = $lev;
        }
    }
}
...


Calculating the number of elements of an underlying data structure

Don't Repeat Yourself

Your looping code appears twice. Once in the body of size() and once in the body of GoRec::size(). You only need it once. In fact, the entire structure of GoRec is kind of weird and unnecessary. I also don't like how you named the function go(), made it void, and have it take a reference... Instead, let's write a free function:

size_t size_of(AnyMap const& data)
{
    size_t size = 0;
    for(const auto& kv : data){
        if(kv.second.type() == typeid(AnyMap)) {
            size += size_of(any_cast<const AnyMap&>(kv.second));
        }
        else{
            size++;
        }
    }
    return size;
}

That way:

int size() const {
    return size_of(data);
}

And we have no repetition and no unnecessary extra case for empty map.

Know Your Interface

There are several different overloads for boost::any_cast. You are using the wrong one. This is the one you want:

template<typename ValueType> const ValueType * any_cast(const any * operand);

This overload will not throw, and will return a null pointer if you're attempting to cast to the wrong type. Now, the overload you're using will throw if it's the wrong type - but you're explicitly checking that first. Effectively, you're re-implementing what any_cast is doing under the hood, which is bad.

If you used the other overload, you could let the any internal implementation remain private. And the code ends up looking more direct:

size_t size_of(AnyMap const& data)
{
    size_t size = 0;
    for(const auto& kv : data){
        if (auto submap = any_cast<AnyMap>(&kv.second)) {
            size += size_of(*submap);
        }
        else{
            size++;
        }
    }
    return size;
}


At a high level, I think you're overusing regexes. You can split stuff into words earlier and then clean them, and you don't need to treat newlines as an explicit token. If you do want to split them as an explicit token called newline to protect it from future regexes, you can handle that when you're constructing the markov chain by having a dedicated class, or just a string \n.

class NewlineToken:
    pass

I would take your input text and split it into words first, but do it a line at a time so I don't need to read the whole file into memory. Also, don't use file as the name of a temporary file since it shadows a builtin.

The split method when called with no arguments splits on whitespace.

with open("corpus.txt") as fh:
    for line in fh:
        words = line.split()
        # do stuff with words

After that you can strip punctuation from your words and lowercase it.

word.lower().translate(None, string.punctuation)

I'd probably wrap that all up in a generator that looks something like this.

def stripped_words(path):
    with open(path) as fh:
        for line in fh:
            words = line.split()
            for word in words:
                 yield word.lower().translate(
                         None,
                         string.punctuation
                 )

More about string.punctuation here https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python

The markov chain construction is good. zip automatically truncates the longer iterator and .setdefault is really useful. I actually didn't know about that until reading this. You'd have to modify it a little bit if you're iterating over words from your file rather than working with an array.

This line selects a word uniformly at random regardless of how many times it appears in the text rather than selecting a word with probability equal to its frequency. I'm not sure what the requirements are, but it is something that jumped out at me.

# more frequent words aren't more likely to be chosen here
current_word = random.choice(list(markov_chain.keys()))

Some miscellaneous comments:

You don't need to escape everything in your first character class.

text = re.sub(r'([,.!?;:])',r' \1 ', text)

In this line

text = re.sub(r'[^a-zA-Z0-9|\,|\.|\!|\?|\;|\:]',r' ',text)

| is part of your character class, I'm not sure whether you intended it because it isn't escaped like your other non-alphanumeric characters are.


Counter with increment and decrement buttons

Preface: I haven't worked in the Android ecosystem, so this review is mostly looking at the Kotlin side of things. I've also had minimal exposure to the Redux pattern.

Some low hanging fruit that IntelliJ IDEA points out:

return state is unreachable code in fun reducer. Control flow will always exit as action can only be .INCREMENT or .DECREMENT. I would use an else -> throw IllegalStateException("Invalid Action") in the when, to keep safety in the case of expanding the enum class Action in the future. As a bonus, this is not marked as unreachable code, as IntelliJ recognizes it as a fallback case.
Explicit type arguments in val store = Store<Action, State>... are not required: just val store = Store(State(), ::reducer) works fine and Kotlin infers the types. This is Kotlin's biggest advantage over Java.
class Store<Action, State> can have declaration site variance. Read the link for information about what this means; it is written class Store<in Action, out State> and does not change any semantics of the present code.
private val reducer can be declared directly in the constructor. It's personal preference whether you declare it there or not, but if you do, I would probably also declare currentState there as well (instead of initialState).

Some other points:

I wouldn't use the package com.myapplication; it's a placeholder. Instead, give it something that identifies this package as yours. Oracle's Java tutorial recommends using a domain you own. Even though I do own http://cad97.com, rather than use package com.cad97.project I usually use just cad97.project, as a holdover from before I bought the domain. For you, this pattern would suggest a base package of daniel_t. If you do not own the domain, DO NOT use a com (or any other common TLD) base package.
Personally, I typically don't specify argument labels on function types. (This refers to the types for parameters to the Store constructor, the MutableMap types, the subscribe method.)
Java (and in my adventures so far, Kotlin) typically uses one-letter types for generic types, to distinguish them from regular types. This is compounded by the fact that your generic Action is named the same as your concrete Action. How you resolve this is up to the programmer, but in an ideal world you would not have this conflict of names.
You can return dispose directly: just write return { subscribers.remove(id) }
Store::notifySubscribers can be written as a single-expression function: private fun notifySubscribers() = subscribers.values.forEach { it(currentState) }
subscribers can be declared as private var subscribers = mutableMapOf<Int, (State) -> Unit>()
Rather than return Error from Store::dispatch, use IllegalStateException, as it is more descriptive of the reason for the error.
By the format of Store::dispatch, it looks like what you're trying to do is use a Lock. Kotlin provides special support for this, which would be written something like this:

private val dispatchLock = ReentrantLock() // replaces dispatching

fun dispatch(action: Action) = dispatchLock.withLock {
    currentState = reducer(action, currentState)
    notifySubscribers()
}


Efficiency of grouping a List of case classes by more than one field

Your code is fine

There's nothing wrong with the way you've implemented it. It's readable, and will have reasonable O(n) performance.

Alternative implementation

You've mentioned l is created by concatenation of two lists. As far as I understood one of the lists contains only clients with bool=false and one only clients with bool=true. Some clients will appear on both lists. Example:

val l1 = List(
  Client("87658763", Some(Instant.EPOCH), false),
  Client("87658769", Some(Instant.EPOCH), false),
)

val l2 = List(
  Client("87658769", Some(Instant.EPOCH), true)
)

If this is correct, then an alternative way to implement you function is:

val m1 = l1.map(c => (c.key, c.time) -> c).toMap
val m2 = l2.map(c => (c.key, c.time) -> c).toMap

(m1 ++ m2).values.toList

Or for better (most likely) performance you can use the breakOut trick which will do the mapping and List to Map transformation in single step.

val m1: Map[(String, Option[Instant]), Client] = l1.map(c => (c.key, c.time) -> c)(scala.collection.breakOut)
val m2: Map[(String, Option[Instant]), Client] = l2.map(c => (c.key, c.time) -> c)(scala.collection.breakOut)

(m1 ++ m2).values.toList

Whether this solution is more elegant than your's is subjective. I leave it up to you to decide which one you like more. Whether it's faster should be determined by measurement under production-like load.

First measure & profile

First of all, if you're doing these operations once per the pair of mentioned API calls, then it's likely that the performance will get dominated by the API calls, not this code. If you're doing it more often, then you could remember the results. Before optimising the code I recommend you to measure the performance and determine where is the bottleneck.

Performance factors

If you come to a conclusion that performance of this code is indeed critical, then most likely the problem will be one of these:

allocation of garbage - groupBy, map, toList each allocate a new data structure.  No, the Scala compiler does not optimise this in any way. While allocation is a cheap process, all the garbage will have to be collected, and Garbage Collection can be expensive in some scenarios.
passes over the data set - groupBy, map, toList each is an O(n) operation iterating over the data. Additional these operations may slow down if the data won't easily fit in CPUs cache.

Which one will be dominant, will depend on Heap and GC configuration, the size of l, other workloads in the JVM and other factors. Both can be improved by doing as small number of passes over the data as possible.

Less passes over the data

These are the hints I can give on reducing the number of passes over the data, in this, and other similar situations:

Check If you can avoid some collection conversions. Maybe the Iterable[Client] returned by my is ok, and you don't have to convert it toList.
Use breakOut.
Try doing more in single step. foldLeft is a powerful operation which lets you combine many operations on a collection into one (at the expense of readability).
Use mutable structures under the hood. Keep immutables in the API.


Hello and welcome to Code Review.

Code comments

Consider writing what you expect each function to do at its most important steps. Short concise comments are preferred (I am guilty of not doing this, too!). This would help reviewers that look at your code and yourself when debugging.

Class names

Your queue's name is MCMP, which I assume stands for multi-consumer/multi-producer. It is an unclear class name. Consider changing it to something more descriptive such as: lock_free_queue.

template <typename T, int Size>
class lock_free_queue
{
    /* declarations */
}

Redundancy in iHead, iTail, iWrite

One of those variables is redundant, your queue should support pushing from one end and popping from the other concurrently, so you only require iHead and iTail. The interaction between these three variables is confusing. Can you explain how they are supposed to work together?

They don't do what you think they do

size() and wasEmpty() are obviously supposed to return the size of the queue and if it is empty, respectively. However, you are not doing an atomic operation to evaluate their expressions. Therefore, nothing prevents another thread from modifying one of either atomic variable after it is loaded. For example:

template<typename T, int Size>
bool MCMP<T, Size>::wasEmpty()
{
    return ( iHead.load() == iTail.load() );
}

What happens if a value is loaded from iHead.load(), but then another thread modifies iHead a bunch of times before iTail loads? It will be compared with an outdated value of iHead and could make your queue say that it is not empty, but it is actually empty in reality.

Compare/exchange loops

You seem to misunderstand how compare/exchange loops work. Every time the compare/exchange operation fails, the first argument of the compare/exchange function (expected) gets updated with the newest value of A.

So in your case, there is no need to load from A every single time in the loop. Your compare/exchange loops thus become:

int newIndex;
int index = iHead.load(); // the initial load from the atomic variable
do
{
    if ( index == iTail.load() )
        return false;
    newIndex = index + 1;
} // 'index' gets updated when the loop fails
while ( !iHead.compare_exchange_weak( index, newIndex ) );

The ABA problem

tryPop( T& ) and tryPushLater( const T& )

Because concurrent code can execute with undetermined timings, your do{} while{} loops suffer from the ABA problem; newIndex gets updated in the loop when the condition fails, but it is possible for one thread to stall and for another to come in and change the value of index from A to B then back to A. In that case, newIndex would not be updated, as the condition would succeed when the original (stalled) thread resumes.

How could it fail if iHead is always incremented?

Thread A can be paused for an indeterminate amount of time. While A is paused, a number of threads concurrently push/pop elements causing your index to overflow and reach the value that A has; A resumes and finds that the comparison is equal and doesn't update newIndex. You have the ABA problem.

While this scenario is very unlikely, it is still possible. Therefore, the code is not error-free. Your queue could not be used as part of a long running application because that issue might eventually arise causing the application's state to become corrupted.

If you require further explanation of this issue, tell me so in a comment.

The ABA problem - Extended

For an atomic compare/exchange operation:

Let T1, T2 be threads.
Let A be the atomic variable.
Let E be the expected value of A.
Let N be the new value of A on success.

In any compare/exchange based algorithm that loads the value of A and performs another operation based on that value, such as:

Updating N if the compare/exchange operation fails (A.load() != E) with the result of a calculation dependent on the most up-to-date value of A.
Dereferencing the value loaded from A if it is a pointer.
Performing a lookup based on the value loaded from A.
etc.

The ABA problem occurs when thread execution timings cause T1 to stall before the compare/exchange operation (that is dependent on the value loaded from A) is evaluated.

While T1 is stalled, T2 changes the value of A to some other value and then back to the original value of A before T1 resumes. Once T1 continues, the condition of the compare/exchange operation will thus evaluate to true when it should in fact be false.

In the case of the first example of the previous bullet list, N would be stored in A while N has an invalid value/state; had the compare/exchange operation failed (as it should have) N would have been updated according to the new value of A before the next compare/exchange evaluation.

Other bugs

When you pop an element from your queue, you don't actually remove the element, you just return a reference to it.
The values get written to the array whether makePushedDataAvailable() is called or not, so other threads will see those values. Is this expected?

Conclusion

I've highlighted the most obvious bugs in your program and a few design issues. The ABA problem being the most serious one.


"whether its bad practice or not" to sub-divide.  No, not bad practice - in fact good in certain areas.  It often comes down to maintenance - how many functions per file and the optimal answer is highly problem dependent.  IMO, too often files need fewer functions than code needs fewer files.
ungetch() have troubles as it ungets a EOF.  This special value should not be unget-able.  Further – I have doubts that when char is signed, that these 2 functions properly handle some char values as the real getc() returns unsigned char and EOF.  Example: If (char) 255 is un-gotten, on get, it may have the value of EOF.   Recommend making your unget buffer unsigned char.
Unclear to the whole need for user unget/get functionality as standard library ones well handle 1 level of get/unget.
The whole addtree(), should input be alphabetical, devolves into a linked list.  Consider AVL trees.
Below test i against size after the assignment.  Recommend test before to cope with pathological size values like 1.  Recommend re-write - avoiding code like (word+i++).  Further, consider size_t rather than int for array indexes.

// from
do {
  *(word+i++) = c;
} while (isalpha(c = getch()) && i < size-1);

// to
if (size > 0) size--;
while (i < size) {
  word[i++] = c;
  c = getch()
  if (!isalpha(c)) {
    break;
  }
}

MAX_WORD is fuzzy.  Suggest MAX_WORD_SIZE.
ungetch() and getch() look way too much like standard functions.  Suggest io_ungetch() and io_getch().
Cast not needed.

// return (struct tnode *) malloc(sizeof(struct tnode));
return malloc(sizeof(struct tnode));

// p = (char *) malloc(strlen(s)+1);
p = malloc(strlen(s)+1);

Magic number 4.  Why 4?

// printf("%4d %s\n", node->count, node->word);
printf("%d %s\n", node->count, node->word);

If a function does not modify a pointer's contents, use const.

// void treeprint(struct tnode *node, int min_count, int max_count)
void treeprint(const struct tnode *node, int min_count, int max_count)

Minor: .h file void ungetch(int); --> void ungetch(int ch);  Also add a little documentation of the .h files, it goes a long way in understanding.
Minor: spelling: doesnt --> doesn't
Pedantic point: char may be signed and is...() defined for unsigned char and EOF, not signed char.

// if(isalpha(word[0]))
if(isalpha((unsigned char) word[0]))


Turning nested jQuery Promises into flat code structure using .done() and .then()

You can substitute returning Promise objects from functions for using callbacks as parameters to function, to chain .then() and .catch(). Array.prototype.map() and Promise.all() can be substituted for jQuery.each() which does not await the fulfillment of Promise objects iterated.

Which requires returning the jQuery promise object from storeGroupOnServer

storeGroupOnServer = function(uuid, callback) {
    return $.post('saveGroup.php', {uuid:uuid},'json')
           .then(function(data) {
             return data.groupid;
           });
};

and returning a jQuery promise object of Promise from createGroupDomNode

createGroupDomNode = function(groupid, callback) {
    var cloner = $('#cloner');
    var newnode = cloner.clone(true);
    newnode.attr('id',groupid);
    newnode.removeClass('hide');
    cloner.after(newnode);
    return $.Deferred().resolve(newnode);
}

and awaiting <img> element load event

function createNewChildDomNode(imgpath, groupdom){
    return $.Deferred(function(dfd) {
             imgnode = $('<img/>')
                       .on("load", dfd.resolve)
                       .on("error", dfd.reject)
                       .attr('src',imgpath);
             picnode = $('<picture/>').append(imgnode);
             $(groupdom).first().prepend(picnode);
           }).promise();
}

For example

const data = {
  uuid: {
    1: 4,
    2: 5,
    3: 6
  }
};
const response = {
  4: "a",
  5: "b",
  6: "c"
};

const groupPromise = Promise.resolve(data.uuid[1]); // initial `Promise`
const arrayOfFiles = [Promise.resolve({
  fileInfo: {
    cdnUrl: 10
  }
}), Promise.resolve({
  fileInfo: {
    cdnUrl: 20
  }
}), Promise.resolve({
  fileInfo: {
    cdnUrl: 30
  }
})];

const storeGroupOnServer = (uuid) => {
  console.log({
    uuid
  });
  // `return` response `Promise`
  return Promise.resolve(response[uuid])
};

const createGroupDomNode = (groupid) => {
  console.log({
    groupid
  });
  // `return` `groupid`
  return Promise.resolve(groupid)
};
const createNewChildDomNode = (groupdom, {
  // destructure `cdnUrl` define as `imgpath`
  fileInfo: {
    cdnUrl: imgpath
  }
}) => {
  console.log({
    imgpath,
    groupdom
  });
  // process `<img>` elements here
  // `return` resolved or rejected `Promise`
  // at `load` or `error` event
  return Promise.resolve("done processing " + imgpath)
};
let handleFiles = (groupnode, file) => {
  console.log({
    groupnode,
    file
  });
  // handle each `file` `Promise`, pass `group` node to
  // function passed to `.then()`
  return file.then(createNewChildDomNode.bind(null, groupnode))
};
const handleGroupDomNodes = (groupnode) => {
  console.log({
    groupnode
  });
  // use `Promise.all()`, `.map()` to process array of `Promise` objects
  return Promise.all(
    arrayOfFiles.map(handleFiles.bind(null, groupnode))
  )
};

groupPromise
.then(storeGroupOnServer)
.then(createGroupDomNode)
.then(handleGroupDomNodes)
.then(complete => console.log(complete)) // to illustrate chain completes
.catch(err => console.error(err)); // handle errors in chain


Fundamentally, at some point, you have to do a cross-join to calculate your results. Performance will be a problem... but there are things that can be done.

First though, why the ugly SQL? Formatting SQL to make it readable is not hard to do:

select C.NUMCLI,
       C.NAAM,
       T.FULLNAME,
       (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) as DIFF
from (
        select LASTNAME ||' '|| FIRSTNAME ||' '|| MIDDLENAME  as FULLNAME
        from TMP_CONTROL
     ) T,
     (
        select NUMCLI,
               NOMCLI ||' '|| PRNCLI as NAAM
        from CLIENT
        where CODLAN = 3
          and STAANN <> 'D'
     ) C
where (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60

We can see a few things in here.....

Your source data contains a middle-name but your main table does not. Are you sure you want to be joining them this way? Will it create the correct results?

Now, about those performance improving options....

Let's assume that the best way to solve this problem is to do a cross-product of the two tables. Compare each value in table a with all values in table b. Oracle ha a few options for doing this. I will list them in what I consider to be a worst-to-best order:

true cross-product - It can do a true Cartesian product of the data - build an in-memory join of each value in the temp table joined to each value in the primary table, and then scan the results once, calculating the edit distance, and then discarding those results which are < 60. It can either calculate the string concatenation of the names before or after the Cartesian product, either option will be (very) slow.
nested-loop T->C - It can loop through each temp table value, and for each of them, it can do the name-concatenation, and then it will need to join to the primary table (with the conditions), do the name-concatenation, and discard bad edit-distances.
nested-loop C->T - It can loop through each value in the primary table, check the conditions, and for each successful value, it can do the String-concatenation, it can scan all values in the temp table, compute the name-concatenation, and then calculate the edit distance, and discard the bad results.
nested-loop C'->T' or T'->C' - It can produce a temporary, or in-memory version of the pre-filtered C table and name-concatenated T and C tables, and then do a nested-loop of these two in-memory tables, discarding bad edit distances.

Your SQL is written to suggest you want it to do the last option, create two in-memory data sets, each of them pre-computed to contain just the name-concatenated values, and then you only perform the cross-product on these tables.... but, just because you wrote the SQL that way does not mean that Oracle will do the process that way....

... have you done an explain-plan to figure out which option it has taken?

My guess is that it has chosen nested-loop T->C, with a second possibility of nested-loop C->T. The reasons?

the temp table probably does not have statistics up to date, and is not indexed at all
the primary table probably has some indexes on CODLAN and/or STAAN
when Oracle optimizes the query, it will likely decide the temp-space required to store all the name-concatenated values will require too much memory, or even physical IO

Now, we want/need Oracle to choose the most efficient cross-join mechanism... and we do not want it calculating the name-concatenation on the fly because it will need to repeat that many times for at least one side of the cross-product.

The solution is to force Oracle's plan to do what we want, and the way to do that is to pre-compute the data needed for the cross-product.

Your temp table should already have the pre-computed name-concatenated values... why are you having to do the name-concatenation as part of the query? Call this column FULLNAME

Then, create a second table as:

create table TMP_CLIENTNAME (
    NUMCLI INTEGER NOT NULL,
    NAAM NVARCHAR(255) NOT NULL)
)

insert into TMP_CLIENTNAME
select NUMCLI,
       NOMCLI ||' '|| PRNCLI as NAAM
from CLIENT
where CODLAN = 3
  and STAANN <> 'D'

Then your cross-product query becomes:

select C.NUMCLI,
       C.NAAM,
       T.FULLNAME,
       (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) as DIFF
from TMP_CONTROL T,
     TMP_CLIENTNAME C
where (UTL_MATCH.EDIT_DISTANCE_SIMILARITY(NAAM, FULLNAME)) >= 60

This query forces Oracle not to do any calculations other than the edit-distance in the join. This will make a difference....

The down-side is that you need additional storage for the data.

Once you have your data in this format you can consider some other options.... (which will likely affect the results of the edit-distance calculations)

index the first letter of each name, and only calculate the edit distances where the first letters are the same.
only calculate the edit distance when the length of the two names are less than say 5 characters different.
.....


Note: The concepts presented in this answer have been implemented in the following 'alternate' implementation in this question: Name Filtering using a Trie

Interesting problem. Your code is hard to read, not because it is unstructured, or messy, but because the helper function names are hard to grasp.... what do they do?

So, on the good side, your 'visual' style is consistent, and neat. All your lines are indented well, and braced, etc. Well, except for this line:

if (partQuery.trim().length() <= 0) return true;

Naming

The first issue is naming..... Four things:

helper0 and helper1 .... do not help, despite the name.
Not a big deal, it's probably a 'local rule', but it is unconventional to use 'prefixes' in Java for variable names. What does the m mean? mTotalNames should just be totalNames. You are using "Hungarian" notation of some sort, and that is not good practice in Java
'Part' is overloaded in too many places. partQuery, partName, partNameList, it becomes hard to remember which variables are which.
iterator is a horrible name. We know it is an iterator, but what does it iterate?

Algorithm

This is a situation where the right data structure will help a lot. You are doing and repeating too much work. Consider this:

you convert names to lower case often.
you split names.... often.
you get prefixes... often.

What you need is a better algorithm, and the right one, is to build a trie.

The trie will be indexed by the characters in the names. This will allow you to search for names in a very fast way, and not do any of the overhead processing repeatedly.
Build the trie once, and then use it repeatedly when you type to filter the names.

Bug

Your code will not process things correctly for a certain subset of names/queries.

Consider the name "Andy Anderson", and the search query "And Andy".... this will not match, because the search query word 'And' will match against 'Andy' first, and then that leaves the search term 'Andy', which will not match against the word 'Anderson'.

You need to sort the search terms in decreasing-length order, and always search with the longest query term first.

Follow Up

This subject intrigues me, I may implement my recommended solution myself... in a day or so.


I want to run the timer at 2:00 a.m. and shutdown the application

The whole switch can be replaced by

hoursUntilShutdown = (26 - currentTime.Hour) % 24

where % is the remainder of the division, as in C (I don't use C#, so I can only assume it's the same).


Function to check if folder path is valid

Magic numbers

All error codes are magic numbers. It's hard to keep numbers in mind, though. If I use

path_is_correct_directory(some_path)

and get -6, what exactly did I do wrong? I have to look into the documentation, check the error values and add that to my own code:

if(path_is_correct_directory(some_path) == -6) {
    yell_at_user("Path may not contain slash!");
}

But that's still opaque. Instead, use an enum:

enum RESULTS {
    PATH_IS_VALID     = 0,
    PATH_IS_DIRECTORY = 1,
    /*   ---   */
    PATH_IS_NULL   = -1,
    PATH_IS_EMPTY  = -2,
    PATH_TOO_SHORT = -3,
    /*   ---   */
    INVALID_DRIVE           = -4,
    INVALID_DRIVE_DELIMITER = -5,
    /*   ---   */
    PATH_CONTAINS_SLASH         = -6,
    PATH_CONTAINS_COLON         = -7,
    PATH_CONTAINS_ASTERISK      = -8,
    PATH_CONTAINS_QUOTE         = -9,
    PATH_CONTAINS_LT            = -10,
    PATH_CONTAINS_GT            = -11,
    PATH_CONTAINS_PIPE          = -12,
    PATH_CONTAINS_QUESTION_MARK = -13
};

Instead of magic numbers, I can now confidently compare against a nice name:

if(path_is_correc_directory(some_path) == PATH_IS_DIRECTORY) {
    list_directory_contents(some_path);
}

Keep scope of variables short

Since you use C99, you can keep the scope of your variables shorter. For example i should only be valid in the for loop, but not outside. szPath can get initialized with strlen right away (after the NULL check).

Variables that shouldn't change can be const

All szPath, path driveLetter and validDriveLetter should not change and can therefore get changed to const.

sz is a prefix for strings, not numbers

In Hungarian notation sz is a prefix for "string terminated by zero". Since Hungarian notation is used throughout Windows APIs, that can be a source of confusion. path_size is fine on the other hand.

All at once

int path_is_correct_directory (const char *path)
{
    if(path == NULL)
        return PATH_IS_NULL;
    if(*path == '\0')
        return PATH_IS_EMPTY;

    const size_t path_size = strlen(path);

    if(path_size < 3 || path_size> MAX_PATH)
        return PATH_TOO_SHORT;

    const char    driveLetter[3]      = { path[0], path[1], '\0' };
    const BOOL    validDriveLetter    = PathIsDirectory(driveLetter);

    if(validDriveLetter == 0)
        return INVALID_DRIVE;

    if(path[2] != '\\')
        return INVALID_DRIVE_DELIMITER;

    for(int i = 3; i < path_size; i++)
    {
        if(path[i] == '/')  return PATH_CONTAINS_SLASH;
        if(path[i] == ':')  return PATH_CONTAINS_COLON;
        if(path[i] == '*')  return PATH_CONTAINS_ASTERISK;
        if(path[i] == '"')  return PATH_CONTAINS_QUOTE;
        if(path[i] == '<')  return PATH_CONTAINS_LT;
        if(path[i] == '>')  return PATH_CONTAINS_GT;
        if(path[i] == '|')  return PATH_CONTAINS_PIPE;
        if(path[i] == '?')  return PATH_CONTAINS_QUESTION_MARK;
    }

    if(PathIsDirectory(path))
        return PATH_IS_DIRECTORY;

    return PATH_IS_VALID;
}

By the way, Windows also supports network directories, which start with \\.


Compile time positive and negative powers of two

Your code is not C++98 compliant

Standards prior to C++11 only allows const integer static member initialisation (see here).

So unfortunately your code is not C++98 compliant and in fact does not compile. So technically your code is off-topic on this site. As it is not working as intended. Your code probably only compiles because you're using a compiler that has an extension to allow non integer const static members.

To get around this typically you would define a static method that returns the value. In fact, this is why std::numeric_limits<T>::max() is a function instead of a static member value. However these cannot be evaluated in a constant expression context. You need C++11 constexpr for that afaik.

General advice

Some general advice. Template parameters are compile time constants by definition. Any sensible compiler should do any necessary casts during compile time so you will not get a run-time penalty for using higher precision.

For this reason I advice that you use the largest types possible in your template to get the most precision at no additional cost. I.e. change float to double and int to long long.

You should consider wrapping the templates that are not intended for use by the user in a suitable namespace. Typically I use a nested namespace called detail.

Also identifiers in ALL_CAPS_WITH_UNDERSCORES are typically reserved for macros. So I advice against using this naming convention for your identifiers as it will confuse many readers.

Better implementation

If we restrict ourselves to the bits of the code that are C++98 compliant, then we can have a much easier implementation for the integer exponentiation.

template<unsigned long long exponent>
struct ipow_2{
    static const unsigned long long value = (1 << exponent);
};

If you want a C++98 compliant negative exponent you can use:

template<long long exponent>
struct pow_2{
    static double value(){
        if (exponent == 0) {
            return 1;
        }
        else if (exponent > 0) {
            double half = pow_2<exponent/2>::value();
            return (1<<(exponent&1))*half*half;
        }
        return 1 / pow_2<-exponent>::value();
    };
};

But be aware that the same caveat for non-integer const initialisation still applies so it's not hugely useful in TMP for example.

If we accept use C++11 you can simplify and generalize to:

// Tail call optimization will transform this into the equivalent
// loop
constexpr int64_t ipow_p(int64_t base, int exp, int64_t ans = 1) {
    return exp < 1 ?
        ans : ipow_p(base*base, exp/2, (exp % 2) ? ans*base : ans);
}

constexpr double ipow(int base, int exp){
    return exp > 0 ? ipow_p(base, exp) : 1.0 / ipow_p(base, -exp);
}

This is usable in a constant (TMP) context thanks to the constexpr qualifier and At -O2 the call will be expanded to a constant.