Since your search is only by 1 parameter, a map<string,Book> would work a lot better than a vector.

map<string,Book> mBooks;
string LibrarySystem::BookDataOutput(string bookId)
{
    Book book = mBooks[bookId];
    string data =
        "Book author: " + book.bookAuthor + "\n" +
        "Book name: " + book.bookName + "\n" +
        "Book type: " + to_string(book.bookType) + "\n" +
        "Book Id: " + book.bookID;
    return data;
}


This code looks quite nice, actually. If this was a homework assignment, you could almost turn it in right now. I only have some minor issues with the code, plus some bugs, and would then like to talk about alternatives to structure your lexer (the words tokenizer, lexer and scanner are all equivalent here).

I don't see a single comment in your code, aside from that TODO.
hasMoreToken should be hasMoreTokens. Notice the plural-“s”. This makes reading the code more pleasant.
Each lexeme should have a Type type, not a String type. By using a string, you loose all type safety. (Apparently there is a name for this antipattern: Stringly Typed).
You should probably use toString() instead of name(). This should not happen before the type is actually printed out, i.e. only in the main.
A seasoned Java programmer will use a lot more visibility modifiers. Especially pos and expression ought to be private. but I personally don't care.
You have inconsistent formatting. You put the opening braces of class and method declarations on the same line, but you put them under the keyword for control flow statements. In Java, the braces usually open on the same line.
It looks as if your switch was outdented one level. This happens because you didn't use a block for the preceding while. Always using blocks can make code easier to read.
General style note: Place blank lines between logically seperate blocks of your code. Inside the Lexeme class, a blank line between the fields and the methods could improve readability.
This piece of code:

while(expression[pos] == ' ')
        pos++;

will attempt to access an array entry outside of the allowed range when the strings ends with whitespace. Add a bounds check here.

On an architecture level, it would be nice to make your Tokenizer an Iterable. Heck, it implicitly already is a kind of Iterator. If we clean that up, we can do:

for (Token token : new Tokenizer(expression)) {
  System.out.println(...);
}

We can turn it into an Iterator by renaming hasMoreTokens to hasNext and getToken to next. If you can't rename them, a wrapper method will do as well. We also need a dummy method remove that throws an UnsupportedOpertationException. If we want to make it Iterable, we need to add an iterator method that returns the object itself, although this may be considered hackish.

The State Machine, and Why I Don't Like It

In your getToken method, you have written a kind of state machine that performs the parsing. You have seemingly flattened it into a single state with one character lookahead, but it actually has three (plus two) different states. Here are all transitions you have written:

# transitions that consume a char are written A -- char -> B
# lookahead transitions           are written A --(char)-> B

START --(not ' ')-> UNKNOWN
START --     ' ' -> START

# the operator cases
UNKNOWN -- '+'|'-'|'*'|'/' -> OPERATOR END
NUMBER  --('+'|'-'|'*'|'/')-> END

# the whitespace case
UNKNOWN  -- ' ' -> END # unreachable
OPERATOR -- ' ' -> END # unreachable
NUMBER   -- ' ' -> END

# the default digit case
UNKNOWN  -- '0'..'9'|'.' -> NUMBER
NUMBER   -- '0'..'9'|'.' -> NUMBER
OPERATOR -- '0'..'9'|'.' -> NUMBER # unreachable

# the default error case
UNKNOWN  -- not '0'..'9'|'.' -> UNKNOWN
NUMBER   -- not '0'..'9'|'.' -> NUMBER
OPERATOR -- not '0'..'9'|'.' -> OPERATOR # unreachable

There might be a few issues with this.

You can't output good error messages, because you don't have that good of an idea where you are, and because you skip over any junk in the string, allowing for 12foobar3 to be recognized as 123. Any extensions to the lexer would therefore be backwards-incompatible.
Extending this kind of lexer is difficult with increasing number of different token types, because all possible transitions have to be considered for that type, as all transitions happen in that one switch.
It obscures the actual flow of control.
You would consider ... to be a number.
I don't feel comfortable with consuming the char in the whitespace case. It is logically separate from tokenizing a number, and therefore should be separated in your code.
The existence of an UNKNOWN type is ridiculous. This is a case where having a null type might be preferable, and complaining if it is still null at the end of the method.

It might be better to make your states more explicit as actual states in your code. Also note that single-character lookahead is sufficient for your grammar, but would have difficulties recognizing operators like <=.

Another thing worth considering would be to put the body of your while(hasMoreTokens()) loop into a seperate method – this would remove the need for the endOfToken flag, as you could simply return. First, optimize for simplicity and readability, only second for performance.

Together, I might write code like this (untested sketch, no final code):

...

boolean illegalState = false;

public boolean hasNext() {
  return pos < expression.length && !illegalState;
}

public Lexeme next() {
  if (!hasNext()) {
    throw new NoSuchElementException();
  }

  // this can be removed if we do it in the constructor,
  // as we remove all WS *after* each token.
  skipWhitespace();

  // dispatch actual tokenization based on single character lookahead
  Lexeme lexeme;
  char c = expression[pos];
  if (c == '+' || c == '-' || c == '*' || c == '/') {
      pos++;
      lexeme = new Lexeme(Type.OPERATOR, Character.toString(c));
  } else if ('0' <= c && c <= '9') {
      lexeme = tokenizeNumber();
  } else {
      illegalState = true;
      throw new java.text.ParseException("Expected operator or number", pos);
  }

  // clean up after ourselves, so that hasNext() doesn't recognize
  // trailing whitespace as another token:
  skipWhitespace();

  return lexeme;
}

private void skipWhitespace() {
  while(pos < expression.length && expression[pos] == ' ') {
    pos++;
  }
}

private Lexeme tokenizeNumber() {
  StringBuilder token = new StringBuilder();

  // effectively, this method recognizes the language specified by the regex
  // /[0-9]+(?:\.[0-9]+)?/
  // (PCRE style)

  // lex the integer part
  int posBeforeInt = pos;
  while (pos < expression.length && '0' <= expression[pos] && expression[pos ] <= '9') {
    token.append(expression[pos++]);
  }
  if (pos == posBeforeInt) {
    illegalState = true;
    throw new java.text.ParseException("Every number must have an integer part", pos);
  }

  // optional: lex decimal
  if (expression[pos] == '.') {
    token.append(expression[pos++]);

    int posBeforeDecimal = pos;
    while (pos < expression.length && '0' <= expression[pos] && expression[pos ] <= '9') {
      token.append(expression[pos++]);
    }
    if (pos == posBeforeDecimal) {
      illegalState = true;
      throw new java.text.ParseException("Number has decimal point, but no decimal digits", pos);
    }
  }

  return new Lexeme(Type.NUMBER, token.toString());
}

You may have noticed that this lexer is much more similar to a top-down parser now, which I find easier to reason about. There is no difference between a lexer and parser, both transform a list of X to Y by giving them structure. (Lexer: chars → tokens, Parser: tokens → parse tree).

An abstraction possibility that opens up is the concept of a character class – a Set of characters with common properties. E.g. '0' <= expression[pos] && expression[pos ] <= '9' ought to be written as digits.contains(expression[pos]). Also, there are dozens more whitespace characters than just the \x20 space character.


Creating multiple DOM buttons in JavaScript (I am not DRYing)

Factor repeated code into a function

Any code that is all part of "doing one thing" can be naturally captured in a function definition and function call. Any details that differ between the two situations can be made into arguments to the function.

const boxOne = createBox( 'boxOne' );
const buttonOne = createButton( boxOne, 0 );
const boxTwo = createBox( 'boxTwo' );
const buttonTwo = createButton( boxTwo, 1 );

function createBox( name ){
  var box = document.createElement('div');
  box.classList.add( name );
  return box;
}
function createButton( box, idx ){
  var button = document.createElement('button')
  button.classList.add("button")
  button.setAttribute('type', 'button');
  button.addEventListener('click', () => {
    box.classList.add('token');
    box.textContent =  playerController.activePlayer;
    boardController.board[idx] =  playerController.activePlayer;

    gameController.afterButtonIsPressed();
    gameController.winnerAction;
  });
  return button;
}

This doesn't just apply to code that is repeated. Any block of code where you find yourself writing a comment about what it is doing could probably be expressed as a function. The function's name can express the idea of the comment. And by removing the bulk of code to a different location, it can make the main-line code easier (faster) to read. In the code here for example, the two lines

    gameController.afterButtonIsPressed();
    gameController.winnerAction;

would make for a nice small function. And a single line call to it probably wouldn't need to be set off by a paragraph break.


Lowering the cyclomatic complexity of this method, suggestions?

You could easily extract the 4 functions you have within if statements by having

arrayChecker()
arraySetter()
classChecker()
arraySetter()

And then have something like

//Exit immediately if override is not allowed ( why wait ? )
//Personally, that would be the first line for me
if(!$allowOverride)
  return;

// Payload is array or ArrayAccess implementation inside main array
if (is_array($payload) || $payload instanceof \ArrayAccess) {
  if(!$arrayChecker($paramName)) {
    $arraySetter($paramName, $paramValue);
  }
}

// Payload is stdClass inside the main array
if ($payload instanceof \stdClass) {
  if(!$classChecker($paramName)) {
    $classSetter($paramName, $paramValue);
  }
}

One more thing, you re-use the payload variable. For me, what you get from ->getPayload() is a payload of an array with something in the first position. ( crate plus the goods ). To then re-use the variable to point just to the goods seems wrong to me.


Your concerns are correct. The std::notify_one description says that

  Even if the shared variable is atomic, it must be modified under the mutex in order to correctly publish the modification to the waiting thread.

Code wise, return true/return false usually indicate a room for improvement. What you are actually returning is a state of _shutdown. Do it explicitly:

        if (!shutdown) {
            dequeue item;
        }
        return !_shutdown;

You may also notice that shutdown is always tested with negation. It indicates that the semantics is reversed. I recommend to replace shutdown with something like keep_running.


Performing benchmarks with such small values is pretty much meaningless, you will usually be concerned with larger values. And this is how you  tipically compare the time performance of different snippets:

require 'benchmark'
require 'set'

n = 1_000_000
Benchmark.bm do |b|
  b.report("sets") do
    s1 = Set.new (1..n/3.floor).map { |x| 3 * x }
    s2 = Set.new (1..n/5.floor).map { |x| 5 * x }
    sum = s1.merge(s2).inject(0, :+)
  end

  b.report("select") do
    sum = (1..n).select { |x| x % 3 == 0 || x % 5 == 0 }.reduce(0, :+)
  end
end

Output:

         user     system      total        real
