Merge three ByteArrays together and then split resulting ByteArrays

The way you are doing it is fine, however it seems like a better idea to just put all of the data you want to serialize into a Serializable object and then just serialize that automatically. For example you could do something like :

public static void main(String[] args) throws IOException,
    ClassNotFoundException {
  String os = "whatever os is";
  long lastModifiedDate = 1379811105109L;
  short schemaId = 32767;
  Thing myData = new Thing(os, lastModifiedDate, schemaId);

  ByteArrayOutputStream byteOsTest = new ByteArrayOutputStream();
  ObjectOutputStream outTest = new ObjectOutputStream(byteOsTest);
  outTest.writeObject(myData);

  byte[] allWrittenBytesTest = byteOsTest.toByteArray();

  ObjectInputStream inTest = new ObjectInputStream(new ByteArrayInputStream(
      allWrittenBytesTest));
  Thing myDataTest = (Thing) inTest.readObject();

  short schemaIdTest = myDataTest.getSchemaId();
  long lastModifiedDateTest = myDataTest.getLastModifiedDate();
  String avro = myDataTest.getAvro();

  System.out.println(schemaIdTest);
  System.out.println(lastModifiedDateTest);
  System.out.println(avro);

  writeFile(allWrittenBytesTest);
}

// in its own java file
public final class Thing implements Serializable {

  private final String avro;

  private final long lastModifiedDate;

  private final short schemaId;

  public Thing(String avro, long lastModifiedDate, short schemaId) {
    this.avro = avro;
    this.lastModifiedDate = lastModifiedDate;
    this.schemaId = schemaId;
  }

  public String getAvro() {
    return avro;
  }

  public long getLastModifiedDate() {
    return lastModifiedDate;
  }

  public short getSchemaId() {
    return schemaId;
  }
}


Object for generating HTML for hyperlinks

For the suggested use case having an object is an overkill.

As far as I can tell from the code provided, every link is generated only once, which makes class variables; a dedicated method to clean the state; and a code to instantiate an object all unnecessary. So a function would be more appropriate here.

Besides, as it seems that a code is more intended to create an HTML <a> tag dynamically than to create an URL, and also in order to follow the Single responsibility principle, I would change the list of parameters to just

hLink('http://example.com/?input=0#section', 'website', '_blank');

which will make parameters more sensible and consistent.


Project Euler #8: max product of 13 consecutive digits in a sequence

Let's go through it step-by-step.

for (int j = i, k = 0; j < limit; j++, k++) {
    x[k] = Integer.parseInt(String.valueOf(largeNum.charAt(j)));

    sum = x[k] * sum;

}

In this for loop, whose goal is to calculate the product of the limit digits starting at the index i, there are multiple concerns:

You are converting the character at the index j to an integer by first turning it into a String and parsing that String into an integer. You can do it in a more direct manner by using Character.getNumericValue(char); this will directly return the numeric value of the character, i.e. 5 for the character '5'. Also, since we know before-hand that we will be dealing with digits that are only [0-9] (and not all Unicode digits), we can even use a simple arithmetic calculation with largeNum.charAt(j) - '0'.
You are using a pre-allocated array to store this integer. You don't need it: you can just store the integer as a local variable. This will also simplify the for loop conditions: it is currently iterating over both a j and a k when only one is really needed.

With those considerations, you could have:

for (int j = i; j < limit; j++) {
    int digit = largeNum.charAt(j) - '0';
    sum *= digit;  // which is the same as "sum = digit * sum"
}

if (sum < previousSum) {
    sum = previousSum;

}
previousSum = sum;

This works but is awkward to read: we're interested in getting the maximum sum and this code is dealing with a "sum" and a "previous sum". Also, why are talking about "sum" when the problem deals with "products"?

Consider renaming the result to maximumProduct and the current product to product. With this, you can have:

maximumProduct = Math.max(maximumProduct, product);

which is a lot clearer: at the end of calculating the product for the current index, we retrieve the maximum of the current maximum and the calculated product, using Math.max.

sum = 1;

The first remark is: what is this code doing at the end of the for loop? It actually initializes a value for sum that will be used for the product of the next index. Thus, this should be placed at the top of the loop: let the current index initialize its temporary values correctly.

if (limit > largeNum.length()) {
    break;
}

It took me a bit of time to figure out why this code was there. Its purpose is actually to "correct" the fact that the subsequent loop considers limit digits because its ending condition is

//                  v---v
for (int j = i; j < limit; j++) {

You should not change the value of limit. This in fact a constant of the problem: it is the number of consecutive digits to consider. Thus, what you need to do is:

At index i, consider the next limit digits with

for (int j = i; j < i + limit; j++)
//                  ^-------^

End the main loop when there are less than limit digits left with

for (int i = 0; i < largeNum.length() - limit; i++)
//                  ^-----------------------^

Additional comments

As said before, limit is a constant of this problem. At the very least, it should be given as parameter of computeProduct, just like largeNum. Both of those could then be made constants (i.e. private static final).
computeProduct, despite its name, does more than computing the product; it actually prints it. Consider changing the method so that it returns the wanted product. Then, you can have the main method print it.

All in all, this is what you end up with:

private long computeProduct(int limit, String largeNum) {
    long maximumProduct = 1;
    for (int i = 0; i < largeNum.length() - limit; i++) {
        long product = 1;
        for (int j = i; j < i + limit; j++) {
            int digit = largeNum.charAt(j) - '0';
            product *= digit;
        }
        maximumProduct = Math.max(maximumProduct, product);
    }
    return maximumProduct;
}


Is this the right approach for Controller-Service-Dao implementation?

There are various implementations of MVC or MVC inspired patterns, there aren't hard and fast rules to follow, each implementation is often tweaked to suit certain needs.

Here are some old threads that explain the responsibility of each layer and may answer some of your questions:

  Is this the right approach for Controller dao service pattern?

MVCS - Model View Controller Service

Responsibilities and use of Service and DAO Layers

  Purpose of service class , is it for redirection only to dao or for validations also?

Service layer vs DAO — Why both?

In MVC , DAO should be called from Controller or Model

  Do we need to use inheritance for Dao classes ?

Most effective way to reflect inheritance relationship in DAOs?


Here are some things that may help you improve your code.

Check return values for errors

The call scanf can fail.  You must check the return values to make sure it hasn't or your program may crash (or worse) when given malformed input or due to low system resources.  Rigorous error handling is the difference between mostly working versus bug-free software.  You should strive for the latter.

Decompose your program into functions

Almost all of the logic here is in main in one rather long and dense chunk of code.  It would be better to decompose this into separate functions.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).  In this particular case, I happen to think it's perfectly appropriate because it's a single short program that and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences.

Use <cstdio> instead of <stdio.h>

The difference between the two forms is that the former defines things within the std:: namespace versus into the global namespace.  Language lawyers have lots of fun with this, but for daily use I'd recommend using <cstdio>.  See this SO question for details.

Prefer iostream to old-style printf

The iostream library is the more modern C++ way to do I/O.  Prefer it over printf and scanf.  So instead of this:

printf("%d + %d = %d", a, b, zbroj);

Write this:

std::cout << a << " + " << b << " = " << zbroj << '\n';;

See SL.io.3 for details.

Initialize variables before use

The mod variable is printed before it is set to any value.  That is not likely to be useful.  Better is to always make sure that all variables are initialized before using them.

Use constant string concatenation

This code currently includes these lines:

cout << "U kojem modu kalkulatora zelis biti? \n" << mod;
cout << "Mod 1 je za zbrajanje \n";
cout << "Mod 2 je za oduzimanje \n";
cout << "Mod 3 je za mnozenje \n";
cout << "Mod 4 je za dijeljenje \n";

I would suggest writing it instead like this:

std::cout <<
    "U kojem modu kalkulatora zelis biti? \n"
    "Mod 1 je za zbrajanje \n"
    "Mod 2 je za oduzimanje \n"
    "Mod 3 je za mnozenje \n"
    "Mod 4 je za dijeljenje \n";

Since the next line happens to be scanf, I'd suggest instead using your prompt function.

Consider using more idiomatic C++

While your use of and and not is not techncially wrong, you should be aware that many experienced C++ programmers will be unfamiliar with these operator alternatives, and so if others read your code, it might be an impediment to their understanding of the code.

Eliminate redundant variables

I don't speak Croatian, but the variable names are good in that they accurately describe what the variables mean in the context of the program.  However, I would suggest that instead of zbroj, razlika, umnozak, kolicnik you could use a single variable rezultat.

Don't Repeat Yourself (DRY)

The mathematical operations in the case statement all include very similar repeated code.  Instead of repeating code, it's generally better to make common code into a function.  The only thing that varies is the prompt, the mathematical operation and the way the result is printed.  An advanced technique would be to gther them all into a data structure.  If you're just beginning, don't worry if you can't understand this yet.  It uses lambda expressions and C++17 std::string_view among other things.  I am putting it here to show how powerful C++ can be:

#include <cmath>
#include <iostream>
#include <string_view>
#include <array>

int prompt(const char* name)
{
    std::cout << name;
    int value;
    std::cin >> value;
    return value;
}

int main()
{

    struct MathOp {
        std::string_view opname;
        int (*operate)(int a, int b);
        std::string_view opsymbol;

        void operator()() const {
            std::cout << "Odabrali ste " << opname << "!\n";
            int a = prompt("a: ");
            int b = prompt("b: ");
            int rezultat = operate(a, b);
            std::cout << a << opsymbol << b << " = " << rezultat << '\n';
        }

    };

    constexpr std::array<MathOp, 4> op{{
        { "zbrajanje", [](int a, int b){ return a+b; }, " + " },
        { "oduzimanje", [](int a, int b){ return a-b; }, " - " },
        { "mnozenje", [](int a, int b){ return a*b; }, " * " },
        { "dijeljenje", [](int a, int b){
                if (b == 0) {
                    std::cout << "dijeljenje s nulom \n";
                    return 0;
                }
                return a/b;
            }, " / " },
    }};

    std::cout << "U kojem modu kalkulatora zelis biti? \n";
    for (std::size_t i{0}; i < op.size(); ++i) {
        std::cout << "Mod " << i+1 << " je za " << op[i].opname << "\n";
    }
    unsigned mod;
    std::cin >> mod;

    if (mod > 0 && mod <= op.size()) {
        op[mod-1]();
    } else {
        std::cout << "Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru! \n";
    }
}

Now if we want to add exponentiation, for example, all we need to do is add a single line to the op array:

{ "eksponenciju", [](int a, int b){ return static_cast<int>(std::pow(a,b)); }, " ** " },


import glob
import re
import os.path
from collections import defaultdict

class Pylocwolowitz(object):
    '''Pylocwolitz is a very simple text localization system, meant to be used
by web applications (but can pretty much be used anywhere). Yes, another
localization system.'''

def __init__(self, path, format_deserializer='json'):

Calling it format_deserializer suggests to me that it should be a function. Perhaps it should just be format?

    if format_deserializer not in ('json', 'yaml'):
        raise ValueError('FormatNotSupported')

    self.path = path
    self.format_deserializer = format_deserializer
    self.locales = defaultdict(dict)
    self._find_file()

