Multithreading algorithm for high performance parallel computing and Producer-Consumer queue using POSIX threads

Style

I see something that looks like a thread safe queue abstraction, which is mysteriously implemented as a collection of globals and one argument. These are a fairly well-known subspecies of container, so write one (or find an existing one that suits your purposes)

template <typename T>
class MTQueue
{
public:
  // simple operations will lock & unlock on every call
  void push(T const &);
  T pop();

  // ...
};

Just pass a pointer to this to your thread function, and your threads can pop at will.
Note this could trivially use a std::queue or any other container internally (and you may prefer FIFO rather than LIFO) - all you're really doing is bundling some container with a mutex and enforcing the lock semantics when you change (or inspect) it.

I also see something that looks like a barrier (your use of semaphores), but I suspect your consumers can start consuming as soon as there's something in the queue, so you just need a way for the producer to wait until they're all done. We could add a method to wait until the work queue is empty, but that doesn't tell us the work is complete.  Should there be a results queue? If so, use another instance of the same type: the producer can be popping results in parallel, it doesn't need to wait until the last one is calculated.

Performance

There are a couple of approaches to making it fast:

Batching

Consider the relative cost of the synchronization involved in popping an item from the queue, and actually doing the work: it might be faster overall to add a more elaborate interface so you can push/pop multiple items with only the same synchronization overhead, eg.

  // more elaborate interface to amortise synchronization cost?
  void push(std::vector<T> const &);
  void pop(std::vector<T> &out);

or you could just switch to pushing/popping a batch of work object instead of single jobs: same effect, may leave you with a simpler and more reuseable queue.

Alternative Synchronization Strategies

Mutual exclusion is only one way of sharing data across multiple cores, and to be honest it's probably a good fit here (especially if you calibrate the batch size correctly).
However, if you really want to get stuck in, look up lock free or non-blocking queues as well - for some workloads and core counts, they might suit you better.


Code dealing with files and separate lines in them

the posted code does not cleanly compile!

Compile with warnings enabled, then fix those warnings.

for gcc, at a minimum use:

-Wall -Wextra -Wconversion -pedantic -std=gnu11

Note: other compilers use different options to produce the same results.

in function: setup_myfile()  there are statements like:

return -1;

However, that only gets execution back to the call in main()

setup_myfile(argv[1], &my_file);

Which is ignoring the returned value.  So, when setup_myfile() fails, main() will keep right on executing, as if everything is OK.

Suggest, rather than: return -1;  to use:

exit( EXIT_FAILURE );

which will properly exit the program

regarding:

file->size = st.st_size;

This is performing an implicit conversion from off_t to unsigned long int.  Probably better to declare file->size as an off_t.


Project Euler #8: Maximum product of 13 consecutive digits

Data types

The number of consecutive digits you can support is limited not by the length of the input, but by the maximum value that can be stored in a uint64_t.  While 913 is comfortably smaller than 264 - 1, you should be cautious about overgeneralizing your claims.

It's weird that you initialize uint64_t integers with floating-point literals 1.0 and 0.0.

Loop and conditional style

Never omit the optional braces in conditional and loop blocks like that.  By doing so, you are being a contributing factor to a future coding accident.  If you want to omit the braces, then put the statement on the same line so that it cannot be misinterpreted.  If you feel that braces take up too much vertical space, then please switch to the K&R brace style so that you don't feel compelled to omit them.

Your while-loops fit the classic for-loop pattern, and should be written as for-loops to make them easy for other programmers to recognize.

uint64_t max = 0;
int data[DIGITNUM];
for (int i = DIGITNUM - 1; number[i] != '\0'; ++i)
{
    for (int k = 0; k < DIGITNUM; ++k)
    {
        data[k] = char2int(number[i - k]);
    }

    uint64_t product = getProduct(data);
    if (product > max) max = product;
}

Algorithm

You transfer almost every digit to the temporary data array 13 times.  It would be smarter to treat the data array as a circular-buffer.

uint64_t max = 0;
int consec[DIGITNUM];
for (int n = 0, c = 0; number[n] != '\0'; ++n, ++c) {
    if (c == DIGITNUM) {
        c = 0;        // Circular buffer wraparound
    }
    consec[c] = char2int(number[n]);
    if (n < DIGITNUM - 1) {
        continue;     // Circular buffer not fully initialized yet
    }

    uint64_t product = getProduct(consec);
    if (product > max) {
        max = product;
    }
}

Here, I've used n and c as array indices, which are mnemonics for the respective arrays number and consec that they index into.


A better way to read text files into html?

What do you mean with the variable name wanted? I don't understand what it has anything to do with what you are doing, so it's a badly chosen name.

if( wanted[i] === "\n" )
    continue;

This won't do anything. Since you split by "\n", there will be no line breaks leftover. I assume you want wanted[i] === "". Also consider .trim()ing all you lines, otherwise a stray white space will break this.

if (i === (wanted.length-1) )
    {
        // [...]
        break;
    }// Break early because the rest cannot be processed correctly

I'm not sure why you are "breaking early" here. Your condition triggers for the last line, so it's not really "early".

newString += wanted[i];

Repeated string concatenation is a slow process and uses a lot of memory. Instead just leave your strings in the array and at the end just return wanted.join();

EDIT: One more thing: Both the original div and the other ul you later add inside have the same id. That's invalid.

EDIT: Regarding the ID: In your script you have $("#todoList").append( compiledData ); so there's obviouly an element with the id todoList, but your template has the code <ul  id="todoList" class="workList"> in it, so you are creating a second element with the same ID.


Colored image will become black and white

Input validation

If the received image is not RGB, throwing an IllegalArgumentException without a custom message is not very friendly. Users would have to look at the code to understand what went wrong exactly.

The long chain image.getColorModel().getColorSpace().getType() is extracted to an imageType local variable that's only used for validation.
I would be good to move the validation to a dedicated helper method, let's say validateImageType.

Java conventions

Member variables should be declared at the top, followed by constructors, followed by methods. Very roughly speaking. So move the declaration of threshold higher.

Naming

As the interface name already implies the conversion to black and white,
the method name toBlackAndWhite is redundant. I'd rename it to simply convert.

Misc

0x000000FF is the same as 0xFF, so you can shorten it.


There are a few things that we can do to clean this up.

This is something I would extract to its own method.  Handle getting the user input in the main() method, and then pass that on to the drawDiamond() method.
Your for loops are divided into iterating over lines, spaces, and
marks.  We can simplify that down to just rows and columns where we can iterate over each individual unit at a time.  This will also eliminate one of your System.out.println()s in the final method.
We can simplify down the math of where to print a piece of the diamond.

if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))

Final Method:

void drawDiamond(int sqr)
{
    int half = sqr/2;
    for (int row=0; row<sqr; row++)
    {
        for (int column=0; column<sqr; column++)
        {
            if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))
            {
                System.out.print("*");
            }
            else System.out.print(" ");
        }
        System.out.println();
    }
}


Think your worrying yourself about small details here, any advantages of one over the other would be minor at best.

I think out of all 3, the last solution would be my preferred one. It's clean from a code separation POV and does exactly what it says on the tin, also easier to change behaviour without affecting the other should that ever need to happen.

FWIW for performance reasons it's recommended you bind UI event handlers in the constructor e.g.

constructor() {
    this.toPrevYear = this.toPrevYear.bind(this);
}
...
render() {
    return <button onClick={this.toPrevYear}>Prev</button>;
}


Have I gone too far in factoring out repeated code in this example?

I think what you did was a good thing. I also think you could combine the first 2 functions as well.

Something like this:

private function _add_item($path, $type, $where = self::ADD_LAST) {
    $script = "<script src='$path'></script>\n";
    $css = "<link rel='stylesheet' href='$path'>\n";

    if ($type == 'script') {
        $html = $script;
    }
    elseif ($type == 'css') {
        $html = $css;
    }

    $this->_add_external($type, $html, $where);
}

Or this:

private function _add_item($path, $type, $where = self::ADD_LAST) {
    $script = "<script src='$path'></script>\n";
    $css = "<link rel='stylesheet' href='$path'>\n";

    switch($type) {
        case 'script':
            $html = $script;
            break;
        case 'type':
            $html = $css;
            break;
    }

    $this->_add_external($type, $html, $where);
}

Or this (My favorite):

private function _add_item($path, $type, $where = self::ADD_LAST) {
    $array['script'] = "<script src='$path'></script>\n";
    $array['css'] = "<link rel='stylesheet' href='$path'>\n";

    $html = $array[$type];

    $this->_add_external($type, $html, $where);
}

EDIT:

And I think this would work too, an all in one solution:

private function _add_item_external($path, $type, $where = self::ADD_LAST) {
    $array['script'] = "<script src='$path'></script>\n";
    $array['css'] = "<link rel='stylesheet' href='$path'>\n";

    switch($where) {
        case self::ADD_LAST:
            array_push($this->_data[$type], $array[$type]);
            break;
        case self::ADD_FIRST:
            array_unshift($this->_data[$type], $array[$type]);
            break;
    }
}


Permutation-stream based n-queens solution

Variable Names

There is little reason not to give the variables clear meaningful names. Using abbreviations leads to using bd in check-diagonals and brd in the search loop. Calling the board board makes the code clearer. Similarly, the time a reader spends figuring out that r1 and r2 refer to rows is wasted time for every reader. It saved the programmer four keypresses once.

The size of the board is a natural number. The traditional notation for the Natural Numbers is n not N. It's why it's the 'n-queens' problem not the 'N-queens' problem.

Concurrency and Parallelization

Concurrency covers all problems where the execution can be logically simultaneous whether or not the implementation runs in parallel or not. Most concurrent processes do not run entirely in parallel. Parallelization is a way of executing a concurrent process. All concurrent processes are not run in parallel. All parallel processes are logically concurrent.

The n-queens problem

The solution space of n-queens problem is non-polynomial. The size is n!. Parallelization with p nodes still leaves the solution space non-polynomial, approximately n!/p. A solution that would take a 100 million years still takes an impractical time when spread across 1,000,000 nodes.

What makes the n-queens problem interesting is that it is non-polynomial and that it has symmetries that allow for the search space to be pruned.  For example, many configrations are isomorphically related to  other configurations by board rotation and mirroring.

Optimizing solutions to NP problems

There is no general algorithm for quickly solving non-polynomial problems. That's what makes them interesting/hard depending on one's perspective. Speeding up the code to a specific problem requires taking advantage of the problem specifics.