sets    0.550000   0.020000   0.570000 (  0.580492)
select  0.200000   0.000000   0.200000 (  0.207238)


"Better" is obviously fairly subjective. After a quick glance I would like to make a few suggestions:

If you already imported scipy, you don't need to import
scipy.optimize separately. You can either limit the importing by just
importing the (sub)modules you need, which is cleaner. Or you can
import the entire module and just use what you need.
Especially in terms of usability and readability for later (especially rereading your own code), I would suggest adding some docstring to describe what it does: https://www.python.org/dev/peps/pep-0257/#id16
Similarly I would use a clearer naming convention. The program won't run faster if you call it "energy_curve_calculator_function_using_curve_fit" or "f", but when you look into your files, you will know the difference.
Lastly, I would also advise you add a comment block (or one line) between each section of code explaining what it does.

Right now pep8 only checks that your lines aren't too long. I would concentrate a little more on making sure someone who didn't write the code (or you in a few months) can read what it's doing based on the flow, comments where needed and the variable names.


Get icon from website, show and update icon

I'd restructure this code significantly. The first thing I'd do is move the image-retrieval into a separate method and the image placing would then be "simpler"..

Compare your code against:

Image image = getRemoteLogo();
if (image != null) {
    // Logo updated
    updateLogo(image);
}

This is largely reimagining what you're doing, and depending on how you prefer it, you might move the nullcheck into updateLogo.

This allows you to hide the image and get rid of the IMO .. clunky null-initialization before the try-block:

private Image getRemoteLogo() {
    try {
       URL remoteUrl = new URL(Config.getRemoteLogoUrl());
       return Toolkit.getDefaultToolkit().getImage(remoteUrl);
    } catch (MalformedURLException ex) {
       // this is the point where you can slap the programmer :D
       ex.printStackTrace();
       return null;
    }
}

This neatly hides the hardcoded dropbox URL in a (not further specified) Configuration, which allows changing the logo location without having to replace classes.

Also it cleanly abstracts away the Image-loading and has clear behavior in error cases. It also gets rid of the superfluous boolean flag you have.

The updateLogo(Image) is history then, you do your ComputerCheck and set the image accordingly.

The startup slowdown is something you'll have to live with.

Oh and I changed the variable names slightly. Use speaking names wherever possible, future maintainers (including yourself) may not be able to map out which number corresponds to which URL :)


You need to use ActiveModelSerializers (AMS) to serialize your json responses based upon the instances of your class.

class CampaignsController < ApplicationController
  def index
    render json: { characters: campaign.characters }
  end

  def create
    @character = campaign.characters.new(character_params.merge(char_class_id: char_class.id))

    if @character.save!
        render json: @character, serializer: CharacterSerializer, status: 201 # This should automatically be formatted by AMS
    else
        not_found('Something went wrong: Check line 24 of the Character Controller')
    end
  end

  private

  def campaign
    @campaign ||= Campaign.find_by_id(params[:campaign_id])
  end

  def char_class
    @charClass ||= CharClass.find_by_id(params[:character_char_class_id])
  end
end

This is how you AMS class for Character class should look like

class CharacterSerializer < ActiveModel::Serializer
  attributes :message, :character_name, :character_class, :character_level, :character_experience, :character_gold, :character_perks, :character_image

  def message
    'Successfull added this character to the campaign!'
  end

  def character_name
    return object.character_name + ' the ' + character_class # check the associations
  end

  def character_class
    object.charClass.class_name
  end

  def character_perks
    # Unsure what this get names methods does so im leaving it for you to refactor
    get_names(object.character_perks),
  end

end

Also add this to your ApplicationController

class ApplicationController < ActionController::Base

  # Add this to your application controller

  def not_found(message = nil)
    render json: { message }, status: 404
  end

end

I'll update the refactored model class based upon your info soon. Hope this helps for now.


Yes, #3 is the one - this is exactly what Dependency Injection/Inversion of Control containers are meant for - removing the assembly part of the services from the main code.

Using an external DI framework will also give you additional benefits, such as stubbing out services while unit testing, allow future extensions to services without changing your main code, etc.

A good start to which framework to use you can find here: How do the major C# DI/IoC frameworks compare?


It's pretty simple and readable as far as it goes, which is good. It doesn't do a whole lot but I have some comments that you might consider.

methods?

It's curious that you mention mimicking classes but there are no function pointers in the structs. In C it's more difficult to get the constructor in there, but print could be a function pointer.

typedef struct {
    //...
    void (*print)(struct player);
    //...
} player;

player new_player() {
    //...
    new_player.print = print_player;
    //...
}

int main(){
    //...
    user.print(user);
    //...
}

Initializers

C does have a nice initializer syntax, esp. with C99's designators. Your
constructor function could be somewhat nicer by using the initializer.

player new_player() {

    player new_player = {
    .health = 100,
    .armor_level = 0,
    .currency = 0,
    .player_weap = {
        .name = "Starter Sword",
        .damage = 1,
        .durability = 100
        }
    };

    return new_player;
}

Or even simpler with a compound literal.

player new_player() {
    return (player) {
    .health = 100,
    .armor_level = 0,
    .currency = 0,
    .player_weap = {
        .name = "Starter Sword",
        .damage = 1,
        .durability = 100
        }
    };
}


How to refactor this groupby alike method but with index?

First of all get rid of these tuples. After one week you will forget what each int represents. Define simple struct/class for your brick.

Second thing, small performance suggestion for big row count - explicit initial list size:

... = new List<Tuple<char, int, int, int>[]>(myBoard.Length);//assuming myBoard is an array

without it, list would be recreated and rewritten every 4 new elements.

Below is mine implementation with linq extensions. Probably it is not faster. I don't know if it is more readable, but at least line count is smaller :)

public struct Brick
{
    public char Symbol { get; set; }
    public int Length { get; set; }
    public int RowID { get; set; }
    public int ColumnID { get; set; }

    public override string ToString()
    {
        return string.Format("{0} {1} {2} {3}", Symbol, Length, RowID, ColumnID);
    }
}

public Brick[][] GetHorizontalBricks(char[][] board)
{
    return
        board
            .Reverse() //bottom up row order
            .Select((row,rowIndex) =>
                row
                    .Select((c,i) => new { c = c, i = i })
                    .GroupBy(symbol => symbol.c) //assumption that we will never see 2 groups of same nonzero character in single row
                    .Where(symbol => symbol.Key != 0 && symbol.Count() > 1)
                    .Select(brick =>
                        new Brick
                        {
                            Symbol = brick.Key,
                            RowID = rowIndex,
                            ColumnID = brick.First().i,
                            Length = brick.Count()
                        })
                    .ToArray()
            )
            .Reverse() //reverse again to show result in form like you provided
            .ToArray();
}

and Console app test:

static void Main(string[] args)
{
    char[][] board = new char[][]
    {
        new char[] { (char)0, (char)0, 'b' ,'b','b','c'},
        new char[] { (char)0, (char)0, 'h' ,'g','g','c'},
        new char[] { (char)0, (char)0, 'h' ,'a','a','c'},
        new char[] { (char)0, (char)0, 'f' ,'f','d','d'},
        new char[] { (char)0, (char)0, 'i' ,'j','e','e'},
        new char[] { (char)0, (char)0, 'i' ,'j',(char)0,(char)0}
    };

    foreach (var row in new Program().GetHorizontalBricks(board))
    {
        Console.WriteLine("Row:");
        foreach (var brick in row)
            Console.WriteLine(brick);
    }

    Console.ReadLine();
}


Move an element up / down an array in Javascript

What you are doing isn't very efficient. First you remove the element from the array, and to close the gap, every single element after it has to move position. Then you insert the element again, and to make room for it, every single element after it has to move position again, back to where they started.1

What you are doing is simply swapping to elements in the array. There is no need to do any array manipulation or touch any of the other elements.

$scope.moveUp = function(index)
{
    if (index === 0) {
        return;
    }
    [$scope.list[index], $scope.list[index-1]] = [$scope.list[index-1], $scope.list[index]];
};

$scope.moveDown = function(index)
{
    if (index === $scope.list.length - 1) {
        return;
    }
    [$scope.list[index], $scope.list[index+1]] = [$scope.list[index+1], $scope.list[index]];
};

I'm using destructuring to swap the values. It's basically a way to assign multiple values at the same time without needing a temporary variable.

1 That's how it works in theory at least. It will depend on the internal working of the JavaScript engine, and whether it has been optimized for this kind of task.


1. (Possible) bugs

There are several problematic aspects of the code in the post. However, it is impossible for me to tell whether these really indicate bugs, because the code has no documentation, and so it is impossible for me to know what it is supposed to do.

The code is not portable to Python 3, because of the use of the true division operator here:

ix = (i/self.i_every) % len(self.keys)

This causes ix to be a float, which results in a warning when evaluating self.env_idx[ix]:

  VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future

The code needs to use the floor division operator, i // self.i_every, to ensure that ix is an integer.
The shuffling logic is fragile: it relies on ix successively taking the value 0 (so that the array is shuffled) and then 1 (so that the shuffled flag is cleared). But this depends on exactly the right sequence of values of t being passed to step. If other values get passed, then the array may never be shuffled:

>>> e = SimpleEnv([1, 2, 3], [10, 20, 30])
>>> for t in np.arange(dt, 100, period * 3):
...     i = e.step(t)
>>>

The output "shuffling" does not appear, indicating that the array was never shuffled.
There is nothing about the interface that stops t from going backwards in time. But if you try to go backwards past a shuffle, then you get different results for the same values of t:

>>> e = SimpleEnv([1, 2, 3], [10, 20, 30])
>>> e.step(period * 1); e.get_key()
(0, 1)
>>> e.step(period * 4), e.get_key()
shuffling
(0, 2)
>>> e.step(period * 1), e.get_key()
(0, 2)

It would be better if the interface were designed so that unsupported actions (like going backwards in time) cannot be attempted.

2. Separation of concerns

An important software design principle is separation of concerns. The idea is that you separate your code into pieces, each of which has a single concern. This makes the pieces easier to understand and easier to test, and makes it more likely that you can reuse some of them.

In this code there are three concerns:

Maintaining corresponding arrays of keys and values.
Generating a sequence of shuffled indexes into the arrays of keys and values, where the indexes are re-shuffled after they have been used.
Converting timestamps into entries in the sequence of shuffled indexes.

Let's see how these might be implemented:

This concern seems very simple. We can just have two variables:

keys = np.arange(4)
values = np.arange(1, 5)

In some circumstances it would make sense to have a state object which varies over time. But we're using NumPy and a rule of thumb when it comes to using NumPy is that we want to do as much as possible with uniform arrays (even if these are big) rather than using iterators that have to evaluate code at each step. So let's write a function that constructs the sequence we need:

def reshuffled_indexes(n, m, state=np.random):
    """Return an array of shape (n,) consisting of shuffled indexes in the
    range [0, m). The indexes are re-shuffled each time they have all
    been used. Optional argument state may be a np.random.RandomState
    instance for random reproducibility.

    """
    out = np.empty((n,), dtype=int)
    r = n % m
    for i in range(0, n - r, m):
        out[i: i + m] = state.permutation(m)
    if r:
        out[-r:] = state.permutation(m)[:r]
    return out

For example:

>>> reshuffled_indexes(17, 4)
array([1, 0, 2, 3, 2, 1, 0, 3, 0, 3, 1, 2, 0, 1, 3, 2, 2])

Note the optional state argument. This is a useful argument to have on any function that produces a random result, because in order to test a function with random results, you need to be able to ensure reproducibility of the random number sequence.
The time series t is converted to an array of indexes by subtracting dt, dividing by the period, and rounding to the nearest integer:

t = np.arange(dt, run_time, dt)
index_t = ((t - dt) / period).round().astype(int)

Now that you have the array of indexes, you know how many reshuffled indexes you are going to need:

r = reshuffled_indexes(index_t[-1] + 1, len(keys))

and you can use this to index the arrays of keys and values to get time series for each:

r_t = r[index_t]
keys_t = keys[r_t]
values_t = values[r_t]


Caesar Cipher Encryption / Decryption in Python

The shift() function was fairly easy to understand, in no small part because
you've chosen reasonable and clear variable names. Here are a few relatively
minor suggestions regarding the function. (1) Strings are iterable, so you can
convert to characters directly. (2) Python makes iteration so easy that looping
over data via an index is usually not needed. Instead, just iterate directly.
And for those cases when an index is needed, enumerate() is often the best
option, because it provides both index and value -- which helps your code by
reducing its visual weight and thus aiding readability. (3) The assignment to
new_char is a moderately complex expression. One way to improve code
readability is to such computations apart. (4) A dict to lookup a letter's
index would eliminate the need to scan ALPHABET repeatedly.
# 4
ALPHA_IDXS = {a:i for i, a in enumerate(ALPHABET)}

def shift(string, n):
    # 1
    shifted = list(string)
    # 2
    for i, char in enumerate(shifted):
        if char.isalpha():
            # 3 and 4
            j = (ALPHA_IDXS[char.lower()] + n) % len(ALPHABET)
            new_char = ALPHABET[j]
            if char.isupper():
                new_char = new_char.upper()
            shifted[i] = new_char # The only place we use index.
    return ''.join(shifted)

Another technique to consider is converting shift() into a generator function.
This simplifies the code even more because the function no longer has to
assemble a return data collection -- although at a small cost to the caller,
which must do the assembling. Here's what that might look like.
def shift(string, n):
    for i, char in enumerate(string):
        if char.isalpha():
            j = (ALPHA_IDXS[char.lower()] + n) % len(ALPHABET)
            new = ALPHABET[j]
            char = new if char.islower() else new.upper()
        yield char

You did a nice job in getGoodness() with keeping the steps of the algorithm
very clear. Here are a few suggestions: (1) Because bool is a subclass of
int, you can treat True and False as integers -- just add up the Trues.
Also, functions like sum() take any iterable, so you don't need an
intermediate list. (2) msg_length seems a bit misleading: it is not the
length of msg; it is the number of alpha characters. (3) A Counter can
compute letter frequencies for you. (4)
Shouldn't this calculation be done on a lowercase version of the text?
from collections import Counter

def getGoodness(msg):
    # 1 and 2
    n_alphas = sum(i.isalpha() for i in msg)
    # 3 and 4
    freqs = Counter(msg.lower())
    msg_frqs = [round(freqs[a] / n_alphas, 4) for a in ALPHABET]
    diffs = [abs(a - b) for a, b in zip(msg_frqs, FREQUENCIES)]
    avg_diff = round(sum(diffs) / len(diffs), 4)
    return avg_diff

Finally, some comments about the orchestration code. (1) Put your code in
functions. (2) Set yourself up for testing. It helps a lot during the
development and debugging lifecycle. (3) In the loop to compute goodnesses for
the shifted strings, a tuple seems like a handier data structure than a
dict. It simplifies the code and is better suited for min(). (4) I
recommend the habit of setting up all scripts so they can take arguments --
again, useful during development and sometimes usage.
# 1
def main(args):
    # 2
    TESTS = (
        (
            "Oqqcfrwbu hc ozz ybckb zokg ct ojwohwcb, hvsfs wg bc kom o pss gvcizr ps opzs hc tzm. Whg kwbug ofs hcc gaozz hc ush whg toh zwhhzs pcrm ctt hvs ufcibr. Hvs pss, ct qcifgs, tzwsg obmkom psqoigs pssg rcb'h qofs kvoh viaobg hvwby wg wadcggwpzs. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Ccv, pzoqy obr mszzck! Zsh'g gvoys wh id o zwhhzs. Poffm! Pfsoytogh wg fsorm!",
            "According to all known laws of aviation, there is no way a bee should be able to fly. Its wings are too small to get its fat little body off the ground. The bee, of course, flies anyway because bees don't care what humans think is impossible. Yellow, black. Yellow, black. Yellow, black. Yellow, black. Ooh, black and yellow! Let's shake it up a little. Barry! Breakfast is ready!",
        ),
        (
            "Ebiil, tloia!",
            "Hello, world!",
        ),
    )
    for msg, exp in TESTS:
        # 3
        scores = []
        for i in range(26):
            txt = ''.join(shift(msg, i))
            g = (getGoodness(txt), txt)
            scores.append(g)
        got = min(scores)[1]
        # 2 Always be testing.
        print(exp == got, '=>', got[0:30])

# 4
if __name__ == '__main__':
    main(sys.argv[1:])


Checking if a LinkedList is a palindrome

As Ratchet Freak points out, your code uses an \$n\$ size stack to manage the reversal of the list, so it's \$O(n)\$ space complexity. The question is whether there's a better way too, though.

First up, your comparison here is very dubious:

if (s.pop() != iterator2.next()) {

That's doing a native object comparison, and you are comparing Integer, and not int. This is bound to fail, and I am surprised it works for you (I presume Java is reusing Objects for your int value boxing). You should be calling this instead:

if (!s.pop().equals(iterator2.next())) {

Then, your isPalindrome variable is useless. It's never set to false. Instead you return immediately if it's not a palindrome (which is a good thing).

Further, consider that your input is a LinkedList which is a double-linked implementation (as you pointed out) which means a reversed iteration is "easy".

public boolean isPalindromeList(LinkedList<Integer> list) {
    ListIterator<Integer> forward = list.listIterator(0);
    ListIterator<Integer> reverse = list.listIterator(list.size());
    while (forward.hasNext()) {
        if (!forward.next().equals(reverse.previous())) {
            return false;
        }
    }
    return true;
}

You can see this running in ideone: https://ideone.com/LmfQrB


Use portable code as much as possible

You should avoid

#include <Windows.h>

when you can use portable c++ features (according the current c++ standard) instead:

Sleep(1000);

should be

std::this_thread::sleep_for(1s); // needs to #include <thread>

As you see that's much more readable, and will compile on other operating system environments as well.

Use a better random number generator

letter = rand() % 27 + 64;

Doesn't provide a good random number generator (besides you missed to initialize the seed with srand() and your program will produce the same sequence of random numbers with every run).

C++ provides easy to use and configurable (regarding the wanted number distribution requirements) random generators like listed here.

Do not use system("pause");

Besides that statement isn't portable again, it introduces security problems. If there's a program existent and accessible at the system called pause that doesn't do what's intended (but some malicious things instead), that one will be executed.

If you wan't to wait for some input rather use std::cin >> dummy; or such.

Check the state of input operations

 cin >> ph;

You never checked that the user inputted a valid number. If something like xxxx is entered, your loop will never stop.

Better do something like:

bool stop = false;
do
{
    int ph;
    cout << "Press 1 to continue or 2 to stop\n";
    if(cin >> ph) {
         if (ph == 1)
         {
             Points += act();
         }
         else if(ph == 2)
         {
             stop = true;
         }
    }
    else {
         cin.clear();
         std::string dummy;
         std::getline(cin,dummy); // Consume the invalid input
    }
} while(!stop);

  I would like to add a way to either check if a word is correct, or to suggest words but it would mean I need to connect it to a dictionary of some sort (which I don't know how to do).

You can use std::map or std::unordered_map to create dictionaries.

I can't give you any sample code how to integrate these in your program, since it's unclear for me how you wan't to make use of these exactly.


The heal method and the handling of health points strike me as odd. In the current setup,

heal does not heal; it simply returns a random number. It also currently has no direct relation to any part of the Pokemon class, so it doesn't really make sense as a method of the class.
The health points of each Pokemon are "loose" in the script, along with instances of the Pokemon class. You have a Pokemon class representing a Pokemon, and it makes sense that health would be an attribute of a Pokemon itself.

The design can be improved by doing something like (stripped down):

class Pokemon:
    def __init__(self, start_health):
        self.hp = start_health

    def heal(self, heal_amount):
        self.hp += heal_amount

    def hurt(self, damage):
        self.hp -= damage

Now, you can do something like:

mew = Pokemon(100)
mew.hurt(50) # Ow
mew.heal(49) # Back to almost full
print(mew.hp) # Prints 99

And you don't need to have loose health values floating around in the code for each Pokemon in use. Using the method like this also lets you check the health after healing to ensure that you didn't exceed the maximum health allowed. As long as you're going to make use of a class, you can benefit by having it encapsulate all the data (like health) that's directly relevant to it.

I also decided to not have heal generate the random amount to heal for the following reasons:

Are you sure that every time you want to heal you want it to be a random value, and are you sure you will always want it to be a random value in the range (10, 25]? As you mentioned, what about potions? Are you sure you want potion healing to be random, and always in that range? What about when Pokemon level up and have more health? Are you sure that you'll only want to heal them in that narrow range? The Pokemon class simply does not have enough information to always decide how much Pokemon should be healed by, and that shouldn't be its responsibility in the first place anyways.
Using random data complicates testing. Say you want to add tests to ensure the correctness of the hurt and heal methods. You would expect this to always pass:

start_health = 100
poke = Pokemon(start_health)
poke.hurt(50)
poke.heal(50)

# A simplified test
print("Test Passed?", poke.hp == start_health)

If the methods are correct, you would expect this test to always pass. With random data though, your tests can't be as definitive. You may know that it was hurt by some value, then healed by some value, but that isn't enough information to ensure correct functionality (unless you're only testing that it produces results in a certain range).

For small toy projects like this, testing isn't really necessary (although it's always good to practice). When you start dealing with larger projects split across multiple files, written by multiple people, and changing code that you haven't looked at in potentially months, you need tests to ensure that code stays correct from one change to the next. Making testing easier helps ensure the validity of the tests, and prevents you from wasting your time trying to Jerry-rig some test in place after the fact.

If some code wants to hurt the Pokemon by a random amount, they can generate the random data themselves to pass in to hurt.

while battle_continue == True: has a redundant condition. while (and if) just check if their condition is truthy. You can just write:

while battle_continue:


Java sort by selection: which is better in regards to readability and efficiency?

Readability:

The first one is far more readable because it can be translated at so:

selection(tab)
    for each value of tab: i = (0->size-1)
        minor = tab[i]
        for each value of tab: j = (i->size-1)
            if (tab[j] < minor)
                swap(minor, tab[j])
        tab[i] = minor;
    return tab;

This is very simple and symmetric.  The otherSelection is a bit more difficult to read because it tracks a pos.  This is a uncommon way to do this sort (not necessarily bad).  Then it does the swap post inner loop.  This was personally more difficult for me to read.  The first wins here.

Time Efficiency:

Both run \$O(n^2)\$.  However, otherSelection does only swap once per n-iteration.  This actually is more efficient to do.

Space Efficiency:

selection only needs 4 int variables where as otherSelection needs 5.  It's a bit more space efficient to use selection.  As user @200_success mentioned, the space efficiency is the same at worse case since both are constant space \$O(1)\$.  This isn't counting the input space (which you shouldn't really anyways).

Final verdict:

selection is a better option than otherSelection as far as readability.  However, otherSelection is better for efficiency.  This is a better variant of otherSelection which is just as good when it comes to space efficiency:

public static void selectionSort2(int[] x) {
    for (int i=0; i<x.length-1; i++) {
        int minIndex = i;      // Index of smallest remaining value.
        for (int j=i+1; j<x.length; j++) {
            if (x[minIndex] > x[j]) {
                minIndex = j;  // Remember index of new minimum
            }
        }
        if (minIndex != i) {
            //...  Exchange current element with smallest remaining.
            int temp = x[i];
            x[i] = x[minIndex];
            x[minIndex] = temp;
        }
    }
}

If you care for efficiency, this is the better selection sort option.  You could also do a bit-swap for when swapping the variables.

Final notes:  Since this is Java, you don't need to do the return statement at the end.


Fundamentally, not really. When you need to create a nested structure, there are no built-in ways to get around explicitly testing if the intermediate object(s) exist, and creating them if they don't.
(If you just wanted to access a possibly-existing nested element, you could use optional chaining to achieve it concisely, but nested creation is much more verbose)
There are libraries that do nested creation for you, but they ultimately implement the same sort of logic under the hood:

// Just for demonstration, I do not recommend using a library for this:

let map = {};
function newRoom(x, y) {
  _.setWith(map, [x, y, 'monsters'], {}, Object);
}
newRoom(0, 0);
console.log(map);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

One shortcut you can make in your original code is to simply check map[x] instead of comparing against undefined. You can also declare the monsters object inline when assigning the room. You should also declare the map object with const unless you're reassigning it later.
Now that logical nullish assignment exists, you could use it as well, though given how new it is, you (or others who may read the code) may not be comfortable with it, and it may look a bit confusing regardless:

const map = {};

function newRoom(x, y) {
    map[x] ??= {};
    map[x][y] = {
        monsters: {}
    };
}

/*
or
function newRoom(x, y) {
    if (!map[x]) {
      map[x] = {};
    }
    map[x][y] = {
        monsters: {}
    };
}
*/

newRoom(0, 0);
console.log(map);

I do recommend using brackets for your if blocks. They'll make it a bit easier to read and will keep you from accidentally writing on the wrong indentation level assuming that something is inside the if block, when it actually isn't.
Note that both the above code and your original code will overwrite contents of the room if it already exists in the map. Hopefully that's desirable.
There are a few alternative methods to achieve the same result that require fewer characters of code, that code golfers or minifiers could use, but they sacrifice readability and therefore aren't worth it IMO, eg:

const map = {};

function newRoom(m,n){map[m]||(map[m]={}),map[m][n]={monsters:{}}}

newRoom(0, 0);
console.log(map);

Another thing to consider - as of ES2015, Maps are more suited to dynamic properties than objects. If you want a Map, use a Map instead of an object.
function newRoom(x, y) {
    if (!map.has(x)) {
        map.set(x, new Map());
    }
    map.get(x).set('y', { monsters: {} });
}


Validating the difference in days between two dates

Client code:

   status, msg := permanentExpiry(entity, 100, time.Now())

  The idea is that this code check if the PermanentExpiry is at most 100
  days in the future from a given compare date.

  It can be assumed that both dates are in the same timezone. The dates
  should be compared only on day basis, that's why the time objects are
  reset to 00:00:00 time.

  Still feels a bit clunky and not sure if it's clear that the
  comparision is done based on full days only.

In Go, encapsulate that sort of logic in useful functions like isExpired. For example,

expire.go:

package main

import (
    "fmt"
    "time"
)

// isExpired returns true if date is not before the expiration date.
// The expiration date is start date plus expire days.
// Start is in the same time zone as date.
func isExpired(date, start time.Time, expire int) bool {
    loc := date.Location()
    y, m, d := start.In(loc).Date()
    x := time.Date(y, m, d+expire, 0, 0, 0, 0, loc)
    return !date.Before(x)
}

func main() {
    now := time.Now()
    starts := []time.Time{
        time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()),
        now,
        time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location()),
    }
    expire := 10 // 100
    for _, start := range starts {
        for i := expire - 2; i <= expire+1; i++ {
            date := now.AddDate(0, 0, i)
            x := isExpired(date, start, expire)
            fmt.Println(
                x, "\t",
                date.Format("2006-01-02 15:04"),
                start.Format("2006-01-02 15:04"), expire,
            )
        }
        fmt.Println()
    }
}

Output:

false    2017-07-20 11:07 2017-07-12 00:00 10
false    2017-07-21 11:07 2017-07-12 00:00 10
true     2017-07-22 11:07 2017-07-12 00:00 10
true     2017-07-23 11:07 2017-07-12 00:00 10

false    2017-07-20 11:07 2017-07-12 11:07 10
false    2017-07-21 11:07 2017-07-12 11:07 10
true     2017-07-22 11:07 2017-07-12 11:07 10
true     2017-07-23 11:07 2017-07-12 11:07 10

false    2017-07-20 11:07 2017-07-12 23:59 10
false    2017-07-21 11:07 2017-07-12 23:59 10
true     2017-07-22 11:07 2017-07-12 23:59 10
true     2017-07-23 11:07 2017-07-12 23:59 10


It's fine. Yes, in an ideal world, we'd verify that the id we passed into the PeopleRepository.Get() method is the same one that's getting passed to the client.Get() method, but that's also getting down into testing the internal implementation of the method. What you really care about here is that when the Person isn't found, a specific exception is thrown, so in this particular case it's fine.

Remember, we want to tests for specific results, not the internal implementation.

I'm going to quote Jon Skeet's comment to a related SO question.

  I would test that the usage of those functions do the right thing, rather than testing that the exact same function is used. – Jon Skeet Oct 8 '12 at 9:33


The code you have there may accomplish the task you have in mind for it, but it's not useful for a "real world" usecase.
That's because usually you'd want to be able to run an algorithm like this multiple times on the same graph, maybe even concurrently.
The problem that's posing itself here is that Node mixes two concerns: Representing the graph and traversing it.
Storing the Visited state inside the Node is really useful, but it's also quite limiting. As such you could greatly benefit from storing visited Nodes as a Set instead to separate traversal from representation.

There's also some minor optimization possibilities:

Replace the foreach in the Node constructor with AddRange

Once .NET 5 releases (or you switch to .NET Core) You can slightly simplify the while loop in the BFS itself using searchQueue.TryDequeue(var (node, length)).

Storing visited nodes in a HashSet (or similar) enables reformulating EnqueueNotVisitedChildrenNodes as:
foreach (var child in node.Children.ExceptWith(visited))
{
    searchQueue.Enqueue((child, length + 1));
}

This reformulation of course then messes with the visited state of nodes you didn't actually visit yet, since you set Visited when you enqueue the node, not when you actually visit it.
This flagging visited when enqueueing utterly breaks as soon as you start working with "weighted graphs", where the smallest number of edges may not be the optimal path (like the following)
(A) -(1)- (B) -(1)- (C)
  \                 /
   -------(5)-------

Going from (A) to (C) via (B) is cheaper than the direct route here :), if your real target was a node (D) that's only connected to (C), your current code would route you through (C) because the shorter route through (B) would be ignored since (C) already counts as visited when you dequeue (B).

Overall this code is really nice and clean, but it lacks general applicability (which is not a bad thing in itself).


Simultaneously searching listings by attributes such as category, title, postcode

I HIGHLY suggest using PHP PDO with prepared statements ALONG with filtering each field for specific accepted characters.

But to answer your question, your method above is no longer considered safe and can be exploited.

PDO & Tutorial:

http://php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

You can use preg_match to filter for specific character sequences.

Basic Regex Filter Example:

if (preg_match('/^[0-9-]+$/', $_POST['postcode']))
{
    //POSTAL CODE IS GOOD TO GO
    //Filters for charaters "0-9" along with "-" for longer postal codes
}
else
{
    //REJECT
}


Simple Registration Form. I would like to get rid of code duplications

In functional programming terms, using Lenses could help you modify nested object elegantly. There are no native supported lenses in kotlin language but some libraries provided. Check klenses or arrow.


About your existing code
There's only two things I have to complain about in your current ItemStorage.

public void setItems(int[] a, int[] b) See those parameter names? a and b. They represent completely different things, they should have been named itemIds and amount.

Item(id)s in one array, and amount in another. What if each item would have enchantments? (which, for the sake of simplicity, also is an int for now) Would you add private int[] enchantments? Then what if you would add damage for items? Or other properties? It's a bad bad idea to store it like this. It's not all about performance, it's also about extensibility.

But then I thought, I could just do an Item object, with the tools in that class for that item, and have a private property isStackable and amount.

Yes, yes, YES!!

If you want to change some value of an Item object, you'll need to call a new construct and then get the old value then add the new value and then pass it to the construct. with primitives you can do that instant, which gives also performance positives

No, no, NO!!
If by "construct" you mean constructor, then no - use a setSomeValue(int newValue) method instead. If by "construct" you mean a set method like setSomeValue(int newValue), then sure, if you want to change some value you'd have to do item.setSomeValue(item.getSomeValue() + 3); but that's fine. This won't affect performance much. Java even use a Just in Time compiler to boost the performance of such calls.
If you want to you could even add a method like this to your Item class:
public void changeSomeValue(int change) {
    this.someValue += change;
}

This is especially useful for values you change often without caring much about the actual value at the moment, such as changing a player's HP. (I personally often call methods such as player.heal(4) or player.damage(6))
Designing an Inventory and Items
I think you should look at how the API of Bukkit (the Minecraft server) has been made. Bukkit have a class for ItemStack and also an interface for Inventory. You can probably find a lot of inspiration from Bukkit, although you probably won't even need half of it.
Here are some example classes that I think you could use:
public class ItemStorage {
    private Item[] items;
    private SomeObject owner; // Player, Chest, whatever... if you need it.
}

public enum ItemType {
    WEAPON(1, 1), SHIELD(2, 1), MONKEY(3, 4), MUG(4, 42), FISH(5, 64);
    // You never know what you might need in your game

    private final int id;
    private final int maxStackSize;
    private ItemType(int id, int maxStackSize) {
        this.id = id;
        this.maxStackSize = maxStackSize;
    }
}

public class Item {
    private ItemType type;
    private int amount;
}

If you want to somehow dynamically add items, then an enum won't work well for you, use an int in that case. Although I think an enum is good enough for now.


In order to solve this problem you should either use a stack or recursion to keep track of the current nesting levels. The proposed solutions (including the linked one from assylias) will not do when you have multiple different delimiters and also string delimiters.

Here is a solution that seems to work based on recursion. It can probably be made a little shorter but i tried to keep it readable:

public class BalancedDelimiters {

    private static class NotBalancedException extends RuntimeException {
        private static final long serialVersionUID = 1L;
    }

    private static final Map<Character, Character> blockDelimiters = new HashMap<Character, Character>();
    static {
        blockDelimiters.put('(', ')');
        blockDelimiters.put('[', ']');
        blockDelimiters.put('{', '}');
        blockDelimiters.put('<', '>');
    }

    private static final Set<Character> stringDelimiters = new HashSet<Character>();
    static {
        stringDelimiters.add('\"');
        stringDelimiters.add('\'');
    }

    public boolean checkForBalance(String extractedString) {
        try {
            consume(extractedString, null);
            return true;
        } catch (NotBalancedException e) {
            return false;
        }
    }

    private String consume(String remainingString, Character currentDelimiter) {
        while (true) {
            int nextInterestingCharacter = getNextInterestingCharacter(remainingString);
            if (nextInterestingCharacter == -1) {
                if (currentDelimiter == null) {
                    return "";
                } else {
                    throw new NotBalancedException();
                }
            }

            char delimiter = remainingString.charAt(nextInterestingCharacter);
            remainingString = remainingString.substring(nextInterestingCharacter + 1);
            if (closes(delimiter, currentDelimiter)) {
                return remainingString;
            } else if (isBlockStartDelimiter(delimiter)) {
                remainingString = consume(remainingString, delimiter);
            } else if (isStringDelimiter(delimiter)) {
                remainingString = consumeToNextStringDelimiter(remainingString, delimiter);
            } else {
                throw new NotBalancedException(); // we found a delimiter that we could not use!
            }
        }
    }

    private int getNextInterestingCharacter(String remainingString) {
        for (int i = 0; i < remainingString.length(); i++) {
            if (remainingString.charAt(i) == '\\') {
                i++; // also skip next character
            } else if (isAnyKindOfDelimiter(remainingString.charAt(i))) {
                return i;
            }
        }
        return -1;
    }

    private String consumeToNextStringDelimiter(String remainingString, char delimiter) {
        for (int i = 0; i < remainingString.length(); i++) {
            if (remainingString.charAt(i) == '\\') {
                i++; // also skip next character
            } else if (remainingString.charAt(i) == delimiter) {
                return remainingString.substring(i + 1);
            }
        }
        throw new NotBalancedException();
    }

    private boolean closes(char delimiter, Character currentDelimiter) {
        if (currentDelimiter == null) {
            return false;
        }
        return blockDelimiters.get(currentDelimiter).equals(delimiter);
    }

    private boolean isAnyKindOfDelimiter(char c) {
        return isBlockDelimiter(c) || isStringDelimiter(c);
    }

    private boolean isBlockDelimiter(char c) {
        return isBlockStartDelimiter(c) || isBlockEndDelimiter(c);
    }

    private boolean isBlockStartDelimiter(char c) {
        return blockDelimiters.containsKey(c);
    }

    private boolean isBlockEndDelimiter(char c) {
        return blockDelimiters.containsValue(c);
    }

    private boolean isStringDelimiter(char c) {
        return stringDelimiters.contains(c);
    }
}

Note that I handle normal delimiters (i call them block delimiters) differently from string delimiters as they behave quite differently. I'm using an exception to control flow when the string is not balanced. Maybe some will find that a bit ugly but it saves a few lines of code (i think).


Creating an Array of Linked Lists from a BST

Your return types and the types left of the assignments should be as general as possible, so you only need to change the instantiation if you want to change the implementation to an other type of list.

List<Node>
List<List<Node>>

In general it is a good idea to replace ifs that covers the whole function by a guard condition. So you get rid of a level of nesting.

{
    if (n == null) return arr;
    if (arr.get(level) == null) arr.add(level, new LinkedList<Node>());

    arr.get(level).add(n);
    addLists(arr, n.leftChild, level + 1);
    addLists(arr, n.rightChild, level + 1);

    return arr;
}

I only checked your code layout. If you want to see if it works, write a test as tb     suggested.


Connection to a database, do I need to create a new one and close it everytime?

I have to agree with Praveen's comment that you should open a connection when you need it and close it when your are done with the Database operations.

But first I have to make a serious objection to this statement:

ps = conn.prepareStatement(SQL_QUERY.replace("?", id));

That is not the way you should use prepared statements!

By using that, you are opening yourself to SQL Injection. Consider what would happen if an id something like 'random-useless-name' OR 1 == 1; DROP TABLE sometablename; -- was given. Catastrophic failure!

Instead, use this:

ps = conn.prepareStatement(SQL_QUERY);
ps.setString(1, id);

You might want to take a look at the PreparedStatement tutorial to see how PreparedStatements are normally used. If you are using parameters in the query, use the setXXX methods!

I would say that yes, it is better if you extract the Connection parameter to the main method and provide it to your getSomething method(s). I would use it as a local variable if possible though. Also make sure to put the conn.close(); inside a finally statement and not at the end of the try.

public static void main(String[] args) {
    Connection conn = null;
    try {
        int lines = 0;
        DBExtract ex = new DBExtract();
        ...
        conn = openConnection();
        lines += ex.getSomething("1", file, conn);
        lines += ex.getSomethingElse("1", file, conn);
        lines += ex.getSomethingDifferent("1", file, conn);
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.close();
    }
}

In this way the caller could also control the transactional state of bulk operations, that is it can decide if and when to commit or to rollback.

Finally, using local variables in place of member variables reduces the chance of having connection leaks, because you really need to be sure to call the "close" method.

Future suggestions:

If you have an application that requires several database connections that should be able to be open simultaneously I recommend using c3p0 Connection Pooling

If you are working on a mid-size to large-size project and want some assistance with the database stuff, I recommend learning Hibernate

C3P0 and Hibernate can be used at the same time, but they require some configuration. They take a while to configure for the first time, but once you got it running they do a lot of things for you. (They're just suggestions though, you should prioritize the other things first!)


Please stop using:

using namespace std;

It may seem like a time saver. But for anything that isn't a toy program, it causes problems with collisions. So, it is a bad habit to get into. Stop before it becomes a habit.

You have alternatives.
You can selectively bring stuff into the current scope:

using std::cout;
using std::vector;

Alternatively (my preference) you prefix stuff in the the standard library with std::. The name std was chosen so it was short enough that people would not be hampered with typing it.

Prefer to use the C++ version of the headers:

#include <time.h>
// Prefer
#include <ctime>

Note: This also puts the functions in the standard namespace.

This is correct:

int size = sizeof(array)/sizeof(int);

But it makes the code brittle. If you change the type of the array. You also need to remember to change type here in the size expression. It is best to let the compiler deduce this so use:

int size = sizeof(array)/sizeof(array[0]);

Usage:

qsort(array, 0, size-1 );

Here you are making right bound point at the rightmost item. In C++ it is so common that the end points one past the end of the data it may make the code slightly harder to grok. I would stick with the standard convention of pointing one past the end. This means there will be some adjustment in your qsort but not that much and it makes it easier for C++ users to read.

Prefer pre-increment:

++leftposition;  // rather than leftposition++;

Though it makes no difference in this situation. There are situations where it can. So it one of those habits you should get into. Then when the types of objects are changed you do not need to search your code to make sure you are using the efficient version you know you used the efficient version automatically.

Your test for a sortable array is not aggressive enough:

if (rightbound > leftbound) {

You only don't sort if the array is zero length. Which may potentially lead to long recursion as you randomly choose a pivot point that always dives stuff to one side (luckily your non standard code below saved you by always leaving the pivot off subsequent sorts).

The real answer is you only need to sort arrays that have a size >= 2. (size zero and one are already sorted).

if ((rightbound - leftbound /* +1 depending on if you rightbound is one past or not*/ ) >= 2)

Small difference from a standard implementation here:
Which can potentially give you an infinite loop.

        while ( array[leftposition] < pivot ) {
            leftposition++;
        }
        while ( array[rightposition] > pivot ) {
            rightposition--;
        }

What happens if the value is equal to the pivot.
In that case it will go to a random side. Also if both left and right side hit a value that is equal to pivot then you will swap them and restart the loop which will do nothing swap them and restart the loop (etc)

        while ( array[leftposition] <= pivot ) {
            leftposition++;
        }
        while ( array[rightposition] > pivot ) {
            rightposition--;
        }

Your left bound of the first recursive call is wrong.

    qsort( array, 0, leftposition - 1 );
    qsort( array, leftposition + 1, rightbound );

Should be leftbound.

    qsort( array, leftbound, leftposition - 1 );
    qsort( array, leftposition + 1, rightbound );

Since there can potentially be more than one value equal to pivot. Maybe you can remove the all from the side you put them in.

You need to look at the standard libs.

We have a std::swap()

void swap(int &a, int &b)

// use
std::swap(val1, val2)

We have a way to print stuff:

void output( int* array, int size )

// use
std::copy(std::begin(array), std::end(array), std::ostream_iterator<int>(std::cout, "\n"));

We have a way to generate values:

void randomize( int* array, int size )

// use
generate(std::begin(array), std::end(array), ::rand);

This is what I got:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <ctime>

void qsort( int* array, int leftbound , int rightbound );

int main()
{
    //declare array
    int array[100];

    //get size of the array
    int size = sizeof(array)/sizeof(array[0]);

    //randomize value
    std::srand(std::time(NULL));
    std::generate(std::begin(array), std::end(array), std::rand);

    //start the quicksort algorithm
    qsort(array, 0, size);

    //output the array
    std::copy(std::begin(array), std::end(array), std::ostream_iterator<int>(std::cout, "\n"));
}

void qsort( int* array, int leftbound , int rightbound )
{
    if ((rightbound - leftbound) >= 2)
    {
        int pivot = array[leftbound + (rand() % (rightbound - leftbound))];
        int leftposition    = leftbound;
        int rightposition   = rightbound - 1;

        while ( leftposition < rightposition )
        {
            while ((array[leftposition] <= pivot) && (leftposition < rightposition))
            {   ++leftposition;
            }
            while ((array[rightposition] > pivot ) && (leftposition < rightposition))
            {   --rightposition;
            }
            std::swap(array[leftposition], array[rightposition]);
        }
        // At least the pivot point will be on the left hand side.
        // This will also be the largest value. So move the leftposition back
        // to remove all the pivot points.
        while(((leftposition-1) > leftbound) && (array[leftposition-1] == pivot))
        {   --leftposition;
        }
        qsort(array, leftbound, leftposition-1);    // leftposition is one past the end of the left
        qsort(array, rightposition+1, rightbound);  // Thus at the start of the right.
    }
}


Calculating price after sales commission and discount

Just a quick note: Don't use floating point variables where you may need exact results:

Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required
Why not use Double or Float to represent currency?

Fortunately Java has BigDecimal.


Horrible case statement for displaying a title

There are a few issues with this method:

The parameter kind is not descriptive enough. Is this a kind of report? Is it report_type?
You seem to be looking up a Location, Position and Department using the same id. I'm not sure this is possible, but if it is, you should rather use the relations rather than id-lookups.
This method is trying to generate a report's subtitle, presumably in the controller. The conditional of the case statements should be replaced by polymorphism. Something like separate classes which all respond to the same method.

I don't quite understand the context of your code, but aim for something like

class PositionReport
  # ...
  def subtitle
  end
end

class GradeReport
  # ...
  def subtitle
  end
end

Then you are reasoning about different report types, each of which handles it's own subtitles (and other logic).

Just my two cents.


It's not terrible as it stands, but I think there are some ways it might be improved.
Include all needed files
The function needs several #include files that are not listed.  Specifically, it needs these:
#include <stddef.h>
#include <stdio.h>
#include <limits.h>

It's important to list those, especially for a beginner.
Be careful with signed and unsigned
In the binary function, the compares an int iByte to a size_t nBytes, but size_t is unsigned and int is signed.  Instead, declare both variables as size_t types, or better, see the next suggestion.
Count down instead of up
If we count down instead of up, not only do many compilers generate more efficient code, but we also avoid the signed/unsigned problem mentioned above.
Declare variables in as small a scope as practical
Putting all definitions at the top of the function is an antique style of C.  In modern C (C99 and later) we declare variables as late as practical, ideally as they are defined, to avoid problems of uninitialized variables.
Use a bitmask directly instead of calculating
I would write the inner loop like this:
for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1)

That makes it very clear that we're using a bitmask and how it is calculated and handled.
Use a convenience cast
Rather than casting p every time, I'd be inclined to declare an internal unsigned char * variable and use that instead.
Avoid encoding types in names
C is a statically typed language, so it is neither necessary nor desirable to encode the type within the name.  See NL.5 for more.  (Those are C++ guidelines, but this is equally applicable to C.)
Use pointers
Sooner or later, even beginners are going to need to learn how to use pointers.  They have the considerable advantage here in simplifying the code.
Use const where practical
The function does not and should not modify the pointed-to value, so it's better to make that explicit and declare it const.
Consider separating the function into two
One way to think of this code is that it's printing one or more bytes with additional separators and formatting.  That suggests an alternative which is to separate out the part that just prints the ones and zeroes from the loop.
Results
Here's the slightly refactored code using all of the suggestions above:
#include <stddef.h>
#include <stdio.h>
#include <limits.h>

void toBinary(const unsigned char *ptr) {
    for(unsigned char mask = 1U << (CHAR_BIT-1); mask; mask >>= 1) {
        putchar(*ptr & mask ? '1' : '0');
    }
}

void binary(const void* p, size_t nBytes) {
    for(const unsigned char* ptr = p; nBytes; --nBytes) {
        putchar('[');
        toBinary(ptr++);
        putchar(']');
        if(nBytes > 1) {
            putchar('\t');
        }
    }
    putchar('\n');
}

#define BINARY(x) binary(&x, sizeof x)

int main(void) {
    char a = 85;
    int b = 0x12345678;
    BINARY(a);
    BINARY(b);
}


Extension method to retrieve list of days in the current week

Let's talk about two major things in this: building a modular API, and Unit Testing.

This can be easily unit tested, you should have 7 tests, one for a date in each day of the week. Let's pick a Week (past, present or future, doesn't matter), for this I'm going to pick an easy week. Since DayOfWeek.Monday is the first day of your week, we'll pick the first week of a month that starts on a Monday.

Scrolling backwards in my calendar I found August, 2016. August 1st, 2016 is a Monday, so we'll test that week.

The problem right now with your code is that it cannot be tested. You have to reset the system clock to test it. This is not a hard problem to fix. We'll redefine the API a little bit (add a default parameter, basically):

public static DateTime[] Daily(this TimeSpan ts, DateTime? checkDay = null)

So that's easy, now we can specify a specific day to check. All we have to do in the code is use that variable.

var weekDate = checkDay ?? DateTime.UtcNow;

Bam. That should be the first line of the method. That will make sure we get weekDate set to a valid DateTime.

Alright, good. So we redesigned the API a little and made it support an extra feature with no effort. Now we need to talk about that return.

Generally speaking: robust, modular API's that return a collection should return an IEnumerable<T> of some sort. I may have the user specify a specific DayOfWeek and try to find the first date in a give week that is that DayOfWeek, so I don't need the entire list (potentially). This is because each caller has different requirements (potentially), and to most closely follow SRP we shouldn't care about the resulting collection.

Our API doesn't need to worry about the collection as a whole, only generating each element in it. This may be a bizarre concept to understand at first, but our method should not care what the caller is going to do with the collection itself. We just generate it, so we don't need a list or array, we just need to return each element as it's generated.

We do this by returning an IEnumerable<DateTime> so that we can use the yield return statement instead of return. This will allow us to make a more modular API that doesn't always have to enumerate everything. It's the caller's responsibility to call .ToArray() if they need an array, or .ToList(), or enumerate it, ect.

public static IEnumerable<DateTime> Daily(this TimeSpan ts, DateTime? checkDay = null)

Lastly, different users' may have their week start on a different day. We want to accommodate for that, so we'll create a new default parameter for that.

public static IEnumerable<DateTime> Daily(this TimeSpan ts, DayOfWeek startDayOfWeek = DayOfWeek.Monday, DateTime? checkDay = null)

Bam. Now we've built a much more robust API that can be tested more easily as well. It should be trivial to implement this, in fact, we only need to change a few parts of your original code.

public static IEnumerable<DateTime> Daily(this TimeSpan ts, DayOfWeek startDayOfWeek = DayOfWeek.Monday, DateTime? checkDay = null)
{
    var compDate = checkDay ?? DateTime.UtcNow;
    var days = startDayOfWeek - compDate.DayOfWeek;
    var startDate = compDate.AddDays(days);

    for (var i = 0; i < 7; i++)
    {
        yield return startDate.AddDays(i).Date + ts;
    }
}

It's even shorter now, supports your original use-case, and add's many more supported use-cases.

Then we build Unit-tests, they'll all have mostly the same body:

var expected = new DateTime[]
{
    new DateTime(2016, 8, 1, 15, 0, 0),
    new DateTime(2016, 8, 2, 15, 0, 0),
    new DateTime(2016, 8, 3, 15, 0, 0),
    new DateTime(2016, 8, 4, 15, 0, 0),
    new DateTime(2016, 8, 5, 15, 0, 0),
    new DateTime(2016, 8, 6, 15, 0, 0),
    new DateTime(2016, 8, 7, 15, 0, 0)
};
var inputTimeSpan = new TimeSpan(15, 0, 0);
var inputDate = new DateTime(2016, 8, 1);

var actual = Daily(inputTimeSpan, checkDay: inputDate).ToArray();

CollectionAssert.AreEquivalent(expected, actual);

Just change inputDate. Once we do this we'll see that on 2016-08-01 we get a failed result. No big deal, we just need to make sure we fix our method. (Easy fix too.)

Our bug is the offset, on Sunday you'll get Monday-Sunday for the upcoming week. (So on 7 Aug 2016 you get 8 Aug 2016 - 14 Aug 2016.) That's fine, to fix it we'll just check if days > 0 and if so we'll subtract from it.

days = days > 0 ? days - 7 : days;

We'll just add that after we assign days the first time, and bam. We're done.

Final Code

public static IEnumerable<DateTime> Daily(this TimeSpan ts, DayOfWeek startDayOfWeek = DayOfWeek.Monday, DateTime? checkDay = null)
{
    var compDate = checkDay ?? DateTime.UtcNow;
    var days = startDayOfWeek - compDate.DayOfWeek;
    days = days > 0 ? days - 7 : days;
    var startDate = compDate.AddDays(days);

    for (var i = 0; i < 7; i++)
    {
        yield return startDate.AddDays(i).Date + ts;
    }
}

As you can see, it's still nice and short, and it's more robust than the original. :) This was an excellent start, and hopefully you take more out of this than just a bug fix. :)