def _find_file(self):
    '''Find all json files'''

You are finding files, find a file. Consider changing the name.

    listing = glob.glob(
        os.path.join(self.path, '*.' + self.format_deserializer))
    for infile in listing:

I'd do

 path = os.path.join(self.path, '*.' + self.format_deserializer)
 for infile in glob.glob(path):

Which I think comes out a bit cleaner

        self._make_loc(infile)

def _make_loc(self, infile):
    '''Store content of the file in a memory'''

Avoid abbreviations, I have no idea what loc is.

    lang = os.path.basename(infile).split('.')[0]

There is a splitext function which you might find useful here. You also don't ue this until way latter. Perhaps you should determine it later.

    if self.format_deserializer == 'json':
        import json
        with open(infile) as fil:
            data = json.load(fil)
    else:
        import yaml
        with open(infile) as fil:
            data = yaml.load(fil)

Instead, you could do

 deseralizer = __import__(self.format_deserializer)
 with open(infile) as fil:
    data = deserializer.load(fil)

That would avoid doing the same thing twice.

    for key, value in data.items():
        if isinstance(value, dict):
            self.locales[key].update(value)
        else:
            self.locales[key].update({lang: value})

def loc(self, key, lang, values=None):
    '''Return the string key, translated to the requested language (if such
    a translation exists, otherwise no traslation occurs). Any other
    parameters passed to the method are injected to the placeholders in the
    string (if present).'''

    if self.locales[key].get(lang) is None:
        return key

Do you actually want to skip formatting this case?

    ret = self.locales[key][lang] if key in self.locales else key

Why are you checking if key is in self.locales? It will be because the previous statement will have put it in regardless. And if it's not there, the first statement would have already returned. Also, its more pythonic to try and fetch it and catch the exception like:

   try:
       ret = self.locales[key][lang]
   except KeyError:
       ret =  key

That way you only lookup the dictionary once. But we can actually do even better by using get with a default

   ret = self.locales[key].get(lang, key)

That, I think, is a very slick approach.

    if values is None:
        return ret
    else:
        return ret % values

Using .format would probably be preferred


Reverse each group of k elements in a list

The core of your solution doesn't suit my taste:

private static String reversedByK(String[] nums, int k) {
    StringBuilder result = new StringBuilder();
    for (int i = k - 1; i < nums.length; i += k) {
        for (int j = i; i - j <= k - 1; j--) {
            result.append(',').append(nums[j]);
        }
    }

    for (int i = nums.length - nums.length % k; i < nums.length; i++) {
        result.append(',').append(nums[i]);
    }
    return result.substring(1);
}

My main gripe is that it works at two different levels: it accepts an array as input, but returns a string.  It's a mild violation of the Single Responsibility Principle.  One consequence is that it uses the assumption that a comma should be used as a delimiter.  It would be more elegant if whichever function performed .split(",") were also responsible for doing String.join(",", …).

Also consider taking advantage of the Scanner more to help you with parsing the input.

private static final Pattern DELIM = Pattern.compile(";|\n|\r");

public static void main(String[] args) {
    …
    try (Scanner file = new Scanner(new File(args[0])).useDelimiter(DELIM)) {
        while (file.hasNextLine()) {
            System.out.println(reversedByK(file.next(), file.nextInt()));
            file.nextLine();
        }
    } catch (FileNotFoundException fnfe) {
        System.err.println("Could not find file.");
    }
}

private static String reversedByK(String list, int k) {
    String[] array = list.split(",");
    reversedByK(array, k);
    return String.join(",", array);
}

private static void reversedByK(String[] array, int k) {
    for (int i = 0; i + k <= array.length; i += k) {
        for (int a = i, b = i + (k - 1); a < b; a++, b--) {
            String swap = array[a];
            array[a] = array[b];
            array[b] = swap;
        }
    }
}

One bonus benefit of this swap-in-place solution is that there is no need for a second loop in reversedByK() to handle the remaining elements.


Constructing file paths for each row of a datatable in C#

One simple trick here would be to take the column processing outside of the row processing (the column metadata should not change while the rows probably will):

using (var metadaDataTable = GetMetaDataTable())
{
    var columns = metadaDataTable.Columns
        .Cast<DataColumn>()
        .Where(col => col.ColumnName != "path_variable")
        .ToList();
    var path_variable = metadaDataTable.Columns
        .Cast<DataColumn>()
        .SingleOrDefault(col => col.ColumnName == "path_variable");
    string path_variable_value;

    foreach (var row in metadaDataTable.Rows.Cast<DataRow>())
    {
        var newfileName = columns.Aggregate(string.Empty, (current, col) => current + (row[col] + "_"));

        newPath = CleanFileName(newfileName);
        path_variable_value = path_variable == null ? null : row[path_variable].ToString();
        // TODO: do something with the path_variable_value before continuing the loop.
    }
}

Note also I've sprinkled a liberal amount of LINQ in there to signify intent rather than mechanism.

Finally, Also surrounded the lifetime of metaDataTable with a using construct as DataTable implements the IDisposable interface.


Go Web API for Sending Emails via Contact Form

A couple thoughts on contact.go.
Global Variables
In general, it's advised to not use global variables like
var mailgunSender string = "email@sender.com"
var mailgunReceiver string = "email@receiver.com"

Instead, there are a few options. You already have a struct definition inside the HandleContact closure, so you could just move them there. You could also pass them as arguments to HandleContact().
The other alternative could be to define a Mailgun struct with those as fields (and could probably include the mailgunDomain and mailgunAPIKey as well). Then define HandleContact as a method on the Mailgun struct, and use the handler by first creating a new Mailgun with the appropriate values like so:
main.go
mg := Mailgun{
    Sender:   "email@sender.com",
    Receiver: "email@receiver.com",
    Domain:   mailgunDomain,
    ApiKey:   mailgunAPIKey,
}
r.HandleFunc("/contact", mg.HandleContact()).Methods("POST", "OPTIONS")