In the case of n-queens, pruning the search space of isomorphic non-solutions each time a non-solution is found. Optimization comes from writing code that coming across the the n=3 non-solution:

  a b c
1 Q Q
2
3

prunes the search space of isomorphic configurations such as:

  a b c
1   Q Q
2
3

and

  a b c
1     Q
2     Q
3

Other Strategies

An empty board has zero probability of being a solution. This is lower than a board with a queen randomly placed in each column. Though the probability of random placement producing a solution is slight, it is better than an empty board.

Gradient Descent Starting with a randomly populated board, an estimate of the distance from a solution is made. [1] Next each alternative position for each queen is examined and an estimate of the distance from a solution is made for each resulting configuration. The one move that results in minimizing the distance from the solution is made and the process repeats.

When no improvement is possible the solution may be abandoned [2] and a new random board generated. Generating and examining random boards is parallizable and typically done because the number of boards examined is often large.

[1]: Choosing how to measure the distance is art informed by science, not pure science except in so far as recognizing that the problem of measuring is still in NP.

[2]: More complex approaches may not always chose the configuration closest to a solution and/or backtrack when no improvement is possible. Again, optimization is based on understanding the particulars of the problem.


Cleaning Netflix-style recommendation engine datasets

The usual
Use a PEP8 linter; move global code into functions; use type hints; use a __main__ guard.
Column use
basics.drop(basics.columns[[3,4,6,7]], axis=1, inplace=True)
basics.columns = ['tconst','type','title','year','genre']

really shouldn't be necessary. Use the usecols kwarg of read_table instead; the col names are a loose guess from the IMDB documentation:
basics = pd.read_table(
    'basics.tsv',
    usecols=(
        'tconst', 'titleType', 'primaryTitle', 'startYear', 'genres',
    ),
)


Process files in a directory and upload them to URL

Your code is already pretty good, you have to tighten a scope of lexical (my) variables. Also as non-perl related, always get rid of unnecessary loops.

use strict;
use warnings;
use Data::Dumper qw(Dumper);
use File::Spec qw(catfile rel2abs);
use Digest::SHA qw(sha256_hex);
use Archive::Tar;
use JSON;
use HTTP::Request::Common;
use LWP::UserAgent;

my ($dir, $url) = @ARGV;
my $archive = "archive.tar.gz";

my @AoH;
my @checksumfiles;
my @array;
# same as glob("$dir/*")
while (my $file = <$dir/*>) {
    -f $file or next;

    my $fullpath = File::Spec->rel2abs($file);
    my %h = (
        path    =>  $fullpath,
        size    =>  -s $file,
        id      =>  sha256_hex($fullpath),
    );
    push @AoH, \%h;

    my ($ext) = $h{path} =~ /(\.[^.]+)$/;
    # defined or
    my $idext = $h{id} . $ext // ''; # fix codereview coloring */
    push @checksumfiles, $idext;
    push @array, $h{path};
}

# my @array;
# for my $i (0..$#AoH) {
    # no warnings 'uninitialized';
    # my ($ext) = $AoH[$i]{path} =~ (/(\.[^.]+)$/);
    # my $idext = $AoH[$i]{id} . $ext;
    # push(@checksumfiles, $idext);
    # push(@array, $AoH[$i]{path});
# }


Map in which values are concretions of a generic class

Your clients do not need about how you are providing the Adapter<>. They just have to provider the Target and Source class instances.

Here is one possible implementation,

public class DoubleKeyMap {

    private Map<Wrapper, Adapter<Target,Source>> adapterMap;

    public DoubleKeyMap(Map<Wrapper, Adapter<Target,Source>> adapterMap) {
        this.adapterMap = adapterMap;
    }

    public Adapter<Target,Source> get(Class<Target> targetClass, Class<Source> sourceClass) {

        Wrapper wrapper = new Wrapper(targetClass, sourceClass);

        return adapterMap.get(wrapper);
    }

    private class Wrapper {

        private Class<Target> target;

        private Class<Source> source;

        private Wrapper(Class<Target> target, Class<Source> source) {
            this.target = target;
            this.source = source;
        }
    }
}

Hide the wrapper from outside world by making it private.

The client just provide Target and Source Class instances

class Client {
    public static void main(String[] args) throws ClassNotFoundException {
        DoubleKeyMap doubleKeyMap = new DoubleKeyMap(Collections.emptyMap());

        Adapter<Target, Source> targetSourceAdapter = doubleKeyMap.get(Target.class, Source.class);
    }
}


SQL

If you want a count, ask for a count.  Don't ask the server to send all the data for all the rows, just to have the client count the rows.  (A few hundred rows is a trivial amount of data for a database to handle, but still, you should follow good practices.)

SELECT SUM(inactive_count) AS inactive_count
    FROM (
        SELECT COUNT(article_active) AS inactive_count
            FROM wcx_articles WHERE article_active = '0'
        UNION ALL
        SELECT COUNT(video_active)
            FROM wcx_videos WHERE video_active = '0'
        UNION ALL
        SELECT COUNT(app_active)
            FROM wcx_apps WHERE app_active = '0'
        UNION ALL
        SELECT COUNT(link_active)
            FROM wcx_links WHERE link_active = '0'
    ) AS wcs_objects;

Schema

If in fact all four of your tables are union-compatible with each other, then you should strongly consider merging them into one table with a wcx_type attribute that declares what type of object that row represents.

Are your …_active columns really strings?  Those columns should be of the BOOLEAN (i.e., TINYINT(1)) type.  The query should be adjusted accordingly: use …_active = 0 instead of …_active = '0'.

PHP

You reused the $query parameter to store the result of the query.  Don't be stingy like that — it's confusing.  Use a new variable to store the result.

You have a leak: mysqli_free_result( $query ); never gets called, because that statement is unreachable.

You are mixing the object-oriented and procedural styles of mysqli.  You should either use the object-oriented style consistently…

public function num_rows($query) {
    if (!($result = $this->link->query($query))) {
        $this->log_db_errors($this->link->error, $result, 'Fatal');
        return $this->link->error;
    }
    $num_rows = $result->num_rows;
    $result->free();
    return $num_rows;
}

or use the procedural style consistently…

public function num_rows($query) {
    if (!($result = mysqli_query($this->link, $query))) {
        $this->log_db_errors(mysqli_error($this->link), $result, 'Fatal');
        return mysqli_error($this->link);
    }
    $num_rows = mysqli_num_rows($result);
    mysqli_free_result($result);
    return $num_rows;
}


Simple recursive function to find missing number in a permutation

As others pointed out in comments (and as usual), an iterative solution can be better. But you said you want to practice recursion, so I guess you want to stick with that.

This code:

int(ceil(len(lis))/2)

Is exactly the same as:

len(lis) // 2

Because, there's no point taking the ceiling of a list length, as it's always an integer. And you can use // to divide and throw away the remainder, which is the same thing as casting a floating point number to integer, but shorter and simpler.

You should not duplicate code. You should put the result of the above calculation only once, save it in a variable and reuse it when creating A and B.

Similarly, instead of duplicating the logic when creating ISA and ISB, it would be better to put the common logic into a function.

Some more meaningful variable and function names would be good too.


Deleting most recent files by parsing filename

You can reduce number of loops, sorts, and matches, so this should perform faster,

my $num_to_keep = 2;

my $dir = "/home/mp3files";
opendir my $DH, $dir or die "$! $dir";

# only mp3s
my $fileRE = qr/(.+) _ (\d{4}-\d{2}-\d{2}) \.mp3$/x;

my %count;
# files to delete
my @files = map {
  my $basename = $_->[1];
  (++$count{$basename} > $num_to_keep) ? $_->[0] : ();
}
sort {
  $b->[2] cmp $a->[2] # sort descending by date
}
map {
  my @match = /$fileRE/;
  (@match && -f "$dir/$_") ? ["$dir/$_", @match] : ();
}
readdir($DH);

close $DH;
unlink(@files);


It looks like you can simplify it to the single regex:

    matcher = re.compile(r'^(.+)([0-9]{6})([PC])([0-9]+)$')
    groups = matcher.search(option)

Then symbol, expiry, type and price are in groups[0], groups[1], groups[2] and groups[3] respectively. The expiry is guaranteed to be in yymmdd format, hence the {6} qualifier. You may want to add a {8} length qualifier to the price.


Implementing a faster inbound neighbour similarity in Networkx

"Jaccard coefficient", not "Jacard" or "Jacquard": it's named after Paul Jaccard.
There are no docstrings. What do these functions do? What do they return?
The results of these functions depend on the global variable G. If you ever needed to generalize your program to operate on more than one graph at a time this dependency would become very inconvenient. The functions ought to either take the graph as an argument, or be methods on the graph class.
Is Gamma standard graph terminology for this function? I've seen it called 'neighbourhood' (or 'open neighbourhood' when it needs to be clear that u is not included).
Python has a built-in decorator functools.lru_cache for caching the results of a function. So you can write:

@lru_cache(maxsize=None)
def neighbourhood(g, u):
    "Return the set of vertices in the graph g that are adjacent to u."
    return set(g.successors(u)).union(g.predecessors(u))

Reuse the set of successors instead of discarding it:

@lru_cache(maxsize=None)
def neighbourhood(g, u):
    "Return the set of vertices in the graph g that are adjacent to u."
    result = set(g.successors(u))
    result.update(g.predecessors(u))
    return result

In common_friends and total_friends, there is no need to make a copy of the neighbourhood before taking the union/intersection. You can take the union/intersection directly:

def total_friends(g, u, v):
    """Return the number of vertices in the graph g that are in the
    neighbourhoods of u or v (or both).

    """
    return len(neighbourhood(g, u) | neighbourhood(g, v))

def common_friends(g, u, v):
    """Return the number of vertices in the graph g that are in the
    neighbourhoods of both u and v.

    """
    return len(neighbourhood(g, u) & neighbourhood(g, v))


Instead of keeping KEY in config, I would keep it with user records. A unique key for each user.

I admit, I don't get why creating keys dynamically would break the load balancing scenario.  We can have a key created at the back-end where we have a single service serving all the load balances servers (such as a database).


Dependency injection in constructor vs Supplying argument in utility functions

If you use second option you should probably declare  methods as static. Since you dont have any "data" associated with NameService object instance(service).

Like this:

public static string GetFullName(Person person)
{
    var fullName = $"{person.FirstName} {person.MiddleName} {person.LastName}";
    return fullName;
}

And then you can call...

NameService.GetFullName(person);

... without object initialazing - without line var service=new NameService();


Find and remove duplicate files in one or more directories

