Looks good.
Personally, I would take:

foreach($curPath in ($LiteralPath + $Path | Where {$_} | Resolve-Path)) {

and break out the collection generation code.
Specifically into something like:

$PathList = Join-Path $literalPath $Path | Resolve-Path

You shouldn't need to worry about a Where-Object to validate that it isn't $null.  If there is no result it won't go up the pipeline.

If you Dot Include all of your Scripts you can wait until all are included then check your commands.  This will run anything else you have in the script though.

It may be safer to use the parser like this sample below.  In this code I looked for catch blocks to insert a breakpoint , but you could have it filter for your test prefixes too.

$ParseError = $null
$Tokens = $null
$AST = [System.Management.Automation.Language.Parser]::ParseInput($psISE.CurrentFile.Editor.Text, [ref]$Tokens, [ref]$ParseError)
if($ParseError) {
    foreach($er in $ParseError) { Write-Error $er }
    throw "There was an error parsing script (See above). We cannot expand aliases until the script parses without errors."
}
$a = $ast.FindAll({($args[0] -is [System.Management.Automation.Language.CatchClauseAst])},$true)

Josh


Random item from array

You don't need the for loop to select a random item from an array.

Just get an index using Math.floor(Math.random() * array.length)

function getRandomQuote(array) {
    return array[Math.floor(Math.random() * array.length)];
}

Or as an arrow function, and you don't need the get part of the function name that is implied.

const randomQuote = array => array[Math.floor(Math.random() * array.length)];

You can also use bitwise or zero | 0 in place of the Math.floor function

const randomQuote = array => array[Math.random() * array.length | 0];

Random pick from array

If you wish to ensure each quote is randomly selected and not repeating until all have been randomly selected you can create a copy of the array, and pick items from that using Array.splice until empty, then copy the source array again.

For example the function encapsulates array and source You must first call the function with an array, then any other calls will return a random item that does not repeat until all items have been picked.

const randomQuote = (() => {
    const picked = []; // to hold picked items
    var source;   // array of items to pick from
    return srcArray => {
        if (srcArray) {
            source = srcArray;
            picked.length = 0;
        } else {
            if (!picked.length) { picked.push(...source) }
            return picked.splice(Math.random() * picked.length | 0, 1)[0];
        }
    }
})();

randomQuote(["a","b","c","d","e","f"]); // set up the source array
console.log(randomQuote()); // display random quote in console.

At any time you can reset the source array by calling the function with an array.

Random and the array, common functions

Here is a set of common functions that use random to access arrays. Rather than have functions rely on each other, each function is written to be entirely stand alone. If you use many of them it will pay to encapsulate them all in an object.

const randItem = arr => arr[Math.random() * arr.length | 0];
const randPick = arr => arr.splice(Math.random() * arr.length | 0, 1)[0];
const randPut = (arr, item) => arr.splice(Math.random() * (arr.length + 1) | 0, 0, item);
const randShuffle = arr => {
    var len = arr.length
    while (len) {
        arr.push(arr.splice(Math.random() * (len--) | 0, 1)[0]);
    }
    return arr;
}
const randPlay = (arr, repeat) {
    var item;
    repeat = repeat > arr.length ? arr.length : repeat
    arr.push(item = arr.splice(Math.random() * repeat | 0, 1)[0]);
    return item;
}

What they do.

randItem(array)  return a random item but does not remove it
randPick(array)  returns a random item removing it from the array
randPut(array, item) randomly inserts the item into the array
randShuffle(array) Shuffles the array in place (does not make a copy)
randPlay(array, number) A variation on the no repeat, selects random items from the bottom number items. Good for play lists when you dont want to repeat the same track. Use with randShuffle on the array before you call randPlay. The same item will not play again until another array.length - number items have played.


JavaScript circular linked list compatriot game

The Ouroboros

Your code is way too complex for the task

The most obvious improvement is to remove the functions find, findPreviouse, and count

Why

Rather than hold the data each list item has, hold the current link. This means you dont need to find the item each time you move along the list
You can know the remaining number of links by counting each link removed so there is no need for the function count.
If you remove the next link in the sequence rather than the current you don't need to find the previous link as you already have that, thus you dont need findPreviouse.

Some more points

When doing a simple countdown use a while loop. eg while (n--) { is much simpler than for (let i = n; i > 0; i--) {
Don't test for conditions if there is no need. In remove you have if (!(prevNode.next == this.head)) { which I can not work out why you have it there. Also it should have been written as if (prevNode.next !== this.head) {
You should use const when ever possible, only if the variable has to change should you use var or let
Always use === or !== never use == or !=
If you are defining a object use the prototype or define the properties as an object. Creating a list of unrelated function names and then adding them to the object at creation is a mess, a source of bugs from the inevitable naming conflicts.

eg

function LList() {
    this.head = new Node("head");
    this.head.next = this.head;
}
LList.prototype = {
    remove(item) {
        // function body
    },
    findPrevious(item) {
        // function body
    },
    display() {
        // function body
    },
    count() {
        // function body
    },
    // and so on...
};

Rewrite

I think that the LList and Node objects are overkill for this problem. A simple ad-hock object can hold the item position and link to the next. You only need to hold the current node, and to determine when you have two left just count off each item as they are removed.

function survivor(number, step) {
    var i = 0, current;
    const add = pos => {
        const link = {pos};
        if (current) {                 // check if not first item
            link.next = current.next;  // insert link to tail
            current.next = link;
        } else { link.next = link }    // first link points to self
        current = link;                // Hold current as head
    }
    const stepOverAndRemove = (link, n) => {
        while (--n) { link = link.next }   // do this n-1 times
        return link.next = link.next.next; // remove next link and return link after that
    }

    while (i < number) { add(i++) }  // create list
    current = current.next;          // move to the start

    // remove every `step` item until only two remain
    while (number-- > 2) { current = stepOverAndRemove(current, step) }

    // return the position of the remaining two
    return [current.pos, current.next.pos];
}


I don't think this could get much drier. let is not cached across examples but it is cached within examples, so you can't move that let out of the nested describe blocks.

Maybe it might be easier for you to define tests that test when the model is valid, and then have a catch-all test to fail in any other case? Unless you are testing validation messages (which I don't think you need to be testing individually, and that is out of the scope of a unit test), you don't need to know which individual field failed, only that the model is invalid and X should happen.

describe TimeEntry do
  describe "validity" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "is invalid without a project" do
      entry.project = nil
      expect(entry).to_not be_valid
    end
    it "is invalid without a user" do
      entry.user = nil
      expect(entry).to_not be_valid
    end
  end
end

Alternatively you can do the above.


From a quick read :

Xml seems like a bad name for your wrapper, you should consider something like xmlParser ?
I would allow access to data and elements by using this instead of var because you wrap so little of the XML parser API
this.length seems wrong ( the parser has no length), maybe loadedElementCount, but even that is pretty bad, I would just let the caller use elements.length.
I would return elements in this.load, since that is pretty much what the caller would need next.
You are not checking for falsey values of nodeName in this.load
I would not create a var element in getValueAt, I would just return elements.item(index).childNodes[0].data


search a given word in word file by Aspose

Some quick remarks:

FindContentOfWordDoc is a bad class name, in the first place because it contains a verb. Please follow the Microsoft rules.

While this code only does a search, it is peppered with names that refer to "find and replace". This makes it hard to understand. I assume this must be due to Aspose, so perhaps this is inevitable, but then perhaps you could add some comments to explain why you implemented it this way.
Are you certain this is the best way to execute a search? I find it odd that you would need to "abuse" the "find and replace" functionality; it seems odd that Aspose would include that functionality yet not a "find" on its own.

You don't check content: is this function only intended for single word queries, or also for combinations of words? And why not check if the user actually entered a search term, in order to avoid invoking the callback etc. on a null or an empty string?


Sequence generator with custom step size, start value and operation

Generally code looks good. Despite that, there are number of places where it could be improved.

There is no need to specify output type explicitly. I'm not a language lawyer, but return type seems explicit to me. Also, ideone compiler is able to compile it without return type hints.

The behavior of the next is surprising. It returns old value and then advances it. I'd expect it to be vice versa. I guess you wanted to output initial value once, so it is probably a design choice. On top of that, it is probably the most performance draining part of the code.

There is no need to write constexpr on every function. It will mean inline, which itself means bloating size of the executable. Cases where it could be really compile time evaluated are very rare. The deal breaker factor here is advancer function, and if it returns different values on each call it is probably impossible to evaluate it at compile time. I'm excluding possibilities of immense template metaprogramming magic.

I would change interface to use binary operation to advance it. It would be much more customizable.

Overall I think std::generate_n is more for randomly generated numbers or something alike. People usually use std::iota to fill with increasing values.

Proposal

I propose a very different solution.

The solution will be a generic function named stepping_iota.

template <typename OutputIterator, typename T, typename UnaryAdavanceOp>
void stepping_iota(OutputIterator first, OutputIterator last, T init_value, UnaryAdavanceOp op)

It will call std::iota under the hood, to avoid surprises. But to do that, it will use proxy pattern. Specifications say that it is not required for decltype(*first) and T to match. So we can implement very small proxy, which will have all the needed functionality.

namespace impl_details
{
    template <typename T, typename UnaryAdvanceOp>
    class proxy
    {
        T value;
        UnaryAdvanceOp op;
    public:
        proxy(T init_value, UnaryAdvanceOp op_) :
            value(init_value),
            op(op_)
        {}

        operator T()
        {
            return value;
        }

        T operator++()
        {
            value = op(value);
            return value;
        }

        T operator++(int)
        {
            T old = value;
            value = op(value);
            return old;
        }
    };
}

I've written post increment for the sake of symmetry.

Then the stepping_iota will construct the proxy and pass it to std::iota:

impl_details::proxy<T, UnaryAdavanceOp> p(init_value, op);
std::iota(first, last, p);

Despite the function has a few parameters, it is customizable and easy to use with lambdas. It uses unary operation, which is common and used in functions such as std::transform.

Complete example:

#include <numeric>

namespace impl_details
{
    template <typename T, typename UnaryAdvanceOp>
    class proxy
    {
        T value;
        UnaryAdvanceOp op;
    public:
        proxy(T init_value, UnaryAdvanceOp op_) :
            value(init_value),
            op(op_)
        {

        }

        operator T()
        {
            return value;
        }

        T operator++()
        {
            value = op(value);
            return value;
        }

        T operator++(int)
        {
            T old = value;
            value = op(value);
            return old;
        }
    };
}

template <typename OutputIterator, typename T, typename UnaryAdavanceOp>
void stepping_iota(OutputIterator first, OutputIterator last, T init_value, UnaryAdavanceOp op)
{
    impl_details::proxy<T, UnaryAdavanceOp> p(init_value, op);
    std::iota(first, last, p);
}

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> v(10'000);

    stepping_iota(v.begin(), v.end(), 0, [](const int& x) { return x + 1; });

    for (const auto& elem : v)
    {
        std::cout << elem << ' ';
    }
}

In C++17 you will be able to write:

impl_details::proxy p( init_value, op );


Angular UI-Router Repetitive templateProvider Using $rootScope

A better solution is to resolve the data in a parent route, then inject the resolved data ("identityResolve") from a service ("identity") into each child instance.

.state('app.auto', {
    abstract: true,
    url: '',
    resolve: {
        identityResolve: ['identity', function(identity) {
            return identity.initialize().$promise;
        }]
    }
})

Which then is used like this

.state('app.auto.public.inventory.list', {
    url: '/',
    views: {
        'auto-one@app.auto': {
            templateProvider: ['$templateCache', 'identityResolve', function($templateCache, identityResolve) {
                return $templateCache.get(identityResolve.version + '/html/inventory/list/index.html');
        }],
        controller: 'InventoryList'
    }
});


User experience

-h  or --help should print the usage message to standard output, which you do.  However, on any unrecognizable command line, you should print the same (or similar) message to standard error and exit with a non-zero status.
Similarly, other error messages should go to standard error and result in a non-zero status.

Style issues

Good job, double-quoting almost every variable you used.  A lot of shell programmers neglect to do so.
Good job, breaking the program up into functions.  A lot of shell programmers don't.
Indent your code consistently.  It's hard to see where your functions begin and end.
Make use of case to replace convoluted if statements.
Do all of your command-line parsing in one place, and have a coherent parsing strategy.  You can either use getopt (which has a bit of a learning curve) or build something based on shift (which is easier for a beginner to understand).
You can pass parameters to functions.  Passing $PPA to ppa_verification() would be more elegant than using a global.

There isn't 100% consensus on whether variable names should be $ALL_CAPS or $lower_case.  One common convention is $ALL_CAPS for global and/or exported variables, $lower_case for local or non-exported variables.

Use of wget

Instead of writing the output of wget to a temporary file, you could just pipe it to grep directly: wget -q -O - "$url" | grep -q "$release".
But then, to distinguish between a wget failure (e.g. network problem) and the release not being found by grep, you would have to interrogate ${PIPESTATUS[0]} and ${PIPESTATUS[1]}, which is a bit complicated.
Why not try to fetch the subdirectory of dists/ that you care about instead?  Then you only need to test whether the server returned an HTTP 200 (Success!) or HTTP 404 (Not Found).

#! /bin/bash
SCRIPT="ppa-tool"
VERSION="200_success"
DATE="2014-03-26"
RELEASE="$(lsb_release -si) $(lsb_release -sr)"

helpsection()
{
    echo "Usage : $SCRIPT [OPTION]... [PPA]...
-h, --help     shows this help
-c, --check    check if [PPA] is available for your release

Version $VERSION - $DATE"
}

ppa_verification()
{
    local ppa="${1#ppa:}"

    local codename="$(lsb_release -sc)"
    local url="http://ppa.launchpad.net/$ppa/ubuntu/dists/$codename/"

    wget "$url" -q -O /dev/null
    ######################################################################
    # Exit Status
    #
    # Wget may return one of several error codes if it encounters problems.
    # 0 No problems occurred.
    # 1 Generic error code.
    # 2 Parse error--for instance, when parsing command-line options, the `.wgetrc' or `.netrc'...
    # 3 File I/O error.
    # 4 Network failure.
    # 5 SSL verification failure.
    # 6 Username/password authentication failure.
    # 7 Protocol errors.
    # 8 Server issued an error response.
    ######################################################################
    case $? in
      0) # Success
        echo "$SCRIPT : '$ppa' is available for $RELEASE"
        ;;
      8) # HTTP 404 (Not Found) would result in wget returning 8
        echo "$SCRIPT : '$ppa' is NOT available for $RELEASE"
        return 1
        ;;
      *)
        echo "$SCRIPT : Error fetching $url" >&2
        return 3
    esac
}

PPA=
while [ -n "$*" ] ; do
    case "$1" in
      -h|--help)
        helpsection
        exit 0
        ;;
      --check=*)
        PPA="${1#*=}"
        ;;
      -c|--check|check)
        PPA="$2"
        shift
        ;;
      *)
        helpsection >&2
        exit 2
        ;;
    esac
    shift
