See §1.9 for the cause of the bug identified by janos.

1. Review

The code only runs on Python 2.7, because it uses the / operator for floor division. But support for Python 2.7 is scheduled to end in 2020. It is long past the time when it was a good idea to start writing new projects in Python 2.7. Even if you really can't use Python 3, it is still a good idea to use the floor division operator // to make the code portable.
There are no docstrings. What do these functions do? In the case of heapSort there is a comment that could be turned into a docstring.
heapSort modifies its input. If I run:

>>> a = [6, 7, 2, 4, 1, 0, 3, 9, 8, 5]
>>> heapSort(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Then a is now empty:

>>> a
[]

This is likely to be surprising to someone using this code. It would be better to either leave the input unchanged (taking a copy if necessary), like the built-in function sorted, or to modify the input in-place, like the method list.sort.
The name struct could be improved: for experienced Python programmers this name suggests a fixed-size object of the kind that is manipulated by the struct module. A name like list or seq (for "sequence") would be clearer.
The base case does not depend on x and so it should be outside the loop.
Two values can be swapped without needing a temporary variable, if you use a tuple assignment:

struct[x-1], struct[x//2] = struct[x//2], struct[x-1]

The numbers x-1 and x//2 are computed three times. The repetition of x-1 can be avoided by changing the loop from:

range(len(seq),0,-1)

to:

range(len(seq) - 1, -1, -1)

which can be simplified to:

reversed(range(len(seq)))

and the repetition of x//2 can be avoided by assigning a local variable:

parent = (x + 1) // 2

(It need to be (x + 1) // 2 rather than x // 2 because of the change in the loop range.)
It's conventional use names i, j and so on for index variables (leaving x, y and so on for coordinates).
Normally the way heaps are implemented is that element \$i\$ is the parent of elements \$2i + 1\$ and \$2i + 2\$. However, in the code in the post, element \$i\$ is the parent of elements \$2i\$ and \$2i + 1\$. But this requires element 0 to be its own parent, which makes no sense! Presumably this is why you felt the need to add the special case:

if struct[0] < struct[1]:

But this special case led to the bug.

If you changed the implementation so that it used the usual convention for the layout of the heap, then this special case would be unnecessary. Moreover, if you did this then the special case:

if len(struct) < 2:

would also be unnecessary.
heapify currently does two things: it converts the input sequence into a max-heap, in-place, and it pops the first (maximum) item. It would be clearer, I think, to separate these two features, so that heapify only does the heap-conversion, leaving the popping to the caller.

2. Revised code

def heap_sorted(iterable):
    "Return new list of all items from iterable in descending order."
    result = []
    seq = list(iterable)
    while seq:
        heapify(seq)
        result.append(seq.pop(0))
    return result

def heapify(seq):
    "Transform sequence into a max-heap, in-place."
    for i in reversed(range(1, len(seq))):
        parent = (i - 1) // 2
        if seq[i] > seq[parent]:
            seq[i], seq[parent] = seq[parent], seq[i]

3. Performance

The docstring says:

  HeapSort. Worst: \$n \log n\$

But it is easy to see that this is not the case. That's because heapify is called \$n\$ times, and on the \$i\$th call heapify loops over all the remaining \$n-i\$ elements of the sequence, and calls struct.pop(0) which also takes time proportional to the length of struct. So the overall runtime is proportional to $$ \sum_{0\le i< n} n - i = {n(n + 1)\over2} $$ which is \$Θ(n^2)\$.

To get the runtime down to \$O(n \log n)\$, you need to heapify just once, and then instead of extracting the maximum item by popping the list, swap the maximum item with the last item in the list, and then apply the "sift down" procedure to repair the heap condition in time \$O(\log n)\$.


Copying files into Dropbox folder from command line

Your script will be a lot easier to read if you expand the long statements to multiple lines:

@echo off
set dropbox=%userprofile%\dropbox
if exist %dropbox% (
    if not exist %dropbox%\%2 mkdir %dropbox%\%2
) else (
    echo Get Dropbox for PC before using this!
)
if exist %dropbox%\%2 copy %1 %dropbox%\%2
@echo on

Is that @echo on at the end necessary? Probably not, but I don't have a Windows with me to play around to verify.

The last if statement is pointless to execute if the first if statement was false. It would be better to move this inside the first if statement:

@echo off
set dropbox=%userprofile%\dropbox
if exist %dropbox% (
    if not exist %dropbox%\%2 mkdir %dropbox%\%2
    if exist %dropbox%\%2 copy %1 %dropbox%\%2
) else (
    echo Get Dropbox for PC before using this!
)

Possibly an even better way is to use the equivalent of an early return,
by leaving the main execution path when something is wrong.
You can do this using goto :eof.
After this the else statement can be flattened:

@echo off
set dropbox=%userprofile%\dropbox
if not exist %dropbox% (
    echo Get Dropbox for PC before using this!
    goto :eof
)
if not exist %dropbox%\%2 mkdir %dropbox%\%2
if exist %dropbox%\%2 copy %1 %dropbox%\%2

Rather than using the meaningless symbols %1 and %2 throughout the script,
it would be better to put these values to variables with descriptive names, for example:

@echo off
set source=%1
set target=%2
set dropbox=%userprofile%\dropbox
if exist %dropbox% (
    echo Get Dropbox for PC before using this!
    goto :eof
)
if not exist %dropbox%\%target% mkdir %dropbox%\%target%
if exist %dropbox%\%target% copy %source% %dropbox%\%target%


Point

Your Point class is immutable, which makes it thread safe. So, you have that right. The code style is very compact, and not very readable. I would prefer you to have it as:

final class Point {
    // Class Needs to be thread safe
    private final double x, y;

    public Point(double x0, double y0) {
        x = x0;
        y = y0;
    }

    public double x() {
        return x;
    }

    public double y() {
        return y;
    }

    public String toString() {
        return "(" + x + "," + y + ")";
    }
}

Synchronization

OK, I started off writing a bunch of stuff here, but it's all sort of moot.

You do not run any concurrent threads.... and, even if the threads were concurrent, you are not actually running multiple threads against the same instances... you are not testing anything....

For example, you have the synchronized add() method. That's great, but, your test loop is:

public void run() {
    synchronized(this) {
        for(int i=0;i<1;i++) {
            add(p);
        }
    }
    display();
}

Now, since you synchronize outside the add method (and outside the loop), there's no other thread that can call the add anyway.

Still, that's not a problem, because your main method does:

    for(int i=0;i<N;i++) {
        x = (Math.random()*N);
        y = (Math.random()*N);
        Point p = new Point(x,y);
        Thread cp = new CollectionPoint(p);
        cp.start();

        try {
            cp.join();
        } catch(InterruptedException e) {}

    }

So, you create N threads. Each thread gets its own instance of CollectionPoint, so, none of the threads are adding content to the same CollectionPoint, there's no problem there...

but, even that is moot, because you only ever have one thread running at any one time...

You start the thread, and join to it in the same loop, so you only run one test thread, wait for it to complete, then run the next thread, etc.

Bottom line is that your code is not tested in a meaningful way, there is no concurrency on any one instance, and the actual test you do ensures that no other thread can access the class anyway.

So, your basic question is: "Is my solution thread safe?". The answer is "Yes", because you never allow more than one thread to run at any one time.


Comparing run-length decoding algorithms

Elegance is a matter of taste, so you'll probably get different answers for that point. Personally, I find your solution easier to understand: it makes good use of the algebra defined through the rld type.

From an efficiency standpoint, your algorithm creates as Many values as the repetition count in the original one. That means that your algorithm will generate memory allocation. It will also have to match it again as many times through recursion, so there's a computational extra load as well. The solution proposed by the site is more efficient in that regard: it only allocates the necessary values to construct the resulting list, and only matches once each element of the input list.


It looks pretty good to me. With a cost of 100% on the FullTextMatch, I'd consider running this as a standard statement and hard code the variables just to see what the execution plan says.
I do have one question though. Your case statement for @ColumnName = 'DateAdded'... doesn't this throw an error when @ColumnName <> 'DateAdded' as you end up with something like:

order by P.LastName asc, desc


Java 8

Since you are on Java 8, you should consider using its stream-based processing feature to achieve what you need in a more expressive way.

First, you need a method that accepts a TreeEntry and gives you the desired Map object:

private Map<String, Object> extractDetails(TreeEntry file) {
    Map<String, Object> map = new HashMap<>();
    map.put("sha", file.getSha());
    map.put("path", file.getPath());
    map.put("name", GitHubHelper.getNameFromPath(file.getPath()));
    map.put("size", Objects.toString(file.getSize()));
    map.put("commits", GitHubHelper.getCommits(config, repo, file.getPath()));
    return map;
}

The idea here is to be able to use this as a method reference, e.g. ThisClass::extractDetails, for map()-ping the filter()-ed elements, before collect()-ing toList():

// Assuming fileList is a Collection implementation
List<Map<String, Object>> files = fileList.stream().filter(f -> "blob".equals(f.getType()))
                                            .map(ThisClass::extractDetails)
                                            .collect(Collectors.toList());

Double brace initialization

This StackOverflow question shows the pitfalls of using it. In short, yes, there will be a performance impact, and it doesn't end there. Due to the anonymous classes it creates, you may get an unusual number of compiled class files, and not to mention the small but significant gotchas surrounding class equivalence testing (potentially) and final classes.


Using Gibbs sampling to segment an image

Since this is homework, I won't give you the exact answer, but here are some hints.

== is overloaded in numpy to return an array when you pass in an array. So you can do things like this:

>>> numpy.arange(5) == 3
array([False, False, False,  True, False], dtype=bool)
>>> (numpy.arange(5) == 3) == False
array([ True,  True,  True, False,  True], dtype=bool)

You can use boolean arrays to assign to specific locations in an array. For example:

>>> mostly_true = (numpy.arange(5) == 3) == False
>>> empty = numpy.zeros(5)
>>> empty[mostly_true] = 5
>>> empty
array([ 5.,  5.,  5.,  0.,  5.])

You can also negate boolean arrays; together, these facts allow you to conditionally assign values to an array. (numpy.where can be used to do something similar.):

>>> empty[~mostly_true] = 1
>>> empty
array([ 5.,  5.,  5.,  1.,  5.])

You can then multiply those values by other values:

>>> empty * numpy.arange(5)
array([  0.,   5.,  10.,   3.,  20.])

And many different numpy functions (really ufuncs) provide a reduce method that applies the function along the entire array:

>>> results = empty * numpy.arange(5)
>>> numpy.multiply.reduce(results)
0.0

You should be able to completely eliminate that for loop using only the above techniques.


I don't have a C# compiler, but I think the 2nd version will be faster if you drop the i % 3 in the 2nd loop, let it sum all the multiple of 5, and then make another pass to remove the multiples of 15.
And since the summing of 3, 5, 15 are repetitive, I'd introduce a helper function, like this:

static int sumOfMultiples(int x, int limit)
{
    int sum = 0;
    for (int i = x; i < limit; i += x)
    {
        sum += i;
    }
    return sum;
}

Then in Main, you could write:

int max = 1000;
int sumNums = sumOfMultiples(3, max) + sumOfMultiples(5, max) - sumOfMultiples(15, max);

But of course, the suggestion of @VikasGupta in comments is the best,
to use pure math instead of looping, rewriting the helper as:

static int sumOfMultiples(int x, int limit)
{
    int n = (limit - 1) / x;
    return x * n * (n + 1) / 2;
}


Vectorizing a sequence \$x_{i+1} = f(x_i)\$ with NumPy

You can't vectorize this. Repeated application of \$x_i = \mu x_{i-1} (1-x_{i-1})\$ is chaotic.


This is generally nicely presented code, and it is good to read.
Your suspicions that the code is not as efficient as it could be, is correct. There's some simple things to fix, and some harder ones. First though, the sieve:
Sieve
A sieve of Eratosthenes is best implemented as an actual array. Your code uses a list as a type of queue. Let's look at this code here:

    while (!numbers.isEmpty()) {
        prime = numbers.get(0);
        primes.add(prime);

        for (int i = prime; i < limit; i += prime) {
            numbers.remove((Integer) (i));
        }
    }

That code takes the first number in the un-processed ones, and removes it, it's prime. That's fine, no problem, but.... Look at what numbers is:

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

It's an array list, so what the first loop through here does:

        for (int i = prime; i < limit; i += prime) {
            numbers.remove((Integer) (i));
        }

is essentially remove the item at position 0, which, for an array list, means every other item needs to be shuffled forward one spot. To remove the first item, you have also moved every other item.
Again, when you find the next multiples of the prime, you are shifting each larger value by 1 position as well.
This could result in a lot of shuffling..... a huge amount, in fact.
What's worse, though, is as you go through the multiples of the prime (for example, 7), you say:
remove(7);
remove(14);
....
remove(987); // (141 * 7)

When you say remove (987) you have to scan the entire list looking for that value.... so you scan all the early values, and shift all the later values.
The Sieve is traditionally implemented as a fixed, primitive array, of booleans:
boolean[] sieve = new boolean[1000];
Arrays.fill(sieve, true);

The above code initializes 1000 boolean members, and sets them all to true.
Now, with your sieve like that, you can simply:
for (int prime = 2; prime < sieve.length; prime++) {
    if (sieve[prime]) {
        // this is a prime number
        for (int notPrime = prime * 2; np < sieve.length; notPrime += prime) {
            sieve[notPrime] = false;
        }
    }
}

Now, you have removed all non-prime values by setting the index value to be false.
There are ways to make that faster, but, the important thing is there's no scanning for values, or shifting things either.
Reverse
Your reverse method converts things to a string, and reverses that. I would prefer an int-based system:
private static int reverse(int p) {
    int reverse = 0
    while (p != 0) {
        reverse *= 10;
        reverse += (p % 10);
        p /= 10;
    }
    return reverse;
}


Formatting seconds as hours:minutes:seconds

Bug
Handling a case of 0 minutes is a bit more involved. For example, giving 3601 as an input produces 1:1 instead of expected 1:00:01.

Trust your math
min and sec are guaranteed to be less than 60. There is no point to test for it.

Computing spaces
I recommend not to compute them explicitly. You know that the output should be right-aligned into the 7-character-wide field. An std::setw(7)  manipulator is specifically designed to do the job. Write your output to the string (or a stringstream), and
      std::cout << std::setw(7) << s << '\n';

will achieve the goal.


"Algorithmic Crush" problem hitting timeout errors

Constraints

  \$3 ≤ N ≤ 10^7\$
    \$1 ≤ M ≤ 2 \cdot 10^5\$
    \$1 ≤ a ≤ b ≤ N\$
    \$0 ≤ k ≤ 10^9\$

You should verify that every value you read from the user is a valid value in your program.

As far as complexity goes, a suffix tree with a complexity of \$O(N\log{}N)\$ compared to your current \$O(MN)\$ solution that adds difference to every value in the range \$[A,B]\$.  With \$N \sim 10^7\$, an \$O(N\log{}N)\$ solution may still be too slow.

For this problem, I would employ a max prefix sum scan on a difference array.  To generate a set of range differences, we adjust \$arr_{a} \mathrel{{+}{=}} k\$ and \$arr_{b+1} \mathrel{{-}{=}} k\$.  Going back to your sample data, your difference array would look like this:

         #   1.......................N...N+1
5 3      #   0     0     0     0     0     0
1 2 100  # 100     0  -100     0     0     0
2 5 100  # 100   100  -100     0     0  -100
3 4 100  # 100   100     0     0  -100  -100

To calculate the max prefix sum, accumulate the difference array to \$N\$ while taking the maximum accumulated prefix. (*) denotes new max found.

DiffArray  100  100    0    0  -100  -100
PrefixSum  100*
Max = 100

DiffArray  100  100    0    0  -100  -100
PrefixSum       200*
Max = 200

DiffArray  100  100    0    0  -100  -100
PrefixSum            200
Max = 200

DiffArray  100  100    0    0  -100  -100
PrefixSum                 200
Max = 200

DiffArray  100  100    0    0  -100  -100
PrefixSum                       100
Max = 200

Building a difference array in \$O(M)\$ and finding the max prefix sum in \$O(N)\$ results in a \$O(M+N)\$ linear algorithm.


A simple and safe implementation for strnstr (search for a substring in the first n characters of char array)

Design:  The str as an array and searched up to n is inconsistent with string like functions and strstr().  Rather than "the search is limited to the first n characters in the array", I'd also expect characters in str that follow a null character are not searched.   IMO, a design flaw.

Following review assumes str[i] == 0 has no special meaning.
Weak argument name str.  str is the address of an array and maybe not a string.  Calling a potential non-string str conveys the wrong idea.  Suggest src, etc.  When looking for sub-strings, I like needle and haystack.
As the C version does not change str contents, recommend making that const.  "The rationale for the first parameter is not to be const is that you may want to use the return value pointer to modify the array in that location." does not apply.  Just cast char * the return value.  Follow strstr()s tyle.

// From C library.
      char *strstr( const char *s1, const char *s2);

// Expected signatures: (spaced for clarity)
// C
      char *strnstr(const char *src, const char *substr, size_t n);
// C++
      char *strnstr(      char *src, const char *substr, size_t n);
const char *strnstr(const char *src, const char *substr, size_t n);

Using a name that is close to standard names is tricky.  C reserves name with certain prefixes, etc and so does *nix, etc.  Maybe use CP_strnstr() and an optional #define strnstr CP_strnstr.
Corner case: Returning str with if(0 == substr_len) return str; does not make sense when size == 0.  I'd expect NULL.
Underflow possible.  The length of the needle may be longer or shorter than the haystack

// add check
if (n + 1 < substr_len) {
  return NULL;
}
pEnd -= (substr_len - 1);

Minor

In debug mode, consider testing against NULL

char *strnstr(char *str, const char *substr, size_t n) {
  assert(str || n == 0);
  assert(substr);


How to refactor common methods that depend on local variables into a base class

Here are some tips:

1) Turn Model into a constructor that accepts an object as the default values.

Note: Constructors should start with a capital letter.
Code:

// Model
function Model(defaultValues) {
    this.values = defaultValues || {};
}

Usage:

var modelFoo = new Model({
    type : 'foo',
    prop1 : '',
    prop2 : ''
});
console.log( modelFoo.values.type === "foo" );  // true

2) For readability, set the value of module.exports at the end of the file.

Assuming Foo and Bar are in the same file you can export both of them like so.

Code:

module.exports = {
    "Foo" : Foo,
    "Bar" : Bar
};

3) Since Model is a constructor, you can access the interval values by using this and attach functions to it by using prototype.

Also, returning this gives access to the current object instance.

Old Code:

model.init = function (val) {
    _.extend(values, val);
    return model;
}

model.store = function (cb) {
    db.insert(values.type, values, cb);
}

New Code:

Model.prototype.init = function (val) {
    this.values = _.extend(this.values, val);
    return this;
};
Model.prototype.store = function (cb) {
    db.insert(this.values.type, this.values, cb);
    return this;
};

4) Make sure that you define db in the module.