Using DAOs

  The problem that I have is that these objects all need to be stored in a database, and I need methods to retrieve the information, create the objects and return them. Since it does not make sense - at least to me with my limited experience in OOP - for an object to have access to the database and be able to fetch itself, I'm using a Database class for each of my main objects that are stored in the database : CompanyDatabase, CandidateDatabase, OfferDatabase.

You are right that it would not make sense for an object to have access to the database and fetch itself, and you have more or less the right approach.
The classes that perform the database operations are commonly called "DAO" -- data access object. (I recommend to rename those classes to CompanyDao, CandidateDao, OfferDao.)

It's not common to make the data accessor methods static.
If you use DAO instances instead of static method references,
then you get a very flexible design where you could change the backend of your operations by simply passing a DAO instance that implements the same interface, but instead of a database, it transfers data from a web service, or a csv file,
or via radio transmissions from the moon.

Class design

Avoid public fields in classes, like $id and $name in Company.
Fields are an implementation detail of a class,
and should not be easily manipulable from outside,
but strictly through dedicated accessor methods.

Working with SQL

Avoid SELECT *.
It's recommended to name the columns you need explicitly,
for two reasons:

Prevent wasted bandwidth between your program and database fetching unnecessary columns
Make sure you receive the columns in the right order, regardless of their ordering in the table