done

if [ -z "$PPA" ]; then
    helpsection >&2
    exit 2
fi

ppa_verification "$PPA"


Hide menu during user inactivity with jQuery, setInterval performance

Hmmm... polling at regular intervals instead of using a handler... not good. It means that the interval between the event (mousemove, etc) and the call to fadeOut is variable. It also means that the script continues to use up a small amount of CPU while nothing is happening. And there's a tradeoff between these two things: If you increase the second argument to setInterval you get more variation in waiting time but less needless CPU usage.

Also, the logic feels slightly wrong: the element is hidden if it is near the left edge after 30 seconds; but if it isn't, and subsequently is moved left, fadeOut will not be called. Having said that, I'm not sure what the events are; if it's impossible to move it left without triggering one of the events, then ignore this paragraph. If this is an issue then I'm not sure exactly what behaviour you want, so I've ignored this issue in my answer - my code will behave as I just described.

Anyway, what you need is window.setTimeout; this function schedules another function to run after a given interval. So if you call window.setTimeout in the event handler, it will cause another function (hideIfNecessary, below) to run 30 seconds after an event is fired.

Of course, if another event is fired while the clock is ticking, you want to call hideIfNecessary 30 seconds after the second event, but cancel the one 30 seconds after the first event. To cancel events scheduled with window.setTimeout, use setTimeout's evil twin, clearTimeout.

So without further ado, here's my version of your code with setTimeout. (I haven't tested it though.)

var timeoutId = null;

function hideIfNecessary(){
    var posx=$("#page").offset();
    if (posx.left < 2) {
        $('#menu').fadeOut(1000);
    }
}

$(document).bind('mousemove keydown scroll touchstart', function() {
    var posx=$("#page").offset();
    if($('#menu').is(':hidden') && posx.left < 2) {
        $('#menu').fadeIn(1000);
    }
    if (timeoutId !== null) window.clearTimeout(timeoutId);
    timeoutId = window.setTimeout(hideIfNecessary, 30000);
});


The seasoned Zombie sniper: a query to find unanswered questions with specific tags

You have made a nice looking query here. I just have to nit-pick a little bit.

You query the table Posts with a synonym q where I would expect p instead. I know you want to indicate that it is a question but nevertheless I would expect p instead of q.
Every sql-statement is written in capital-letters but the AS keyword is written in lower-case-letters.

What you didn't take into account is the entering of a tag-synonym which would be  nice to have as well.


Binary Search implementation: HackerRank - Climbing the Leaderboard

You are on the right track. However, implementing your own bisection algorithm is not a good idea. Python has the built-in ("batteries included") bisect module, containing all the bisection algorithms we need.
They are implemented in Python, but overridden by fast C implementations if those are available, which would then be as fast as we can hope for.

The from bisect import bisect (with the bisect function as an alias for bisect_right) replaces your binSearchMod function.
In the code at the bottom, there is a "manual" bisect implementation without recursion, which is also a step forward.
It is probably best to avoid recursion if (much) simpler means are available.

In your base climbingLeaderboard function, you have

        if ascore<scores[len(scores)-1]: # alice scores are smaller than all
            res.append(len(set(scores))+1)
        elif ascore > scores[0]: #alice score is greatest
            res.append(1)

which handles special cases.
These cases are not special enough to warrant this, and are code smell.
Your basic search algorithm should return correct results to append to res on its own, as we will see shortly.
See also import this: Special cases aren't special enough to break the rules..

As an aside, slicing (using slice objects) makes indexing sequences much easier: scores[len(scores)-1] is just scores[-1].
Further, you return a list using

return [False, start]

This is a bad idea.
You later use it to index into it, but that job can better be done by a tuple.
Simply calling

return False, start

will return a tuple.
This can be unpacked into two variables in one assignment, or indexed into just like lists.
Tuple unpacking is convenient and easy to read.

The distinction between lists and tuples is important: lists are (should be) homogeneous, aka contain a sequence of elements of the same type (think filenames).
Tuples are heterogeneous, aka the position of elements has meaning and they are of different types.
In your example here, this would be bool and int, which have different semantics.

A key aspect to realize is that duplicate scores in the leaderboard can just be tossed, since they do not count towards anything.
This calls for a set implementation.
This also automatically gets rids of your

    #ssign ranks to scores
    for score in range(1,len(scores)):
        if scores[score]!=scores[score-1]:
            rank+=1
            rankScores.append(scores[score])

code block, saving a whole \$ \mathcal{O} (n) \$ iteration.

Since bisect relies on ascending order, while the input is sorted in descending order, a call to sorted is required, which automatically returns a list.

bisect(sequence, item) will return the index where to insert item in sequence while retaining order.
If items compare equal, item is inserted to the right of existing items.
If a list of scores in ascending order is [20, 30, 50], then Alice is really in second place if she scored 30. bisect_left would sort her into third place.

Since ranks are 1-indexed, increment by 1.
Lastly, the below result would be inverted, since the sorting inverted the list.
Therefore, use len to rectify.

#!/bin/python3

import math
import os
import random
import re
import sys
from bisect import bisect

# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
    length = len(scores)
    return [length - bisect(scores, alice_score) + 1 for alice_score in alice]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    scores_count = int(input())

    scores = sorted(set(map(int, input().rstrip().split())))

    alice_count = int(input())

    alice = list(map(int, input().rstrip().split()))

    result = climbingLeaderboard(scores, alice)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

This passes all tests. The required sorted step is \$ \mathcal{O}(n\, \log n)\$, see here.