contact.go
type Mailgun struct {
    Sender:   string
    Receiver: string
    Domain:   string
    ApiKey:   string
}
func (m *Mailgun) HandleContact() http.HandlerFunc {
    type body struct {
        Name    string `json:"name"`
        Email   string `json:"email"`
        Message string `json:"message"`
    }

    mg := mailgun.NewMailgun(m.Domain, m.APIKey)
    //etc...

I think the biggest advantage to setting it up this way is that it becomes very testable. You can inject whatever settings are appropriate for testing.
Printing
fmt.Printf() outputs to Stdout by default, so the lines
fmt.Fprintln(os.Stdout, "## New message!")
fmt.Fprintln(os.Stdout, message+"\n")
// ...
fmt.Fprintln(os.Stdout, "Mailgun response:", resp)
fmt.Fprintln(os.Stdout, "Mailgun ID:", id)

are functionally the same as
// Note 2 newlines to keep output identical to your implementation
fmt.Printf("## New message!\n %s\n\n", message)
// ...
fmt.Printf("Mailgun response: %s\n", resp)
fmt.Printf("Mailgun ID: %s\n", id)

Errors
Don't forget to handle the error from json.NewEncoder(w).Encode(b) at the end of contact.go. As the code is written I don't see any reason why it should ever return an error, you're just re-encoding the body you just decoded and echoing it back to the client. But if you ever change your code and the body is modified in some way it could fail silently and lead to debugging headaches.
Also wondering what the purpose of re-encoding is, you could just store and re-use the original value of r.Body. Did you mean to encode and return the response from Mailgun?


For the sake of efficiency, I suggest you use a StringBuilder. The problem here is that String.replace will have to copy a this string applying the character replacement several times. With a StringBuilder you can apply those character replacements in a single pass over the input string. I had this in mind:

public static String to13375p34k(String word) {
    StringBuilder sb = new StringBuilder(word);

    for (int i = 0; i < sb.length(); ++i) {
        char currentCharacter = sb.charAt(i);

        switch (currentCharacter) {
            case 'o':
                sb.setCharAt(i, '0');
                break;

            case 'l':
                sb.setCharAt(i, '1');
                break;

            case 'e':
                sb.setCharAt(i, '3');
                break;

            case 'a':
                sb.setCharAt(i, '4');
                break;

            case 't':
                sb.setCharAt(i, '7');
                break;
        }
    }

    if (sb.charAt(sb.length() - 1) == 's') {
        sb.setCharAt(sb.length() - 1, 'Z');
    }

    return sb.toString();
}


Implement funcionality with handling errrors without throwing exceptions

I can not go with throwing exceptions because it will exit the app.

That's but a grave delusion and misconception about exception. What you have to learn yet, there is an infinite number of different exceptions, and catch (\Exception $e) is not the only way to catch an exception.

So you have a solution in three easy steps

First, define your own kind of exception:

class MyFormHandlerErrorException extends Exception {}

then make your methods throw this certain exception

if (something goes wrong) {
    throw new \MyFormHandlerErrorException('Error message goes here');
}

and then simply catch this only one

public function create() {
    try{
        $resource = $this->bcRepo->get($bcId);
        $dto = EntityDto::fromBc($resource);
        $entity = Entity::fromDto($dto);
        $this->entityRepo->create($entity);
    } catch (\MyFormHandlerErrorException  $e) {
        $this->reporter->add($e);
        return false;
    }
}

bingo! now your specific exceptions will be caught whereas all other error will bubble up to error handler. As simple as that

If you want to define several different exceptions of the same kind, then just create one basic exception and then extend all others from this:

class MyFormHandlerErrorExceptionA extends MyFormHandlerErrorException {}
class MyFormHandlerErrorExceptionB extends MyFormHandlerErrorException {}
class MyFormHandlerErrorExceptionN extends MyFormHandlerErrorException {}

now you could either catch any of them specifically, or catch them all at once by catching the base exception


Functional abstraction to find nth root of a number - Newton raphson

First, congratulations for the work you did : one can easily see that you put some thinking into it and as far as I have tested it, it works.

However, I still have a few comments and most of them are about the fact that you might have tried to be too clever.

Indeed, the use of both recursion and nested functions is a bit too much for my brain. Among other things, it took me a while to spot that the guess argument of the newtons_method is not used (and I am not even sure of it, am I right ?). You could make is easier to grasp by using names conveing more meaning.

Here's my attempt to un-nest functions and to change names (I am fully aware that they are not perfect) :

def recur_improve(next_step, isdone, x, i, max_iterations):
    if i > max_iterations or isdone(x):
       return x
    else:
       return recur_improve(next_step, isdone, next_step(x), i + 1, max_iterations)

def improve(next_step, isdone, initval=1, max_iterations=100):
    return recur_improve(next_step, isdone, initval, 1, max_iterations)

def newtons_method(fn, max_iterations=100):
    def newtons_step(x):
        return x - fn(x) / approx_deriv(fn, x)
    def newtons_isdone(x):
        ALLOWED_ERROR_MARGIN = 0.0000001
        return abs(fn(x)) <= ALLOWED_ERROR_MARGIN
    return improve(newtons_step,
                        newtons_isdone,
                        max_iterations)

Then, the recursion can be easily replaced by a while loop :

def improve(next_step, isdone, initval=1, max_iterations=100):
    x = initval
    i = 1
    while i < max_iterations and not isdone(x):
        x = next_step(x)
        i +=1
    return x

Then, one can see that counting iterations is boring. We have builtins to do this in a concise and efficient way.

def improve(next_step, isdone, initval=1, max_iterations=100):
    x = initval
    i = 1
    for i in range(max_iterations):
        if isdone(x):
            break
        x = next_step(x)
    return x

(I might have introduced on off-by-one error in the iteration counts but I can't be bothered).

Then, instead of passing functions using your original functions, you could just write conditions directly :

def improve(fn, initval=1, max_iterations=100, epsilon=0.0000001):
    x = initval
    for i in range(max_iterations):
        if abs(fn(x)) <= epsilon:
            break
        x -= fn(x) / approx_deriv(fn, x)
    return x

Then you don't even need to have multiple functions anymore and your code boils down to :

def newtons_method(fn, initval, max_iterations=100, epsilon=0.00000001):
    x = initval
    for i in range(max_iterations):
        if abs(fn(x)) <= epsilon:
            break
        x -= fn(x) / approx_deriv(fn, x)
    return x

It seems much clearer to me.

Also, your def nth_root(rootfunc, x) function doesn't seem really useful to me. You could just have :

def cuberoot(x):
    return newtons_method(lambda y: y * y * y - x, x)

result = cuberoot(27**3)

print(result)

And get the result you expect.

Finally, your function deserves some documentation.

Final code :

def approx_deriv(fn, x, dx=0.00001):
    """ some docstring. """
    return (fn(x + dx) - fn(x))/dx

def newtons_method(fn, initval, max_iterations=100, epsilon=0.00000001):
    """ some docstring. """
    x = initval
    for i in range(max_iterations):
        if abs(fn(x)) <= epsilon:
            break
        x -= fn(x) / approx_deriv(fn, x)
    return x

def cuberoot(x):
    """ some docstring. """
    return newtons_method(lambda y: y * y * y - x, x)

result = cuberoot(27**3)

print(result)


Get rid of some len

left_len, right_len, l_len = len(left), len(right), len(l)

Get rid of these, they don't do anything in terms of readability. They also are unnecessary, the len call is not O(n) it is simply O(1).

(Maybe) a library?

Also, although Rosetta code isn't always the most stylistic source, if you look at their solution, the use a pre-built merge. As you say you are "reinventing the wheel", maybe you don't want to do that but something to consider in the future.

Naming

l_ind, r_ind ...

I would write those out in full as left_ind and right_ind.


Stack is a black hole from other code

The first impression I get is you can't get anything back once you put it in the Stack.

peek and pop both return void, so once you've put your value in with push that's the end of it.  I know your methods output to the console, but that's pretty useless to the rest of your program.

When you're writing things like data structures try to put the user interaction outside of the class you're modelling.  Both for input and output.  This will encourage you to define methods that actually allow you to use the data structure in the way that you would in a normal program.  With that in mind, peek at least should return a value.  isEmpty should return a bool.  Depending on your approach, pop could also return the value popped, or it could simply remove the item (however if you go down this approach I would expect it to throw a exception if you pop from an empty stack).

I would also be expecting push to throw an exception if the stack is full.  At the moment, the client has no idea that their value hasn't been added to the stack.


You could have used the bitwise methods in BigInteger.

You could get rid of both .mod(two) and BigInteger two and instead use !__.testBit(0).

  Returns true if and only if the designated bit is set. (Computes ((this & (1<<n)) != 0).)

You could have also used .shiftRight(1) to divide by 2

  Returns a BigInteger whose value is (this >> n). Sign extension is performed. The shift distance, n, may be negative, in which case this method performs a left shift. (Computes floor(this / 2n).)

I haven't put a ton of thought, but I think you could also find a clever way to get rid of 3 with testBit and bitLength, but I think that .compareTo/equals method is alright.

public static int answer(String n) {
    //convert n to BigInteger
    BigInteger x = new BigInteger(n);
    BigInteger three = new BigInteger("3");
    BigInteger y, z;
    int counter = 0;

    //Loop for as long as x is not equal to 1
    while(!x.equals(BigInteger.ONE)){
        //Check if x is divisible by 2
        if(!x.testBit(0)){
            //divide x by 2
            x = x.shiftRight(1);
        } else {
            //subtract x by 1 and then divide by 2 store in variable z
            y = x.subtract(BigInteger.ONE);
            z = y.shiftRight(1);
            //check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
            if(!z.testBit(0) || x.equals(three)){
                x = y;
            } else {
                x = x.add(BigInteger.ONE);
            }
        }
        counter++;
    }
    return counter;
}


The biggest performance problem (for small matrices), and a common mistake, is doing this:

_mm256_extract_epi32(vec_multi, 0) + _mm256_extract_epi32(vec_multi, 1) +_mm256_extract_epi32(vec_multi, 2) +_mm256_extract_epi32(vec_multi, 3) +_mm256_extract_epi32(vec_multi, 4) +_mm256_extract_epi32(vec_multi, 5) +_mm256_extract_epi32(vec_multi, 6) +_mm256_extract_epi32(vec_multi, 7);

This dominates not just horizontal screen space, but also the performance (or lack thereof) of the loop.

Actual extracts (an extract with an index of 0 is turned into vmovd by a reasonable compiler, which is less of a problem) have a throughput of only 1 per cycle on typical CPUs. There are 7 here, so even with just this horizontal addition the loop body could only execute once every 7 cycles (but there is other stuff in there too so it's worse).

There are slightly faster ways to do horizontal sums, for example (not really tuned or anything, just some simple "better than totally naive" hsum)

int hsum_epi32(__m256i x)
{
    __m128i l = _mm256_extracti128_si256(x, 0); //implicit
    __m128i h = _mm256_extracti128_si256(x, 1);
    l = _mm_add_epi32(l, h);
    l = _mm_hadd_epi32(l, l);
    return _mm_extract_epi32(l, 0) + _mm_extract_epi32(l, 1);
}

But that is not great either. Ideally there should just be no horizontal operation in the inner loop. Even more ideally, not anywhere. And that can be arranged: a block of 8 results can be computed by rearranging the computation so that horizontal operations turn into broadcasts. Broadcasting from memory is pretty cheap (naturally it sort of "wastes" the load by loading only one thing, but it's not a slow operation), and there are much fewer of them, so that's probably better.

Sort of like this (to show the general idea, not tested)

for (int i = 0; i < N; i++) {
  for (int j = 0; j < N; j += 8) {
    auto sum = _mm256_setzero_si256();
    for (int k = 0; k < N; k++) {
      auto bc_mat1 = _mm256_set1_epi32(mat1[i][k]);
      auto vec_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j]);
      auto prod = _mm256_mullo_epi32(bc_mat1, vec_mat2);
      sum = _mm256_add_epi32(sum, prod);
    }
    _mm256_storeu_si256((__m256i*)&result[i][j], sum);
  }
}

There is some room for improvement. The memory access pattern through mat2 is not ideal, the inner loop iterates over the rows and only half of a cache line is used every time, for a large enough matrix that means half of every cache miss is wasted. It's probably better to unroll the middle loop by 2 (or 4) again. As a bonus, we get to re-use the broadcast from mat1. Sort of like this (not tested, showing 2x)

for (int i = 0; i < N; i++) {
  for (int j = 0; j < N; j += 16) {
    auto sumA = _mm256_setzero_si256();
    auto sumB = _mm256_setzero_si256();
    for (int k = 0; k < N; k++) {
      auto bc_mat1 = _mm256_set1_epi32(mat1[i][k]);
      auto vecA_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j]);
      auto vecB_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j + 8]);
      auto prodA = _mm256_mullo_epi32(bc_mat1, vecA_mat2);
      auto prodB = _mm256_mullo_epi32(bc_mat1, vecB_mat2);
      sumA = _mm256_add_epi32(sumA, prodA);
      sumB = _mm256_add_epi32(sumB, prodB);
    }
    _mm256_storeu_si256((__m256i*)&result[i][j], sumA);
    _mm256_storeu_si256((__m256i*)&result[i][j + 8], sumB);
  }
}

But, it's probably still possible to improve it, and I didn't test anything.

I've done some testing now, and made some improvement specifically for larger matrices (below N=64 it doesn't really help).

Some results on Haswell, compiled with MSVC[1] 2017, measuring the time (in cycles) per element of the result matrix (so you can mentally compare it to how much time it should take). Time results were eyeballed and rounded to a "typical" value.

       64 128  256  512  1024  2048
naive  90 305 1360 2700  9500   TLE
v1     19  45  170  340  1460  7900
v2     18  40  170  245  1030  4300
v3     22  44   85  150   380   950
v4     17  35   70  150   310   750
v5     18  35   70  140   275   550
ideal  16  32   64  128   256   512

ideal is based on the throughput of vpmulld on Haswell, which is one every two cycles. So per cycle there can be 4 multiplications, we need N of them, so N/4 is the ideal time per element. For small sizes that's not so hard to get near, but for bigger matrices the memory access pattern messes up everything. v1 and v2 are the versions from above.

v3 adds loop tiling to significantly improve the performance for bigger matrices. Understandably this causes some overhead, noticeable for smaller matrices. v4 unrolls the i loop by 2x. Annoyingly, the best choice for the block size depends not only on cache size, but also on the size of the matrix. The times above are not all with the same parameters, but tuned a bit per N.

I'm not sure where to go from here but it seems as though some improvement should still be possible, for bigger sizes it's still a decent factor away from the ideal.

v3:

size_t jb = std::min(512u, N);
size_t kb = std::min(24u, N);

for (size_t jj = 0; jj < N; jj += jb)
{
    for (size_t kk = 0; kk < N; kk += kb)
    {
        for (size_t i = 0; i < N; i += 1) {
            for (size_t j = jj; j < jj + jb; j += 16) {
                __m256i sumA_1, sumB_1;
                if (kk == 0) {
                    sumA_1 = sumB_1 = _mm256_setzero_si256();
                }
                else {
                    sumA_1 = _mm256_load_si256((__m256i*)&result[i][j]);
                    sumB_1 = _mm256_load_si256((__m256i*)&result[i][j + 8]);
                }
                size_t limit = std::min(N, kk + kb);
                for (size_t k = kk; k < limit; k++) {
                    auto bc_mat1_1 = _mm256_set1_epi32(mat1[i][k]);
                    auto vecA_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j]);
                    auto vecB_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j + 8]);
                    sumA_1 = _mm256_add_epi32(sumA_1, _mm256_mullo_epi32(bc_mat1_1, vecA_mat2));
                    sumB_1 = _mm256_add_epi32(sumB_1, _mm256_mullo_epi32(bc_mat1_1, vecB_mat2));
                }
                _mm256_storeu_si256((__m256i*)&result[i][j], sumA_1);
                _mm256_storeu_si256((__m256i*)&result[i][j + 8], sumB_1);
            }
        }
    }
}