If I had to pick a least-favourite line in the program, it would be this one:

if 'testrun' in globals():

… because

Global variables are bad.
You didn't even declare testrun as a global variable using global testrun, but rather you used introspection.
You didn't test the flag to see whether it was True or False; you just check for its existence.
The whole problem could have been avoided by calling handleResults() with a parameter.

print('%s is not a valid path, please verify' % i)
sys.exit()

When you exit the program due to an error, exit with a non-zero status.
i is an unconventional iteration variable, since it has the connotation of being an integer.  The code would be more readable if you had written for folder in folders: ….

In hashfile(), you should call open() using a with block.
Since hashfile() seems like it could be a basic reusable operation, I would avoid having it print anything.  The findDup() function, which calls hashfile(), prints status updates, and in fact it prints the same path just before calling hashfile().


Find the starting indices of all occurrences of the pattern in the string

Your code contains a bug.

For banana and a, it should return [1, 3, 5], but it doesn't.


Simple binary search tree for use in programming competitions

First of all, your code does not work. In the "insert_bst" function, you create a Node named "new_node" and then assign the rightnode pointer that node's address. However, your "new_node" variable has automatic storage duration, and thus is destroyed at the end of the function. Therefore, after the function call is over, your pointer is pointing to unallocated memory
(or something like that; my knowledge might be inadequate, I rarely deal with pointers). In order to avoid this, you need to use dynamic memory allocation.

Edit: To confirm my claims, I asked a question on StackOverflow.

Then, here is my version of inset_bst() function without next_node variable. However, I did not use it in the code, because I am not sure whether it actually improves the computation time, because it uses more if statemets. And I am too lazy to check :D

void insert_bst(int key, const std::string& value) {
    Node *cur_node = &root_node;
    // Search through bst for key
    while (1) {
        if (key < cur_node->key) {
            if(cur_node->leftnode == nullptr) {
                cur_node->leftnode = new Node(key, value);
                break;
            }
            cur_node = cur_node->leftnode;
        } else {
            if(cur_node->rightnode == nullptr) {
                cur_node->rightnode = new Node(key, value);
                break;
            }
            cur_node = cur_node->rightnode;
        }
    }
}

Here is the modified code with the rest of my criticism/tips:

#include <iostream>

/**
    1. Avoid using "using namespace std". There are plenty of reasons why,
    google it if you doubt my word.
    2. Use nullptr instead of NULL macro
**/

struct Node {
    int key;
    Node *leftnode;
    Node *rightnode;
    std::string value;

    /** 3. It is always wise to use constructors instead of creating empty instances of
        structs / classes and then initializing member variables one by one
    **/
    Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {}

    //If you want the ability to construct nodes with undefined keys/values
    //Node() : leftnode(nullptr), rightnode(nullptr) {}
};

// I initialized it here for testing purposes, you did it in main, it doesn't really matter,
// except that previously the value of root_node was an empty string
Node root_node(1, "Node #1"); // Binary search tree

/**
    4. No need to use the "inline" specifier, at least in this case. The compiler usually
    can decide whether to inline functions by itself.
**/

std::string query_bst(const int key) {
    Node *cur_node = &root_node;
    while (cur_node != nullptr) {
        if (key == cur_node->key) {
            return cur_node->value;
        }
        if (key < cur_node->key) { /* value already returned, no need for else */
            cur_node = cur_node->leftnode;
        } else {
            cur_node = cur_node->rightnode;
        }
    }
    return ""; // Return empty string if not found
    /**
        5. If you don't want to return such awkward empty string, you might consider
        implementing some exception handling (i.e throw an std::runtime_error() with an
        appropriate error message on failure)
    **/
}

/**
    6. Pass strings by const ref if you are not going to modify them
**/
void insert_bst(int key, const std::string& value) {
    Node *cur_node;
    Node *next_node = &root_node;
    // Search through bst for key
    while (next_node != nullptr) {
        cur_node = next_node;
        if (key < cur_node->key) {
            next_node = cur_node->leftnode;
        } else {
            next_node = cur_node->rightnode;
        }
    }
    /**
        7. Currently your code allows duplicate keys. As I did not know whether such
        behaviour was intentional, I left it as it is.
    **/
    if (key < cur_node->key) {
        cur_node->leftnode = new Node(key, value);
    }
    else {
        cur_node->rightnode = new Node(key, value);
    }
}

/**
   8. Finally, with this modified code, you'd need to properly handle dynamically allocated
   memory. However, as your code did not provide any removal functions, I did not implement
   memory deallocation.
**/

int main() {
    /* Test code */
    //root_node.key = 1;
    insert_bst(2, "Node #2");
    insert_bst(3, "Node #3");
    std::cout << query_bst(3) << '\n';
}

Finally, here is the same code without all the comments:

#include <iostream>

struct Node {
    int key;
    Node *leftnode;
    Node *rightnode;
    std::string value;
    Node(int tkey, const std::string& tvalue) : leftnode(nullptr), rightnode(nullptr), key(tkey), value(tvalue) {}
};

Node root_node(1, "Node #1"); // Binary search tree

std::string query_bst(const int key) {
    Node *cur_node = &root_node;
    while (cur_node != nullptr) {
        if (key == cur_node->key) {
            return cur_node->value;
        }
        if (key < cur_node->key) { /* value already returned, no need for else */
            cur_node = cur_node->leftnode;
        } else {
            cur_node = cur_node->rightnode;
        }
    }
    return ""; // Return empty string if not found
}

void insert_bst(int key, const std::string& value) {
    Node *cur_node;
    Node *next_node = &root_node;
    // Search through bst for key
    while (next_node != nullptr) {
        cur_node = next_node;
        if (key < cur_node->key) {
            next_node = cur_node->leftnode;
        } else {
            next_node = cur_node->rightnode;
        }
    }
    if (key < cur_node->key) {
        cur_node->leftnode = new Node(key, value);
    }
    else {
        cur_node->rightnode = new Node(key, value);
    }
}

int main() {
    /* Test code */
    insert_bst(2, "Node #2");
    insert_bst(3, "Node #3");
    std::cout << query_bst(3) << '\n';
}


I have a few points I would like to suggest.

Firstly, I would rename the name_to_index function to fit the verb-first function naming convention. Based on your other naming conventions, I would use something like convert_name_to_index.

The next thing I would do is rename your mpCmd class. The Pythonic convention is to use PascalCase instead of camelCase for class names. Also, shortening words can be handy in some places:

management --> mgt
character --> char

While, in others places it can inhibit understanding:

# Is this a comfy cat? A comfy cot? Comfy cut?
ct.description = 'Comfy'

Now, in your context it is pretty easy to know what the name is supposed to mean. However, especially in class names, its better to have too many characters than have too few. I would rename your class to something like CommandMap.

My next points touch on your convert_val function.

Python understands the conditional in your if-statement just fine (because or has a higher precidence than and). However, to the human eye, it can be ambiguous:

# Is the grouping this?
if (part1 and part2) or (part3 and part4):

# Or this?
if ((part1 and part2) or part3) and part4:

# Or this?
if (part1 and (part2 or part3)) and part4:

I would use the structure of my first example above in your code to help the statement feel less ambiguous.

The second part of convert_val function that I would change is your assert callable(func) line. The assert keyword is generally used in testing and just feels odd here. Here is how I would structure that section of code:

elif isinstance(val, (tuple, list)):
    func, indexes = val
    indexes = rmap(self._convert_key, indexes)

    if not callable(func):
        raise TypeError('{} is not callable'.format(func))

    return (lambda row: func(*rmap((lambda i: row[i]), indexes)))

My final point is in your convert_key function. If the input is not either an int or a str then you raise TypeError. As you have it now this is what prints:

>>>raise TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError

Instead of raising the class TypeError, raise an instance of type TypeError with its own message:

>>>raise TypeError('Key must be an int or a string.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Key must be an int or a string.

Other than these suggestions, your code looks nice.


Evaluate whether string is in alphabetical order or reverse alphabetical order

I think that your solution is overengineered.  I don't think that there is much reason to define a StringCharactersInAlphabeticalOrderEvaluator interface, containing one evaluateAlphabeticalOrderOfCharacters(String) method.  Do you plan to write an implementation other than StringCharactersInAlphabeticalOrderEvaluatorImpl?  Is there even any reason to have an object at all?

To be fair, different languages have different collation rules.  For example, in Spanish, the letter ñ follows n, and, until the rules were simplified in 1994, the digraph ch was treated as a letter between c and d, and ll was treated as a letter between l and m.  However, if we were going to get fancy and generalize, I would recommend doing it "properly", using a Collator.

This exercise, though, is marked as "easy".  It looks like "ASCIIbetical" order is good enough: we don't have to consider case folding, digraphs, diacritics, Unicode surrogate pairs, or locale-specific rules.  For that, we can just compare the code points using char subtraction or Character.compare(char, char).

You have implemented evaluateAlphabeticalOrderOfCharacters() as a monolithic function, which violates the Single Responsibility principle.  There isn't much advantage to having it do two kinds of ordering checks and classify the result into four categories.  You would be better off exposing two independent checks.  In fact, by splitting it up, you might save a few loop iterations, since each loop could exit early as soon as it detected an out-of-sequence character.

Suggested solution

The principal functions in this class are isAlphabeticalOrder() and isReverseAlphabeticalOrder().  They both delegate to a isMonotonic() helper function to avoid code duplication.  There is a classifyOrder() helper to produce the result strings to be printed in main().

I've used CharSequence rather than String, as a hint that the string is to be interpreted more as a sequence of characters.  I think that a List<Character> would be overkill.

import java.util.Scanner;

public class AlphabeticalOrderChecker {
    private static int ASCENDING = +1,
                       DESCENDING = -1;

    private static boolean isMonotonic(CharSequence cs, int trend) {
        for (int i = 1; i < cs.length(); i++) {
            if (trend * Character.compare(cs.charAt(i - 1), cs.charAt(i)) > 0) {
                return false;
            }
        }
        return true;
    }

    public static boolean isAlphabeticalOrder(CharSequence cs) {
        return isMonotonic(cs, ASCENDING);
    }

    public static boolean isReverseAlphabeticalOrder(CharSequence cs) {
        return isMonotonic(cs, DESCENDING);
    }

    private static String classifyOrder(CharSequence cs) {
        boolean asc = isAlphabeticalOrder(cs);
        boolean desc = isReverseAlphabeticalOrder(cs);
        return (asc && desc) ? "IN ORDER AND REVERSE ORDER" :
               (asc)         ? "IN ORDER" :
                      (desc) ? "REVERSE ORDER" :
                               "NOT IN ORDER";
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            System.out.printf("%s %s\n", s, classifyOrder(s));
        }
    }
}


