Template for endianness-free code, data always packed as BIG-Endian

Your code is good, except for two methods : operator unsigned() const and self_t& operator=(unsigned m). They are too complex, and by just looking at them, it is far from clear what they are doing.

First, you can add new values to your enum :

enum {
    lastBit = firstBit + bitSize - 1,
    mask = (1 << bitSize) - 1,
    firstBitIndex = 8 - (firstBit & 7),                         // change to proper name
    nameThisValueProperly = (7 - (lastBit & 7)) & mask,         // change to proper name
};

First modify your operator unsigned() const to this :

inline operator unsigned() const
{
    const uchar *arr = selfArray();
    const uchar *p = arr + firstBit / 8;

    unsigned result = CalculateSomeValue( p );

    return (result >> nameThisValueProperly );
}

// name this method properly
inline unsigned CalculateSomeValue( const uchar *p ) const
{
    int i = firstBitIndex;
    unsigned result = *p;

    while (i < bitSize)
    {
        result <<= 8;
        result |= *(++p);
        i += 8;
    }

    return result;
}

Of course, you need to put proper names both for enum values and method names, so when someone looks into this code says "Aha, that is what is is doing". This way, you can easy increase code clarity.

Also, by making method smaller, you can easily test them.

More about this method, you can read in Clean code by Robert Martin.

You can do something similar for the self_t& operator=(unsigned m). Break it up, until you find it clean.


Caml light and finding the prime factors

I guess that I should not be giving you an answer, but guide you. So, one general remark that I have: stylistically, it would be preferable to see you start with

let largest_factor n =
    let rec aux_factor d n =
        ...
    in
        # some expression involving to aux_factor

The idea is that your solution function should be an expression of your problem and nothing else, so largest_factor number, not largest_factor number what_is_that.

Note that I am talking OCaml here, not sure if the pseudosample I wrote is cromulent Caml Light.


Evaluating a polynomial at a given value of x and n

By following Horner's Method only n multiplications are needed.

#include <stdio.h>

int main()
{
   // n is the deg of polynomial
   // x is the value of polynomial for which it is to be evaluated
   int x=0,n=0,A[10],b,i;

   printf("Enter value of n,x \n");
   scanf("%d %d",&n,&x);

   //Taking coefficient values
   printf("Enter the coeficients\n");

   for(i=0;i<=n;i++) scanf("%d",&A[i]);

   for(i = n - 1,b = A[n];i >= 0;i--) b = b*x + A[i];

   printf("\nSum of polynomial is %d\n",b);

   return 0;
}


Starting with:

return (!value || value == undefined || value == "" || value.length == 0);

Looking at the last condition, if value == "", it's length MUST be 0. Therefore drop it:

return (!value || value == undefined || value == "");

But wait! In JS, an empty string is false. Therefore, drop value == "":

return (!value || value == undefined);

And !undefined is true, so that check isn't needed. So we have:

return (!value);

And we don't need parentheses:

return !value

Q.E.D.


The Trie approach might be overkill for this question.  I think that a plain (ordered) std::set (or std::multiset) would be adequate.  The set's lower_bound() member takes you directly to the first entry with the specified substring.  From there, we can either count linearly, or use lower_bound again with a new key created by adding 1 to the last character, then just return the iterator difference.
I'd certainly consider writing separate add() and find() functions instead of plonking all the code in that big if/else.  If nothing else, it makes the unit tests easier to write.


As mentioned in the comments, Ruby already has a very nice Set class in its standard library. But, as also mentioned, there's still code to review here.

So, review-wise, a few things that caught my eye:

@cs. Sorry, but I'm a stickler for descriptive names. I'm guessing this is supposed to be short for "CustomSet", but that's the name of the class, and the variable is just an array. Something like @members might make more sense.
I'd also add a private accessor method for the variable. Call it members, and replace (almost) all instances of @cs with members. By accessing it though a method, you decouple your code better.
You constructor is unnecessarily complex. Just duplicate the input array:

  def initialize(list = [])
    @cs = list.dup
  end

#to_list. "List" isn't a thing in Ruby. Array is a thing though, and the conventional name for this sort of method is to_a. However, you don't want to return your instance variable directly! If you do, it can then be modified externally. It also allows external code to keep references, and all manner of other stuff. So return a dup instead.
#empty is self-modifying. It should either be empty! to indicate its effect, or it should be called clear (to match the so-named method on Array). The method should probably also just call clear on the internal @cs array instead of replacing it.
#member? should perhaps be aliased (or renamed) as #include? (again to match Array)
#each can be shortened to just

def each(&block)
  @cs.each(&block)
end

#put could be written more idiomatically using include?:

def put(item)
  @cs << item unless @cs.include?(item)
end

Or you can push the new item immediately, and just call uniq! afterward. Or you can use a hash (i.e. instance of Hash - not to be confused with the method discussed later), and use its built-in duplicate handling, e.g.:

def put(item)
  @cs[item.hash] = item # assumes @cs is a hash
end

Since Ruby 1.9, hashes are ordered too, so in effect it'd be little different from using an array internally.
#difference, #intersection, and #union can be handled via the internal arrays, e.g.:

def difference(other)
  self.class.new(@cs - other.to_a)
end

def intersection(other)
  self.class.new(@cs & other.to_a)
end

def union(other)
  self.class.new(@cs | other.to_a)
end

And as you can see from the above, those methods should probably be aliased (or renamed) as -, &, and | respectively.
@cs.delete(n) if index(n) - there's no need for the if guard. It just requires an extra lookup to do, and slows things down. The call to delete will work fine on its own.
#== and #eql?. Here you may again use the fact that both self and other have array representations that already support all this:

def ==(other)
  self.class == other.class && @cs == other.to_a
end

I'd include a dup method for cloning a set. E.g.:

def dup
  self.class.new(@cs)
end

I'd include the Enumerable module to get a bunch of methods "for free". All that's required on your class is that it has an #each method - which is does.

Now, about your #hash. Your method is simply flawed, because it doesn't use reduce correctly. Your method is currently equivalent to (:+).hash (or, if the set's empty: :+). You're simply using reduce wrong.