v4:

size_t jb = std::min(512u, N);
size_t kb = std::min(24u, N);

for (size_t jj = 0; jj < N; jj += jb)
{
    for (size_t kk = 0; kk < N; kk += kb)
    {
        for (size_t i = 0; i < N; i += 2) {
            for (size_t j = jj; j < jj + jb; j += 16) {
                __m256i sumA_1, sumB_1, sumA_2, sumB_2;
                if (kk == 0) {
                    sumA_1 = sumB_1 = sumA_2 = sumB_2 = _mm256_setzero_si256();
                }
                else {
                    sumA_1 = _mm256_load_si256((__m256i*)&result[i][j]);
                    sumB_1 = _mm256_load_si256((__m256i*)&result[i][j + 8]);
                    sumA_2 = _mm256_load_si256((__m256i*)&result[i + 1][j]);
                    sumB_2 = _mm256_load_si256((__m256i*)&result[i + 1][j + 8]);
                }
                size_t limit = std::min(N, kk + kb);
                for (size_t k = kk; k < limit; k++) {
                    auto bc_mat1_1 = _mm256_set1_epi32(mat1[i][k]);
                    auto vecA_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j]);
                    auto vecB_mat2 = _mm256_loadu_si256((__m256i*)&mat2[k][j + 8]);
                    sumA_1 = _mm256_add_epi32(sumA_1, _mm256_mullo_epi32(bc_mat1_1, vecA_mat2));
                    sumB_1 = _mm256_add_epi32(sumB_1, _mm256_mullo_epi32(bc_mat1_1, vecB_mat2));
                    auto bc_mat1_2 = _mm256_set1_epi32(mat1[i + 1][k]);
                    sumA_2 = _mm256_add_epi32(sumA_2, _mm256_mullo_epi32(bc_mat1_2, vecA_mat2));
                    sumB_2 = _mm256_add_epi32(sumB_2, _mm256_mullo_epi32(bc_mat1_2, vecB_mat2));
                }
                _mm256_storeu_si256((__m256i*)&result[i][j], sumA_1);
                _mm256_storeu_si256((__m256i*)&result[i][j + 8], sumB_1);
                _mm256_storeu_si256((__m256i*)&result[i + 1][j], sumA_2);
                _mm256_storeu_si256((__m256i*)&result[i + 1][j + 8], sumB_2);
            }
        }
    }
}

Yet an other version, with even more tiling and with rearranging matrix 2. Added to the table of times above. Of course, some time can be saved if that matrix can be assumed to already be in that order, but I counted the rearranging in the benchmarks. That overhead scales as O(N²) while the meat of the algorithm scales as O(N³) so for a large matrix it does not represent a significant cost anyway.

It seems to behave well now, staying around 110% of the theoretical optimum for any size I test. Perhaps some small tweaks are still possible. For example, unrolling the i loop by 4 instead of 2 improved it slightly in my tests, but the difference is kind of small.

v5:

size_t ib = std::min(256, (int)N);
size_t jb = std::min(512, (int)N);
size_t kb = std::min(16, (int)N);

int *mat2 = (int*)_aligned_malloc(N * N * sizeof(int), 32);
size_t m2idx = 0;
for (size_t jj = 0; jj < N; jj += jb)
{
    for (size_t kk = 0; kk < N; kk += kb)
    {
        for (size_t j = jj; j < jj + jb; j += 16)
        {
            for (size_t k = kk; k < kk + kb; k++)
            {
                auto vecA_mat2 = _mm256_loadu_si256((__m256i*)&mat2in[k][j]);
                auto vecB_mat2 = _mm256_loadu_si256((__m256i*)&mat2in[k][j + 8]);
                _mm256_storeu_si256((__m256i*)&mat2[m2idx], vecA_mat2);
                _mm256_storeu_si256((__m256i*)&mat2[m2idx + 8], vecB_mat2);
                m2idx += 16;
            }
        }
    }
}

for (size_t ii = 0; ii < N; ii += ib) {
    for (size_t jj = 0; jj < N; jj += jb) {
        for (size_t kk = 0; kk < N; kk += kb) {
            for (size_t i = ii; i < ii + ib; i += 2) {
                for (size_t j = jj; j < jj + jb; j += 16) {
                    size_t m2idx = (j - jj) * kb + kk * jb + jj * N;
                    __m256i sumA_1, sumB_1, sumA_2, sumB_2;
                    if (kk == 0) {
                        sumA_1 = sumB_1 = sumA_2 = sumB_2 = _mm256_setzero_si256();
                    }
                    else {
                        sumA_1 = _mm256_load_si256((__m256i*)&result[i][j]);
                        sumB_1 = _mm256_load_si256((__m256i*)&result[i][j + 8]);
                        sumA_2 = _mm256_load_si256((__m256i*)&result[i + 1][j]);
                        sumB_2 = _mm256_load_si256((__m256i*)&result[i + 1][j + 8]);
                    }

                    for (size_t k = kk; k < kk + kb; k++) {
                        auto bc_mat1_1 = _mm256_set1_epi32(mat1[i][k]);
                        auto vecA_mat2 = _mm256_loadu_si256((__m256i*)(mat2 + m2idx));
                        auto vecB_mat2 = _mm256_loadu_si256((__m256i*)(mat2 + m2idx + 8));
                        sumA_1 = _mm256_add_epi32(sumA_1, _mm256_mullo_epi32(bc_mat1_1, vecA_mat2));
                        sumB_1 = _mm256_add_epi32(sumB_1, _mm256_mullo_epi32(bc_mat1_1, vecB_mat2));
                        auto bc_mat1_2 = _mm256_set1_epi32(mat1[i + 1][k]);
                        sumA_2 = _mm256_add_epi32(sumA_2, _mm256_mullo_epi32(bc_mat1_2, vecA_mat2));
                        sumB_2 = _mm256_add_epi32(sumB_2, _mm256_mullo_epi32(bc_mat1_2, vecB_mat2));
                        m2idx += 16;
                    }
                    _mm256_storeu_si256((__m256i*)&result[i][j], sumA_1);
                    _mm256_storeu_si256((__m256i*)&result[i][j + 8], sumB_1);
                    _mm256_storeu_si256((__m256i*)&result[i + 1][j], sumA_2);
                    _mm256_storeu_si256((__m256i*)&result[i + 1][j + 8], sumB_2);
                }
            }
        }
    }
}

_aligned_free(mat2);

[1] MSVC is a C++ compiler so my examples are technically not C, but it's really about the approach anyway and it's trivial to convert.


Your code is easy to read, formatting is pretty consistent, and does indeed do what it is supposed to as far as I can tell, so that's a good. I just have a few suggestions.

class Stack {
public:

Well if everything is public, use a struct instead, it will save you a few keystrokes. But the size_ and top members probably shouldn't be public - they're not meant to be inspected (much less changed) from outside your class.

bool empty() { return top == 0; }
while (current != 0) {

Prefer nullptr instead of 0 (you already did that in other places).

void push(T data) {
  if(empty()) {
    top = new Node(data);
    size_++;
  } else {
    top = new Node(data, top);
    size_++;
  }
}

You can simplify this: if the stack is empty, then top is null, and new Node(data) does the same thing as new Node(data, nullptr). So you don't need the conditional, you can simplify it to:

void push(T data) {
  top = new Node(data, top);
  size_++;
}

The pop function will fail to compile for e.g. Stack<std::string>: you can't construct a string from -1. Your only real option here is to throw an exception if pop is called on an empty stack. (You should look at the standard container's interface: they have separate top() and pop() members. See this answer for example as for why it is done that way.)

And your destructor is a bit too complex, you don't need the two special cases as they'll be handled by the main loop just fine: if empty(), top is null so the while loop simply won't run. If there's just one element, the while loop will run just once. So you can cut it down to:

~Stack()
{
  while (top != nullptr) {
    Node *next = top->next;
    delete top;
    top = next;
  }
}

One last observation - what happens if someone writes this:

Stack<int> s1;
s1.push(1);
Stack<int> s2 = s1;
s1.pop();
s2.pop();

Unfortunately, this will compile but produces undefined behavior - the second pop will access free'd memory. You should either implement the rule of three (sometimes now called the "rule of 5" taking into account move constructor and move assignment), or simply not allow copying of your stacks:

Stack(Stack const&) = delete;


ReentrantLock with priorities for waiting threads

After calling shutdown(), the shutdown boolean may never get checked. The Thread may be stuck in waitingQueue.take().

It's probably not a good idea to catch and swallow InterruptedException.

Considering those two points together, it makes sense to remove the Thread and use Executors.newSingleThreadExecutor() instead, and delegate to its shutdown() method.

Finally, it's fairly low-level and error prone to use wait() and notifyAll(). Using notify() is even riskier than notifyAll(). I'd recommend using a Condition instead.


PowerShell - Execute Windows Task Scheduler

Your instincts are good to dislike that bit of code.

Whenever you can, you should put code in data structures rather than in control statements. It makes the code clearer and easier to maintain.

So for instance you could put your settings in a hash table like this:

$FrequencySettings = @{
    Once     = @{Once   = $true}
    Daily    = @{Daily  = $true}
    Weekly   = @{Weekly = $true; WeeksInterval = 1; DaysOfWeek = 'Monday'}
    Monthly  = @{Weekly = $true; WeeksInterval = 4; DaysOfWeek = 'Monday'}
    }

# Let's test it:
$FrequencyParams = $FrequencySettings['Monthly']
New-ScheduledTaskTrigger @FrequencyParams -At "0:00"

I haven't checked that the particular settings I've put in above are all correct. I just want to show you the basic idea.


There are a few things that you might consider here, to improve readability, maintainability, and (indirectly through those qualities), reliability.

As a guideline, if a piece of code goes over 10 lines or statements, it is probably about time to break it up into functions.

In this case, I might consider breaking it up into following functions:

public function getEmailInput() {}
public function getFileInput() {}
public function insertIntoDatabase() {}
public function generatePdf() {}
public function sendConfirmationEmail() {}
//Maybe some others, as you see fit

This will allow give you a little more freedom to update the steps as that inevitably becomes necessary without as much risk of breaking other parts or having to remember how the entire program works.

On the JavaScript side, it looks like this is the kind of script that needs to fail safe, so I might consider checking for success rather than failure, like so:

.done(function (response) {
    if(response === 'success'){ //make sure we got the response we needed
        window.location.replace('failure.html');
    } else {
        window.location.replace('success.html');
    }
}).fail(function (jqXHR, textStatus) {
    console.log(textStatus);
});


I don't know what's up with the spacing in the docstring, but fix it.

Your memoize_all doesn't work with everything:

memoize_all(int)(1)
#>>> Traceback (most recent call last):
#>>>   ...
#>>> AttributeError: type object 'int' has no attribute 'func_code'

I suppose this doesn't bother you much, but it irks me ;).

Consider

for i, arg in enumerate(args):
    arg_dict[arg_names[i]] = args[i]

There's no point doing args[i]; it's just arg. Further, one should do

for i, (name, arg) in enumerate(zip(arg_names, args)):
    arg_dict[name] = arg

But then one can just do

arg_dict = dict(zip(arg_names, args))

You could even use

arg_dict = dict(zip(arg_names, args), **kwargs)

You try and save this with

key = pickle.dumps(arg_dict)

I'm not at all fond of this method. pickle is a bit fragile and more complicated than I would expect. I would personally do something like

key = frozenset(arg_dict.items())

If you skip generating arg_dict, this is

key = frozenset(kwargs.items()) | frozenset(zip(arg_names, args))

This does prevent accepting mutable arguments, but it's normally best to enforce purity before caching arguments anyway.

You then have just

def cached(*args, **kwargs):
    arg_names = func.func_code.co_varnames
    key = frozenset(kwargs.items()) | frozenset(zip(arg_names, args))