Without sorting the input, a bisect implementation that works on reversed sorted lists is required.
The change compared to the original implementation (link above) is minimal, as seen below.
if a[mid] < x: lo = mid+1 is simply inverted to if a[mid] > x: lo = mid+1 (I also formatted the code more).

Simply calling list((set(sequence)) on the scores will not work.
Duplicates will be purged, but the order will be lost.
Therefore, we simply construct a new list, using a set to block appending already seen elements, see here.

The below approach works, but similarly to yours, fails for long inputs in its naive version.
This is why I added previous_higher_bound.
This counter keeps track of what rank Alice was on in the past.
It could also be named previously_lowest_rank or similar.
This is passed to bisect to drastically tighten the searched range, allowing the tests to pass.
Unfortunately, it also makes the approach more verbose.

# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice):
    def reverse_bisect_left(sequence, x, lower_bound=0, higher_bound=None):
        """Return the index where to insert item x in list a, assuming a is sorted in reverse.
        """
        if lower_bound < 0:
            raise ValueError("lo must be non-negative")
        if higher_bound is None:
            higher_bound = len(sequence)
        while lower_bound < higher_bound:
            middle = (lower_bound + higher_bound) // 2
            if sequence[middle] > x:
                lower_bound = middle + 1
            else:
                higher_bound = middle
        return lower_bound, higher_bound

    def uniquelify_list(sequence):
        seen = set()
        return [int(x) for x in sequence if not (x in seen or seen.add(x))]

    def leaderboard_rank(scores, score, higher_bound=None):
        result, previous_higher_bound = reverse_bisect_left(scores, int(score), higher_bound=higher_bound)
        return result + 1, previous_higher_bound

    def get_ranks(scores, alice_scores):
        scores = uniquelify_list(scores)
        previous_higher_bound = len(scores)
        ranks = []
        for alice_score in alice_scores:
            result, previous_higher_bound = leaderboard_rank(scores, alice_score, previous_higher_bound)
            ranks.append(result)
        return ranks
    return get_ranks(scores, alice)


#n_primes

Ruby has the Prime class as part of its stdlib, so you don't need to roll your own prime number generator.
n_primes(word_array.length + 1)[1..-1]

A more Rubyesque version might use drop(1) instead of the [1..-1] slice.
words = {} + primes.each_with_index

Instead of creating an empty Hash and then adding elements to it, you can use Array#zip to create an array of word/number pairs. You can turn that into a hash with Hash[], if you'd like.
words.reject

Purely from a semantic standpoint, I think select would be more natural to use. I think of it as "finding the words to print" rather than "discarding the words that shouldn't be printed" which sounds like a double negative.

You could also consider using #inject or #each_with_object to collect matches instead of #reject + #values
to_print.length == 0

Use Array#empty? instead.
to_print.join ''

You don't need the argument for Array#join.

I'd do this:

require "prime"

puts "Enter the words you would like to use (separated by spaces)"
words = gets.strip.split

puts "Enter the number to count up to"
count = gets.strip.to_i

pairs = Prime.first(words.count + 1).drop(1).zip(words)

1.upto(count) do |n|
  line = pairs.each_with_object([]) do |(prime, word), memo|
    memo << word if (n % prime).zero?
  end
  puts line.empty? ? n : line.join
end

Or, more in line with yours, the last part could be:

1.upto(count) do |n|
  line = pairs.select { |prime, _| (n % prime).zero? }.map(&:last)
  puts line.empty? ? n : line.join
end


Inherited code checking Struts method name

I don't believe there's any good use-case for this code.  I know it makes for a boring answer, but sometimes the correct thing really is simple and boring.  As you say, the Struts framework should always redirect to the appropriate method and fail entirely otherwise.

Even the scant lines you posted have some bad/useless programming practices, so my guess is that the developer thought he was being thorough and clever by tacking on needless framework.

if (method != null && "myMethod".equals(method)) {
    // Perform the actual work

He already checks for method != null and then checks for "myMethod".equals(method).  The only reason to use the second construction for a String comparison is to avoid a NullPointerException... which he's already done by checking against null.  So either he doesn't know that Java short-circuits conditions, or he has no idea what the purpose is behind the second construction.

Also, it's generally a bad idea to have huge wrappers around entire method bodies.  It would be a better design to have something like this (if it were needed at all):

if(method == null || !method.equals("myMethod") {
    return;
}

//do stuff

... Or you could write the conditional as if(!"myMethod".equals(method)), but I honestly really hate the flipped comparison rather than explicitly checking for null.  I suppose it's a matter of taste, though.

Anyway, bottom line: no, there's no use for it, and there's evidence that the original programmer didn't entirely know what he was doing, anyway.


Design Issue:

From a design perspective I see one issue in LogicUnit. Out is an inferred latch because it is not assigned in all conditions of Op. The risks associated with these latches and how to use them property (when needed) have already been discussed on other Stack Exchange sites; such as here on Electrical Engineering Stack Exchange and here on Stack Overflow. Synthesis considers all possibilities. Depending on your setup it may or may not recognize Op>4 as out of bounds. It is safer to give it an explicit assignment and allow the synthesizer to choose how to optimize.

In your situation a latch should not be inferred. The easiest way to resolve this is to ass a default statement:

always @* begin
  case(Op)
    3'b000: Out = ~A;
    3'b001: Out = A & B;
    3'b010: Out = A | B;
    3'b100: Out = A ^ B;
    default: Out = A ^ B; // <<-- or any expression to a known value
  endcase
end

You may have noticed I also changes the <= to =. This has to do with coding style recommendations and suggestions that I will cover next.

Coding style:

Blocking vs Non-Blocking Assignments:

The only major coding style concerning I see is that you are using non-blocking assignments (<=) for all assignments in your always blocks. Non-blocking assignments should be used for flops (edge-sensitive) or latches (level-sensitive). Blocking assignments (=) should be used for combinational logic; which is what your logic is.

Blocking and non-blocking update the LHS at different regions in the scheduler. Blocking is immediate evaluation and assignment. Non-blocking is immediate evaluation with postponed assignment. Non-blocking was introduced to resolve a race condition when evaluating and assigning synchronous logic. Using non-blocking inappropriately, such as using it everywhere, can introduce another form of race conditions.

It is recommended to keep blocking and non-blocking assignments in separate always blocks. There are technically legal ways to safely mix them, but most avoid it all together

FYI, by using blocking assignment you could merge the always blocks that assign Out and Zero.

Sensitivity list:

What you have is legal and 100% complaint with the original Verilog IEEE standard (IEEE1364-1995). However automatic sensitivity (@* or @(*)) was added in IEEE1364-2001 and is the preferred and recommended way of declaring conbinational and latching logic with Verilog. @* use the RHS varabiles and nets used in the always-block to determine what signals it needs to be sensitive to. It does not look for signals used inside the body of tasks or functions (signals in the port list are fine) used with in the always block. This is a limitation, but it is also not recommended to have synthesizable tasks/functions reference non-port signals.

@* does more that reduce typing. By allowing verilog to manage the sencitity list for you, it reduces the risk of forgetting a signal (behavior vs synthesis mismatch), having unnecessary signals (possible simulation overhead), and typos (compiling errors or will use the wrong signal).

In summary use @* (or the synonymous @(*)).

Module Instances:

You are using connect by order which is okay for small modules with simple connectivity and whose port list isn't under constant editing. If you use connect by name, the port connections are explicit and it will not matter if the port order is re-arranged. It also helps any human readers of your code understand how the ports are intended to connect.

Adder DEV_ADD( .A(A), .B(FinalB), .Cin(FinalCin), .S(AddResult), .Cout(Cout) );

Module header:

Your module header is is complaint IEEE1364-2001 non-ANSI style (History: in IEEE1364-1995, declaring something to be an output and a reg had to be done in separate statements). I have heard of one case where some tools do not support non-ANSI header with one-line output reg. I have know idea how prevalent this issue is as most new code is written with the ANSI header style. Legacy code and some generated code is written as non-ANSI that is comparable with IEEE1364-1995. ANSI header style is currently the most popular because it is the simplest and cleanest way of managing ports. It becomes more useful as the port list grows and when it is edited often.

You don't need to change your code if you do want to. Be aware if you ever run into an issue with another simulator, synthesizes, or other tool that takes in Verilog. A compiling issue could be because some developers skipped support for one-line output reg for non-ANSI headers. It is technically a bug for the tool but it is unlikely to get much attention. The developers are more focused in adding/fixing/improving higher demand features. Plus there are two work arounds: ANSI and 1995's non-ANSI.

Here is an example of you ALU headed in the three flavors.

ANSI style (popular): IEEE1364-2001 ==> IEEE1800-2012(SystemVerilog)

module ALU( // PORT ORDER, DIRECTION, AND TYPE
  input [7:0] A, B,
  input Cin,
  //011-A+B, 111-A-B, 000-NOT A, 001-A AND B, 010-A OR B, 100-A XOR B
  input [2:0] Op,
  output reg [7:0] Out,
  output Cout,
  output reg Zero,
  output reg Sign );

non-ANSI style (1995 style): IEEE1364-1995 ==> IEEE1800-2012(SystemVerilog)

module ALU(A, B, Cin, Op, Out, Cout, Zero, Sign); // PORT ORDER
  // PORT DIRECTION
  input [7:0] A, B;
  input Cin;
  //011-A+B, 111-A-B, 000-NOT A, 001-A AND B, 010-A OR B, 100-A XOR B
  input [2:0] Op;
  output [7:0] Out;
  output Cout;
  output Zero;
  output Sign;
  // OUTPUT TYPE
  reg [7:0] Out;
  reg Zero;
  reg Sign;

non-ANSI style (2001 style): IEEE1364-2001 ==> IEEE1800-2012(SystemVerilog)

module ALU(A, B, Cin, Op, Out, Cout, Zero, Sign); // PORT ORDER
  // PORT DIRECTION AND TYPE
  input [7:0] A, B;
  input Cin;
  //011-A+B, 111-A-B, 000-NOT A, 001-A AND B, 010-A OR B, 100-A XOR B
  input [2:0] Op;
  output reg [7:0] Out;
  output Cout;
  output reg Zero;
  output reg Sign;


Become familiar with rustfmt. For example, else goes on the same line as the previous closing brace:

-        }
-        else if input == 2 {
+        } else if input == 2 {

Rust doesn't do tail call optimization, so unbounded recursive calls are better replaced with iteration.
I might extract a function that does the reading from standard input, trimming, and parsing.
No need for a type on the vec; inference will kick in.
You can use match with values like numbers. This can be used to replace the large if-else chain at the end of main.
Move the command out-of-range check/warning from the "parse" match to the match of the command value. This groups the error text closer to the place that will change.
I wouldn't embed the match inside the println!; it's not obvious enough. Instead, put the print inside the match.
Can then remove the continue because that's the normal flow
Don't convert the number to a string to print it; numbers implement Display.
You check the index twice; once when getting the value, once when actually indexing. Remove one or the other.

use std::io;

fn parsed_line<T>() -> Result<T, T::Err>
    where T: std::str::FromStr
{
    let mut element = String::new();
    io::stdin().read_line(&mut element).expect("Failed to read line!");
    element.trim().parse()
}

fn get_element() -> i64 {
    loop {
        println!("Enter the element: ");

        match parsed_line() {
            Ok(num) => return num,
            Err(_) => println!("Invalid number! Try again."),
        }
    }
}

fn get_index(length: usize) -> usize {
    loop {
        println!("Enter the index: ");

        match parsed_line() {
            Ok(index) if index < length => return index,
            Ok(index) => {
                println!("Invalid index! {} is not in range [0, {})! Try again.", index, length);
            },
            Err(_) => {
                println!("Invalid number! Try again.");
            }
        }
    }
}

fn main() {
    println!("Welcome to the Vector application!");

    let mut vec = Vec::new();

    loop {
        println!("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-");
        println!("What do you want to do?");
        println!("1. Clear the vector");
        println!("2. Add element");
        println!("3. Insert element at pos");
        println!("4. Delete an element at index");
        println!("5. Print an element");
        println!("6. Print vector");
        println!("*. Exit");

        let input: u8 = match parsed_line() {
            Ok(num) => num,
            Err(_) => break,
        };

        let length = vec.len();

        match input {
            1 => vec.clear(),
            2 => vec.push(get_element()),
            3 => vec.insert(get_index(length), get_element()),
            4 => {
                vec.remove(get_index(length));
            },
            5 => println!("The element is: {}", vec[get_index(length)]),
            6 => {
                for i in &vec {
                    println!("{} ", i);
                }
            }
            other => println!("{} is not in the range [0, 6]!", other),
        };
    }
}


Caesar and Vigenère ciphers in Haskell, Take 2 (not so simple this time)

Bases

Vigenère has a "bug". That is due to your alphabet management. Strictly speaking, both Caesar and Vigenère advance characters in their respective alphabet. Therefore, your alphabet should be something like

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

and caesar 1 "Z" could lead to "a" without losing the original Caesar's meaning. It's just shifting in the alphabet.

You, on the other hand, have two alphabets:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz

You stay in the respective alphabet while shifting and therefore not lose the case. Up to that point, everything seems fine, right?

Now we come to the mentioned bug:

> vigenere ['A'..'Z'] $ ['a'..'z']
"uwyacegikmoqsuwyacegikmoqs"
> vigenere ['A'..'Z'] $ ['A'..'Z']
"ACEGIKMOQSUWYACEGIKMOQSUWY"

You check the case of the secret, but not of the key. Theoretically, you should check that too:

vigenere, unVigenere :: String -> String -> String
vigenere = cipher helper ' '
  where
    helper k x =
        let base  = if isUpper x then 'A' else 'a'
            kbase = if isUpper k then 'A' else 'a'
        in advanceBy (ord k - ord kbase) base x

Since you use that function so often, a baseOf might be handy:

baseOf :: Char -> Char
baseOf x = if isUpper x then 'A' else 'a'

Note that you don't notice the bug in checks, since you do the same in unVigenere

Caesar knows its key

In caesar, you can just ignore the key, since you already know it:

caesar n = cipher helper ' ' [n]
  where
    helper _ x =
        let base = if isUpper x then 'A' else 'a'
        in advanceBy n base x

More on that later.

Type signatures

While it is possible to write multiple type signatures in a single line, it's usually not done.  If I have a look at unVigenere, I will only see its definition if I miss vigenere line:

unVigenere = cipher helper ' '
  where
    …

Now I have to guess it's type. I have to check cipher, helper's type, and so on. Compare that to

unVigenere :: String -> String -> String
unVigenere = cipher helper ' '
  where
    …

which immediately tells you what type unVigenere has. I don't need to scan the rest of the code anymore.

Remove unused imports

You import toLower, but you don't use it.

Even more general cipher

While your cipher is now rather general, there are still some small things off. First of all, your cipher's only work for ASCII letters, yet the only ignored character is a single space.

We can fix this if we use a predicate instead:

cipher :: (k -> a -> a) -> (a -> Bool) -> [k] -> [a] -> [a]
cipher f p k = helper (cycle k)
  where
    helper _ [] = []
    helper (k:ks) (x:xs)
        | not (p x) = x : helper (k : ks) xs
        | otherwise = f k x : helper ks xs

Together

isAsciiLetter x = isAscii x && isLetter x -- both from Data.Char

we can now say which characters we want to change. But we can make cipher even more generic. At the moment, we need a list of keys before we can actually call cipher. But that prevents certain kinds of ciphers, namely those that work with the value of the previous character. We need some kind of state for that.

Here's where that hint from my last comment comes in:

cipher :: (k -> a -> (k, a)) -> (a -> Bool) -> k -> [a] -> [a]
cipher f p = go
  where
    go _ []     = []
    go k (x:xs) =
      | not (p x) = x : go k  xs
      | otherwise = y : go k' xs
      where
        (k',y) = f k x

What does f now do? Well, given a key and something to encrypt, it gives us the encrypted version and a new key. Here is how you would use it in caesar:

caesar :: Int -> String -> String
caesar n = cipher helper isAsciiLetter n
  where
    helper k x =
        let base = if isUpper x then 'A' else 'a'
        in (k, advanceBy k base x)

Here's a variant that shifts the first character by n, the next by n + 1 and so on:

caesar' :: Int -> String -> String
caesar' n = cipher helper isAsciiLetter n
  where
    helper k x =
        let base = if isUpper x then 'A' else 'a'
        in (k + 1, advanceBy k base x)

We can even do something silly like only cipher every second character:

caesar'' :: Int -> String -> String
caesar'' n = cipher helper isAsciiLetter 0
  where
    helper k x =
      | even k = (k + 1, x)
      | otherwise = let base = if isUpper x then 'A' else 'a'
                    in (k + 1, advanceBy n base x)

However, since our stateful function is now so powerful, we don't actually need isAsciiLetter anymore. If we want to ignore a character, we can just do so in our f:

cipher :: (k -> a -> (k, b)) -> k -> [a] -> [b]
cipher f = go
  where
    go _ []     = []
    go k (x:xs) = y : go k' xs
      where
        (k',y) = f k x

Here's caesar again with the new function:

caesar n = cipher (onlyAscii go) n
  where
    go k x = let base = if isUpper x then 'A' else 'a'
             in advanceBy k base x

The new function onlyAscii is a modifier of f. In this case, it will apply f only on ASCII letters and keep the key and the character otherwise:

onlyAscii :: (k -> a -> (k, a)) -> (k -> a -> (k, a))
onlyAscii f k x
  | isAsciiLetter x = f k x
  | otherwise       = (k, x)

But that's just a demonstration of what you could do with that function. Back to your code. How would we capture vigenere?

vigenere k = cipher (onlyAscii go) (cycle k)
  where
    go (k:ks) x = (ks, advanceBy (ord k - ord (baseOf k)) (baseOf x) x)

where baseOf is left for an exercise. Let us check that it does the same as your previous version:

the key is the cycled String, so it stayed the same
due to onlyAscii, we don't change any non-ASCII letter
if we evaluate go, we have an ASCII letter
we use the first element from the key to cipher the current x, and return the rest from the key for the next application.

Therefore, this vigenere behaves just as yours.

Atbash

This variant of cipher can be used to implement map. Don't believe me? Well, there's a cipher called Atbash. It doesn't need a key, and we could simply implement it like this:

atbashSingle :: Char -> Char
atbashSingle k = chr $ 26 - ord k + 2 * ord (baseOf k)

atbash :: String -> String
atbash = map atbashSingle

But of course, we can use cipher again:

atbash = cipher (ignoreKey atbashSingle) ()

ignoreKey :: (a -> b) -> (k -> a -> (k, b))
ignoreKey f k x = (k, f x)

Which shows that map f == cipher (ignoreKey f) ().

Exercises

That cipher is now harder to use than before. Add some convenience functions like onlyAscii and ignoreKey to make it easier to work with it.
Create a type synonym to make (k -> a -> (k, b)) more user friendly.
There's a Monad that captures this kind of computation. Which is it? Can you write cipher with the help of that Monad?


C++ Template to implement the Factory Pattern

Seems pretty reasonable. I mean, I definitely wouldn't put this in production code because it relies on parsing a class name out of __PRETTY_FUNCTION__, and that's not necessarily guaranteed to keep working in future versions of GCC let alone Clang (and __PRETTY_FUNCTION__ isn't even supported at all on MSVC; they have __FUNC_SIG instead).

In fact, I just tested on Godbolt, and your to_string<T>() function doesn't work at all on Clang. Furthermore, even on GCC, it has trouble with corner cases like A<';'> — https://godbolt.org/z/UNVRQL

Nitpicks on your test code: The rule of thumb I follow is that every polymorphic method should have exactly one of virtual, override, or final (and really nothing should ever have final). So your repetition of virtual is just clutter, to me.

Ditto your use of std::endl (which flushes) versus plain old "\n" (which also flushes if you're outputting to a line-buffered stream such as std::cout). You could save some typing there.

You misspell "labeled" in at least two places: LabledClass and labled_classes. These are implementation details, but it's still important to spell things right so that you can grep for them later.

You pass const std::string_view& id by reference. This is unidiomatic. string_view is already a trivially copyable type, the size of two pointers. It doesn't make sense to force one of those onto the stack just so you can take its address and pass it by reference. Pass string_view by value.

    //checl all products inherit from interface_type
    std::apply([](auto&&... tuple_elem) {
        ((static_check<decltype(tuple_elem.data)>()), ...);
    }, labled_classes{} );

Typo: checl for check. And this is waaay more complicated than it needs to be. Just static_assert the thing you want to assert:

static_assert(std::is_base_of_v<interface_type, products> && ...);

In fact, let's use the idiomatic CamelCase for template arguments, and keep them short:

template<class Base, class... Ps>
[...]
    static_assert(std::is_base_of_v<Base, Ps> && ...);

std::apply([&result, &id](auto&&... tuple_elem) {
    (( tuple_elem.label == id ?
       result = std::make_unique<decltype(tuple_elem.data)>() :
       result ), ...);
}, labled_classes{} );

This complexity is a little more irreducible, but still, doing it all with a tuple and std::apply seems like way more template instantiations than you really ought to have here. What's wrong with a good old-fashioned chain of ifs?

Also, nit: if you're capturing everything by reference, just write [&]. It saves brain cells for the reader of your code.

int dummy[] = {
    ([&]() { if (id == to_string<Ps>()) result = std::make_unique<Ps>(); }(), 0) ...
};

We could even short-circuit as soon as we find the match. That's easy if we leave result null at first; then result will be null if and only if we should still be doing string comparisons.

static std::unique_ptr<Base>
create(std::string_view id, std::unique_ptr<Base> default_type = nullptr)
{
    static_assert(std::is_base_of_v<Base, Ps> && ...);

    std::unique_ptr<Base> result = nullptr;
    int dummy[] = {
        ([&]() {
            if (result == nullptr && id == to_string<Ps>()) {
                result = std::make_unique<Ps>();
            }
        }(), 0) ...
    };
    if (result == nullptr) {
        result = std::move(default_type);
    }
    return result;
}

At this point it's no longer clear why you need struct factory at all. So personally I'd get rid of it, and rename the now-free function create to makeUniqueByName or something.


Checking whether a timestamp is 10 minutes old

Your description says that you want to check whether the searchTimestamp is less than 10 minutes old. Your code does something different, though.

Your code checks whether there's less than 10 minutes between the times (the difference is <= 10 minutes .... If the searchTimestamp is 2 minutes in the future, it will pass the test, if it is 9 minutes in the future, it will pass the test, and if it is 11 minutes in the future, it will fail the test.

Of interest, the math you use does a 10 minute check, but the message says "greater than 5 minutes old."

Your message should say: "timestamp is older than 10 minutes, or more than 10 minutes in the future"

So, changing your code to be what I think it should be, is a lot simpler than you would think.

What you want is for the searchTimestamp to have happened sometime after 10 minutes ago.... this is the way to do it:

private static final int TEN_MINUTES = 10 * 60 * 1000;

then, in your method:

long tenAgo = System.currentTimeMillis() - TEN_MINUTES;
if (searchTimestamp < tenAgo) {
    System.out.println("searchTimestamp is older than 10 minutes");
}


You might break apart the code in separate functions, and create a function that opens and closes a modal with a custom text. I didn't check this code, hopefully you get some ideas for improvement!

$('#saveSubmit').on('click',()=>validateForm())

function validateForm()
{
  var criteria =
  {
    company: $('#company').val(),
    partnercode: $('#partnercode').val(),
    office: $('#office').val(),
    // few more
  }

  let error = ""
  if(criteria.company == "")
  {
    error += "No company specified";
  }
  if(criteria.partnercode == "")
  {
    error += "No partner code specified";
  }

  if(error == "") {
     postData(criteria);
  } else {
     showModal(error);
  }

}

function postData(criteria){
    $.post('process/editUser.php', {criteria:criteria},(data)=>checkData())
}

function checkData(data) {
      if(data.indexOf("Error") >= 0) {
        showModal("error " + data, false);
      } else {
        showModal("data posted!", true);
      }
}

function showModal(content, button) {

    $('#modal').show();
    $('#message').text(content);
    if(button){
        $('#modalbutton').show();
        $('#modalbutton').on('click',() => hideModal());
    }
}

function hideModal {
    $('#modal').hide();
}


Some notes:

def subtract *numbers: While Ruby allows to omit parens, the community consensus is that it makes signatures harder to read.
(numbers.drop 1): When you have to write parens like this, it's a signal that you should just write them in the method call. It looks like Scala or Haskell, not Ruby.
As @Nakilon pointed out, you can drop the drop/first, a fold without an initial value takes the first one.
The identity value for subtraction is 0, let's use it for empty inputs.
xs.inject(initial) { |acc, x| acc.method(x) } -> xs.inject(initial, :method)

We can now write:

def subtract(*numbers)
  numbers.inject(0, :-)
end

  For me, simply moving logic isn't a new style per se, and so conceptually this is nothing new to me.

I don't agree. The steps followed are conceptually the same, yes, but the use of a widely known generic abstraction like reduce/inject has reduced the overall complexity. Of course, one abstraction does not make much difference, but dozens of them change the way a whole program describes what it's doing. And that's what programing is about: building abstractions to reduce complexity.


Prime numbers that are also a prime number when reversed

Name Classes properly.
What is a "Back Wards Prime"?  I have no idea.  I can guess what a Backward Prime is; perhaps you need to change the capitalization of the class!
I'm told that name is dictated by the coding challenge, so you can't change it for your challenge submission; but I'm leaving this comment stand -- the required class name is horrible.
Name variables properly.
This condition is confusing:
    if ( ... && start != rev)

Is this really testing if the reversed value is different from the starting value?  No!  You're using the starting value as the loop variable, and continuously incrementing it with start++;.  Make a new loop variable, and use a proper loop.
    for(long candidate = start; candidate <= end; candidate++) {
        ...
    }

Reducing the work
You appear to have determined that any single digit prime, when read backwards, will not be different than the original, as well as 10 & 12 not being prime, and 11 not being different when reversed.  Therefore, you need only consider values greater than 12.  This optimization should be done before the loop starts,
to avoid the overhead of testing the condition at each iteration.
You should also notice that 2 is the only even prime number, therefore you need not look at any even value.  Instead of moving the start value up by 1, you could skip even values by incrementing by 2.
    if (start < 13)
        start = 13;
    else if (start % 2 == 0)
        start += 1

    for(long candidate = start; candidate <= end; candidate += 2) {
        ...
    }

Avoid creating unnecessary intermediate results
Consider:
new StringBuilder(String.valueOf(start))

You are passing an integer to function which converts it into a string, and then returns that string.  How does that function work?  You then take that resulting string, and pass it to the constructor of the StringBuilder, to copy into the working area.  Do you need that intermediate string?
new StringBuilder().append(candidate)

The StringBuilder.append(long) function takes a long value, and converts it into string characters directly inside the StringBuilder.  This could potentially be faster.  It is even 3 characters shorter, while using a longer variable name, so it is certainly more concise!
Also, consider sb.append(start + " ");. This converts start to a string (again), adds " " to it (internally using another StringBuilder!), and then appends this brand new string to sb.  Instead, you could write:
sb.append(candidate).append(' ');

No intermediate strings needs to be constructed and discarded.
Avoid useless work
        long rev = ...;
        if(start > 12 && isPrime(rev) && isPrime(start) && start != rev)
            ...

If start is not prime, is there any point computing rev?
    for(long candidate = start; candidate <= end; candidate += 2) {
        if (isPrime(candidate)) {
            long rev = ...;
            if (isPrime(rev) && candidate != rev)
                sb.append(candidate).append(' ');
        }
    }

Better.  But what about that candidate != rev?  That looks like a very fast test, and isPrime(rev) is probably much, much slower.
    for(long candidate = start; candidate <= end; candidate += 2) {
        if (isPrime(candidate)) {
            long rev = ...;
            if (candidate != rev && isPrime(rev))
                sb.append(candidate).append(' ');
        }
    }

But wait!  How many times will candidate != rev be false?  Very rarely?  It may not gain anything, and the change may even slow the program down.  Always profile!
Performance at the cost of conciseness
Constructing a new StringBuilder inside the loop can be a costly operation.  You could construct one outside the loop, and use the .setLength(0) method to clear it, for the next iteration:
    StringBuilder temp = new StringBuilder();

    for(long candidate = start; candidate <= end; candidate += 2) {
        if (isPrime(candidate)) {
            long rev = Long.parseLong(temp.append(candidate).reverse().toString());
            if (isPrime(rev) && candidate != rev)
                sb.append(candidate).append(' ');
            temp.setLength(0);
        }
    }

Major optimizations
Reduced search space
How many primes in the ranges 200-299, 400-699, and 800-899 will be reversible primes?  How about in the ranges 2000-2999, 4000-6999, 8000-8999?  How many in the ranges 20000-29999, 40000-69999, 80000-89999?  And so on?
Zero.  A reversible prime cannot start with a 2, 4, 5, 6, or 8, because when reversed, the number will be divisible by two or five, and thus won't be prime.
Implementing this observation in an efficient manner would certainly not make the code concise, but would dramatically speed it up.  Left to student.
Sieve of Eratosthenes
You are potentially doing many, many primality checks using trial division.  It may make more sense to use the Sieve of Eratosthenes to generate a BitSet of prime flags.  Then isPrime(candidate) becomes a simple \$O(1)\$ lookup: prime.get(candidate).
Alternately, if maintaining a BitSet of \$10^{\lceil \log_{10}{end} \rceil}\$ bits is too memory intensive, use the sieve to generate the prime numbers up to \$\sqrt{10^{\lceil \log_{10}{end} \rceil}}\$, and use trial division with just those prime numbers, to avoid pointless trial division by odd composite numbers (9, 15, 21, 25, 27, 33, ...).


Your code is not thread-safe on many levels. Even if you replace regular increments/decrements with methods from Interlocked class, you will still need additional synchronization to make sure, that Callback is not called while Start is running.
Term coroutine has a specific meaning in context of Unity, so you should probably use different word to avoid confusion.
I don't know what is the recommended way of doing these things in Unity. In absence of TPL (I assume Unity still uses .Net 3.5), the easiest solution I can think of, that does not require good understanding of threading, is to return WaitHandles from your async methods:

void Start()
{
    var handles = new List<WiatHandle>();
    handles.Add(MyLogger.LogLastMonth());
    handles.Add(MyParser.ParseFiles());
    //etc...
    ThreadPool.QueueUserWorkItem(_ =>
    {
        WaitHandle.WaitAll(handles.ToArray());

        //at this point you might want to dispose handles
        //if you do not plan to re-use them

        //Make sure this call is thread-safe.
        //If it is not, you will have to dispatch this call back to main thread
        // or set some bool field here, and move the call to Update.
        SceneManager.LoadScene("GameScene");
    });
}


ViewModel constructor with many parameters

why don't you write an abstract factory containing all the references you need?
You can then implement a factory method for your ViewModel creating an instance based on some configuration parameters.
Your client code now doesn't need to know the constructor sintax but just the configuration needed for the right instance.


Loader animation using Custom View in Android

I would avoid "new Timer();" for this use case.
The timer task it changing the paint object on a thread other than the main UI thread, which is very likely to lead to non-deterministic behavior.

I recommend using an ObjectAnimator ( see the Property animation guide )

If you need to support pre-API 11 releases, you can use NineOldAndroids.


Consistency
Sometimes you are using 4 spaces for indentation, sometimes 2. Sometimes you are using vertical whitespace (an empty line) before a method definition, sometimes you don't. Sometimes you have whitespace at the end of a line, sometimes you don't. In one case, you indent a couple of lines just for no discernible reason.
You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.
Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).
In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing IFF you actually want to convey some extra information.
For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a good reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).
Indentation
The community standard for indentation is 2 spaces. For example, your first two lines should look like this:
class InsertionSort
  attr_accessor :arr

Instead of this:
class InsertionSort
    attr_accessor :arr

Furthermore, you should only indent in places where there is a logically nested structure, e.g. a method definition inside a class definition, the body of the method definition, the body of a block, etc. An exception is a continuation of the previous line, this should also be indented.
Here, you are indenting for no apparent reason:
arr[left_ele_moving_right], arr[mover_key] =
arr[mover_key], arr[left_ele_moving_right]

  mover_key -= 1
  left_ele_moving_right -= 1

On the other hand, in the same place, you should indent this:
arr[left_ele_moving_right], arr[mover_key] =
  arr[mover_key], arr[left_ele_moving_right]

To make it clear that the second line is a continuation of the first.
No whitespace at the end of the line
There should be no whitespace at the end of the line. For example, this line:
if arr[key] < arr[to_the_left]

Has a space at the end. That shouldn't be there. And there are two more lines like this.
Also, there are multiple "empty" lines that actually contain only spaces. Again, those shouldn't be there.
No empty line at the end of the file
Your file should end with a single newline. There should not be an extra empty line at the end of the file.
Vertical whitespace
There should be a blank line after every "logical" break. In particular, there should be a blank line after the attr_accessor:
attr_accessor :arr

def initialize(arr)

On the other hand, there should be no empty line directly after the if and the until.
Otherwise, your use of vertical whitespace looks good! Logical steps in the method are clearly separated by empty lines, the code looks "light", not all bunched together with "room to breathe". I like it, well done!
self is the implicit receiver
In Ruby, if you don't explicitly specify the receiver of a message send, the receiver is self. In idiomatic code, you should never explicitly specify the receiver self, unless it is absolutely necessary.
Right now, I can only think of cases, where it would be necessary:

To use an attribute writer method: self.foo = bar.
To use an operator: self + foo

So, this:
self.arr

should just be:
arr

Same here:
while key < self.arr.length

should be
while key < arr.length

Prefer predicate methods over relational operators
You should prefer "speaking" predicate methods such as Numeric#negative? over relational operators such as < 0.
So, this:
left_ele_moving_right < 0

should be
left_ele_moving_right.negative?

Code Formatting
If possible, you should set your editor or IDE to automatically format your code when you type, when you paste, and when you save, and set up your version control system to automatically format your commit when you push, as well as set up your CI system to reject code that is not correctly formatted. If not possible, you should seriously consider using a different editor or IDE, version control system, or CI system.
Here's the result of your code, when I simply paste it into my editor, without doing anything else:
class InsertionSort
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def sort
    key = 1
    to_the_left = key - 1

    while key < arr.length
      if arr[key] < arr[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0

          arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end

      key += 1
      to_the_left += 1
    end

    arr
  end
end

As you can see, simply copying your code into my editor, the editor corrected every single thing I wrote above except one.
Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of the ones I listed.
Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can actually correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".
In particular, running Rubocop on your code, it detects 26 offenses, of which it can automatically correct 23.
Here's what the result of the auto-fix looks like:
class InsertionSort
  attr_accessor :arr

  def initialize(arr)
    @arr = arr
  end

  def sort
    key = 1
    to_the_left = key - 1

    while key < arr.length
      if arr[key] < arr[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?

          arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end

      key += 1
      to_the_left += 1
    end

    arr
  end
end

And here are the offenses that Rubocop could not automatically correct:
Inspecting 1 file
C

Offenses:

insertion_sort.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.
class InsertionSort
^^^^^
insertion_sort.rb:8:3: C: Metrics/AbcSize: Assignment Branch Condition size for sort is too high. [<10, 21, 7> 24.29/17]
  def sort ...
  ^^^^^^^^
insertion_sort.rb:8:3: C: Metrics/MethodLength: Method has too many lines. [17/10]
  def sort ...
  ^^^^^^^^

1 file inspected, 3 offenses detected

Similar to Code Formatting, it is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.
attr_reader vs. attr_accessor
You are never writing to arr, so it should probably be a Module#attr_reader instead of a Module#attr_accessor:
attr_reader :arr

Access Restrictions
arr is not intended to be used by other objects. In fact, it shouldn't be used by other objects! It is private internal state of the sorter object. Therefore, it should not be part of the public API, it should be private:
private attr_reader :arr

Iterators
In Ruby, you almost never use loops. You would normally use at least an low-level iterator such as Kernel#loop, [#each], or Integer#. Really, you want to use higher-level iterators such as Enumerable#map, Enumerable#select, Enumerable#group_by, Enumerable#flat_map, Enumerable#inject, etc.
In this case, we are going to use Integer#times for the outer loop.
def sort
  arr.length.times do |key|
    to_the_left = key - 1

    if arr[key] < arr[to_the_left]
      mover_key = key
      left_ele_moving_right = to_the_left

      until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?
        arr[left_ele_moving_right], arr[mover_key] =
          arr[mover_key], arr[left_ele_moving_right]

        mover_key -= 1
        left_ele_moving_right -= 1
      end
    end
  end

  arr
end

Guard clauses
If you have a case where an entire method or block is wrapped in a conditional, you can replace that with a "guard clause" and reduce the level of nesting.
E.g. this:
def something
  if foo
    bar
    baz
    quux
  else
    42
  end
end

can become this:
def something
  return 42 unless foo

  bar
  baz
  quux
end

After the above change, there is now an opportunity to do that in your code:
def sort
  arr.length.times do |key|
    to_the_left = key - 1

    next unless arr[key] < arr[to_the_left]

    mover_key = key
    left_ele_moving_right = to_the_left

    until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?
      arr[left_ele_moving_right], arr[mover_key] =
        arr[mover_key], arr[left_ele_moving_right]

      mover_key -= 1
      left_ele_moving_right -= 1
    end
  end

  arr
end

Objects
I don't see a particular reason why insertion sort should be an object. It doesn't have any state (having the array to be sorted, as you do, as state is somewhat weird), and it only has a simple single behavior. It would make more sense for a sorting algorithm to be an object if it carries some complex state that persists between different runs of the algorithm.
In a language which supports procedures or functions, this should probably be a function.
In Ruby, I would make it maybe a singleton method of a module, or an instance method of Array. However, I would not name it sort because that method already exists. I would also not name it insertion_sort because that is an implementation detail. I think stable_sort would be a good name, because the fact that insertion sort is stable (if implemented correctly) is an important distinguishing feature that sets it apart from the default sort in Ruby, which is not stable.
So, either something like this:
module Sort
  module_function def stable_sort(arr)
    # …
  end
end

or something like this:
class Array
  def stable_sort
    length.times do |key|
      # …
    end
  end
end

Actually, I am not a big fan of monkey-patching core classes. At least put the method in a separate mixin, so that it is easier to trace where the code is coming from:
module StableSortExtension
  def stable_sort
    length.times do |key|
      # …
    end
  end
end

class Array
  include StableSortExtension
end

But even better would be to make it a Refinement:
module StableSort
  module StableSortExtension
    def stable_sort
      length.times do |key|
        to_the_left = key - 1

        next unless self[key] < self[to_the_left]

        mover_key = key
        left_ele_moving_right = to_the_left

        while self[mover_key] <= self[left_ele_moving_right] && left_ele_moving_right >= 0

          self[left_ele_moving_right], self[mover_key] =
            self[mover_key], self[left_ele_moving_right]

          mover_key -= 1
          left_ele_moving_right -= 1
        end
      end
    end
  end

  refine Array do
    include StableSortExtension
  end
end

Now, the Array#stable_sort method will only exist for code which explicitly activates the Refinement with
using StableSort

Observe:
ary = [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]

ary.stable_sort
# undefined method `stable_sort' for [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]:Array (NoMethodError)

using StableSort

ary.stable_sort

p ary
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

However, I would not do it this way. This stable_sort method mutates its receiver, which is generally not the case for other sort methods in Ruby, and thus very surprising to people.
So, the method should at least dup the receiver and perform its mutations on that duplicate, then return it.
Which brings me to my next point:
Mutation
Your method mutates its argument. That is an absolute no-go. You should never-ever break someone else's toy. An argument that is handed to you, is sacred.
You can fix this by simply adding something like arr = arr.dup at the beginning of the method (or arr = dup for the case where you want to make it an instance method). But I believe we can improve the code more generally.
More generally, your code looks more like FORTRAN, Pascal, or C, with lots of mutation, looping, manual fiddling with indices.
Insertion sort can actually be expressed very elegantly without mutation and without looping, which will not only simplify the code, but also get rid of the mutation problem.
Something like this:
module Enumerable
  protected def ins(element)
    return [element] if count.zero?

    head = first
    return [element] + self if element <= head

    [head] + drop(1).ins(element)
  end

  def stable_sort
    return [] if count.zero?

    drop(1).stable_sort.ins(first)
  end
end

This version does not mutate anything, and it works with all Enumerables (including Enumerators), not just Arrays. (It does not work with infinite Enumerators, though.)
Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files.
Note: I put this at the very end, because there actually are no String literals in your code, so it doesn't matter. Rubocop and some other Linters will complain about this regardless. It's your choice whether you want to get into the habit of always adding it, regardless of whether you use String literals in the code or not. Personally, I always add it, just in case I add a String literal later on.


Automate the Boring Stuff with Python - The Collatz sequence project

One thing you’ll want to learn is not to repeat yourself, when coding.

Consider:

def collatz(number):
    global nextNumber
    if number % 2 == 0:
        nextNumber = number//2
        print(nextNumber)
    else:
        nextNumber = 3*number+1
        print(nextNumber)

You have two identical print statements at the end of both the if and the else clauses.  These can be combined and moved out of the if-else:

def collatz(number):
    global nextNumber
    if number % 2 == 0:
        nextNumber = number//2
    else:
        nextNumber = 3*number+1
    print(nextNumber)

You are printing in your collatz generator function.  If you want the longest sequence starting under 10000000, you’re going to do a lot of printing!  Instead, move the printing responsibility to the caller.  They know whether they want to print it, or just find the length.

Don’t use global to return one value from a function.  (As Aaron states in the comments: "don't use global ever if you can avoid it (which is always)"). Just return the value,

def collatz(number):
    if number % 2 == 0:
        nextNumber = number//2
    else:
        nextNumber = 3*number+1
    return nextNumber

and let the caller assign it to whatever variable they want.

nextNumber = collatz( int(number) )
print(nextNumber)
while nextNumber != 1:
    nextNumber = collatz(nextNumber)
    print(nextNumber)

Reordering, to remove one of the calls to collatz:

number = int(number)
while number != 1:
    number = collatz( number )
    print(number)

Here, you are try to validate the user input is a number:

if integer.isdigit() ==True:
    collatz(int(integer))
    # ... print Collatz sequence ...

while integer.isdigit() != True :
        print('Please try again.')
        integer=input()
        # ... print Collatz sequence ...

Multiple issues here.

You are using an if <expr> followed by a while <not expr> to perform a sort of if ... else ... statement.  If the first input is valid, you print the Collatz sequence in the "then" clause, and the while loop never starts because the condition is immediately False.  If the if <expr> doesn't pass, the while <not expr> catches control and prompts the user for valid input, in a loop.
You are repeating the code to print that Collatz sequence.  And as I said above, (omitted, because *I* am *not* going to repeat myself).
The while loop will fail with a ValueError exception at collatz(int(integer)) if the user enters an invalid input the second time.
.isdigit() tests if the string consists only of "digit" characters, including odd things like the superscript 2 (²), which are not valid for the int(...) method.  So you could still get a ValueError exception even when .isdigit() returns True!  You would need to use .isdecimal() instead.

These issues can be avoiding by using Python's exceptions.  Try to convert the input to an integer, and use the exception to detect invalid input.  Python’s exception handling is exceptional! Learn it. Rely on it:

number = None
while number is None:
    try:
        number = int( input("Enter a number: ") )
    except ValueError:
        print("Try again")

 # ... print collatz sequence here


Scanner is slow compared to BufferedReader but that's not the main bottleneck of this code.
(The speed of parsing the input is hardly ever the bottleneck in programming contests.)

The main bottleneck is that for every position shouted out, you iterate over every soldier. The more positions are shouted out, the more wasteful this gets.

Realize that the captain could shout out a million positions, but all that will matter is the minimum and maximum positions. Let's say there are 7 soldiers,
and the captain shouts out a 1000 numbers, but always between 3 or 4:

  0 1 2 { 3 4 } 5 6

Regardless of how many numbers he shouted, the greatest numbers assigned to soldiers will be:

  4 3 2 { 1 1 } 2 3

This logic will simplify the algorithm:

Find the min and max number shouted by the captain
Iterate over the soldiers (just one pass!), and assign the largest of \$| i - max |\$ and \$|i - min|\$

Simple implementation in Java, given the number of soldiers, and the positions shouted out by the captain:

private int[] solution(int num, int... positions) {
    int[] soldiers = new int[num];
    int max = 0;
    int min = num - 1;
    for (int pos : positions) {
        min = Math.min(min, pos);
        max = Math.max(max, pos);
    }
    for (int i = 0; i < soldiers.length; ++i) {
        soldiers[i] = Math.max(Math.abs(i - max), Math.abs(i - min));
    }
    return soldiers;
}

Unit tests:

@Test
public void testBasic1() {
    assertArrayEquals(new int[]{1, 0, 1, 2}, solution(4, 1));
}

@Test
public void testBasic2() {
    assertArrayEquals(new int[]{3, 2, 1, 1, 2, 3}, solution(6, 2, 3));
}

Last but not least, the original code was poorly formatted and not well decomposed to methods. It's best to separate the parsing and the main logic, to see clearer, so you can focus better on the main implementation. Separating the parsing and the main logic sometimes sacrifices a bit of performance or requires more memory, but in my experience never so much to run out of time / memory. By writing in a clean way you effectively gain more coding time to focus on the real problem, and find the trick to optimize the algorithm.


Hover on list items to change map marker styling

While I wouldn't say your code is inefficiently styled, you can definitely improve the performance of your components.

React performs in a tree format, when a component updates, all their children will attempt to update and potentially re-render. This is part of what React calls the Reconciliation process.

There is a function you can add to your component classes called componentShouldUpdate, which comes with parameters (nextProps, nextState). The idea of this function is to decide whether the component needs to re-render.  You can find some more information on this property here.

For example, if you were to hover and change the colour of one of the markers, the entire list of markers rerenders, but, you can make a check to see whether the specific marker is the one you want to color and so needs to be updated.

These kinds of stops on rerendering means as high as possible in your render trees means you can get the most performance gains.

shouldComponentUpdate(nextProps) { // inside MapMarker.js
    const { props } = this;
    return props.hoveredCardId !== nextProps.hoveredCardId
      || nextProps.hoveredCardId !== props.pageid;
}


Python implementation of a Morse code translator

The first thing that stands out from your code is the big table giving the morse code: it's lengthy, hard to read, and hard to check. (And consequently, it contains two mistakes.) I would write something like this:

from itertools import izip

def pairwise(s):
    """
    Generate pairs from the sequence `s`.

    >>> list(pairwise('abcd'))
    [('a', 'b'), ('c', 'd')]
    """
    it = iter(s)
    return izip(it,it)

morse_encoding = dict(pairwise('''
    a .-    b -...  c -.-.  d -..   e .     f ..-.
    g --.   h ....  i ..    j .---  k -.-   l .-..
    m --    n -.    o ---   p .--.  q --.-  r .-.
    s ...   t -     u ..-   v ...-  w .--   x -..-
    y -.--  z --..

    1 .----   2 ..---   3 ...--   4 ....-   5 .....
    6 -....   7 --...   8 ---..   9 ----.   0 -----

    , --..--  . .-.-.-  ? ..--..  / -..-.   - -....-
    ( -.--.   ) -.--.-  ' .----.  ! -.-.--  & .-...
    : ---...  ; -.-.-.  = -...-   + .-.-.   _ ..--.-
    " .-..-.  $ ...-..- @ .--.-.
'''.split()))

morse_decoding = {v:k for k,v in morse_encoding.iteritems()}

You rebuild the decoding table every time you start a new translation. This seems wasteful: I suggest building it only once, as above.
Not everything needs to be a class. A class is a data abstraction whose instances represent some thing together with methods for operating on that thing. You don't actually have any persistent data here: all you are using the class for is to store the temporary state for a single translation). It makes more sense to structure this code as functions.
Your classes and methods have no docstrings and no doctests. Even a small doctest or two might have caught the mistakes in your Morse code table.
In your determine_lang method, you use a regular expression that matches strings that are not Morse code. It would be simpler to do the test the other way round: to determine that the string is Morse code (because Morse code contains only dots, dashes and spaces). Python's sets provide a clear and concise way to express this test:

def is_morse_code(s):
    """
    Return True if the string `s` resembles Morse code (contains only
    dots, dashes and spaces), False otherwise.

    >>> is_morse_code('... --- ...')
    True
    >>> is_morse_code('abc')
    False
    """
    return set(s) <= set('.- ')

The original challenge may have referred to "English", but there's nothing actually English-specific about Morse code. It translates any language that can be written in the Latin alphabet. So I would prefer names that didn't presume that we were translating English.
When a character cannot be encoded or decoded, you print a message to inform the user. The usual approach in Python is to raise an exception.
Your translation code seems very complex for what it is doing. All you need to do is split the string into words, split each word into letters, translate each letter, join the translated letters into words, and then join the translated words into the result. This can be done neatly and concisely using split and join and a couple of loops:

def morse_encode(s):
    """
    Encode the string `s` in Morse code and return the result.
    Raise KeyError if it cannot be encoded.

    >>> morse_encode('morse code')
    '-- --- .-. ... .  -.-. --- -.. .'
    """
    return '  '.join(' '.join(morse_encoding[l] for l in word)
                    for word in s.lower().split(' '))

def morse_decode(s):
    """
    Decode the string `s` from Morse code and return the result.
    Raise KeyError if it cannot be decoded.

    >>> morse_decode('-- --- .-. ... .  -.-. --- -.. .')
    'morse code'
    """
    return ' '.join(''.join(morse_decoding[l] for l in word.split(' '))
                    for word in s.split('  '))


I would suggest moving out your animation loop to a separate system, and that your object at least have a render and update method (sort of an interface). That way, you have a centralized way to control the render loop, you're objects don't have to worry about the render loop while keeping the knowledge of how to render and update inside the object.

let objects = [];

// Render loop
function renderLoop(){
  requestAnimationFrame(renderLoop);
  objects.forEach(object => object.update());
  objects.forEach(object => object.render());
}

// Add objects
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());
objects.push(new ExplodeLayer());

// Start loop
renderLoop();

explodeLayer is a constructor. It's a convention that constructors have the first letter of words in capital letters. It should be ExplodeLayer.

Also suggesting you move requestAnimationFrame call as the first call in the render loop. That way, scheduling the next frame won't be blocked by slow code before it and you're assured that the next callback is ready to be called regardless of slowdowns in code.

this.updatePosition = function(index) {
  this.elem[index].style.left = this.particle[index].x + 'px';
  this.elem[index].style.top = this.particle[index].y + 'px';
}

This is probably better when done in canvas for better performance, but I understand that there is an itch to do it in the DOM :D However, you can further improve performance by using CSS3 transforms, specifically the translate3D transforms. They have the advantage of being hardware-accelerated (the GPU does the work), making them smoother than normal.

Lastly, your explode layer is... a layer. It's comprised of particles. Suggesting you create a separate class for a single particle. That way, your explode layer can focus on being a layer (calculating position, managing particles, etc.), while particles can focus on how an individual particle renders (textures, colors etc.).


As far as readability goes, maybe you'd like to add an arg1 arg2 arg3 -- result1 result2 type of comment to each function? So we know what was on the stack before invoking, and what we expect to find afterward? Almost equivalently, you might show a unit test invoking your function and verifying the result.


Retrieve all parents, all possible children, sorted and with their "depth"

What I needed was the pipe operator! It was of course just doing what I was telling it to - pushing the results of itself onto the current element in the array. Only when the rootsections loop completes does it start a new array element.

The 'pipe' (|) is a different array merge operator which appends what's to the right of it onto the end of the array on the left.

all_sections | fetch_all_sections(standard, section, depth)

The pipe operator changed how depth worked so instead I just counted the number of "." in sortlabel:

depth = section.sortlabel.split('.').length -1

The full method:

# Calls itself for each section recursively to fetch all possible children
def fetch_all_sections(standard, section = nil, depth = 0)
  all_sections = []

  if section.nil?
    rootsections = standard.sections.sorted
    if ! rootsections.nil?
      rootsections.each_with_index do |section, i|
        depth = section.sortlabel.split('.').length - 1
        all_sections << fetch_all_sections(standard, section, depth).first
      end
    end
  else

    all_sections << {:id => section.id, :sortlabel => section.sortlabel, :title => section.title, :depth => depth}

    section.children.sorted.each do |section|
      all_sections | fetch_all_sections(standard, section)
    end
  end

  return all_sections
end

If someone seeing this is considering something similar but starting from scratch, consider an Active Record Nesting gem: https://www.ruby-toolbox.com/categories/Active_Record_Nesting

UPDATE: I added .first within the rootsections loop. This is because I inadvertently built an array of arrays, each containing 1 hash. What I wanted was an array of hashes. Much easier retrieval now!


Ruby solution to Project Euler Problem #4: Largest palindrome product

Let's start with something small:

def isPalindrome(n)
  n == n.to_s.reverse.to_i
end

How do I know if a number is a palindrome?

Convert it to a string.
Produce the reverse of that string.
Convert the reversed string to a number.
Compare the numbers for equality.

As yourself: why did we need to do the last two steps?  We could have said:

Convert it to a string.
Produce the reverse of that string.
Compare the strings for equality.

and skipped the "convert to integer" step entirely.

Next small thing. I've removed every line of your program that does not use variable found:

found = false
while (x > 100 && !found)
  while (y > 100 && !found)

See any problems with that code? Because I don't see anywhere that it is set to true and therefore it will always be false. I'm not sure why a variable that is always false is of use to you.

Next thing: You check all pairs: (999, 999), (999, 998), ... (999, 101) and then start over again with (998, 999).  But you already checked (998, 999) when you checked (999, 998)! You don't need to start y at 999.  It suffices to start y at x.  Then you only check each pair once instead of checking the vast majority of them twice.

Next thing: If you find an (x, y) pair that is a palindrome, you don't need to check (x, y - 1); even if it is a palindrome, it will be smaller. Probably this is what you were trying to do with your "found" variable, but you never wrote the logic correctly.

Next thing: Remove all that print-debugging trace. If you need to debug your program, use a debugger.


Binary search use in simple guessing game

I'm thoroughly puzzled by your use of the response variable.

The condition for the while-loop is response != 'Y'.  The first time through, response is an uninitialized variable, containing any imaginable int value.  So, the behaviour of your program is undefined.

response is an int.  Why are you comparing it to 'Y'?  That makes 89 a special number.

If we make it inside the loop, you ask the user to enter a character 'L', 'H', or 'Y', but actually read an integer.  If you actually enter one of those three characters, scanf() will fail to read an integer; your program will consider the input to be invalid, and it will loop forever, since scanf() will immediately fail again, etc.  There are only two ways to terminate your program: CtrlC or by typing 89Enter at the prompt.

Then you call toupper() on the integer; the toupper() function only makes sense for translating a letter to its uppercase counterpart.  (The toupper() function takes an int instead of a char only because it is meant to support EOF, or -1, as a value.)

Then, in the switch block, you have magic numbers 72, 76, and 89.  Magic numbers should not exist in your code.

Your first printf() call is also wrong.  It should be

printf("Okay, let's start. Is it %d?\n", guess);

since &guess would print the address of the guess variable instead of its contents.  Your compiler should have warned you about that mistake.  You should have heeded the warning, as well as tested your code.


How can I make this piece of code more secure?

I come back to this at the end, but if this answer is tltr, basically, I end up suggesting not to write your own DB abstraction layer, It's been done before, way better than you're doing it now.
That doesn't mean the rest of this answer doesn't contain valuable tips on how to improve your code quality in general, so please do read through it:

For a start, when you're using an object to contain data, that object is responsible for that data's integrety, not the user of the object. By that I mean: if I am to use your object, you must be able to ensure that, regardless of how I use your object (I may forget the strip_tags call, for example) the input won't contain any markup.
The only way to do that is to define setter methods that take care of this:

class DataObjects_User
{
    private $name = null;
    public function getName()
    {
        return $this->name;
    }
    public function setName($name = null)
    {//setting null ~= unsetting
        if ($name !== null && !is_string($name))
        {
            throw new InvalidArgumentException('Name must be string');//don't hush-up errors
        }
        $this->name = is_null($name) ? $name : strip_tags($name);
        return $this;
    }
}

Your code appears to require me to set a creation date manualy. Why? Why not create a field in the table that has NOW() as a default value? or an ON UPDATE CURDATE clause? wouldn't that be easier?
even so, you could omit this, by simply adding a constructor to the object above, too:

class DataObjects_User
{
    private $name = null;
    private $created = null;
    public function __construct()
    {
        $this->created = new \DateTime;//I prefer to keep everything OO
    }
    public function getCreated($format = 'Y-m-j H:i:s')
    {//use class constants for the format
        if ($format === false)
        {//allow user to get the object itself?
            return $this->created;
        }
        return $this->created->format($format);
    }
    public function setCreated(DateTime $obj = null)
    {//again, null to unset
        $this->created = $obj;
        return $this;
    }
    public function getName()
    {
        return $this->name;
    }
    public function setName($name = null)
    {//setting null ~= unsetting
        if ($name !== null && !is_string($name))
        {
            throw new InvalidArgumentException('Name must be string');//don't hush-up errors
        }
        $this->name = is_null($name) ? $name : strip_tags($name);
        return $this;
    }
}

You may be wondering why I keep adding the option of setting the properties to null... well, that's perfectly simple: If these objects represent data in the DB, it's not unlikely you'll find yourself using these objects to build queries. If some of these properties have default values, or values that are irrelevant to a query, you can uset them, by passing null (or nothing, since it's the default value) to their setters.

$user = new DataObjects_User();//constructor sets created date!
$user->setName('Bobby');
    ->setCreated();//unset created

Now you can pass $user to a generic createBind() method. Besides, if you have a couple of these objects, just create an interface/abstract class if only for typehinting, and extend all dataobjects from that:

class DataObjects_User extends DataObjects_Abstract{}
//the createBind method then could look like this:
public function createBind(DataObjects_Abstract $model)
{
    $getters = get_class_methods($model);
    $bind = array();
    foreach($getters as $getter)
    {
        if (substr($getter,0,3) === 'get' && method_exists('s'.substr($getter,1), $model))
        {//getter and setter exist, this is a property
            if ($model->{$getter}() !== null)
            {//avoid null properties
                $bind[':'.substr($getter,3)] = $model->{$getter}();
            }
        }
    }
    return $bind;
}
//when applied to $user
var_dump(
    $queryObject->createBind(
         $user->setName('Bobby')
              ->setCreated()
    )
);

That should yield:

array(':name' => 'Bobby');

Which makes life a lot easier when using prepared statements, doesn't it?

since I'm on the subject: When using PDO, you don't have to bother with all those deprecated mysql_real_escape_string calls anymore... just use prepared statements. If you can't, then learn to use them. It's not that hard, and an awful lot safer at any rate than what you have now.

Basically, with the $user object, being passed through the createBind method, all you need to do is:

$bind = $queryObject->createBind(
     $user->setName('Bobby')
          ->setCreated()
);
$fields = array_keys($bind);
$query = 'SELECT * FROM tbl WHERE ';
foreach($fields as $field)
{
    $query .= substr($field,1) .' = '.$field;
}
$statement = $pdoInstance->prepare($query);
$statement->execute($bind);

This is just as secure as your code, if not more secure. The downsides:

the properties of your objects have to be the same as the field-names in your db
data and logic are too tightly coupled here...

Lastly, I'd like to point that, even though it's not something that'll leave a gaping hole in your app's security, storing passwords the way you are doing is not done. Common practice is to store password-hashes, not encrypted passwords. Encryption, as the word implies, is a two way deal: anything that is encrypted can be decrypted. A hash-function, by its very nature is a one-way algorythm: A hash can't be de-hashed (well, it can be brute-forced, but even then, collisions, salt and time-complexity make that less viable to would-be hackers). Instead of encrypting the pass, try this, inside the user model:

private $passHash = null;
const PASS_SALT = '$0m3_r@Nd0M_5tr1n9';
public function setPassHash($password)
{
    $this->passHash = hash('sha256', self::PASS_SALT.$password);
    return $this;
}

But that's just on the data model. Any abstraction layer you're writing to query the DB isn't going to cut it as your app grows. As I've stated previously, in other answers:

On the whole, I'd suggest you use Doctrine entities, though. ORM's aren't very inviting at first, but once you get the hang of how easy it is to distil tables from objects and objects from tables (yes, it works both ways), you haven't got anything to worry about.