1. Introduction

In this answer I'm just going to look at the function counting_sort. You'll see that there's plenty here for one answer.

2. Review

There's no docstring. What does this function do? What arguments does it take? What does it return?
When a function returns a result, it's conventional to name it with a noun or noun phrase describing the result. Hence the built-in function is called sorted rather than sort.
The first argument is named collection but this needs to be a sequence, so a name like seq would be better.
If the second argument were the number of keys (rather than the maximum key) then there would be no need to increment it (and similarly no need to decrement this argument in the callers).
The variables B and C could have more descriptive names, for example result and count respectively.

3. Performance

The lists B and C can be initialized more quickly using the * operator:

B = [None] * (len(collection) + 1)
C = [0] * d_range

The main loop looks like this:

for i in range(len(collection) - 1, -1, -1):
    B[C[collection[i][digit]]] = collection[i]
    C[collection[i][digit]] -= 1

But this means that collection[i] has to be looked up three times on each iteration. It is faster to iterate over the items in the collection (using reversed to do so in reverse order), avoiding the lookups:

for item in reversed(collection):
    B[C[item[digit]]] = item
    C[item[digit]] -= 1

Now, item[digit] has to be looked up twice on each iteration. It is faster to cache this in a local variable:

for item in reversed(collection):
    k = item[digit] # the key for this item
    B[C[k]] = item
    C[k] -= 1

Now, item[digit] is looked up twice for each item, once when counting the number of occurrences of each key, and once in the main loop. This can be reduced to a single lookup by creating an array of keys at the start:

keys = [item[digit] for item in collection]

and then using this when counting keys and in the main loop.
If C[k] is changed so that it has the value \$\left|\{\mathrm{key}<k\}\right|\$ rather than \$\left|\{\mathrm{key}≤k\}\right|\$, then this has three benefits: (i) the main loop can iterate over the collection in forward order, avoiding the call to reversed; (ii) the slice B[1:] at the end is avoided; (iii) the initialization of B is simplified.

Applying all these changes results in the following code:

def counting_sorted(seq, nkeys, digit=-1):
    """Return a new list containing all the items from seq in ascending
    order of item[digit], which must be a non-negative integer less
    than the parameter nkeys.

    """
    keys = [item[digit] for item in seq]

    # count[k] = |{key = k}|
    count = [0] * nkeys
    for k in keys:
        count[k] += 1

    # index[k] = |{key < k}|
    index = [0] * nkeys
    for k in range(nkeys - 1):
        index[k + 1] = index[k] + count[k]

    result = [None] * len(seq)
    for k, item in zip(keys, seq):
        result[index[k]] = item
        index[k] += 1
    return result

I find that this reduces the runtime to about 60% of the original. On my test data this is a little faster than the built-in sorted.

4. Interface improvements

There are a couple of infelicities in the interface to counting_sorted, and I think that for ease of use and understandability of the code it would be worth fixing them, even at the expense of a few percent slowdown.

The function requires us to pass in the value of nkeys. This is fragile (it would be easy to pass in the wrong value) and redundant (it can be computed from the data). So I would remove this parameter and add the line:

nkeys = max(keys) + 1

after the computation of keys.
The function looks up the sort key for each item by indexing the item with digit. But this only works for some kinds of item. Other sorting functions (like the built-in sorted) take a general key-derivation function, and I think it would be better to do so here. In your radix sort function you can make the key functions you need using operator.itemgetter

Revised code:

def counting_sorted(seq, key=None):
    """Return a new list containing all the items from seq in ascending
    order. A custom key function can be supplied to customise the sort
    order. Sort keys must be non-negative integers.

    """
    if key is None:
        keys = seq
    else:
        keys = list(map(key, seq))
    nkeys = max(keys) + 1

    # count[k] = |{key = k}|
    count = [0] * nkeys
    for k in keys:
        count[k] += 1

    # index[k] = |{key < k}|
    index = [0] * nkeys
    for k in range(nkeys - 1):
        index[k + 1] = index[k] + count[k]

    result = [None] * len(seq)
    for k, item in zip(keys, seq):
        result[index[k]] = item
        index[k] += 1
    return result

5. Answers to questions

Naming is one of the hardest things about programming. Reading other peoples' code is good practice—you'll find yourself continually thinking, "what on earth did the programmer mean by foo?" and then you can apply the same thought process to your own code.
I wanted to avoid the slice on B, and this change followed straightforwardly.
I think you're right and nkeys was a poor choice of name. What I meant by this was "number of (possible) distinct key values" but the name nkeys doesn't make that clear. (Naming is hard!)
You're right in this particular case that passing radix would be faster than calling max. But you'll see in the introduction to §4 that I gave my reasons for making these changes as "ease of use and understandability". The point is that by generalizing the function (so that it works in the general case, and not just in one specific context) it is easier to re-use, and easier for other programmers to understand and maintain.

This is a theoretical concern—after all, maybe you'll never want to re-use this code and no other programmers will ever work on it. But considered as an exercise I think it's valuable: in a professional context it's a good idea to make code as clear and easy to maintain as possible.
It's easy to change radix_sort to use the revised interface. There are two sensible approaches. (i) Transform each item into a list as before, and then pass key=itemgetter(-1) on the first iteration, key=itemgetter(-2) on the second iteration, and so on. (ii) Leave the items unchanged, and pass key=lambda x: x % radix on the first iteration, key=lambda x: (x // radix) % radix on the second iteration, and so on.
I use timeit.
As I said in the introduction, this answer is quite long enough already. Maybe someone else can have a look at radix_sort?


Hash function in C for sets and associative arrays

... in knowing whether this is a good approach ...

Small improvements

Keep in range

uint_fast32_t may be wider than 32 bits.  Values outside the 32-bit range in x will have a result that depends on those excessive upper bits.  I'd suggest coding to insure 1) only the lower 32 are used to form the answer and 2) the answer only has lower 32-bits set.  #2 being an important aspect here - don't generate results outside 32-bits.  When uint_fast32_t is 32-bit, a good compiler will optimize away the & 0xFFFFFFFF masks.

uint_fast32_t h = x & 0xFFFFFFFF;
...
return h & 0xFFFFFFFF;

Readability

Style issue:

I find reading hexadecimal constants easiest to read when the case of the x differs from the digits.

// h = h * 0xae6a495b;
h = h *    0xAE6A495B;

Avoid naked magic numbers.

I did not note the 2 hex constants were the same until a bit later.  Defines/const objects would have helped and self-document the code.

const uint_fast32_t hash_m = 0xAE6A495B;
const uint_fast32_t uint32_mask = 0xFFFFFFFF;
const unsigned hash_shift = 16;

uint_fast32_t h = x & uint32_mask;
h = h ^ (h >> hash_shift);
h = h * hash_m;
h = h ^ (h << hash_shift);
h = h * hash_m;
return h & uint32_mask;

Why 32 for a general approach?

With "good approach to integer hashing or general hashing" seems to assume an "integer" is 32 bits.  Such an assumptions breaks the "general hashing".  For a "general hashing" I would use unsigned or perhaps size_t and steer the constants based on the type's range.  Either that or forgo the "general" adjective to this code and simply say its is designed for 32-bit as hash_u32() implies.

uint_fast32_t vs. uint32_t

uint_fast32_t has 2 advantages, 1) it always exists since C99 as uint32_t may not exist on rare machines that lack 32-bit types.  2) It may be "faster".

Yet uint_fast32_t is also problematic.  It is more difficult to test.  Proper function testing obliges a test on machines where uint_fast32_t is 32 and more than 32-bit as the above masking discussion points out potential pitfalls on the rarer  wide uint_fast32_t.

I doubt code was written to take advantage of #1 (uint32_t may not exist).

Unless #1 is a design concern, best, especially for a "general" function, to stick to fixed width or regular types and reserve the "fast" types for internal function usage and not as a function parameter nor return value.  Using "fast" as part of the function I/F, may be useful in select cases, but not "general".

Missing header

I'd expect #include <stdint.h> as part of the code to define uint_fast32_t, else code does not compile.

Good Hash?

I threw together a quick test to see how  32-bit values mapped to what.

Note: On my machine with a 64-bit uint_fast32_t, code died on flag[i] unless OP's function had h masked with h & 0xFFFFFFFF.

#include <stdint.h>
uint_fast32_t hash_u32(uint_fast32_t x) {
  uint_fast32_t h = x & 0xFFFFFFFF;
  h = h ^ (h >> 16);
  h = h * 0xae6a495b;
  h = h ^ (h << 16);
  h = h * 0xae6a495b;
  return h & 0xFFFFFFFF;
}

#include <assert.h>
#include <stdio.h>
void hash_u32_test(void) {
  _Static_assert(CHAR_BIT == 8, "CHAR_BIT != 8");
  unsigned char *flag = calloc(1, 1u << (32 - 3));
  if (!flag) return;
  uint32_t twice = 0;
  uint32_t x = 0;
  do {
    uint_fast32_t y = hash_u32(x);
    uint_fast32_t i = y / 8;
    uint_fast32_t j = y % 8;
    if (flag[i] & (1u << j)) {
      twice++;
    }
    flag[i] |= (1u << j);
    x++;
  } while (x);
  printf("twice %lu\n", (unsigned long) twice);
}

int main() {
  hash_u32_test();
  return 0;
}

My result was twice 0 implying a one-one mapping of all 32-bit inputs to output, so from a hash perspective, that is good for OP's function to pass.


This can be simplified to this:

$(window).scroll(function() {
    var $sticky = $('#contentSideIner'),
        elTop = $sticky.offset().top,
        wTop = $(window).scrollTop();
    $sticky.toggleClass('sticky',  wTop > elTop)
        .toggleClass('stickyBottom', wTop > elTop + 4685);
});

The window object already exists, so no need to wait until it loads before attaching an event handler to it.
Don't cache objects outside of the event handler unless it's really needed (consumes more memory, code is less encapsulated, makes your page susceptible to problems if layout or DOM elements change, etc...)
Use jQuery chaining for multiple method calls on the same jQuery object
Only use one event handler and put both .toggleClass() calls in the same event handler.


The organization of the program is rather haphazard:

It starts with a word value calculation function
Then it checks for the existence of the input file
Then defines the ordinals map (which the first function depends on!)
Then it creates a triangleNumbers map
Then it reads the words from the input file
Then it counts the words that pass the triangularity test

Interspersed among that are three unit tests.

Surely these definitions could be grouped together more logically.

makeTriangleNumber is altogether wrongly named.  It actually has nothing to do wth triangular numbers.  Rather, it sums the values of the letters of a word.  I would call it wordValue instead.

Within the makeTriangleNumber function, .reduceLeft(_ + _) could just be written as .sum.

Personally, I would simplify the definition of ordinals by taking advantage of Seq.zipWithIndex, then compensate for the off-by-one difference by adding the length of the word.  (That may be a controversial move, since ordinals would no longer match the problem description.)