Code:

var db = require("db").db;

5) Create a generic setter and getter function for the properties.

Old Code:

model.prop1 = function (val) {
    if (!arguments.length)
        return values.prop1;
    values.prop1 = val;
    return model;
}

New Code:

Model.prototype.createPropSetterAndGetter = function (propName) {
    this[propName] = (function () {
        return function (val) {
            if (!arguments.length) {
                return this.values[propName];
            }
            this.values[propName] = val;
        };
    }());
};

Usage:

var modelBar = new Model({
    type : 'bar',
    prop3 : '',
    prop4 : ''
});
console.log( typeof modelBar.prop3 === "undefined" ); // true
modelBar.createPropSetterAndGetter("prop3");
console.log( modelBar.prop3() === "" ); // true
modelBar.prop3( "PAY ME!" );
console.log( modelBar.prop3() === "PAY ME!" ); //true and hurry.

Final Result:

var db = require("db").db;

// Model
function Model(defaultValues) {
    this.values = defaultValues || {};
}
Model.prototype.init = function (val) {
    this.values = _.extend(this.values, val);
    return this;
};
Model.prototype.store = function (cb) {
    db.insert(this.values.type, this.values, cb);
    return this;
};
Model.prototype.createPropSetterAndGetter = function (propName) {
    this[propName] = (function () {
        return function (val) {
            if (!arguments.length) {
                return this.values[propName];
            }
            this.values[propName] = val;
        };
    })();
};
// Foo
var Foo = function () {
    var modelFoo = new Model({
            type : 'foo',
            prop1 : '',
            prop2 : ''
        });
    modelFoo.createPropSetterAndGetter("prop1");
    return modelFoo;
};
// Bar
var Bar = function () {
    var modelBar = new Model({
            type : 'bar',
            prop3 : '',
            prop4 : ''
        });
    modelBar.createPropSetterAndGetter("prop3");
    return modelBar;
};