reduce takes an initial value and a block. The block, in turn, receives two arguments: The value carried over from the previous iteration (or the initial value, first time 'round), and the current element in the array. For instance:

sum = [1, 2, 3].reduce(0) do |sum_so_far, item|
  puts "Sum so far: #{sum_so_far}"
  puts "Current value: #{item}"
  sum_so_far += item # this is returned and becomes sum_so_far in the next iteration
end
puts "Final sum: #{sum}"

which'll print

Sum so far: 0
Current value: 1
Sum so far: 1
Current value: 2
Sum so far: 3
Current value: 3
Final sum: 6

As you can hopefully tell, your use of reduce is very different.

What you seem to be trying to do is either

@cs.reduce(0) { |sum, member| sum += member.hash }

or

@cs.map(&:hash).reduce(0, &:+)

which are functionally identical ways of doing the same thing: Sum the hash values of each object in the set.

However, this approach seems flawed to me, since you'd risk conflicts. A set with just one member might have the hash 7 (the member's hash), and a set with two members might also have a hash of 7 (because the members' hashes are 3 and 4). That's no good.

Honestly, I'd consider simply not implementing #hash unless you have very good reason to do so. You have ==/eql? to check for equality, so why bother with hash? Easier to let the default implementation handle that.


PEP-8

Class names should be CapWords, so instead of rectangle you should have Rectangle.
Commas should be followed by 1 space.  You've mostly followed this, except in s1 = rectangle({'p1': (1,1), 'p2': (2,2)})

Bugs

The formula for "area" is not twice the sum of width & height.
I don't know what "surrounding" is, but the formula for perimeter is not width times height.
The midpoint (centre?) of a rectangle should be within the bounds of the rectangle.  Consider the rectangles with corners (10, 10) and (12, 12).  The centre would be (11, 11), not (1, 1) as calculated.

Awkward initialization

This code:

        names = list(dct.keys())
        coords = list(dct.values())
        start = [names[0], coords[0]]
        end = [names[1], coords[1]]
        self.start = start
        self.end = end

relies on the dictionary's ordering of keys.  It can break in Python 3.6 and earlier (CPython 3.5 and earlier).  It does not enforce the key names p1 and p2; any two keys will work.  And self.start[0] and self.end[0] are never used, so storing the key names in these entries is unnecessary.

The code could simply and safely read:

         self.start = dct['p1']
         self.end = dct['p2']

with suitable modifications of the usage of self.start and self.end.

Class with no methods

A class should have methods.  Without any methods, you'd be better off with a namedtuple for constant data, or a dict for mutable data.

So let's give your class some methods:

    def width(self):
        return self.end[0] - self.start[0]

    def height(self):
        return self.end[1] - self.start[1]

As mentioned by Peilonrayz, you may wish to use abs(...) here.

You can use these methods externally:

print('width: ', s1.width())
print('height: ', s1.height())

as well as in other members of this class:

    def area(self):
        return (self.width() + self.height()) * 2    # Note: Formula is still incorrect

An Over-Engineered Solution

Do not submit this as your home-work solution!  You would likely fail or be expelled!  This illustrates some advanced concepts like the @dataclass and the NamedTuple, type hints and the typing module, as well as read-only @property attributes, a @classmethod, and """docstrings""".  You may find these interesting to study in your free time.

from typing import NamedTuple
from dataclasses import dataclass

class Point(NamedTuple):
    x: float
    y: float

@dataclass
class Rectangle:
    """A class for calculations on a Rectangle"""

    p1: Point
    p2: Point

    @classmethod
    def from_dict(cls, dct):
        """
        Constructs a Rectangle from a dictionary with "p1" and "p2" keys.
        These keys must contain a tuple or list of two numeric values.
        """
        return Rectangle(Point._make(dct['p1']), Point._make(dct['p2']))

    @property
    def width(self):
        """
        Computes the width of the rectangle.
        """
        return abs(self.p2.x - self.p1.x)

    @property
    def height(self):
        """
        Computes the height of the rectangle.
        """
        return abs(self.p2.y - self.p1.y)

    @property
    def area(self):
        """
        Incorrectly computes the area of the rectangle.
        """
        return (self.width + self.height) * 2     # Note: still the incorrect formula

s1 = Rectangle.from_dict({'p1': (1,1), 'p2': (2,2)})
print('point one: ', s1.p1)
print('point two: ', s1.p2)
print('width: ', s1.width)
print('height: ', s1.height)
print('area: ', s1.area)

Output:

point one:  Point(x=1, y=1)
point two:  Point(x=2, y=2)
width:  1
height:  1
area:  4


How can I optimize this combination method?

I'd try to go with a different approach. At the moment you're evaluating all the possible combinations, while I think it could be useful to evaluate only the meaningful ones. To do that I'd start with a two phase approach. First you can generate all the valid fleets and then you can sort them using a comparator that takes into account their Range/Variance.

This is the code you can use to generate all the possible fleets:

private static IEnumerable<Fleet> PossibleVoyages(IList<Captain> captains, IList<Crew> crews, int voyagesToPrepare, Fleet fleet)
{
    var possibleVoyages = new List<Fleet>();
    if(voyagesToPrepare == 0)
    {
        possibleVoyages.Add(fleet);
    }
    if(captains.Count < voyagesToPrepare || crews.Count < voyagesToPrepare)
    {
        // We cannot find any valid solution here
        return possibleVoyages;
    }
    else
    {
        foreach(var captain in captains)
        {
            foreach(var crew in crews)
            {
                var newFleet = fleet.Add(CreateShip(captain, crew));
                possibleVoyages.AddRange(
                    PossibleVoyages(
                        FreeCaptains(captains, newFleet),
                        FreeCrews(crews, newFleet),
                        voyagesToPrepare - 1,
                        newFleet));
            }
        }
    }
    return possibleVoyages;
}

I have not implemented the methods FreeCaptains, FreeCrews, and CreateShip but they should be obvious. Fleet act as an immutable collection of ships.

Once you get all the possible voyages you can just sort them using a comparator and Linq sort.

I'm not sure this is going to help much, but it is worth giving it a try.
A possible way to improve it is to keep track of the best fleet we generated so far and to just compare it with every fleet we generate instead of doing all the comparisons at the end. This could possibly prune a lot of solutions once you find a good one and it is definitely worth trying.


Mixing in-class initialization and initializer lists

Well, the first example is bad for a simple reason: It contains code which is never used, as none of the in-class-initializers are used by any constructor.

The second one is fine, using in-class-initializers for any initializations multiple constructors share (you don't even have to decide between multiple choices).
One can argue about extracting the constant initializers for the other three members out of the single constructor having one for each respective one, but that's debatable.

There's only one more criticism of your code:
The last single-line-comment is too long, you should have split it.


prompt("Please enter a decimal number");

is a little confusing to me. I thought you wanted a number with a few decimal digits on it.

It might make more sense to say "Please enter a base 10 number"

You are a little incosistent in how you turn your string numbers into number numbers.

In the beginning, you use parseInt:

var binConvert = parseInt(decimal, 10).toString(2);

In the end, you use parseInt:

alert(parseInt(makeNumber, 2));

But in the middle, you use Number:

var makeNumber = Number(srj);

It is better to be consistent and stick to one function (in my opinion, you should use parseInt).

If you take the above advice in using parseInt, you can then get rid of the last parseInt call like so:

var makeNumber = parseInt(srj, 2); // I moved the parseInt call up here

//convert back to decimal
alert(makeNumber);

This might just be me, but your comments are a little confusing.

Here, you wrote:

//convert back to decimal
alert(parseInt(makeNumber, 2));

Aren't you technically converting to binary? (The radix parameter of parseInt is 2).


Review on my multiple JQuery Slider on a page

In my option your code has two problems:

You unnecessarily fill your HTML with empty elements which you could just create in your script. Changing that would remove the necessity for the rel attribute.
more importantly (even if there are people that may disagree), you have unnecessarily made your form dependent on JavaScript. It would be much better to have select elements in your HTML, which you can replace with sliders. That way even users without JavaScript can use your form unrestricted.

I've written an example how I would do it:

$(".ui_slider select").each(function() {
    var select = $(this); // Cache a refernce to the current select
    var sliderDiv = $("

"); // create a div for the slider
    var displayLabel = $(""); // create a span to display current selection

    if (select[0].selectedIndex < 0) // Make sure that an item is selected
        select[0].selectedIndex = 0;

    select
        .hide() // hide the select
        .before( // Insert display label before the select
            displayLabel
               .text(select.find("option:selected").text()) // and set it's default text
        )
        .after(
           sliderDiv // Insert the silder div after the select
               .data("select", select) // store a reference to the select
               .data("label", displayLabel) // store a reference to the display label
               .slider({
                    max: select.find("option").length - 1, // set to number of items in select
                    slide: function(event, ui) {
                        var select = $(this).data("select");
                        select[0].selectedIndex = ui.value; // update the select
                        $(this).data("label").text( // Update the display label
                            select.find("option:selected").text()
                        );
                    }
               })
        );
});

HTML (repeat as needed):

    Overall:
    <select name="overall" id="overall">
        <option value="0">Not Good</option>
        <option value="1">OK</option>
        <option value="2">Average</option>
        <option value="3">Above Average</option>
        <option value="4">Excellent</option>
        <option value="5">Outstanding</option>
    </select>

Working sample: http://jsfiddle.net/YfqCx/2/


Beginner code for a Rock, Paper, Scissors game in Python

The code repetition could be cleaned up quickly by replacing your seven if blocks with something like:

print("Your opponent played: " + str(opponentMove) + ".")

if player1Move == opponentMove:
    print ("Tie!" + " Please go again.")
elif (player1Move == "Rock") and (opponentMove == "Paper"): # rock loses to paper
    opponentScore = opponentScore + 1
elif (player1Move == "Paper") and (opponentMove == "Rock"): # paper beats rock
    player1Score = player1Score + 1
elif (player1Move == "Paper") and (opponentMove == "Scissors"): # paper loses to scissors
    opponentScore = opponentScore + 1
elif (player1Move == "Scissors") and (opponentMove == "Paper"): # scissors beats paper
    player1Score = player1Score + 1
elif (player1Move == "Scissors") and (opponentMove == "Rock"): # scissors loses to rock
    opponentScore = opponentScore + 1
elif (player1Move == "Rock") and (opponentMove == "Scissors"): # rock beats scissors
    player1Score = player1Score + 1
else:
    print ("Invalid choice")

print("Your score: " + str(int(player1Score)))
print("Your opponent's score: " + str(int(opponentScore)))

This eliminates all of the continue statements.  Keeping with the same approach you have started, perhaps splitting into cases where player1 wins vs opponent wins is the next improvement:

if player1Move == opponentMove:
    print ("Tie!" + " Please go again.")
elif ((player1Move == "Rock") and (opponentMove == "Paper")) or
     ((player1Move == "Paper") and (opponentMove == "Scissors")) or
     ((player1Move == "Scissors") and (opponentMove == "Paper")):
    player1Score = player1Score + 1
elif ((player1Move == "Paper") and (opponentMove == "Scissors")) or
     ((player1Move == "Scissors") and (opponentMove == "Rock")) or
     ((player1Move == "Rock") and (opponentMove == "Paper")):
    opponentScore = opponentScore + 1
else:
    print ("Invalid choice")


Movement function for a Sokoban game using Python

strings

I seems your grid is a nested list of strings. It would be clearer, if you change that to Enums

from enum import Enum

class Tiles(Enum):
    WALL = '0'
    PLAYER = "*"
    BOX = '£'
    EMPTY = '.'

so you can do something like this:

w = Tiles.WALL
e = Tiles.EMPTY
b = Tiles.BOX
p = Tiles.PLAYER
grid = [
    [w,w,w,w,w],
    [w,e,e,e,w],
    [w,e,e,b,w],
    [w,b,b,p,w],
    [w,e,e,b,w],
    [w,e,e,b,w],
    [w,e,e,e,w],
    [w,w,w,w,w],
]

getter and setters

Python does not have the Java tradition of setters and getters. If you want to work with a calculated property, of protect a property, you can use @property. This can work like this

class Boxes:
    def __init__(self, row, ...):
        self._row = row
        ...

    @property
    def row(self):
        return self._row

and so on for char and column

double work

The position of the Boxes and the player is kept both in the MapGrid , and in PlayerMan and Boxes. This is double work, and prone to errors.

Now to move something, you have to adapt it both in the grid (.despawn and .spawnXXX and on the PlayerMan and Boxes, resulting in a lot of unnecessary code.

All you really need to capture the state of the board is this:

class SokobanGrid():
    def __init__(self, grid, position, strength=None):
        grid = list(map(list, grid))  # make a copy of the grid
        assert grid[position[0]][position[1]] == Tiles.PLAYER
        num_players = sum(
            sum(tile == Tiles.PLAYER for tile in row)
            for row in grid
        )
        assert num_players == 1

        self._grid = grid

        self._dimensions = len(grid), len(grid[0])
        self.position = position
        self.strength = strength

    def copy(self):
        return SokobanGrid(self._grid, position=self.position)

displayOnScreen()

instead of making a method that returns a string representation of the board, you can define __str__ and/or __repr__

    def __str__(self):
        rows = (
            f'x{idx}: ' + ''.join(tile.value for tile in row)
            for idx, row in enumerate(self._grid)
        )
        header = ' ' * 4 + ''.join(map(str, range(self._dimensions[1]))) + '\n'
        return header + '\n'.join(rows)

you can omit the position parameter, and go look for it yourself.

g = SokobanGrid(grid=grid, position=(3, 3))
print(g)

    01234
x0: 00000
x1: 0...0
x2: 0..£0
x3: 0££*0
x4: 0..£0
x5: 0..£0
x6: 0...0
x7: 00000

The interactions with the tile then go like this:

    def tile(self, x, y):
        return self._grid[x][y]

    def iswall(self, x, y):
        return self.tile(x, y) == Tiles.WALL

    def isbox(self, x, y):
        return self.tile(x, y) == Tiles.BOX

    def isempty(self, x, y):
        return self.tile(x, y) == Tiles.EMPTY

    def set_tile(self, x, y, tile):
        self._grid[x][y] = tile

    def swap_tiles(self, old, new):
        old_tile = self.tile(*old)
        new_tile = self.tile(*new)
        self.set_tile(*old, new_tile)
        self.set_tile(*new, old_tile)

moving

Instead of a move method for each direction, you can make a generic one, that accepts a direction. The directions can be an Enum, with a value the change in coordinates it entails (UP is (-1, 0), because row 0 is the top row)

class Direction(Enum):
    UP = (-1, 0)
    DOWN = (1, 0)
    LEFT = (0, -1)
    RIGHT = (0, 1)

The first helper method yields all the moves in a certain direction until it hits a wall (not included) or an empty spot (included)

    def _moves(self, Direction):
        x, y, = self.position
        x_max, y_max = self._dimensions
        dx, dy = Direction.value
        while 0 <= x < x_max and 0 <= y < y_max:
            if self.iswall(x, y):
                return
            yield x, y
            if self.isempty(x, y):
                return
            x, y = x + dx, y + dy

the second helper method checks whether the player can move in a certain direction:

    def can_move(self, direction):
        for boxes, position in enumerate(self._moves(direction)):
            if self.isempty(*position):
                return True
            if self.iswall(*position):
                return False
            if self.strength and boxes > self.strength:
                return False
        return False

This raises a class IllegalMove(Exception): pass to signal to the user interface that a move is not allowed. You might use a ValueError instead

This can be tested with

d = Direction.DOWN
u = Direction.UP
l = Direction.LEFT
r = Direction.RIGHT

assert g.can_move(u)
assert g.can_move(d)
assert not g.can_move(l)
assert not g.can_move(r)

The meaning of the strength parameter, is the maximum amount of boxes the player can push. If we set this to 1, it should not be able to push down anymore:

g_1 = g.copy()
g_1.strength = 1
assert g_1.can_move(u)
assert not g_1.can_move(d)
assert not g_1.can_move(l)
assert not g_1.can_move(r)

Now to move, we must start from the first empty tile to the player, and swap the tiles piece by piece

    def move(self, direction):
        if not self.can_move(direction):
            raise IllegalMove
        moves = self._moves(direction)
        moves = reversed(list(moves))
        for old, new in pairwise(moves):
            self.swap_tiles(old, new)

pairwise is from the itertools recipes

from itertools import tee, takewhile
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

so:

g_move = g.copy()
g_move.move(d)
print(g_move)

    01234
x0: 00000
x1: 0...0
x2: 0..£0
x3: 0££.0
x4: 0..*0
x5: 0..£0
x6: 0..£0
x7: 00000


The code is mostly readable and clear:

the variable names are descriptive (for the most part - x is a little unclear)
there is good use of const and let instead of var

Some of the lines are a little lengthy - the longest line appears to be 117 characters long (excluding indentation):

newIntervals[newIntervals.length - 1][1] = Math.max(newIntervals[newIntervals.length - 1][1], sortedIntervals[i][1]);

I considered suggesting that a for...of loop be used to replace the for loop in the imperative solution after seeing the suggestion to use arr.entries() in this answer which would allow the use of a variable like interval instead of sortedIntervals[i], though when comparing in FF and chrome with this jsPerf test it seems that would be slower and thus less optimal, perhaps because each iteration would have an added function call.

When intervals.sort() is called the array is sorted in-place so intervals could be used instead of sortedIntervals, however it does seem that using sortedIntervals. That would reduce the storage by \$O(n)\$.


As you are using a singleton which loads the document once, I would say "Yes you will probably see some degradation in performance to service calls if you only load it on demand".

If your service is the one and only program which modifies the document then your approach is probably viable.

A few notes:

Don't throw Exception. Be as specific as you can.
You mentioned that the file might be big. I don't know what the particular requirements of your application are but be aware that should the service crash at the right moment while saving changes you'll very likely be left with a corrupt xml document because it was only partially saved. Even if it is only a one a million chance it can still be a big problem.
Your service sounds like it's using an xml file as some kind of cheap db backend data store. While there might be scenarios where this is the best/only option forward you might want to consider if it's not better to use an embedded db like SqLite, Sql Server CE or similar ones and have an xml export option instead.


Can I do it without allocating extra memory?

In fact, yes.  The trick is to merge recursively (technically, the \$O(\log N)\$ extra memory is still necessary for recursion). Here is a pseudo-code for the classic in-place merge:

// Prerequisite: [begin, mid) and [mid, end) ranges are sorted
inplace_merge(begin, mid, end)
{
    if (end - begin) < 2) return;

    left = begin + (mid - begin)/2;
    right = lower_bound(mid, end, *left);

    mid = rotate(left, mid, right);

    inplace_merge(begin, left, mid);
    inplace_merge(mid, right, end);
}

Stability

The most important feature of merge sort is stability: the elements compared equal retain their original order (not very important for integers, but immensely important when sorting structured data). Your implementation loses it:

if (left[i] < right[j]) {
    array.push_back(left[i]);
    ++i;
}else {
    array.push_back(right[j]);
    ++j;
}

In case of equality it is an element from right to be pushed first. Easy to fix with

if (right[j] < left[i])

or

if (left[i] <= right[j])

First way is preferred, because it doesn't assume existence of operator<=.


Lets have a little style review, before some code refactoring, and finish off with some performance comparison.

Style and code review

I suggest you read up on PEP8, which is the official style guide for Python.

Not using snake_case for variable and function names - You are using mostly camelCase, and in some cases one letter variables
Good use of singular vs plural – I like combinations like for route in routes. They make sense
Good use of if __name__ ... - This is good construct
Many temporary variables – You have a little too many temporary variables, which are only used once. These can often be skipped
Avoid using indexes in loops – In general, it is better to avoid using indexes in loops, rather than looping on the elements themself. Especially bad is it when you use str(i) to get the index, when the Nodes list should have used pure integers directly as keys.
Avoid building large lists in memory – Your code builds the routes list in memory. When calling this for a route length of 9, your original code uses approx 6.7MB to store the routes. My optimised routine below, uses 0.02MB because it uses generators instead...
Avoid recalculating distances – Python can memoize the output from a function for each given input by using decorators. This means that you can calculate the distance between two points once, and the next time you need it the memoize function picks your previous calculation of the result.
Use docstrings instead of ordinary comment to document functions – If you use docstrings, some of the editors will provide interactive help when you use your functions, and it is according the style guide.

Performance comparison

I made some variants of the code, both of your original, the one by SuperBiasedMan (with some correction as his code currently has a bug), some versions using only generators, itertools, sum and min, and finally a version using for loops instead of list comprehension and a slightly alternate optimisation to find the minimum.

I used the following version of memoize, which most likely can be further optimised:

def memoize(f):
    """ Memoization decorator for functions taking one or more arguments. """
    class memodict(dict):
        def __init__(self, f):
            self.f = f
        def __call__(self, *args):
            return self[args]
        def __missing__(self, key):
            ret = self[key] = self.f(*key)
            return ret
    return memodict(f)

@memoize
def distance(p1, p2):
    """Calculates distance between two points, memoizes result"""
    d = (((p2[0] - p1[0])**2) + ((p2[1] - p1[1])**2)) **.5
    return int(d)

One version taking it to the extreme regarding list comprehension and generators are this one:

def route_generator(route_length):
    """Generate all possible routes of length route_length, starting at 1."""
    for route in permutations(xrange(2, route_length+1)):
        yield (1, ) + route

def main_holroy_v2(instance_size=INSTANCE_SIZE):
    print min((sum(distance(NODES[start], NODES[stop])
                   for start, stop in pairwise(route)), route)
                       for route in route_generator(instance_size))

I made the Nodes into a global dict with integers as key, named NODES. After some testing I found that the extreme variant was slower than expected, so I fumbled around and found this to be the fastest in my environment:

def find_shortest_route3(nodes, route_length):
    """Find shortest route of length route_length from nodes."""

    minimum_distance = None
    for route in permutations(xrange(2, route_length+1)):
        current_distance = 0

        prev = nodes[1]
        for next in route:
            current_distance += distance(prev, nodes[next])
            prev = nodes[next]
            if minimum_distance and current_distance > minimum_distance:
                break
        else:
            if not minimum_distance or current_distance < minimum_distance:
                minimum_distance = current_distance
                minimum_route = route

    return minimum_distance, minimum_route

def main_minimum3(instance_size=INSTANCE_SIZE):
    distance.clear()

    cost, route = find_shortest_route3(NODES, instance_size)
    print('Shortest route: {}'.format((1, ) + route))
    print('Travel cost   : {}'.format(cost))

Some comments on this code:

It turns out that list comprehensions are slightly slower than plain for loops in this case
Instead of completing the sum for a route, I break out of the inner loop if the sum has crossed an earlier minimum. The current route is then not interesting any more
The actual route returned  does not include the starting point. This can easily be added, as done in the print statement. This eliminates the need for either adding in the starting point to all routes, or to remove all routes not starting at the correct point. In short, it is more efficient

If the inner for loop completes ordinarily (no breaks), then it goes into the else block of the for loop. A slightly strange construct, but for this purpose ideal, as we then can compare the minimum distance versus the current route distance
The distance.clear() is used to reset the memoisation between test run done using timeit in IPython. Memory profiling was done using a module name memory_profiler.

Here are some of the timing results I got:

In [325]: %timeit main_org_str(9)    # Your original code
    1 loops, best of 3: 529 ms per loop
In [326]: %timeit main_org(9)        # Using int as keys
    1 loops, best of 3: 304 ms per loop
In [327]: %timeit main_holroy_v2(9)
    1 loops, best of 3: 420 ms per loop
In [328]: %timeit main_superbiasedman(9)
    1 loops, best of 3: 362 ms per loop
In [330]: %timeit main_minimum3(9)
   10 loops, best of 3: 146 ms per loop
In [330]: %timeit main_minimum3(9)    # After removing `**0.5`
   10 loops, best of 3: 116 ms per loop

As can be seen here your original version took around 0.5 seconds, but only changing into using ints as keys and memoisation, shaved off 0.2 seconds. My extreme version and version by SuperBiasedMan, actually uses longer time than your version when optimised. But still the fastest version is the minimum3 version, clocking in at 146 milliseconds. (The last number, 116 ms, comes if you remove the **0.5 in distance(). Taking the square root is somewhat expensive.)

So there you have it, your code is not too bad timewize, but it used way too much memory. When coding according to the most pythonic ways, using generators, list comprehensions and sum and min you lower the memory consumption, changes the readability, but don't always gain that much in reduced time.

Of the alternatives I tested, the optimal combination for a brute force approach runs in approximately 30% of the time, and uses almost none memory. Some other timings for my optimal method: (10: 1.26 seconds, 11: 11.7 seconds, 12: 1 min 54 seconds). So better algorithms should be applied if wanting to calculate the shortest route for routes longer than 11/12 nodes.


How can I make my decrypt method more efficient?

If you can assume that every index in the encrypted message is included in the key, You can loop over the key and encrypted message together, placing each letter into the correct decrypted message slot directly:

public static char[] decrypt(char[] encrypted, int[] key)
{
    char[] decrypted = new char[encrypted.length];

    for (int i = 0; i < encrypted.length; i++)
    {
        decrypted[key[i]] = encrypted[i];
    }

    return decrypted;
}


Variable length string validation against whitelisted characters

Instead of removing valid characters, you may look for invalid ones:

    private static readonly Regex ReferralCodeValidator = new Regex(
       @"[^ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789]",
       RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

    public static bool IsValidReferralCode(this string code)
    {
        // preliminary tests omitted for brevity
        return !ReferralCodeValidator.Match(code).Success;
    }

I can't say if this solution is more elegant (beauty is in the eye of beholder), but it surely looks more straightforward.


Sorting an array of positive integers including 0 much faster than Radix Sort

I think you re-invented counting sort, but with some small differences. Also you probably need to sort your sparse array keys before iterating over them so that's O(k log k) at least unless your possible range of values is small (let's call it N) so you can just try all N values and it will be O( N ).
Performance wise, it's hard to beat if you have a small range of value N.


Convert infix regular expression notation to postfix

General Observations
It is difficult to accurately define any bottle necks when only one function is presented. The brief moment when main() and match() were visible was very helpful, although it would have been nice if the body of match() was included as well.
It might be better to use a power of 2 (1024, 2048, ...) for MAX_LINE rather than a round number like 10000.
The code is overly complex and should be broken into multiple functions, this is actually proved by the multiple goto RELOOP; statements. These goto statements can be replaced by break; and continue and in one case by the return of a function. Try to avoid writing Spaghetti code.
Implement Stacks using Structs
It is much easier to maintain code when the stack pointer and the stack container (array) can be found in one place. Rather than write push and pop as macros, implement them as functions that take a stack struct, and in the case of push the parameter of what is being pushed on the stack.
Magic Numbers
While there are symbolic constants used rather than number constants in some parts of the code, this could be improved, it is also possible to use enums rather than #define to define symbolic constants in C and I would recommend using enums to represent the error ids because it is expandable.
typedef enum Error_Code
{
    REGEX_TOOLARGE = 1,
    PAREN_MISMATCH = 2
} Error_Code;

Just a quick though here, if the error codes start at 0 rather than 1 than any error messages could be stored as an array of strings.
The place where there are still magic numbers is in this code:
    int prec_map[OP_NUM] = { 1, 2, 3, 4, 4, 4 };

It isn't clear what any of those numbers mean.
It isn't clear that OP_NUM is necessary because the count can be determined by either one of the following:
    char id_map[] = { '(', '|', '.', '?', '+', '*' };
    const size_t OP_NUM = sizeof(id_map)/sizeof(*id_map);

or
    int prec_map[] = { 1, 2, 3, 4, 4, 4 };
    const size_t OP_NUM = sizeof(prec_map)/sizeof(*prec_map);

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them.
Posible Optimization
Use strlen() only once and store the value in a variable.


Function to test if the current time is within a time window

You are taking a DateTime, formatting it to a string, then assigning that to another datetime, just to get the time of day. That won't compile with Option Strict On. What you want is provided by DateTime.TimeOfDay.

I would also change ByRef to ByVal in the parameter list.

Once you are comparing timespan instead of date, you don't have to do date addition. You can just detect the wrap-around case and you only have to check endTime.

 Public Function IsCurrentTimeBetween(ByVal dteStartTime As DateTime, ByVal dteEndTime As DateTime) As Boolean

            Dim startTime, endTime, currentTime As TimeSpan

            startTime = dteStartTime.TimeOfDay
            endTime = dteEndTime.TimeOfDay
            currentTime = Now.TimeOfDay

            If endTime < startTime Then
                'the times span midnight
                Return (currentTime <= endTime)
            Else
                'the times do not span midnight
                Return (startTime <= currentTime AndAlso currentTime <= endTime)
            End If

End Function


Python Clean way to get whether a number is above/below two values and increment accordingly

I would write it as

low_count = sum(map(lambda x: x < low, site_results))
high_count = sum(map(lambda x: x > high, site_results))

but admit I'm spoiled by Haskell.

Edit: As suggested by @Nick Burns, using list comprehension will make it even clearer:

low_count = sum(x < low for x in site_results)
high_count = sum(x > high for x in site_results)


Style

These are in order of me thinking of them; not in order of first appearance. Sorry!

#[test]

If you mark your tests with #[test], then running cargo test will run them. If you also mark them with #[cfg(test)], then they'll only be compiled in test mode.

Unneeded collect()

cargo clippy is an invaluable tool. Here, it found an optimisation!

if !number.iter().filter(|&x| *x > 0 && *x >= from_base ).collect::<Vec<_>>().is_empty(){
    return Err(Error::InvalidDigit(from_base));
}

It points out that .collect::<Vec<_>>().is_empty() should be replaced with .next().is_none():

if !number
    .iter()
    .filter(|&x| *x > 0 && *x >= from_base)
    .next()
    .is_none()
{
    return Err(Error::InvalidDigit(from_base));
}

The compiler's probably smart enough to turn this into efficient code,[citation needed] but this code can be made clearer:

if number.iter().any(|&x| x > 0 && x >= from_base) {
    return Err(Error::InvalidDigit(from_base));
}

Unnecessary casting

inter = inter as f64/base as f64;

can be

inter /=  base as f64;

and you can get rid of all of the base as f64 bits by putting

let base = base as f64;

at the top of convert_back.

After a quick pass through cargo fmt to clean up the errant spacing and expand the iterator chain to separate lines, this all looks pretty good.

Algorithm

Your algorithm is, sadly, more limited than it looks. Your use of as is a little risky, as casting to a smaller integer truncates it. However, that won't get to be a problem, because as soon as the from_base.pow ends up with a number bigger than u32 can store, it'll panic.

You need some kind of "too big" Error variant if you want to handle this gracefully; you could check whether number.len() > u32::MAX (otherwise as's truncation could cause issues), and then check whether all the .pow calls are guaranteed to work (perhaps with .checked_pow?), and then whether adding all the digits together will exceed the bounds of u32.

Alternatively, you could make the algorithm convert via base 2³² instead of u32s, which would resolve the issue.


Don't subtract absolute values:

    if (c >= 'a' && c <= 'z') return c - 93;

It makes it hard to understand what you are doing when you subtract integer literals from character codes. I would normally expect some form of value that conveys some meaning. For example lets assume ASCII (You probably want your keyboard thing but I don't know the appropriate macro).

 if (c >= 'a' && c <= 'z') return c + 3 - 'a';  // For some reason you want 'a' to map to 3
                                                // If we assume ASCII 'a' => 96

 if (c >= 'A' && c <= 'Z') return c + 4 - 'A';  // For some reason you want 'A' to map to 4
                                                // If we assume ASCII 'A' => 65

Either you have some other requirement that is not ASCII (very possible), you want 'a'/'A' to map to some non zero number or you have a bug. But it is hard to tell with the way you have written your code as the literal values 93 and 61 have no real meaning.


Quasi-random sequences: how to improve style and tests?

A couple of possible code improvements that I noticed:

sourcelen = len(values) * n

This seems unnecessarily complicated to me. I mean, after a second of thinking the reader of this line will realize that len(values) * n is indeed the length of source, but that's still one step of thinking more than would be required if you just did sourcelen = len(source) (after populating source of course).

That being said, I don't see why you need to store the length of source in a variable at all. Doing for i in xrange(len(source)): isn't really less readable or less efficient than doing for i in xrange(sourcelen):, so I'd just get rid of the variable altogether.

source = []
for val in values:
  source += [val] * n

This can be written as a list comprehension like this:

source = [x for val in values for x in [val]*n]

Using list comprehensions is usually considered more idiomatic python than building up a list iteratively. It is also often more efficient.

As Fred Nurk points out, the list comprehension can also be written as

source = [val for val in values for _ in xrange(n)]

which avoids the creation of a temporary list and is maybe a bit more readable.

j = int(random() * (sourcelen - i)) + i

To get a random integer between x (inclusive) and y (exclusive), you can use random.randrange(x,y), so the above can be written as:

j = randrange(i, len(source) - i)

(You'll also need to import randrange instead of random from the random module). This makes it more immediately obviously that j is a random number between i and len(source) - i and introduces less room for mistakes.


Using $.when is useful when you know you have N asynchronous operations that have to resolve. However, in this case you, as you say, don't know how many there'll be, so the simpler thing would be to create one "master" promise/Deferred and resolve that at the appropriate time.

Which is basically what you're already doing with that repoPageReqs[0] promise, you just have it mixed up in an array and insisting on all this $.when stuff that's not useful here.

But first, some small stuff:

You have i as an implied global variable in your for(i in data) - that's a no-no.
I'm also wary of the parseLinkHeader(headerLink)["next"] line. For one, it might as well be .next instead of the bracket notation, but more importantly, is it safe to assume that parseLinkHeader will always return an object? If it fails, I'd rather have it return null or undefined, but then the code will fail when trying something like null["next"].

I'd don't know how your parseLinkHeader function works, but it just smells a little strange to me.

Anyway, point is to use a single "overall" promise, instead of all that $.when stuff. Something like:

function downloadAllRepos(path) {
  var deferred = $.Deferred(), // the "master" promise
      repos = [];

  function parseLinkHeader(header) { ... }

  function receivedReposPage(data, status, req) {
    if (status !== 'success') {
      deferred.reject(data, status, req); // reject the promise if any page fails to load
      return;
    }

    // if data is an array, then you should *not* use a for..in loop
    // but a regular for loop instead.  for..in is made to iterate
    // object properties, not array elements. Calling the counter var
    // i makes me think you're dealing with an array... but I don't
    // know what the data variable is, so I've kept the for..in loop
    // and the assumption that it's an object rather than an array,
    // but added a sanity check to skip over any inherited properties
    // that might otherwise get erroneously iterated.
    // (And if data is an array, you might get away with simply
    // saying `repos = repos.concat(data)` instead of looping!)
    for (var prop in data) {
      if (!data.hasOwnProperty(prop)) continue;
      allRepos.push(data[prop]);
    }

    // you may want to call deferred.notify() here to let
    // others know that you've downloaded another page, e.g.
    // you could send the number of repos gotten so far:
    deferred.notify(repos.length);

    // a slightly safer approach to getting/parsing the header
    var linkHeader = parseLinkHeader(req.getResponseHeader('Link'));
    if (linkHeader && linkHeader.next) {
      getPage(linkHeader.next); // get the next page
    } else {
      deferred.resolve(repos); // all done, resolve the promise
    }
  }

  function getPage(path) {
    $.get(path, receivedReposPage);
  }

  // get the first page
  getPage(path);

  // return a promise
  return deferred.promise();
}

// Example
downloadAllRepos("https://api.github.com/my/repos/path")
  .progress(function (repoCount) {
    console.log("Downloaded " + repoCount + " repo(s) so far...");
  })
  .success(function (repos) {
    // code to run when *all* pages have loaded
  })
  .failure(function (data, status, req) {
    // code to run if a page failed to load
    console.log(data, status, req);
  });

I've placed everything inside the downloadAllRepos() function to reduce the overall footprint.


JavaScript constructor and namespace in object literal style

I would suggest splitting the addition of the methods as follows:

myApp.model.Person.prototype.sayName = function () {
    alert(this.name);
};

myApp.model.Person.prototype.sayHi = function () {
    alert("Hi, " + this.name);
};

This way you can define additional methods in different places (if needed), as you're not replacing the entire prototype in one go.


Binding Lists of Commits to a DataGridView in Winforms with an MVP architecture

A problem I see here is that the current approach will generate deeply nested BindingList objects if you repeatedly call the setter with a list you previously got from the getter. If you see what I mean. Probably you don't really do such thing in practice, but it's still ugly.

I'm going to assume that you generally want the getter return the same list that was originally passed to the setter. That is, if you passed some list x to the setter, you want that list x back from the getter, not some wrapped(x) list.

To make this work, you would need to keep the original list, or have a way to access it again if the setter puts it in a wrapper.
It seems this can be done using a BindingSource:

Create a BindingSource with a BindingList and null parameter, and keep it in a field
Bind your grid to this BindingSource
Make the list getter return the underlying list with bindingSource.List
Make the list setter replace the underlying list, either by replacing the list in the BindingList, or by replacing the BindingList in the BindingSource

This last item is a work in progress.
I spent some time searching through the docs for it,
but it seems harder than I expected.
(Btw I found this discussion illuminating.)

If all else fails, you could clear the underlying list and add all elements from the incoming list.
Depending on how you use the getters and setters,
you might want to do some defensive copies as appropriate.

Unrelated to your main concern, the code duplication when calling the fetch/push/... handlers is not great, with the boilerplate null checks. It would be good to create a helper method CallHandlerIfNotNull or similar.


Quicksort implementation using filter() to perform partitioning

I think having one lambda in your definition of sublist is perfectly appropriate, but the use of filter isn't appropriate because you are going to need a list anyway. You aren't using it wrong, there are just better solutions.

Also, as noted in the other answer, you can avoid repeated slicing L by creating a copy of the list on the first run of the function through an optional default argument (see first in the code below).

Finally, summing three lists in your return statement is probably less than optimal. With unpacking in Python 3, you can turn this into a single comprehension which should be better in terms of intermediate object creation.

from operator import ge, lt

def qsort(L, first=True):
    if len(L) <= 1:
        return L

    L = L[:] if first else L
    pivot = L.pop()
    sublist = lambda op: [n for n in L if op(n, pivot)]

    return [*qsort(sublist(lt), False), pivot, *qsort(sublist(ge), False)]


I had a similar project for a client. I looped a table filter by employee name for the chosen manager. Then I moved the resultant table values to a new sheet and ran activesheet.move to create a new workbook.

I used your 'testname' saveas portion of the code to pass the manager folder variable and employee variable folder within my loop.

Saveas(...  & "/" & str_manager & "/" & str_employee & ".xlsx" )

The system stress calculations are interesting but not needed. That is because using arrays, counting, bubble sorting, loops are most efficient depending on the size of the dataset.  Mine was quicker when using a table filter loop


100 chairs in a circle problem solving with Angular.js and visualization

Mathematical % simplification

Remember that $$a\  \%\   b == a  \ \ if\ b > a$$

I don't know the math, but Python confirms:

>>> import random
>>> def random_ints():
    for _ in range(1000): yield random.randint(1, 100)
>>> all(a % b == a for a in random_ints() for b in random_ints() if b > a)
True

So:

    fireIndex += skipCount;

    //if fireIndex becomes greater than $scope.people.length, then set fireIndex to remainder from fireIndex / $scope.people.length
    if(fireIndex > $scope.people.length){
      fireIndex %= $scope.people.length;
    }

can be simplified to

fireIndex = (fireIndex + skipCount) % $scope.people.length

Comments

Some comments are good, but you should avoid writing comments next to obvious code:

  if ($scope.people.length > 1) { // if more than 1 people

It is already obvious from the code that you are checking if there are more than 1 people, the comment just doubles the effort required to change the code.

The below comment is very confusing instead:

if($scope.people.length >= 1){ // if start button clicked again

Probably you changed the code but not comment.


Simulate the "cd" command of a file system

Overcomplicated

The implementation is really overcomplicated and hard to read.

  It works, but I feel there must be better way to do that?

Your instincts are good. When you know there's a better way, something you can try is start over from scratch using a different algorithm and see where that goes. Another technique is using TDD and let the tests drive your design.

Poor readability

The code is too compactly written at many places, for example:

    if( "".equals(this.path)||"".equals(newPath)||!this.path.startsWith("/"))
    // ...

    return this.cd(newPath.length()>1?newPath.substring(1):"");
    // ...

    return this.cd(newPath.length()>3?newPath.substring(3):"");

This is really hard to read like that and doesn't help the understandability of the code.
All modern IDE's have an auto-reformat function that will put spaces around operators and make the code much easier to read.

Normalization

The cd method effectively normalizes the path, for example a/b/.. becomes correctly a. But the initial path passed to the constructor is never normalized. For example new Path("/a/b/../..").cd("c").getPath() returns /a/b/../../c instead of c.

This is a bit confusing inconsistency. It would be better to normalize the initial path too.

With a good normalizer method, the implementation of cd itself could be much simpler:

public Path cd(String newPath) {
    if (isAbsolutePath(newPath)) {
        path = normalizePath(newPath);
        return this;
    }

    path = normalizePath(path + SEPARATOR + newPath);
    return this;
}

In this case, of course, normalizePath does the real heavy lifting.
It could go something like this:

private String normalizePath(String path) {
    boolean isAbsolute = isAbsolutePath(path);

    List<String> parts = new ArrayList<>();
    for (String part : path.split(SEPARATOR)) {
        if (part.isEmpty() || part.equals(".")) {
            continue;
        }
        if (part.equals("..")) {
            if (parts.isEmpty()) {
                if (isAbsolute) {
                    continue;
                }
            } else {
                if (!parts.get(parts.size() - 1).equals("..")) {
                    parts.remove(parts.size() - 1);
                    continue;
                }
            }
        }
        parts.add(part);
    }

    String prefix = isAbsolute ? SEPARATOR : "";
    return prefix + String.join(SEPARATOR, parts);
}

Bug or unclear specs?

What should new Path("a/b").cd("..").getPath() return?
I would expect a, but in fact it gives a/b.

What about new Path("a/b").cd("../../..").getPath()?
I would expect .., but it gives a/b for this too.

Special treatment of ...

There is a condition for path segments starting with .... Why is that? The description says that directory names contain only letters of the alphabet.
That makes this special treatment odd.
It seems that such path segment is illegal, and throwing an IllegalArgumentException would seem appropriate.

Testing

For something a bit tricky like this,
the main method in the class is really far too little to verify that the class works well.
Not to mention of course that testing in a main method is not a good way.
I strongly recommend to develop test cases and cover as many interesting corner cases as possible, to flush out obscure bugs.


Direct character iteration
                for (int letter = 0; letter < 26; letter++) {
                    word[chari] = 'a' + letter;

does not need to use integers. Instead,
for (char letter = 'a'; letter <= 'z'; letter++) {
    word[chari] = letter;


This code is good for tutorial use.

Some suggestion:

You are switching over 'x','y' and 'z' :

function rotateCube( axis ) {
    switch ( axis ) {
        case 'x':
            mesh.rotation.x += 0.02;
            break;
        case 'y':
            mesh.rotation.y += 0.02;
            break;
        case 'z':
            mesh.rotation.z += 0.02;
            break;
    }
}

You could simply use axis straight.

function rotateCube( axis ) {
  mesh.rotation[axis] += 0.02;
}

You could explain some of your magical constants, like 10000, it is those values that always throw me off when I experiment with this 3d library.

You should probably extract your rgb codes into well named variables like cubeColor, pointLightColor etc.

This line could use some comment: requestAnimationFrame( animateScene );

One liner functions that are called only once are wrong, I'd much rather you keep those lines in-line with a comment above them as to what is going on.

function renderScene() {
    renderer.render( scene, camera );
}

function animateScene() {
    requestAnimationFrame( animateScene );
    renderScene();
    rotateCube( axisRotation );
}

is less readable than

function animateScene() {
    requestAnimationFrame( animateScene );
    //Render scene
    renderer.render( scene, camera );
    rotateCube( axisRotation );
}

You could merge the treatment of keyCode and which.

var inputChar = null;

if ( event.which === null ) {
    if ( event.keyCode < 32 ) inputChar = null;
    else inputChar = String.fromCharCode( event.keyCode );
}

if ( event.which != 0 && event.charCode != 0 ) {
    if ( event.which < 32 )
      inputChar = null;
    else
      inputChar = String.fromCharCode( event.which );
}

you can change the above to

var keyCode   = event.keyCode || event.which,
    inputChar = keyCode < 32 ? null : String.fromCharCode( keyCode );

Though I will admit that might be too Golfic for a tutorial, you could turn the ternary into a regular if statement to keep things easy.

Furtermore, from a style perspective, your if's look bad

    if ( event.keyCode < 32 ) inputChar = null;
    else inputChar = String.fromCharCode( event.keyCode );

should be

    if ( event.keyCode < 32 )
      inputChar = null;
    else
      inputChar = String.fromCharCode( event.keyCode );

and

if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) {
    axisRotation = inputChar;
}
else if ( inputChar == 'w' ) toggleObjectWireframe();
else inputChar = null;

should be either

if ( ~['x', 'y', 'z'].indexOf( inputChar ) ) {
    axisRotation = inputChar;
}
else if {
    ( inputChar == 'w' ) toggleObjectWireframe();
}
else {
    inputChar = null;
}

or

if ( ~['x', 'y', 'z'].indexOf( inputChar ) )
    axisRotation = inputChar;
else if ( inputChar == 'w' )
  toggleObjectWireframe();
else
  inputChar = null;

I would advocate the second approach.

Furthermore, the following 2 lines seem pointless, I took them out in the fiddle, and it works just fine;

document.body.style.width = "100%";
document.body.style.height = "100%";

Finally, this :

document.onkeypress = getChar;

is old skool, and should be avoided in general, I understand it is easy for a tutorial, but you should at least put a line of comment that this is not ideal.

All in all, I like your code, even though this review got a bit lengthy.


Rolling median function (Daily Coding Problem 377)

This compiles cleanly and produces reasonable integer output (though not in the format required by the problem statement).

Note that you are required to include <cstdlib> before using EXIT_SUCCESS; failing to do so may be a portability bug.

All that copying and sorting gets expensive as the input and k both get larger.  We should probably create a stateful class that we can update with the new right-most value and the left-most to be removed.  I'd probably implement that with two sets - one holding values lower than the median and one holding higher values.  When we shift the window by one position, then we update the two sets and move an element if necessary to balance them (remember that because a set is sorted, it's easy to find the lowest and highest values using front() and back()).


Building navigation structure for multiple users by adding values to multiple arrays at once

It works and I can't see any side effects, but it is unusual to see code like this, and I am not sure of the point of creating all 3 user arrays at once.

Do you intend to display all 3 user menu options at the same time, or can only 1 user be logged in at once?

This is my preference for readability, also if you create a menu array and need items in a different order for different users, it would be difficult to achieve using the current code.

<?php

function build_menu($user)
{
    // ### clearly show what each test is and what menu options are being set
    $menu = array();

    if ($user == 'Al') {
        $menu[] = array(
            "link" => "/admin.php",
            "text" => "Admin Login",
            "icon" => "wp.png");
    }

    if (in_array($user, array('Bob', 'Chris'))) {
        // menu options for multiple users can use in_array test
    }

    // default menu options for all users
    $menu[] = array(
        "link" => "/Wordpress/wp-login.php",
        "text" => "Login to Wordpress",
        "icon" => "wp.png");

    $menu[] = array(
        "link" => "/Gallery/Login.php",
        "text" => "Login to Gallery",
        "icon" => "picutres.jpg");

    return $menu;
}

function userbox($heading, $contents)
{
    // ### contents is supposed to be an array, why test it for being a blank string?
    // ### use {} to show scope
    if ($contents == "") {
        return;
    }

    // ### escape heading, what if it has html chars
    echo "

" . htmlspecialchars($heading). "

";

    /// ### think about your variable naming, $contents is actually menu items
    /// ### and $key is ambiguous, key of what?
    /// ### what if you used foreach ($menu_items as $menu_item) {

    foreach ($contents as $key) {

        // ### use {} around if statements, it is easier to see the scope of what is effected
        // ### use not empty instead of != "", that way if an array key doesn't exist like the 'updated' key below, your program won't generate a warning
        // ### use single quotes if you don't want to escape every double quote

        // if($key['link']!="")echo "";
        if (!empty($key['link'])) {
            echo '';
        }

        // ### i have given an example above, I will leave these ones for you to change
        if($key['icon']!="")echo"";

        // ### escape html incase there are special characters
        // echo $key['text'];
        echo htmlspecialchars($key['text']);

        if($key['link']!="")echo "";
        if($key['updated']!="")echo " (".$key['updated'][0].")";
        echo "
";
    }
    echo "

";
}

$user = 'Al';
$menu = build_menu($user);
userbox($user, $menu);


Python, Iterate through a list sending batches of 100 records at a time to an API, then appending results to another list

You should just be able to append the returned API list directly to return_list:

dict_list = [This is the list with 9000 dicts]
batch_list = []
return_list = []

for i in dictlist:
    batch_list.append(i)
    if len(batch_list)  == 100:
        return_list.append(API_CALL_FUNCTION(batch_list))
        batch_list.clear()

if batch_list:
    return_list.append(API_CALL_FUNCTION(batch_list))

and your else clause is un-needed.

You should also explore slicing the dictlist instead of iterating through each one.
You can call dictlist[0:100] and it will return a list containing the first 100 elements. dictlist[100:200] will return the next chunck, etc.

Hope this helped! Good luck.


Your code is simply a GET request, so the shorthand getJSON can be used for this.
Instead of success and complete, use the more standard Promise method then.
Instead of a recursive setTimeout, use setInterval instead. This avoids your code from rescheduling a callback on each iteration. You can always clear interval timers with clearInterval.
When using setInterval, clearing the timer will suffice for stopping the polling. You don't need the boolean flag to tell you to stop.
When using setInterval, you don't need an extra function for a recursive call anymore.
You also seem to use OOP. It is normally advised to put methods on the prototype and not the instance so that methods are shared per instance and not created per instance.
It is usually not advised to use inline scripts. Use addEventListener to bind your click handlers.
Booleans are usually prefixed with an is, has or are depending on the grammar. This is to not mistake a property as some other non-boolean value.
Put the url and interval in a variable that acts as a constant. That way, you can easily configure as well as spot the values and not dig through code.
If ES6 is available for you, self = this can be taken care of by using arrow functions.

In the end, your code could be as simple as

function Request() {
  this.pollTimer = null;
  this.interval = 1000;
  this.url = './request.php';
}

Request.prototype.disablePoll = function () {
  clearInterval(this.pollTimer);
  this.pollTimer = null;
};

Request.prototype.activatePoll = function () {
  this.pollTimer = setInterval(() => {
    $.getJSON(this.url).then(response => console.log(response))
  }, this.interval);
};


It's not that messy IMO, but there are a few things which you could have done better:

Always compile code with every warning turned on, and fix them. When compiled with -Wall, your code produces 2 same warnings:

warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

You should fix them.
Your choice variable really wants to be an enum instance:

enum class mode {
    encrypt, decrypt
};

You have some redundant code:

if(choice == "E") choice = "e";
// redundant if in the next line your lower casing every character in 'choice'

const correctness: alphaToInt can and should be const, as you're not going to modify it no matter what.
getCoords can be reduced considerably (it looks too bloated otherwise IMO):

std::vector<std::string> getCoords(){
    std::cout << "Coordinates (separate with spaces): ";
    std::string strCoords;
    std::getline(std::cin, strCoords);

    std::stringstream streamCoords(strCoords);
    return{ std::istream_iterator<std::string>{ streamCoords }, std::istream_iterator<std::string>{} };
}

squareIJ doesn't have to be a std::string[5][5], it can be a simple char[5][5]. Don't allocate memory if you don't have too (this might actually not allocate memory for the std::string, due to SSO actually).
Use auto to simply some variable definitions if you want to:

// std::vector<std::string> coords = getCoords();
auto coords = getCoords();

// ...

Use ranged-based loop instead of index loop. For example,

for(int i = 0; i < coords.size(); ++i){
    std::string coord = coords[i];
    output.push_back(squareIJ[coord[0] - '1'][coord[1] - '1']);
}

becomes

for (const auto& coord : coords)
    output.push_back(squareIJ[coord[0] - '1'][coord[1] - '1']);

Include every necessary headers, you forgot <cctype> for std::isspace.
If you expect every character to be upper case, either (1) tell the user (not recommended) or (2) upper case the string yourself:

std::transform(input.begin(), input.end(), input.begin(), ::toupper);


I would move all of the functionality into a single document ready handler. I will use the short-hand notation.

$(function () {
    /* All code goes in here. */
});

I will use less verbose selectors for creating my jQuery objects and I will cache them by assigning them to variables.

var $div = $('#TheDiv');
var $form = $('#TheForm');
var $window = $(window);

I think that hiding the form on the textarea's focusout event is a bad idea because this event could be triggered by the user tabbing out of the textarea. Hiding the form at this point would prevent the user from submitting the form.

I think a better approach is to take our direction directly from your requirements and hide the form when the user clicks outside of it. We can do this by attaching a click handler to the $window. In this handler we will call hideForm only if the clicked target was neither the form element nor an element within the form.

$window.on('click.TheForm', function (e) {
    if ($(e.target).is($form)) { return; }
    if ($.contains($form.get(0), e.target)) { return; }
    hideForm();
});

Notice above that the click event has been namespaced with '.TheForm'. Namespacing will allow us to easily remove the event handler without removing any other click events that may have been attached to the window. I will wrap the $window click handler code from above into a function so that we can re-attach this handler as we please. I will also create a function for removing the handler.

var attachWindowClick = function () {
    $window.on('click.TheForm', function (e) {
        if ($(e.target).is($form)) { return; }
        if ($.contains($form.get(0), e.target)) { return; }
        hideForm();
    });
};

var removeWindowClick = function () {
    $window.off('click.TheForm');
};

If we want to hide the form when it is submitted, it will be better to listen for the submit event on the form rather than the mousedown event on the submit button, because the user can submit the form without the mouse, for example, by pressing Enter.

$form.on('submit', function (e) {
    /* Do AJAX stuff here. */
    hideForm();
    e.preventDefault();
});

In the showForm function, we will attach our window click listener so that we can capture clicks while the form is displayed. Note that we do not want our click of the #TheDiv to bubble-up and trigger our handler, so we will ensure our call to attachWindowClick is outside of the current call stack by using setTimeout with a delay of 0 milliseconds.

var showForm = function () {
    $form.show();
    $div.hide();
    $form.find('textarea').focus();
    setTimeout(attachWindowClick, 0);
};

The final code looks as follows:

$(function () {
    var $div = $('#TheDiv');
    var $form = $('#TheForm');
    var $window = $(window);

    var attachWindowClick = function () {
        $window.on('click.TheForm', function (e) {
            if ($(e.target).is($form)) { return; }
            if ($.contains($form.get(0), e.target)) { return; }
            hideForm();
        });
    };

    var removeWindowClick = function () {
        $window.off('click.TheForm');
    };

    var hideForm = function () {
        $form.hide();
        $div.show();
        removeWindowClick();
    };

    var showForm = function () {
        $form.show();
        $div.hide();
        $form.find('textarea').focus();
        setTimeout(attachWindowClick, 0);
    };

    $form.on('submit', function (e) {
        console.log('do ajax');
        hideForm();
        e.preventDefault();
    });

    $div.on('click', showForm);
});


Optimization difficulty  is about quadratic on the length of a function. I suggest a separate shift function, like

 char shift(char ch, int shift)
 {
            if (ch == 'z')
            {
                 return 'a';
            }
            else if (ch== 'Z')
            {
                return 'A';
            }
            else
            {
                return ch + 1;
            }
   }

And you can call it in the loop.

Anyhow this programme does not need speed up, runtime is dominated by input and output taking.

Avoid namespace std;, return 0, and system("pause").
The first causes name clashes, the second is not needed, the third is a portability issue and a security breach.

As a minor note, declare and assign length on the same line:

  int length = (int) str.length()

Following @Ryan 's suggestion, -25 can be used to merge 'z' and 'Z'. It then becomes so short to beg for a ternary:

 char shift(char ch, int shift)
 {
     return ch == 'z' || ch == 'Z' ? ch - 25 : ch + 1;
 }


First of all, it's good that you try to implement something like a blog/forum on your own. It will teach you a lot of good/bad practices. In one comment you said, that you are trying to understand how these frameworks could be impemented, so it would be very good, if you take a look at them. Check out their APIs and see what they did.

Im used to Symfony (http://symfony.com/) so my advice will mostly use their architecture as an example. However, be sure to remember that there are many ways to success and the things I describe are my current point of view.

Your major problems (maybe not now, but in a few days/weeks/months) are the structure of your project, the structure of your source code and the mixing of php/html.

Project Structure

Currently, you have a few php files in your root directory and a few php files in your PHP directory. On a first glance, it seems, that the PHP directory contains your framework and the root folder contains the views, which use this framework. If that's the case, make it obvious.

Advice #1: Give your framework a name and rename the folder accordingly.

That way, you will have an easier time to find the place you are looking for. Which leads to the next problem: Your core.php contains multiple class definitions. If you continue doing this, your file will grow exponentially and it will take you a long time to find the line you want to modify.

Advice #2: Put each php class in a separate file.

The next step is to use namespaces to further structure your classes and files. It might be more difficult to begin with, but will help you in the long run. Additionally you might want to look into autoload. Used correctly, this should solve your troubles with include and require.

Advice #3: Use Namespaces and autoload

Another possible improvement are the files in your root directory. Currently you probably access each file directly via www.whatev.er/viewPost.php or www.whatev.er/createPost.php. I highly recommend to take a look at something like a controller/routing mechanism and only use ONE file (index.php) to access your website. Take a look at .htaccess and URL Rewriting. This is actually a pretty powerful and extensive technique. So just a short explanation: Every (nearly every) call to your website is redirected to your index.php. So www.whatev.er/blub/bla/1234 or www.whatev.er/post/create all call your index.php. In the index file, you can parse the requested uri and call the appropriate actions.

Advice #4: Use .htaccess and URL Rewriting and only one file as an entry point to your website.

Advice #5: Use some kind of controller/routing mechanism to handle actions depending on your route.

Source Code Structure

As already mentioned, only define one class per file. I like it, that you encapsulate the fields of your classes. However, you have many static functions, which basically degrades your classes to some kind of namespaces. There is nothing wrong with static functions, but be careful not to overuse them.

Advice #6: Don't overuse static functions (and statics in general)

As you mentioned, getUsersDB() and getPostsDB() is suboptimal. You have pretty much three options:

Use global objects
Pass a reference where it is needed
Use dependency injection

The use of global objects is generally discouraged, but migh be okay given your current experience. Another (slightly) better option is to instantiate the database once and pass it to the method that needs the database. The imho best option is to use dependency injection. However, this is pretty advanced stuff and something you want to look into in the future.

Advice #7: Use dependency injection if possible. Globals might be okay for now, but lead to trouble in the future.

You say, that you have posts and comments. However, in your code you only deal with assoc arrays. Why don't you create classes for Post and Comment? This is the perfect place to use a class.

Advice #8: Use classes for entites (Post/Comment) and not assoc arrays.

If you use classes for Post/Comment, you might wonder how to write them to json. PHPs jsonSerialize will help you there. However, you probably have to convert json -> Post/Comment yourself.

Advice #9: Use jsonSerialize or something similar to serialize objects to json.

Mixing of PHP/HTML

This is probably the problem, that will annoy you the most in the future. As it will make dealing with outputting stuff way more complicated than it needs to be. I highly encourage you to use some kind of templating system to render templates and display html. Don't ever output or print html code in a php file. Take a look at twig (used in eg. Symfony). Something like that will extremely improve your codebase. Your problem with printing will vanish and you can use common parts of html code without any problems.

Advice #10: Use some kind of templating mechanism to output HTML.


Hackerrank Day 8: Dictionaries and Maps solution in C++

You should not use using namespace std; This is bad practice that will get you into trouble once you want to use a function that has the same name.
You can use descriptive names. So instead of "n" use "numEntries" or whatever.
You should declare the iteration variable inside the for loop rather than at the beginning.
std::map has an emplace method that you should use rather than insert.
You are using a std::map, which is is a red black tree. You most likely want a std::unordered_map
You search twice for the key. With modern C++17 you can do the following:

if (auto res = phone_dir.find(key); res != phone_dir.end())
{
     std::cout << key << "=" << res->second << std::endl;
} else {
     std::cout << "Not found" << std::endl;
}

You are using std::endl which involves a flush of the stream. You definitely only want a \n here.
Whitespace is cheap. Grab some to improve readability
Same for lines. It is bad practice to have braces on one condition and pu the other one on the same line. This severely affects readability
return 0; is implied for main so you can skip that.
I almost forgot, you should reserve the space in the map.


Usertool For Website Admins -- Follow up

Bug

Adding a user with a username that is already taken overwrites the existing user.

Adding a user with a blank username is allowed. (Maybe you should allow alphanumeric characters only, and set a minimum required length)

Unbounded recursion

def add_user
    # ...
    add_user if restart
end

The recursion you're using for repeating this function can grow arbitrarily deep, causing a stack overflow error. Use a loop instead:

def add_user
  loop do
    # ...
    break unless restart
  end
end

Then, restart doesn't need to harshly exit the whole program. It can simply return a boolean:

def restart
  puts "Would you like to edit another user?"
  input = gets.chomp
  return input =~ /yes/i
end

(You can print "Exiting program" at the end of the program, if you want)

Also, don't exit in menu. It's not needed.

Nitpicking

print "...?\n"

Use puts instead of using a newline in the string.

if hash[:users].has_key?(to_delete)
  hash[:users].delete(to_delete)
else
  puts 'User not found'
end

Hash#delete returns the deleted value, or nil if the key is not found. So you can use its return value for the condition:

user = hash[:users].delete(to_delete)
unless user
  puts 'User not found'
end

Also, rename to_delete to username.

puts "Would you like to edit another user?"

This message appears for every action, not just editing. Pass a string argument to specify the action (e.g. "add" or "edit") and use it when printing the message. Also, rename restart to again? to be more accurate.

Creating a class

Most methods operate on the same data structure: the users hash. So it makes sense to put them all inside a class which stores the hash as a field. As a bonus, you won't need to reread the users file every time you perform an action.

class UsersList
  def add(username, email_address, member_status)
    file[:users][username.to_sym] = {
      email_address: email_address,
      member_status: member_status
    }
  end

  def remove(username)
    file[:users].delete(username)
  end

  def save
    save_hash
  end

  def to_s # for viewing
    file.to_s
  end

  private

    def file
      # Return @hash, which stores the hash
      # If it's not loaded yet (@hash is nil), initialize it with load_hash first
      @hash ||= load_hash
    end

    def load_hash
      File.exist?('users.yml') ? YAML.load_file('users.yml') : {users: {}}
    end

    def save_hash
      File.open('users.yml', 'w') { |s| s.write(@hash.to_yaml) }
    end
end

Notice all methods for accessing the hash use the private method file. (I named it file because hash is an existing method of all objects). file returns the hash, but only loads it once from the file, when it's first needed.

Note the methods only deal with the logic of the operations, not with interacting with the user, in order to seperate these two concerns.

To use this class, you'll need to make an instance of it:

$users_list = UsersList.new # global variable for handling the users list

Then change add_user, delete_user and view_all to use it:

def add_user
  loop do
    username = prompt('Enter username: ')
    email_address = prompt('Enter email:')
    member_status = prompt('Enter member status:')
    $users_list.add(username, email_address, member_status)
    break unless again?('add')
  end
end

def delete_user
  loop do
    username = prompt("Enter username:").to_sym
    unless $users_list.remove(username)
      puts 'User not found'
    end
    break unless again?('delete')
  end
end

def view_all
  puts $users_list.to_s
end

Finally, at the end of your program, save the users list:

$users_list.save


Name Mashup Program Improvement in Python

Any time you're doing essentially the same thing (even if it's in different orders) to different values, it's a strong clue that the values should be a collection (like a list or tuple) rather than independent named variables.  It'll usually make your code a lot shorter, and it makes it much much easier to extend -- what if you wanted to play the mashup game with more names?

from itertools import permutations
from typing import List

print('Welcome to the Name Mashup Game')

names = [
    input('Enter one full name(FIRST LAST): ').split(),
    input('Enter second full name(FIRST LAST): ').split(),
    # input('Enter third full name(FIRST LAST):' ).split(),  <- try me!
]

def mash(first: List[str], second: List[str]) -> List[str]:
    """
    Produce a list where each element has the first half of the corresponding
    element from the first list and the second half of the corresponding
    element from the second list.

    For example:
        mash(['AA', 'BB'], ['XX', 'YY']) -> ['AX', 'BY']
    """
    return [
        a[:len(a)//2] + b[len(b)//2:]
        for a, b in zip(first, second)
    ]

for first, second in permutations(names, 2):
    print(' '.join(mash(first, second)))


So you have two classes which are very similar and differ only in one thing? Then make a parent class that has all the behavior and let the others inherit from it or add a switch to flip between the two behaviors.

I would probably go with the first. To accomplish this, make self.drawRect a property (and rename it to self.rect, it does not actually draw anything, it just says where to draw):

class NeuronIO:
    """Draw input or output of a neuron.

    Abstract base class.
    """
    color = 0, 0, 0  # default color is black

    def __init__(self, neuron):
        self.neuron = neuron

        width = 0.5 * self.neuron.width
        offset = width / 2
        distance = 0.4 * self.neuron.width
        self._pos = None
        self._rect = None

    def draw(self, surf):
        pygame.draw.ellipse(surf, self.color, self.rect)

    @property
    def pos(self):
        """Needs to be implemented by the child classes"""
        raise NotImplementedError

    @property
    def rect(self):
        if self._rect is None:
            pos = self.pos
            self._rect = pos[0] - offset, pos[1] - offset, width, width
        return self._rect

class NeuronOutput(NeuronIO):
    """The place where a Neuron outputs its signal"""
    color = 200, 150, 200

    @property
    def pos(self):
        if self._pos is None:
            self._pos = (self.neuron.x + math.sin(self.neuron.angle) * distance,
                         self.neuron.y - math.cos(self.neuron.angle) * distance)
        return self._pos

class NeuronReciever(NeuronIO):
    """Where a Neuron receives input"""
    color = 200, 255, 200
    @property
    def pos(self):
        if self._pos is None:
            self._pos = (self.neuron.x - math.sin(self.neuron.angle) * distance,
                         self.neuron.y + math.cos(self.neuron.angle) * distance)
        return self._pos

Here both rect and pos are cached so that they are only calculated the first time they are needed.

In addition I added some whitespace around operators and after commas, as recommended by Python's official style-guide, PEP8.

At this point you should ask yourself: "But how often do I need to draw the receiver or output without also drawing a neuron?". If the answer to that question is "probably never!", then you should just fold all of that functionality into the Neuron class:

import math
import random
import pygame

class Neuron:
    """A single neuron with Synapses that connect to others"""

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.pos = x, y
        self.width = 30
        self.offset = self.width / 2
        self.connections = []
        self.angle = math.radians(random.randint(0, 360))
        self.rect = (self.x - self.offset, self.y - self.offset,
                     self.width, self.width)
        self.color = 200, 150, 50

    def draw(self, surf):
        pygame.draw.ellipse(surf, self.color, self.rect)
        pygame.draw.ellipse(surf, *self.input)
        pygame.draw.ellipse(surf, *self.output)

    @property
    def input(self):
        color = 200, 255, 200
        rect = self.calc_rect()
        return color, rect

    @property
    def output(self):
        color = 200, 255, 200
        rect = self.calc_rect(output=True)
        return color, rect

    def calc_rect(self, output=False):
        width = 0.5 * self.width
        distance = 0.4 * self.width
        offset = 0.25 * self.width
        if output:
            pos = (self.x + math.sin(self.angle) * distance,
                   self.y - math.cos(self.angle) * distance)
        else:
            pos = (self.x - math.sin(self.angle) * distance,
                   self.y + math.cos(self.angle) * distance)
        return pos[0] - offset, pos[1] - offset, width, width

Here I did not go through the effort of making sure that Neuron.input and Neuron.output are only calculated once, but you could do it in the same way as I did above.

Note that I made all of your lists into tuples (like Neuron.pos). This is just aesthetics atm, but if you want to be able to do e.g. neuron.pos[0] += 1, then you need to make them lists again.


You are not allocating per se when when writing to the queue. std::array is backed by a plain C-array on the stack, that gets moved.

So you only ever allocate depending on the underlying container the std::queue is based on. By default this is a std::deque.

I do not really understand the need for the std::array in the type though. Why not just use a std::string and limit the size of it to 4096? There is even a constructor that does explicitely that string (const char* s, size_t n)

Before I get to the Code there are some other things I would like to mention:

why are you not useing std::copy instead of memcpy. The former works better with C++ and will in the end almost always end up as memcpy?
You do not need to define the special member functions. In fact you have forgotten 2 of then, aka copy assignment and copy constructor. Why do I say forgotten? Because there is no way to tell. So If you want your queue to be move only then you should actually delete those special member functions you dont want.
In your read function you never check whether the size you want to read is actually valid. Is that intendend? If so why? A std::array is not initialized so the memory in it that is not written by you will be random. You are not writing to it but you are copying it around. So you should actually take the minimum out of size and queue.front().size()
std::string has a member function std::string::copy that copyies a certain amount of chars to a buffer (http://www.cplusplus.com/reference/string/string/copy/). I would suggest to use that for writing back to the buffer

That leads me to the following:

#include <string>
#include <queue>
#include <vector>

class simple_queue
{
private:
    static constexpr uint32_t max_msg_size = 4096;
    std::queue<std::string, std::vector<std::string>> char_queue;

public:
   simple_queue(const simple_queue&) = delete;
   simple_queue& operator=(const simple_queue&) = delete;

    uint32_t write(const char* const buff, const uint32_t size) noexcept
    {
        const uint32_t size_to_copy = std::min(max_msg_size, size);
        char_queue.emplace(buff, size_to_copy);
        return size_to_copy;
    }

    uint32_t read(char* const buff, const uint32_t size) noexcept
    {
        if (char_queue.empty())
        {
            return 0;
        }
        std::string& msg = char_queue.front();
        const uint32_t size_to_copy = std::min(msg, size);
        msg.copy(buff, size_to_copy, 0);

        char_queue.pop();
        return size_to_copy;
    }
};

EDIT:

I forgot to mention, that now you should use a std::vector as backing of the queue as your are not storing a gargantuan array but rather a mall std::string.

Note that it actually ends up being the same. The std::deque based std::array implementation is backed by a linked list, so each array ends up in a node of a linked list, which is kind of similar to the separate allocation of the std::string


Not a JavaScript pitfall per se, but I'd stay away from using two variable names that are only differentiated by the case of the second letter in a single lexical scope like that. (JsonObject vs JSonObject)

Also, the bindFormToJson function is re-defining the iterateJson function every time it is called, which a waste of cycles (not egregious, but less than ideal). Using coffeescripts do notation is a handy way to create a closure and return a value from it:

$ -> $.fn.bindFormToJson = do ->

    iterateJson = (Source, FullKey, Seperator, func) ->
        for key, value of Source
            newKey = ""
            if FullKey == ""
                newKey = key
            else
                newKey = FullKey + Seperator + key

            if typeof(value) == "object"
                iterateJson value, newKey, Seperator, func
            else
                func newKey, value

    return (JsonObject, OverwritePopulatedFields) ->
        selector = $(this).selector
        iterateJson JsonObject, "", "_", (key, value) ->
            field = $(selector + " #" + key)
            currentValue = field.val()
            if (currentValue and OverwritePopulatedFields) or not currentValue
                field.val(value)

The return is unnecessary, but I figured it can't hurt to be explicit about what's happening there.


Optimization of multiple arrays for filtering

There may exist a way to make this particular loop run faster.  In fact, I'm sure there probably is... however, it's kind of a futile effort.

There's a lot of time also being wasted elsewhere where we're creating these original three arrays we're passing in here.  We need to take a far more OOP approach to this problem.

I don't know what this code actually represents, but for now, I'm going to use "Phenotype" and assume that's an accurate noun to give to the object that the JSON data is trying to describe.

The way the JSON data is structured suggests that the these three data points are obviously tied to each other.  We don't need to create three separate arrays and somehow rely on a common index among them to remember what goes with what.  Let's make a container to hold all of this information:

struct Phenotype {
    var phenotype: String
    var SNP: String
    var data: String
}

(The struct name and its variable names are probably far from optimal.)

Now, when we parse out the JSON data, we create a single array of instances of our Phenotype struct rather than three arrays of the different types.

Now we don't even need to write the method in your question, because we can do it with the built-in filter method:

let limit = someValue
let dataFromJSON = someFuncCreatingArrayOfPhenotypesFromJSONData(data)

let filteredData = dataFromJSON.filter { $0.data <= limit }

And filteredData represents exactly the data your method was trying to extract.


This uses no variables other than Ans, but because real( and imag( are two-byte tokens, the code is larger. It is also faster than your code according to Timtech.

i+dim(identity(1                    //{1+i,1+i}
Repeat getKey
Pxl-Change(real(Ans(1)),real(Ans(2
Ans+imag(Ans)(1-2inot(real(Ans) and real(Ans)≠{62,94
End

In your original solution, you can thusly save a total of six bytes at the cost of a small amount of speed, and the use of named lists. Two bytes less than that is a program that starts at (2,2) instead of (1,1) because command order is switched:

dim(identity(1→A                    //{1,1
Repeat getKey
Ans→B
Ans+∟A→A
Pxl-Change(Ans(1),Ans(2
∟Bcos(πʳnot(Ans and Ans≠{62,94
End

Finally, if your calculator is in radian mode, you can save one more byte by removing the ʳ.