    if key not in cache:
        cache[key] = func(*args, **kwargs)
    return cache[key]

Note that in Python 3, this would be better with a signature object:

import functools
from inspect import signature

def memoize_all(func):
    """
    This is a caching decorator. It caches the function results for
    all the arguments combinations, so use it with care. It does not
    matter whether the arguments are passed as keywords or not.
    """
    cache = {}
    func_sig = signature(func)

    @functools.wraps(func)
    def cached(*args, **kwargs):
        bound = func_sig.bind(*args, **kwargs)
        key = frozenset(bound.arguments.items())

        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return cached


Unit tests for os.scandir/scantree a directory

General

You use what seems to be a non-standard docstring style. That's fine, but it's actually quite close to the RST / Sphinx syntax. An overview of the various styles can be found here. It's a good idea to pick one you like and stick to it, or to simply enforce your own style, but mixing styles will certainly result in confusion. 'Why is this RST not being interpreted correctly?!' or 'Why does this perfectly readable docstring have random pieces of RST syntax thrown in?'
These two lines:

if not path:
    path = self.path

Should be a red flag. Let's get this straight. There's a path associated with self, and a custom path can be passed as a parameter to the method. This means that map_directory() should either be @staticmethod'ed, or self.path should not exist. Without context, there's no way of telling which is the right solution, but this is clearly wrong.
When you raise the exception (by the way, BullShitError, really?) you tell the developer what went wrong (good) but don't give them a list of valid options (bad). Not everyone is going to read through the documentation immediately when they get an exception. To a reasonable extent, exception messages should tell the developer exactly what to do to prevent the exception in the future.

Questions

Barely. The only thing I don't think is worth testing is whether the return type is a generator. The other tests look sane and useful, so keep them.
In a controlled testing environment, you might as well have a tuple of the entries and check if the method call matches the expected results.
That's impossible to tell if you don't show us what self.scan_tree() actually does.


Given a byte string S of length l, obtain the string D of length l-1 as D(i) = S(i) * S(i+1)

Inconsistent addressing of d
d is an array of 2-byte elements (d times l dw 0) and mov [d + esi], ax indexes into it with esi as the offset. However, esi is increased by 1 every iteration, so the resulting access pattern is that the stores keep stepping half on top of the previous store, shown by such a diagram: (storing -3, -12 and 28 in sequence)
FD FF
   F4 FF
      1C 00

This is possible to do, but probably unintentional.
Normally my recommendation would be to increase the register by 2 in the loop, but esi is also used to index s so that won't work. You can change the store to double esi though, for example:
mov [d + esi*2], ax

Or,
mov [d + esi + esi], ax

If you change d to be an array of bytes then the store should be mov [d + esi], al, with the original address but storing only 1 byte. Storing overlapping words would put the right data in d, but it's strange and stores a stray byte just after the end of d.
Calling exit
exit performs C library termination procedures, but the C library runtime environment wasn't used or even initialized (this code is in start, not main), so it's not necessary. It makes more sense to call ExitProcess (kernel32.dll), or just return (that does not work on Linux, but this is a Windows program and there it does work).
The loop instruction
loop is not great, it has some niche uses but typically it should be avoided. jecxz by contrast is OK, just unusual.
Minor things
The best way to zero esi isn't mov esi, 0, it's xor esi, esi, unless the flags must not be affected.
The two loads of the current and next element of S could be merged into a single word load, if you want. For example mov ax, [s + esi] followed by imul ah.


Shifting an 128-bit integer consisting of four 32-bit integers

Well, I don't have a 32 bit build environment available just now.  While I wrote this for 64bit, I'm only processing 32bits at a time.  I haven't timed it, so I can't say if it is faster than yours, but it has no jumps.  At the very least, it might give you some ideas.

If the comments look like copy/paste from some C code, there's a reason for that...

; void Shl(int s, DWORD *m)
; Shift the 4 DWORDs at m left by s bits

Shl proc

; s - ecx
; m - rdx

; rax, rcx, rdx, r8-r11 are scratch under Windows 64bit calling convention

    mov r8d, [rdx + 12]     ; t1 = m3; MSB
    mov r9d, [rdx + 8]      ; t2 = m2;
    mov r10d, [rdx + 4]     ; t3 = m1;
    mov r11d, [rdx]         ; t4 = m0; LSB
    xor eax, eax            ; t0 = 0;

    cmp ecx, 32
    cmovge r8d, r9d       ; t1 = t2;
    cmovge r9d, r10d      ; t2 = t3;
    cmovge r10d, r11d     ; t3 = t4;
    cmovge r11d, eax      ; t4 = t0;

    cmp ecx, 64
    cmovge r8d, r9d       ; t1 = t2;
    cmovge r9d, r10d      ; t2 = t3;
    cmovge r10d, r11d     ; t3 = t4;

    cmp ecx, 96
    cmovge r8d, r9d       ; t1 = t2;
    cmovge r9d, r10d      ; t2 = t3;

    cmp ecx, 128
    cmovge r8d, r9d       ; t1 = t2;

    and ecx, 31

    shld r8d, r9d, cl       ; t1 = (t1 << s) | (t2 >> (32 - s));
    shld r9d, r10d, cl      ; t2 = (t2 << s) | (t3 >> (32 - s));
    shld r10d, r11d, cl     ; t3 = (t3 << s) | (t4 >> (32 - s));
    shl r11d, cl            ; t4 = t4 << s;

    mov [rdx + 12], r8d  ; m[3] = t1;
    mov [rdx + 8], r9d   ; m[2] = t2;
    mov [rdx + 4], r10d  ; m[1] = t3;
    mov [rdx], r11d      ; m[0] = t4;

    ret

Shl endp

Yes, I'm using 7 registers, but if you push everything and use EBP, I think you'll be able to squeeze this in.  Another reason I prefer 64bit.


If something is mandatory then use private setters and constructor arguments, and validate in the constructor (TaxLevel) [1];
Use collection initializer notation [2];
DeterminateTaxLevels should be private and called from the constructor (I would actually make it a simple attribution in the constructor);
DeterminateTaxLevels should have a better name like LoadTaxLevels, because it does not "determine" anything;
DeterminateTaxLevels has no reason to return bool - why does it?;
Salary is misspelt;
Either call the salary "bruto" or "in Nis" - you should be consistent, and I advise "bruto" because it means more than some random TLA like NIS (whatever it is);
As @Gene S said, try to follow coding standards: use brackets in ifs, use line-breaks after ifs, use camelCase on parameter names and not PascalCase, etc...

footnotes
[1]:
private class TaxLevel
{
    /// <summary>
    /// The money count that the tax applies to.
    /// </summary>
    public decimal Money { get; private set; }
    /// <summary>
    /// The tax level where 1.0 is 100% tax.
    /// </summary>
    public decimal TaxDeduction { get; private set; }

    public TaxLevel(decimal money, decimal taxDeduction) {
        if (money < 0 ) {
            throw new ArgumentOutOfRangeException("Money must be grater than 0");
        }
        if (taxDeduction < 0 || taxDeduction > 1.0m) {
            throw new ArgumentOutOfRangeException("TaxDeduction must be between 0.0 and 1.0");
        }
        Money = money;
        TaxDeduction = taxDeduction;
    }
}

[2]:
_TaxLevels = new List<TaxLevel>() {
    new TaxLevel {Money = 4770m, TaxDeduction =  0.10m },
    new TaxLevel { Money = 3700, TaxDeduction = 0.14m },
    // ...
    new TaxLevel { Money = decimal.MaxValue, TaxDeduction = 0.42m },
};


Finding permutation from given lexicographical rank

Style

Python has a style guide called PEP 8 which is definitly worth reading and and worth following if you do not have good reasons not to. In you case, your function name for instance is not compliant to PEP8. You'll find tools online to check your code compliancy to PEP8 in a automated way if you want to.

API / Function signature

Your function signature is a bit unclear. This situation often happens when recursive solutions are applied. A good way to solve this would be to define another function calling the complicated function with the right arguments or to use default arguments.

If I understood everything properly, the point if to get the n-th performutation from a list. A simple way to do so would be to have a function taking the rank and the lst as an argument.

Testing

In order to keep things simple, it is a good option to write a simple (even if inefficient) solution to be able to see patterns and/or write tests to ensure that your more efficient works and is indeed more efficient.

A very simple solution could be written like this :

def from_rank(rank, lst):
    sorted_perm = sorted(itertools.permutations(lst))
    return sorted_perm[rank]

And you can write some simple tests like this :

tests_cases = ([], [1], [1, 2], [1, 2, 3], [3, 2, 1], [2, 2], [2, 2, 2])
for lst in tests_cases:
    for i in range(math.factorial(len(lst))):
        a = list(from_rank(i, lst))
        b = list(from_rank2(i, lst))
        if a != b:
            print(i, a, b)

Another more simple solution

Your solution involves both recursion and mutations of data. This can make things very hard to understand. A more simple idea could be to say that from the rank, it is easy to know which element will be the first of the permatation. Indeed, if your list has n elements, you know that there are (n-1)! permations of length n-1 and so the rank-th permutation will have for its first element the rank / ((n-1)!)-th elements. You can repeat the same thinking for a smaller list consistent of the remaining elements with the remaining part of the rank.

This can be written:

def from_rank2(rank, lst):
    my_lst = sorted(lst)
    ret = []
    while my_lst:
        fact = math.factorial(len(my_lst) - 1)
        idx, rank = divmod(rank, fact)
        ret.append(my_lst.pop(idx))
    assert rank == 0  # invalid rank - out of range
    return ret

Please note that this solution does not seem to handle very well lists with repeated elements. You can easily enhance your test suite to show it :

tests_cases = ([], [1], [1, 2], [1, 2, 3], [3, 2, 1], [2, 2], [2, 2, 2], [2, 2, 3], [1, 2, 5, 4, 3, 2])


Web scraping data from US postal zip codes

"5 min to fetch 70-100 records" seems pretty slow. Even though, you are fetching the same URL 3 times per Zip Code, this still seems slow.