First, look at your documentation to see how will look to users:

  The Go Blog

  Godoc: documenting Go code

$ go doc sprinkle
The sprinkle command allows the user to define some transformations in a
file called test.txt. The user can then provide some domain names such as
'go' and the application will randomly transform it, using the
transformations defined in test.txt. Every transformation in the test.txt
file must have an asterisk (*) in place of the domain name. For example, if
the test file contains:

*-is-awesome.com

love-*.net

lets-*.org

Then, if the user enters 'go' in the command line, the output could be
something like:

go-is-awesome.com
$

Amongst other things, domain name is a misnomer.

Second, look at your sprinkle command help:

$ ./sprinkle -help
$

Third, read your code. And, fourth, run your code.

Find and fix several bugs (others have identified some of them). Since domainName is a misnomer, rename it to wildcard.

Rewrite the sprinkle command go doc description:

$ go doc
The sprinkle command transforms a random line of text from the sprinkle.txt
file by replacing asterisk (*) wildcard characters with text from stdin.

For example,

    $ cat sprinkle.txt
    *-is-awesome.com
    love-*.net
    lets-*.org
    $ echo go | ./sprinkle
    love-go.net
    $ echo go | ./sprinkle
    go-is-awesome.com
    $
$

TODO: provide sprinkle command help.


Script which migrates files to secondary storage and symlinks them

Not bad at all. Nice to see functions but perhaps you have too many.

Do you really need this as a function?

function DeleteFIle($File){
    del $file.fullname
}

This function is listed twice but is only called once. It could have probably stayed in the Archive function.

function CheckPathLength($file){
    if ($File.FullName.Length -ge 220){
        copy $PathWarning $File.DirectoryName
    }
}


Yours is better.  Both are bad.
Don't use either of them
The mysql_* functions aren't a good way to learn how to interact with databases.  It is a shame that there are still tutorials teaching how to interact with databases using these functions.  Here is a snippet that explains more about why you shouldn't use those functions and what you can use instead:

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.Snippet Source

Minor Comments
You missed quotes around phone.
In pure PHP don't use an end tag ?>.  It can cause output if you have blank lines after it causing headers to be sent prematurely (see this).


Selecting indices of a cell array that strcmpi-match the contents of another cell array

Appending to an array

INDX46=[INDX46; i;]; is a very slow way of appending to a vector. Instead, do INDX46(end+1) = i;.

When appending to the matrix in this preferred way, MATLAB actually extends the storage of the vector. MATLAB will double the underlying memory block size so that repeated appending will be optimal (O(log n) rather than O(n)). That is, most of the loop iterations the data will not need to be copied to extend the array.

In contrast, the first method of appending actually creates a new array, and copies the old array and the new value into it. The interpreter does not use the optimal O(log n) method of extending the array.

See this Q&A on Stack Overflow for an experiment that demonstrates the above.

Finding strings

There's no data in the OP that can be easily used to test modifications, but as I see it, the double loop is comparing each of the elements of list46 to each of the elements of elec.label to find the indices in the latter that contain an element of the former. This loop can be sped up greatly by first sorting alphabetically the two lists. With two sorted lists, one need to go through both lists only once to find all matches. The algorithm goes from O(nm) to O(n+m), with n and m the lengths of the two arrays.

MATLAB has a function ismember that does just this:

INDX46 = ismember(elec.label, list46);


Rails and Redis: how should I handle validation here?

In your model.

You can include ActiveModel::Validations directly in your model without relying on ActiveRecord for persistence.

See ActiveModel::Validations & the date_validator gem

A quick example more relevant to you;

class MyThingie

  include ActiveModel::Validations

  validates :start_date, :presence => true
  validates :end_date,   :presence => true

  # Check out the date_validator gem, it allows things like
  validates_date_of :end_date, :after => :start_date

  validates_format_of :location, :with => /[A-Za-z]/

  # ...
end


Avoiding the 'possible loss of data' compiler warning

Your types are not the same, and you're relying on implicit conversion. The compiler is warning you because not all implicit conversions in this case will be valid. If you know that the conversion is valid in your case, then you should do the conversion explicitly. It's sensible to check the condition you're relying on:

extern "C" LPWIN32_FIND_DATAW ZFILEIO_API GetFileInfoByIndex(INT64 index) {
    assert(index <= SIZE_MAX);

    return total_size >= 0
        && index <= file_vec->size()
        && index >= 0 ? &file_vec->at(static_cast<size_t>(index)) : NULL;
}

The check can be either an assert or throw an exception, depending on how confident you are that this condition cannot (even theoretically) be hit in your code. You may also want to make sure that the range of index is checked at a higher level in the code where it can throw a more meaningful exception, e.g. in the constructor of the corresponding type. Even if you do this, keeping an additional check in the code just prior to the cast is useful, because it verifies to a future maintainer that the cast is valid.

If the compiler still complains when you have the explicit cast in place, then I think your only option is to temporarily silence the warning. I still prefer the cast solution even in this case, since it's obvious to the reader that something potentially dangerous is being done.

Note that SIZE_MAX is not defined in the C++ standard AFAICT. It's likely to be available on your platform, but if not there's almost certainly another way of getting the same information, namely the maximum value of size_t.


Finding greatest value in array smaller than x

Interface Design

The class could be better named.  (As @DaveJarvis points out, it's more of a namespace than a class, but I'm OK with a design that is not pure OOP.)  I suggest BinarySearcher: it describes what it can do, without repeating the name of the function, and still leaves it open for you to add a findSmallestValueGreaterThanOrEqualToX() function later.

Returning an Integer is weird, especially since the inputs are unboxed ints.  I know, you want to be able to return null if no suitable element is found.  I have another suggestion: return the index of the element found rather than the element itself; if no suitable element exists then return -1.  That behaviour is reminiscent of String.indexOf(), which all Java programmers should be familiar with.  Knowing the index, the caller can easily retrieve the element from the array.

We could also shorten the function name a bit.  I suggest that the method signature should be

/**
 * Given a sorted array and a limit, finds the rightmost element
 * whose value does not exceed the limit.
 *
 * @param data An array sorted in ascending order
 * @param limit The maximum value to look for
 * @return The index of the last element in data whose value is less
 *         than or equal to limit.  If no such element exists, returns -1.
 */
public static int greatestIndexNotExceeding(int[] data, int limit)

Search Logic

There is no reason for your helper function to consult arr.length.  The helper function's job is to look between indices lb and ub.  The caller will vouch for the validity of those bounds.  What happens beyond that range is none of the helper function's business.

You have seven cases, which is way too many.  You should only need four:

No suitable element
Found the result
Consider the upper half of the range
Consider the lower half of the range

Null-Handling

There's no need to throw new NullPointerException() explicitly.  The very next line will raise a NullPointerException naturally when it tries to access arr.length.  The arr != null assertion is similarly pointless.

When might it be beneficial to check for null explicitly?  When a constructor or a setter method accepts an argument and stores it for future use, but does not try to use it immediately.  In those cases, it can be hard to track down later how an instance or class variable came to be null.

Proposed Solution

public class BinarySearcher {
    /**
     * Insert JavaDoc here…
     */
    public static int greatestIndexNotExceeding(int[] data, int limit) {
        if (data.length < 1) {
            return -1;
        }
        return greatestIndexNotExceeding(data, limit, 0, data.length - 1);
    }

    private static int greatestIndexNotExceeding(int[] data, int limit, int lb, int ub) {
        final int mid = (lb + ub) / 2;

        // Need to go lower but can't
        if (mid == lb && data[mid] > limit) {
            return -1;
        }

        // Found a candidate, and can't go higher
        if (data[mid] <= limit && (mid == ub || data[mid + 1] > limit)) {
            return mid;
        }

        if (data[mid] <= limit) {
            // Consider upper half
            return greatestIndexNotExceeding(data, limit, mid + 1, ub);
        } else {
            // Consider lower half
            return greatestIndexNotExceeding(data, limit, lb, mid);
        }
    }
}

It should be possible to restructure the code to reduce the number of comparisons between data[mid] and limit, but I think it's more readable this way.


Registering or logging in when creating a new comment object

My opinions:

The class methods by and others are unnecessary.
The service object should be initialized by feeding objects instead of params.
Build a guest user is not job of CommentService.

Then code like these:

# Controller
def create
  user     = current_user || build_guest_user
  @comment = user.new(params[:comment])
  service  = CommentService.new(@comment, user)
  if service.save
     if user.guest?
       redirect_to 'guest_user_sign_in_or_register'
     else
       redirect :back, notice: "Comment created"
     end
  else
     # blah blah
  end
end

# ApplicationController
def build_guest_user
  # your logic here
end

# CommentService
def initialize(comment, user)
  @comment = comment
  @user    = user
end

def save
  if @comment.save
    # extra service logic here
  else
    false
  end
end

Add

Mohamad, think about this, when a visitor hit a "Post Comment" button, he will reach create.

If he's logged in, that's fine.

If he not logged in, he will be treated as a guest user, no matter registered or not. -- Then treated by build_guest_user method.

Then, after comment saved, the controller can judge if he is a guest user or not. If not, nothing to do. If he is, an Ajax template will be rendered back asking his signing in or register.

If he signed in, the comment under the guest will be moved to his user account. And this guest user will be deleted, guest session be replaced by user session.

If he register, same as above.

If he refuse to either sign in or register, the guest user and his comment will be kept there.


First, like ANeves said, the only thing your catch does is that it resets the exception's stack trace, which is not what you want to do. Just remove the try/catch completely, it serves no purpose here.

Second, I don't see any reason to use WebRequest here, using WebClient is much simpler.

