You can reduce your code in several ways.

First, since you seem to want the absolute value of the difference between qtys for the same ìd`:

$toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );

It can be achieved more simply:

$toAdd[$key] = abs($oldReset[$key] - $val);

BTW, when id doesn't exist in $oldReset you probably want the same, so you should use $toAdd[$key] = abs($val); instead of $toAdd[$key] = intval($val); (but maybe you are sure that qty is always positive).

On the other hand, you're preparing both $newArr and $oldArr to get a simplified version of the form array(id => qty): you can do it for only one array, so using less code and probably working faster.

With all the changes proposed above, your whole code becomes:

$oldReset = [];
foreach ($oldArr as $item) {
  $oldReset[$item['id']] = $item['qty'];
}
foreach ($newArr as $key => $val) {
  $id = $val['id'];
  $qty = $val['qty'];
  if (isset($oldReset[$id])) {
    $toAdd[$id] = abs($oldReset[$id] - $qty);
  }
  else {
    $toAdd[$id] = abs($qty);
  }
}

Last point, I notice that you don't try to detect ids existing in $oldArray and not present in $newArray. But again maybe you're sure it cannot happen.


Hard code col and row counts is not good

int colRight = 2;
int colLeft = 0;
int rowTop = 0;
int rowEnd = 2;

Test method should print out results - not method

I think this will fail if the matrix is not square

if (colRight == colLeft && rowTop == rowEnd)

I think this is cleaner

public static void TestSpiralPrint()
{
    int[,] matrix = new int[5, 4];
    matrix[0, 0] = 1;  matrix[0, 1] = 2;  matrix[0, 2] = 3;  matrix[0, 3] = 4;
    matrix[1, 0] = 5;  matrix[1, 1] = 6;  matrix[1, 2] = 7;  matrix[1, 3] = 8;
    matrix[2, 0] = 9;  matrix[2, 1] = 10; matrix[2, 2] = 11; matrix[2, 3] = 12;
    matrix[3, 0] = 13; matrix[3, 1] = 14; matrix[3, 2] = 15; matrix[3, 3] = 16;
    matrix[4, 0] = 17; matrix[4, 1] = 18; matrix[4, 2] = 19; matrix[4, 3] = 20;
    List<int> output = SpiralPrint(matrix);
    foreach (int i in output)
        Debug.WriteLine(i);
    Debug.WriteLine("");
}
private static List<int> SpiralPrint(int[,] matrix)
{
    List<int> output = new List<int>();
    if (matrix.Length > 0)
    {
        int top = 0;
        int btm = matrix.GetLength(0);
        int lft = 0;
        int rht = matrix.GetLength(1);

        while (lft < rht && top < btm)
        {
            for (int i = lft; i < rht; i++)
                output.Add(matrix[top, i]);
            top++;

            for (int i = top; i < btm; i++)
                output.Add(matrix[i, rht - 1]);
            rht--;

            if (lft < rht)
            {
                for (int i = rht - 1; i >= lft; i--)
                    output.Add(matrix[btm - 1, i]);
                btm--;
            }

            if (top < btm)
            {
                for (int i = btm - 1; i >= top; i--)
                    output.Add(matrix[i, lft]);
                lft++;
            }
        }
    }
    return output;
}


Well to me the bad thing is that the function produces an unexpected behavior.

You try to divide by 0, it divides by 1. Huh?

What I would do is throw an Argument Error Exception (or what ever other exception that you think is appropriate).

def calc_percentage(numerator, denominator)
  if denominator.to_f.nonzero
      then (numerator/ denominator.to_f) * 100
      else raise ArgumentError, "Denominator can not be 0.", caller
  end
end

This way it produces something that is logic and consistent.


The most obvious is that although this matches the prototype of the standard strcat function, it works very differently. The standard strcat function does not allocate memory.
You do not account for the terminating NUL character when allocating memory for the new string.
Following from (2), you do not actually NUL terminate the new string.
The value of sizeof(char) is defined to be 1, so you don't really need to multiply by that value.
Your use of spaces is slightly inconsistent, in the first loop there is no space after != but there is in the second loop.
Although the use of *(str3+i) is valid and not wrong, it is more readable and common to use str3[i] instead. MISRA compliant functions have to use the latter.
You could move the declaration of int len_str3 down to where its value is computed, so you would have int len_str3 = len_str1 + len_str2;. That way you don't have what might appear to be an uninitialised variable at the top.


Efficiently generate large file to create SQL table and insert sample user data

The main culprit here is your progress indicator.

You're continuously refreshing a line in stdout every time write is called, and write is called a very large number of times. If you reduce the frequency of console writes, you'll make your script a whole lot faster. One option is to write to the console only every 0.5 seconds or so:

// Performance checker:
setTimeout(() => {
    console.log('Process after 10 seconds: ', Math.floor(total_bytes / target_bytes * 10000)/100);
}, 10000);
// Actual code:
let timeoutId;
const write = str => new Promise(resolve=>{
    total_bytes += Buffer.byteLength(str, 'utf8');
    writerStream.write(str, resolve);
    if (!timeoutId) {
        timeoutId = setTimeout(() => {
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
            const pct = Math.min(100, Math.floor(total_bytes / target_bytes * 10000)/100);
            process.stdout.write(pct+"% complete");
            timeoutId = null;
        }, 500);
    }
});

On my machine, this results in a speed improvement from around 0.25% in 10 seconds, to around 2.03% in 10 seconds - an improvement of a whole order of magnitude.

Another thing: if you're going to use ES2015+ syntax - which you are, and should - then always declare variables with const when possible. Never use var, it has too many gotchas to be worth using (such as function scope instead of block scope, the ability to accidentally re-declare it, automatically putting properties on the global object when on the top level in a browser, etc).


Finding duplicate files on a disk using MD5

Formatting

The code formatting is good. The only major gripe I have is that there are some long lines (117 chars). Part of this is due to the high level of indenation, which we'll solve in another way, but even with heavily indented code, lines can be shorter. I use the black code formatter (with a linelength of 79) to format my code, so I don't have to worry about spacing, long lines or inconsistent quote characters any more

Try-except

You should surround the part that can fail (reading the filesize and file_hash) as closely as possible with the try-except clause. If you want to print a debug message and prevent the rest of that iteration to be executed, you can do that by adding a continue after the print

globals

as you question it, globals are not the correct way to pass information here. A different approach would be to have parts that

generate the paths to the files to check
return the hash
look for duplicates in the hashes
report the duplicates

Each part can receive the result of the previous step as input

generate the paths

Since python 3.4 there is a more convenient way to handle file paths: pathlib.Path

from pathlib import Path
def walking(path):
    return Path(path).glob("**/*")

This returns a generator that yields Paths to all of the files under path. Since it is so simple, it can be inlined.

hashing

def hashing(paths, chunk=False):
    for path in paths:
        filesize = path.stat().st_size
        if chunk:
            file_hash = md5_sum(fname, 8192)
        else:
            file_hash = md5_simple(fname, file_size > 1000 * 1024 * 1024)
        yield path, file_hash

magic numbers

This previous function has some magic numbers 8192 and 1000 * 1024 * 1024.
Better would be to define those a module level constants:

CHUNKSIZE_DEFAULT = 8192
MAX_SIZE_BEFORE_CHUNK = 1000 * 1024 * 1024 # files larger than this need to be hashed in chuncks

def hashing(paths, chunk=False):
    for path in paths:
        filesize = path.stat().st_size
        if chunk or file_size > MAX_SIZE_BEFORE_CHUNK:
            file_hash = md5_sum(fname, CHUNKSIZE_DEFAULT )
        else:
            file_hash = md5_simple(fname)
        yield path, file_hash

I'm not 100% happy with MAX_SIZE_BEFORE_CHUNK as variable name, but can't immediately think of a better on

hoist the OI

If you look at this talk by Brandon Rhodes, it makes sense not to open the file in the method that calculates the hash, but have it accept a filehandle. This is also the approach taken in this code review answer
So to reuse the slightly adapted code from this answer

def read_chunks(file_handle, chunk_size=CHUNKSIZE_DEFAULT):
    while True:
        data = file_handle.read(chunk_size)
        if not data:
            break
        yield data

def md5(file_handle, chunk_size=None, hex_representation=False):
    if chunk_size is None:
        hasher = hashlib.md5(file_handle.read())
    else:
        hasher = hashlib.md5()
        for chunk in read_chunks(file_handle, chunk_size):
            hasher.update(chunk)

    return hasher.digest() if not hex_representation else hasher.hexdigest()

This gets called like this:

def hashing(paths, chunk=False, hex_representation=False):
    for path in paths:
        file_size = path.stat().st_size
        with path.open("rb") as file_handle:
            chunk_size = (
                CHUNKSIZE_DEFAULT
                if chunk or file_size > MAX_SIZE_BEFORE_CHUNK
                else None
            )
            file_hash = md5(
                file_handle,
                chunk_size=chunk_size,
                hex_representation=hex_representation,
            )
        yield path, file_hash

looking for duplicates

Instead of keeping a long string with all the duplicates, you can keep a set of the Paths for each file_hash. A collections.defaultdict(set) is the suited container for this. You add each path to the set at the in the dict. At the end of the function, you filter the keys that have more than 1 entry:

def duplicates(hashings):
    duplicates = defaultdict(set)
    for path, file_hash in hashings:
        duplicates[file_hash].add(path)

    return {
        filehash: paths
        for filehash, paths in duplicates.items()
        if len(paths) > 1
    }

report the filesizes

instead of formating the csv-file yourself, you can use the csv module. It even has a writerows. Instead of defining the lambda function to srt by value, you can use operator.itemgetter

import csv
from operator import itemgetter

def report_results(file_handle, filesizes):
    writer = csv.writer(file_handle, delimiter=",", lineterminator="\n")
    sorted_sizes = sorted(filesizes.items(), key=itemgetter(1))
    writer.writerows(sorted_sizes)

This method can also be used to save the file_hashes

reporting the duplicates

def report_duplicates(file_handle, duplicates):
    writer = csv.writer(file_handle, delimiter=",", lineterminator="\n")
    for file_hash, duplicate_files in duplicates.items():
        for file_name in duplicate_files:
            writer.writerow((file_hash, str(file)))

Here I exported a csv file with the hash and filenames of the duplicates. If you want it in another format, you can easily change this method

bringing it together

def main(path, chunk=False):
    files = [file for file in Path(path).glob("**/*") if file.is_file()]

    filesizes = {str(path): path.stat().st_size for path in files}
    with open("test_filesizes.csv", "w") as file_handle:
        report_results(file_handle, filesizes)
    filehashes = dict(hashing(files, chunk=chunk))

    with open("test_hashes.csv", "w") as file_handle:
        report_results(file_handle, filehashes)

    duplicates = find_duplicates(filehashes.items())
    with open("test_duplicates.csv", "w") as file_handle:
        report_duplicates(file_handle, duplicates)

And then we put everything behind a __main__ guard:

if __name__ == "__main__":
    main(<path>)


Calculate all cyclic subgroups of a group under multiplication of modulo n (group theory)

Two things to consider:

pow is an overkill. To calculate the subgroup, I'd continuously multiply a power by the generator:

subgroup = [1]
power = generator
while power != 1:
    subgroup.append(power)
    power = (generator * power) % modulus

BTW, now you don't have to special case a trivial subgroup.
I would also strike out calculated powers from the list of candidate generators (that is, coprimes). This way you'd avoid recalculating the same subgroup over and over again.


LeetCode: Finding all possible letter combinations from an inputted phone number

Preface:

Next time you post code, please include the #includes.  It is easier to review if reviewers can simply copy the code and compile it.  In the same vein, it's helpful if you include any special compiler flags and a test case.  Here is the code as I am reviewing it: https://godbolt.org/z/zQ5mH3.

Review:

You don't write std:: before STL classes so I assume you are using namespace std;.  Many have written about why this is a bad idea so I won't repeat it here, but note it's especially bad in headers (.h files).  It's a less bad in implementations (.cpp files).  You haven't split out your code into a header/implementation, so anyone who #includes your code will also be forced to use namespace std... which is not good.
You use a map<char, vector<char>> to find possible letters from digits.  I think this is OK in cold code/as a mockup implementation while you figure out the rest of your code.  But this is a waste of time/memory in hot code because:

the map is known at compile time
there is no reason to allocate/deallocate anything, and map/vector can both use the heap

Using a function that returns initializer_list<char> instead of a map to vectors speeds up your function 1.6 times (http://quick-bench.com/eYwFgmzQmT95dOsLSRH35FT4QAI).  In case you don't already know, initializer_list is a lightweight data-structure that can be iterated but will not allocate/deallocate memory.  Note that in order to safely return initializer_list, you need to make the list static and might as well make it constexpr.

Your Solution class passes a lot of state in each recursive call.  This call happens many times, so you should try to make it cheap.  For starters you could pass the constant strings by const& to avoid unnecessary copies (this is a 1.9x speed up from the original).  But you could also opt to make the string, result, and digits member variables and then only pass the index in the recursive calls.  This has a few advantages:

Your recursive calls will only have a this pointer and an index (so the arguments will fit in almost every cache line).
It becomes natural to use the same strings the whole time and only copy when producing the result as opposed to the way it was originally written with s + string({c}) which does a heap allocation (at least with std::string and GCC 10).

The simpler recursive calls + the functional map results in a 3.3x speedup compared to the original implementation.  The recursive function now looks like:

void letter_combination_helper(int i) {
  if (i == m_digits.size()) {
    m_result.push_back(m_string);
    return;
  }

  for (char c : lettermap(m_digits[i])) {
    m_string.push_back(c);
    letter_combination_helper(i + 1);
    m_string.pop_back();
  }
}

... where I have prefixed the member variables with "m_" for clarity, and lettermap is a function returning initializer_list<char>.

Minor nit: It's nice to use camelCase or snake_case but not both.
Minor nit 2: I think the indentation of the code you posted is weird e.g. construct_num_letter_map's open bracket is indented but the closing bracket isn't.  This weirdness might have been introduced when you pasted your code into the question, so I won't expand on this.

I think if you make these changes you will have some fast and elegant code.  The general algorithm is the same -- I think you got that right from the start which is good.  I believe the algorithm is optimal since you need O(pow(len(digits), 4)) space to store the result vector, and it seems reasonable to spend that much time writing the answer down.

If I had to summarize the comments into one morsel of feedback, it would be to think more carefully about which operations need to use memory (i.e. allocate/deallocate/copy/dereference).  This was the issue with map (it has to dereference a lot to do lookups) and also with passing lots of state in the recursive calls (lots of copying).  The general rule of thumb is that memory is slow, and if you can reasonably avoid it, then you should.  If you keep at it, this will become second nature to you.


You're right, most of the time, you shouldn't use polling like this. You should instead block the thread indefinitely if there is no work and wake it up when it's needed.

Fortunately, the same namespace that contains the ConcurrentQueue<T> you use also has the solution you need: BlockingCollection<T>. The collection has methods that will always return an item, and block if none are available, which is exactly what you need. Using that class, I would rewrite your code like this:

BlockingCollection<Command> queuedCommands = new BlockingCollection<Command>();

private void MainBackgroundLoop(object sender, DoWorkEventArgs e)
{
    do
    {
        Command command;
        bool commandAvailable = queuedCommands.TryTake(out command, Timeout.Infinite);
        if (commandAvailable)
            command.Execute();
    } while (commandAvailable);
}

Because the collection doesn't know about your DoWorkEventArgs, you have take care of ending the loop in some other way. In the code above, if you call queuedCommands.CompleteAdding(), it will make sure remaining items are processed and then it will shut down, because TryTake() will return false. Another option for cancellation is to use an overload of TryTake() that takes a CancellationToken and use that to cancel the operation.


Class or not in Page Scraper (Python BeautifulSoup)

Class inheritance
Classes no longer have to be subclasses from object
class WebsiteImages:

Naming Conventions
Methods and variable names should be snake_case. Classes should be PascalCase, so you got that correct :-).
Imports
Any and all imports should go at the top of the file.
f"" strings
You should use f"" strings to directly implement variables into your strings.
url = urllib.request.urlopen(f"{self.website_url}&page={page}&sort=best")

User Interaction
The way a user has to interact with this program is pretty challenging to understand. If I was a normal user, I would do something like this:
person = WebsiteImages("John Smith", "https://www.WebsiteImages.co.uk")

But I would get an error, or no images returned because I didn't know the name had to be encoded with %20 and I didn't know I needed to specify a very particular url. I would blame it on the program and look for something else that's more user friendly.

I would solve this by only requiring a name. Since you're going to one website, you can save the url as an instance variable and sort things out there, instead of relying on a user to provide perfect input. Never trust user input.
john = WebsiteImages("John Smith")
print(john.get_image_ids())

And within the constructor you can do something like this:
def __init__(self, photographer: str):
    self.photographer = '%20'.join(photographer.split())
    self.website_url = f"https://www.WebsiteImages.co.uk/search/photographer?photographer={self.photographer}"


About your solution

Your tree generation code is wrong. It doesn't return a tree, it returns a multidimensional list instead. There is a good, detailed article about a tree data structure: Everything you need to know about tree data structures.

The main idea of tree - the connection of nodes. All begins from the root - the singular node at the first level, that contains references to the all nodes at the next level, which in their turn have references to the next level nodes, so on. Thus, every node should have as minimum as two fields: one for value and one for list of its childs (terminology used in trees).

Edit after the comment [start]:

Actually, the tree generation code returned value is resembling the tree, especially taking into account that the Python lists and numbers are objects. It has root object with 3 childs, each child has three childs too, so on. (when height=3, branches=3). At the last level it has objects with a number value.

Thus, it complies the first tree data structure requirement: the connection of nodes (from my own definition :)). But not all nodes have value - only the last level's nodes do (the leaves in the tree terminology). So, you anyway can't walking through tree, changing or printing all nodes value, because some nodes don't have them:

root[
    2-nd lvl[         4-th lvl with values
            3-rd lvl[18, 19, 20],
                    [21, 22, 23],
                    [24, 25, 26]
            ],
            [
                    [27, 28, 29],
                    [30, 31, 32],
                    [33, 34, 35]
            ],
            [
                    [36, 37, 38],
                    [39, 40, 41],
                    [42, 43, 44]
            ]
    ]

Edit after the comment [end]:

I didn't throughout investigation of your tree walk code, but by glance it uses the the wrong tree idea as well as the tree generation code and therefore, can't work correctly.

My partial solution

I read your requirements and wrote my own solution, that creates tree, walks through it and applies a passed function to each node. It can't process only end nodes though, but this functionality is easy to add.

class Tree(object):

    def __init__(self):
        self.value = None
        self.childs = None

    # Build tree recursively
    # All nodes doesn't have values, just child list
    # Values will be set by the passed function
    def grow_tree(self, height, child_num):
        if height < 2:
            return

        self.childs = []

        for i in range(child_num):
            child = Tree()
            self.childs.append(child)
            child.grow_tree(height - 1, child_num)

    # Walk through tree iteratively
    def walk_tree(self, func):

        all_current_level_nodes = [self]

        while all_current_level_nodes:
            all_next_level_nodes = []

            for node in all_current_level_nodes:
                func(node)
                if node.childs:
                    all_next_level_nodes.extend(node.childs)

            all_current_level_nodes = all_next_level_nodes

### Recursive implementation
###
#   def walk_tree(self, func):
#       func(self)
#
##      if isinstance(self.childs, list):
#       if self.childs:
#           for child in self.childs:
#               child.walk_tree(func)

Testing

### Functions for passing to the "walk_tree" method
def set_values(node):
    node.value = set_values.cnt
    set_values.cnt += 1

def print_values(node):
    print(node.value)

def print_id(node):
    print(id(node))

def square_values(node):
    node.value = node.value ** 2

tree = Tree()

tree.grow_tree(2, 3)

tree.walk_tree(print_id)

# Function is an object. Add the "cnt" field to this object.
# It will work as a static variable, preserve counter between calls.
set_values.cnt = 1
tree.walk_tree(set_values)

tree.walk_tree(print_values)

tree.walk_tree(square_values)

tree.walk_tree(print_values)

Output

# "print_id" function was applied on each node while walk_tree
139632471400688
139632471400800
139632471400856
139632471400912
# "set_values"
# then "print_values" were applied
1
2
3
4
# "square_values"
# then "print_values" were applied
1
4
9
16


Priority scheduling algorithm using std::vector

While comments have suggested more suitable types than std::vector, I'm going to assume that the use of this underlying type is a given, and suggest straightforward improvements without changing that.
The main performance concern is here:

void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
    pair_list.emplace_back(pro_ID, pro_pri);

    std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
        return a.second < b.second;
    });
}

It's wasteful to sort the vector every time we add an element, when we know it was sorted before we called this function.  Instead, we need to insert the new element in the correct position.
void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list)
{
    auto position = std::upper_bound(pair_list.begin(), pair_list.end(), pro_pri,
                                     [](auto pri, auto const& ele) { return pri < ele.second; });
    pair_list.emplace(position, pro_ID, pro_pri);
}

We use the type std::vector<std::pair<int, int>> a lot.  It's worth giving it a name:
using priority_queue = std::vector<std::pair<int, int>>;

That makes changing the code easier, e.g. if we decide that process ids actually need to be unsigned long or something.
However, I observe that every function takes one of these as an argument.  That suggests that we want a class with this vector as member, then convert those free functions to be members of that class.

Thank you for including the test program - that's always helpful in a review.  There's a couple of small points:

for (int i = 0; i < process_ID_list.size(); ++i) {

We're mixing signed and unsigned types in this comparison (int and std::size_t).  Obviously we should change int i to std::size_t i - and enable more compiler warnings.

       std::cout << "process is already in list" << std::endl;

Prefer to use std::cerr for error messages.

The pattern if (condition) return true; else return false; can simply be replaced with return condition.  So:
bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)
{
    return pair_list.front().first != pro_ID;
}

The loop in check_pro_is_present can be replaced with std::any_of:
bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)
{
    return std::any_of(pair_list.begin(), pair_list.end(),
                       [pro_ID](auto const& e){ return e.first == pro_ID; });
}

Modified code
This is just a beginning - we'll probably want an initialiser-list constructor, and replace print() with operator<<(), but it's a start.
#include <algorithm>
#include <iostream>
#include <utility>
#include <utility>
#include <vector>

template<typename T, typename Priority = int>
class priority_queue
{
    std::vector<std::pair<T, Priority>> values = {};

public:
    void print(std::ostream &os) const {
        for (const auto& pa : values) {
            os << "process_ID: " << pa.first << ", "
               << "priority: " << pa.second << '\n';
        }
        std::cout << '\n';
    }

    void add(T t, Priority pri) {
        auto const position
            = std::upper_bound(values.begin(), values.end(),
                               pri,
                               [](auto const& pri, auto const& ele) { return pri < ele.second; });
        values.emplace(position, std::move(t), std::move(pri));
    }

    bool contains(int pro_ID) const
    {
        return std::any_of(values.begin(), values.end(),
                           [pro_ID](auto const& e){ return e.first == pro_ID; });
    }

    bool has_higher(int pro_ID) const
    {
        return values.front().first != pro_ID;
    }
};

int main()
{
    const std::pair<int,int> processes[]
        = { { 1345, 41 }, { 45, 334 }, { 5646, 747 },
            { 52525, 41 }, { 55757, 47 },
            { 23424, 7 }, { 68696, 75 }, { 55878, 544 },
            { 667, 42 }, { 252, 6 } };

    priority_queue<int, int> queue;
    for (auto const& p: processes) {
        if (queue.contains(p.first)) {
            std::cerr << p.first << " is already in list\n";
        } else {
            queue.add(p.first, p.second);
        }
        queue.print(std::cout);
    }

    int query_pro_ID = 1345;
    std::cout << std::boolalpha << queue.has_higher(query_pro_ID) << '\n';
}


RxJs - Flat nested swithMaps and pass variables on Http interceptor

Your specific example can be simplified by treating the non-observables as simple variables, eg:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const user = this.fireAuth.currentUser;
  if (!user) return next.handle(request);

  const isApiUrl = request.url.startsWith(apiCloudURL);
  const token = user.getIdToken();

  if (isApiUrl) request = this.addToken(request, token);

  return next.handle(request).pipe(
    catchError(error => {
      if ( isApiUrl &&
            token &&
            error instanceof HttpErrorResponse &&
            error.status === 403) {
        return this.handle403Error(request, next);
      } else {
        return throwError(error);
      }
    })
  )
}

However, in the general case your question uncovers a couple of interesting RxJS "patterns".
First let's ignore the path where there is no user.  What you end up with is a sequence of requests (ie your switchMaps), but where the result of any earlier request is any later request.  There is no completely clean solution to this in standard RxJS - a number of options are discussed in this article Aggregating RxJS Requests.  Nesting is the most common solution, which was your starting point.
I have been involved in the implementation of a utility to address this scenario.
With your example the resultant code would be:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const isApiUrl = request.url.startsWith(apiCloudURL);

  return concatJoin(
    from(this.fireAuth.currentUser),
    ([user]) => from(user.getIdToken),
    ([user, token]) => {
      if (isApiUrl) request = this.addToken(request, token);
      return next.handle(request).pipe(...),
    },
  ).pipe(
    // resultant value is [user, token, result] - we just want the result
    map([,,result]) => result
  );
}

Now returning to handle the case where there is no user, in your implementation you are right, the filter would cause it to never emit a value.  There has to be a level of nesting:
intercept(
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {

  const isApiUrl = request.url.startsWith(apiCloudURL);

  return from(this.fireAuth.currentUser).pipe(
    switchMap(user => {  // or use the iif operator
      if (!user) return next.handle(request);

      return concatJoin(
        (from(user.getIdToken),
        ([token]) => {
          if (isApiUrl) request = this.addToken(request, token);
          return next.handle(request).pipe(...),
        },
      ).pipe(
        // resultant value is [token, result] - we just want the result
        map([,result]) => result
      );

    )
  )
}


Single Page App - Browser Storage API Design

You are correct that there is no need to wrap this with a promise. As it is, there are a few problems with the GetOrSetLocal function.

The function will always try to fetch the values from the server, even if it is cached locally.
The function's name is misleading, when first reading the code I assumed the function could be used to set a value in storage - not just retrieve values. I'm not really sure what to suggest for a name...
I would recommend using something other than callback for the Axios instance as it is decidedly not a callback. It might be best to just call it axios.
burst would be better named ignoreCache to more clearly indicate it's purpose.

If I was unable to use async/await, here is how I would write this function:

const StorageHandler = {
    ...,
    GetFromCache(url) {
        if (!this.StorageEnabled) return null
        return JSON.parse(localStorage.getItem(url))
    },
    GetOrSetLocal(url, axios, ignoreCache = false) {
        if (!ignoreCache) {
            return new Promise(resolve => {
                const cached = this.GetFromCache(url)
                resolve(cached === null ? this.GetOrSetLocal(url, axios, true) : cached)
            })
        }

        return axios.get(url)
            .then(response => {
                if (this.StorageEnabled) {
                    localStorage.setItem(url, JSON.stringify(response.data))
                }
                return response.data
            })
    },
}

Alternatively, if you are able to use async/await, I would prefer this version.

const StorageHandler = {
    ...,
    async GetOrSetLocal2(url, axios, ignoreCache = false) {
        if (!ignoreCache) {
            const cached = this.GetFromCache(url)
            return cached === null ? this.GetOrSetLocal2(url, axios, true) : cached
        }

        const { data } = await axios.get(url)

        if (this.StorageEnabled) {
            window.localStorage.setItem(url, JSON.stringify(data))
        }

        return data
    },
}

Another comment: I tend to avoid using proxies as I find they quickly multiply and end up making debugging a royal pain. It might be better to define StorageEnabled as a getter.

const StorageHandler = {
    TestedStorage: false,
    _StorageEnabled: false,
    get StorageEnabled() {
        if (!this.TestedStorage) {
            this.TestStorage()
        }
        return this._StorageEnabled
    }
}

And one more thing:
It is probably better to implement caching with response headers instead of saving responses in localStorage. Since this is a get api, you can use headers to tell user's browsers to cache the responses for the appropriate amount of time and you get faster responses automatically, without introducing more JS. (Unless the response is out of your control of course - in which case this is probably a good idea.)


Passing a true/false value to a model used in a controller

None. However, it has several issues. Here it is, indented differently to avoid horizontal scroll:

    Auto

        :

    <select name="IsAuto"
            class="togglehidden"
            id="IsAuto"
            data-role="slider"
            data-hidden-id="#autohidden">
        <option value="false">No</option>
        <option value="true">Yes</option>
    </select>
    @Html.HiddenFor(m => m.IsAuto, new { id = "#IsAuto", value="#IsAuto" })
    <input
        type ="hidden"
        name ="autorel"
        id="autorel"
        value="@(Model.IsAuto = "#IsAuto".AsBool())" />

Where is the closing tag for div?
What do you use, XHTML or HTML5? In the first case, you should close img. In the second case, you shouldn't close the last input.
"#IsAuto".AsBool() always returns false, since "#IsAuto" is never equal to "true".
Why are you assigning a value to a property of your model in a view in the last line? Maybe you expected Model.IsAuto == ...?
An id of the hidden field which starts by # is weird.
If you care about naming conventions, m is a poor name for a variable. Basically, any person who have never used ASP.NET MVC before wouldn't be able to know that it refers to a model.
Given the actual syntax for the hidden field, wouldn't it be easier to simply write it in plain HTML?


Sorting and searching problem related to a group of people standing in a rectangle

Split it up!  The current method does more than one thing, I'd create at least three helper methods:

int[][] parseInput(String[] input);
int getMaxOfMinHeightInColumns(int[][] peoples);
int getMinOfMaxHeightInRows(int[][] peoples);

It would be easier to follow and understand.
I looks like a bug that the following testcase fails:

@Test
public void test() {
    String[] input = {"9 2 3",
     "4 8 7"};
    int[] result = getPeople(input);
    assertArrayEquals(new int[] {4, 7}, result);
}

Reusing the count variable is a bad sing:

count=0;

Try to use two different variables for different purposes and more descriptive names. What does it count? Put that into the name of the variable.
A few explanatory variable would be more readable here and remove some duplication:

String[][]findMaxOfMin = new String[people.length][people[0].split(" ").length];
int[][] findMinOfMax = new int[people[0].split(" ").length][people.length];

Consider creating one for people.length and another for people[0].split(" ").length (columnNumber, rowNumber, for example).
(String[]) casting seems unnecessary here:

temp[j] = Integer.valueOf( ((String[])people[j].split(" "))[i]);


Notes:

This tap usage is not uncommon to see but IMHO it's very, very dubious. You can use a functional approach (see code below).
I wouldn't return the string along with the attribute, just the array of classes (which Rails3 helpers understand).

I'd write:

def tr_classes(user)
  [
    ("error" if !user.company),
    ("disabled" if user.disabled?),
  ].compact.presence
end

Tables are usually easier to build from helpers. You now would use the function that way:

content_tag(:tr, :class => tr_classes(user)) do
  content_tag(:td, user.name)
end


Should this Point class remain a class, or become a struct?

If you are using point as a property bag (like this).

Then just make it a struct (leave the members public). If you think there is a slight possibility of modifying the implementation then use get/set (ers) to access the memebrs but this class is so simple it seems over kill.

If this is part of a school class then your professor is going to say use member accessors so that the internal implementation can change and the internal implementation can change without the class interface being changed.

Though true in this simplistic case its just not going to happen.

Though I would add constructors to make sure the members are correctly initialized.

PS. Try not to use a leading underscore on identifiers. Though in this case it is not a problem the rules are non trivial and not well known so best avoided. see https://stackoverflow.com/a/228797/14065


you can abuse the fact that

  All hotness ratings are (integers) on a scale of 0 to 10

Just keep track of how many men/women there are of each score. This looks something like this:

int[] men = new int[11];
for (i = 0; i < modelsWithMe; i++) {
    men[sc.nextInt()]++;
}

Then for the score you need to figure out how to combine the pairs given those frequency arrays.

int m = 10;
int w = 10;
while(m >= 0){
    while(men[m] == 0) {
        m--;
    }
    while(women[w] == 0){
        w--;
    }
    hotnessSum += m*w;
    men[m]--;
    women[w]--;
}

This calculation can still be optimised greatly. If you have 21 man score 10 and 30 women score 10 for example, you could add 21*10*10 to the total and reduce the frequencies of both by 21 instead of looping 21 times to achieve the same total. I'll leave turning this into code to you.


I've seen quite a few programmers who don't enjoy seeing arrays coming in as arguments into the code (me personally, I'm fine with it as long as there is some sort of documentation that goes with it so you don't forget what the function can and cannot take).

password_hash($password, PASSWORD_BCRYPT, $options);

would instead be:

password_hash($password, PASSWORD_BCRYPT, $cost);

The above is purely an FYI and not my opinion.

When it comes to accepting username/passwords, you want to be sure you're on a secure location. Based on your current code, if you're only a http:// page (typically port 80) then a malicious bot can potentially sniff the username/password. Easiest way to do this, is run a check against $_SERVER['HTTPS'] but if that fails, you do want to redirect the user to another page or something like that.

You shouldn't have more than one user with the same username, so create a LIMIT 1 at the end of the SQL query, otherwise it'll scan the entire table no matter how many results you get.

$stmt = $cxn->prepare('SELECT * FROM users WHERE username = ? LIMIT 1 ');

Same concept for your cookies table lookup:

$stmt2 = $cxn->prepare("SELECT * FROM cookies WHERE username = ? LIMIT 1");

Is there a purpose of creating additional variables that are essentially the same values of the initial variables?

e.g.

$username = $_POST['username'];

What that ends up doing is you will use up additional memory blocks when it's not really needed to happen. Also, you could lose track of what $username is down the road, and re-initialize it with a different value. Same idea when you're looking at your $row data.

PASSWORD_BCRYPT is not meant to be fast, but it is meant to be secure. You're running it twice, with different values, is there a reason you're doing that for your logs considering you can't reverse the encryption? I'd just run it once and put it against $hash_password

If you're using time() multiple times across the page, that's when you may want to put that against a variable. Even though it's a very quick function, it'll be faster to look it up against a variable that has a fixed number and is stored in a particular memory block, creates a consistent value across the board in case you have to do additional comparisons against each other (compare something about the expiration date or check the value that got inserted into the log table and since that's a salt, might as well have that as a reference etc.).

If the username/password verification feels like it takes a long time, then it is taking a long time, that's the way I see it. If you don't mind how long it takes, you might be ok (as saying 1 second is relative to the actual speed of the script). However, for bottlenecks, you'd have to test pieces of your code to see where is it slowest.

Hope this helps.


What you're essentially doing is transforming a list to another list (a list of <tr> to an array). Instead of jquery.each() and pushing to an array, use jquery.map() instead. jquery.map() works like array.map() except it returns a jQuery collection (an array-like object with jQuery metadata). You can bolt on jquery.get() at the end to convert it to a plain array afterwards.

There's also a shorter version of jquery.find - using the $ function with two arguments. The first being the selector, the second being the context. Internally, this just does jquery.find but from an authoring point of view, it's just shorter. In addition, you can use the :eq() selector in place of jquery.eq().

Now the above advice is for jQuery. I'm not exactly sure how identical the Cheerio API is to the jQuery API, but if they are, the above advice will probably hold.

As mentioned in the other answer, your code is heavily duplicated. A common advice is to move it out to a function and call that function. But you do not simply do that. I recommend taking a functional approach. You pass in all the arguments needed for the function to work, and operate on those arguments. This keeps the function independent from scope, variable visibility, side effects and so on.

Also suggesting using let and const whenever possible, preferrably const if you don't expect a variable's value to change. This signals other readers of your code what a variable should be, if it's supposed to be block-scoped or not, if the value can be changed or not.

There's also object property shorthands. If the variable you're assigning to an object property has the same name as the property, you can omit the : and the right-hand side.

Update: I've always been told (and I always forget) to pull filter operations early on in the stream. This reduces the number of iterations down the stream, avoiding unnecessary iterations. In this case, we filter out all entries without currency name first to avoid scraping and data generation for them.

const getText = element => element.text().replace(/\r?\n|\r/g, " ").trim();

router.get("/:ticker?", function(req, res, next) {
  const reqCurrencyName = req.params.ticker

  rp(baseUrl).then(body => {
    const $ = cheerio.load(body);
    const currencies = $("tr").filter((i, e) => {
      // Filter rows with no currency name
      return Boolean(getText($('td:eq(1)', e)))
    }).map((i, e) => ({
      // Construct the object
      currencyName: getText($('td:eq(1)', e))
      marketCap: getText($('td:eq(2)', e))
      price: getText($('td:eq(3)', e))
      dataSupply: getText($('td:eq(4)', e)).replace(/ /g, "")
      volume: getText($('td:eq(5)', e))
      negativeChange: getText($('td:eq(6)', e))
    }))

    // Respond
    res.send(currencies.get())
  })
  .catch(error => {
    rollbar.log(error)
    res.send({ error })
  })
})


By everything I know the code looks OK from security POV.

Parameter naming convention

Your check function takes hash_User and hash_Input as parameters. This is a pretty strange naming convention. Standard Java convention would be hashUser and hashInput (which you already use in method names). hash_user and hash_input (note the lack of capital letters) would also be pretty OK.

Constants

As chillworld stated in his answer I'd extract algorithm, length and iterations as nicely named constants with some nice JavaDoc. It'll be easier to understand the code later (not an issue at this point), and easier to reuse it it next methods. While you're at it you could also declare the length of generated salt.

Encoding

Your generateHash function takes String and uses getBytes on it. Note that this is influenced by the platform's default encoding. If you later move to another platform, your hashes suddenly won't match anymore. You could force encoding by using one of the other variants of getBytes.

Verifying the password

Your check method takes byte[] hash_Input, String hash_User. Now, I'm having trouble guessing which one should be the hash stored in the DB and which one the new one user is trying to log in with. Also, how do you plan to get the one that's represented as String? Considering that the generateHash function returns byte[] you'd have to convert it to String and then back to byte array, but that's not reversible - if you use e.g. UTF-8 more than one byte sequence maps to the same String. And do you ever plan to use it really in that way? Why not having a function boolean check(byte[] hash, String password, byte[] salt) instead?

Plan for the future

This one is less clear. Suppose at some point later you want to change your algorithm/parameters (say 60000 iterations is no longer enough). Suddenly all your old hashes are no longer valid. If it's a new installation it's no problem, but what if you update installation which already has 10000 users? You can try to decode using both ways and log in if one succeeds. This increases the CPU cost of login, allows for possible collisions (unlikely). And what if you then change the algorithm second time? You could somehow encode the algorithm and parameters in the hash. This removes the possibility of collisions and later allows you to cheaply select which one of the (costly) password hashing functions to choose. And it scales well with subsequent changes. You could then update the stored hash if a user with old hash logs in. And since distinguishing users with old hash methods is easy, after some time you could ping the ones that didn't log on. The bad part: After some time one could forcefully hack your DB and replace with the weaker hash. You'll have to think carefully whether you want this one.

Plan for tests

Another not so clear one. In the current way whoever uses this class has to use this exact specification. Normally this is exactly what you want, but in case you'd like to unit-test anything that uses it the test will become unnecessary long (PBE algorithms are designed exactly to be slow, and will slow down your test in this case). You can work around this by declaring an interface with two implementations - this one, and the mock one used in tests (say generateHash returns simply password and salt concatenated and generateSalt returns a constant array). Good part: Your tests no longer need 1 second each to run. Bad part: You need to somehow get that instance in each and every class that needs it. Could be as easy as using Sprint and @Autowire on the correct field. Could be as hard as having every object own a reference to this object only to pass on to newly generated objects, while a handful of those deep in the creation chain really uses that reference. Second bad part: Somehow could inject your objects with another, weaker implementation. And this could really be a problem (compare with previous point) when you use e.g. applet or a client-side application to generate the hashes. You'd also need to consider the good and bad consequences here.


A Simple Interactive Program that Can Solve A Linear System of Equations

Why not do the arithmetic in parentheses? That way, it will be clearer.
The rest of the code is very clear and understandable, I didn't find any bugs.


Handling 8 toggle buttons in a point-of-sale application

Short answer: You need the Java Collections framework.

Instead of eight standalone variables cust1...cust8, you should put them into a Collection so that you can easily iterate through them:

// assuming the buttons are of JButton type
Collection<JButton> buttons = Arrays.asList(cust1, cust2, /* ... */, cust8);
for (JButton button : buttons) {
    if (button.isSelected()) {
        cust = custDAO.getCustById(Integer.getInteger(button.getText()));
        int sales = cust.getTotalSales();
        cust.setTotalSales(sales + subtotal);
        custDAO.updateCustomer(cust);
    }
}

Longer answer...

It is not known how these lines are being run, but you can also consider writing event listeners, which is the typical implementation for checking if buttons have selected. For example, to use an ActionListener:

JButton button = new JButton();
// lambda expression below requires Java 8
button.addActionListener(actionEvent -> {
    JButton source = (JButton) actionEvent.getSource();
    // using valueOf() as getInteger() looks at System.getProperty(),
    // unless that is really the intended usage
    cust = custDAO.getCustById(Integer.valueOf(source.getText()));
    int sales = cust.getTotalSales();
    cust.setTotalSales(sales + subtotal);
    custDAO.updateCustomer(cust);
});

Instead of having cust as a method, or even class, variable, you should scope it appropriately to eliminate any possible mis-references. Also, you can consider adding a more expressive method updateTotalSales(int incoming) that returns the object itself, so that you do not have to perform that 'manually' here:

public Customer {

    // ...

    public Customer updateTotalSales(int incoming) {
        setTotalSales(getTotalSales() + incoming);
        return this;
    }
}

JButton button = new JButton();
button.addActionListener(actionEvent -> {
    JButton source = (JButton) actionEvent.getSource();
    Customer cust = custDAO.getCustById(Integer.valueOf(source.getText()));
    custDAO.updateCustomer(cust.updateTotalSales(subtotal));
});

In the unlikely (?) event that you still prefer/require the original iteration method by checking on isSelected(), the Collection-based implementation, coupled with stream-based processing, can also achieve the same outcome with the following, for simplicity:

// buttons from the short answer
buttons.stream().filter(JButton::isSelected).findFirst()
        .map(i -> custDAO.getCustById(Integer.valueOf(i.getText())))
        .ifPresent(cust -> custDAO.updateCustomer(cust.updateTotalSales(subtotal)));

By using a method reference JButton::isSelected, filter for the JButton where that is true.
Use findFirst() to 'get' it in the form of an Optional wrapper.
From the JButton instance, map() it to the desired Customer object, and finally call custDAO to 'consume' it via the ifPresent(Consumer) method.


Binary to decimal converter in JavaScript

Flawed exercise

Before I begin, I would like to point out that the exercise is flawed:

The task is not really converting the input from a binary to a decimal representation.  Rather, it is to convert it to a number, whose conventional string representation is rendered in base 10.  The test suite included this test:

xit('11010 is decimal 26', function() {
  expect(new Binary('11010').toDecimal()).toEqual(26);
});

… which could also have been written as:

xit('11010 is twenty-six', function() {
  expect(new Binary('11010').toDecimal()).toEqual(0x1a);
});

It is bad practice to return 0 for new Binary('junk').toDecimal().  Acceptable results would be to either throw an exception or return Number.NaN.

Review

Your invalidInput function either returns true or falls off the end.  Good practice would be to name it isInvalidInput, and have it explicitly return true or false.  Better yet, reverse the sense and call it isValidInput.  Even better, don't expose the validation function as a method at all — you don't really need one.

this.binary.split('').reverse() and Math.pow(…) seem extravagant.

Suggested solution

// Constructor
var Binary = function(binary) {
  this.binary = binary;
  this.base = 2;
};

Binary.prototype.toDecimal = function() {  // <-- Method name is a misnomer!
  var output = 0;
  for (var i = 0; i < this.binary.length; i++) {
    output *= 2;
    switch (this.binary.charAt(i)) {
      case '0': break;
      case '1': output += 1; break;
      default:  return 0;   // <-- This sucks, but the test suite requires it!
    }
  }
  return output;
}


Finding the coordinates on an edge of a square

I think the solution is a little simplier

const dx = targetX - sourceX;
const dy = targetY - sourceY;
const scale = Math.hypot(dx, dy) / Math.hypot(radius,radius * (Math.abs(dy / dx) < 1 ? dy / dx : dx / dy));
const tx = targetX - dx / scale;
const ty = targetY - dy / scale;

If it is just the boundary of the box you are after. The only comparison is to find out which part of the box the line ends on, top/bottom or left/right the rest works by preserving dx and dy's sign. It also works if dx or dy is zero.

The only thing I am not sure of is if the offset is from the target, if so I would change to

const dx = sourceX - targetX;
const dy = sourceY - targetY;
const scale = Math.hypot(dx, dy) / Math.hypot(radius,radius * (Math.abs(dy / dx) < 1 ? dy / dx : dx / dy));
const tx = targetX + dx / scale;
const ty = targetY + dy / scale;


#!/usr/bin/env python

import sys, math

ur = [[1,0],
      [1,1]]

ul = [[0,1],
      [1,1]]

lr = [[1,1],
      [1,0]]

ll = [[1,1],
      [0,1]]

Rather then creating four separate variables, I'd suggest making a list. I'd also suggest using the numpy library for its array type. It makes working with 2D arrays much nicer then using lists of lists.

shapeCounter = 1

matrix = []

Don't use global variables. Instead, pass matrix in as the parameter to the function.

def printMatrix():
    for row in matrix:
        for element in row:
            if(element >= 10):

Parens aren't needed here

                print("%d" % element),
            else:
                print(" %d" % element),
        print
    print

Note that if you used numpy, that library would already be able to nicely print a matrix.

def square(n):
    global matrix

This function should really create and return the matrix

    matrix = [[0]*(2**n) for x in xrange(2**n)]

In numpy, this would be matrix = numpy.zeros( (2**n, 2**n) )

    matrix[0][len(matrix) - 1] = -1
    rec(0, 0, len(matrix) - 1, len(matrix) - 1)
    matrix[0][len(matrix) - 1] = 0
    printMatrix()

Functions that do work on your variables shouldn't print them. Your main control function should do the printing.

def writeRect(rect, x, y):
    global shapeCounter

This isn't a terrible use of a global, but I'd avoid it. I'd have an object this attribute was stored on.

    matrix[y][x] += rect[0][0] * shapeCounter
    matrix[y+1][x] += rect[1][0] * shapeCounter
    matrix[y][x+1] += rect[0][1] * shapeCounter
    matrix[y+1][x+1] += rect[1][1] * shapeCounter
    shapeCounter += 1

def rec(sx, sy,
        ex, ey):

I wouldn't use abbreviations. Use start_x, end_y to make your code clearer.

    if(ex - sx < 1 or ey - sy < 1):
        return
    #print("(%d,%d) (%d,%d)" %(sx,sy,ex,ey))

    if(matrix[sy][sx] != 0):
        rect = ul
    elif(matrix[ey][sx] != 0):
        rect = ll
    elif(matrix[sy][ex] != 0):
        rect = ur
    elif(matrix[ey][ex] != 0):
        rect = lr

You don't need all those parens

    hx = sx + (ex - sx) / 2
    hy = sy + (ey - sy) / 2

    writeRect(rect, hx, hy)

    rec(sx, sy, hx, hy)
    rec(hx + 1, sy, ex, hy)
    rec(sx, hy + 1, hx, ey)
    rec(hx + 1, hy + 1, ex, ey)

if __name__=='__main__':
    square(int(sys.argv[1]))


Simplify JavaScript collision detection with offset

Bug #1

Your code does not follow pattern (x - a < y + b) && (x + b + a > y) but (x - a < y + b1) || (x + b2 + a > y) instead. So our refactored formula is moot! obsolete

Bug #2

A collision is detected when any of the guards trigger, not when all.

Proposed Solution

Solving both bugs, we could refactor Nikko Khresna's method:

function detectCollision(source, target, line) {
  return
       source.location.x < target.location.x + target.width + line
    || source.location.x + source.width + line > target.location.x
    || source.location.y < target.location.y + target.height + line
    || source.location.y + source.height + line > target.location.y
  ;
}

and you can call it as follows

const collision = detectCollision(
  background.allPixels[i], background.allPixels[j], drawLineBetweenPixelRange);

Obsolete section because OP made a mistake in the formula: I'll keep it for historical reasons :)

Formula (Obsolete)

The way I see it, we could rewrite your expression:

var result = (x - a < y + b) && (x + b + a > y)

as

var result = (x - a - b < y) && (x + b + a > y)

and further as

var result = (x - (a + b) < y) && (x + (a + b) > y)

now we can substitute (a + b) with offset

var result = (x - offset < y) && (x + offset > y)

which means x and y have to be within offset distance of each other (|x-y| = abs(x-y))

var result = Math.abs(x - y) < offset

Now you can substitute x, y and offset with your variables, and - as suggested in the other answer - use a method that calculates this collision for you.


Job execution on records supplied by database

For starters code-wise, I'm guessing you can try allApplicationDetails.parallelStream().

Try to use more method references if possible as there are potential performance advantages to doing so.

Your try-catch is unusually wide, if an Exception is thrown from the first stream element, no further processing is done. Are you sure that is OK?

How is jobExecutionContext being used?

Other more worthy considerations...

  What I am doing is very simple, just get all the records and loop through one by one, and do things.

Can you batch some of these operations together? For example, do your 'downstream' libraries accept multiple inputs at once, or do they only send individually?

Do you really need to retrieve all 22 columns of 1.5 to 2 million records? Are there perhaps temporal columns on the table so that you can only fetch the most recently updated rows? Or a subset of the columns to minimize network traffic?

The bigger question is... can your actions be farmed off to an ExecutionService provider so that they can be performed asynchronously?

Simple in-memory processing of 1.5 to 2 million records in 2 minutes is relatively trivial with recent processing power. Having to incur network latencies (from emailing, twitter-ing tweeting, SMS-ing) is obviously going to introduce the 'timeout' issues that you are witnessing.

Most of these questions aren't really going to be covered by a code review (seeing how I've only dedicated four sentences to that), so perhaps you may want to drop by Programmers.SE for some of the more hard-hitting questions I've asked.


Longest Substring Without Repeating Characters in Scala

Some observations while looking over the code:

if (s.isEmpty) 0 - This isn't necessary. The code produces the correct results without this test. Removing it would reduce the level of indenting for the rest of the code.
if (!(lookupTable contains c)) - Dijkstra suggests that it is usually better to test for the positive condition, especially when there is an else block. It's often much easier to read and parse that way. In this case the else condition is "NOT table has c == false". (Ouch!)
val newLength - You actually don't need this variable. Try:length = length max i - start
lookupTable(c) = i - This assignment is made on both sides of the if test, which means it really doesn't belong there.

if (lookupTable contains c) {
  length = length max i - start
  start = lookupTable(c) + 1
  lookupTable.retain((k,v) => v >= start)
}
lookupTable(c) = i

But, of course, the most noteworthy is the use of mutable variables and data structures. Sometimes we have to fall back on imperative programming if functional means/methods are creating a bottleneck, but, short of that, the point of learning/using Scala is its Functional Programming capability.

Here's a reworking of the same algorithm using two index values to access a static array of characters. Each index is advanced via tail-recursive methods so everything remains immutable.

def lengthOfMaxSubstring(s: String): Int = {
  val chars: Array[Char] = s.toArray

  def headForward(leadx: Int, rearx: Int, cSet: Set[Char], best: Int): Int = {

    def tailForward(tlx: Int, cs: Set[Char]): (Int, Set[Char]) =
      if (chars(tlx) == chars(leadx)) (tlx + 1, cs)
      else tailForward(tlx + 1, cs - chars(tlx))

    if (leadx >= chars.length) best max leadx-rearx
    else if (cSet(chars(leadx))) {
      val (newTail, newSet) = tailForward(rearx, cSet)
      headForward(leadx+1, newTail, newSet, best max leadx-rearx)
    } else
      headForward(leadx+1, rearx, cSet + chars(leadx), best)
  }
  headForward(0, 0, Set(), 0)
}


SICP Exercise 1.3: Sum of squares of two largest numbers out of three

Finding the minimum of three numbers is easier than sorting three numbers, and it doesn't require creating a temporary array.

This runs about 10 times faster.

var sumSquareNotMin = function(x, y, z) {
    var min = Math.min(x, y, z);
    return -min * min + x * x + y * y + z * z;
};

As @Corbin mentioned, floating-point arithmetic is tricky.  I've arranged the negative term first, which should cope better with overflow.  However, in extremely unusual cases (such as when dealing with a mix of tiny and huge numbers), the result could differ from the original.


Method that returns an integer chosen by user

You should start using comparison operators,

for a range from 1 to 4, use this:

if (oneFour >= 1 && oneFour <= 4)

This reads naturally as "if variable is more than or equal to 1 and variable is less then or equal to 4", which is the same thing as "if variable is in range 1 to 4".

Other improvements:

Instead of setting the isError value, you can return oneFour; directly.
Using the above advice, you can change your loop to while (true), eliminating your isError totally.
Using the above advice, you can make the scope for the oneFour variable smaller, which is a good thing (when possible).
Braces. Always use braces.

Resulting code will look something like this:

static int oneToFour()
{
    while (true)
    {
        try
        {

            int oneFour = Convert.ToInt32(Console.ReadLine());
            if (oneFour == 1 || oneFour == 2 || oneFour == 3 || oneFour == 4)
            {
                return oneFour;
            }
            else
            {
                Console.WriteLine(_warning);
            }
        }
        catch { Console.WriteLine(_warning); }
    }
}


Proper and elegant way of Building a XML Document

I ended up changing my approach and went with a serialize method:

public static class SerializationHelper
{
    internal static string SerializeObject<T>(this T toSerialize)
    {
        var xmlSerializer = new XmlSerializer(toSerialize.GetType());
        var textWriter = new StringWriter();
        xmlSerializer.Serialize(textWriter, toSerialize);
        return textWriter.ToString();
    }
}
[Serializable]
public class SFDocument
{
    public int TableId { get; set; }
    public int PageSize { get; set; }
    public int PageIndex { get; set; }
    public string MultiCompany { get; set; }
    public int Language { get; set; }

        [XmlArrayItem("Field")]
        public List<string> Fields { get; set; }

        public List<TableFilter> TableFilters { get; set; }

        [XmlArrayItem("Field")]
        public List<string> Key { get; set; }
        public SFDocument(): this(5415, 1, 1, "No", 1033){}

        public SFDocument(int tableId, int pageSize, int pageIndex, string multiCompany, int language)
        {
            TableId = tableId;
            PageSize = pageSize;
            PageIndex = pageIndex;
            MultiCompany = multiCompany;
            Language = language;

            Fields = new List<string>();
            Key = new List<string>();
            TableFilters  = new List<TableFilter>();
        }
}

[Serializable]
public class TableFilter
{
    public string Field { get; set; }
    public string Filter { get; set; }

    public TableFilter() {}

    public TableFilter(string field, string filter)
    {
        Field = field;
        Filter = filter;
    }
}

void Main()
{
    var sfd = new SFDocument();
    sfd.Fields.Add("Field1");
    sfd.Fields.Add("Field2");
    sfd.Fields.Add("Field3");
    sfd.Fields.Add("Field4");

    sfd.Key.Add("Key1");
    sfd.Key.Add("Key2");
    sfd.Key.Add("Key3");

    sfd.TableFilters.Add(new TableFilter("field1", "filter1"));
    sfd.TableFilters.Add(new TableFilter("field2", "filter2"));
    sfd.TableFilters.Add(new TableFilter("field3", "filter3"));
    sfd.SerializeObject().Dump();
}


Implementing a Stack in Java for a technical interview

A stack should not know about the first element. A stack only know about the last element that was pushed, so the Stack object itself should only have one Node called last. Because of this, the constructor should be changed as well to only take one Node ex: public Stack(Node node).

Edit: As @vnp says, Node is private, so it cannot be created outside this class. Either create a constructor which takes an Object, or don't create any constructors and always create an empty Stack.

This constructor doesn't do anything and will throw a NullPointerException:

public Stack() {
    first.next = last;
}

In pop(), you shouldn't need to do any fancy while loops. Just check if last is null and if not, get last's data and set last to last.next:

public Object pop() {
    if(last == null) {
        return -1;
    }
    else {
        Object item = last.data;
        last = last.next;
        return item;
    }
}

In push(), you should simply set last to be the new Node, and have it point to the old last as it's next:

public void push(Object data) {
    last = new Node(data, last);
}

In peek(), you can change first to last and simply return last.data:

public Object peek() {
    if(last == null) {
        return -1;
    }
    return last.data;
}

One final point: you should not give your variables one character names like d, n, l, and f. If the variables in your constructor should have the same name as the private member variables, then give them the same name and prefix the members with this to differentiate them. For example, you can change the Node constructor to:

private Node(Object data, Node node) {
    this.data = data;
    this.next = node;
}


Checking whether one string is a rotation of another

I have a couple of comments on the code that you have posted.

First, your isSubstring function is not checking for a 0 length n1 string, so it will always return true for an empty string - is that what you want?

Second, your isSubstring function is calling s2.substring for every possible position until it finds a match.  You can limit the number of calls by performing a simple pre-check to see if s1.charAt(0) == s2.charAt(i).  If this is not true, then you know the substring will not match, saving you the overhead of calling the substring() function and creating the additional substring, and then performing the full String.equals() comparison.

Third, your rotation function is overly complex.  Since you're just doing an inString comparison, you only have to concatenate the input string to itself once, and then all valid rotations will be a substring of it.  To show the example visually, given an input string of "abcd", and the valid rotations of "bcda", "cdab", and "dabc":

abcdabcd
 bcda
  cdab
   dabc

All of the rotations are substrings of the double-concatenated version.  This accomplishes the same result of your function, but uses \$O(2n)\$ memory.  You originally listed yours as using \$O(n)\$ memory, but that is too low - you are using \$O(n^2)\$ memory, because you are concatenating all the permutations of the rotations.

Finally, your runtime \$O(n^2)\$ calculations aren't quite right, because you are short-circuiting out once you know that the string being searched is too long to be in the remainder.  Unless the input string is 1 character, then the number of permutations being checked is actually smaller - and if you add in the first character optimization I listed above, the total cost of the function would go down even further.


Leap year determination using guard clause

Compilers

Welcome to Code Review. First of all, "better" is a very personal opinion term, unless it has been defined. From a compiler's point of view, both functions do the same. As compilers are data flow analysis beasts, a decent one will simplify the function's flow to the following variant (see https://godbolt.org/z/yZCPOv):

ret = 0
if year & 3 /= 0
   goto end
ret = 1
if year % 100 /= 0
   goto end
ret = (year % 400 == 0)

end:
   return ret
return 0

As you can see, with -Os (or any other optimization level), your functions will result in the same assembler. This already answers your first (implicit) question:

  I was wondering whether it would be correct to change this function by using guard clauses like below

"Better"

Since both generate the same assembler, both are the same. We can of course check that by hand, as there are only four equivalence classes we have to check, but that's left as an exercise.

Regardless, the better way is the one that's easier to understand and follows fits into the rest of your code. If all your code is written in the first style, use that one. If you usually bail out early, use the latter. Neither have advantages over the other as soon as we enable optimizations. Without optimizations, your latter variant uses less jumps (but only a single one), and that's still compiler dependent.

In the end, use the variant you like most, but make sure you can still understand and explain it to yourself or someone else at a later time.

Just for completion, I personally prefer variants that have less jumps but are still readable, so I'd probably write something along

//! @returns whether @c year is a leap year
bool IsLeapYear(int year)
{
    //! A year is a leap year if its divisible by 4, but not by 100,
    //! @b unless it's also divisible by 400.
    return  (year %   4 == 0)
        && ((year % 100 != 0) || (year % 400 == 0));
}


Dynamic array sorting and storing program

import java.util.*;

It's often preferred to do separate imports rather than import an entire group.  Some disagree with this.  You can see both viewpoints argued at https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad

    ArrayList<Integer> array = new ArrayList<Integer>();

It's generally preferred to use the interface on the left side, as so

    List<Integer> numbers = new ArrayList<Integer>();

It won't make much difference in a program like this, but in a program where you pass your field as a method parameter, it can make it much easier to change implementations in the future.  It also encourages you to think about whether or not to use implementation specific functionality.

I prefer to use a more specific name than array.  Of course, in this case, you don't have much of one as the field is pretty generic.  I might also go with data.  Some would prefer array to these names.

    public Ascending()
    {
        array.add(2);
        array.add(4);
        array.add(6);
        array.add(8);
    }

Is that test code in your constructor?  That's not the place for it.  Consider

    public Ascending(List<Integer> initial)
    {
        numbers.addAll(initial);
    }

or better yet, something like

    public Ascending(List<Integer> initialData)
    {
        for (Integer number : initialData)
        {
            numbers.add(number);
        }
    }

As that makes sure that the order is correct (assuming add is implemented correctly).

Then you can change the values in the calling code rather than editing the class itself.  I.e. change

        Ascending obj = new Ascending();

to something like

        Ascending ascending = new Ascending(Arrays.asList(2, 4, 6, 8));

Alternately, you could define a new method add and call it in main.  This would also allow you to pull some code out of your ascendingOrder method.

    public void ascendingOrder()

Usually methods have verb names.  Since this takes input, I might call it something like addFromInput.

Also consider breaking this into three parts:  a for loop in main; an input process method; and an add method.

        for(int loop=0;loop<=10;loop++)
        {
            Scanner sc = new Scanner(System.in);

You don't need to make a new Scanner for every iteration.  Do it once prior to starting the loop:

        Scanner sc = new Scanner(System.in);
        for (int loop = 0; loop <= 10; loop++)
        {

I also added some whitespace in the for loop declaration.  It makes it easier for me to read (the computer won't care).

            System.out.println("The array is 2,4,6,8 ");

Consider writing a toString method so that you can just say

            System.out.println("The array is " + this);

Then it will output the current array on every iteration rather than outputting the original array.  This also allows you to change the initial values in only one place.

Alternately, you can write a print method that does the same thing.  The toString is more flexible though.

            int i,size = array.size(),last=size-1;

            for(i=0;i<size;i++)
            {
                if(input<array.get(i))
                {
                    array.add(i,input);
                    System.out.println("\nSorted array -:");
                    for(int y:array)
                    {
                        System.out.println(y);

                    }
                    break;
                }
            }

            if(input>array.get(last))
                {
                    array.add(size,input);
                    System.out.println("\nSorted array -:");

                    for(int q:array)
                    {
                        System.out.println(q);
                    }
                }

The indent looks wrong at the end there.  However, this whole block of code can be replaced with

            add(input);
            System.out.println("\nSorted array -: " + this);

if you define add and toString as previously discussed.

The add method can be defined as

    public void add(Integer number)
    {
        int i = 0;
        int size = numbers.size();

        while (i < size && number < numbers.get(i))
        {
            i++;
        }

        numbers.add(i, number);
    }

or

    public void add(Integer new)
    {
        int i = 0;

        for (Integer number : numbers)
        {
            if (new < number) {
                numbers.add(i, new);
                return;
            }

            i++;
        }

        numbers.add(new);
    }

among other implementations.

Note that I don't do your last check.  It's unnecessary in both versions.

In the first version, i always equals the correct place in the list when it exits the loop.

In the second version, it never reaches the code outside the loop unless it has already checked every previous location.  Note that when used with just one argument, add appends the element to the list.  This has the same effect as numbers.add(size, new); but is shorter to write.

Moving the printing of the array out of the add process simplifies the logic as well and saves duplicating code.


Page for editing an item from an expenses list

I've noticed a few things, which I'm going to elaborate in the following.

Interfaces

First off, your interface Expense.
It looks good so far, what I'd like to see is something like a structure in it, let it be alphabetically sorted or sort it optionals first or both, something like:

export interface Expense {
    amount: number;
    createdAt: number;
    description: string;
    id: string;
    note?: string;
}

It increases readability and allows others to quickly parse all existing keys (it's a bit nitpicking here, but it can have a huge effect).

Next up:

type PathParamsType = {
  id: string;
};
//component own props
type PropsType = RouteComponentProps<PathParamsType> & {
  id: string;
};

interface StateProps {
    expenses: Expense[]
}

interface DispatchProps{
    addExpense : (expense : Expense) => any,
    removeExpense : (expenseId : string) => any
}

type Props = PathParamsType & PropsType & StateProps & DispatchProps;

My two pain points here are, PathParamsType as well as DispatchProps.
PathParamsType is not speaking for it self, try to give variables or interfaces a very consice name. Also I thought, you accidentially declared { id: string; } twice. There is some kind of repetition that could have been avoided. Please consider the following:

interface WithId {
    id: string;
}

/* Maybe name ComponentProps to something more speaking. */
type ComponentProps = RouteComponentProps<WithId> & WithId;

Also, you are declaring a props type below, why didn't you merge all in the first place.
Something along the lines like: type Props = RouteComponentProps<WithId> & WithId /* & so on ... */;.

!!Side note!! Avoid stuff like: type Foo = { bar: string; foo: number; } we have interfaces for that.

Your function typing seems also a bit odd to me.

interface DispatchProps{
    addExpense : (expense : Expense) => any,
    removeExpense : (expenseId : string) => any
}

any seems in appropriate here. If you don't return a value from a function use void. If that function never returns (e.g. you quit the application inside that function), use the keyword never. But please don't use any.

To sum the interface section up, your code from above could have looked a bit like this:

interface WithId {
    id: string;
}

interface StateProps {
    expenses: Expense[];
}

interface DispatchProps{
    addExpense : (expense : Expense) => void;
    removeExpense : (expenseId : string) => void;
}

type Props = RouteComponentProps<WithId> & WithId & StateProps & DispatchProps;

React Component

Let's get to the component itself.

const EditExpensePage: React.FunctionComponent<Props> = (props): any => {
 /* ... */
}

The same as in the DispatchProps interface, a function does not return any. You actually broke the type system here. The following is fully compliant to your function/ variable typing.

const IamBroken: React.FunctionComponent<Props> = (props): any => 5;

This works as IamBroken should be a functional component but the function itself returns any and any is 5 (hopefully that explanation helps, at least a bit). What you would have wanted instead is:

const IamNotBroken = (props): React.FunctionComponent<Props> => 5; /* TypeScript: ERROR!!!! */

To apply the above pattern to your component (two solutions are available):

/* Variant 1 */
const EditExpensePage = (props: Props) => {
 /* ... */
}

/* Variant 2 */
const EditExpensePage: React.FunctionComponent<Props> = (props) => {
 /* ... */
}

Both solutions are totally fine, if you ask me though, I prefer the first one, it's sleek and if needed the compiler is able to infere the React.FunctionComponent part.

Component internals, functional programming

Inside your component I've noticed a few things as well.
let selectedExpense = GetSelectedExpense(props.match.params.id, props.expenses). From what I have seen, that you never re-assign selectedExpense. Therefore it's better to keep such variables as constants: const selectedExpense.

I see what you want to achieve with the GetSelectedExpense function. But there are better way's to achieve this in TypeScript/JavaScript. Have a look at Arrays over at MDN. There are a few helpful methods for overall array handling. What you are looking for is something like find.
(Side Note: There is a powerful concept that is called destructuring, and it helps you to avoid to write props. over and over again).

const { expenses, match } = props; /* Concept of destructuring, see my side note above */
const selectedExpense: Expense | undefined = expenses.find(expense => expense.id === match.params.id);

The onSubmit function could be improved in the following way. First, you want to avoid inline array functions as props (many linters are warning about possible performance issues). While that seems to be true, it also doesn't add to readability as well. Have a look at the following (I'm making use of the useCallback hook):

const { expenses, selectedExpense, removeExpense, addExpense, match } = props;
const selectedExpense: Expense | undefined = expenses.find(expense => expense.id === match.params.id);

const onSubmit = useCallback((expense) => {
    expenses.filter(exp => exp.id === selectedExpense).map(exp => removeExpense(exp.id));
    addExpense(expense);
}, [removeExpense, addExpense, selectedExpense]);

return (<ExpenseForm description={selectedExpense?.description} amount={selectedExpense?.amount} onSubmit={onSubmit}/>);

Last but not least, your compose thingy at the end. It seems wrong and should be like this (because compose is coming from redux which shouldn't be abused to chain higher order components):

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(EditExpensePage));


Construct URLs out of filenames of zero-byte images and open them in Firefox for re-downloading

I don't see anything really wrong with your script. It looks quite functional, and I don't see anything superfluous, though it is very verbose. If it weren't for the fact that I don't see a ; at the end of every line I'd assume you're more accustomed to C# than PowerShell from how structured your script is, not that there's anything wrong with that at all.

All that said, if it were me I think I'd have done a couple of things differently. Nested If statements are hard to read in my opinion. I would prefer to use a Switch statement instead to define cases.

process {
    Switch ($true){
        {(Get-UrlStatusCode -Url "$domain/data/$file") -ne 200} {"$domain/data/$file";continue}
        {(Get-UrlStatusCode -Url "$domain/cached/data/$file") -ne 200} {"$domain/cached/data/$file";continue}
        default {$null}
    }
}

You may note that I output the strings directly in the case scriptblocks; that is because Write-Output is implied, and everything not otherwise directed (such as capturing it in a variable, or using Write-Host or Out-File which redirect the output to the screen or a file respectively) is returned from a function to the pipeline.

For your Get-ChildItem command I would suggest using the -file parameter. That way the FileSystem provider only returns files to PowerShell and you don't have to filter out folder later. This will help speed things up in general, and also simplifies your filter. Kudos on using a filter by the way, almost nobody does it and it's really under appreciated IMHO. Along those same lines I would strongly suggest letting the provider filter files as well using -include, then passing it to your filter. It would look something like this:

filter isEmptyImage {
    if ($_.Length -eq 0 -and $_.Name -match '__.+\.(jpg|png|gif)') { $_ }
}
$emptyFiles = Get-ChildItem -Path $sourceDir -Recurse -Include '*.jpg','*.png','*.gif' -File | isEmptyImage | Select-Object -ExpandProperty Name

This way the File System provider only returns files that end in .jpg, .png, and .gif, and PowerShell has less to sort through.

Lastly, PowerShell is pretty bad about adding and removing things from arrays. It rebuilds its array each time, so I think I would avoid that by capturing the jobs all at once, and then changing the While clause to be a little more intrusive.

$jobs = foreach ($file in $emptyFiles) {
    $job = [powershell]::Create().AddScript($PrepareUrl).AddParameters(@{domain=$domain;file=$file})
    $job.RunspacePool = $rp
    [PSCustomObject]@{
        Job = $job
        Result = $job.BeginInvoke()
    }
}

Or if you want to get fancy you could simply do:

$Jobs = $emptyFiles | %{ [powershell]::Create().AddScript($PrepareUrl).AddParameters(@{domain=$domain;file=$_}) | %{ $_.RunspacePool = $rp;$_ } } | Select *,@{l='Result';e={$_.Job.BeginInvoke()}}

Then we change over to a Do/While loop instead of just a While loop:

$jobsLeft = $jobs | Where-Object { $_.Result.IsCompleted }
$urlList = Do {
    $jobsLeft = $jobs | Where-Object { $_.Result.IsCompleted }
    $WriteProgressParams = @{
        Activity = 'Waiting for jobs to complete'
        Status = "$($jobsLeft.Count) jobs remaining"
        PercentComplete = (($jobs.Count - $jobsLeft.Count) / $jobs.Count * 100)
    }
    Write-Progress @WriteProgressParams # splatting
    Start-Sleep -Milliseconds 50
    foreach ($job in $jobsLeft) {
        [string]$job.Job.EndInvoke($job.Result)|?{$_}
        [void]$job.Job.Dispose()
        [void]$jobs.Remove($job)
    }
} while ($jobsLeft.Count -gt 0)

Those are my suggestions, take'em or leave'em.


I know that you receive double, but you shouldn't get your system "infected" by double prices. This is just wrong. Convert them once you received them.

Instead of comparing your Doubles to find the Integer, you could also just work with the String and replace the zeros. This will also work with your double values and is a valid approach if you just want to render the number.

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class Main
{
    public static void main(String... args)
    {
        System.out.println(format(new BigDecimal("2.1111")));
        System.out.println(format(new BigDecimal("5454542.1111")));
        System.out.println(format(new BigDecimal("5454542.1")));
        System.out.println(format(new BigDecimal("5454542")));
    }

    private static String format(BigDecimal price)
    {
        return createFormat().format(price).replace(",00", "");
    }

    private static DecimalFormat createFormat()
    {
        DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
        dfSymbols.setDecimalSeparator(',');
        dfSymbols.setGroupingSeparator(' ');
        final String currency = "$";
        dfSymbols.setCurrencySymbol(currency);
        return new DecimalFormat("###,###,##0.00 \u00A4", dfSymbols);
    }
}

This will give you:

2,11 $
5 454 542,11 $
5 454 542,10 $
5 454 542 $


Console application to search for files that contain a match for a regex

private static void SearchDirectory(string path)

This method does not need to be recursive. You could use the Directory.EnumerateFiles method

Directory.EnumerateFiles Method (String, String, SearchOption)

where

  One of the (SearchOption) enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.

I don't know how your regex looks like but for simple pattern with wildcards you can use the second parameter

  The search string to match against the names of files in path. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions.

As far as the multithreading is concered you should definitely use the new TPL (Parallel.ForEach) instead of creating your own threads.


There's a timing attack. To see whether a user has registered or not, I can try to login. If it fails fast, the user is not registered. If it takes time, the user is registered. To fix this information disclosure, calculate some dummy hash even if the user cannot be found in the database.

The SQL part is fine.

The $submitted_username calls htmlentities too early. The only correct time to call htmlentities is exactly at the point where you embed a text into an HTML snippet. That doesn't happen in your code, though. To fix this, rename the variable from submitted_username to submitted_username_html, to prevent it from being used in any other context. For example, code that reads db_insert($submitted_username_html) looks wrong enough to warrant a thorough code review.

Your code could benefit from being split into a few well-named functions. After doing that, the main code might read like this:

$logged_in_user = log_in($_POST);
if ($logged_in_user === FALSE) {
    // …
} else {
    // …
}

When you extract all the detailed code into a function, you can use early returns for all the error cases. And when you step through the code using a debugger, you can easily skip over all the details of the login process, if you are not interested in it.

In the config part, you should prefix all variable names with db_, to avoid confusing the username with the submitted_username. Or group them into an object called db_config. Then you can access it as $db_config['username']. There, the identifier username is appropriate since it is qualified by the word db_config, which makes it unambiguous.

The SHA-256 algorithm you use for hashing is not secure enough anymore since specialized hardware can compute it too fast, even with 65536 iterations. PHP has a built-in set of password hashing algorithms. Just use that instead of iterating on your own. Migrating from your custom password hashing to the PHP default will cost a bit of time and work, but it's worth the effort. And since you are not the first to do that, there's already plenty of documentation on it. Probably. Hopefully.


Sorry. You need to use two statement since you are updating two different tables.


Automated suggestions

If you don't have shellcheck installed, grab it, or use the online service.  It reports a bunch of questionable constructs:

202986.sh:4:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
202986.sh:6:38: note: read without -r will mangle backslashes. [SC2162]
202986.sh:8:22: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:10:9: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:12:10: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:12:61: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:12:84: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:14:15: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:14:41: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:14:68: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:16:11: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:16:22: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:16:51: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:18:8: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:19:8: note: Double quote to prevent globbing and word splitting. [SC2086]
202986.sh:23:7: note: Use $(..) instead of legacy `..`. [SC2006]
202986.sh:25:7: note: Use ./*glob* or -- *glob* so names with dashes won't become options. [SC2035]
202986.sh:25:24: note: Double quote to prevent globbing and word splitting. [SC2086]

Prefer lower-case for variable names

We normally use upper-case names for environment variables intended to change the behaviour of programs we use.  It's better to use lower-case for ordinary shell variables.

Check for program failure

At present, if compilation fails, we'll still proceed, likely with old code.  Instead, we should abort execution if any of the steps fail.  It's pretty easy to ask the shell to do this for us (though it's worth learning the exceptions); we can also ask it to check we don't expand any undefined variables, too:

set -eu

Useless use of xargs

I've never seen this pattern before:

echo "$filename" | xargs program

Unless your filename contains whitespace (the rest of the code implies it doesn't), that's exactly

program "$filename"

Unusual date conversion

Do you really mean to give the result file a name given by day-within-year and minute-within-hour?  That's a surprising combination, and certainly deserves a justifying comment if it is really what you want.

Avoid temporary files

Pipeline processing can produce results with lower latency than storing intermediates to temporary files.  We can pipeline one input into pdftk and create the other using a process substitution in roughly this manner:

enscript "$CPPFILE" | ps2pdf \
    | pdftk - <(./a.out | enscript | ps2pdf) \
            cat output "$TITLE.final.pdf"

Consider using Make

If you make a change to a single file, you need to re-run the script (re-doing all the compilation and output processing) to update the final output.  Make is more intelligent: you can write pattern rules that enable you to re-build and re-run only what's out of date, without wasting time and energy on the bits that haven't changed.

It can also clean up the temporary files, and you could write a "clean" rule to clean up all the result files.

If you do write a Makefile, be sure to bring it here for review!


Performance shifting for SQL Database and Linq memory grouping

It's hard to tell if this will work without trying it but I'd at least give this a shot. By calling ToList on your calls, visits and visitors and then concating them you are losing the database query structure, try this instead:

            using (var db = new Track_LOpEntities())
            {
                var visitors = db.JTrack_Visitors.AsNoTracking()
                    .Where(v => v.CreatedOn >= start & v.CreatedOn <= end)
                    .Select(v => new DashHelper() { DateAndTime = v.CreatedOn.Value, Source = 1 });

                var visits = db.JTrack_Visits.AsNoTracking()
                    .Where(v => v.DateTimeStart >= start & v.DateTimeStart <= end)
                    .Select(v => new DashHelper() { DateAndTime = v.DateTimeStart.Value, Source = 2 });

                var calls = db.JTrack_Calls.AsNoTracking()
                    .Where(v => v.calldate >= start & v.calldate <= end)
                    .Select(v => new DashHelper() { DateAndTime = v.calldate.Value, Source = 3 });
               var totals = visits.Union(calls).Union(visitors);
               var visitorsGroup = totals.GroupBy(q => new { q.DateAndTime.Date, q.DateAndTime.Hour });

        List<DashGraph> dg = new List<DashGraph>();

        foreach (var g in visitorsGroup)
        {
            dg.Add(new DashGraph()
            {
                Date = g.Key.Date,
                Hour = g.Key.Hour,
                TotalVisitors = g.Where(x => x.Source == 1).Count(),
                TotalPageViews = g.Where(x => x.Source == 2).Count(),
                TotalCalls = g.Where(x => x.Source == 3).Count()
            });
        }

            }

Also I'm not sure why you need a transaction scope, your not doing any updates.


Programmatically close optical drive tray

Note that the Visual Studio C# code editor has an integrated code beautifier. Depending on your setup, it can be executed with different shortcut keys. Call it from the menu for the first time, so that you can see the active shortcut keys (it is Ctrl-E-D for me). Menu: Edit > Advanced > Format Document.
By using a technique called LINQ (Language INtegrated  Query), you can get the management object easier. It uses extension methods from the namespace System.Linq. Therefore, you must include a using System.Linq; at the top of your code. Then you can query with
ManagementObject managementObject = moc.FirstOrDefault();
if (managementObject == null) {
     // Handle error (output text or throw exception)
     Console.WriteLine("Could not find a management object!");
} else {
     ...
}

This FirstOrDefault extension method calls GetEnumerator and MoveNext internally and returns null if no object is available.
Do not give it the name obj. Almost everything is an object, so this name is not very informative.
Exceptions are a complex matter. It raises a lot of questions like "should I throw an exception or output a message to the user?", "should I create my own exception types?", "should I log the exception?" etc., etc. There is no single best answer to these questions. Therefore, I content myself with giving you a link: C# Exception Handling Best Practices.
If you intend to reuse this functionality, you could encapsulate it into your own class:
public enum OperationResult
{
    Failure,
    NoDriveFound,
    DriveIsOpenOrEmpty,
    MediaIsLoaded
}

public class OpticalDriveCloser
{
    public OperationResult CloseFirst()
    {
        ...
    }

    public OperationResult[] CloseAll()
    {
        ...
    }
}

It returns an operation status as enumeration type and lets the calling application decide how to proceed. I.e. it does neither call Console.WriteLine nor throw exceptions and focuses on pure, non-UI logic. A console application will have a different UI-logic than a windows forms application or a web application.


Just a few points of advice:

avoid using globals. The reason they are bad is that they allow functions to have hidden (as in non-obvious and undeclared) and thus hard to understand side effects. Also, this can lead to spaghetti code.
try to use str.format when you print out strings:

print(KEYWORD + ":" + exploit(HOST, credentials))

should be:

print('{}:{}'.format(KEYWORD, exploit(HOST, credentials)))

your docstrings are partially good. I'm saying partially because telling me things that I already know isn't helping. For example, :param host: or :param credentials:. I already know these are parameters to that function. You could at least specify the data structure they denote.
consider rewriting this:

(line for line in response_lines if PATTERN.match(line))

like this:

(line
for line in response_lines
if PATTERN.match(line))

The reason I like writing it like this is that it allows you to see more easily that you've changed you're code (on a svn / git repo).