For extracting the words from the file, I suggest using Regex.findAllMatchIn(source:CharSequence), which gives you an Iterator of regular expression matches.

The heart of your program is the for loop.  It's not very good functional programming, though.  Ideally, the entire exercise should revolve around one line of code that looks like this:

words.count(word => isTriangularNumber(wordValue(word)))

How should isTriangularNumber be defined?  In your loop, you're discovering triangular numbers like this:

var tmp = Stream.from(triangleNumbers.max._2 + 1)
  .map((x) => (x * (x + 1) / 2, x))
  .takeWhile(_._1 <= candidate)

… using the triangleNumbers map for memoization.  I propose a more elegant definition — a lazy stream:

val triangularNumbers = Stream.from(1).scan(0)(_ + _)

Rather than the given formula, this definition relies on the recurrence principle that makes the numbers "triangular" in the first place.

Suggested solution

val wordValue = {
  val ordinals = ('A' to 'Z').zipWithIndex.toMap
  (word:String) => word.length + word.map(ordinals).sum
}

val isTriangularNumber = {
  val triangularNumbers = Stream.from(1).scan(0)(_ + _)
  (n:Int) => triangularNumbers.find(_ >= n).get == n
}

val inputFile = Source fromFile Paths.get(args(0)).toUri
val words = "\"([^\"]*)\"".r findAllMatchIn(inputFile.mkString) map(_.group(1))

val count = words.count(word => isTriangularNumber(wordValue(word)))
println("The answer is: " + count)


Your proposed changes will have marginal impact.  The way IIS works, IHttpHandlers are not invoked until the entire request body has been transferred.  That is, the entirety of the file data is already available by the time your first line of code runs.  That means your stream copying is just moving bytes around in memory, and while that is not instantaneous it's probably not slow enough that it's worth making it asynchronous.

I think you already know this, but you should make the Postgres call asynchronous if that's an option.  With the current call, you have a thread taken up waiting for a remote process to do its work.  With an asynchronous call, that thread would be available to do real work.  Of course, that only makes a difference if there is an incoming request that's waiting for a thread.


Honestly it looks like most of your code can't be simplified. However I found:

to_positional_argument_string is a mouth full, and people would understand your code easier if you just use repr.
to_keyword_argument_string is another mouth full and so you could call it kw_repr.
You may want to add a comment explaining what isinstance(field, abc.Iterator) is for. This is because at first it confused me.
[Controversial] You can change your code so that you don't need to be passed constructor_or_initializer. To do this you'd create parameters when __repr__ is first used.


That depends on how you define better. Better might be more CPU or memory efficient, or it could be fewer bytes in the compiled code, or better parallelization.
But I am going to take a chance on assuming that this code runs on a reasonably normal platform and has no special requirements, and therefore being better generally means better readability.
Readability Improvements
In which case, your code is fine. But we can make it easier to read by splitting it into named steps and wrapping it in a good function.
public List<Integer> getNumbersOccuringOddTimes(final List<Integer> numbers) {
    final Map<Integer, Integer> numberCounts = numbers.stream().collect(groupingBy(Function.identity(), counting()));
    final Predicate<Entry> isOdd = e -> e.getValue() % 2 == 1;
    return numberCounts.entrySet().stream().filter(isOdd).map(Entry::getKey).collect(toList());
}

I've made five minor adjustments to your code to help with readability. I have;

Added a descriptive method name that wraps the steps.
Split the two streams into separate statements.
Used static imports (not shown) for the Collectors functions.
Moved the modulus check into a predicate variable (isOdd) so it can be named.
Swapped out the lambda in .map to a method reference because it is shorter and more descriptive.


Order of evaluation of function arguments

Your code returns 1/2 if the (f 0) is evaluated first, not 0. A better way would be to return the last argument to f, with a default of 0.

(define last 0)
(define (f x)
  (define temporary last)
  (set! last x)
  temporary
)

When (+ (f 0) (f 1)) is evaluated with (f 0) first, execution is as follows:

f is called with 0
temporary is set to 0 (the default last)
last is set to 0 (the argument to f)
temporary (0) is returned
f is called with 1
temporary is set to 0
last is set to 1
temporary (0) is returned
0+0=0

If (f 1) is evaluated first, then execution is as follows:

f is called with 1
temporary is set to 0 (the default last)
last is set to 1 (the argument to f)
temporary (0) is returned
f is called with 0
temporary is set to 1
last is set to 0
temporary (1) is returned
0+1=1


Making an str(which makes a string from an object) for the node class which would simplify the graph return method
the str converts an object to a string type

is this a dense graph or sparse graph?
Sparse Graphs have a lot less edges between vertices
Sparse Graphs can be efficently used as adjency lists
Dense Graphs can be efficnetly represented with an adjency matrix (2d list of bool)
Note: if you are familar with binary, you can use an int to set and get bits in Python (more space efficent than 2d list)

I would suggest a new class for what to do when the algorithm reaches a node (such as NodeVisit)
This new class can a function called call(node) and run as object(the_node)
This allows diffrent code to run on node such as print out or add distances along a path

Dijkstra's algorithm has a lower Big O with a min priority que
Min priority ques are similar to real life lines with priority levels and tasks
This can be made from a list where left_row is 2 * row and right_row is (2 * row) + 1

Make a seperate function or even class for Dijkstra's algorithm
Dijkstra's algorithm can be done using parallel lists for vertex, distance, prev vertex
Looking up the wikipedia article for Dijkstra's Algorithm shows its psudo code

If you plan to use node anywhere else then make self.visited a parallel array and not inside the node class
Another situation where int and binary can be used for space efficency


Producer/Consumer implementation using condition_variable

A couple of comments on your test-harness code:

for (int i = 0; i <= 20; i++)
// ...
for (int i = 1; i <= 20; i++)

You've got 21 consumers and only 20 producers. This means your test code will never terminate, right?

You can avoid off-by-one errors like this by getting comfortable with the "half-open range" idiom of C-style languages. Every for-loop you write in C, C++, Java, C#, JavaScript, Perl, or whatever, should look like this:

for (int i = 0; i < N; ++i)

Notice that it starts at 0 (inclusive) and goes up to N (exclusive), so it iterates exactly N times.

    consumers.push_back(std::thread([&](){
        stack.get();
    }));

is a verbose way of writing

    consumers.emplace_back([&](){ stack.get(); });

I see you writing

arr_ = new T[size_];

— that's a red flag. Prefer to use std::vector<T> or std::unique_ptr<T[]> instead of raw pointers. The reason is that those will behave properly on copy-construction and/or move-construction, whereas your current pointer-based code requires some extra code in the special member functions (constructors and assignment operators) in order to work correctly.

Look up the Rule of Zero and try to apply it here.

Since you're relying on the destructor to delete[] the array allocated in your constructor, you should =delete the copy constructor and copy assignment operator; otherwise you're allowing the client code to make shallow copies that will lead to use-after-free and double-free bugs.

But! Your current code does actually result in an implicitly deleted copy constructor, because the default definition would have been ill-formed, because you can't copy-construct a std::condition_variable. So you're okay, modulo some really verbose error messages and the danger that someone might come along and refactor your class to remove the uncopyable members.

Shouldn't a Stack be copyable? or at least movable? Right now your Stack is neither copyable nor movable, because of its std::condition_variable and std::mutex members.

The names set and get (for push and pop respectively) are ill-chosen.

The name capacity for space_left is also ill-chosen. The word capacity already has a meaning in C++: it means "maximum possible size", as in std::vector::capacity. When you're trying to find a name for a thing, choose the name that best represents the thing itself — usually this is easy because most things already have established names (e.g. stack, push, pop). When you need a name for a thing that really doesn't yet have a name, then you just need to avoid naming it the same as something else that's already in the lexicon (e.g. capacity).

capacity needs to be a private member function, or else it needs to take the mutex mu, because otherwise the client code could call x->capacity() at the same time as some other thread is calling x->get() and suddenly you've got a race condition.

However, if you simply slap a mutex lock around the body of capacity, you'll find that set and get both deadlock, because each of them calls capacity while the mutex mu is already (still) locked.

std::cout << "Getting num: " << top_value << " Capacity: " << this->capacity() << std::endl;
locker.unlock();

Calling such expensive I/O routines under a mutex is a bad habit anyway. You could at least improve the code slightly by rephrasing it as

int cap = this->capacity();
locker.unlock();
std::cout << "Getting num: " << top_value << " Remaining capacity: " << cap << std::endl;

Consider what happens when T is not default-constructible; consider what happens when T is default-constructible but its default constructor is relatively expensive. What do you want to have happen in those cases?

Consider what happens when T is move-only. What do you want to have happen in that case?

Consider what happens when the following line in set throws:

top_++;
arr_[top_] = num;  // T::operator= THROWS AN EXCEPTION

What happens the next time you get from the stack? What do you want to have happen in that case?

But basically, this seems like reasonably good code (modulo the wrong names for things like push and pop, and the for-loops).

Your use of mutexes and condition variables seems fine to me. notify_one will probably be more efficient than notify_all, but either one is fine.


First: the runtime is O(wn), as it should be for this algorithm.

Consider a single run of _LSBSort. Let n be the length of arr. Clearly the first loop is time O(n). Let si be the length of deques[i]. Then the second loop is time
$$ O(s_1) + O(s_2) + \dots + O(s_{10}) = O(s_1 + s_2 + \dots + s_{10}).$$
Noting that each element is present in exactly one of the deques, we conclude
$$s_1 + s_2 + \dots + s_{10} = n.$$
Thus the entire method runs in time O(n). As it is called w times, we conclude the entire algorithm is O(wn) time.

Second: some comments on the code.

These methods should be static.
Use an ArrayList for deque. Arrays of generics are just too ugly.
Call the list deques because it is plural.
Initialize all the deques up front. Clear and reuse between iterations.
Use extended for loops throughout.
Use loop instead of recursion.

private static void LSBSort(int[] arr) {
    List<ArrayDeque<Integer>> deques = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        deques.add(new ArrayDeque<Integer>());
    }

    for (int d = 1; d <= 1000; d *= 10) {
        for(int i : arr) {
            deques.get((i / d) % 10).add(i);
        }

        int cursor = 0;
        for (Deque<Integer> D : deques) {
            for (Integer j : D) {
                arr[cursor++] = j;
            }

            D.clear();
        }
    }
}


Supplying parameterless callback to function expecting void * param

When I compile your code with gcc (9.1.1 ) and use the command line option -Wall, I get a warning:
cb.c:20:10: warning: passing argument 1 of ‘call’ from incompatible pointer type [-Wincompatible-pointer-types]
   20 |     call(noparams, context); // warning expected
      |          ^~~~~~~~
      |          |
      |          void (*)(void)