Also, you might want to have better parameter names: fileloc doesn't say what exactly it is, and doesn't use the usual capitalization. And loc is unnecessarily abbreviated (you're not trying to write a Twitter post where every character counts, readability is more important) and too ambiguous.

public void DownloadFile(string url, string savePath)
{
    var client = new WebClient();
    client.Credentials = new NetworkCredential(Username, Password);
    client.DownloadFile(url, savePath);
}

This method could be rewritten as one expression, but I probably wouldn't do that:

public void DownloadFile(string url, string savePath)
{
    new WebClient { Credentials = new NetworkCredential(Username, Password) }
        .DownloadFile(url, savePath);
}


Does PDO::quote helps me to protect me against sql injection?

The PDO::quote() function is not correct for making column names safe. It's basically a wrapper for the QUOTE() function in MySQL:

The string is returned enclosed by single quotation marks and with each instance of backslash (), single quote ('), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.

The enclosing single-quote marks make the result usable as a string value in SQL, but you are using it for a column name. So you would end up with:
'mycolumn' = 'myvalue'

The single quotes make it not act like a column in your expression. The QUOTE() function is for string or date values, not identifiers like column names or table names.
You posted an update, where you changed to using a bound query parameter for the value, and you used a regular expression replacement function to strip out any non-word characters from the column name.
But this still risks the column being a reserved SQL keyword, which will cause errors in your code:
SELECT = 'myvalue'

To avoid this, the column name should be enclosed in backticks:
`SELECT` = 'myvalue'

If you enclose the column in backticks, then the column may be a reserved keyword, or it can even have punctuation, whitespace, international characters. Those are legitimate for SQL identifiers, but your escaping function would not allow it.
You should make sure if the column name contains a literal back-tick, you double it, which will make it act like a literal back-tick in your SQL.
function quoteIdentifier($str) {
    return '`' . preg_replace('/`/', '``', $str) . '`';
}


Checking whether a string contains a substring only once

Perhaps using pattern matching. It looks more readable to me, but I have no idea about which is more efficient.

public static boolean containsOnce(final String s, final CharSequence substring) {
    Pattern pattern = Pattern.compile(substring.toString());
    Matcher matcher = pattern.matcher(s);
    if(matcher.find()){
        return !matcher.find();
    }
    return false;
}

public static void main(String[] args) throws Exception {
    System.out.println(containsOnce("aba","a"));    //false
    System.out.println(containsOnce("abab", "ab")); //false
    System.out.println(containsOnce("aba", "b"));   //true
    System.out.println(containsOnce("aaa", "aa"));  //true
    System.out.println(containsOnce("",""));        //true
    System.out.println(containsOnce("ab",""));      //false
}

Also note that containsOnce("aaa","aa") returns true. Not sure if you would count this as correct or not.

Note: you can also write it as

Pattern pattern = Pattern.compile(substring.toString());
Matcher matcher = pattern.matcher(s);
return matcher.find() && !matcher.find();

I don't know which of the two is more readable.

EDIT:

After looking up whichever is faster: indexof vs matcher
It seems to be the general consensus that indexof is a bit faster, but that we're talking about such low times that it really doesn't matter much.

Go for whichever solution you prefer I guess ...


Creating readline() function, reading from a file descriptor

As we've basically worked out in the comments: when there's already a thing, use the thing. To get a line from a file descriptor, you can

Call fdopen on your file descriptor to get a FILE*
Check for NULL, perror and exit if necessary
Call fgets
Check for NULL again
Repeat 3-4 as necessary
fclose your FILE*
Do not call close on your file descriptor


Create MD5 hash list of big memory mapped files

You named your class MediaFile but basically its a class which creates checksums for any given file. You should consider to rename the class to e.g ChecksumCreator of FileChecksumCreator. This would make the purpose and the responsibility of that class obvious by looking at its name.
Omitting braces {} although they might be optional can lead to serious bugs which aren't tracked easily. I would like to encourage you to always use them.
You are using C# 6 but you still use private setters for your properties. With C# 6 you can just omit them if you either set the proerties at startup or from inside of the constructor. The backing field of a getter only property is internally handled as readonly and because you only set them inside the constructor you should take this route. While we are at the constructor, you are first assigning null to the Checksums property and later on you are using the GenerateChecksums() method to assign a value to it. The mentioned points could be implemented like so

public string FilePath { get; }
public List<byte[]> Checksums { get; }

private FileInfo fileInfo;
private MemoryMappedFile memoryMappedFile;

public MediaFile(string filePath)
{
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"{filePath} was not found!");
    }

    this.FilePath = filePath;

    this.fileInfo = new FileInfo(filePath);
    this.memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open);

    this.Checksums = this.GenerateChecksums();
}

But basically, you won't need a FileInfo object here, because you are only using the Length property of the FileInfo object. So let us change this like so

public string FilePath { get; }
public List<byte[]> Checksums { get; }

private long fileLength;
private MemoryMappedFile memoryMappedFile;

public MediaFile(string filePath)
{
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"{filePath} was not found!");
    }

    this.FilePath = filePath;

    this.fileLength= new FileInfo(filePath).Length;
    this.memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open);

    this.Checksums = this.GenerateChecksums();
}

But what happens if you decide later on to go the way @EricLippert has shown in the comments, like using a CRC hashprovider to generate the checksums ? You would need to change the class in question. Maybe it would be better to inject a HashAlgorithm provider so you could easily switch to another one.

This would result in an overloaded constructor and a slightly changed Dispose() method like so

private bool hasOwnershipOfHashprovider = false;
private HashAlgorithm hashProvider;

public MediaFile(string filePath)
    : this(filePath, MD5.Create())
{
    hasOwnershipOfHashprovider = true;
}
public MediaFile(string filePath, HashAlgorithm hashProvider)
{
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"{filePath} was not found!");
    }
    if (hashProvider == null)
    {
        throw new ArgumentNullException($"hashProvider");
    }

    this.FilePath = filePath;

    this.hashProvider = hashProvider;
    this.fileLength = new FileInfo(filePath).Length;
    this.memoryMappedFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open);

    this.Checksums = this.GenerateChecksums();
}

public void Dispose()
{
    this.memoryMappedFile.Dispose();
    if (this.hasOwnershipOfHashprovider)
    {
        this.hashProvider.Dispose();
    }
}

But what happens if the user of that class won't call Dispose() ? Take a look at proper-use-of-the-idisposable-interface.
I don't see why the Read() method should be public. If it needs to be public, you should add some proper validation of the passed arguments.
If a filePath is passed to the constructor which represents a file with Length == 0 the MemoryMappedFikle.Create() method will throw an ArgumentException which should better be thrown by your code.


2 small enhancements that I can see:

First, you could avoid to compute log(e,10) twice in each iteration by noticing that log(a*b) = log(a)+log(b). Since one term is fixed, you save 1 computation:

log2 = math.log(2.0,10)

def getDotArrayLog():
    e=55
    data = []

    while e<grandtotal:
        e+=1
        loge = math.log(e, 10)  # compute once only
        data.append((2 * e / (loge + log2 + 2)) - e / (loge - 4))
    return data

then, in your final loop, you could zip both arrays instead of using a counter and index access, and use enumerate to do the index counting for you, since you still need it for your computations:

for counter,(e,p) in enumerate(zip(logs,producta)):
    a = (1-p)*(counter+55)
    print "Amount of primes:", e
    print "Amount of inhibitors:", a
    print e-a


Find a 2x2 vowel square in a grid (Coderbyte 'Vowel Square' problem)

These are all relatively minor notes:

You can use typing.List to provide a better type definition for the parameter (List[str]), precisely defining what it's a list of.
I always try to avoid giving variables names that are just a variation on the Python type to tell me what its type is (that's the type annotation's job); the problem description calls this the "matrix" so I'll use that.
If the problem description doesn't say what to do with invalid input, I'd assume it's fine (and preferable) to just let the code raise an exception if any assumptions are violated.
If you're checking that a bunch of iterable conditions are all true, I think it generally looks nicer to use the all function than to do a bunch of ands.
For iterating over indices (i.e. where it's super obvious from context what the variable represents and a longer name only serves to distract) I always prefer using short, generic variable names like i, j or x, y.

from typing import List

VOWELS = "aeiouAEIOU"

def find_vowel_square(matrix: List[str]):
    """Return the top left grid ref of any 2x2 sq composed of vowels only

    If more than one 2x2 sq exists. Return that which is at the most top-left
    position.
    """
    for y in range(len(matrix) - 1):
        for x in range(len(matrix[y]) - 1):
            if all (matrix[i][j] in VOWELS
                    for i, j in [(y, x), (y+1, x), (y, x+1), (y+1, x+1)]):
                return f"{x}-{y}"

    return "Not found"


Prompting for five test scores and printing the average

Firstly - Java Code Convention
Read the Java code convention, see this cheatsheet
The Java Code convention has a more detailed description -
Why use code conventions (From the link) -

Code conventions are important to programmers for a number of reasons:

80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original
author.
Code conventions improve the readability of the software,
allowing engineers to understand new code more quickly and thoroughly.

Secondly - Refactoring
Start by using arrays - this will really reduce the amount of code you wrote. For example:
// Declare this constant at the top of the class
private static final int NUMBER_OF_SCORES = 5;

int[] score = new int[NUMBER_OF_SCORES];

System.out.println("Please enter your test scores");

// Read all Scores
for (int i = 0; i < NUMBER_OF_SCORES; i++) {
  score[i] = stdIn.nextInt();
}

With arrays, you can also easily calculate the total score and output each score -
// Total Score
int totalScore = 0;
for (int i = 0; i < NUMBER_OF_SCORES; i++) {
  totalScore += score[i];
}

// Output All the scores
for (int i = 0; i < NUMBER_OF_SCORES; i++) {
  System.out.print("score " + i + " = " + score[i]);
}

You can also introduce a Person class - example. (Take note of the getInitials function)
public class Person {

    private final String name;
    private final String surname;

    public Person(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }

    public String getName() {
        return name;
    }

    public String getSurname() {
        return surname;
    }

    public String getInitials() {
        return "" + name.charAt(0) + surname.charAt(0));
    }
}

With the introduction of a Person class, the main function can transform into the for example. (Also splitting up the main function into smaller parts)
public static final int NUMBER_OF_SCORES = 5;

public static void main(String[] args) {
    Scanner stdIn = new Scanner(System.in);
    System.out.print("Please enter your first name: ");
    // Read First Name
    String firstName = stdIn.next();
    System.out.print("Please enter your last name: ");
    // Read Last Name
    String lastName = stdIn.next();
    System.out.println("Hello " + firstName + " " + lastName);
    if (firstName.equals(lastName)) {
        System.out.println("Your first and last name are the same.");
    } else {
        // Now you know you have a valid person.
        Person person = new Person(firstName, lastName);
        System.out.println("Your first and last name are different.");
        processName(person);
        readAndProcessScores();
    }
}

private static void processName(Person person) {
    String full = person.getName() + person.getSurname();
    System.out.println("The length of your first name is: " + person.getName().length());
    System.out.println("The length of your full name is: " + full.length());
    System.out.println("Your initials are " + person.getInitials());
}