module.exports = {
    "Foo" : Foo,
    "Bar" : Bar
};


You iterate through the whole Map, which is O(n) and therefore slow as hell. Worse, you even recreate every element and put it into another element, which is even slower.

Why not just do:

scala> val map = Map(1 -> Set(5,3), 2 -> Set(7,3))
map: scala.collection.immutable.Map[Int,scala.collection.immutable.Set[Int]] = Map(1 -> Set(5, 3), 2 -> Set(7, 3))

scala> def updateMap[A, B](map: Map[A, Set[B]], key: A, value: B) =
         map + ((key, map.getOrElse(key, Set()) + value))
updateMap: [A, B](map: Map[A,Set[B]], key: A, value: B)scala.collection.immutable.Map[A,Set[B]]

scala> updateMap(map, 1, 9)
res0: scala.collection.immutable.Map[Int,Set[Int]] = Map(1 -> Set(5, 3, 9), 2 -> Set(7, 3))

And you probably want to introduce another type parameter B to the signature of updateMap to allow values of a different type than the one of the key.


Usual comment: add """docstrings""" to public methods at the very least.

Avoid double (and triple) lookups.  Python has fast exception handling.  Instead of testing for existence, and then fetching the value, just fetch the value.  And don’t fetch it more than once.  Ie, replace this:

if key in self.dict:
    val = self.dict[key].val
    self.list.delete(self.dict[key])
    self._insert(key, val)
    return val
else:
    return -1

with this:

try:
    node = self.dict[key]
    val = node.val
    self.list.delete(node)
    self._insert(key, val)
    return val
except KeyError:
    return -1

Above, you are deleting/discarding a ListNode containing a key-value pair, and then immediately creating a new ListNode with the same key-value pair to insert.  LinkedList.insert() takes the trouble to clean the node for insertion; why not reuse the node?  You wouldn’t have to update self.dict[key], either.

Similar optimizations for put():  don’t do double lookups and possibly reuse node (but with updated .val).


Conditional parsing, non-standard approach

A few comments:

bool nectar_loader::resolve_conditional( const std::function<bool(const string&)> &config_contains )

I'd generally prefer to turn this into a template, and pass the correct function type (and if I used std::function at all, use it only internally to store something):