So you might want to up the warning level on the compilation. You could suppress this warning with a cast -- it is ok to cast function pointers.
However the real problem is that it is, I believe, undefined behaviour to call a function (either directly or through a function pointer) with a different number of arguments from those given in its definition. (You might want to check this by asking a stack overflow question with tags C and language lawyer).
If it is indeed UB then you have to avoid it. It might appear to work with a particular compiler, but fail arbitrarily with a different compiler, or even with the same compiler on a different platform.
What you have to do, I think, is to provide a callback with the demanded arguments. You could do this, for example, by adding
void noparams_wrap(void* p) {
    noparams();
}

and passing noparams_wrap to call() rather than noparams() itself.


Outlook VSTO: Fastening email loop on a large pst file

After looking at your code I see some stuff which could speed this up if coded different.
'/Full folder path splited into array and removed the rootfolder name with tag (e.g Outlook_Backup -> _Backup is the tag)
Dim FolderPath() As String = f.FolderPath.TrimStart("\"c).Split("\").Skip(1).ToArray

'/Array joined back to get MailFolderPath without tag
Dim MailFolderPath As String = String.Join("\", FolderPath)

For each Item in f.Items you are trimming the FolderPath and Split it by \ to Skip the first arrayitem before you call ToArray(). The ToArray() isn't needed because this overload of String.Join would take an IEnumerable(Of String).
But the main point here is that f.FolderPath won't change for each Item. It would be much faster to pull this outside of the For loop.
Removing the BackGroundWorker.ReportProgress() for each and every Item would speed this up as well. How about reporting progress only for each folder?

Although VB.NET isn't case sensitive it would be good to follow the .Net Naming Guidelines for naming things.


Divide and Conquer algorithm for counting inversions

More clear by using extra argument?
If you passed in a count by reference to each function, and each function incremented this count instead of returning a new count in a tuple, the code might look cleaner.  For example, this:

IntVec as, bs, cs;
std::tie(as, left_inv) = count_inv(left);
std::tie(bs, right_inv) = count_inv(right);
std::tie(cs, split_inv) = count_split_inv(as, bs);
return std::make_tuple(cs, left_inv + right_inv + split_inv);

would become this:
IntVec as = count_inv(left, count);
IntVec bs = count_inv(right, count);
return count_split_inv(as, bs, count);

And in main(), this:
long long inv;
std::tie(ys, inv) = count_inv(xs);

would become this:
long long inv = 0;
count_inv(xs, inv);


Reporting the highest satisfied poker hand in F#

The solution here is to use an active pattern, which enables you to create a custom matching function.

You can even reuse your existing functions.

It would look like

let |StraightFlush|_| hand = tryStraightFlush hand

then you can use it like this

match hand with
|Straightflush(score) -> ...
| ....


No
You cannot output \$\Theta(n^2)\$ items in \$o(n^2)\$ time. Output size is a trivial lower bound of any algorithms.


You also may use csv module to iterate over your file. Your code would be faster because of C implementation and cleaner without line.rstrip(endl).split(sep)


Seems like you already incorporated a few of the suggestions from back when this was on StackOverflow, e.g. changing the inner loop to max. However, you do so in a very inefficient way:

you create a slice of the list, O(n) time and space
you get the max of that slice, O(n) time
you get the index of that element, O(n) time

Instead, you can get the max of the range of indices, using a key function for comparing the actual values at those indices:
largest = max(range(0, lastUnsortedInteger+1), key=arr.__getitem__)

This way, this step has only O(n) time (for Python 3).
Some other points:

the an parameter (the length of the array/list) is not necessary, you can use len
in my opinion, it is a bit simpler looping from first to last index, and using min instead of max accordingly
since the swap is a single line now and only used once, we could inline this directly into the sorting function
the function modifies the list in-place, so no return is needed and might lead users to expect that the function does not modify the list but create a sorted copy instead
technically, arr is not an array but a list, and you might prefer snake_case to camelCase (it's "Python" after all)

My version:
def selection_sort(lst):
    for i in range(len(lst) - 1):
        k = min(range(i, len(lst)), key=lst.__getitem__)
        lst[i], lst[k] = lst[k], lst[i]

Needless to say, for all practical purposes you should just use sorted or sort.


The 128 case can be optimized as:

    if (packetType == 128)
    {
        // packet stores number of times following pixel is repeated
        repeat = (packetHdr & ~(1 << 7)) + 1;
        bytes = inFile.ReadBytes(bytesPerPixel);
        for (int j = 0; j < repeat; j++)
        {
            bytes.CopyTo(pixData, count);
            count += bytes.Length;
        }
    }

The 0 case can be optimized as:

    if (packetType == 0)
    {
        // packet stores number of pixels that follow
        repeat = ((packetHdr & ~(1 << 7)) + 1) * bytesPerPixel;
        bytes = inFile.ReadBytes(repeat);
        bytes.CopyTo(pixData, count);
        count += bytes.Length;
    }


On Stack Overflow duplicate questions are closed.

For your question, a search of Code Review Stack Exchange for "[go] selection sort" finds, amongst others,

Selection sort algorithm with increasing/decreasing sort options

which has several detailed answers that address your question. For example, the code for my answer, simplified for ascending order only, is

// selectionSort sorts the array a into ascending order.
// The selection sort algorithm is an in-place comparison sort
// with O(n*n) time complexity.
func selectionSort(a []int) {
    for i, x := range a[:len(a)-1] {
        k := i
        for j, y := range a[i+1 : len(a)] {
            if x > y {
                // out of order
                k = i + 1 + j
                x = y
            }
        }
        a[k], a[i] = a[i], x
    }
}

My code is idomatic Go and it's more than twice as fast as your code when running a Go benchmark which sorts 1024 random integers.

BenchmarkDemas           300       4894852 ns/op
BenchmarkPeterSO        1000       2339806 ns/op


An alternative would be to recursively/iteratively trim off the first and last elements of the string until you reached the middle one or two characters.

(defn trim-first-and-last [s]
  (subs s 1 (dec (count s)))
)

(defn get-middle-recur [s]
  (if (<= (count s) 2)
      s
      (get-middle-recur (trim-first-and-last s))
  )
)

(= (get-middle-recur "a") "a")
(= (get-middle-recur "aa") "aa")
(= (get-middle-recur "aba") "b")
(= (get-middle-recur "abba") "bb")
(= (get-middle-recur "abcba") "c")
(= (get-middle-recur "abccba") "cc")


Naming

You did a good job with most your variable names, but not so much with your class name. Typically, you would not want ANY class name to start with a lowercase letter. The class name is also not too descriptive (what is balanced, again?). I recommend changing public class isBalanced to public class TreeBalanceChecker or public class IsBalanced if you don't heed the second part (don't forget to change the file name as well).

Secondly, what is up with haTab? Everything else was so well named, this just seems out of place. Changing it to heightTable would be more descriptive.

Permissions

What I learned is that if you don't have a modifier on your functions, and no other class is using them, add private. That's just standard Java. On the same line, if another class does need to access something, make it public. You seem to be missing a lot of those.

Constructors

There is only one constructor for TreeNode. That is not very helpful if you want to set the left and right children or parent at construction time, or you don't want to set a value.

New code

/**
 * Definition for a binary tree node.
 */
class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode parent;

    public TreeNode(){
        val = 0;
    }
    public TreeNode(int x) {
        val = x;
    }
    public TreeNode(TreeNode left, int x, TreeNode right){
        this.left = left;
        this.right = right;
        val = x;
    }
    public TreeNode(TreeNode parent, TreeNode left, int x, TreeNode right){
        this.left = left;
        this.right = right;
        this.parent = parent;
        val = x;
    }

}

public class isBalanced {
    // first we will get the left height and right height of the node
    // and compute the height difference.if it is > 1 we will return false
    // hashtable to maintain height of each node to reduce the no of redundant
    // height computations
    private static Hashtable<TreeNode, Integer> heightTable = new Hashtable<>();

    static int height(TreeNode root) {
        // if the node is null then it returns the height as -1
        int heightOfNode;
        if (root == null) {
            return -1;
        }
        if (heightTable.containsKey(root)) {
            return haTab.get(root);
        }
        int leftHeight, rightHeight;
        leftHeight = height(root.left);
        rightHeight = height(root.right);
        // finds the height of left subtree and right subtree and returns
        // the max of both + 1
        heightOfNode = Math.max(leftHeight, rightHeight) + 1;
        haTab.put(root, heightOfNode);
        return heightOfNode;
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight, rightHeight;
        leftHeight = height(root.left);
        rightHeight = height(root.right);
        // if left child and right child are balanced and the difference in
        // their heights is < 2
        // then it is balanced
        if (isBalanced(root.left) && isBalanced(root.right)
                && Math.abs(leftHeight - rightHeight) < 2) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(-2);
        root.right = new TreeNode(-3);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.right = new TreeNode(-1);
        System.out.println(isBalanced(root));
    }
}

Additions

These are just some things to think about adding, not necessary at all

let the user create the tree with STDIN
expand TreeNode class to store height instead of the table
add a method to display the entire tree in STDOUT

Happy coding!


Python comes with a built-in pickle module for serialization:

>>> import pickle
>>> with open('data', 'wb') as f: pickle.dump(9 ** 33, f)
>>> with open('data', 'rb') as f: print(pickle.load(f))
30903154382632612361920641803529

(P.S. I wouldn't use a filename ending with .txt to store binary data.)


Perfect Number usage in higher order function

Here is my corrected solution.

object ListMapHigherOrder{
  def main(args:Array[String]) = {

    val intList: List[Int] = args.map(_.toInt).toList

    def isPerfectNumber(input: Int) :String  = {
      val check_sum = ( (2 until input).collect  { case x if input % x == 0 => x }  ).sum
      if (input <= 1) "false"
      else if ( check_sum == input - 1 ) "true"
      else "false"
    }

    def myHigherOrderFunction(argFn: Int => String, argVal:List[Int]): List[String] = { argVal.map(argFn) }

    println(myHigherOrderFunction(isPerfectNumber, intList))
  }
}

Since this is supposed to be code review, I will not mince words. Some problems I noticed with your code:

1) Your formatting is irregular. For anyone trying to understand your code, this is a needless obstruction.

2) You do not check if the number is negative or equal to 1. In all such cases, the number is not perfect. You need to check for these cases.

3) You are using a var for check_sum. This is an eyesore for anyone who knows the language. Prefer immutable values.

4) You copied and pasted your code for isPerfectNumber from someone else without understanding what it does. In this case, the code you copied and pasted is actually wrong, because it gives the wrong answer for 1. It is probably also a good idea to explicitly check if the number is negative. The original code was also relatively inefficient because of the call to square root. The change to remove square root is only a micro-optimization, but it should be faster.