The SELECT query is from a table called companies,
but the UPDATE query is into a table called compagnies.
I suspect one of them is a typo.
In any case,
some frameworks recommend naming tables with singular words,
for example in this case I'd go for "company" instead.


Best data Structure for storing a phone keypad format

It's not possible to say if this method is a good or useful abstraction without context which you have not provided. Accordingly, this review is of the method by itself.
My primary concern with this method is that it is hard to read and understand. Complexity leads to bugs, and should be avoided where possible. This method is doing a simple thing in a complex way. Readers have to worry about a loop and three branches instead of a simple, static mapping.
keypadDemo() should return the Map, not print it. Let the client decide what to do with it.
ax and hm are very poor variable names. Variable names should clearly indicate the value they hold.
Using an integer to magically act as characters makes the method harder to read.
Use the most appropriate abstraction. Map<Integer, List<Character>> would be preferable. The type of list is an implementation detail.
A loop is the wrong structure to build this map. The code is hard to read, which means it's easy to introduce bugs and hard to notice them.
Short-circuiting the loop might make it easier to read.
Empty lists would be better than using null. It's easier to write code that correctly handles an empty list than to special-case null checks.
In idiomatic Java, there is whitespace before a { and after a }. There is whitespace after a for, if, etc.
If I were to need this method in my own code, it would look like: (untested)
/**
 * Generates a mapping from digits on a telephone keypad to the letters for
 * digit. The letters are in alphabetical order. Digits with no letters
 * map to an empty list.
 */