template <class func>
bool nextar_loader::resolve_conditional(func &config_contains) {

    bool result = true;
    // My very own recursive implementation
    /*
      - each set of parenthesis is handled recursively
      - logical AND: +
      - logical OR:  |
      - logical NOT: !
      - two bools: "result" and "current"
      - "result" keeps global result, and is modified by "+"
      - "current" keeps results for "|" and "!"
      - syntax checking for invalid
    */

I'd prefer to move the block comment to just above the function header. I'd also prefer more descriptive names than result and current. Given their use, I'd consider names more like "expression_value" and "subexpression_value".

    bool previous_was_operator = true;
    bool current = false; // keep track of current state

This comment seems to add nothing to our understanding of the code. I'd consider something more like: "// Assume current sub-expression is invalid until parsed." (assuming that's really why you've initialized it to false).

    string token;
    while( next_token(token) )
    {
        conditional_operator op;
        if( map_value(conditional_operator_map, token, op) )
        {
            if( previous_was_operator )
            {
                if( op == conditional_operator::not_op )
                    current ^= current; // negate next

Again, the comment seems to do little to assist understanding of the code. I'd probably start by pointing out that an expression like a op1 op2 b is valid if and only if op2 is a unary operator (of which this grammar apparently only supports one).

                    case conditional_operator::plus_op:
                        result = result && current; // "current" -> "result"

Given that you're using it as an and, I'd name this conditional_operator::and_op (or something similar). Then name should reflect the logical meaning of the operator, not the fact that it happens to be (mis-)represented with the + character.

                        if( !result ) // negative when an element of a "+" expression
                        current = false; // reset "current"

This if statement appears redundant (at least to me). You've just set result to the logical and of current and result, so it will be true if and only if both inputs were already true.

result = current = (current && result);

So, both end up true if and only if both started out true. If either started out false, both end up false.

                        break;
                    case conditional_operator::or_op: // combine with "current"

                    case conditional_operator::not_op: // unreachable
                        throw runtime_error( "Internal logic error in nectar_loader::resolve_conditional" );

This looks rather like a bug. Did you really intend that or_op would throw an exception as unreachable, or should there be a break after the or_op case?


I actually just started learning asyncio a couple days ago, so I won't be able to comment too deeply. I do see a few things though:

Disregarding asyncio for a sec, I think google could be set up better. You have the base case of the recursion as n == 100, and are incrementing n in each recursive call. To easily allow the caller to decide how many time to run, I'd reverse how n is being handled. I would decrement it each call, and set the base case as n <= 0. With how you have it now, say the caller wanted it to run 1000 times, they would need to call it as

google(-900)

which is a little wonky. I'd change the first bit to:

async def google(n):
    if n <= 0:
        return None

    await s.add_task(google, n=n - 1)

. . .

I'm not sure recursion is the cleanest tool for the job here. I'm also not sure entirely why you're using a job queue or why you're using a elaborate class here unless the goal is to be able to handle jobs being added at a later time.

If your goal is just to initiate many requests and wait on them at the same time, you could just gather them:

import aiohttp
import asyncio as a

# google no longer cares about how many times it runs
# That is arguably beyond the responsibilities of a function intended to make requests
async def google():
    async with aiohttp.ClientSession() as session:
        async with session.get('http://h...content-available-to-author-only...n.org/get') as resp:
            print(resp.status)

async def start_requests(n_requests: int):
    routines = [google() for _ in range(n_requests)]  # Create a list of reqeust-making coroutines
    await a.gather(*routines)  # Unpack the routines into gather (since gather is var-arg)

Also, instead of doing timing using a single attempt and plain subtraction, it would be more accurate to use timeit:

from timeit import timeit

print("t:", timeit(lambda: a.run(start_requests(10)), number=20))  # number is the amount of tests to do

I'm assuming there's no issue using timeit for async code.


Try some features, typically available from functional languages. For example, functions that is first class values.

local operators = {
    ["+"] = function(x,y) return x+y end,
    ["-"] = function(x,y) return x-y end,
    ["*"] = function(x,y) return x*y end,
    ["/"] = function(x,y) return x/y end
}

local function default()
    print "No such operator"
end

print("Choose numbers:")
print("Num1:")
local num1 = io.read()
print("num2:")
local num2 = io.read()
print("Choose operator: + / - / * / /")

local func = operators[io.read()] or default
print(func(num1,num2))

io.read()


A couple of things I noticed:

Here:

while (std::cout << "Please enter the third term in the series: " && !(std::cin >> thirdTerm)) {
    std::cin.clear(); //clear bad input flag
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
    std::cout << "Invalid input; please re-enter.\n";
}

Aside from the prompt string this is repeated three times.  This would be better if it was in a separate function that accepted the prompt string and the address of the variable to store the input value:

void GetInput(string prompt, int& input)
{
    while (std::cout << prompt && !(std::cin >> input))
    {
        std::cin.clear(); //clear bad input flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //discard input
        std::cout << "Invalid input; please re-enter.\n";
    }
}

GetInput("Please enter the third term in the series: ",thirdTerm);
GetInput("Enter the third from the last term in the series: ",thirdLastterm);
GetInput("Please enter the sum of the series: ",sum);

Here:

    do {
        total = 0;
        vSeries.push_back(thirdTerm + (a * constantNumber));
        a++;
        for (int i = 0; i < vSeries.size(); i++) {
            total += vSeries[i];
        }
    } while (total < sum);

You're iterating through the vector getting a new total.  It would be better to just add each element to a running total:

    total = 0;
    do {
        int temp = thirdTerm + (a * constantNumber);
        vSeries.push_back(temp);
        total += temp;
        a++;
    } while (total < sum);


There isn't anything majorly wrong, so these will be mostly minor things.

getMethods doesn't really get methods, isMethod (or isBindable) is a more descriptive name for it.

You'd also want to check that .call is in fact the .call inherited from Function
prototype, or since you are doing the filtering in preparation for .bind, just
check that obj[key].bind === Function.prototype.bind or similar. Also check for truthiness, so you don't try to access null.bind:

return obj[key] && obj[key].bind ===

If Name is a normal function, it shouldn't be capitalized and be a named like a noun,
this is convention for functions that are meant to be invoked as constructors using new.
Something like makeName or makeNamespace, a verb that implies a factory, would
be a better fit.


Atbash Cipher in Rust - Exercism exercise

// "Encipher" with the Atbash cipher.
pub fn encode(plain: &str) -> String {
    let mut coded: String = plain.to_string();

    coded.retain(|c| c.is_ascii_alphanumeric());
    coded.make_ascii_lowercase();

    let coded_no_spacing = String::from_utf8(
        coded
            .bytes()
            .map(|c| {
                if c.is_ascii_alphabetic() {
                    122 - c + 97

You can b'z' and b'a' to refer to the ascii codes of the letters.

                } else {
                    c
                }
            })
            .collect(),
    )
    .unwrap();

    spacer(coded_no_spacing)
}

You are mixing two different approaches here. Firstly, you make a string out of the input and then modify it. Secondly, you use an iterator over the bytes of the string. This code would be more straightforward if you just iterated over the letters.

Here is my approach:

plain
    .chars()
    .filter_map(|c| {
        if c.is_ascii_alphabetic() {
            let letter = c.to_ascii_lowercase() as u8;
            Some(char::from(b'z' - letter + b'a'))
        } else if c.is_ascii_alphanumeric() {
            Some(c)
        } else {
            None
        }
    })
    .collect()

If you haven't seen it before, the filter_map function combines filtering and mapping. The closure can return either None, to remove the element or Some(x) to provide an element in the output.

/// "Decipher" with the Atbash cipher.
pub fn decode(cipher: &str) -> String {
    let mut out = encode(cipher);
    out.retain(|c| c.is_ascii_alphanumeric());
    out
}

It took me a bit to figure out why you were filtering the chars again. But I see it is remove the spacing. It would make more sense to split the basic ciphering and into its own function so you can call that without adding the spacing. Then you wouldn't have to filter it.

fn spacer(coded_no_spacing: String) -> String {
    let mut coded_no_spacing = coded_no_spacing.chars();

    let mut temp_char = coded_no_spacing.next();
    let mut counter = 0;
    let mut coded_with_spaces = "".to_string();

I would use String::new() to create an empty string. For "extra credit", you could use String::with_capacity to reserve the correct amount of space for the string, something like:

String::with_capacity(coded_no_spacing.len() + coded_no_spacing.len() / 5);

That's dubiously worthwhile, but sometimes it can be a helpful optimization.

Onwards:

    while temp_char.is_some() {

Firstly, there is a construct you can use when you want to iterate as long as something return Some instead of None.

while let Some(temp_char) = coded_no_spacing.next()

But in this case, this is just iterating over for the chars, so you should use a forloop

for temp_char in coded_no_spacing.chars()

        if counter % 5 == 0 && counter != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(temp_char.unwrap());
        temp_char = coded_no_spacing.next();
        counter += 1;

Instead of counting, use the enumerate() method on iterator. It will give you an index.

    }
    coded_with_spaces
}

Here is my version:

fn spacer(coded_no_spacing: &str) -> String {
    let mut coded_with_spaces = String::new();

    for (index, char) in coded_no_spacing.chars().enumerate() {
        if index % 5 == 0 && index != 0 {
            coded_with_spaces.push(' ');
        }
        coded_with_spaces.push(char);
    }

    coded_with_spaces
}


It seems to me that it would be better if the User struct knew how to initialize itself, by putting the initialization code into a constructor.

So, your header would be something like this:

struct User
{
    User();
private:
    GetOSVersion();
    std::string Username;
    std::string PCName;
    std::string OSVersion;
};

...and the implementation (.cpp, or whatever) file something like this:

std::string
User::GetOSVersion() {
    // code from GetOSVersion here
}

User::User() {
    // code similar to body of InitUser goes here
}

Since you didn't seem to be using the ID member of User, I removed it. Since the information isn't all about the user, but includes the OS version and such, it would probably be better to rename User to something more like SystemInformation.

I'd also prefer to do initialization as initialization, so this:

OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

...would be implemented more like:

OSVERSIONINFOEX osvi = { 0 };

...or (if you can use C++11):

OSVESIONINFOEX osvi {};

I'd also probably add a stream insertion operator for the class (whatever you end up naming it), using code something like this (inside the class definition):

friend std::ostream &operator<<(std::ostream &os, User const &u) {
    return os << u.Username << " " << u.PCName << " " << u.OSVersion;
}

Finally, if you're going to do OS version information, you probably want to support more  than the two OS versions you have right now. Given that there are lots of other ways to get this information, and all of them do a better job than this, nearly the only reasonable choices seem to me to be either expand coverage substantially to the point that it's at least somewhat useful, or else remove it completely.


Add method to Ruby's Enumerable module that produces every nth element

nth slicing

Perhaps you could use a slice with map instead.

module Enumerable
  def nth(n)
    self.each_slice(n).select{|c| c.length == n}.map(&:last)
  end
end

unit tests

print [2, 4, 6, 8, 10, 12].nth(3) # => [6, 12]
print "\n"
print [2, 4, 6, 8, 10].nth(3) # => [6]
print "\n"
print [2, 4, 6, 8].nth(3) # => [6]
print "\n"
print [2, 4, 6].nth(3) # => [6]
print "\n"
print [2, 4].nth(3) # => []
print "\n"

Rubocop Report

Skipping an iteration should be done like this..

 next unless i == relevant_iteration

    ordinal += 1
    relevant_iteration = ordinal * n

rather than..

if i == relevant_iteration
  ordinal += 1
  relevant_iteration = ordinal * n

General Guidelines:

use 2 spaces for indentation
frozen string
n as parameter name: min length should be 3 -> takeIndex instead?

Refactored

# frozen_string_literal: true

module Enumerable
  def nth(takeIndex)
    i = 0
    ordinal = 1
    relevant_iteration = takeIndex * ordinal

    self.select do |num|
      i += 1

      next unless i == relevant_iteration

      ordinal += 1
      relevant_iteration = ordinal * takeIndex

      num
    end
  end
end


Improving performance of a subroutine that checks for a vacancy in a lattice

Three thoughts about this.

First is unless the lattice is small you won't actually run into a boundary condition most times. Check if a boundary condition is possible once and have two CheckForVacancy functions one with and one without boundary checks.

Second thought is remove the boundary check altogether by adding duplicate elements.  In one dimension if you had the following

Index:1,2,3,4,5
Value:3,4,3,2,1

Make the array

Index:0,1,2,3,4,5,6
Value:1,3,4,3,2,1,3

So you trade extra storage to remove the bounds checks.

Finally, you still have a lot of no_ops in the for loop. All those add zero statements do nothing.  You could unroll the loop to eliminate them at the expense of more code. You removed the 0,0,0 option already I think.

Your comment indicates that the lattice gets modified during execution, that makes removing the bounds check more complex.

Depending on the size of the lattice and the number of times you call CheckForVacancy for an individual cell you could either memoize the cells adjacent to a cell or pre-compute them.  This would work if you have enough memory and if you call the function with the same values multiple times.


Converting Pandoc Markdown images from captioned to inline

How about a regular expression?

def convert(s):
  return re.sub(r"((?:\A|^ *\n)!\[.*\]\(.*\))\n(^ *\n|\Z)", r"\1\\\2", s, 0, re.M)

def test1():
  print convert("""![foo](bar)\n\nthis is a test\n""")

def test2():
  print convert("""line 1\n\n![foo](asd)\n\nanother test\n""")

def test3():
  print convert("""line 1\n\n![foo](asd)\n""")

def test4():
  print convert("""line 1\n\n![foo](asd)\nNot blank\n""")

Note: I am using ^\s*\n to match a blank line - i.e. it can also contain spaces.


Speeding up a length calculation for a QGIS plugin

I'm not familiar with the libraries in question, but it seems to me that you could take a couple of things out from the for loop:

The if condition does not look like it would change between iterations.
As changeAttributeValues takes a dictionary argument, I would expect it to handle a dictionary with multiple keys as well. Construct a dict with all fid : attrs pairs in the loop and make just one function call after.

My proposal:

def calculatelength(self):
    idx = self.resLayer.fieldNameIndex('Longueur')
    caps = self.resLayer.dataProvider().capabilities()
    if caps & QgsVectorDataProvider.ChangeAttributeValues:
        features = self.resLayer.getFeatures()
        feature_attrs = {}
        for feature in features:
            fid = feature.id()
            flen = feature.geometry().length()
            feature_attrs[fid] = {idx : flen}
        self.resLayer.dataProvider().changeAttributeValues(feature_attrs)


There’s no need for recursion here.  You have some base probability map, and you want to rotate it such that the maximum element points in some particular direction.  You could implement that fairly simply:

var INDICES = [1, 2, 3, 6, 9, 8, 7, 4];
var PROBABILITIES = [80, 60, 30, 20, 10, 20, 30, 60];

function generateProbabilities(lastNumpadDirection) {
    var lastIndexDirection = INDICES.indexOf(lastNumpadDirection);
    var shifted = PROBABILITIES.slice(PROBABILITIES.length - lastIndexDirection)
        .concat(PROBABILITIES.slice(0, PROBABILITIES.length - lastIndexDirection));
    var result = {};
    for(var i = 0, l = INDICES.length; i < l; i++) {
        result[INDICES[i]] = shifted[i];
    }
    return result;
}

Much of the complexity here comes from needing to deal with directions represented as arrows on the numpad–here, I convert them to 45-degree-offsets going clockwise from northwest, shift the probabilities array, and then convert back to your desired numpad format. Illustrated:


Performance testing.

Please note this answer is about performance not complexity.

Why the strange performance result?

The reason for the different results is down to poor testing.

JavaScript unlike most languages is never fully compiled. In the background there are multi level optimization engines that look at the running code and apply optimizations as the code is running.

The optimizer however has a penalty that is most evident when the code is first run. It can also optimize some code quicker than others.

To compare functions you need to let the optimizer do its thing (each browser have very different optimizing methods). Only after the function has been run several times can you start to get accurate results.

When I tested your code I found that the "backtracking" method was on average less than 5% slower.

Testing example

The snippet is a down and dirty performance tester that will test functions over many cycles and give a mean result of the function time.

Note that the result is not of a single call but that of many calls in a row. The tester will first make sure that the tests are not below the timer resolution before starting.

As an example I have kept the total test cycles low, but the numbers are still not stable and would take some more time before the optimizer is happy.

Included are your two functions as in the question, and alternative method using no recursive calls and a modification of one of your functions.

Performance increase.

In you function

function combinations(n, k) {
    let result= [];

  function recurse(start, combos) {
    if(combos.length === k) {
      return result.push(combos.slice());
    }
    if(combos.length + (n - start + 1) < k){
      return;
    }
    recurse(start + 1, combos);
    combos.push(start);
    recurse(start + 1, combos);
    combos.pop();
  }

  recurse(1, []);
  return result;
}

The combos array is being passed as an argument. There is no need to as it is the same array. Declare it outside the recurse function.

You are returning the array in one path and the other two your return undefined. Keep the return types the same.

You are recursing and then test for combos.length === k but you can test before the call saving the need to call.

There seams to be a slight favor for an arrow function, so changed the recurse function to such.

The modified function is consistently the quickest.

function combinationsAV2(n, k) {
  const result= [];
  const combos = [];
  const recurse = start => {
    if (combos.length + (n - start + 1) < k) { return }
    recurse(start + 1);
    combos.push(start);
    if(combos.length === k) {
       result.push(combos.slice());
    }else if(combos.length + (n - start + 2) >= k){
       recurse(start + 1);
    }
    combos.pop();
  }
  recurse(1, combos);
  return result;
}

Testing example

Note that the timing is adjusted to ensure good time resolution. The results are meaningless as absolute performance figures. They only have comparative meaning within a test run.

//n!/(r!(n-r)!)
Math.factorials = [1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000];

Math.biCof = (n,r) => Math.factorials[n] / (Math.factorials[r] * Math.factorials[n-r]);

function combinationsG(n, k) {
    const result= [];
    const combo= [];
    const last = k - 1;  // points to last item in combo
    var i = k;
    while (i--) {
        combo.push(k - i);
    }
    const starts = [...combo];
    var pos,count = Math.biCof(n,k)
    while (count --) {
        result.push([...combo]);
        combo[last] += 1;
        if (combo[last] > n) {
            pos = 0;
            while (combo[last - pos] > n-pos) {
                pos += 1;
                combo[last-pos] += 1;
                if (pos === k) { break }
            }
            while (pos > 0) {
                combo[last-pos+1] = combo[last-pos] + 1
                pos --;
            }
        }
    }
    return result;
}

function combinationsAV2(n, k) {
  const result= [];
  const combos = [];
  const recurse = start => {
    if(combos.length + (n - start + 1) < k){
      return;
    }
    recurse(start + 1);
    combos.push(start);
    if(combos.length === k) {
       result.push(combos.slice());
    }else if(combos.length + (n - start + 2) >= k){
       recurse(start + 1);
    }
    combos.pop();
  }
  recurse(1, combos);
  return result;
}

function combinationsA(n, k) {
    let result= [];

  function recurse(start, combos) {
    if(combos.length === k) {

      return result.push(combos.slice());
    }

    if(combos.length + (n - start + 1) < k){
      return;
    }
    recurse(start + 1, combos);
    combos.push(start);
    recurse(start + 1, combos);
    combos.pop();
  }
  recurse(1, []);
  return result;
}

//backtracking method
function combinationsB(n, k) {
  let result = [];
  let stack = [];
  function combine(currentNumber){
    if(stack.length === k) {
      let newCombo = stack.slice();
      result.push(newCombo);
      return;
    }
    if(currentNumber > n) {
      return;
    }

    stack.push(currentNumber);
    combine(currentNumber + 1);
    stack.pop();
    combine(currentNumber + 1);
  }
  combine(1);
  return result;

}

/*===========UTIL to display results============*/
function log(data) {
     const div = document.createElement("div");
     div.textContent = data;
     logger.appendChild(div);
}
log.clear = function(){ logger.innerHTML = "" }

/*================TESTING CODE==================*/
const tests = {
    data : [15,3],  // arguments for function calls
    functions : [ {  // functions to test and a name as reference
            name : "Backtracking method",
            func : combinationsB,
        },{
            name : "Native Combinations",
            func : combinationsA,
        },{
            name : "Modified Native",
            func : combinationsAV2,
        },{
            name : "While loops",
            func : combinationsG,
        },
    ],
    cycles : 100,
    prepCycles : 30, // Number of cycles to run before testing. This
                     // is a optimizer shake down and use to ensure test times
                     // are above the timerResolution
    testPerCycle : 20,
    timedCycleTrim : 1,  // used to increase runtime if time to low
    timedCycles : 2,  // number of calls to test function * timedCycleTrim
    timerResolution : 0.4, // this is the minimum resolution of the timer in ms
                           // Note that due to security concerns performance timers
                           // have had the time resolution reduced to stop
                           // code attempting to access CPU caches
    testInterval : 10, // Time between test cycles.
    resolutionError : false, // If the run time of the timedCycles is lower than
                             // the timer resolution then the accumulating error
                             // makes results meaningless. This flag is set true
                             // when test time is too small. In the prep phase
                             // timedCycleTrim is used to increase the time
                             // till a time above timerResolution is found

}

log.clear()
startTest(tests);

function startTest(tests){

    function doCycle(test){
        var totalTime, count, time, j, i;
        const data = tests.data;
        i = tests.testPerCycle;
        totalTime = count = 0;

        while (i--) {
            j = tests.timedCycles * tests.timedCycleTrim;

            /* ========= TEST LOOP ==========*/
            const now = performance.now();
            while (j --) { test.func(...data) }
            time =  performance.now() - now;

            if (time <= tests.timerResolution) {
                tests.resolutionError = true;
                return;
            }
            count ++;
            totalTime += time;
        }
        test.count += count;
        test.time += totalTime;
        test.mean = test.time / test.count;

    }
    function resetTest(test){
        test.count = 0;
        test.time = 0;
    }
    function showTestStatus(test) {
        if (test.count) {
            log(`Test '${test.name}' mean ${test.mean.toLocaleString(undefined,numFormat)}ms`);
           // log(`Total ${test.time.toLocaleString(undefined,numFormat)}ms over ${test.count} cycles`);
        } else {
            log(`Test '${test.name}' not yet tested`);
        }
    }
    function eachTest(call,testArr = tests.functions){
        testArr.forEach(call)
    }
    const selectors = {
        index : 0,
        random() { return tests.functions[Math.random() * tests.functions.length | 0] },
        ordered() { return tests.functions[(selectors.index++) % tests.functions.length ] },
    }
    function setupPrep() {
        selectors.index = 0;
        cycles = tests.prepCycles * tests.functions.length;
        selector = selectors.ordered;
        prepPhase = true;
        tests.resolutionError = false;
        eachTest(resetTest);
        setTimeout(doNextCycle, tests.testInterval);
    }

    function doNextCycle() {
        const test = selector();
        doCycle(test)
        cycles --;
        if (tests.resolutionError) {
            if (prepPhase) {
                if (tests.timedCycleTrim  === 100) {
                    log(`Test '${test.name}' is not responding to cycle trim. Test aborted` );
                } else {
                    tests.timedCycleTrim += 2;
                    log(`Timed cycles increased to : ${tests.timedCycles * tests.timedCycleTrim}` );
                    setupPrep();
                }
            } else {
                log(`'${test.name}' failed, function runtime too low. Test aborted.` );
            }
        } else {
            if (cycles) {
                if (!prepPhase) {
                    log.clear();
                    log(`Test status ${cycles / (tests.cycles * tests.functions.length) * 100 | 0}%`);
                    eachTest(showTestStatus);
                }
                setTimeout(doNextCycle, tests.testInterval);
            } else if (!prepPhase) {
                log.clear();
                log("Testing complete...");
                log("Calls per cycles : " + tests.timedCycles * tests.timedCycleTrim);
                log("----------------------------------------");
                eachTest(showTestStatus,[...tests.functions].sort((a, b) => a.mean - b.mean));
            } else {
                log("Prep complete...")
                prepPhase = false;
                cycles = tests.cycles * tests.functions.length;
                selector = selectors.random;
                eachTest(resetTest);
                setTimeout(doNextCycle, tests.testInterval);
            }
        }
    }
    const numFormat = {minimumFractionDigits: 3, maximumFractionDigits: 3};
    var cycles, selector, prepPhase;
    log("Starting tests. Calibrating run times... ");
    setupPrep();
}


just some minor things...

private boolean inBounds(int row, int col)
{
    if(row < 0 || row >= maxRow || col < 0 || col >= maxCol)
        return false;
    else
        return true;
}

could be more clear if you directly return the value

private boolean inBounds(int row, int col)
{
    return (row >= 0 && row < maxRow && col >= 0 && col < maxCol)
}

the same matters for isAlive()

public boolean isAlive(int row, int col)
{
    return inBounds(row, col) && board[row][col];
}

another thing is the name of the variable maxRows and maxColumns is not exactly what they are, i would use the simple forms for them rows and columns since they are rows and columns...

that would not even make conflicts for your iterations for(int row = 0; row < rows; row++)...

remove your whitespace, that makes reading easier...


Recursive Fibonacci in Rust with memoization

There's no reason to ascribe a type to memo.
Don't expose the memoization logic outside the call. Instead, create a shim function that creates the memoization vector for you.
You can then define the memoized function inside the shim function, preventing people from accidentally calling it.
Since the memo variable isn't used after the top-most recursive call, you can just pass in the reference directly, without creating a variable.
As mentioned in the comments, the map(|x| x) call is not needed here.
Write some kind of automated tests.

fn fib(number: usize) -> usize {
    fn fib_memo(n: usize, memo: &mut [Option<usize>]) -> usize {
        memo[n].unwrap_or_else(|| {
            let result = {
                if n > 1 {
                    fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
                } else {
                    1
                }
            };
            memo[n] = Some(result);
            result
        })
    }

    fib_memo(number, &mut vec![None; number + 1])
}

fn main() {
    let number = 46;
    let r = fib(number);
    println!("{}", r);
    assert_eq!(2971215073, r);
}

That being said, I'd point out that this memoized version of Fibonacci is not the most efficient — you don't need to keep every previous value forever. Instead, check out numerous ways of being more efficient:

Implement a generic Fibonacci sequence in Rust without using Copy trait
How to swap two variables?
How to avoid excessive cloning in Rust?
Is it possible to use a fold with a Vec?

One possible implementation of that:

fn fib(n: usize) -> usize {
    fn fib_memo(n: usize, memo: &mut [usize; 2]) -> usize {
        let [a, b] = *memo;
        let c = a + b;
        if n == 0 {
            c
        } else {
            *memo = [b, c];
            fib_memo(n - 1, memo)
        }
    }

    if n < 2 {
        1
    } else {
        fib_memo(n - 2, &mut [1, 1])
    }
}

Or a non-recursive variant:

fn fib(n: usize) -> usize {
    if n < 2 {
        1
    } else {
        let mut memo = [1, 1];
        let mut n = n - 2;

        loop {
            let [a, b] = memo;
            let c = a + b;

            if n == 0 {
                return c;
            }

            memo = [b, c];
            n -= 1;
        }
    }
}


Class for working with users and passwords in a PHP CMS

New code (optimizations/simplifications, see comments in code for explanations):

class Users {
    private static $key, $table, $logtable;

    public static function init($key) {
        self::$key = $key;
        self::$table = DBPREFIX.$key.'s';
        self::$logtable = self::$table.'_access_log';
    }

    public static function isLogged() {
        if(isset($_SESSION[self::$key]) and isset($_SESSION[self::$key]['uid'])) { # Combined ifs
            $uid = intval($_SESSION[self::$key]['uid']);
            $user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
            return count($user) > 0; # Simplified
        }
        return false; # Removed unnecesary elses
    }

    public static function userExist($login) {
        $user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
        return count($user) > 0; # Simplified
    }

    public static function getUser($login) {
        $user = DB::select()->from(self::$table)->where('login', '=', $login)->execute()->object();
        if(count($user) > 0) {
            return $user[0];
        }
        return false; # Removed unnecessary else
    }

    public static function generateHash($password) {
        $salt = self::generateSalt();
        $hashedPassword = crypt($password, $salt);
        return array('hashed_password' => $hashedPassword, 'salt' => $salt);
    }

    private static function generateSalt($blowfishPre = '$2y$10$', $blowfishEnd = '$', $allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./', $saltLength = 20) { # Added arguments for future customization
        $charsLength = strlen($allowedChars);
        $salt = "";
        for($i=0; $i < $saltLength; $i++)
        {
            $salt .= $allowedChars[mt_rand(0,$charsLength)];
        }
        return $blowfishPre . $salt . $blowfishEnd; # Removed unnecessary variable
    }

    public static function comparePasswords($input, $uid) {
        $user = DB::select()->from(self::$table)->where('id', '=', $uid)->execute()->object();
        if(count($user) > 0) {
            $user = $user[0];
            $password = $user->password;
            return crypt($input, $password) === $password;
        }
        return false; # Removed unnecessary else
    }

    public static function userExit() {
        if(isset($_SESSION[self::$key])) {
            unset($_SESSION[self::$key]);
        }
    }

    public static function changePassword($password, $uid) {
        $newPassword = self::generateHash($password);
        if(isset($newPassword['hashed_password']) && isset($newPassword['salt'])) {
            DB::update(self::$table)->set(array('password' => $newPassword['hashed_password'], 'salt' => $newPassword['salt']))->where('id', '=', $uid)->execute();
        }
    }

    public static function updateTime($uid) {
        DB::update(self::$table)->set(array('last_login' => time()))->where('id', '=', $uid)->execute();
    }

    public static function writeAccessLog($uid, $success) {
        DB::insert(self::$logtable)->set(array('admin_id' => $uid, 'date' => time(), 'success' => $success ? '1' : '0'))->execute(); # Inlined success var.
    }
}


Edit button toggles modal and load data from PHP using AJAX and JQUERY

Welcome to Code Review! Hopefully you enjoy using this site and receive valuable feedback.

Wow, what patience you have to type out/copy all of those lines to update the form inputs. Instead of doing that, you could loop through the input fields and check if the name matches a key in the returned data. One can use .each() to iterate over the input fields, then check the name using .attr() and the in operator.

$('#updateEmpForm input').each(function() {
    const inputName = $(this).attr('name');
    if (inputName in data) {
        $(this).val(data[key]);
    }
});

To exclude certain fields, like any password inputs, the selector could be updated to include pseudo-class selectors like `:not() - for example:

$('#updateEmpForm input:not([type="password"])').each(function() {

That should handle all but the last repeated line - which can be included before or after the call to .each():

$("#updateEmpForm input[name='edit']").val(data.ID);

You could also define a mapping of input names to keys and look in the mapping for values. For example:

const inputNameKeyMapping = {
    edit: 'ID',
    //any other names that don't match keys directly
}

And use that mapping when assigning the value - something like:

$('#updateEmpForm input').each(function() {
    const inputName = $(this).attr('name');
    const key = inputNameKeyMapping[inputName] || inputName;
    if (key in data) {

That way you wouldn't need to include manual value settings lines.

Also, instead the click handler can be simplified from:

$('body').on('click', '.editButton',function(){

To using the .click()  (short-cut) method on only elements with that class name editButton:

$('.editButton').click(function(){

I see let is used to declare the variable edit:

let edit = $(this).val()

However, that value is never re-assigned. To avoid unintentional re-assignment, you could use const instead.

const edit = $(this).val()

And it is best to be consistent with line terminators - if most lines have them then make sure all do.


Is one version any better than the other?

It depends on what you actually want.

V1 is a single time operation. The table is going to be filled only once and subsequent calls will use cached data.
V2 on the other hand will be executed on each acceess.

One cannot say which one is to chose. You must know what would work better for you.

  Is there anything one version does that another does not?

Yes. V1 will get data only once and V2 everytime. This means that it might be acceptable to let the first property be a property because subsequent calls will be fast and only the first time initialization might take some time (depending on how much data it needs to get). The value it returns is stored in a backing field and it returns the same value everythime.

The second solution on the other head clearly behaves like a method because it can return different lists on each call thus I would make V2 a method.

  How do I get a better feel for what is going on?

This if is the answer:

if (_tableTypeList == null)
{
    var temp = TableTypes.OrderBy(t => t.ID);
    _tableTypeList = ((IListSource)temp).GetList() as BindingList<TableType>;
}

  I was surprised to find that another call to TableTypesList1 did not call the getter.

It probably did but when you put the breakpoint inside the if it's obvious that this block won't be called again.


Comparing each item from dir with each item from another dir

It's recommended to use enumerate rather than iter (renamed i), _ and indexing.

for i, abs_path in enemerate(mentors_sql_abs):
    mentors_sql[i][0] = abs_path

It's better to use zip rather than build mentors_sql manually.
Your function could further be simplified if you don't extend mentors_sql_* and just yield the values.
Please only use one string delimiter, either ' or ".
x is a pretty bad variable name, I would use file. Even for a comprehension it's pretty poor, as x isn't short hand for anything.
The only difference between the two functions as you walk different paths. And so you can change your input to account for this, and use one function.
I don't see the need for returning both relative and absolute paths, and so won't comment on it too much. You may want to return one and convert when needed.

def find_sql(path):
    for dirpath, subdirs, files in walk(path):
        for file in files:
            if file.endswith('.sql'):
                yield (
                    path.join(dirpath, file),
                    path.join(path.basename(dirpath), file)
                )

mentors = find_sql(config["MAIN_DIR"] + '\\Homework')
students = find_sql(config["MAIN_DIR"] + '\\Students Homework')


Scala: Are assertions acceptable outside of test context?

In short: yes, assertions make perfect sense outside testing and can raise the confidence that the code is actually correct.

Design by contract

What you like to assert, namely, that "dataOption must be defined if tpe does not represent a subtype of Option[Any]" can be considered a precondition of your method. That is, a condition over the parameters (and fields and global state) that needs to hold in order for your method to run successfully. The method implementer states such conditions and can then rely on them, whereas the caller is responsible for ensuring that they hold. The dual concept are postconditions, where the caller gets the guarantee which the implementer must ensure.

Languages such as Eiffel and Spec# natively support this so-called design by contract approach to programming. Natively, because contract elements such as preconditions, postconditions and invariants are built into the language. There is a significant difference, however, when the contracts are looked at. Eiffel checks contracts at run-time, which is quite similar to testing in the sense that only concrete executions are considered. Spec#, on the other hand, verifies contracts statically, which means that it tries to assert that the contract holds for all possible executions. The latter is very challenging and not always possible, but it yields much stronger guarantees in case it is. The former is easier, but gives you weaker guarantees.

Other languages lack native support for such contracts, for example Java or C#. In order to design by contract, Java developers can use JML and C# developers can use Code Contracts. JML is based on Java annotations and can be used for static verification and run-time checking, as can Code Contracts be, but they are implemented as a regular library.

Scala

Scala also lacks built-in support for contracts, but there are quite a few projects that try to work around this. Amongst others, there are:

Very simple run-time checked pre- and postconditions described in the paper Contracts for Scala
Static verification of functional Scala code with Leon
Run-time checking of Scala with a Code-Contracts-like library (project report)
Static verification of possibly non-functional Scala code (project description, the report will be only soon)

The answer

Back to your question: You use assertions (and the control flow) to check the precondition of your method, hence, you kind of do design by contract - which is good, because it makes it more likely that errors are detected close to where they are caused. These checks are basically like small unit tests and thus can increase the confidence in your code.

In order to make the method's precondition as explicit as possible, I would move the assertion to the begin of the method

private def convertData(dataOption: Option[ByteString], tpe: Type): Any = {
  assert(tpe.<:<(typeOf[Option[Any]]) || dataOption.isDefined,
         "<put helpful error message here>")

  ...
}

You could also put assertions at all return points of the method in order to mimic postconditions.

In case you worry about performance, you can use the fact the assert is annotated as @elidable and thus can be removed by the compiler, for example, for a production build.


Project Euler #6 - Sum square difference

As in many of the euler problems, a formula can be derived in whole or part to speed up the runtime.  In this case, the formulas below provide O(1) runtime.  For this example it's trivial, but imagine it's the sum of the squares of the first 1 billion numbers.  Since you are defining your own functions, as I am in my examples, I think it makes sense to provide the most efficient solution so that when these are used in later problems, they won't be a factor affecting performance.

Regarding the use of let, yes, it's often the case that you will bind what you need to in the let binding.  You could actually get by with no let at all, but as I have done below and as you did, I think your code is clearer than if you had inlined everything.

(defn sum-of-squares
  "1^2 + 2^2 + 3^2 ... N^2   ==>   N*(N+1)*(2N+1)/6 "
  [n]
    (/ (* n (+ n 1) (+ 1 (* n 2))) 6))

(defn sum-of-naturals
  "1 + 2 + 3 ... N   ==>   N*(N+1)/2 "
  [n]
  (/ (* n (inc n)) 2))

(defn answer []
  (let [sum (sum-of-naturals 100)
        square-of-sum (* sum sum)
        sum-of-square (sum-of-squares 100)]
    (- square-of-sum sum-of-square)))


Priority Queue implementation for top k frequent elements leetcode in Ruby

The objects in the priority queue (as implemented above) have their priority determined by <, >, and ==. So however equality is defined for the object determines its priority. For numbers and strings, this is fairly obvious but the default implementation of equality, less than and greater than for hashes may surprise you and not give the result you are expecting.
Perhaps you could consider passing in a block to your initialize method to allow you to provide your own comparison function in those cases where the default one doesn't match your needs. Like Enumerable::sort does.


Serving static assets through wildcard rule

There is a better way.

If you wish to serve static files with express - it comes bundled with static middleware. To use it, you simply add this line before your routes:

app.use(express.static(__dirname + '/public'));

This may require slight adjustment to your paths but it replaces all those manual routes and is more efficient (caching, expiration etc).

Check out this example.

I would, however, suggest that you use something like nginx for your static assets since it's typically more robust and it'll free resources from your node server.


Error-handling #ifdefs for AFNetworking requests

I would put ifdef DEBUG inside the failure method, so it's handled in one place only.

(void) failure(id response, NSError error) {

#ifdef DEBUG

#else

#endif

}


Here is just a quick response to your code:

Look into the csv module – This module handles csv-files rather nicely
Look into using functions to separate concerns – At all the places you've added comments, you should/could use functions. And the comments should rather be docstrings on line after function definition like in the following:

def write_list_to_file(guest_list, filename):
    """Write the list to csv file."""

    with open(filename, "w") as outfile:
        for entries in guest_list:
            outfile.write(entries)
            outfile.write("\n")

Variable and function names are usually snake_case – See example above, which is according to PEP8
Use the with construct to encapsulate file handling – This is called a context manager, and it handles error cases, opening and closing of the file. See example above.
Why do you create the file, and not write to it directly? – I don't quite see why you do the # Creating .csv file, when you can both create and write to it directly.
Change text to avoid guestNumber – Having the guestNumber seems unneccessary. If you change the text, you don't need it. Using something similar to "Add another guest (Name, age, location) or 'Done': ".
Doing capitalize() is somewhat "dangerous" – What if "John McEnroe" comes along, or "Jean von Luxembourg"?  They wouldn't like their name changed into "John Mcenroe" or "Jean Von Luxembourg". The same applies to the location part.
In general, don't add stuff you're going to remove immediately afterwards – That is I would most likely not add the Done guest for later removal, instead of adding it first and then removing it. Add a simple if in front of the append and the issue is avoided.
Avoid lengthy input prompts – Maybe personal preference, but I would rather have a lengthy text in front of the input prompt, instead of a lengthy prompt text. This way you could possibly also give even more examples of legal input.
Change into separate inputs – If you change to using the csv module, I would also change to three separate input statements, and possible do some simple validation on each of the inputs before adding them into the guest list.
Careful think about variable names – Some of your names are good, and some not so good. I.e. guestNames when it actually is both the name, age and location, is misleading. And in for entires in guestList, it would possibly read easier as for guest in guest_list:.

The latter is a typical pattern by the way, that is to use the singular of something plural, i.e. for guest in guests:, for number in numbers:, and so on. In general, plural version indicates list of some sort, whilst the singular version can be used within loops and similar.

I'll end this hasty review with a very useful construct which could cleanup your code (when you've created functions):

def main():
    """Main method used when called as a script."""

    guests = enter_guests()
    write_list_to_file(sorted(guests), "guestlist.csv")

if __name__ == '__main__':
    main()

Using this construct would allow for your code to be reused as a module later on, whilst still allowing it to be run directly from the command line. It also makes it very easy to understand what happens just skimming the code.


Do I always have to return something in an anonymous function?

While I understand how it may seem a pointless little nitpick for such simple code to have to have a return something from all code paths if it has one from any, pretty much every thing that a reviewer could say something about can be seen the same way. Individually the rules like the one Netbeans wants to enforce here don't do much, but when all followed together they make for much more maintainable code (especially after letting it sit there until you have forgotten about it for 16 months).

Further recommendations

Wrap the code in an IIFE (and add 'use strict';)

On top of other things this allows you to use a $ for jQuery here and not worry about messing with any conflict issues.
There is no reason to name the init function that you are just passing to $.ready; inline it.
Cache the jQuery elements.
Pass in global variables used to the IIFE (window, alert, msg_enter_question, msg_correct_answer).
document.getElementById("content").style.display has too many . I'd rewrite it as $content.css('display') after caching the element. Better still:

!$content.is(':visible')

_e is an awful variable name; that underscore adds nothing to it but makes it more annoying to type. Rename to e.
This:

var answer_count = 0
$(".answer").each(function() {
    if(this.value) answer_count++;
});

is better written as:

var answer_count = $answers.filter(function () { return this.value !== ''; }).length;

But it is even better to be commented out or otherwise removed since you aren't using it anywhere.
Similarly:

var correct_answer_selected = false;
$(".correct_answer").each( function(_e) {
    if(this.checked) {
        correct_answer_selected = true;
        return true;
    }
});

should be:

var correct_answer_selected = $correctAnswers.is(':checked');

Move variables to the top of their respective functions (personal preference in agreement with JSLint).
Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object. Thus:

if(!contents) {
    alert(msg_enter_question);
    e.preventDefault();
    e.stopPropagation();
    return true;
}

may as well be:

if(!contents) {
    alert(msg_enter_question);
    return false;
}

Most obvious there is that the return true statement is exactly not what is actually happening and thus is wrong. Since I would prefer to be explicit I would probably do this:

if(!contents) {
    alert(msg_enter_question);
    e.preventDefault();
    e.stopPropagation();
    return false;
}

As this same if statement is used twice (with different values) I would prefer to pull it out into a function:

function check(item, e, msg) {
    if (!item) {
        alert(msg);
        e.preventDefault();
        e.stopPropagation();
        return false;
    }
    return true;
}

This leaves:

    //...
    if(!check(contents, e, msg_enter_question)) {
        return false;
    }
    correct_answer_selected = $correctAnswers.is(':checked');
    check(correct_answer_selected, e, msg_correct_answer);
}

The problem of not all paths returning something is still here, so change the last line to return check....
If you inline correct_answer_selected then the pattern if (!x) { return false; } return y; logic can be replaced with return x && y:

return check(contents, e, msg_enter_question) &&
    check($correctAnswers.is(':checked'), e, msg_correct_answer);

The Full Monty then becomes (after some very minor spacing changes to pass jslint):

(function ($, window, alert, msg_enter_question, msg_correct_answer) {
    'use strict';

    $(function () {
        var $correctAnswers = $(".correct_answer"),
            $content = $('#content');

        function check(item, e, msg) {
            if (!item) {
                alert(msg);
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
            return true;
        }
        $("#post").submit(function (e) {
            // Make sure question is supplied
            var contents;
            if (window.tinyMCE && !$content.is(':visible')) { // If visual mode is activated.
                contents = window.tinyMCE.get("content").getContent();
            } else {
                contents = $content.val();
            }

            return check(contents, e, msg_enter_question) &&
                check($correctAnswers.is(':checked'), e, msg_correct_answer); //A correct answer must be selected.
        });
    });
}(jQuery, window, alert, msg_enter_question, msg_correct_answer));


I don't get what your solution brings that something like this doesn't:

public class DataManager
{
    private HttpSessionState session
    public String MemberID
    {
        get {return session["MemberID"];}
        set {session["MemberID"] = value;}
    }
}

Managing the collections Keys and PossibleKeys in two places seems error-prone.
Your naming convention of prefixing everything with 'p' is unusual (in C#).


If you have the possibility to use it, you could try the async / await pattern. It is however only part of the standard since ecmascript 2017.

The pattern allows you to wait for promise before continuing the execution path. This means you could rewrite your current code in the following syntax

// mock
const User = {
  findOne: async function( param ) {
    return new Promise(resolve => setTimeout(() => resolve( param ), 500));
  }
};

const _deleteOneToOneRooms = function(userId, teamMembers) {
  return async function() {
    let user = await User.findOne({ _id: userId });
    for (const member of teamMembers) {
      let foundMember = await User.findOne({ _id: member });
      // do something with that member
    }
  };
};

const removeUser = async function() {
  return _deleteOneToOneRooms( 5, [10, 15, 16] )().then( () => console.log('done') );
};

// an async function returns a promise in itself, so from outside an async function, you can use the `then` syntax
removeUser().then(() => console.log('async also done'));
// this will be logged first
console.log('remove user was called, rest is async');

This only gives you an idea from how you could reformat your code using this pattern.

The last piece of code can then also be rewritten like:

const _deleteOneToOneRooms = function(userId, teamMembers) {
  return async function() {
     let deletedUser = await User.findOne({ _id: userId });
     let usersNoCommonTeam = await _getUsersWithNoCommonTeams(deletedUser, teamMembers);
     return await _getOneToOneRooms(userId, usersNoCommonTeam);
  };
};


Using an AsyncTask to populate a ListView in a Fragment From a SQLite table

All in all, this code is great. I don't see much in the way of problems. There are a few nit-picks:

    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }

The above code takes one ClassCastException and swaps it with another. Is it necessary? If it is necessary (because the current message does not give details on the current activity), then I recommend initializing the cause of the thrown CCE:

    } catch (ClassCastException e) {
        ClassCastException tothrow = new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
        tothrow.initCause(e);
        throw tothrow;
    }

it is a pain, but you benefit from getting all the information in the stack trace. Currently you are losing some.

The only other issue I see is the extension of the AsyncTask. You have re-implemented the methods:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }

This is completely unnecessary and you can delete that code. Just let the ancestor code be.


Such a great question,

hasLost and hasWon should be functions
You should write functions with the keyword function, otherwise you get a mess of anonymous functions in stack-traces. The fat arrow syntax was only meant for inline functions.
head is not a great variable name, I don't know what it is supposed to be from the name
On the whole, the challenge in pure fp is to never assign, which you do a few times, read this for good measure: https://stackoverflow.com/a/33114654/7602
I am not sure I like that the guess function creates a new Hangman object every single time, there has to be a cleaner approach.

I found an interesting guide: https://drboolean.gitbooks.io/mostly-adequate-guide/ which states that this should be avoided.. Meanwhile, this is my this littered approach. It follows all my recommendations, and shows where I feel fat arrows have a place. I will try to rewrite again once I finish the guide ;)

function Hangman(word, copy, mistakes){

  //Initialize again, no assignments here ;)
  if(!copy){
    return Hangman(word, '_'.repeat(word.length), 0 );
  }

  //Non Exposed functions requiring context
  const won = (() => {
    return function won(){
      return word == copy;
    };
  })();

  const lost = (() => {
    return function lost(){
      return mistakes > 5;
    }
  })();

  const updateMistakes = (() => {
    return function updateMistakes(oldCopy , newCopy){
      return mistakes += oldCopy == newCopy ? 1 : 0;
    }
  })();

  const applyGuess = (() => {
    return function applyGuess(letter){
      return copy  = word.split('').map( (c,i) => letter == c ?  c : copy[i] ).join('');
    }
  })();

  //Exposed Functions
  function guess(){
    return function guess(letter){
      if(!done()){
        updateMistakes( copy , applyGuess(letter) );
      }
      this.display();
      return this;
    };
  }

  function display(){
    return function display(){
      console.log( won()? 'You won' : lost() ? 'You lost' : copy + ' ' + mistakes );
    };
  }

  //Return object
  return {
    guess : guess(),
    display: display(),
  }

  //Pure function?
  function done(){
    return won() || lost();
  }

}

const game = Hangman('Agile Development');
game.guess('e').guess('a').guess('t').guess('z');

Okay, 2nd version with far less this, many more clean functions:

function Hangman(word, copy, mistakes){

  //Initialize again, no assignments here ;)
  if(!copy){
    return Hangman(word, '_'.repeat(word.length), 0 );
  }

  //Exposed Functions
  function guess(){
    return function guess(letter){
      if( !done( won(word,copy), lost(mistakes) ) ){
        //An assignment, it was unavoidable I think
        mistakes = updateMistakes( mistakes, copy , copy = applyGuess(word,copy,letter) );
      }
      display(word, copy, mistakes, letter );
      return this;
    };
  }

  //Return object, kind pointless now that there is only 1 function :/
  return {
    guess : guess()
  }

  //Not entirely pure function, not cacheable
  function display(word, copy, mistakes, letter){
    console.log( won(word,copy) ? 'You won' :
                 lost(mistakes) ? 'You lost' :
                 copy + ' ' + mistakes + ' You tried (' + letter + ')' );
  }

  //Pure functions!!
  function applyGuess(word, copy, letter){
    return word.split('').map( (c,i) => letter == c ?  c : copy[i] ).join('');
  }

  function updateMistakes(mistakes, oldCopy , newCopy){
    return mistakes + (oldCopy == newCopy ? 1 : 0 );
  }

  function done(won, lost){
    return won || lost;
  }

  function won(word, copy){
    return word == copy;
  }

  function lost(mistakes){
      return mistakes > 5;
  }

}

const game = Hangman('Agile Development');
game.guess('e').guess('a').guess('t').guess('z');


Verbosity

String myString = getOutputFile();
File myFile = new File(myString);
FileInputStream inputStream = new FileInputStream(myFile);

FileInputStream can take String as argument. I'd do this instead:

FileInputStream inputStream = new FileInputStream(getOutputFile());

Whoa whoa whoa! We are reading from the output file? Did you make a mistake? I dunno, but by simply removing some lines I've suddenly exposed what could be a flaw!

Clarity

You're making a lot of objects and doing things with them. Try putting some blank space in between. It groups statements together and makes the code more logical.

void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException {
    FileInputStream inputStream = new FileInputStream(getOutputFile());

    File encodedfile = new File(path,"filename" + ".mp4");
    FileOutputStream outputStream = new FileOutputStream(encodedfile);

    SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);

    int b;
    byte[] d = new byte[8];
    while((b = inputStream.read(d)) != -1){
        cos.write(d, 0, b);
    }
    cos.flush();
    cos.close();
    inputStream.close();
}


Your code is one block, one piece of code that goes from start to finish, mixing logic and user-interface. While it works (Great!) this is sub-optimal for readibility and maintanability.

I will now show you what I think is a more readable approach. (The concept is the same, but this code will behave a bit differently than yours. Adapting it to your needs is left as an exercise for the reader).

Without farther ado, let's start:

 require 'arrow_test'

This code imports an automated testing framework I wrote, inatalling it is as easy as gem install arrow_test in the command line. Automated tests run in milliseconds to verify the correctness of your code.

ALPHABET = ("a".."z").to_a

The alphabet. Note that UPPERCASE means that it cannot be changed. It is a constant.

# Moves a letter forward in the alphabet by
# the given key wrapping around.
#

A short summary of what the function does, method level comments are encouraged over line level comments.

#
# shift('a', 2) #=> 'c'
#
#
#
# shift('z', 2) #=> 'b'
#

Example usage that doubles as tests, you may change them to see what happens.

 def shift(letter, key)
     ALPHABET[ (ALPHABET.index(letter) + key) % ALPHABET.length]
 end

This is a function, takes an input and has an output, It applies the Caesar cipher logic to a single character. The modulo operator % makes it behave like the alphabet is a circle. You may see the example with z.

 # Encrypts a text using by shifting all its letters by
 # the given key. All characters that are not lower and alphabetic
 # are deleted.
 #
 #
 # monoalphabetic_cipher('abcd', 2) #=> 'cdef'
 #
 #
 #
 # monoalphabetic_cipher('cdef', 2, decode=true) #=> 'abcd'
 #

A short phrase of description and a pair of tests like the other function.

 def monoalphabetic_cipher(text, key, decode=false)
   text
    .chars
    .select { |char| ALPHABET.include?(char) }
    .map {|char| shift(char, (decode ? 26 - key : key) )}
    .join
 end

Here I discard the non-lowercase chars, (select line), and apply the shift to each char (map line). chars and join are just to go from string to list and viceversa, not important. Seeing a 'flowchart' of the code may help understanding.

And this is all, try it with:

puts 'Enter shift and then text'
shift = gets.chomp.to_i
text = gets.chomp
puts monoalphabetic_cipher(text, shift)

Now user interface and logic are separated and the logic is tested. Feel free to ask any question


News-reading application using the Observer pattern

I think in general your implementation is fine. You could however use the intefaces that are already provided by .NET:

IObservable<T>

  Defines a provider for push-based notification.

IObserver<T>

  Provides a mechanism for receiving push-based notifications.

You can read more about them in the article about the Observer Design Pattern

In your your application you could use them to replace the Publisher and the ObserverBase.

The KindleApplication would become a IObserver<T>:

public partial class KindleApplication<T>
{
    public T Message { get; set; }

    public void Subscribe(IObservable<T> news)
    {
        _newsUnsubscribers[news] = news.Subscribe(this);
    }

    public void Unsubscribe(IObservable<T> news)
    {
        if (_newsUnsubscribers.TryGetValue(news, out var newsUnsubscriber))
        {
            newsUnsubscriber.Dispose();
            _newsUnsubscribers.Remove(news);
        }
    }
}

and it would implement this interface by storing the observables in a dictionary so that you can unsubscribe again:

public partial class KindleApplication<T> : IObserver<T>
{
    private readonly IDictionary<IObservable<T>, IDisposable> _newsUnsubscribers = new Dictionary<IObservable<T>, IDisposable>();

    public void OnNext(T value)
    {
        Message = value;
    }

    public void OnError(Exception error)
    {
        // ...
    }

    public void OnCompleted()
    {
        // ...
    }
}

The NewsChannel is now an IObservable<T> that notifies all observers about the changes:

public partial class NewsChannel<T>
{
    private T _newStory;

    public T NewStory
    {
        get { return _newStory; }
        set
        {
            _newStory = value;
            Notify();
        }
    }

    private void Notify()
    {
        foreach (var observer in _observers)
        {
            observer.OnNext(_newStory);
        }
    }
}

The new implementation could use an ISet<IObserver<T>> so that you don't subscribe the same channel multiple times and consequently get multiple updates for the same change.

It uses a private class that implements the logic for unsubscribing via the IDisposable interface.

public partial class NewsChannel<T> : IObservable<T>
{
    private ISet<IObserver<T>> _observers = new HashSet<IObserver<T>>();

    public IDisposable Subscribe(IObserver<T> observer)
    {
        _observers.Add(observer);
        return new Unsubscriber(_observers, observer);
    }

    private class Unsubscriber : IDisposable
    {
        private ISet<IObserver<T>> _observers = new HashSet<IObserver<T>>();

        private IObserver<T> _observer;

        public Unsubscriber(ISet<IObserver<T>> observers, IObserver<T> observer)
        {
            _observers = observers;
            _observer = observer;
        }

        public void Dispose()
        {
            _observers.Remove(_observer);
        }
    }
}

If you like you can split each class into multipe partial files to better separate the implementation of the intefaces from the actual data.

As far as the test is concerned it's really hard to follow it. You should split it into multiple tests that possibly verify only a single case. This means you could have such test as:

OnNext_NotSubscribed_DoesNotReciveMessage
OnNext_SubscribedToOneFeed_RecivesSingleMessage
OnNext_SubscribedToTwoFeeds_RecivesMultipleMessages
OnNext_SubscribedAndUnsubscribed_DoesNotReciveMessages
etc.


Creating vector of primes using Sieve of Eratosthenes

From Wikipedia, the Sieve of Eratosthenes algorithm is:

  To find all the prime numbers less than or equal to a given integer n
  by Eratosthenes' method:

  Create a list of consecutive integers from 2 through n: (2, 3, 4,
  ..., n).
  Initially, let p equal 2, the first prime number.
  Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p,
  4p, etc.; the p itself should not be marked).
  Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now
  equal this new number (which is the next prime), and repeat from
  step 3.

Your algorithm does not seem right really, notably it skips the step 4 which is essential for fast operation; and there are some non-C++ idioms too

Do not return the std::vector; instead pass it as a reference to the function.
Do not pass integers as const references.
If n < 2, return empty vector.
The Eratosthenes sieve goes like: "for all values from 2 to sqrt(n) - if the number is a prime then mark all its multiples not prime. However all multiples less than i * i have been marked already composite by previous iterations.
Do not multiply the loop variables when a simple addition suffices.
As a simple optimization, the 2 is always in the primes as we skipped the "no values" already; thus we add it. Then we iterate only odd integers starting from 3.

Thus we get

std::vector<int> generate(int n) {
    std::vector<int> result = std::vector<int>();
    if (n < 2) {
        return result;
    }

    // initialize the vector
    std::vector<bool> input(n + 1, true);

    // calculate the upper limit as the square root of
    // of N. all composite numbers <= N must have a
    // factor <= sqrt(N)
    int sqrtN = (int)sqrt(n);

    // iterate from 2 up to the square root of N
    for (int i = 2; i <= sqrtN; i ++) {
        if (! input[i]) {
            // i is a proven composite number,
            // all its multiples have been
            // marked not prime by all its prime factors by now.
            continue;
        }

        // as an optimization, all multiples *less* than
        // the square of i are already marked, (they have
        // another prime factor less than i), so we can start
        // from the square which is the smallest composite
        // not yet marked
        for (int j = i * i; j <= n; j += i) {
            input[j] = false;
        }
    }

    // as n >= 2, then add 2 here
    result.push_back(2);

    // and check only odd numbers here,
    // no other even number can be set
    for (int i = 3; i <= n; i += 2) {
        if (input[i]) {
            result.push_back(i);
        }
    }

    return result;
}

Of course you do not need the second loop to just fill in the result vector; if the input[i] is true (the continue was not executed), the number is a prime and you can push_back it to the result vector there:

if (! input[i]) {
    // i is an already proven composite number,
    // all its multiples have been
    // marked not prime by all its prime factors by now.
    continue;
}

// i is a prime
result.push_back(i);


Formatting

for (i = 0, ch = test; *ch; *ch++) {
        if (*ch == '@') {
            pos1 = ch;  // <-stores last @ address
            i++;
        }
    }
    pos2 = ch;

You have an extraneous level of indentation in there that throws out that block.

int     i;
char    *pos1, *pos2;
char    *ch;

This is a weird indentation level, it doesn't match anything else and is unnecessary. It literally just complicates how you read it.

Naming

int test(char test[]):

Naming both your function and variables test is bad practice. How am I meant to tell as an outsider reading your code what it is that your code does.

/* Pos1 - test <-a character must be before "@". Ch - pos1 <-Counts
 * backwards from the end of the string towards "@". A character
 * must be between "@" and "." */

If you feel the need to explain your code with comment blocks like this, you can probably improve your naming.

Name your variables as to what they are. For Example: charactersAfterAt.

Duplicate Logic

scanf("%39s", test);
while(1){
    // ...
    scanf("%39s", test);
}

You can reduce duplicate logic by declaring the scan inside the loop at the top.