5) You are trusting that calling toInt on a String won't throw an exception. This depends on the assignment specification. If the exercise assumes you will always get well-formed input, then I suppose this is fine. But if not, you need to use a try-catch block or a Try monad. Since I am not sure if you need this stuff, I won't add it to your solution.

6) The idiom for myHigherOrderFunction is strange. There is almost no point to passing a list and a lambda function to a function just so you can call map on it. If you need to call map, just call map. Creating a wrapper function is unnecessary and an eyesore. I understand that this is what the assignment asks you to do, probably to test your understanding of functions as values. However, it is ugly code, I cannot help but mention that this should be avoided normally.

I think this question is rather manageable, and that if you had spent more time on it, you would have been able to get it yourself. However, I will not lecture you. The biggest mistake you made was trusting someone else's code without checking it yourself. So you should not trust me either.


Is it acceptable to pass an Exception into a function that then may or may not throw it?

As Winston said, use full names for your variables.  Also keep the case consistent - then when you write $Object instead of $object it will be more obvious.

Static should almost never be used if you are writing object oriented code.  You basically have namespaced functions with this code.  Rather than write a static utils class for SQL I would write an SQL class (or use an existing one).  If you want objects of a class to be created PDO can do this for you.

As far as the exception goes:

No, you shouldn't do that.  Your code creates an object that it doesn't need to every time the function is called.  At the worst you would have passed in the exception string and instantiated with new Exception in fetchIdIntoInstance.

Main Recommendation

You are better of dealing with an exception after it has happened at a level where you know why it happened.

Keep your lower level functions simple:  If something strange happens throw an exception.  In your case I would assume that your sql should work in fetchIdIntoInstance and throw an exception if you can't make the new instance.

At a higher level database operations will have a meaning.  You will be doing something specific that is easily understood.  Maybe you will be adding a record to a table or reading an object that you expect to be in the database.  At this point you can handle the exception and write meaningful information to a log file or something similar.

You could catch exceptions in getThatOneInstance but it does not seem like the right place.  I think you should catch it higher up where you know what to do with it.


jQuery "on('click')" to toggle webpage content

The code pattern:

$("#main").html("");
$("#main").append(bar);

can be simplified to:

$("#main").html(bar);

In general, the code is, clear, easy to read, and well organized. All the decisions among alternatives are reasonable and straight forward. Doing the simplest thing that might work is a good approach because it avoids adding unneeded complexity to the necessary complexity.

The use of template literals rather than strings might be unnecessary complexity because the templating features are not used. Support for template literals is not universal among browsers. The page may break for no reason for some people. To put it another way, using template literals rather than strings creates potential broken pages for no gain in browsers that support template literals.


Arduino Create and send data to Serial Port (Software Serial function)

CreateMessage is a misnomer. The message it creates vanishes as soon as the function returns. Its real purpose it to send a message. So call it appropriately.
Too many comments duplicating the functionality. For example, any time you feel you need a comment as in

digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit

it means that you really need a function

void enableRS485Transmit(....) {
    digitalWrite(SSerialTxControl, RS485Transmit);
}

The inner loop of CRC computation can be simplified. Notice that no matter what, the first thing you do is crc16 >>= 1. Factor it out:

    for (i = 8; i != 0; i--) {
        crc16 >>= 1;
        if (crc16 & 0x0001) {
            crc16 ^= 0xA001;
        }
    }

Granted, the compiler will likely notice that. Still it is good for the reviewers and maintainers.
The function takes 24 bytes of stack space. Seems like a bit too much. Granted, the compiler would likely optimize out most of it. Still, consider

    enum { Slave, Function, AddHi, AddLo, DataHi, DataLo, CrcHi, CrcLo, MsgSize};
    byte message[MsgSize] = {1, 6, Address>>8, Address, Data>>8, Data};
    unsigned int crc = CRC(message, CrcHi);
    message[CrcHi] = crc;
    message[CrcLo] = crc >> 8;

If your compiler has <stdint.h>, I strongly recommend using an explicit uint16_t rather then unsigned int (of unspecified bit width).


refactor Python code with lots of None type checks

As an example,

    getItems = [x for x in items if x.find("div", class_="quantity")]
    if getItems:
        itemsInStock += getItems

can be written

    itemsInStock.extend(x for x in items if x.find("div", class_="quantity")]

extend (and for that matter, +=) are no-ops on empty lists.

Now, I'm not sure what some of the function you call return, but I don't like that getItemsInStock returns None if no items are in stock -- it makes more sense to return an empty list in that case. If your other functions did the same, you wouldn't need any of your if guards. Another example:

    pages = self.combThroughPages()
    if pages:
        for each in pages:
            ...

can be written

    for page in self.combThroughPages():
        ...

but only if combThroughPages returns an empty list when there are no, um, pages, I guess? (It's not clear from your function name.)


Optimizing code solution for Palindrome Index-Hackerrank

It may well be an error @ Hackerrank. If I'm not mistaken the nodejs-code expects you to provide console input. Or you may have accidentally changed something in the surrounding code.

Concerning your code: writing ES20xx, it's good practice to terminate lines with a semicolon (;), because not doing so may result in nasty bugs.

  let palindrome = s === s.split('').reverse().join('')

You don't need this variable. It could've been:

if(s !== s.split('').reverse().join('')) {

Furthermore, if you wanted to declare a variable, it could've been a const here (you are not modifying it afterwards).

Just for fun, here's an alternative approach, using substrings from the original given string:

"hannach,ava,reopaper,annana,ewve,blob,otto,michael,racecaar,wasitacatiwsaw"
  .split(",")
  .forEach(name => console.log(`[${name}] => ${palindromeIndex(name)}`));

function palindromeIndex(s) {
    if (`${[...s]}` === `${[...s].reverse()}`) { return "is palindrome"; }
    let i = 0;
    while(i < s.length) {
      const sx = `${i < 1 ? s.substr(1, 0) : s.substr(0, i)}${s.substr(i + 1)}`;
      const  rsx = `${[...sx].reverse().join("")}`;
      if (sx === rsx) {
        return `removing '${s[i]}' (@ position ${i}): '${sx}'`;
      };
      i += 1;
    }
    return -1;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


Methods to get single and multiple JDBC results

You can factor out the boilerplate like so:

protected String getSingleFilePathResult(Query query) throws UwsException {
    return doWithConnection(conn -> conn.getSingleFilePathResult(query));
}

protected List<String> getMultipleFilePathResults(Query query) throws UwsException {
    return doWithConnection(conn -> conn.getMultipleFilePathResults(query));
}

protected <T> T doWithConnection(Function<conn, T> callback) throws UwsException {
    try (JdbcPooledConnection conn = createConnection()){
        return callback.Invoke(conn);
    } catch (SQLException sqle) {
        throw new UwsException(SQL_EXCEPTION + sqle.getMessage(), sqle);
    }
}


Store the newest 100 numbers. (delete old ones)

You could make your life way easier if you used the deque data structure.

from collections import deque

d = deque(maxlen=2)
d.append(1)
d.append(2)
d.append(3)

sum(d)  # gives 5, which is the sum of the last two inserted elements.

With this, you call the sum function only when you really need to, which will improve your performance if you don't need the sum every time (like when you're first populating the container).

Also, deque probably has faster length checking internally than using len onto a list.


Loops would be the perfect tool here to reduce duplication; although getting it exactly as you have will be difficult due to you currently spelling out numbers ("first", "second", "third"...). For the sake of simplicity, I'm going to ignore the numeric words, because producing those is non-trivial and a whole project on its own unless you use an existing library.
In their place, I'm going to use a simple function. This can be optimized using a dictionary acting as a case, but I think it's fine as-is besides some minor duplication:
def format_number(n: int) -> str:
    last_digit = str(n)[-1]
    if last_digit == "1":
        return f"{n}st"
    elif last_digit == "2":
        return f"{n}nd"
    elif last_digit == "3":
        return f"{n}rd"
    else:
        return f"{n}th"

>>> format_number(2)
'2nd'
>>> format_number(5)
'5th'
>>> format_number(1)
'1st'

It goes a little bit wonky in the teens ("12nd"), but like I said, it isn't a super straightforward problem, and I don't want to sidetrack the review.

First, you can ask for numbers using a loop, and in the loop, place the entered numbers into a list:
nums = int(input("How many numbers you want to calculate?\n"))

entered_nums = []
for n in range(nums):
    x = float(input(f"Enter the {format_number(n + 1)} number: "))
    entered_nums.append(x)

When run, I get:
How many numbers you want to calculate?
3
Enter the 1st number: 9
Enter the 2nd number: 8
Enter the 3rd number: 7

And entered_nums now holds [9, 8, 7].
If you're at all familiar with list comprehensions though, you'll notice that that loop can be simplified a bit:
entered_nums = [float(input(f"Enter the {format_number(n + 1)} number: "))
                for n in range(nums)]

And this will have the same effect with a bit less bulk.

Once you have the numbers to do math on, you need to ask for the operation to apply, then apply that operation.
For the first, I'm going to import the operator module because it'll make life much easier. operator.add for example is the same thing as +; only it can be stored as an object.
I'm going to use a dictionary to store the menu code to operator relationship:
from operator import add, sub, mul, truediv
. . .

func = int(input('''What do you want to do?
            1 to add
            2 to subtract
            3 to multiply
            4 to divide
            '''))

code_to_op = {1: add,
              2: sub,
              3: mul,
              4: truediv}

This allows for easily doing math:
>>> code_to_op = {1: add,
                  2: sub,
                  3: mul,
                  4: truediv}

>>> op = code_to_op[3]
>>> op(3, 5)
15

Note though that a bad dictionary lookup will cause an error. code_to_op[5] for example will raise a KeyError. I didn't handle that for simplicity and because you currently aren't handling bad input. It should be dealt with though.

So now once we can get the operator that the user wants, we need to apply it to the numbers they entered. Again, a loop (or something that acts as a loop) is our friend here. We'll need to keep track of the current result of the equation (the "accumulator"), and a loop to do the math:
acc = entered_nums[0]  # The first number they entered will be our starting accumulator
for entered_num in entered_nums[1:]:  # And we'll loop over all the numbers after the first
    acc = op(acc, entered_num)

print(acc)

If the user entered in the numbers 2, 3, and 4, and then entered in 1 for the operator (add), acc would hold 9.0 at the end of that loop.
The acc+loop pattern is incredibly common in programming though. So common in fact that it has its own name: reduce:
from functools import reduce

. . .

result = reduce(op, entered_nums)

reduce here automates the looping for us. It's essentially equivalent to the previous loop that calculated the same value.

After taking that all into consideration, I'm left with:
from operator import add, sub, mul, truediv
from functools import reduce

def format_number(n: int) -> str:
    if n == 1:
        return f"{n}st"
    elif n == 2:
        return f"{n}nd"
    elif n == 3:
        return f"{n}rd"
    else:
        return f"{n}th"

while True:
    try:
        nums = int(input("How many numbers you want to calculate?\n"))

        entered_nums = [float(input(f"Enter the {format_number(n + 1)} number: "))
                        for n in range(nums)]

        code_to_op = {1: add,
                      2: sub,
                      3: mul,
                      4: truediv}

        func = int(input('''What do you want to do?
                    1 to add
                    2 to subtract
                    3 to multiply
                    4 to divide
                    '''))

        op = code_to_op[func]

        acc = entered_nums[0]  # The first number they entered will be our starting accumulator

        for entered_num in entered_nums[1:]:  # And we'll loop over all the numbers after the first
            acc = op(acc, entered_num)

        print(acc, "\n")

    except(ZeroDivisionError):
        print("You can never divide by Zero!")

    except(ValueError):
        print("Check your input.")

And an example run:
How many numbers you want to calculate?
6
Enter the 1st number: >? 9
Enter the 2nd number: >? 8
Enter the 3rd number: >? 7
Enter the 4th number: >? 6
Enter the 5th number: >? 5
Enter the 6th number: >? 4
What do you want to do?
                    1 to add
                    2 to subtract
                    3 to multiply
                    4 to divide
                    >? 1
39.0

There is still a lot that can be mentioned (grouping things into functions, fixing some error handling), but I need to start studying for an exam :)


Looks to me as if you've already got the most elegant solution in mind.

In C++14 you'd remove the dependency on std::function and simply return a naked lambda, like this:

template <class Output, class... Inputs>
auto make_function(const Output& output, Inputs&... inputs) {
  return [&](typename Inputs::result_type... input_vals) {
    int dummy[] { 0, ((void)inputs.set(input_vals),0)... };
    return output.get();
  };
}

but in C++11 you can't make a function-that-returns-a-naked-lambda without a ton of boilerplate — if it's even possible at all.

Also, a nitpick, with props to @stephan-t-lavavej's talk at CppCon 2014. You wrote

(inputs.set(input_vals),0)...

but what you should have written was

((void)inputs.set(input_vals),0)...

to avoid accidentally calling MaliciousUserCode::operator,(int).


Black hole

If the input is invalid, then there's no feedback to the caller, you just swallow the problem.  This may be ok for your situation, but generally I'd try to make sure the caller has some way of knowing if the operation did anything.

if (input == null || input.length < 2) {
    return;
}

You also don't have any tests for these edge cases (which may be fine if you really don't care about them, but then why bother checking the input at all).