public static Map<Integer, List<Character>> digitsToCharacters() {
    Map<Integer, List<Character>> digitsToCharacters = new HashMap<>();
    digitsToCharacters.put(0, Arrays.asList());
    digitsToCharacters.put(1, Arrays.asList());
    digitsToCharacters.put(2, Arrays.asList('a', 'b', 'c'));
    digitsToCharacters.put(3, Arrays.asList('d', 'e', 'f'));
    digitsToCharacters.put(4, Arrays.asList('g', 'h', 'i'));
    digitsToCharacters.put(5, Arrays.asList('j', 'k', 'l'));
    digitsToCharacters.put(6, Arrays.asList('m', 'n', 'o'));
    digitsToCharacters.put(7, Arrays.asList('p', 'q', 'r', 's'));
    digitsToCharacters.put(8, Arrays.asList('t', 'u', 'v'));
    digitsToCharacters.put(9, Arrays.asList('w', 'x', 'y', 'z'));
    return Collections.unmodifiableMap(digitsToCharacters);
}


This looks like a good attempt. Let's first start assuming we only have to deal with positive values.

private int getProductOfMaximalsForMoreThanTwoElements( List<int> B)
{
    int max1 = B.Max();
    B.RemoveAt(B.IndexOf(max1));
    int max2 = B.Max();
    B.RemoveAt(B.IndexOf(max2));
    int max3 = B.Max();
    return max1 * max2 * max3;
}

This method would provide the solution. So let's review it.

Starting with a couple of style choices, method names in C# should be PascalCase. Additionally, the name of the method is vague. The method provides the product of the 3 biggest numbers: GetProductOfTop3Numbers.

B.IndexOf(B.Max()) is doing unnecessary work. Max loops over the entire list to find the maximum value, and IndexOf does it all over again. That's a waste of effort. Sadly, System.Linq doesn't provide an ArgMax method, so we will have to spin our own:"

public static int ArgMax(this IList<int> list) {
  var max = int.MinValue;
  var argmax = -1;
  var index = 0;
  foreach(var item in list) {
    if (item > max) {
      max = item;
      argmax = index;
    }
    index++;
  }
  return argmax;
}

Here, instead of looping through the list to find the maximum value, and then search the list for that value, we can just return the index we found that biggest value at. The max is then easily retrievable through B[index].

The act of searching the list for the max, and popping it can be its own method:

public static int PopMax(List<int> list)
{
  var argmax = list.ArgMax();
  var max = list[argmax];
  list.RemoveAt(argmax);
  return max;
}

Our initial method would then be:

private static int GetProductOfTop3Numbers(List<int> list) {
  var product = 1;
  product *= PopMax(list);
  product *= PopMax(list);
  product *= PopMax(list);
  return product;
}

Or, more generic:

private static int GetProductOfTopNNumbers(List<int> list, int n) {
  var product = 1;
  for(var times = 0; times < n; times++) {
    product *= PopMax(list);
  }
  return product;
}

Now let's return to the actual problem: negative numbers. This is what caused you problems introducing a bunch of if-statements. Let's see if we can find something for that.

We want the highest possible product. If we simply take the top 3 items from the list, we might risk missing out on very negative numbers. Take for instance the list new [] { -5, -5, -3, -1, 0, 1, 2, 3 }. In this case, the naive solution would be 1 * 2 * 3, but actually -5 * -5 * 3 has a bigger product. Note that if we consider negative numbers in our solution, it will always have to be a pair of negative numbers, to cancel out the - signs.

This pair would then always be the two lowest entries in the list. The two most negative numbers together should provide the biggest product out of all negative numbers. The product of these can then be compared to the product of the biggest numbers, to decide which of the two sets to pick.

Furthermore, because we will never take 3 negative numbers (because the product would be negative), we can freely take the biggest number in the list. Should this number also be negative (because the input only consists of negative numbers), this is fine as well, because it would then be the least negative number, which still would result in the biggest product.

So, to recap:

Take the biggest number
Take the next two biggest numbers, or take the next two smallest numbers
Check which together has the biggest product
Done

For the mins, we need to provide a similar ArgMin and PopMin implementations. Also realise that simultaneously popping items from the list at both ends might cause troubles if this list is very short, so be sure to copy the list:

private static int GetProductOfTopNNumbers(List<int> list, int n) {
  var copiedList = new List<int>(list);
  var product = 1;
  for(var times = 0; times < n; times++) {
    product *= PopMax(copiedList);
  }
  return product;
}

All in all, that leaves us with:

public int Solution(int[] A) {
  var list = A.ToList();
  var max = PopMax(list);
  return Math.Max(max * GetProductOfMinNNumbers(list, 2), max * GetProductOfTopNNumbers(list, 2));
}

public static int ArgMin(this IList<int> list)
{
  var min = int.MaxValue;
  var argmin = -1;
  var index = 0;
  foreach (var item in list)
  {
    if (item < min)
    {
      min = item;
      argmin = index;
    }
    index++;
  }
  return argmin;
}

public static int PopMin(List<int> list)
{
  var argmin = list.ArgMin();
  var min = list[argmin];
  list.RemoveAt(argmin);
  return min;
}

private static int GetProductOfMinNNumbers(List<int> list, int n)
{
  var copiedList = new List<int>(list);
  var product = 1;
  for (var times = 0; times < n; times++)
  {
    product *= PopMin(copiedList);
  }
  return product;
}


A 3-D vector class built on top of numpy.array

Your code and text mismatch. You state that you want to use x, y and z, but you don't actually do it. You only use them in the initializer, and then you use them as named parameters when you recreate your object when returning the value. So your code kind of obfuscates that you are working on a numpy array.

Simplify overridden functions

You could also simplify your code some as almost all of the functions does the same:

OPERATIONS = {
    "add" : numpy.add,
    "mul" : numpy.multiply,
    "sub" : numpy.subtract,
    ...
}

def _apply_operation(self, value, operation):

    if isinstance(value, type(self)):
        result = OPERATIONS[operation](value._data, self._data)
    elif isinstance(value, Number):
        result = OPERATIONS[operation](value, self._data)
    return type(self)(*result)

And this could be called like:

def __add__(self, value):
    return self._apply_operation(value, "add")

Another question is why do you use if ... elif, without any else. This does leave for potentially cases where neither of them hit, and this could lead to the result being undefined when returning.

If however you actually mean else instead of elif you simplify the calculation to:

result = OPERATIONS[operation](value._data if isinstance(value, type(self))
                                           else value,
                               self._data)

Or possibly even loose the result and do:

return type(self)(*OPERATIONS[operation](value._data if isinstance(value, type(self))
                                                     else value,
                                         self._data)

Consider adding/changing __repr__ and __str__

In Python it's normal to add spaces after commas, something your __str__ doesn't do. I would change the __str__ and add a __repr__ method like the following:

def __str__(self):
    return str('!r'.format(self))

def __repr__(self):
    return 'Vector3({0}, {1}, {2})'.format(*self._data)

Implement a better test scheme

Your tests are executed but you only have a visual test of them. A much better option would be to use doctest. This would allow you to write tests in the header of each function, and you could be sure they all works as expected.

Something like the following:

def __add__(self, value):
    """Adds the value into self, and returns result as Vector3.

    >>> Vector3(1, 2, 3) + Vector3(2, 4, 6)
    Vector3(3.0, 6.0, 9.0)

    >>> Vector3(1, 2, 3) + 5
    Vector3(6.0, 7.0, 8.0)
    """

    return self._apply_operation(value, "add")

And then in your main code you could simply do:

doctest.testmod()

If all tests pass, you'll see nothing, and it they fail, you'll see why the fail and both the expected and actual results.

Properties

If you want to use x, y and z as aliases into self._data you could use properties which changes self._data like the following:

@property
def x(self):
    """Property x is first element of vector.

    >>> Vector3(10, 20, 30).x
    10.0
    """
    return self._data[0]

@x.setter
def x(self, value):
   self._data[0] = value

...

if __name__ == '__main__':
    doctest.testmod()

    a = Vector3(1, 2, 3)
    a.x = 10.0

    print('a = {}, a.z = {}'.format(a, a.x))

Which would output:

a = Vector3(10.0, 2.0, 3.0), a.z = 10.0

Do however remove the setting of self.x, self.y and self.z from __init__ so you don't have conflicting data variables.


pyCMD; a simple shell to run math and Python commands

The first thing I notice with your code is that the code is a very long global script. To resolve this I'd start by moving your code into functions.
The actual calculations could be as simple as say:
def add(arg1, arg2):
    print(float(arg1) + float(arg2))

To then get the help information we could add a docstring.
def add(arg1, arg2):
    """
    Add:
     Description: Adds 2 numbers
     Syntax: add [num1] [num2]
    """
    print(float(arg1) + float(arg2))

We can get both the docstring and the output of the operation with Python. To get the docstring to be nicely formatted we can use textwrap.dedent.
>>> add("10", "5")
15.0
>>> import textwrap
>>> textwrap.dedent(add.__doc__.strip("\n"))
Add:
 Description: Adds 2 numbers
 Syntax: add [num1] [num2]

To then reduce the amount of lines of code we can bundle all these functions into a dictionary. And just index the dictionary to get a specific function.
COMMANDS = {
    "add": add,
    "sub": sub,
    # ...
}

fn = COMMANDS["add"]
fn("10", "5")

15.0

Whilst you can build the dictionary and execute the commands yourself, you could instead subclass cmd.Cmd. You will need to change the functions slightly to only take a string as input, and prefix do_ to any commands available to the commandline.
import cmd

class PyCMD(cmd.Cmd):
    intro = 'Welcome to pyCMD, user\nStarting command line, use "help" for help'
    prompt = ": "

    def do_add(self, arg):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        arg1, arg2 = arg.split()
        print(float(arg1) + float(arg2))

PyCMD().cmdloop()

Welcome to pyCMD, user
Starting command line, use "help" for help
: help

Documented commands (type help <topic>):
========================================
add  help

: help add

        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]