public static void readAndProcessScores() {
    Scanner stdIn = new Scanner(System.in);

    int[] score = new int[NUMBER_OF_SCORES];
    System.out.println("Please enter your test scores");
    // Read all Scores
    for (int i = 0; i < NUMBER_OF_SCORES; i++) {
        System.out.print("Score " + i + " = ");
        score[i] = stdIn.nextInt();
        System.out.println();
    }

    // Output All the scores
    for (int i = 0; i < NUMBER_OF_SCORES; i++) {
        System.out.print("score " + i + " = " +score[i] + " ");
    }

    // Total Score
    int totalScore = 0;
    for (int i = 0; i < NUMBER_OF_SCORES; i++) {
        totalScore += score[i];
    }

    double scoreAverage = (((double) totalScore) / NUMBER_OF_SCORES);
    System.out.println("Total = " + totalScore);
    System.out.println("Your average is:  " + scoreAverage);
}

This code itself can be refactored even more, but this I leave to you :)
Try doing the following -

Introduce one more class.

Extract the calculate total score into its own function. Use this declaration:
  public static double calculateAverage(int[] scores)

Add some comments to the methods :)

General tips

Always use good descriptive variable names.
Declare variables as needed (Close to where they are used).

Hope this helps!


Increase efficiency of basic string compressor

The following code performs twice as fast as your code does on my machine, both for short strings (e.g. your example) and longer strings.

def compressBetter(string):
    last = string[0]
    result = []
    count = 1
    for c in string[1:]:
        if c == last:
            count += 1
        else:
            result.append(last + `count`)
            count = 1
            last = c

    result.append(last + `count`)
    return ''.join(result)

The main two optimisations are

Using backticks instead of str() for int to str conversion (note that backticks are deprecated and have been removed in Python 3). Some discussion of why they are faster is given here.
Iterating over the string directly rather than indexing. I'm guessing this saves function calls, which have quite a lot of overhead in python.

I find that each optimisation accounts for about half of the performance increase. I am using cPython - the results would probably be very different if you used a different interpreter.


You should be able to cut the code length and improve performance, by simplifying the algorithm. Here are some of the problems I've noticed in your implementation:

You're currently processing all of the type's properties, this is not necessary as you only need few concrete ones. There are few other problems deriving from this one.
You're creating the instance through the Activator class while you're also requesting the constructor of the class, since you already have the ConstructorInfo, it doesn't make much sense to call Activator.CreateInstance. Especially since the Activator is the slowest way to create an instance of a type. You should only stick to one of them, in this case you need information that is contained in the ConstructorInfo, I guess the choice is obvious.

A simpler version (using your Target method):

public static TSource With<TSource, TProperty>(this TSource source,
    Expression<Func<TSource, TProperty>> selector, TProperty value)
{
    var constructor = typeof(TSource).GetConstructors().Single();
    var parameters = GenerateParameters(source, constructor,
        new KeyValuePair<string, object>(selector.Target(), value)).ToArray();
    return (TSource) constructor.Invoke(parameters);
}

private static IEnumerable<object> GenerateParameters<TSource>(
    TSource source, ConstructorInfo ctor,
    KeyValuePair<string, object> parameterToModify)
{
    var type = typeof(TSource);
    foreach (var parameter in ctor.GetParameters())
    {
        if (string.Equals(parameter.Name, parameterToModify.Key, StringComparison.OrdinalIgnoreCase))
        {
            yield return parameterToModify.Value;
        }
        else
        {
            yield return type.GetProperty(parameter.Name,
                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)?.GetValue(source);
        }
    }
}

I'm not a fan of long ternary operators, but if you prefer that you can always switch it. I don't really like KeyValuePair<,> either, but it makes sense to keep things coupled and adding a separate class seems somewhat redundant as it will be used only in 1 occasion.

This is the cleaner approach, but if you really want to squeeze a bit more performance you can avoid the .ToArray() call by creating an object[] instead of IEnumerable<object>:

public static TSource With<TSource, TProperty>(this TSource source,
    Expression<Func<TSource, TProperty>> selector, TProperty value)
{
    var constructor = typeof(TSource).GetConstructors().Single();
    return (TSource) constructor.Invoke(GenerateParameters(source, constructor,
        new KeyValuePair<string, object>(selector.Target(), value)));
}

private static object[] GenerateParameters<TSource>(
    TSource source, ConstructorInfo ctor,
    KeyValuePair<string, object> parameterToModify)
{
    var type = typeof(TSource);
    var ctorParameters = ctor.GetParameters();
    var parameters = new object[ctorParameters.Length];
    for (int i = 0; i < parameters.Length; i++)
    {
        var ctorParameter = ctorParameters[i];
        if (string.Equals(ctorParameter.Name, parameterToModify.Key, StringComparison.OrdinalIgnoreCase))
        {
            parameters[i] = parameterToModify.Value;
        }
        else
        {
            parameters[i] = type.GetProperty(ctorParameter.Name,
                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)?.GetValue(source);
        }
    }
    return parameters;
}

It's a bit longer, but it's not necessarily less readable, you can pick whatever suits you better.

P.S

Perhaps some caching mechanism would be useful, to improve performance of multiple sequential calls.


Verify if meeting datetime ranges overlap in an IEnumerable list of meetings

Sorting is what actually makes it work but if you also want it to be more linq-ish and more solid then you should change the following things:

move the overlap-logic into another method
change the method to return an IEnumerable<Meeting[]> for meetings that overlap
use Any to find out whether any meeting overlap
make both methods extensions

Example:

public static IEnumerable<Meeting[]> Overlappings(this IEnumerable<Meeting> meetings)
{
    var last = (Meeting)null;
    foreach (var meeting in meetings.OrderBy(m => m.Start))
    {
        if (last != null && meeting.OverlapsWith(last))
        {
            yield return new [] { last, meeting };
        }
        last = meeting;
    }
}

public static bool OverlapsWith(this Meeting x, Meeting y)
{
    return x.Start < y.Start ? x.End > y.Start : y.End > x.Start;
}

Gets overlapping meetings:

var overlappingMeetings = meetings.Overlappings();

or checks if there are any. It stops at the first overlapping pair found:

var meetingsOverlap = meetings.Overlappings().Any();

with these new extensions you are more flexible because you can easily check any two meetings overlap and it's easier to undestand than DoesNotOverlap. Usually it's better to write positive conditions and negate them if necessary rather than the other way around.

But even this could be further improved by overloading the two < and > operators:

public static bool operator <(Meeting x, Meeting y)
{
    return x.End < y.Start;
}

public static bool operator >(Meeting x, Meeting y)
{
    return x.End > y.Start;
}

and making the OverlapsWith method still more natural:

public static bool OverlapsWith(this Meeting x, Meeting y)
{
    return x.Start < y.Start ? x < y : y > x;
}


The code is clean, modular and readable. You could try to work with generators
to make the calculations lazy.

I think the namedtuple are a better choice than your dict approach, something like:

Node = collections.namedtuple('Node', ['name', 'distance', 'children'])

You can look into the way a functional language like Hskell or Clojure represents trees. It is weird that you mark the leaves of your tree by empty dicts and replace them with the calculated distance.

PEP8:

Use 4 spaces per indentation level.
Separate top-level function and class definitions with two blank lines.

set_start(): Why not just return tree[start]?
set_end():

tree[end] can result in a KeyError
Why the if len(nodes) > 1?

if end in tree:
    del tree[end]
for child in tree.values():
    set_end(child, end)
return tree

node_distance(): This is an internal function and can be inlined in map_tree().
Please do not place code on module level, but wrap it in a main() or test() function.

nodes = [key for key in x.keys()] can be simplified to nodes = list(x.keys()).


To add to Andrew's answer about taking advantage of what type of timestamps can be creating using strtotime(), your code can be reduced to around 25 lines...

<?php

$schedule = array(
    'this Sunday 8am',
    'this Sunday 10am',
    'this Sunday 12pm',
    'this Sunday 6:30pm',
    'this Wednesday 7pm',
    'this Saturday 10am'
    );

$current_time = strtotime('now');
foreach ($schedule as &$val) {
    $val = strtotime($val);
    // fix schedule to next week if time resolved to the past
    if ($val - $current_time < 0) $val += 604800;
    }
sort($schedule);
$countdown = $schedule[0] - $current_time;

?>

<script type="text/javascript">
    var myTime = <?php echo $countdown; // just personally prefer full tags ?>;
    $('#countdown').countdown({ until: myTime});
</script>

To add to visionary-software-solutions' answer, it would be best to store the schedule in a database or a separate xml/text/json/etc type file.  This way, you can have staff simply use an internal webform to change schedules instead of having the PHP dev hard-code the changes every time.  In that webpage, you can allow staff to only select a weekday and time, and have the page translate that into a string usable by strtotime() in this countdown script.

Edit: fixed strtotime() values.  Careful with "this day" vs "next".  For some insight into what type of strings strtotime() can take, see: http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html


This is a review of your binary tree implementation. I suppose it works, and it doesn't violate any major Go idioms. However, your algorithm for getNode sucks (\$O(n)\$ complexity), and there are a few minor WTFs.

I fail to understand why your SearchTree struct contains a value *int. Your design has no way for a user to get the value out of the tree, and changing the value would destroy the sorting. All you ever do is get a pointer to an argument (which was passed by value…), and then do annoying if value != nil tests. All of that is unnecessary once you use a simple value int.

As mentioned above, your getNode() is weird: Unless the current node contains the value, you recurse into both the left and right subtree. Since you insert the values in a sorted order, we can use the binary tree as an actual binary tree. The function then simplifies to:

func (node *SearchTree) getNode(i int) *SearchTree {
    if node.value < i {
        if node.left == nil {
            return nil
        }
        return node.left.getNode(i)
    }
    else if i < node.value {
        if node.right == nil {
            return nil
        }
        return node.right.getNode(i)
    }
    else {
        return node
    }
}

I also renamed the receiver argument from r to the less cryptic node, and changed the receiver type to *SearchTree. Previously, your function took a tree by value (i.e. copy), then returned a pointer to that copy, which appears to be a bit backwards.

Actually, we can use the same getNode() function for both search and insertion with a few variations. To do this, we return a pointer to the .left or .right entry, which is itself a pointer. We guarantee that the returned pointer will never be nil, and that it will be a pointer to nil if no element was found. Only if it points to nil will that pointer will be writable.

func (node *SearchTree) getNode(i int) **SearchTree {
    if node.value < i {
        if node.left == nil {
            return &node.left
        }
        return node.left.getNode(i)
    } else if i < node.value {
        if node.right == nil {
            return &node.right
        }
        return node.right.getNode(i)
    }
    return &node // not nil, not writable
}