Naming

Rather than giving your variables a single character and a descriptive comment at the top, consider giving the variable a meaningful name endOfRed.  You don't need the comment and you're not going to forget what the variable refers to as you move through the code.

int i = 0; // the end of the red region

Random

From a human perspective, running a bunch of tests with random values can be very reassuring.  However you want your unit tests to be repeatable and reliable.  Having random numbers generated to seed your tests can result in intermittent failures which you want to avoid (consider the impact if this was part of a larger build process).  If you do want to use random, then it would be a good idea to make sure that on failure the input data set is logged / displayed.  The only thing worse than an intermittent failure is one that you can't reproduce.

assertTrue

I'm not a huge fan of assertTrue.  People will often use it to assert equality and the feedback you get from assertTrue (expected true, was false) is a lot worse than the feedback you get if you're asserting equality (expecting x,y,z but got x,y).  When stuff goes wrong you want to know what values were being asserted against and often assertTrue hides that.  From your comments, it looks like you may have had messages which might have been better...

The hole in your tests

You don't actually check that the flags you're producing are the flags for the input.  So, I could replace your code with the following:

public static void dutchFlag(int[] input, int mid) {
    for(int i = 0; i < input.length;i++) {
        input[i] = mid;
    }
}

Even though this code is clearly wrong (since it's essentially a whitewash), all of your tests would pass.  I think your tests would actually be more expressive (and more reliable) if instead, you had three utility functions... findRed, findWhite and findBlue.  These would take in the generated flag and return an array of the numbers to the left of mid, equal to mid, to the right of mid.  So, findRed might look something like this:

private int[] findRed(int[]flag, int mid) {
    for(int index = 0; index < flag.length; index++) {
        if(flag[index] >= mid) {
            return Arrays.copyOfRange(flag, 0, index);
        }
    }
    return flag;
}

A test using it, might then look like:

@Test
public void testDutchWithoutMids() {
    int[] input = {12, 34, 781, -1};
    int mid = 90;

    FlagSorts.dutchFlag(input, mid);

    assertThat(findRed(input, mid)).containsExactlyInAnyOrder(12, 34, -1);
    assertThat(findWhite(input, mid)).isEmpty();
    assertThat(findBlue(input, mid)).containsExactlyInAnyOrder(781);
}

This validates that the flag sections actually contain the numbers that you're expecting them to and if there's any errors you get told what the expected values were and what the actual values are.  Note, I'm using AssertJ for my assertions.


Readers-writers problem using wait notify

This code in the read() method is broken:

public void read() throws InterruptedException {

    synchronized (readWriteLock) {
        while (numberWriters > 0 || numberWriteRequests > 0) {
            readWriteLock.wait();
        }
    }

    numberReaders++;

    System.out.println("Reader #" + Thread.currentThread().getId() + " started reading.");
    Thread.sleep(1000);
    System.out.println("Reader #" + Thread.currentThread().getId() + " finished reading.");

    numberReaders--;

    synchronized (readWriteLock) {
        readWriteLock.notifyAll();
    }
}

Since numberReaders ++ and -- is not in a synchronized block, it essentially may as well not happen as far as other threads are concerned, or, worse, it could partially happen (like the ++ may happen, and the -- may not).

Additionally, they may not produce the right results, anyway. The ++ operator is not atomic, and it is possible for the value to be ++ in two different threads at the same time, and the result to be just one increment for both invocations.

Bottom line is that, from a multi-threaded perspective, this code is broken.

References:

Is the pre-incriment operator thread-safe?
Java Concurrency in Practice (read this if you can)
Java's ReadWriteReentrantLock


Calculator for calculating price per feet amounts

About the only thing that I don't like in it is that you have to edit the code each time a price changes. I'd prefer that to come from a dynamic source, especially if you are going to use it in more than one spot.


// __PRETTY_FUNCTION__ means "$FUNCTION_SIGNATURE [with T = $TYPE]".

When you call type_name_finder(), the only part that changes in __PRETTY_FUNCTION__ is $TYPE. We can use this information to strip the static decoration surrounding that type.

template <typename T>
static constexpr auto type_name_finder() {
    std::string_view name, prefix, suffix;

#if defined(__clang__)
    name = __PRETTY_FUNCTION__;
    prefix = "auto type_name_finder() [T = ";
    suffix = "]";
#elif defined(__GNUC__)
    name = __PRETTY_FUNCTION__;
    prefix = "constexpr auto type_name_finder() [with T = ";
    suffix = "]";
#endif

    name.remove_prefix(prefix.size());
    name.remove_suffix(suffix.size());
    return name;
}


The n parameter is redundant, as it should be possible to deduce the matrix dimensions from matrix itself, using matrix.length and matrix[0].length.  You seem to have made the assumption that matrix is square — you should either document or relax the restriction.

I suggest writing three separate inner functions for the three possible rotations.  One code-reuse technique you could use for the ±90° rotations is to combine transpose and row-swap operations.


Reviewing the Dockerfile and docker-compose.yml files for a basic nodejs mysql project

Probably it's better to you concrete node version.

Also, you can try expressjs framework.

I have got simple example of Dockerfile here in this sub-directory of my repository.
But that is without Docker Compose and connection to any database.


Calculating count of square numbers between two numbers

Can be done in \$O(1)\$ time

The count should be:

\$\lfloor{\sqrt n}\rfloor -\lceil{\sqrt m}\rceil + 1\$

or in terms of your program:

return Math.floor(Math.sqrt(numberTwo)) - Math.ceil(Math.sqrt(numberOne)) + 1;


The code as it stands doesn't read well. And your text is also slightly confusing. I do believe I would rework the code to something along these lines:

Initialize an array of tasks
Add each task to array, with necessary conditions if needed
Await execution of all tasks

This would make for your code to handle extra tasks better, it would clear up the confusion on which tasks actually gets executed, and finally all tasks can be executed in parallell however the compiler feels like doing that.


Modified Sieve of Eratosthenes has very long runtime

First of all some stylistic remarks:

Unnecessary vertical whitespace

You have many empty lines that don't improve readability (and actually hurt because the reader needs to do more scrolling)

Inconsistent indentation

You need to stick to one indentation style and not switch between several.
Make sure to always use the same depth of indentation.

This facilitates faster parsing of the code's structure while reading it.

Use C++11

While it might not be available to you or scares you of because of the many new features, I can only advice you to use the improvements that came with C++11.

Foremost you should go for the auto keyword and range based for loops.
The latter gives a much stronger hint at what a loop iterates:

for(std::list<long long>::iterator output = candidates.begin(); output != candidates.end(); output++){

    runningSum += *output;
    }

becomes

for(auto output : candidates) {
    runningSum += output;
}

Use standard algorithms

There are several instances in your code where you reimplemented standard algorithms to some extent:

The last loop could be replaced by:

long long runningSum += std::accumulate(candidates.begin(), candidates.end(), 0);

Performance

The first thing anyone should do regarding performance problems is profiling. Most of the time our guesses about what is slow are actually wrong.

Yet, I want to give some pointers on what could be hindering performance:

std::list provides poor cache locality, especially when it has been thinned out very much (and especially when it is so big as yours)
the original sieve works via scattering not gathering: in your algorithm each number in the list (after the current prime) has to be tested against each sieve value in the original there is no testing but only striking out values that are multiples of the current prime

Usually prime sieving is done with an array like interface that allows to strike out elements via random access. I am keen to know why you have chosen a list instead.

Random remarks

What is the line

candidates.begin();

good for?

Why is the value of lastSieve hardcoded? You should calculate it from the size of the sieve itself.

Your variables are declared too early:

runningSum is only needed at the end
sieve can be declared locally in the while loop
inner can be declared locally in the while loop

This hints at a more fundamental problem of your code:

Use more functions

Some parts of your code could gain from functions that give names to what you are doing there.

The inner while loop could be moved into a function removeMultiples.

Your whole problem code should be wrapped into a function to be reused later on (hint: project euler will require efficient prime calculation later on!)


Sorting algorithms with utility functions and iterators

There are few problems with merge:

There is no guarantee that T can be constructed from an integral constant (how about sorting strings?). Even if it could, 0xFFFFFFF (BTW, what is this number?) is not necessarily a largest possible value (e.g.T could be 64 bit wide, or 16 bit wide); besides this value may legitimately belong to user data. Bottom line it, using an artificial sentinel is wrong.

(left[i] < right[j]) condition breaks merge sort stability (which is very important reason of using merge sort in the first place).

Calculating pivot as  first + (last - first)/2 assumes a random access iterator, which rules out merge sorting linked lists (which is a second important reason for merge sort to be used). Take a look at std::distance and std::advance.
C++ has partition for a reason: it is very important algorithm of its own. I strongly recommend to factor it out as a function, and call it from quick_sort.
I don't see the reason for qck_sort and mer_sort to exist.

Take a look on how all std:: algorithms operate on semi-open ranges. One of the reasons for that is that last (in STL sense) serves as a natural sentinel. For example, merging may look along the lines of

void merge(I first1, I last1, I first2, I last2, O dst)
{
    while ((first1 < last1) && (first2 < last2)) {
        if (*first1 <= *first2) {
            *dst++ = *first1++;
        } else {
            *dst++ = *first2++;
        }
    }
    while (first1 < last1) *dst++ = *first1++;
    while (first2 < last2) *dst++ = *first2++;
}


Using for loops create new object with other objects with matching id's

In this loop object.otherarray.array you use id property to to ensure to have necessary match. So I assume this item.fields.image.sys.id === asset.sys.id always should have only one match. And it resulted in the following code:

object.array.forEach((item) => {
    item.fileds.image.fields = object.otherarray.array.filter(
        (asset) => item.fields.image.sys.id === asset.sys.id
    )[0].fields;
});

Some explanation:

object.otherarray.array.filter(
        (asset) => item.fields.image.sys.id === asset.sys.id
    )[0];

is an equivalent of your item.fields.image.sys.id === asset.sys.id. In other words, firstly we find necessary asset. Then when we have it we can use fields property to assign it to item.fileds.image.fields.

I also have another variant of my remake:

object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
        .filter((asset) => imageId === asset.sys.id)
        [0].fields;
});