: add 10 5
15.0

The help is clearly a bit on the broken side. To fix this we can change the docstring after the function.
class PyCMD(cmd.Cmd):
    def do_add(self, arg):
        # ...

    do_add.__doc__ = textwrap.dedent(do_add.__doc__.rstrip(" ").strip("\n"))

This is a bit ugly and doing this for each function would be horrible. So we can create a function to do this.
def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))

class PyCMD(cmd.Cmd):
    def do_add(self, arg):
        # ...

    clean_doc(do_add)

This is still a bit on the ugly side so we can use @ to do this for us. This is called a decorator. This makes sense because we're decorating how __doc__ is seen. Note that we changed clean_doc to return fn.
def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))
    return fn

class PyCMD(cmd.Cmd):
    @clean_doc
    def do_add(self, arg):
        # ...

We can add another function like clean_doc, but this time make it a closure if you want to easily add your validation of two arguments.
import functools

def command(fn):
    @functools.wraps(fn)
    def wrapper(self, arg):
        args = [token for token in arg.split()]
        try:
            arg1, arg2 = args
        except ValueError:
            print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
        else:
            return fn(self, arg1, arg2)
    return wrapper

class PyCMD(cmd.Cmd):
    @command
    @clean_doc
    def do_add(self, arg1, arg2):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        print(float(arg1) + float(arg2))

import cmd
import textwrap
import functools

def command(fn):
    @functools.wraps(fn)
    def wrapper(self, arg):
        try:
            arg1, arg2 = arg.split()
        except ValueError:
            print('Too many or too little args, 2 args required, if you want to not use an arg, use a "."')
        else:
            return fn(self, arg1, arg2)
    return wrapper

def clean_doc(fn):
    fn.__doc__ = textwrap.dedent(fn.__doc__.rstrip(" ").strip("\n"))
    return fn

class PyCMD(cmd.Cmd):
    intro = 'Welcome to pyCMD, user\nStarting command line, use "help" for help'
    prompt = ": "

    @command
    @clean_doc
    def do_add(self, arg1, arg2):
        """
        Add:
         Description: Adds 2 numbers
         Syntax: add [num1] [num2]
        """
        print(float(arg1) + float(arg2))

PyCMD().cmdloop()

Welcome to pyCMD, user
Starting command line, use "help" for help
: help

Documented commands (type help <topic>):
========================================
add  help

: help add
Add:
 Description: Adds 2 numbers
 Syntax: add [num1] [num2]
: add 10 5
15.0

Other commands left for you to implement


PermCheck Codility with time complexity of O(N)

This code involves sorting an array of \$N\$ elements, so it has \$O(N * log N)\$ time complexity. To achieve \$O(N)\$ time complexity, you need to avoid sorting input data. Instead, you can create an array of \$N\$ bools to check that each number from \$1\$ to \$N\$ is present in the input array.


Displaying random "ads" from an XML document

If you can use any format, use serialized PHP, it's by far the fastest.

<?php

class Ad {

  public $alt;

  public $departmentName;

  public $linkTo;

  public $name;

}

function formatAd(Ad $ad) {
  return "
linkTo}'>name}' alt='{$ad->alt}'>
";
}

function rightAds($departmentName, $displayNumber) {
  static $ads = null;

  if (!$ads) {
    $ads = unserialize(file_get_contents(__DIR__ . "/smallAdsByDepartment.ser"));
  }

  $pt = $departmentName === "pt";

  /* @var $ad Ad */
  foreach ($ads as $delta => $ad) {
    if (strpos($ad->departmentName, $departmentName) !== false || strpos($departmentName, "all") !== false) {
      $noPT = strpos($ad->departmentName, "noPT") !== false;
      if (($pt && $noPT) || (strpos(__DIR__, "pt") !== false && basename($_SERVER["REQUEST_URI"]) === "admissions.php" && $noPT) || ($departmentName === "cls" && strpos($ad->departmentName, "noCLS") !== false)) {
        unset($ads[$delta]);
      }
    }
  }

  if ($displayNumber <= 1) {
    echo formatAd($ads[mt_rand(0, count($ads) - 1)]);
  }
  else {
    $keys = range(0, count($ads) - 1);
    shuffle($keys);
    $c = count($keys);
    for ($i = 0; $i < $c; ++$i) {
      echo formatAd($ads[$keys[$i]]);
      if ($i === $displayNumber) {
        break;
      }
    }
  }
}


Parsing HTML, XML into a hash map of products

On top of my head, you could convert
(string/trim (html/text (first (html/select ... to a function as it's
used twice already.

In product-hash the function extract-artist-album is called twice,
so the return value should've been reused instead.

A minor style thing is the nth, personally I'd rather use first,
second, ..., unless the indexes get larger, but YMMV.

Also, the last two forms should be in a separate function so the file
can be loaded without them being executed.


Apart from the fact I can't find any use of var loadPage It doesn't need to be an expression.
Instead try:

function loadPage(page) {
}

It is still accessible only within your code here, it is cleaner and easier to debug.
Keep your click events consistent

$(".sub-menu .menu-item, .module-item").click(function(event) {
    $(".page-content").load($(this).data('target'));
    $("title").text( $( this ).text() );
});

Is the only place you're using .click( I'd stick with the $(parent).on('click', '.selector', function(){ style.


"Histogram of Oriented Gradients" (HOG) feature detector for computer vision

As you indicated in the question, you need to vectorize the for loop:

it = product(xrange(n_divs), xrange(n_divs), xrange(cellx), xrange(celly))
for m, n, i, j in it:
    # grad value
    grad = magnit[m * cellx + i, n * celly + j][0]
    # normalized grad value
    norm_grad = grad / img_area
    # Orientation Angle
    angle = angles[m*cellx + i, n*celly+j][0]
    # (-pi,pi) to (0, 2*pi)
    if angle < 0:
        angle += 2 * pi
    nth_bin = floor(float(angle/BIN_RANGE))
    HOG[((m * n_divs + n) * n_bins + int(nth_bin))] += norm_grad

If you look at what this is doing, you're effectively labelling every pixel in the magnit array with a number below n_HOG, and then summing the normalized values for the pixels with each label.

Operations on labelled regions of images are jobs for the scipy.ndimage.measurements module. Here we can use scipy.ndimage.measurements.sum:

bins = (angles[...,0] % (2 * pi) / BIN_RANGE).astype(int)
x, y = np.mgrid[:width, :height]
x = x * n_divs // width
y = y * n_divs // height
labels = (x * n_divs + y) * n_bins + bins
index = np.arange(n_HOG)
HOG = scipy.ndimage.measurements.sum(magnit[...,0], labels, index)
return HOG / img_area

Notes:

I've used % (2 * pi) to get the angles in the range [0, 2π). An alternative that's more like your code would be angles[angles < 0] += 2 * pi but using the modulus is shorter and, I think, clearer.
I postponed the division by img_area until after the summation, because it looks to me as though in the common case n_HOG is much less than img_area and so it's cheaper to do the division later when there are fewer items. (This means that the results differ very slightly from your code, so bear that in mind when checking.)
I measure the vectorized version as being about 60 times faster than your for loop, but it's still not going to be fast enough to run at 30 fps!
I've written angles[...,0] and magnit[...,0] here in order to drop the third axis. But I think it would make more sense if you dropped this axis earlier, before computing angles and magnit, by writing Ix = Ix[...,0] or just Ix = Ix.reshape((height, width)) if you know that the last axis has length 1.

Update

Based on comments, it looks as if you are using Python 2.7, where the division operator / takes the floor of the result if both arguments are integers. So I've changed the code above to use:

x = x * n_divs // width
y = y * n_divs // height

which is portable between Python 2 and Python 3, and simpler than my first attempt:

x = (x / width * n_divs).astype(int)
y = (y / height * n_divs).astype(int)


Clang preprocessor concatenates an extra space vs. gcc - standard C99

I think this is beyond the jurisdiction of the C standard.  See https://stackoverflow.com/questions/37796947/spaces-inserted-by-the-c-preprocessor.  All the standard says on the topic is a footnote:

  Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 5.1.1.2); thus, an expansion that results in two string literals is an invalid directive.

https://port70.net/~nsz/c/c11/n1570.html#note170

But this doesn't really matter since you are not making multiply strings.

Investigating GCC and Clang...

GCC does different things depending on what you ask for:

STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)

... gets me "myProject - mySub - 1.01.c" with GCC 9.3 and -E, but ...

#include STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)

gets me myProject-mySub-1.01.c: No such file or directory.  So -E has spaces and #include doesn't.

Clang is at least consistent.  With Clang 10, #include has spaces: fatal error: 'myProject - mySub - 1.01.c' file not found And Clang 10 and -E also has spaces myProject - mySub - 1.01.c.

In my opinion, Clang's behavior makes the most sense.  Suppose you wanted a space -- how else could you do that?

#define ID(arg) arg

This is a common trick.  I think it's a good idea although it looks a little ugly when you have to use it in so many spots.

#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg

This is fine, but I think it'd be clearer to define STRINGIFY below the helper macro it uses.

Can you get away with something like:

#if VERSION == 1
#include "library-version-1.h"
#else
#include "library-version-other.h"
#endif