    For i = 1 To 3
        cell.Offset(0, i).Value = dataScrape("th", TargetElement(i), "td")
    Next i

Avoid using Global variables whenever possible.  Pass the values as parameters instead.

Turning off Application.ScreenUpdating and setting Application.Calculation = xlCalculationManual will speed up the writing the data to the Worksheet.

The code below processed 200 records in 41 seconds.

Refactored Code

Sub ZipCodeScrape()
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Const BASE_URL = "https://www.unitedstateszipcodes.org/"
    Dim doc As MSHTML.HTMLDocument, cell As Range

    For Each cell In Range("C2", Range("C2").End(xlDown))
        Set doc = getDocument(BASE_URL & Format(cell.Value, "00000"))
        If Not doc Is Nothing Then
            cell.Offset(0, -2).Value = getPrimaryCity(doc)
            cell.Offset(0, -1).Value = getState(doc)
            cell.Offset(0, 1).Value = getTDByTH(doc, "County: ")
            cell.Offset(0, 2).Value = getTDByTH(doc, "Population")
            cell.Offset(0, 3).Value = getTDByTH(doc, "Median Home Value")
        End If

    Next cell
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Private Function getTDByTH(doc As MSHTML.HTMLDocument, Heading As String) As String
    Dim post As Object
    For Each post In doc.getElementsByTagName("TH")
        If post.innerText = Heading Then
            getTDByTH = post.ParentNode.getElementsByTagName("TD")(0).innerText
            Exit For
        End If
    Next post
End Function

Private Function getPrimaryCity(doc As MSHTML.HTMLDocument) As String
    Dim PrimaryCity As String
    PrimaryCity = getTDByTH(doc, "Primary City:")
    getPrimaryCity = Split(PrimaryCity, ",")(0)
End Function

Private Function getState(doc As MSHTML.HTMLDocument) As String
    Dim PrimaryCity As String
    Dim PrimaryCityArray() As String
    PrimaryCity = getTDByTH(doc, "Primary City:")
    PrimaryCityArray = Split(PrimaryCity, ",")
    getState = Split(PrimaryCityArray(1), " ")(1)
End Function

Private Function getDocument(URL As String) As MSHTML.HTMLDocument
    Dim doc As MSHTML.HTMLDocument
    With New MSXML2.XMLHTTP60
        .Open "GET", URL, False
        .send
        If .readyState = 4 And .Status = 200 Then
            Set doc = New MSHTML.HTMLDocument
            doc.body.innerHTML = .responseText
            Set getDocument = doc
        Else
            Debug.Print "URL Not Responding:  "; URL, "Ready state: "; .readyState, "HTTP request status: "; .Status
        End If
    End With
End Function

The Multi-threaded VBA that you referred to would be considerably faster.


For the moment I'll concentrate on the left to right version. Most of the same comments apply to the right to left version as well though.

int atoiLefttoRight(char *s){

Since you're not going to modify the original string, the parameter should be char const *s.

    int num = 0;
    int negative = 1;
    if(s)
        {
        if(*s == '-')

This is an...unusual indentation style. Personally, I'd normally prefer:

if (s) {
    if (*s == '-')

Others prefer:

if (s)
{
    if (*s == '-')

Given the degree to which these two styles dominate, I'd nearly always choose between them rather than trying to invent yet another.

            {
            negative = -1;
            s++;

Although it's unlikely (in the extreme) to make a difference in this case, in cases like this where you can use either prefix or postfix increment (or decrement) I'd choose the prefix form, making this ++s;

            }
            while(*s && (*s <= '9') && (*s >= '0'))

You have this indented under the if statement as if it were controlled by the if statement (but it's not).

I'd also prefer to use isdigit to determine whether a character is a digit.

Finally, this can fail to correctly convert at least one legitimate input. For example, given a 16-bit int, an input of -32768 is legitimate meaningful--but this won't convert it correctly, because it tries to represent the digits as a positive signed number (but the largest signed 16-bit number is 32767).

With a 32-bit or 64-bit int, the number gets larger but the same basic idea applies (and if you had an even larger int, such as 128-bit, the same would still be true--bigger number, but still a number where it would fail).


Your logic seems fine to me, but bear in mind I'm not very experienced in that either, so perhaps someone more experienced with algorithms will find some ways to improve.

Documentation & Naming

It's clear from your code that your intention is to have well-documented code (with is a great habit). It's the first thing that I noticed looking at your code so that's why I am mentioning it specifically.

It feels a bit like your documentation is overcompensating for things that could be just named a bit more clearly. For example:

/**
 * Created by user1 on 8/7/15.
 * my selection sort version
 */

class MySelSort {

    //reference to array
    private int[] arr;
    //num. of elements
    private int n;

I think something like this would be better:

class SelectionSort {

    private int[] arrayToBeSorted;
    private int numberOfElements;

It's a bit more wordy, but completely unambiguous on the other hand. I would also encourage to use Javadoc.

While something like this is OK:

//constructor
public MySelSort(int max) {
    //create array with size
    arr = new int[max];
    //set current items to 0
    n = 0;
}

This would be more like what you see in bigger Java programs:

/**
 * Constructor.
 * <p>
 * Creates an array of integers with a maximum size.
 * The beginning index of the array is initialized to 0.
 *
 * @param maxSize  The maximum size of the array, not null
 */
public SelectionSort(int maxSize) {
    arrayToBeSorted = new int[maxSize];
    numberOfElements = 0;
}

This method's parameter naming is misleading:

//--------------------------------------------------
//insert()
public void insert(int key) {

    //insert key to relevant place in array
    arr[n] = key;
    //increase size of array
    n++;
}

What you call the key is actually rather the value to be inserted at the current key (or index). This would be a bit easier to spot with better naming. Going back to the top, we could name n to elementNumber instead of numberOfElements (which I first named only accordingly to your comment, which again was a bit misleading).

/**
 * Inserts a value at a given key in the array.
 *
 * @param value  The value to be inserted, not null
 */
public void insert(int value) {
    arrayToBeSorted[elementNumber] = value;
    elementNumber++;
}

And so on with documentation and naming. When you get to the end, you get a much clearer picture of what is happening, with no comments needed at all in your main class:

public class SelectionSortApp {

    public static void main(String[] args) {

        SelectionSort arrayToBeSorted = new SelectionSort(100);

        arrayToBeSorted.insert(40);
        arrayToBeSorted.insert(60);
        // ...

        System.out.println("Prior to sorting...");
        arrayToBeSorted.display();

        arrayToBeSorted.selSort();

        System.out.println("After sorting...");
        arrayToBeSorted.display();

    }
}


I cannot think of a clean way to extract the validation logic.

All validation logic should be in an appropriate "validation service" class as @meWantToLearn said.

I assume something like this is possible in FluentValidation:

public class PollVoteValidator : AbstractValidator<Poll,VoteInput>

If not then make a simple class that contains both of these and then create a validator for that:

public class PollInput {
    public Poll {get; set;}
    public VoteInput {get; set;}
}

public class PollVoteValidator : AbstractValidator<PollInput>

Validation Separation of Concerns

Validations such as if (poll == null) belong in a PollValidator class and if (poll.VoterIps.Contains(voterIp)) in a VoterIpsCollection class.

Even if you want to check for null method arguments up front (and that will simplify downstream control logic), the above still applies.

Validation Coordination

The PollVoteValidator would coordinate everything perhaps, with logic, somewhere, like this:

public class PollVoteValidator {
    public ValidateResults Validate (poll, voteInput) {
        var pollValidateResults = myPollValidator.Validate(poll);
        var voteInputValidateResults = myVoteInputValidator.Validate(voteInput);
        // I hope poll is not null!
        var voterIpsCollectionResults = myVoterIpsCollectionValidator.Validate(poll.VoterIps);

        if(/* validations above pass */)
            pollVoteValidatorResults = mypollVoteValidator.Validate(poll, voteInput);

        // consolidate validation results as desired (error messages)
        // for return to the caller

        return pollVoteValidatorResults;
    }
}

One More Thing

This: var voterIp = Request.GetOwinContext().Request.RemoteIpAddress; seems "orphaned" from an OO perspective. voterIp feels like a Voter class property, so maybe you should instantiate a Voter; this implies a "validation service" class for Voter.

The above Voter class stuff may seem like overkill, but there is no OO principle that says "if something seems simple, ignore OO principles".


Since it seems you only need the transactions value once, you might as well just make an attribute reader that does the work:

  def transactions
    external_card_balance.all
  end

No real need to break in down into "fetch and store" and "read from store and iterate", when you can just say "fetch and iterate".

If you're going to be using the transactions collection multiple times, you can either memoize it:

  def transactions
    @transactions ||= external_card_balance.all
  end

Or you can simply pass the transactions as a constructor argument. The latter moves the responsibility for fetching transactions to the user of the class, rather than the class itself, which may make more sense - or it may not. Your call.


Vehicle, Components and Car relationship

Thanks for sharing your code.

OOP doesn't mean to "split up" code into random classes.

The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.

Doing OOP means that you follow certain principles which are (among others):

information hiding / encapsulation
single responsibility
separation of concerns
KISS (Keep it simple (and) stupid.)
DRY (Don't repeat yourself.)
"Tell! Don't ask."
Law of demeter ("Don't talk to strangers!")

We create a new class if we need to implement new behavior not yet present nor belonging to any existing class.

In your example the class Car does not (yet) add any new behavior neither to the class Vehicle which it extends nor to the program as a whole. Therefore it is not needed (as well as your planned class Truck) and Vehicle should not be abstract. If you need to identify different vehicle types you might introduce a vehicleType property of type String...


Changing a character in a string at a specified index position

The fact that your function is named change_char_at and the first parameter is named ch both suggest that ch should be a single character.  However, the function could easily be abused to splice in any number of characters at that location, including zero.  So, you might as well make it obvious and rename the function to string_splice() or something.

I'm not a fan of this function, though.  Basically, it's a long-winded way to do s[:indx] + ch + s[indx + 1:] with some validation.

if type(ch) is not str seems pointless.  If ch is not a string, it would naturally fail with a TypeError anyway during concatenation.
if type(s) is not str might be useful validation, but it also goes against Python's duck-typing philosophy.
if … not len(s) > 0 is an unjustified special case.  If you're going to allow splicing in an arbitrary number of characters, then why shouldn't one be allowed to add something to an empty string?  As a consequence of this failure case, the caller will also need to put in a special case to work around this restriction.
if not(indx >= 0 and indx <= length) is weird because length isn't actually the length of the string; it's one less than that.  It could be more succinctly written as if not 0 <= indx < len(s).  But Python's negative indexing is a feature, not a bug.  Why would you want to defeat the convenience?

In summary, if you want to do s[:indx] + ch + s[indx + 1:], then it's probably best to just write that.  If you want to write this function anyway, I recommend dropping most, if not all, of the validation.

If you want to do a lot of single-character replacements, then you would probably want to convert the string to a list or bytestring instead.


Well, first of all, your closure doesn't have to create a function. This will work just as well:

function createPromise() {
     var p = $.Deferred();
     promises.push(p);
     return p.resolve; // Doesn't create an anonymous function
};

Second of all, if you're doing this pattern a lot, I would make a generic method that lets you convert any function that accepts a callback to one that returns a promise:

function callbackToPromise(func) {
    return function() {
        var args = $.makeArray(arguments);

        var p = $.Deferred();
        args.push(p.resolve); // Add the deferred as a callback

        func.apply(this, args);

        return p.promise();
    };
}

var improvedFoo = callbackToPromise(foo);

function bar(data, cb) {
    var promises = [];
    for (var i = 0; i < data.length; i++) {
         promises.push(improvedFoo(data[i]));
    }
    $.when.apply($, promises).then(cb);
}

$.when really should accept an array of Deferred's as an argument, but until that feature is added, I don't think there's a way to avoid using .apply here, except to add another helper function:

function when(promises) {
    return $.when.apply($, promises);
}

function bar(data, cb) {
    var promises = [];
    for (var i = 0; i < data.length; i++) {
         promises.push(improvedFoo(data[i]));
    }
    when(promises).then(cb);
}

A slightly less-readable version can eliminate the promises variable entirely, though I prefer the more-readable version above:

function bar(data, cb) {
    when($.map($.makeArray(data), function(item) {
        return improvedFoo(item);
    })).then(cb);
}


How to reduce this archive detection function and make it supports wildcards

Your regex can be shortened using {x}, which repeat a pattern x times. So your third regex would become:

exp = new Regex(string.Concat(Path.GetFileNameWithoutExtension(originalFile),
                              "_[0-9]{8}_[0-9]{3}",
                              Path.GetExtension(".log")));

As far as wildcards, if you use * it will be entered into the regex. It looks from MSDN that it won't be removed from the file name when you call GetFileNameWithoutExtension(). However, I was unable to test this as I don't have Visual Studio on my computer. It worked as a wildcard on my regex tests.


Ideas I had in mind were simply using char[] instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.

Yes, that will be faster. Go ahead and write it :-)
Instead of Strings like strResult and strBuffer you could use StringBuilders (although using char is probably faster). StringBuilder is mutable and would be faster than using Strings. StringBuilder also supports insert(offset, char) but also has a reverse method.
I'd rename  strResult to result (to avoid Hungarian notation) and strBuffer to the more descriptive currentWord.

if (str.charAt(i) != ' ') {
    ...
}
else if (str.charAt(i) == ' ') {
    ...
}

The following is the same, you don't need the second, inverted condition:

if (str.charAt(i) != ' ') {
    ...
} else {
    ...
}

You might want to use a more another check for spaces. Currently it handles tabs (\t) as normal characters and

"hi\tthere\tcow"

will be

"woc\tereht\tih"

Here is a slightly improved version with StringBuilders:

public static String reverseWord(String str) {
    int len = str.length();
    StringBuilder result = new StringBuilder();
    StringBuilder currentWord = new StringBuilder();
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != ' ') {
            currentWord.insert(0, str.charAt(i));
        } else {
            result.append(currentWord).append(" ");
            currentWord.setLength(0);
        }
    }
    result.append(currentWord);
    return result.toString();
}


Hacker Rank: Counting names with prefix matches using a trie

You don't validate your input.  If the user enters a string with no space in it, you'll get an exception.

s[0] is a character, so why do you convert it to a string to convert it back to a character?

You should avoid allocating _trieArray until you need it.  Otherwise you'll allocate a bunch of memory you don't use (in all your leaf nodes).

You don't need to use _findCount.  Your private find method can just return that value.

As an additional exercise, rewrite add to not be recursive, and avoid making all those (sub)string copies.


Setting the path to toolbarAssociatedXibName, with fallback

In the spirit of DRY, how about:

NSString *path = nil;
if (delegate && [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)]) {
    path = [delegate toolbarAssociatedXibName:_toolbar];
    if (![[NSBundle mainBundle] pathForResource:path ofType:@"nib"]) {
        IFLog(@"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).", path, _identifier);
        path = nil;
    }
}
if (!path) path = _identifier;

In your pseudocode:

Variable declaration (set to null value)
If there is an option to set the variable to a custom value
    Set it to that custom value
    If the value is not valid
        Log the error
        Set the value back to null
If value is null
    Set the value to a specified default


Force ConcurrentDictionary in a Singleton Registry to Collect Removed Items/Space

Apparently, collections are optimized for performance over memory management. So I'm afraid it is up to us, consumers of the .NET Framework, to implement memory management on collections that grow big and require lots of manipulations.

I would use a scheduled task to periodically make a new instance of the queue, with the values of the previous instance, and clearing the old instance.


Bash script to clear files not matching a given extension

My real concerns with the script are:

cleantex path/to/file.tex will not delete files in that path, but in the current directory.
you should check the actual .tex file exists before you delete all the things around it.
the brace-expansion is unnecessarily complicated...... especially when combined with the extended glob !(*tex). I would manually resolve the brace-expansion so that there is only one complicated operation on that line.
I would use actual glob-expansion and only delete existing files.... and not use the -f option on rm (which does more than just suppress the error message if files do not exist....)


Printing the most used words from phrases

As others have pointed out the most obvious improvements already, I would like to talk about Java 8. Maybe you cannot use it yet, but I would recommend looking into it and this answer should proivde useful for anyone reading this.

My main focus point here will be designing the code such that it will logically do what it is supposed to do.

You have a method in which you take a List<String[]> as argument, and you want to return the top x occurences, that is all you want, in order that means:

Put all Strings together in some structure.
Keep track of how many occurences they have.
Sort the list to have the words with the highest amount of occurences first.
Return the top x occurences.
Then decide what you want to do with it.

Issue 4 and 5 are seperated explicitely here, because that is what you ought to do. Every method should serve one purpose, and doing something and printing it is not one purpose.

Another improvement is that as input I want a structure consisting of Strings, and not your (ugly) List<String[]>, I will also deal with that. The code will be fully explained below. While we are at it, I'll also improve the error checking.

The code:

public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) {
    if (topX < 1) {
        throw new IllegalArgumentException("invalid value for topX: " + topX);
    }
    Objects.requireNonNull(words);
    Comparator<Map.Entry<String, Long>> comparator = Comparator.comparingLong(Map.Entry::getValue);
    return words.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
            .entrySet().stream()
            .sorted(comparator.reversed())
            .limit(topX);
}

List<String[]> phrases = Arrays.asList(new String[]{"a", "b", "c"}, new String[]{"a", "a", "b", "d"});
List<Map.Entry<String, Long>> topEntries = getTopWords(2, phrases.stream().flatMap(Arrays::stream))
        .collect(Collectors.toList());
int counter = 1;
for (Map.Entry<String, Long> entry : topEntries) {
    System.out.println(counter + ": " + entry.getKey() + " - " + entry.getValue());
    counter++;
}

The output:

  1: a - 3
  2: b - 2

The explanation:

You have your List<String[]> phrases first, you want to simply have an object that holds your Strings. Here a Stream<String> is a suitable object, because you only need to have a view on your phrases object, there is no point in actually storing the new data. You do this by calling phrases.stream().flatMap(Arrays::stream).

This will first turn your List<String[]> in a Stream<String[]>.
Then you use a method reference that describes the lambda stringArray -> Arrays.stream(stringArray) to acquire a Stream<String>.
Then with the flatMap you add all elements of the resulting Stream<String> back into the original Stream<String>.

Then you start at the getTopWords method, which returns a Stream<Map.Entry<String, Long>>, again to offer the flexibility to do what you want with the results, they are not stored yet at the point where it gets returned.
First I added some error checking.
Then I obtain a Comparator<Map.Entry<String, Long>> that will compare what the entry is with the lowest number of occurences. This is done by using a Comparator.comparingLong on the value of the entry, which is obtained with the method reference Map.Entry::getValue.
Then I start the chain of operations on the input Stream<String>:

First group the results by their identity, which normally produces a Map<String, List<String>>.
The trick here is that I also used a downstream Collector, which counts the number of times the string occurs, hence it is called Collectors.counting().
At this point I have a Map<String, Long> denoting the word and the number of occurences. It uses a Long, because this is what Collectors.counting() returns.
Then I obtain a Set<Map.Entry<String, Long>> and convert it into a stream.
Then I call sorted() on the Stream<Map.Entry<String, Long>> with the reversed comparator. This is done here, because type interference is not strong enough to use Comparator.comparingLong(Map.Entry::getValue).reversed().
Then I limit() the stream by the top x elements.

Now we have the Stream<Map.Entry<String, Long>>, and here we decide to collect it into a List<Map.Entry<String, Long>>.
Here we continue with your old logic of having a counter attached to it.

A few points that are worth to note:

The explicit comparator.reversed() is ugly, but neccessary to not result in type casting, which is even more ugly, it is a limitation of the current type interference. It might be only an issue in IDE's and the javac compiler might actually compile it though.
The usage of Map.Entry<String, Long> is pretty bloated, but our most reasonable option, besides creating a Pair class ourselves and using Pair<String, Long>. This will hopefully be easier if Java 9 includes tuples (which logically include pairs) as more or less first-class citizens.
In the whole method getTopWords we end up storing all the entries in memory once, with the Map<String, Long>, I am pretty sure there are ways around that, but not worth the effort here, only optimize this if it becomes a real bottleneck.
I was hoping to use the Stream.forEach() method when processing the results, however this is not possible with the requirement that you want to have a counter. Again, more possibilities open up in Java 9 when we hopefully have BiStreams and tuples.

I hope this review has been helpful for you.


Nested parallelism is expensive. It was designed for around 1 nesting level when the first level is not parallel enough, and loop slicing. This kind of recursive problems are much better handled by tasks.

void quickSort_tasks(int arr[], int low, int high)
{
    int pi;
    if (low < high)
    {
        pi = partition(arr, low, high);
        #pragma omp task
        quickSort_Optparallel_omp(arr, low, pi - 1);
        #pragma omp task
        quickSort_Optparallel_omp(arr, pi + 1, high);
    }
}

void quickSort_omp(int arr[], int low, int high) {
   #pragma omp parallel
   #pragma omp single
   quickSort_tasks(arr,low,high);
   // implicit synchronization at the end of parallel section
   // otherwise use
   // #pragma omp taskwait
}

Other sorting algorithms may offer higher performance or more efficient parallelization, although being algorithmically more complex. I'm thinking about radix, pigeonhole and merge sorting.

Parallel radix sort explanation: http://projects.csail.mit.edu/wiki/pub/SuperTech/ParallelRadixSort/Fast_Parallel_Radix_Sort_Algorithm.pdf


What is the idiomatic Rust way to write this naive JavaScript token scanner code fragment?

You should become very familiar with all the methods on Iterator; in this case take_while would be highly relevant.
Other parts of the ecosystem that deal with iterators are invaluable, like String::extend.
Extract the logic about what is an identifier character, then you can write that code much simpler: identifier.extend(chars.clone().take_while(is_id_char)).
In most cases, you can use a for loop instead of while let. scan_string is a good example of this. scan is not, because you wish to pass the iterator into further methods inside the loop body, which is not possible with the for syntax.
In addition to the standard library Iterator methods, you should internalize what Itertools provides.
For example, take_while_ref avoids the need to clone the input iterator and then drive the original with nth.
You could chose to accept a generic iterator instead of Chars specifically.

extern crate itertools;

use itertools::Itertools;

fn is_id_char(c: &char) -> bool {
    match *c {
        'a'...'z' | 'A'...'Z' | '0'...'9' => true,
        _ => false,
    }
}

fn scan_identifier<I>(first: char, chars: &mut I)
    where I: Iterator<Item = char> + Clone
{
    let mut identifier = String::new();
    identifier.push(first);
    identifier.extend(chars.take_while_ref(is_id_char));

    println!("{}", identifier);
}

fn scan_string<I>(chars: &mut I)
    where I: Iterator<Item = char> + Clone
{
    let string: String = chars.take_while_ref(|&c| c != '\'').collect();

    if Some('\'') != chars.next() {
        println!("unterminated string! '{}", string);
    } else {
        println!("'{}'", string);
    }
}

fn scan(src: &str) {
    let mut chars = src.chars();
    while let Some(c) = chars.next() {
        match c {
            '(' => println!("("),
            ')' => println!(")"),
            ';' => println!(";"),
            '\'' => scan_string(&mut chars),
            _ => scan_identifier(c, &mut chars),
        }
    }
}

fn main() {
    let input = "print('Hello, world!');";
    println!("Input:\n\n{}\n\nTokens:\n", input);
    scan(input);
}

I wouldn't write any parsing / tokenizing / scanning that operates on characters, however. Especially since you are converting from a &str to a String, when you could just be returning string slices and avoiding extra allocation.


Grab Text storing it in a var then adding html method and adding animation to it

At first, you are requesting the element # + ValUe 4 times. That means jQuery need to search to the entire DOM 4 times to get an element. Cache the value of this element and use that cache variable:

var elem = $('#' + ValUe);

elem.html(...);

elem.find(...);

$(this) inside the callback of the .animate method refers to the animated element, you don't need to use $('#' + ValUe).find('h2') again, just use $(this).

You use formVaule once, just use that constructor instead of saving it to a variable.

To complete correct code:

var k = $('input[value="' + ValUe + '"]').next().text();
var elem = $('#' + ValUe);

// Display H2 tag with the content that was stored
elem.html('<h2>' + k + '</h2>');

// Animated the h2 tag with a background color
elem.find('h2').animate({ backgroundColor: "#40822B" }, 100, function() {
    // Call a callback function with the attention of removing the background.

    $(this).animate({  backgroundColor: "white"}, 500);

});


PEP 8 specifies four spaces per level of indentation.  Since whitespace matters in Python, this is a pretty strong convention.

You should round() the results to the nearest integer rather than truncating them towards 0.

Each of the three channels is treated identically and independently, so you shouldn't write the same code three times.

def square_root_filter(input_image_file_name, output_image_file_name):
    image_data = skimage.io.imread(input_image_file_name)
    for row_data in image_data:
        for pixel in row_data:
            for channel in range(3):
                pixel[channel] = round(255 * math.sqrt(pixel[channel] / 255))
    skimage.io.imsave(output_image_file_name, image_data)

If you take advantage of the fact that channels is a NumPy array, you can vectorize the calculation.

import numpy as np
import skimage.io

def square_root_filter(input_image_file_name, output_image_file_name):
    image_data = skimage.io.imread(input_image_file_name)
    for row_data in image_data:
        for pixel in row_data:
            pixel[:] = np.rint(255 * (pixel / 255) ** 0.5)
    skimage.io.imsave(output_image_file_name, image_data)


Best way to replace Urls in .Net application

Since you just getting the host url, remove the dots, then append it as a subdomain to the given domain with the approprate protocols (Https or Http). You can do this :

public IEnumerable<string> GetRoutedUrls(IEnumerable<string> urls, string domain, int httpPort, int httpsPort)
{
    if(urls == null) { throw new ArgumentNullException(nameof(urls)); }

    if (string.IsNullOrEmpty(domain)) { throw new ArgumentNullException(nameof(domain)); }

    foreach (var url in urls)
    {
        if (string.IsNullOrEmpty(url)) { yield return null; }

       if(Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri))
        {
            yield return uri.Scheme == "https" ? $"https://{uri.Host.Replace(".", string.Empty)}.{domain}:{httpsPort}" : $"http://{uri.Host.Replace(".", string.Empty)}.{domain}:{httpPort}";
        }
    }
}

usage :

var urls = GetRoutedUrls(grupo.Paginas.Where(p => p.Proxy).Select(x=> x.URL), "example.com", 81, 444)

UPDATE

After clarifying things, I think you don't need Regex since you're replacing an exact match of urls. Regex would be more useful if you want to search for unknown inputs.

To give you an example of that, if we want to get every single url in the response we can use

Regex.Matches(response, @"(https?://)(.*)(\d)", RegexOptions.IgnoreCase)

This would get every single url that has specified a port (e.g. https://example.com:443). Then, we can do stuff on them.

In your method, is different a bit. You already have defined the urls, and you want to check for these urls in your response, if they exist, you want to change them by appending them as subdomain to the given domain, and giving them a new port as well.

Unless if there is any special cases that is not covered or mentioned in your post (which forced you to use Regex in first place), I think it would be a straight forward approach if we just use string.Replace directly.

public string ReplaceResponseUrls(IEnumerable<string> urls, string response, string domain, int httpPort, int httpsPort)
{
    if (urls == null) { throw new ArgumentNullException(nameof(urls)); }

    if (string.IsNullOrEmpty(response)) { throw new ArgumentNullException(nameof(response)); }

    if (string.IsNullOrEmpty(domain)) { throw new ArgumentNullException(nameof(domain)); }

    var responseStringBuilder = new StringBuilder(response);

    foreach (var url in urls)
    {
        if (string.IsNullOrEmpty(url)) { continue; } // skip to the next url

        if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri))
        {
            responseStringBuilder.Replace(
                $"{uri.Scheme}://{uri.Host}:{uri.Port}", // old url
                $"{uri.Scheme}://{uri.Host.Replace(".", string.Empty)}.{domain}:{(uri.Scheme == "https" ? httpsPort : httpPort)}" // new url
                );
        }
    }

    return responseStringBuilder.ToString();
}

Try this approach first, do some tests on it, and let me know if you need any help with it.


No, this s not the best way for several reasons:.

First, with this CTE test data common to all three runs:

with Users as ( select * from (values
        (1,'Pieter')
       ,(2,'Betty')
       ,(3,'Robert')
       ,(4,'Fred')
       ,(5,'George')
       ,(6,'Anne')
   )users(UserID,Username)
),
Roles as ( select * from (values
        (100,'Guest')
       ,(101,'Public')
       ,(  1,'Admin')
       ,(102,'Editor')
   )Roles(RoleID,RoleTitle)
),
Permissions as ( select * from (values
        (1,101)
       ,(2,101),(2,102)
       ,(3,101),(1,102)
       ,(4,101)
       ,(5,100)
       ,(6,1)
       ,(7,101),(1,102)
       ,(8,101)
   )Permissions(UserID,RoleID)
)

Your suggested SQL with results is:

select r.roleID, r.roleTitle, pu.* from roles r
    left outer join (select u.*, p.roleID as xrole from permissions p
         left join users u on p.userID = u.userID
              and p.userID = 2) pu on pu.xrole = r.roleID
         and pu.userID = 2

roleID      roleTitle UserID      Username xrole
----------- --------- ----------- -------- -----------
100         Guest     NULL        NULL     NULL
101         Public    2           Betty    101
1           Admin     NULL        NULL     NULL
102         Editor    2           Betty    102

Note that the same result is obtained if we tidy the SQL somewhat to this:

select
    r.roleID, r.roleTitle,
    u.UserID, u.UsrName
from permissions p
join users       u on u.UserID = p.UserID
                  and p.UserID = 2
right join roles r on p.RoleID = r.RoleID
;

roleID      roleTitle UserID      Username
----------- --------- ----------- --------
100         Guest     NULL        NULL
101         Public    2           Betty
1           Admin     NULL        NULL
102         Editor    2           Betty

Ordering your joins can make your code much easier to read, and often avoid nested subqueries.
Always list all field names (except possibly hen referencing a subquery which already lists them). This helsp to prevent your code from breaking with minor schema changes, such as additional fields or a re-ordering of the physical layout of the fields.


Validating that all open/close parentheses are correctly matched

Short Answer
Yes, I believe it will be functional....
Dubious Recursion
Calling this method recursive is a problem. It is not a recursive method. Just because it is calling itself does not mean it is a recursive function. What you have is a bad loop. From Wikipedia:

A recursive function definition has one or more base cases, meaning input(s) for which the function produces a result trivially (without recurring), and one or more recursive cases, meaning input(s) for which the program recurs (calls itself).

Your code does not have a base case and a recursive case..... unless you consider current==null to be the base case... but that is just the recursion-terminating statement.
What I mean, is that, consider this loop:
boolean checkParenthesis(CharNode current) {
    int p = 0;
    while (current != null) {
        if (current.getData() == '(') {
             p++;
        } else if (current.getData() == ')') {
             p--;
        }
        if (p < 0) {
            return false;
        }
        current = current.getNext();
    }
    return p == 0;
}

That is how you can write the code iteratively.
Now, if I change it just like this:
boolean checkParenthesis(CharNode current, int p) {
    if (current == null) {
        return p == 0;
    } else {
        if (current.getData() == '(') {
             p++;
        } else if (current.getData() == ')') {
             p--;
        }
        if (p < 0) {
            return false;
        }
        return checkParenthesis(current.getNext(), p);
    }
}

What I am trying to show here is that you essentially have a while-loop that uses the stack to check the end condition.
For a long input, your code will fail with a stack-overflow exception.
Iteration
When you have linked data like you do, the natural solution is to use iteration.
The example I have above shows how it can be done.
I am not sure why you are using recursion at all.
Actual Recursion
If you really want to use recursion, the right way to do it would be to recurse down when you encounter a ( value, and recurse up when you encounter a )
Each recursive level will make sure it has a matching parenthesis.... it will look something like:
// used if there is an error.
private static final CharNode ERRORNODE = new CharNode(....);
private static final CharNode ENDOFDATA = new CharNode(....);

boolean checkParenthesis(CharNode current) {
    current = matchParenthesis(current, true);
    if (current == ERRORNODE) {
        return false;
    }
    // current could be null if there was an unexpected ')' as the very last character.
    return current == ENDOFDATA;
}

CharNode matchParenthesis(CharNode current, boolean toplevel) {
    while (current != null && current != ENDOFDATA && current != ERRORNODE) {
        if (current.getData() == ')') {
            // found our matching brace
            return current.getNext();
        }
        if (current.getData() == '(') {
            // need to start a sub-level check for a matching brace.
            current = matchParenthesis(current.getNext(), false);
        } else {
            current = current.nextData();
        }
    }
    if (current == null) {
        return toplevel ? ENDOFDATA : ERRORNODE;
    }
    return current;
}