func (node *SearchTree) Contains(n int) bool {
    return *(node.getNode(n)) != nil
}

// returns true if the tree was mutated as a result,
// and false if the number was already present
func (node *SearchTree) Add(n int) bool {
    target := node.getNode(n)
    if *target == nil {
        *target = &SearchTree{n, nil, nil}
        return true
    }
    return false
}

This double pointer may seem a bit jarring since we're already using one level of pointers. However, we want a pointer to that field in the parent node, which merely happens to contain a pointer type itself.

There is a remaining problem with your tree. Right now, declaring a variable of type SearchTree will assign a default value, which is a struct with all members assigned their default values – nil for pointers and 0 for integers. However, this means that the following code will always evaluate to true:

val empty SearchTree
empty.Contains(0) // true, oops!

The solution is to create a wrapper type containing a pointer to the search tree for the public interface. What was previously called SearchTree, we rename to node, and create type BinaryTree struct { root *node }. While not necessary, I'd also provide an explicit constructor NewBinaryTree().

This is the code I ended up with:

type BinaryTree struct {
    root *node
}

func NewBinaryTree() *BinaryTree {
    return &BinaryTree { nil }
}

type node struct {
    value int
    left, right *node
}

func (node *node) getNode(i int) **node {
    if node.value < i {
        if node.left == nil {
            return &node.left
        }
        return node.left.getNode(i)
    } else if i < node.value {
        if node.right == nil {
            return &node.right
        }
        return node.right.getNode(i)
    }
    return &node // not nil, not writable
}

func (tree *BinaryTree) Contains(n int) bool {
    root := tree.root
    if root == nil {
        return false
    }
    return *(root.getNode(n)) != nil
}

// returns true if the tree was mutated as a result,
// and false if the number was already present
func (tree *BinaryTree) Add(n int) bool {
    if tree.root == nil {
        tree.root = &node{n, nil, nil}
        return true
    }
    target := tree.root.getNode(n)
    if *target == nil {
        *target = &node{n, nil, nil}
        return true
    }
    return false
}

(see it live on ideone)


Deflating a Stream using System.IO.Compression

I think you're doing too much in one function, hiding the big picture I'd want to read without going into the implementation details. I'd first start with a broad overview:

using (var reader = new StreamReader(e.GetDataStream().AsStreamForRead())
{
    SkipOptionalZlibHeader(reader);
    var uncompressedStream = ReadAndDecompressStream(reader);
    DecodeJson(uncompressedStream);
}

With:

const int ExpectedZLibHeaderMarker = 0x78;
const int ExpectedZLibHeaderSize = 2;

static void SkipOptionalZlibHeader(BinaryReader reader)
{
    if (!HasZlibHeader())
        return;

    reader.Seek(CalculateZLibHeaderSize(), SeekOrigin.Current);

    bool HasZlibHeader()
        => reader.PeekChar() == ExpectedZLibHeaderMarker;

    long CalculateZLibHeaderSize()
        => return ExpectedZLibHeaderSize;
}

Stop here for one second. Here you made some HUGE assumptions:

Compression flags are always 0x78. That's not true because if message contract simply says that it's a compressed zlib stream with zlib header then they may change it without breaking the contract. Also note that there is no reason the raw compressed stream cannot start with that magic number. You may want to try to decode the trimmed stream and if it fails then try to decode it as it had no header. Better: be sure it has (or not) the header and stick to it otherwise you're deploying code that may fail.
Header size is always two bytes. According to the flags there might be more than that.
Everything else in the stream is data. No, there is also a footer with a checksum.

Note that we dropped one useless copy because SkipOptionalZlibHeader() simply seek after the header. As exercise for the reader: if underlying stream does not support seeking (check CanSeek property) then you need to read and discard those bytes.

Note that ReadAndDecompressStream() is returning a Stream, the fact that you reuse the same MemoryStream multiple times (very good things if you have a measured and truly beneficial gain in memory footprint and/or performance) is an implementation detail and I'd love to keep its callers unaware of that. Also there is no reason to reuse DeflateStream. We may then implement it as this:

static Stream ReadAndDecompressStream(BinaryReader reader)
{
    // Go back to beginning for writing
    _output.Position = 0;

    using (var decompressor = new DeflateStream(_output, CompressionMode.Decompress, true))
    {
        reader.CopyTo(decompressor);
    }

    // Go back to beginning for reading
    _output.Position = 0;

    return _output;
}

There is something that really bothers me: we're returning an IDisposable object (MemoryStream) but caller does not have its ownership (and then it has not to dispose it). It's not intuitive and it must be documented. Also note that your actual code is working just because an implementation detail: StreamReader calls Dispose() on the provided Stream and your code is working just because disposing MemoryStream has not visible effects (but it's an implementation detail). We also have to do something for that.

Let's first change ReadAndDecompressStream() to return a StreamReader instead and change its name to something more meaningful:

static StreamReader CreateDecompressedReader(BinaryReader reader)
{
    // Go back to beginning for writing
    _output.Position = 0;

    using (var decompressor = new DeflateStream(_output, CompressionMode.Decompress, true))
    {
        reader.CopyTo(decompressor);
    }

    // Go back to beginning for reading
    _output.Position = 0;

    return new StreamReader(_output, Encoding.UTF8, false, _output.Length, true);
}

Now caller has the ownership of the disposable object:

using (var reader = new StreamReader(e.GetDataStream().AsStreamForRead())
{
    SkipOptionalZlibHeader(reader);
    using (var decompressedReader = CreateDecompressedReader(reader))
        DecodeJson(decompressedReader);
}

Note that I removed ?., in your original code if e.GetDataStream()? returned null then the first call to datastr.CopyTo() fails. If this may happen then properly handle the case.

As final step you should add some error checking. With I/O things may go wrong then you'd better be prepared (especially if you keep those assumptions in-place), just don't add catch (Exception) and be specific.


Calculate the average score of groups and each student, C

Completely prototype functions: debt() student_score() group_score();

// void debt();
void debt(int student_list_size);

Avoid naked magic numbers.  Use #define or a constant to self document various numbers.

#define TEST_N (15)
struct STUDENTS {
  ...
  char test[TEST_N];
};

void debt(int student_list_size) {
  // wchar_t test_wchar[15];
  wchar_t test_wchar[TEST_N];
  ...
  // mbstowcs(test_wchar, student_list[i].test, 15);
  mbstowcs(test_wchar, student_list[i].test, TEST_N);

Use size_t for array index types and the result of sizeof.  int may not be the right size to use as an index.  (Also i in main())

 // void student_score(int student_list_size) {
 void student_score(size_t student_list_size) {
   ...
   // for (int i = 0; i < student_list_size; i++) {
   for (size_t i = 0; i < student_list_size; i++) {

Localize variables.  This approaches a style issue, but declaring variables close to their use has value.

void student_score(int student_list_size) {
  // int exam;
  // int average;
  // int digit;
  // int counter_digits;

  for (int i = 0; i < student_list_size; i++) {
    int exam;
    int average;
    int digit;
    int counter_digits;

The strdup() serves no purpose.  Eliminate it.

// sscanf(strdup(buffer), "%d ...
sscanf(buffer, "%d ...

The return value of sscanf() should be checked and string widths limited.  Note: student_list[i].name will have a ' ' at the end.

// sscanf(buffer, "%d %[^0-9] %d %s", &student_list[i].group, ...
if (4 != sscanf(buffer, "%d %99[^0-9] %d %14s", &student_list[i].group, ...) {
   Handle_Format_Error();

Use valid main() signature.

int main() {
int main(void) {

Conversions char to/from wchar_t may need different sizes.
The extra '\n' in puts("4 - Выход\n"); looks wrong.  Guess I am not a fan of puts().  Why not use 1 function call?

fputs("\nВыберите номер пункта меню:\n"
      "1 - Cтуденты, имеющие задолженности\n"
      "2 – Средний балл каждого студента\n"
      "3 – Средний балл всей группы\n"
      "4 - Выход\n"
      "\n", stdout);


I personally like to rely on named functions rather than inline anonymous functions.

this.AjaxPoller = {
  poll: poll,
  request: request
};

function request() {
  $(".ajax_poller[data-url]").each(fetchDataForElement);
}

function fetchDataForElement(i, elem) {
  var url = $(elem).data("url");
  $.getJSON(url, handleJson);
}

function handleJson(data) {
  if (checkProgress(data)) {
    location.reload();
  }
  $.each(data, function(key, val) {
    $(key+ ' .progress_info').html(val);
    $(key + ' .progress-bar').width(val);
  });
}

function poll() {
  setTimeout(this.request, 5000);
}

function checkProgress(obj) {
  var correct = true;
  for (key in obj) {
    if (obj[key] != '100%') correct = false;
  }
  return correct;
}


I think the first version is slightly more elegant and looks okay to me.

In the second version, I would replace LABELS with FLET. LABELS would indicate some kind of recursion.

Generally I would also think if the nested expansion is something I would want, vs. an expansion into a LET* form.

I would also replace CAR and CDR with FIRST and REST.

The DESTRUCTURING-BIND is also not necessary:

(defmacro -> (x form &rest more)
  (cond (more
         `(-> (-> ,x ,form) ,@more))
        ((and (consp form)
              (member (first form) '(lambda function)))
         `(funcall ,form ,x))
        ((consp form)
         `(,(first form) ,x ,@(rest form)))
        (form
         `(,form ,x))
        (t x)))


Compare two arrays and show number of matches in a percentage value

I'm assuming you have already broken your text down into its individual words and stripped the punctuation marks, etc, in your text array?

If so, the percentage of words from the given text array that match your word-list should be pretty easy to find.

Something along the lines of:

function matchPerc(wordList, text){
  var matches = text.filter((word)=>{return wordList.includes(word)}).length
  return (matches / text.length * 100).toFixed(2) + '%'
}


Plain C implementation of 'Cumulative All' operation for R

I see some things that may help you improve your code.

Use variables effectively

The code begins with this:

SEXP cumall_impl(SEXP x) {
    SEXP res = PROTECT(allocVector(LGLSXP, XLENGTH(x)));
    R_xlen_t n = XLENGTH(x);

However, there's not really any reason not to define and use n first:

SEXP cumall_impl(SEXP x) {
    R_xlen_t n = XLENGTH(x);
    SEXP res = PROTECT(allocVector(LGLSXP, n));

Use all required #includes

The code uses memset and so it should also have this line:

#include <string.h>

Even though it happens to compile because some of the R libraries probably also include that, it's important to make sure that the code does not rely on undocumented interface assumptions.

Use a single loop over all elements

The code uses memset to initialize all values to FALSE and then sets the first value explicitly and then loops through all other values.  I'd be inclined instead to recode that as a single for loop instead:

int prev = TRUE;
for (R_xlen_t i = 0; i < n; ++i) {
    if (p_x[i] == TRUE)
        p_res[i] = prev;
    else if (p_x[i] == NA_LOGICAL)
        p_res[i] = NA_LOGICAL;
    else
        p_res[i] = FALSE;
    prev = p_res[i];
}

Writing it this way avoids the need for the if (n == 0) construct and also eliminates the need for the memset.

Note: Ordinarily, we'd prefer to use a switch there instead of a chained if..else but we're prevented from doing so because NA_LOGICAL does not evaluate to an integer constant the way it's defined in R.


Composing a prototype chain in JavaScript

I'll admit to being new to this concept, and can't think of a real-world application for this method. Regardless, here's my thoughts.

Issues #1 and #2 are directly results of your use of Object.Assign which seems an acceptable limitation. Issue #3 is stating a fact of how Object prototypes are set up. The prototype of Object.prototype is by definition null, so #3 is technically a given.

However, your questions make your meaning of #3 more clear.

  Is throwing an error in appendToProto the right way to enforce the assumption from the third issue?

I wouldn't think so, as it limits the usefulness of your function. I would simply skip null values:

if (obj === null || obj === Object.prototype)
    return proto;

This has the benefit of treating null input essentially as if it were not provided, which would seem a more expected result. You could still have an error thrown, but I don't see the value.

If you choose to have an error, at least make the issue more obvious. "Prototype chains are assumed to be delimited by Object.prototype." is confusing and unclear what the issue is to me. I would go for something like: "Cannot appendToProto of null."

In general the error message should indicate what is wrong with the input instead of the codes philosophy regarding what its input should be.


Add entities to and execute "ExecuteMultipleRequest"

Your logic looks fine to me. If you find yourself creating something in two places then feel free to create a helper function to do so.

Your logic can be arguably simpler if you count down rather than up, since we already know the number of requests.

Something like:

private static int MAXTOBEPROCESSED = 1000;

public void processEntities (List<Entity> entities)
{
    var createMultiple = CreateMultipleRequest();

    for (int n = entities.Count; n > 0; n--)
    {
        createMultiple.Requests.Add(new CreateRequest{ Target = entities[n] });

        if (n % MAXTOBEPROCESSED == 0)
        {
            var responseWithResults = (ExecuteMultipleResponse)service.Execute(createMultiple);
            createMultiple = CreateMultipleRequest();
        }
    }
}

private CreateMultipleRequest()
{
    return new ExecuteMultipleRequest()
    {
        Requests = new OrganizationRequestCollection(),
        Settings = new ExecuteMultipleSettings()
        {
            ContinueOnError = false,
            ReturnResponses = true
        }
    };
}


Vertical & Horizontal Direction of a DataTable

I like that you have an actual method, instead of a bunch of code in Main. This makes is easier to reuse, segment changes, and test.

Passing in a string for horizontalDirection and verticalDirection is error prone. The caller could pass in the wrong value without realizing it. It also makes it harder to make changes with refactoring tools.

A better data type would be an enum. An example would be

enum HorizontalDirection
{
    LeftToRight,
    RightToLeft
}

and similar for the vertical direction.

In terms of making it simpler, the main thing that sticks out is you have essentially 4 nearly identical loops. Let's start by comparing the adding of rows. Between the LR and RL versions, the only difference is the direction the column j loop goes. The direction you go when setting all of the cell values doesn't matter in this case (because you are looking up the column with the same index you are setting in the value), so let's move the row adding loops outside the column adding loops.

Now our method looks like this:

internal DataTable GetContainerLocationMap(int row, int column, string bayCode, HorizontalDirection horizontalDirection, VerticalDirection verticalDirection)
{
    var pageMap = new DataTable();

    if (horizontalDirection == HorizontalDirection.LeftToRight)
    {
        for (int i = 1; i <= column; i++)
        {
            pageMap.Columns.Add("C" + i);
        }
    }
    else if (horizontalDirection == HorizontalDirection.RightToLeft)
    {
        for (int i = column; i > 0; --i)
        {
            pageMap.Columns.Add("C" + i);
        }
    }

    if (verticalDirection == VerticalDirection.BottomToTop)
    {
        for (int i = row; i > 0; --i)
        {
            var _pageMapRow = pageMap.NewRow();
            for (int j = column; j > 0; --j)
            {
                _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
            }
            pageMap.Rows.Add(_pageMapRow);
        }
    }
    else if (verticalDirection == VerticalDirection.TopToBottom)
    {
        for (int i = 1; i <= row; i++)
        {
            var _pageMapRow = pageMap.NewRow();
            for (int j = column; j > 0; --j)
            {
                _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, i);
            }
            pageMap.Rows.Add(_pageMapRow);
        }
    }

    return pageMap;
}

Better, but there still seems to be some duplication. Let's try to condense the row adding loops.

Comapring BT against TB, the only difference is the start, end, and direction of the i loop. That means the inside of the loop is identical. Sound like a good place for another method?

internal DataTable GetContainerLocationMap(int row, int column, string bayCode, HorizontalDirection horizontalDirection, VerticalDirection verticalDirection)
{
    var pageMap = new DataTable();

    if (horizontalDirection == HorizontalDirection.LeftToRight)
    {
        for (int i = 1; i <= column; i++)
        {
            pageMap.Columns.Add("C" + i);
        }
    }
    else if (horizontalDirection == HorizontalDirection.RightToLeft)
    {
        for (int i = column; i > 0; --i)
        {
            pageMap.Columns.Add("C" + i);
        }
    }

    if (verticalDirection == VerticalDirection.BottomToTop)
    {
        for (int i = row; i > 0; --i)
        {
            AddRowToContainerMap(i, column, bayCode, pageMap);
        }
    }
    else if (verticalDirection == VerticalDirection.TopToBottom)
    {
        for (int i = 1; i <= row; i++)
        {
            AddRowToContainerMap(i, column, bayCode, pageMap);
        }
    }

    return pageMap;
}

private static void AddRowToContainerMap(int currentRow, int column, string bayCode, DataTable pageMap)
{
    var _pageMapRow = pageMap.NewRow();
    for (int j = column; j > 0; --j)
    {
        _pageMapRow["C" + j] = string.Format("{0}-{1}-{2}", bayCode, j, currentRow);
    }
    pageMap.Rows.Add(_pageMapRow);
}

You could get really fancy and create variables for your loop index start, end, and increment conditions. I don't think it would help readability, but this is another option for condensing code:

int iStart;
int iEnd;
int iIncrement;

if (horizontalDirection == HorizontalDirection.LeftToRight)
{
    iStart = 1;
    iEnd = column + 1;
    iIncrement = 1;
}
else
{
    iStart = column;
    iEnd = 0;
    iIncrement = -1;
}

for (int i = iStart; i != iEnd; i += iIncrement)
{
    pageMap.Columns.Add("C" + i);
}

Comparing the readability of the two, I don't like this change.

At this point, you have two separate if blocks, each with their own for loop, and only one function inside. That's about as "simple" as I would try to make it.

Some style suggestions (the first two are the only ones I feel strongly about, the rest are very subjective):

Using an underscore in a variable name is something I expect for a member variable (field), and not a a local variable. I'd rename _pageMapRow to pageMapRow.
The variables row and column are somewhat ambiguous. At a first glance, I expected them to be an index. Turns out they are the total number of rows and columns to generate. Something like maxRow or totalRows would be clearer in my opinion.
Since we don't have any background to what your function is for, I don't know what bayCode means. If it is clear based on your context, leave the variable name as is. I presume it has to do with an identifier in a warehouse floor or similar.
C# 6 introduced string interpolation as an alternative to string.Format(). It's not necessarily more or less readable in this particular instance, but I like to share it as an option for other scenarios. If you had a longer string it may be useful to see the values as you read it. It also means you don't have to remember to change all of your indices as you add/remove parameters to string.Format.  You could set the cell values using this sytax:

pageMapRow["C" + j] = $"{bayCode}-{j}-{currentRow}";

internal is an unexpected access modifier. That means your method is available for any caller inside your assembly, but not outside. It certainly has its uses, but I tend to learn toward the broader public vs private.

Final look putting all of it together

public enum HorizontalDirection
{
    LeftToRight,
    RightToLeft
}

public enum VerticalDirection
{
    TopToBottom,
    BottomToTop
}

public DataTable GetContainerLocationMap(int totalRows, int totalColumns, string bayCode, HorizontalDirection horizontalDirection, VerticalDirection verticalDirection)
{
    var pageMap = new DataTable();

    if (horizontalDirection == HorizontalDirection.LeftToRight)
    {
        for (int i = 1; i <= totalColumns; i++)
        {
            pageMap.Columns.Add("C" + i);
        }
    }
    else if (horizontalDirection == HorizontalDirection.RightToLeft)
    {
        for (int i = totalColumns; i > 0; --i)
        {
            pageMap.Columns.Add("C" + i);
        }
    }

    if (verticalDirection == VerticalDirection.BottomToTop)
    {
        for (int i = totalRows; i > 0; --i)
        {
            AddRowToContainerMap(i, totalColumns, bayCode, pageMap);
        }
    }
    else if (verticalDirection == VerticalDirection.TopToBottom)
    {
        for (int i = 1; i <= totalRows; i++)
        {
            AddRowToContainerMap(i, totalColumns, bayCode, pageMap);
        }
    }

    return pageMap;
}

private static void AddRowToContainerMap(int currentRow, int column, string bayCode, DataTable pageMap)
{
    var pageMapRow = pageMap.NewRow();
    for (int j = column; j > 0; --j)
    {
        pageMapRow["C" + j] = $"{bayCode}-{j}-{currentRow}";
    }
    pageMap.Rows.Add(pageMapRow);
}


I think you should use uint for things where you cannot have negative values.

vector_error CVectorGet(CVectorInt *vector, int index, int * value)
{
    if(index < vector->nrOfElements && index >= 0)

This check, for instance, wouldn't need the comparison with 0 if you used uint.

In the comments I already said something about overflow. Now, you can indeed say "that's such a big amount of elements, people are not going to surpass this" and not build it in. That's okay. Be sure to add it in as a comment in the header though, because you don't want to accidentally find out that this is a problem.