While it is more verbose version, it is more clear and structive so I would recommend to use this one.

I am open to your comments as I suppose I could not understand your correctly.

Edit: as @MarcRohloff said, you can use find instead of filter. But note, that `find has poor support in browsers:

object.array.forEach((item) => {
    const imageId = item.fields.image.sys.id;
    item.fileds.image.fields = object.otherarray.array
        .find((asset) => imageId === asset.sys.id)
        .fields;
});


Since the output of each step depends on the previous step, it is impossible to entirely eliminate the loop unless the formula can be simplified to allow a multi-step computation. However, the code can definitely still be improved.

Calling np.concatenate is generally inefficient since it requires
memory reallocation and data copying. As long as possible, one should
preallocate all the needed memory and update it iteratively.

Some computation can be moved out of the loop to improve efficiency.
E.g., the np.random.normal call can be done only once. Same with alpha * delta_t.

More meaningful variable names could be chosen.

It is always a good practice to have docstrings and type hints in your code.

Here is one version of improved code:
def cir_simulations(alpha: float, mu: float, sigma: float, delta_t: float, sim_steps: int, num_sims: int):
    """
    Simulate the CIR process.

    Parameters:
    Input
    ...

    Output
    ...
    """
    output_shape = (num_sims, sim_steps + 1)
    sim_results = np.empty(output_shape)
    sigma_dW = np.random.normal(0, sigma * np.sqrt(delta_t), size=output_shape)
    alpha_dt = alpha * delta_t
    sim_results[0, :] = r_prev = mu

    for r_t, sigma_dWt in zip(sim_results[1:], sigma_dW):
        r_t[:] = r_prev = (mu - r_prev) * alpha_dt + np.sqrt(r_prev) * sigma_dWt

    return sim_results

I'm not very familiar with the meaning of all the parameters in the formula. There are two things that I have doubts in your computation:

The rate \$r\$ in the formula is initialized with the same parameter mu used in the iterative computation. Is it expected?
The increment \$dW_t\$ used a fixed variance of 1. Is this supposed to be the case or should it be another function parameter?


Improving the time complexity of my back pack algorithm

OO is not always appropriate

In this case the class is not needed, just write a free standing function for simplicity.

Make the code speak, not the comments

For example:

# @param m: An integer m denotes the size of a backpack

Can be omitted if you write:

def backPack(backpack_size: int, ...):

and:

# @return: The maximum size

Can be omitted if you write:

def backpack_max_size(...):


Your iterative definition will not produce correct results for most values of n.

When rewriting a pure recursive function as an iterative one, one needs to keep as many accumulators as there are base cases.  In the iterative step, compute the next value, store it in the first accumulator, rotate the values of all remaining accumulators and decrement the loop variable.

Here's an implementation in your style:

(define (f_i n)
  ;iterative
  ;initial values of accumulators are f(2) = 2, f(1) = 1 and f(0) = 0; loop variable is n.
  (f_i-prime 2 1 0 n))

(define (f_i-prime f-x+2 f-x+1 f-x n-x)
  (cond ((= n-x 0) f-x)   ; if n-x = 0, then n = x, so return f(x) = f(n).
        ((f_i-prime (+ f-x+2 (* 2 f-x+1) (* 3 f-x))   ; iterative step -- compute next value of f(x + 2);
                    f-x+2                             ; ... rotate all other accumulators;
                    f-x+1
                    (- n-x 1)))))                     ; ... and decrement loop variable.

One may incorporate the helper function within the main function using letrec as follows (this version differs slightly from the previous one in that the loop variable counts up from 0 to n):

(define (f-iterative n)
  (letrec
      ((f-aux
        (lambda (x f-x+2 f-x+1 f-x)
          (cond
            ((= x n) f-x)
            ((f-aux (+ x 1) (+ f-x+2 (* 2 f-x+1) (* 3 f-x)) f-x+2 f-x+1))))))
    (f-aux 0 2 1 0)))

One may also use the do expression to write the iterative version as follows:

(define (f-iterative n)
  (do
      ((x 0 (+ x 1))
       (f-x+2 2 (+ f-x+2 (* 2 f-x+1) (* 3 f-x)))
       (f-x+1 1 f-x+2)
       (f-x 0 f-x+1))
    ((= x n) f-x)))

As to your recursive definition, you may wish to memoize the results in order to decrease your algorithm's complexity, which is currently in O(3 ^ n).  Memoization will improve that to linear complexity.


Here are some suggestions:

Use $.data(this, '_myplugin') & $.data(this, '_myplugin', myplugin). They're SO MUCH faster.
Since you call .publicFunc every time you instantiate your plugin, you should probably move the call into your constructor instead.
Public functions should be assigned to the prototype, so that we don't create a new function every time we create a new instance.
Likewise, define a private function outside of the constructor, in the parent closure. Again, we don't want to have to re-create the same function over and over again.

;(function ( window, document, $ ) {

  function somePrivateFunc ( instance ) {
    console.log( instance.options );
  }

  var Plugin = function( element ) {
    // What is this?
    this.options = $(element).data();
    this.publicFunc();
  }

  Plugin.prototype.publicFunc = function () {
   somePrivateFunc( this );
  };

  $.fn.myplugin = function () {
    return this.each(function () {
      if ( ! $.data(this, '_myplugin') ) {
        $.data( this, '_myplugin', new Plugin(this) );
      }
    });
  };

}(window, document, jQuery));

P.S. You haven't described how you're exposing the plugin's additional methods. For that you should read the jQuery plugin creation tutorial.

Find the section titled Provide Public Access to Secondary Functions as Applicable.


Check the equality for each subset of a string S against the target T and return a count

I'd just like to point out, that the code IMHO has far too many "length optimizations". Just take the first line:

if (!s.length) return +(!t.length);

I've been a JS developer for over 20 years and I couldn't say off the top of my head what + does to a boolean. It would be much more readable as:

if (s.length === 0) {
  return (t.length === 0) ? 1 : 0;
}

Also a comment why these are the correct return values would be very helpful.


Providing unchecked exception "wrapper" interfaces for an API with checked exceptions

Just accept the fact that the exception is unchecked and move on.

The industry is moving away from checked exceptions: C++ never had them, C# decided not to follow Java in this place, and the latest frameworks for Java are using unchecked exceptions.

Face it, checked exceptions are a nice idea that doesn't work in practice.

As a result, the thing you try in your code, will never pass any code review I'll be part of.


Least amount of HTML and CSS to create a bottom border for every section?

Something did feel wrong about your code

IDs are unique

A bit of redundancy is this: div#testimonials

IDs are unique in the page and should only be one element. You can just to #testimonials and still get that div.

Span? Which one?

Another is the span's usage. Suppose you wanted to style a phrase in the testimonial, you'd use span to style it. But your author style definition calls for all spans: #testimonials span. This would affect all spans, not just the author's.

I suggest you do place a class, like "author", to indicate that which span you are trying to style as the author:

#testimonials span.author {
  font-weight: bold;
  color: red;
}

Set the font in the parent

It would be better if you set the default font size on the parent, rather than on each element, unless that element should differ from the others. Also, as far as I know, the browser's default font size is around 16px. You could omit the size declaration.

Aesthetics: Removing the last border

This is just for aesthetics, but I suggest you remove the last entry's border. But since only IE9 supports :last-child, we change the approach. Instead, add a top border and let :first-child, supported in IE7+, remove the very first child's border.

#testimonials > div {
  border-top: solid 1px #666;
}

#testimonials > div:first-child {
  border-top: none;
}

Semantics: It's a list!

If you take a look at your content, it's a list. And if semantics is to be followed, you should use a list.

Worried about size?

You shouldn't. Though semantics might need you to use more code, it's not deployed in this state. Use an automation system like Grunt and minify everything. And make sure to gzip your transfers from the server.

Now this makes more sense.. at least for me:

HTML

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        Piggy McPiggy

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        Oinky Sausagebreath

Frankfurter meatloaf quis chuck, sunt jerky voluptate veniam ex aute commodo duis laboris labore. Sint dolor enim boudin pancetta culpa ham hock, laboris brisket veniam doner short loin velit qui duis.

        Pigster Pickled

CSS

/* removing the default styles of the list */
#testimonials{
    list-style:none;
    margin: 0;
    padding: 0;
}

/*unless your testimonials contain lists, this should be fine */
#testimonials li {
    border-top: solid 1px #666;
}

#testimonials li:first-child {
    border-top: none;
}

#testimonials span.author {
    font-weight: bold;
    color: red;
}


Fully Qualify Ranges

Your code assumes that the correct worksheet will be active when the code is ran.  You should get in the habit of Fully Qualifying all range references.  This will ensure that your code will work as intended no matter what worksheet is activated.

Technically, to be fully Fully Qualified a range needs to be referenced by workbook and worksheet.

  ThisWorkbook.Worksheets("Sheet1").Range ("A2:C7")

Or

  Workbooks("Some Book").Worksheets("Sheet1").Range ("A2:C7")

But in general it is acceptable to exclude the workbook if you are not going to be working with multiple workbooks.

  Worksheets("Sheet1").Range ("A2:C7")

With statement blocks should be used so that you don't have to repeatedly requalify your ranges.

  With ThisWorkbook.Worksheets("Sheet1")

  For Each a in .Range ("A2:C7")

Dynamic Ranges and Relative References

Dynamic Ranges should be used when working with records.  In this way, you will not have to rewrite you code every time a recorded is added or deleted.

This applies to both ranges

With ThisWorkbook.Worksheets("Sheet1")
    With .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
        For Each a In .Cells
            arr.Add a, a
        Next
    End With
End With

and formulas and FormulaArray

Range("F2").FormulaArray = "=IFERROR(INDEX(OFFSET($C1,1,0,COUNTA($A:$A)-1,1),MATCH(1,((OFFSET($A1,1,0,COUNTA($A:$A)-1,1)=$E2)*(OFFSET($B1,1,0,COUNTA($A:$A)-1,1)=F$1)),0)),"""")"

Having the macro hard the ranges for the FormulaArray is an acceptable middle ground.  I would do this to prevent the formulas from slowing up the workbook.

Error Handling

It is best to reduce the scope of On Error Resume Next as much as possible.  This will give you better information when something goes wrong.

On Error Resume Next
For Each a In var
    arr.Add a, a
Next
On Error GoTo 0

Or

For Each a In var
    On Error Resume Next
    arr.Add a, a
    On Error GoTo 0
Next

Variable Naming

Don't not use l as a variable name.  It is too hard to distinguish from 1.

l = 1 does nothing.  The For l = 1 initiates l to 1.

arr should only be used to name arrays variables.  Personally, I default to data, result or results.

Although there is nothing wrong with a, I prefer v, key, or item.

Alternate Methods

Here are some other ways of pivoting the data without using worksheet formulas.

Indexing Array Using ArrayList to Sort Headers

This uses ArrayList to store and sort the headers.  The position of the headers in the ArrayList is used as indices for a 2 dimensional array.

Sub PivotDataIndexedArray()
    Dim key As Variant, data() As Variant
    Dim rowHeaders As Object, columnHeaders As Object
    Set rowHeaders = CreateObject("System.Collections.ArrayList")
    Set columnHeaders = CreateObject("System.Collections.ArrayList")

    With ThisWorkbook.Worksheets("Sheet1")
        With .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
            For Each key In .Value
                If Not rowHeaders.Contains(key) Then rowHeaders.Add key
            Next
            For Each key In .Offset(0, 1).Value
                If Not columnHeaders.Contains(key) Then columnHeaders.Add key
            Next

            data = .Cells.Resize(, 3).Value
        End With

        Dim results() As Variant
        Dim n As Long
        ReDim results(1 To rowHeaders.Count + 2, 1 To columnHeaders.Count + 2)

        'Add names
        rowHeaders.Sort
        For n = 0 To rowHeaders.Count - 1
            results(n + 2, 1) = rowHeaders(n)
        Next

        'Add categories
        columnHeaders.Sort
        For n = 0 To columnHeaders.Count - 1
            results(1, n + 2) = columnHeaders(n)
        Next

        Dim r As Long, c As Long

        'Add dates
        For n = 1 To UBound(data)
            r = rowHeaders.IndexOf(data(n, 1), 0)
            c = columnHeaders.IndexOf(data(n, 2), 0)
            results(r + 2, c + 2) = data(n, 3)
        Next

        .Range("F1").Resize(UBound(results), UBound(results, 2)).Value = results

    End With

End Sub

ADODB CrossTab Query

An ADODB.Connection query can be used to pivot the data.  The source data should be the only data on the worksheet, otherwise, you would have to specify the datas' range on the worksheet in the query (e.g [Sheet1$A1:C7]).

Sub PivotDataADODBQuery()
    Const SQL As String = "TRANSFORM First([Date])" & vbNewLine & _
          "SELECT [Name]" & vbNewLine & _
          "FROM [Sheet1$]" & vbNewLine & _
          "GROUP BY [Name]" & vbNewLine & _
          "PIVOT [Certificate];"

    Dim conn As Object
    Dim rs As Object
    Set conn = CreateObject("ADODB.Connection")

    conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & ThisWorkbook.FullName & "';Extended Properties='Excel 12.0;HDR=YES;IMEX=1';"
    conn.Open

    Set rs = conn.Execute(SQL)

    With ThisWorkbook.Worksheets("Sheet2")
        .Cells.ClearContents

        Dim c As Long

        For c = 0 To rs.Fields.Count - 1
            .Cells(1, c + 1).Value = rs.Fields(c).Name
        Next

        .Range("A2").CopyFromRecordset rs
    End With

    rs.Close
    conn.Close

End Sub


Get host ip address behind load balancer or without lb

Here is a pattern I've used successfully.  However, you need to be aware that the X-FORWARDED-FOR header may contain a comma separated list of ip addresses.  This solution also helps with protocol sniffing, because most secure sites will need to force the web browser to SSL, and if you are using SSL OFFLOADING, you'll need to use the x-forwarded-proto header to determine if a redirect is required.

        string ipAddress = string.Empty;
        string protocol = string.Empty;
        string port = string.Empty;

        if (Request.RequestContext.HttpContext.Request.Headers.GetValues("X-Forwarded-For") != null)
        {
            protocol = (Request.RequestContext.HttpContext.Request.Headers.GetValues("X-Forwarded-Proto")).FirstOrDefault();
            ipAddress = (Request.RequestContext.HttpContext.Request.Headers.GetValues("X-Forwarded-For")).FirstOrDefault();
            port = Request.RequestContext.HttpContext.Request.Headers.GetValues("X-Forwarded-Port").FirstOrDefault();
        }

        if (string.IsNullOrWhiteSpace(protocol))
        {
            protocol = (this.Request.IsSecureConnection ? "HTTPS" : "HTTP");
            ipAddress = this.Request.UserHostAddress;
        }

Example format of header value:

X-Forwarded-For: client, proxy1, proxy2

See https://en.wikipedia.org/wiki/X-Forwarded-For


Pushing local repository to remote repository using python Github

Octal permission fields
77

is likely incorrect. What you've written is 77 in decimal, but this would work out to 115 in octal. If you wanted 077 in octal, you would actually need to write 0o077.
Pathlib
Consider replacing os.path with use of pathlib.
Argument parsing
The argv parsing that you've done is fragile - it will fail with an invalid-index exception if the user provides insufficient parameters. Consider using argparse instead.
Also: do not ask for a password as part of a command line, since it will be stored in the user's shell history. Accept it from an environmental variable, a secure wallet, or from stdin via getpass (not input).
String interpolation
"https://github.com/"+username+"/"+output_repo_name+".git"

is more easily written as
f'https://github.com/{username}/{output_repo_name}.git'


Where should I put menu items in MVC with PHP - Model or Controller?

This a nice example: it shows how the MVC is just a pattern which should be ajusted to your needs.

The menu items you're showing seem very unlikely to change over time. This means you can simply put them in your "templates/menu" view.
If they're shared among multiple views, then the controller is OK.
If the menu items can change dynamically, then your model can provide a meaningful abstraction over your data, and then it would go into a model.


apt alternative for proxy environment with bash shell

Storing passwords in text files is never a good idea, especially if you give that file world-readable permissions.

Try this:

#!/bin/bash

mkdir -p ~/bin/

# add ~/bin to PATH if not already there
echo '[[ :"$PATH": == *:"$HOME/bin":* ]] || PATH="$HOME/bin:$PATH"' >> .bashrc

# create the apt-proxy script
cat <<'END_SCRIPT' > ~/bin/apt-proxy
#!/bin/bash

stty -echo
printf "Password for %s: " "$LOGNAME"
read password
stty echo
echo

export http_proxy="http://${LOGNAME}:${password}@10.20.10.50:3128"
sudo -S apt-get "$@" <<< "$password"
END_SCRIPT

chmod 755 ~/bin/apt-proxy

cat <<INSTRUCTIONS
The apt-proxy script has been installed.
You may need to log out and log back in before you can use it.

usage: apt-proxy package ...
INSTRUCTIONS

mkdir -p dir will silently do nothing if the directory already exists
you only need to add the user's bin dir to the PATH if it is not already there
DO NOT store the user's password. Have the user enter it each time.
you should not even need to use sudo to edit files in your home directory.
777 permissions is overly generous: the world does not have to be able to edit the file
use sudo -S and pass the user's password via stdin


Knuth–Morris–Pratt string match algorithm

1. Review

There's no docstring.
There's no need for parentheses around conditions (Python is not C), so instead of:

while (i+1 < len(pattern)):

you can write:

while i+1 < len(pattern):

The loop while i+1 < len(pattern) calls the len function on each iteration, even though pattern has not changed. You could avoid this wasted call by caching len(pattern) in a local variable.
The or operator has lower precedence than comparison operators, so instead of:

if (j == -1) or (pattern[j] == pattern[i]):

you can omit the parentheses:

if j == -1 or pattern[j] == pattern[i]:

When there's a choice about whether to test for equality or inequality, then I think it's usually clearer to test for equality, so I would write if pattern[i] == pattern[j] instead of if pattern[i] != pattern[j].
There's a small inefficiency in your code. If the test j == -1 or pattern[j] == pattern[i] passes then you set j = next[j] and go round the while loop again. But the condition on the while loop is a condition on i, which has not changed, so you waste the test. It is better to go straight to the test on j, like this:

m = len(pattern)
while i + 1 < m
    while j > -1 and pattern[i] != pattern[j]:
        j = next[j]
    i += 1
    j += 1
    if pattern[i] == pattern[j]:
        next[i] = next[j]
    else:
        next[i] = j

After making this change, i always increases by 1 on each iteration of the main loop, so we could use a for loop instead to make this clear.

2. Revised code

def kmp_table(pattern):
    """Compute the "next" table corresponding to pattern, for use in the
    Knuth-Morris-Pratt string search algorithm.

    """
    m = len(pattern)
    next = [-1] * m
    j = -1
    for i in range(1, m):
        while j > -1 and pattern[i-1] != pattern[j]:
            j = next[j]
        j += 1
        if pattern[i] != pattern[j]:
            next[i] = j
        else:
            next[i] = next[j]
    return next


Leaving out the max value in an Enumeration

This is not efficient:

foreach (int value in values)
{
    if (value != values.Max())

Because in every iteration, you recalculate values.Max(), when it would be enough to do it once, before starting the loop.

Also, you don't need to create values as a List<int>. As a result, the method can be simplified:

static void Opdracht3()
{
    int maxValue = Enum.GetValues(typeof(Opleidingen)).Cast<int>().Max();

    foreach (int value in Enum.GetValues(typeof(Opleidingen)))
    {
        if (value != maxValue)
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}

And as @blueraja pointed out, to reduce duplication even further, it's good to cache Enum.GetValues(typeof(Opleidingen)).Cast<int>() in a variable:

static void Opdracht3()
{
    int[] values = Enum.GetValues(typeof(Opleidingen)).Cast<int>();
    int maxValue = values.Max();

    foreach (int value in values)
    {
        if (value != maxValue)
        {
            Console.WriteLine("Naam: {0}, Waarde: {1}", Enum.GetName(typeof(Opleidingen), value), value);
        }
    }
}


Review of a generic request handler class (RestSharp)

Depend on the IRestClient interface rather than the RestClient implementation and make the field readonly as it is only set via the constructor:

private readonly IRestClient client;

Invert your dependancy on RestClient, if you are not using an IOC container, at least implement poor mans injection so that the class is testable (e.g. you can supply a mock IRestClient to test RestHandler.

public RequestHandler() // If you are using an IOC container, remove the default constructor.
    : this(new RestClient(baseUrl))
{
}

public RequestHandler(IRestClient restClient)
{
    this.client = restClient;
}

As Ron mentioned above, you don't appear to be using secret key and account id so either remove them if they are not needed or use them.

Making the base url a constant inside the class makes it difficult to re-use, I would move that into the application configuration.

If you do need account_id, remove the underscore and camel case it accountId to adhere to  the standard naming conventions.

Adding a property for the DataFormat will make the class more re-usable if you want to call a web service which doesn't support Json:

public DataFormat DataFormat { get; set; }

// Default to Json in the constructor
this.client = restClient
this.DataForma = DataFormat.Json;

ExecuteAsync returns a RestRequestAsyncHandle which allows the request to be aborted, it might be worth looking at whether you need the ability to abort requests or not. You could update your Execute to return the wait handle.

The error checking here doesn't account for any of the other reasons for failure such as a timeout or abort.

if (response.ResponseStatus == ResponseStatus.Error)

Update it to something like this:

switch (response.ResponseStatus)
{
    ResponseStatus.Completed:
        Success(response.Data);
        break;

    ResponseStatus.Error:
    ResponseStatus.TimedOut:
        Failure(response.ErrorMessage);
        break;
}


Multiple string replacement (with similarity) using a dictionary

I can be wrong, but it seems that the problem is that if you have a large number of keywords, you are defining a lot of regular expressions in vain. How about creating a single regex and replacing values only for found keywords?

var words = string.Join("|", keywords.Keys);
text = Regex.Replace(text, $@"\b({words})\b", delegate (Match m)
{
    return keywords[m.Value];
});


Force attribute value on potentially non-existent or locked PyNode

From the documentation link you provided:

  ‘force’ kwarg, which causes the attribute to be added if it does not exist.

So the force kwargs does not seem to allow you to set a new dataType.

Hence it seems that the only way to set a new dataType is to remove and recreate the attribute. From this case, it seems hard to further simplify your code.


This is a bit surprising:

stringBuilder.setLength(0);

Seeing the posted code starting with this is fishy,
as it suggests that there is more code before it,
and that the method is not decomposed enough,
and should be multiple methods instead.

This is a bit surprising:

    final char read = (char) reader.read();
    if (read < 1) {

The read() method returns -1 in case of EOF.
I suggest to change this check to read < 0 or read == EOF to avoid making reviewers ponder.

        MiscUtils.closeAndIgnore(socket, reader);

A common name for this kind of thing is closeQuietly,
usually in a utility class called IOUtils (in Apache commons, for example).
I suggest to follow that good example.
MiscUtils is a bad idea.

    if (read == '\n')
        break; //status header fetched

It's recommended to use braces always, even with single-statement expressions like this.

if (!(status.contains("200") || status.contains("206"))) {

I'd go for the more strict and compact regular expression check:

if (!status.matches("HTTP/.* 20[06] .*")) {

It would be good to split the posted code to two methods:

A method that consumes the status line (the first line)
A method that consumes the remaining lines


It seems fairly sane; I only picked up a couple of things:

Don't ignore errno

You do check for failure, which is good; but you ignore errno. You should use it, and/or perror, to get more detailed failure information.

Assign-in-condition

There's not a compelling reason to do this:

char *pNewline;
if ((pNewline = strchr(user_input, '\n')) == NULL)

Just assign pNewLine where it's declared, not where it's used in the condition.


Regex version of strip() - Ch. 7 Automate the Boring Stuff

If you call regex_strip(s, ""), you will get:

  re.error: unterminated character set at position 0

because neither ^[] nor []$ is a valid regular expression.  You could avoid this by using if not chars: instead of if chars == None:.

There is no need to re.compile() your regular expressions; you aren't saving the compiled patterns anywhere for re-use.

You can simplify your logic by using the reg-ex to capture the middle, non-stripped portion of the string, instead of doing two replacements for the start and end trim operations:

import re

def regex_strip(s, chars = None):

    if chars:
        trim = '[' + re.escape(chars) + ']*'
    else:
        trim = r'\s*'

    return re.fullmatch(f"{trim}(.*?){trim}", s).group(1)

I'm not sure the point of asking you to write your own strip() function is to delegate the task to the reg-ex engine.  It seems like going out and buying a sledge hammer when the problem is to build a nut cracker.


You can shorten the getGenderSelect function like this:

var genderSelect = {

  getGenderSelect: function () {
    $(this).find('#girl-character').toggle(this.val() == 'Girl');
    $(this).find('#boy-character').toggle(this.val() == 'Boy');
  },

  init: function(){
    $('.control-label input[name="gender"]').change(
      $('#caracters').show();
      genderSelect.getGenderSelect();
  )};

};

genderSelect.init();

The toggle function takes a boolean which determines whether to show or hide the  selected elements.


small ticker class to execute a function at a regular inverval

I have some doubts about you member variable running_flag_ and its use in ticker::start(). If its purpose is to avoid calling ticker::start() from the same thread then it can be just bool, not std::atomic<bool>. If its purpose is to avoid calling ticker::start() from the different threads for the same object then you seem to have a data race when two threads might both see running_flag_ equal to false and go ahead with creating two threads  later:

    if ( running_flag_ )
    {
        return;
    }
    running_flag_ = true;
    thread_ = std::thread( [this]() { thread_function(); } );

As far as I know std::atomic::compare_exchange_weak must be used in order to avoid such data race when using atomic variable. However as far as I understand you do not expect high contention in ticker::start() and ticker::stop(). So it seems that a more simple approach could be to have running_flag_ as bool

class ticker {
    // ...
    const function f_;
    const std::int64_t interval_us_;
    bool running_flag_;
    std::thread thread_;
    std::mutex stop_mutex_;
    std::condition_variable stop_cv_;

and rewrite functions in this way:

void start() {
    std::lock_guard<std::mutex> lock( stop_mutex_ );
    if (running_flag_ )
        return;
    thread_ = std::thread( [this]() { thread_function(); } );
    running_flag_ = true;
}

void stop() {
    std::unique_lock<std::mutex> lk(std::mutex);
    if (!running_flag_)
        return;
    running_flag_ = false;
    lk.unlock();
    stop_cv_.notify_one(); // why all? notify_one seems to be enough
    thread_.join();
}

Next, why you write explicitly thread_(),stop_mutex_(), stop_cv_()? It is unnecessary.

Then thread_function() seems to be little bit complicated. I have choosen using a predicate in order to stop:

void thread_function() {
    auto last_time = std::chrono::steady_clock::now();
    while ( true ) {
        const auto wake_up_time = last_time + std::chrono::microseconds{ interval_us_ };
        const auto sleep_time = wake_up_time - last_time;
        std::unique_lock<std::mutex> lk(stop_mutex_);
        if (!running_flag_)
            break;
        stop_cv_.wait_for(lk, sleep_time, [this](){return !running_flag_;});
        if (!running_flag_)
            break;
        lk.unlock();
        last_time = wake_up_time;
        f_();
    }
}

And finally. I think you should use std::chrono::steady_clock instead of std::chrono::high_resolution_clock since they cannot be adjusted and according to http://en.cppreference.com/w/cpp/chrono/steady_clock:

  This clock is not related to wall clock time (for example, it can be
  time since last reboot), and is most suitable for measuring
  intervals.


One object to handle all my database manipulation needs

No user input makes it into the statement itself.

You should write a PHPDoc style comment which explicitely states that specific parameters should not contain user input.

This would of course also be the case if you used a whitelist to check against existing table and column names, as no user should have the ability to change arbitrary tables or columns.

  I have successfully safe guarded against it.

Pretty much. It's not clear to me why you accept , though. Without =, you can't add a second value anyways, so , should not be necessary.

Method Signature

  $dm->update('users', 'sessionid', $session_id, 'username', $user_name);

This isn't very easily understandable. Sure, it updates some table, but a reader has no idea what exactly is happening without looking at the update code itself.

If you go with something like a query builder, you might get code like this:

$dm->update('users')
    ->set('sessionid', $session_id)
    ->set([something else])
    ->where('username', $user_name)
    ->exec();

This would be a lot easier to read as it is clear what each argument actually does.

Functionality

Your method should be able to deal with setting multiple fields at once. For example by accepting an array of records and set_values.

Structure

Your update method shouldn't create a new pdo object on each call. Instead, reuse the same connection for all queries.

Your method should also not echo. It makes it very difficult to recover from errors, or to control what a user sees. Throw exceptions instead (pdo can actually do this for you with ERRMODE_EXCEPTION so there is no need to check here).

Your method should also not change ini settings. These should be set in some configuration class.

With this, your method may look like this:

function update($pdo, $table, $records, $set_value, $compare, $compare_value){

    $table=preg_replace('/[^0-9a-zA-Z_]/', '', $table);
    $records=preg_replace('/[^0-9a-zA-Z_,]/', '', $records);
    $compare=preg_replace('/[^0-9a-zA-Z_,]/', '', $compare);

    $stm = $pdo->prepare("UPDATE $table SET $records = ? WHERE $compare = ?");
    $stm->execute(array($set_value, $compare_value));
}

The PDO exceptions would be handled by your calling code. Depending on what is updated, you may want to log the error, inform the user, ignore the error, perform a different action, and so on.

Of course now the question is if this method is actually needed. Is this:

try {
    $dm->update($pdo, 'users', 'sessionid', $session_id, 'username', $user_name);
} catch ($pdoException) {
    // handle error
}

Really better than this:

try {
    $stm = $pdo->prepare("UPDATE users SET sessionid = ? WHERE username = ?");
    $stm->execute(array($session_id, $user_name));
} catch ($pdoException) {
    // handle error
}

? I don't really think so. The second is clearer, provides less room for error, isn't really longer, and is more flexible.

Misc

only display errors in development. It has a negative effect on security if they are enabled in production. This makes it especially important to only change the setting in some configuration file and not all over the place.
Your password is above average, but you should probably change it now :)
sn, un, pw, dn, opt are all bad names. If you write them out your code will be more readable.