Three clickable navigation elements, where only one should be active

One way to trim down your code would be to make all three links trigger the same function. Inside of this function, you'll want to strip the class from each of the elements, and then assign the playing class to the element that was clicked on. This can be done by passing in the target element as a function parameter.

Also note that .attr() is a jQuery method; you're probably looking for the property className instead.

This can be seen in the following:

function active(target) {
  var elements = document.getElementsByTagName('h1');
  for (var i = 0; i < elements.length; i++) {
    document.getElementsByTagName('h1')[i].className = "";
  }
  target.className = "playing";
}

About

Poop

DGech

Hope this helps! :)


I believe that performance is extremely important on websites.
I would consider any delay at all due to requests to a logging server unacceptable.
I think you should move the logging call to a background thread,
and return the response to the user as quickly as possible.

As usual, it's probably a good idea to put a cap on the maximum number of background threads. It could be even just one thread doing all the logging tasks in sequence.

Other than this, the code looks fine to me.
It's simple and not easy to pick on.


Documentation for a Minecraft server plugin

First of all, there is a dinstinction between comments and documentation.

Documentation (Javadoc) defines the contract of what it documents. The Javadoc on a class, for example, describes what the purpose of the class is and can even give examples on how to use it. On a method, Javadoc describes what the method should be used for, along with its parameters, return type, potential exceptions... This documentation is not embedded directly in the code, but on top of it, as specification.
Comments are private; they are inside the code itself and clarify how the implementation is working.

If you want an example, you can look at the Javadoc for the HashMap class and you can then peek into the comments inside the implementation. Both describe completely different things, because they target different issues: the documentation specifies the class, the comments explain the implementation.

You are right that most of the comments are unhelpful and mostly useless. The point of a comment is to clarify the intent of the code; that is to say, not repeat it, but explain why it is doing what it is doing.

As an example, you currently have:

// Create color instance
BossBarAPI.Color barColor;
// Get current (first) boss bar
BossBar firstBossBar = BossBarAPI.getBossBars(p).iterator().next();

The first comment is, in fact, misleading as it says that the code is creating a color instance, when, in fact, it is not. It is just declaring a new variable barColor without initializing it.
The second comment is just a repeat of the code. If there were something to comment here, it would not be that we're getting the first boss bar (which the code iterator().next() already conveys sufficiently clearly); it would explain why we're getting the first boss bar to begin with.

Another example is:

BossBarAPI.addBar(p, // The receiver of the BossBar
        message, // Displayed message
        barColor, // Color of the bar
        BossBarAPI.Style.PROGRESS, // Bar style
        1.0F); // Fullness

Having a comment on every parameter is too much. This should normally be documented properly with Javadoc on the addBar method, which would explain what each parameter is. An IDE can then simply show this Javadoc (on hover for example), which will actually give more information that those short comments.

However, there are useful ones:

if (!Main.SHOW_BAR) {
    // Do nothing, as AttentionManager or another class has taken over.
    return;
}

Arguably, it isn't directly obvious that doing nothing at that place was the intention. The comment clearly explains why it is the case and helps future developers: they won't need to scratch their head wondering why this code is there.

That said, you are really missing the most important documentation of all, which is the Javadoc.

The class BossBarUpdate doesn't have any.
The constructor of BossBarUpdate "Set global variables", without mentioning what those variables are, what they are used for or what the single parameter Player p is for.
The public method run() is also without documentation. How are users of that class supposed to know what it does?


Magic Numbers

Your biggest issue is too many magic numbers and hard-coded information.

If you added at the top of your script:

ROWS = 5
COLUMNS = 5

then you could have:

def create_random_ship():
    return random.randrange(ROWS), random.randrange(COLUMNS)

Game board can be created with:

game_board = [["O"] * COLUMNS for _ in range(ROWS)]

And you can ask for input from the user with:

row = int(input(f"Enter a row number between 1-{ROWS} >: "))

Along the same vein, you could have:

print(f"""\nIntroductions:
\nYou have {INIT_AMMO} ammo and there are {INIT_ENEMY} hidden ships on map.
...""")

so your welcome instructions can keep up-to-date with any changes to your game initial conditions.

Instructions

You have a if __name__ == "__main__": guard to prevent the code from running if imported into another script, but your instruction are unconditionally printed.  You should move the instruction printing into an instructions() function, and call that only if appropriate.

Infinite Recursion

play_game() calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), which calls play_again(), which can call play_game(), ...

Traceback (most recent call last):
  [...omitted...]
RecursionError: maximum recursion depth exceeded

Don't do that.  Much simpler is to have play_again() return a True/False result, and loop based on the return value:

def play_many_games():

    instructions()

    play_game()

    while play_again():
        play_game()

    print("Goodbye!")

if __name__ == "__main__":
    play_many_games()

No more recursion.

In the comments, @Graipher suggests an alternate method to avoid the recursion:

while True:
    play_game()
    if not play_again():
        break

Yet another alternative introduces a loop condition variable, which is pre-set before the loop:

 playing = True
 while playing:
     play_game()
     playing = play_again()

All three approaches avoid the infinite recursion.

I Saw Three Ships...

ship1 = create_random_ship()
ship2 = create_random_ship()
ship3 = create_random_ship()

# ...

    elif (row, column) == ship1 or (row, column) == ship2 or (row, column) == ship3:

What are you going to do if you change this to four ships, or even 5 ships?

With computers, there are 3 important numbers: zero, one and many.  If you have more than one ship, you have "many" ships, and should put them in a container, such as a list():

ship_coordinates = []
for _ in range(ships_left):
    ship_coordinates.append(create_random_ship())

And when you want to see if a particular row/column matches any one of the ship coordinates in the container, you use the in function:

    elif (row, column) in ship_coordinates:

There are other container types you can use, such as a set() which has faster in performance.  However, it cannot add the same value more than once, and using it would result in slightly different behaviour to what you currently have.  You've mentioned that you have a bug where ships can have the same coordinates, and I am trying very hard not to accidentally fix that.  (Code Review is for reviewing working code only, not help debugging, so I am tiptoeing around the bug, so that you can fix it yourself.)


VBA - new built-in enumerations and backwards compatibility

Without Option Explicit, the msoGraphic identifier in that property scope is a Variant/Empty; there's an implicit type conversion happening when you do this:

If msoGraphic = 0 Then

Sure vbEmpty will equate to 0, or even vbNullString or "", but that's after converting to a comparable type (Integer, or String). There's a better way.

If IsEmpty(msoGraphic) Then

The IsEmpty function will only ever return True when given a Variant/Empty value - which is exactly what we're dealing with here.

  I could of course have just re-declared msoGraphic as a constant with value 28, but best practice seems to be that you should avoid using the actual value and use the enumerate constant instead

One doesn't exclude the other. If you define a public constant in an appropriately named standard module (e.g. OfficeConstants), and use it, then you are adhering to the best practice. What happens then is deliberate shadowing of the MsoShapeType.msoGraphic declaration - something Rubberduck would normally warn about, but with a descriptive @Ignore or @IgnoreModule annotation comment, the intention is clarified, and the static code analysis tool knows to ignore them - and with a link to the official documentation, you ensure the values correctly match the actual documented underlying values for each identifier:

'@IgnoreModule ShadowedDeclaration: these constants are only available in Office 2016+
Option Explicit
'https://docs.microsoft.com/en-us/office/vba/api/office.msoshapetype
Public Const msoGraphic As Long = 28
'...

What you want to avoid, is code like this, where 28 is some magic value that has no clear meaning:

If shapeType = 28 Then

  Does this seem like the best way to handle this situation?

The problem is that you can't name your property msoGraphic (well you could, but then you'd have to fully-qualify the msoGraphic constant, and then that wouldn't be compilable, even without Option Explicit), so any code (hopefully with Option Explicit specified) that means to use the name msoGraphic now needs to use myMsoGraphic instead, and that isn't ideal, because it adds to the overall cognitive load: you, future you, and eventual maintainers have to remember to avoid msoGraphic and use myMsoGraphic instead, whereas with a Public Const in a standard module that hides/shadows the constant from the referenced PowerPoint library when it exists, usage is much more seamless.

That said, while VBA is case-insensitive, a camelCase public member clashes with the naming convention of pretty much everything else in your standard libraries - enum members only have a lowercase prefix as a namespace surrogate; every type, method, member, property, procedure, function, constant, in every standard library, uses PascalCase. There's no reason to not make every single one of your own procedures use this naming convention too; also while the my prefix is ubiquitous in so many VB examples, it's not a good prefix to use in actual code.

One last thing:

  in case the value gets changed at some point in the future

It won't: MsoShapeType is defined in a shared Office library that isn't only referenced by PowerPoint projects - VBA is ridiculously backward-compatible (line numbers, GoSub/Return statements, Call, Let, DefBool keywords, to name a few should-be-extinct-but-aren't-because-backward-compatibility still-supported language features): there is no way any constant ever released into the wild is ever going to get a new value in any future release. Not going to happen.


Condense multiple if statements with or operators?

This sort of thing, with a finite set of coditions, is typically done using an array:

var codeIcons=[
      ["basecloud", "wind"],
      ["basecloud", "rain"],
      ["basecloud", "rain"],
      ["basecloud", "thunder"],
      ["basecloud", "thunder"],
      ....
    ];

Then your method simply becomes:

function returnClass(c) {
    c = parseInt(c);
    return (c < codeIcons.length) ? codeIcons[c] : ["none"];
}

Just adding to a set of advantages this method has:

sure, it is hard-coding logic, but, the presentation is better than multiple if-statements.
it is more managable - you can easily add conditions
you know exactly what conditions lead to certain output (you do not need to scan pages of code to find the right conditions
you cannot have bugs where multiple conditions lead to the same result (these types of bugs tend to creep in after maintaining the code - you have multiple or-conditions where c == xxx.
if, further down the road, you want to migrate the logic for what classes/icons to use, and when, you can easily just change where the array-of-values is configured (i.e. it can become a configuration value, not hard-coded.)


Repeating use of "v." annoys me. Do you see a nicer way?

You can use rails find_or_initialize_by method. Here is example:

  def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)
    prog = Program.find(prog_id)
    prog.values.find_or_initialize_by_participant_id_and_round_id_and_question_id(part_id, round_id, quest_id) do |v|
      v.value = new_value
      v.save
    end
  end


This is actually a nice example of how re-writing an application using MVVM can make life easier. It looks like you have the wrong idea about MVVM (your code should not be in the code behind). As a starting point, you would need an empty MVVM application with a main viewmodel and view, and know how to set up data binding and property changed events. If you haven't done this before, I would recommend taking a look at MVVM light which is a small framework that can get you up and running quickly.

The idea is that your view and viewmodel should not care where the messages are coming from - that is not their concern. This is in line with SRP and means that you can change how you read from the files (or read from somewhere else entirely) without touching any code in your V and VM layers. I would suggest starting with something like this:

ViewModel

public class MainViewModel : ViewModelBase
{
    private IMessageRepository _messageRepository;

    public MainViewModel(IMessageRepository messageRepository)
    {
        _messageRepository = messageRepository;
        FilteredMessages = _messageRepository.GetMessages();
    }

    // This will be bound to the search Button via a command
    public void FilterMessages(string searchString)
    {
        var messages = _messageRepository.GetMessages();
        FilteredMessages = messages.Where(m => m.Contains(searchString, StringComparison.OrdinalIgnoreCase))
    }

    // This will need to be bound to the ListBox and raise PropertyChangedEvents when set
    public IEnumerable<Message> FilteredMessages { get; private set; }
}

Model

public interface IMessageRepository
{
    IEnumerable<Message> GetMessages();
}

public abstract class FileMessageRepository : IMessageRepository
{
    protected readonly string FilePath;

    protected FileMessageRepository(string filePath)
    {
        FilePath = filePath;
    }

    public abstract IEnumerable<Message> GetMessages();

    protected Message BuildMessage(string line)
    {
        ...
    }
}

public class LazyFileMessageRepository : FileMessageRepository
{
    public LazyFileMessageRepository(string filePath) : base(filePath)
    {
    }

    public override IEnumerable<Message> GetMessages()
    {
        // This will read from the file as it is enumerated
        return File.ReadLines(FilePath).Select(BuildMessage);
    }
}

public class EagerFileMessageRepository : FileMessageRepository
{
    private Message[] _cachedMessages;

    public EagerFileMessageRepository(string filePath) : base(filePath)
    {
    }

    public override IEnumerable<Message> GetMessages()
    {
        // This will read from the file once (slow) and keep the result in memory
        return _cachedMessages ?? (_cachedMessages = File.ReadAllLines(FilePath).Select(BuildMessage).ToArray());
    }
}

With this implementation you are free to choose which IMessageRepository you use, and can carry out performance/profiling tests as required.


Changing the first occurrence of a text in a sentence

This, and your past few questions you have asked, have been progressively getting better.

In particular, the naming of methods and variables in this question is much better. You are suffering from 'Hungarian Notation' in the constant name. There is no need to call it STRING_TO_BE_CHANGED because we know it is a String. A simpler name TO_CHANGE would be fine.

In order to take your programming mindset to 'the next level', you have to start to abstract the functions from the particular use case. How do you write your program to solve a general problem, and apply it to a specific use case?

In this program of yours, the guts of the function newLine() can only solve one problem, changing hate to love, in a single phrase.

What I would like to see is a more general use case. In this problem, you have three Strings:

I hate you
hate
love

The objective is to search the first string for the second, and to replace it with the third.

A general function would look like:

public static String replaceWordInText(String phrase, String search, String replacement) {...}

That function embodies the logic you are trying to do, and it can replace any search with any replacement in any text.

How would this be used to solve the problem you have in the book?

public class Question5 {

    private static final String TO_SEARCH = "I hate you";
    private static final String TO_CHANGE = "hate";
    private static final String REPLACE_WITH = "love";

    public static void main(String[] args) {

        System.out.println("The line to be changed is:");
        System.out.println(STRING_TO_BE_SEARCHED);
        System.out.println("I have rephrased that line to read:");
        String result = replaceWordInText(TO_SEARCH, TO_CHANGE, REPLACE_WITH);
        System.out.println(result);
    }

    public static String replaceWordInText(String phrase, String search, String replacement) {
        ....
    }

}

Now, we have a general function applied to a specific use-case. How would the general function be implemented? Well, you have already solved that using the replaceFirst method

    public static String replaceWordInText(String phrase, String search, String replacement) {
        return phrase.replaceFirst(search, replacement);
    }


(I'm assuming you're implementing your own hashtable as an exercise/kata instead of using the CLR's, as I haven't seen anything unique here that justifies rolling your own.)

Here's some feedback:

HashMap should implement core interfaces and functionality as other .NET containers do (e.g.: IEnumerable<T>, IDictionary<TKey,TValue>, provide an enumerator implementation). As a guide, look at the Dictionary<TKey,TValue> class and see what interfaces it implements. I'd expect your code to have a similar level of service;
_blocks should be a List instead of an array, and its capacity (NumberOfBlocks) should be passed optionally through an optional constructor argument. Same applies to the equality comparer. Notice that these initial values seem very, very high - allocating a 42950-Entry[] array right off the bet for an empty container, and an additional 100,000 Entry array at first addition;
Why cast hashCode to uint?
Notice the duplicate code between Add and ContainsKey. This should be cleanly refactored;
blockIndex's and slotIndex's calculations do not seem correct. For example, you are dividing by 100,000, so this will work because int.MaxValue < 100000 * 100000. However, if you make this configurable and a lower value is used, you could go past your _blocks size. You should use modulo instead of division. Also, slotIndex will always be zero (or 1 due to rounding) as (hashCode - blockIndex * BlockSize) == (hashCode - hashCode/BlockSize * BlockSize) == (hashCode - hashCode) == 0. NumberOfBlocks is not used at all here, which is weird;
You should use LinkedList instead of rolling your own linked list (again, I'm assuming you're writing some exercise code, otherwise it's a must). Or at least you should define properties instead of exposing the values as public members;
Don't throw Exception. Create your own custom exception with a proper name;
Setting the entry variable in the if statement in Add is needless and just reduces readability.
The while loop in Add is a bit weird. Why do you need to check entry and entry.Next? I think you meant entry.Next only.
Setting entry at the end of the while look is needless and just reduces readability. I'd actually rename entry to previous for clarity.

Did you write any unit tests for this? Make sure you do so.

EDIT: typo: CRL => CLR


My non-exhaustive list of comments, considering that you seem to prefer (based on observed skill level) plain Java and do not want to use Java 8 yet.

Adhere to the Java's coding standards. One of the catches here is that method names are in camelCase, so it would be private static String solve(int n) {.
Intendation and code formatting. You seem to not be using a single standard for all your code. Furthermore I have to say that using spaces where neccessary will not cause any harm, some examples and improvements.

2.1. for(int i = 0; i < t; i++){ -> for (int i = 0; i < t; i++) {

2.2. long combos = (long)Math.pow(2,n); -> long combos = (long)Math.pow(2, n);

2.3. if(threes%5==0) { -> if (threes % 5 == 0) {

Please be consistent with your formatting is the bottom line.
On to the next point, variable names. It does not hurt to use longer variable names if that makes them more meaningful. In your main you have a variable called t, this name is not descriptive, please consider describing what it actually means. Another example is i, ii and iii in your for-loops, it is much more natural to use i, j, k for these variables.
You could use more abstraction, as your solve method is not easy to follow at all. Consider creating smaller methods that process one step at a time, this will also enable you to be able to test your methods at some point.


Extracting data from a Word document is too slow

Maybe I'm deeply wrong, but please test:

-- Almost all your variables are of type Variant, even the ones which could be Long, like counter. Define each variable with the correct type (it will be faster), in the form:

  Option Explicit
  Dim counter as Long
  Dim ColumnName1 as String, ColumnName2 as String

-- You dont really use pIndex. Try:

Dim currParagraph As Paragraph               ' will be set in loop
For Each currParagraph In objDoc.Paragraphs  ' THIS LOOP IS SLOW

-- I dont see why you make a copy of the paragraph only to 'remove junk character ?
for some weird reason I cant use currParagraph here: I have always heard that this information is with this junk character stick

All will:

'TODO : Add checks, exception handling, dynamic user options, probes, style checks, and fix slowness.
Option Explicit
Sub genTable()

Dim objDoc

'''''''''''''''''''''Modify these''''''''''''''''
Dim ColumnName1 As String, ColumnName2 As String, ColumnName3 As String, magicString As String
ColumnName1 = "foo1"
ColumnName2 = "foo2"
ColumnName3 = "foo3"
magicString = "ASD321: " ' we search for this string

Set objDoc = ActiveDocument ' Because we run inside of word as macro
''''''''''''''''''''''''''''''''''''''''''''''''''

Const MAX = 200 ' using fixed sized arrays, mod this if you'll have more than 200 entries.
Dim vulnerabilityArr(MAX) As Paragraph ' initializing the arrays
Dim severityArr(MAX) As String
Dim paragraphArr(MAX) As String

Dim counter As Long ' will count the processed entries in this
counter = 0

Dim tmpArray() As String ' for splitting
Dim currParagraph As Paragraph, prevParagraph As Paragraph ' will be set in loop
For Each currParagraph In objDoc.Paragraphs  ' THIS LOOP IS SLOW
                                                  ' currParagraph = Left(currParagraph, Len(currParagraph) - 1) 'remove junk character
    If InStr(currParagraph, magicString) > 0 Then ' assuming this string is always present and the other two target data is near it
        tmpArray = Split(currParagraph.Range.Text)             ' extract level
        Set prevParagraph = currParagraph.Previous    ' assuming the previous paragraph is the vuln. name

            'Storing the 3 extracted data
        Set vulnerabilityArr(counter) = prevParagraph
        severityArr(counter) = tmpArray(1)
        paragraphArr(counter) = prevParagraph.Range.ListFormat.ListString ' for some weird reason I cant use currParagraph here

        counter = counter + 1 ' adjusting index
    End If
Next currParagraph

Dim objTable As Table
Set objTable = objDoc.Tables.Add(objDoc.Paragraphs(objDoc.Paragraphs.Count).Range, counter + 1, 3, True, True)
                                 'Set objTable = objDoc.Tables(objDoc.Tables.Count) 'select last table

objTable.Cell(1, 1).Range.Text = ColumnName1
objTable.Cell(1, 2).Range.Text = ColumnName2
objTable.Cell(1, 3).Range.Text = ColumnName3

Dim RowIndex As Long, RowIndexy As Long

For RowIndex = 0 To counter - 1
    objTable.Cell(RowIndex + 2, 1).Range.Text = paragraphArr(RowIndex)
    objTable.Cell(RowIndex + 2, 2).Range.Text = vulnerabilityArr(RowIndex).Range.Text
    objTable.Cell(RowIndex + 2, 3).Range.Text = severityArr(RowIndex)
Next
RowIndexy = RowIndex + 1

objTable.AutoFormat (25)

End Sub


First of all, I think creating a constructor for each form type is overkill. All you need from that subclass are defaults and constraints. Why not remove all that wrapper code and just have the module return defaults and constraints?

// FormDataRules.js
define(function(require, exports, module){
  exports.defaults = { ... };
  exports.constraints = { ... };
});

Then create a validation module that contains all your validation APIs. Doing the above, setProperty falls off since you'll be operating on plain objects.

getConstraints also falls off leaving you with validateProperties which we can just rename to validate - which is a huge operation which just delegates checking to subfunctions inside the module.

// Validator.js
define(function(require, exports, module){

  exports._validateNumbers = function(data, constraint){ ... }
  exports._validatePresence = function(data, constraints){ ... }

  exports.validate = function(data, constraints){
    /* Huge operation to validate each item with each constraint it comes */
  };
});

Here's sample code using above.

define(function(require){
  var Validator = require('Validator');
  var FormDataRules = require('FormDataRules');
  var _ = require('lodash');

  var dataWithDefaults = _.defaults({
    // instance stuff
  }, FormDataRules.defaults);

  var isDataPassed = Validator.validate(dataWithDefaults, FormDataRules.constraints);

});

This makes everything easy to test. FormDataRules are just objects you can simply check values. Validator is a bunch of functions you can simply test by throwing values at it. All the data that mutates lives in a plain object that we have hold to (dataWithDefaults), and not something internal to the validator nor the rules.


Way to delegate command to methods in different files

Separate modules
You didn’t specify a file name for the code in the first block- is it something like builtin.js?
The code in the first block should be divisible into two files- one for command with executeBuiltInCommand and MOD_MODULES, and the other for vanish with USER_MODULES. They could be combined to a single module to replace the current file in the first block - what I presume is builtin.js.
Simplify .apply() syntax
The ES6 feature spread syntax can be used to replace calls to .apply().
For example:

if(isSubArg) await builtInCmdHelpers[args[1]].apply(null, [{channel,
args}, userstate]);

can be simplified to:
if(isSubArg) await builtInCmdHelpers[args[1]](...[{channel, args}, userstate]);

However, since there is a fixed length on that array of arguments, the method can be called directly:
if(isSubArg) await builtInCmdHelpers[args[1]]({channel, args}, userstate);


That's a reasonable approach, but converting to strings early and then doing everything on strings leads to a lot of extra code. Note that this construct in your code, if x!=y, essentially XORs two bits and then does something if the result of that XOR is 1.

Doing that XOR directly on the integers makes the problem simpler, the whole problem of having to pad with zeroes disappears (which about halves the code size already), and the problem is reduced to "count the ones in binary". That could still be done with a similar loop, but there is a short-cut:

return bin(x ^ y).count('1')


Shell script that copies configuration and dotfiles to repository

This is pretty nicely written. I have a couple of tips to improve it though.

Don't include trailing / in path variables

Although there's absolutely nothing wrong with this:

REPO_PATH="$PWD/"
# ...
OS="osx/"
# ...
BASH_DEST="${REPO_PATH}${OS}bash/"

In my experience, not including the trailing slash is typically more ergonomic, and sometimes even less error-prone:

You might have a function that's expecting the trailing slash, and some callers might forget to append it correctly, and there's no reasonable way to enforce at "compile time".
When I see concatenated path-like variables like $REPO_PATH${OS}bash I'm always suspicious if the caller added the slash or not.
It makes me constantly look over my shoulders and re-check all uses.

Consider this alternative:

REPO_PATH=$PWD
# ...
OS=osx
# ...
BASH_DEST="$REPO_PATH/$OS/bash"

Here, I know that "$REPO_PATH/$OS/bash" will be definitely close to what I expect,
and no need to worry about forgotten slashes anywhere.
I also know it's a path,
which is less obvious in the case of the original.

Don't execute the same thing repeatedly

When you detect the OS,
the script might execute uname 3 times.
It would be better to run it once and save in a variable.

Avoid expr

expr is archaic. Usually there are better solutions.
You could also simplify the OS detection conditions using [[ instead:

uname=$(uname -s)

# Detect OS (OS X, Linux or Windows)
if [[ $uname = Darwin ]]; then
    echo "Detected system: OS X"
    OS=osx
    ST_DIR="$HOME/Library/Application Support/Sublime Text 3/Packages/User/"
elif [[ $uname == *Linux* ]]; then
    echo "Detected system: Linux"
    OS=linux
    ST_DIR="$HOME/.config/sublime-text-3/Packages/User/"
elif [[ $uname == *MINGW32_NT* ]]; then
    echo "Detected system: Windows"
    OS=win
    ST_DIR="$HOME/AppData/Roaming/Sublime Text 3/Packages/User/"
    NPM_DIR="$HOME/AppData/Roaming/npm/node_modules/npm/"
fi

Quote paths that may contain spaces

It's not obvious that these paths will never contain spaces:

declare -a destinations=($BASH_DEST $GIT_DEST $NPM_DEST $RUBY_DEST $ST_DEST)

It's better to be safe, and put double-quotes around each.

More careful error handling

If you couldn't detect the OS, I suggest to print a warning and exit.

Use case for switches

The final OS-specific operations could be written a bit cleaner using a case statement.


I would like to kick old habits to the curb

That's a very good intention. Especially given that the present code, sadly, is rather a display of such old habits.

In order to improve, consider learning the following essentials:

PDO prepared statements (be advised that PDO is superior to mysqli for learners). Basically all your queries involving variables must be run not via query() but via prepare()/execute(), with all variables in the query substituted with placeholders.
Password hashing is essential. Just follow the simple example and store in the database not the original password but the result of password_hash() function's call.

there is no reason to limit the maximum password length. Let a user have the password as big as they wish.

the proper error reporting. first of all, always configure PHP to report errors by itself. And then never write a single line of code that intentionally outputs the error message. It's your server's configuration should be responsible for the errors' output.
Use a better code structure. Consider having both the HTML form and the handler sharing the same address, making the file with the form not called directly but included by the PHP file on demand. It will let you to utilize the POST/Redirect/Get pattern. Among other things it will let you to show errors nicely instead of bluntly aborting the script execution to show one. Collect all errors in the array and then run your query only if it is empty. Show the form back along the errors and the entered data otherwise.

the code used for the database connection is better to be stored in a separate file and then just included into every script that will need it.

avoid the code that does nothing useful. For example, running a select query to get all users from the database in order to create a user just makes no sense. You can ditch both the query and the condition that follows.

Taking all the above into consideration your code could be rewritten like this

db.php:

$host = '127.0.0.1';
$db   = 'Database';
$user = 'XXX';
$pass = 'XXX';
$charset = 'utf8mb4';

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

create_user.php

$errors = [];
if ($_POST)
{
    require 'db.php';

    $username = filter_input(INPUT_POST, 'username');
    $password = filter_input(INPUT_POST, 'password');
    $pwd_confirm = filter_input(INPUT_POST, 'confirm_password');

    if ($password !== $pwd_confirm) {
        $errors[] = "Passwords don't match";
    }
    if (strlen($password) < 8) {
        $errors[] = "Password not long enough! Must be at least 8 characters long";
    }
    if ($username === $password) {
        $errors[] = "Username cannot equal password!";
    }

    $stmt = $pdo->query("SELECT 1 FROM Users WHERE usr = ?");
    $stmt->execute([$username]);
    $user_found = $stmt->fetchColumn();
    if ($user_found) {
        $errors[] = "Username already taken";
    }
    if (!$errors)
    {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO Users (usr, pwd) VALUES (?, ?)");
        $stmt->execute([$username, $hashed_password]);
        header("Location: ."); // consider redirecting to the user profile
        exit;
    }
} else {
    $username = "";
}

include 'form.php';

form.php

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>create.html</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <?php foreach ($errors as $error): ?>

<?= $error ?>

    <?php endforeach ?>
    <form method="post">
        Username
        <input type="text" name="username" value="<?= htmlspecialchars($username) ?>">

        Password
        <input type="password" name="password">

        Re-enter Password
        <input type="password" name="confirm_password">

        <button type="submit">Create Account</button>
    </form>


Let's ignore efficiency. It took me five minutes to figure out what you were trying to do. In the kindest way possible, this is a mess. But let's fix that!

Your variable names are terrible. I have no idea what an ass is. What about an asss? Surely that's a bad idea, because it's very easy to mistake one for the other. Even if it wasn't, what are they? A variable name should describe what it holds. A bunch of random characters aren't helpful. Same goes for gpu_ouy. Is that a typo? What are gpu_a and gpu_b? What is aq? What is c?  What is saa? None of these variables names help someone reading your code understand their function.

Don't use len in a for loop. The idiomatic python approach is to just iterate over the collection (and let it deal with lengths and indices). So instead of:

for x in range(len(c.Win32_VideoController())):
    ass = str(c.Win32_VideoController()[x])

Use this:

for controller in c.Win32_VideoController():
   # do something with controller...
   pass

Some random points before we get to the big issue:

In sqa =int(((int(str(saa[1]).replace(";",""))/1024)/1024)/1000), use // instead of calling int so much. This does floor division. So int(int(x / 1024) / 1024) is the same as x // 1024 // 1024. But then you could just merge them: x // (1024 * 1024). But what are those numbers? I suspect you're converting from bytes to GB (expect 1000 MB = 1 GB isn't correct unless you're dealing with harddrives, which sometimes define the measurements like so). So instead use a constant: BYTES_PER_GB = 1024 * 1024 * 1000. Then do: int(vram_size_bytes) // BYTES_PER_GB.
As @IsmaelMiguel points out, not all cards support more than 1GB of RAM. This math will report 0 for them, which you may not want. One solution is to not use floored division (int(vram_size_bytes) / BTYES_PER_GB). When printing using the format specifier .02f so you don't get numbers with tons of decimal places (ex. "Video RAM: {:.02f}".format(vram_size_bytes / BYTES_PER_GB)).
Fix your spacing and formatting. PEP8 your code!
What is saa[1] above? You have some many magic indices that no one can discern without understanding the value of str(controller). Prefer giving things descriptive names (use variables, heck overuse variables to make things clear) to magic indices.
remove can fail (it raises a ValueError if the element isn't found in the list).
You don't need to initialize gpu_a and gpu_b (ex. gpu_a = "" is unnecessary), because later you assign stuff to them. They will be initialized on first assignment.
Given code this fragile, you definitely want to include tests. I'd imagine some integration tests would help. You can amass a list of outputs of str(c.Win32_VideoController()[0])s and manually do this string parsing. Then assert in some tests that your code outputs the thing that you expect for each. unittest will help you with this.

But now the largest issue: you're doing a ton of extra work that you almost certainly don't have to do! I can't seem to find good docs for wmi's wrapping around this, but according to the microsoft docs, this probably returns an object of some type. That means instead of all of this convoluted and fragile string parsing you're attempting, you can probably get at the information you want by just doing controller.AdapterRAM // BYTES_PER_GB or controller.Description (where controller comes from for controller in wmi.WMI().Win32_VideoController()). Open up a Python REPL by running python3 and then run the following:

>>> import wmi
>>> controller = wmi.WMI().Win32_VideoController()[0]
>>> help(controller)
>>> dir(controller)

That should give you an idea of all of the information you can get from it. You don't need to be doing all that string parsing! The information is already available on properties of the object!


So there is a consideration that needs to be made when implementing your own session handler that is not really clear in the PHP documentation.  That is that the SessionHandlerInterface does not support the create_sid() method introduced in PHP 5.5.1 & 7.   For this reason, you might strongly consider extending the PHP SessionHandler class as opposed to implementing the interface if you want best compatibility with more current PHP releases.

Again, this is actually contrary to what the PHP documentation states, but it might help give context to this decision if you look through the the feature development conversation from the core PHP developers. In a nutshell, they didn't add create_sid() to the interface in order not to break backward compatibility.  I would particularly point you to the comment from It from Dec 14, 2012 for the most compelling discussion around interface vs. object inheritance.

By having access to create_sid() method call, you could do something like:

function create_sid()
{
    $sessionId = parent::create_sid();
    // create record in database with this new session id
}

The class name seems odd.  It is not just a "Db Handler" right?  It is Db-based session handler.  So perhaps DbSessionHandler, PdoSessionHandler (if PDO is really the dependency here) or similar might be more appropriate.

Why have all the calls to DBCxn::get() throughout the class? Since this is a critical dependency for this class, you should probably pass this dependency (i.e. a valid PDO object) to the constructor.  There should be no reason for this class to keep having to try to instantiate DB connections (even if perhaps you are using a singleton here).  How about usage like:

try {
    $pdo = new DbCxn::get();
    $dbSessionHandler = new DbHandler($pdo);
    session_set_save_handler($dbSessionHandler);
} catch (PdoException $e) {
    /* bail on execution or maybe don't even catch */
}

With constructor like:

public function __construct(Pdo $pdo)
{
    $this->pdo = $pdo;
}

This gives you the benefit of knowing that you have a valid DB connection via PDO before you even try to set the session save handler.  You can bail out in your bootstrapping process rather than having exceptions/error taking place when you are actually trying to interact with session functionality.

Your implementation is a little naive in terms of handling session destruction and garbage collection.  To implement sessions in a secure and resilient way, one should strongly consider thinking of session destruction as nothing more than setting as setting session data as invalid.  That session data might need to remain in order to handle things such as race conditions from asynchronous requests, such that you can maintain good user experience in your application. Most mature implementations require setting of timestamp-based controls around data validity and a separate process for data deletion.

So here your destroy() function might simply update a field on the record that the data is no longer valid and setting a TTL (maybe a few seconds, maybe longer depending on your application needs) on when the data should be eligible for final deletion via garbage collection.

Your gc() method should then look to delete either active sessions where last update is past maximum lifetime or inactive records that have passed the data validity TTL.

I don't understand the exists property at all.  It seems unnecessary.  You can use REPLACE_INTO to design away your two code branches in write() method (or change operational order of update/insert if you wanted to perhaps remain more database agnostic as suggested in another answer).

I also think that perhaps you are thinking of these method calls being made in more of a linear fashion than what might actually be presented.

You may want to take a look at this great article on how session handlers are called relative to session management code in PHP.  By looking at this, you can see that things like session ID change can happen between calls to the other methods.

I especially like this summary comment from the article:

  The simplest way to think about custom session handlers, is to avoid
  thinking of them as objects with instance methods, although that
  happens to be how it's implemented - instead, think of the methods as
  being static; or in other words, avoid state in your implementation,
  with the exception of accidental state (for optimization/caching
  purposes), and bear in mind, the original API for custom session
  handlers was a set of individual functions, essentially the analog to
  a set of static methods, not to an object.

Right now, you are adding state to your class.

How do you handle session forwarding?  When your code calls for session ID to be regenerated, how will you forward any calls from old session to new session?  This could obviously be handled outside the session handler itself, but it certainly ties into the same data expiry consideration I noted before.

Consider namespacing your session library.

    $rows = $sth->fetchALL(PDO::FETCH_NUM);
    if (count($rows) == 0) {
        $this->exists = "n";
        return '';
    }
    else {
        $this->exists = "y";
        return $rows[0][0];
    }

This seems like it could be simplified. You are only fetching a single value after all.

How about just:

return ($data = $sth->fetchColumn(0)) ? $data : '';

Or non-ternary equivalent if you like.

Your DB interactions seem to consider "happy path" only.  What if statement preparation or execution fails?

I am adding a link to a session management library I created, not so much for you to use (though you are free to do so, though it has no built-in database handler and would need to be extended for that), but rather because I think that within the main readme and the individual class documentation, I have tried to assemble some the better known resources (to me) around session security and session management in PHP. Between this and the code itself, I hope it gives you better footing for dealing with sessions in PHP (which PHP certainly does not make easy "out of the box").

https://github.com/mikecbrant/php-ultimate-sessions


Finding common ancestor in a binary tree

1. Review

You didn't give us the definition of the node objects, so I'm guessing you used something like this:

from collections import namedtuple
Node = namedtuple('Node', 'left right'.split())

There's no docstring. How do I call common_ancestor? What is the meaning of the arguments N1, N2, and head? (I'm guessing that N1 and N2 are the nodes to find the nearest common ancestor of, and that head had to be the root node of the tree.)
The function common_ancestor does two things: it finds a node and prints a message about it. It would be better to separate these responsibilities.
The print statement means that the code is not portable to Python 3.
The function allocates a new list of three status elements for each node in the tree. But as we'll see below, we only need a total of two status elements.
The test head == N2 is not quite right. Here we need the actual node N2, not just any node that happens to be equal to N2, so the test should use is rather than ==.

2. Simpler implementation

The function common_ancestor traverses the tree in depth-first order, keeping track of which of N1 and N2 have been visited so far. So let's start with a simple depth-first traversal implementation:

def traverse(node):
    """Visit all nodes in the tree starting at node, in depth order."""
    if node is None: return
    traverse(node.left)
    traverse(node.right)

Here's a binary tree with two shaded nodes that we want to find the common ancestor of. The thin line shows the order in which nodes are visited by a depth-first traversal.

Suppose that we augment this traversal function so that it keeps track of how many of n1 and n2 have been visited so far:

count = 0
def traverse(node):
    """Visit all nodes in the tree starting at node, in depth order."""
    if node is None: return
    print("Entering {}, count={}".format(node, count))
    if node is n1: count += 1
    if node is n2: count += 1
    traverse(node.left)
    traverse(node.right)
    print("Exiting {}, count={}".format(node, count))

This figure shows the value of count on entry to each node:

And this figure shows the value of count on exit from each node:

You'll see that all the common ancestors of the two nodes have count = 0 on entry and count = 2 on exit (and only common ancestors have this property). So that means that we can implement common_ancestor like this:

def common_ancestor(n1, n2, head):
    """Return the nearest common ancestor of nodes n1 and n2 in the tree
    rooted at head.

    """
    count = 0   # How many nodes in {n1, n2} have been visited so far?
    ancestor = None

    def traverse(node):
        nonlocal count, ancestor
        if node is None or ancestor is not None: return
        count_at_entry = count
        if node is n1: count += 1
        if node is n2: count += 1
        traverse(node.left)
        traverse(node.right)
        if count_at_entry == 0 and count == 2 and ancestor is None:
            ancestor = node

    traverse(head)
    return ancestor

The nonlocal statement was new in Python 3, so if you're stuck on Python 2 then you'll have to find a workaround, for example using a status object:

class Status(object): pass
status = Status()
status.count = 0
status.ancestor = None
# etc.

3. Efficient implementation?

The implementation discussed here has to traverse the whole tree and so takes time \$ O(n) \$. Whether this is important depends on how many common-ancestor queries you have. If there are many, then you'll probably want to change your tree data structure so that you can make efficient common-ancestor queries.

Adding parent pointers allows you to bring the query cost down to \$ O(\log n) \$ on balanced trees but if you have many common-ancester queries then you may prefer to preprocess the tree into a data structure that suppose \$O(1)\$ queries. See Bender and Colton (2000) for an approach based on range-minimum queries.


Your method names do not follow capitalization standards, they should be PascalCase.

However, what's worse is that their names do not correspond to that they do:

displayTemplateNumbers() returns a formatted string (and thus doesn't "display" anything),
totalAmountOfDeletedTags() feels like it should be a property instead of a method.

And totalAmountOfDeletedTags() isn't even necessary, since it can be replaced by simple LINQ: _currentTagCollection.Count(x => x.Deleted);. And since you only need the active tags, you can simply do var activeTags = _currentTagCollection.Count(x => !x.Deleted); (h/t to @RobertSnyder).

At the end of displayTemplateNumbers() you twice call string.Format(). Instead you should do this once:

return string.Format("{0} products, {1} page{2}",
    activeTags / _selectedTemplateConfiguration.TemplateConfigurationTagsPerRow,
    totalPagesActive,
    (totalPagesActive > 1 ? "s" : string.Empty));


Note: I don't think this is what you want to hear. But I have to write "the truth". This is my personal opinions about your code.
Give me parameterized SQL or give me death!

tell me if there are any bugs or improvements to be made.

Don't suggest prepared statements.

I'm sorry, but those two requests really don't fit together in the same Code Review question.
I understand what you're doing here, and it's nice that you're doing it for learning purposes. It's nice to be able to extend the mysqli class in PHP.
However, I wouldn't recommend using the methods you have in this class. As you say:

I'm expecting very different queries in each page

Consider then: What functionality does this class provide you with? How much code does it save for you? Will it make your code more readable?
As I see it, there are primarily four lines that summarize what your class is all about:
$this -> query("INSERT INTO ".$table." (".$extracted[0].") VALUES(".$extracted[1].")");
$this -> query("UPDATE ".$table." SET ".$extracted." WHERE ".$where);
$result = $this -> query("SELECT ".$column." FROM ".$table." WHERE ".$where." ORDER BY ".$orderby."".$limit."");
$this -> query("DELETE FROM ".$table." WHERE ".$where."");

That is, you're essentially making it a little "easier" to write the SQL queries.
In your comment you ask if you can run different queries each time using prepared statements, and if you can use joins and stuff. The answer to these questions is: YES! Is it efficient? YES!. We're often talking milliseconds of difference between prepared statements and non-prepared statements (except when you perform the same prepared statement multiple times with different parameters, in which a prepared statement performs significantly faster!). If you are worried about the speed of prepared statements, don't be. They're fast. If they're slow, then there's something wrong with your database structure or your query, not with the fact that you're using prepared statements.
Here is what I personally think:

Other developers reading your code will be confused as they are not familiar with your Dbquery class
By not using your class you will be more experienced with writing SQL statements, it will probably go faster writing the SQL statements than you think.
Your class does not provide that much functionality. In fact, it can act as a restriction as writing something like select("mytable LEFT JOIN table2 ON (mytable.a = table2.b)", "table2.c, mytable.a", "mytable.a > 4", "table2.c", 5) just feels completely strange, wrong, and hard to remember what the parameters are, and you'll likely end up trying to reconstruct the resulting SQL query in your mind anyway (or is that just me?)

The point I'm trying to make here is: If you expect "very different queries in each page", then write those queries in each page. As long as they're not entirely dynamic queries, use prepared statements! Prepared statements are the way to go in the "real" PHP world.

I am aware of PDO, but I will use MySQL only, so I'm better with MySQLi. So please don't suggest PDO.

Sure, I have nothing against MySQLi myself. That's also what I tend to use when working in PHP. I think the choice of PDO vs. mySQLi is mostly opinion-based. The main advantage of PDO is that it can work with other databases except mySQL, but as you will use mySQL only, it's perfectly fine in my opinion to use mySQLi. At least you're not using the old mySQL functions!


I would really suggest that you better structure your code. Runge Kutta methods are quite straightforward, so you should have a function that iterates a single step in parallel for every variable.

Furthermore, you can slightly deviate from the standard Runge Kutta scheme if you directly store \$x + h_if_i\$ in the \$i\$th component of that vector. You only have to adopt the summation at the end to account for that.

I did so here https://github.com/miscco/Neural_Network_TC/blob/master/Iterate_ODE.h

static void add_RK(std::vector<double>& var) {
    var[0] = (-3*var[0] + 2*var[1] + 4*var[2] + 2*var[3] + var[4])/6;
}

A minimal improvement that I would do is changing this

for (int i=0; i<n; i++)
    x_vec[0][i] = x[i];

To

x_vec[0] = x;

Where you utilize the underlying copy/move constructor, which might be more efficient depending on the compiler.


Responsive search bar implementation using OOCSS

Markup

You're using way more than you need.  You have an unnecessary container element, and 2 empty elements for displaying a purely decorative icon.  This should be all the markup you need to get the same effect:

<form class="search-box">
    <input class="search-box-input" type="search" placeholder="Search"/>
    <div class="search-box-autocomplete" style="display: none;">
        Foo Bar
    </div>
</form>

Placeholder text is not a replacement for label text.  It's supposed to be for providing an example of the type of content you're looking for.

Strange that you're using the html5 placeholder property, but you're not using the html5 input type of search.

CSS

I do not subscribe to the BEM methodology, so I cannot comment as to how well you've followed it;  it always looks overly verbose to me.

As I've already stated, your icon is purely decorative.  It has no place in the markup.  The most appropriate location for it is as a pseudo element on the label for the search field (which doesn't exist here) or the form element.

The following CSS:

#container {
  width: 500px;
  margin: auto;
  margin-top: 30px;
  background: gray;
  color: black;
}

.search-box {
  width: 100%;
  position: relative;
  background: inherit;
  color: inherit;
  height: auto;
}

Can be reduced to this:

.search-box {
  width: 500px;
  margin: 30px auto 0 auto;
  background: gray;
  color: black;
  position: relative;
}

Usability

The entire color scheme has extremely low contrast.

The styling that browsers give when the input element has focus is considered a usability feature.  If it doesn't fit into your design, you're supposed to adjust it to fit, not remove it.

There's no submit button.  There are users who don't understand that they can just hit enter to submit a form.


Here's a small refinement on the technique. Wherin instead of looking for odd multiples  and removing them, you keep an extra reference in the incomplete sieve and look those specific multiples of the next prime. The first step is the same, looking for 3* (3, 5, 7, 9, ...,) but the second step you only look for 5*(5, 7, 11, 13, 17, 19, 23 , 25, ...)

Overall a small speedup, but the upside is you will never be looking for a multiple that isn't either in the partial sieve or beyond it's range.

(define (primes-up2 n)
  (cons 2 (unfold null?
                  car
                  (lambda (x) (remove-partial-seive-multiples (car x) (cdr x)))
                  (iota (quotient (- n 1) 2) 3 2))))

(define (remove-partial-seive-multiples n partials)
  (let recur ((xs partials)
              (ys partials)
              (i (* n n)))
    (cond ((null? xs) '())
          ((< (car xs) i) (cons (car xs) (recur (cdr xs) ys i)))
          ((= (car xs) i) (recur (cdr xs) (cdr ys) (* (car ys) n)))
          (else (error "you ought not hit this")))))

This works as any multiple of n still in the partial sieve must also be coprime with all primes less than N. (of which the partial sieve is a complete list)

Now while not purely functional instead of keeping the result and reversing it in the end on your second iteration, you could implement it as a tail-modulo cons. While not stickly functional on the inside, it is functional from the outside.

Another optimization would be to pass the maximum canidate to the remover of multiples and just return the xs when i is smaller than the last search.


Java beans performance with object inside object

From a performance perspective both approaches are comparable. Yes, method 2 will use some additional memory and require a few more instructions for instantiating your NameVO, but unless you're dealing with millions of objects, I would not worry too much about that.

From a coding standards perspective, method 2 is superior over method 1. In general, composite values (such as names) deserve their own object.

First of all, it allows you to add additional methods in your NameVO, such as the likely String getFullName(), which handles the possibility of having null as a middleName. This also gives you the flexibility to change the contents of a NameVO later on, for example by adding initials, salutations, etc.

Secondly, it gives you the option to reuse NameVO in other contexts. For example, you could have a Customer object with a name field, and a Supplier with a name field, etc.

Thirdly, if your code uses validation, you can decouple the validation of the contents of a name from the validation of the existence of a name.

Furthermore, by adding an equals and hashCode, you also gain the possibility to store your objects in a Map, indexed by NameVO.

As an aside, I would even go so far as to suggest a slightly modified version of your method 2:

public class SampleVO {
    NameVO name;
    // getters and setters
}

//Name object
public class NameVO {
    final String firstName;
    final String middleName;
    final String lastName;

    public NameVO(String firstName, String middleName, String lastName) {
      // assignments
    }

    // getters
}

This effectively makes your NameVO immutable, making it more suitable for use as a key in a Map. It also makes it safer to pass NameVO objects around without having to fear side effects.


optimize nested for loops within nested if statements

You are implementing an inner join as a nested loop join. There are several other ways to implement joins, such as hash-based or sort-merge sort. Which one is better depends on the length of the lists.

I will sketch a hash join as that usually works most of the time.

void applyFavoriteChangesToMerchantStore(){

    List<Merchant> favoriteMerchantsList = FavoriteMerchantStore.getInstance().getFavoriteMerchantsList();
    if(favoriteMerchantsList != null && !favoriteMerchantsList.isEmpty()) {
        // build the hash table
        Map<String, Merchant> favoriteMerchantById = favoriteMerchantsList.stream().collect(Collectors.toMap(Merchant::getId, Function.identity()));
        List<Merchant> storeMerchantList = MerchantStore.getInstance().getMerchantList();
        for (Merchant storeMerchant : storeMerchantList) {
            // probe the hash table
            Merchant favoriteMerchant = favoriteMerchantById.get(storeMerchant.getId())
            if(favoriteMerchant != null){
                //merchant match found
                //set merchant favorite status

               storeMerchant.setFavoriteMerchant(favoriteMerchant.getFavoriteMerchant());
                //set offer favorite status
                applyOfferChanges(favoriteMerchant.getOffferList(),
                        storeMerchant.getOffferList());
            }
        }
    }
}

I assumed that TextUtils.equals is equal to String.equals. If it's more lenient (e.g., case-insensitive), you need to normalize the lookup key (e.g., String.toLowerCase()).


Print all combinations of balanced parentheses

Jus a few minor points:

I guess you have a typo here:

if (length % 2 == 1) {
    throw new IllegalArgumentException("The length should be positive");
}

If length is 3 it prints that The length should be positive.
An exaplanatory variable would be a little bit easier to read here and it would express the purpose of the expression:

final boolean oddLength = (length % 2 == 1);
if (oddLength) {
    throw new IllegalArgumentException("...");
}

It could be easier to read and modify the expected outputs in the tests, especially if length is higher than four:

Arrays.asList("(", "(", "(", ")", ")", ")"),

I'd rather use a custom verification method here:

private static void verifyPaths(final List<String> expectedPaths,
        final int length) {
    final List<List<String>> braceCombinations = getBraceCombinations(length);

    final List<String> joinedBraceCombinations =
        flattenBraceCombinations(braceCombinations);

    assertEquals(expectedPaths, joinedBraceCombinations);
}

private static List<String> flattenBraceCombinations(
        final List<List<String>> braceCombinations) {
    final Joiner joiner = Joiner.on("");
    final List<String> joinedBraceCombinations = new ArrayList<>();
    for (final List<String> braceCombination: braceCombinations) {
        final String joinedBraceCombination = joiner.join(braceCombination);
        joinedBraceCombinations.add(joinedBraceCombination);
    }
    return joinedBraceCombinations;
}

With plain strings as expected output:

final List<String> expectedPaths = Arrays.asList(
    "((()))",
    "(()())",
    "(())()",
    "()(())",
    "()()()");
verifyPaths(expectedPaths, 6);

I would consider changing the current

List<List<String>>

return type to

Set<List<String>>

The order of combinations doesn't look so important and it would make the test less specified (the order of expected paths would not be important too).


From a short review;

The first snippet does not work, try it with inputTitle = 'BBB'

You are in essence doing 2 things

Find a possible match
Update the match or insert the data

Ideally, this is done in 1 'loop'

If you don't care too much about performance, I would go for a functional approach

This is my counter-proposal (which modifies the data)

const data = [
  {
    title: 'AAA',
    people: [ 'John', 'Megan',]
  },{
    title: 'BBB',
    people: [ 'Emily', 'Tom']
  }
]

function mergePeople(data, title, people){
  const target = data.filter(record=>record.title===title);
  if(target.length){
    target.forEach(record => record.people = people);
  }else{
    data.push({title, people});
  }
  return data;
}

function quickClone(o){
  return JSON.parse(JSON.stringify(o));
}

console.log(mergePeople(quickClone(data), "AAA", ["Tom", "Jerry"]));
console.log(mergePeople(quickClone(data), "BBB", ["Ben", "Jerry"]));


shell library for Debian package releases

Some lints:

Uppercase names are by convention only for exported variables.
You can use getopt to parse parameters. This should make it easier to handle optional parameters, and also makes it easy to avoid positional parameters (which makes commands more self-documenting).
Use More Quotes™
I would guard against errors and accidents by using set -o errexit -o noclobber -o nounset -o pipefail at the top of the script.
returning anything other than an exit code is a problem. You function should instead output the value (and ensure other output goes to standard error). One issue is the semantics of conflating exit codes. The other is the lingering bug because exit codes wrap around after 255.
You can use mktemp --directory to create a temporary directory to store intermediate results. Even better would be to pass results in a pipeline to avoid any temporary files.


Searching for an object with spectific property, using user input

Always nice to see a student eager to learn.

Class Book

Your should try to always use an access modifier, so this should be

public class Book

Other issues:

Public properties in C#, should begin with a capital letter.
Price should be a Decimal (used for currency or monetary values) instead
of a whole number.
Genre should rightfully be a property to a Book, and not static to the entire class.  Changing the genre then becomes as easy as updating the property.
myList does not belong in the Book class. It should not be static and should be moved to Main.
ToString() does not need to refer this..  Nor is the output needed.  Instead just return the string.Format.

Search Methods

The names should use PascalCasing, example SearchByPublisher, SearchByPrice.

There is no reason for the trailing .ToList() inside each respective foreach.  The Where has already returned an enumerable collection that you will iterate over.

For comparing strings, you have no regard for case.  Thus "HOBBIT" and "hobbit" would not match "Hobbit".  You may want to allow for ignoring the case.  Another consideration would be on matching a partial string.  Consider if the user enters "dragons" at the console that maybe you want to return "A Dance with Dragons".

Going Further

As a beginner, be sure you grasp what you see so far.  Then go a step further and add a Books class that implements List<Book>.  Now the search methods could be moved inside the Books class.  In the name of Separation of Concerns, you don't want the searches to also write to the console.  Instead, the search should be concerned only with searching.  That would mean each respective search would return an IEnumerable, or really just the results of the Where( ... ).


Calculate the time it takes to achieve your money goal in Kotlin

Hi yes I would store the textEdit references in a field of the class (not actual global scope), if you want to access them more often.

Running through the view hierarchy to find it on each click is not the most performant thing for more complex layout and so not best practice. These references stay valid until onDestroyed is called, so it's ok to store them.

BUT with Kotlin you would usually do it like this without casts etc. https://kotlinlang.org/docs/tutorials/android-plugin.html

import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        resultsButton.setOnClickListener {
            // Either try catch NumberFormatException or validating the string with
            // TextWatcher will be required to avoid problems here, but also in the original code.
            calculateAndDisplayTimeUntilMoneyGoal(
                goal: Float.valueOf(moneyField.getText().toString()),
                salary: Float.valueOf(salaryField.getText().toString()),
                increaseInPercent: Float.valueOf(increaseField.getText().toString()))
        }
    }
};


Implementing RSA-AES encryption protocol

whether this is a correct - that is secure - implementation of such an
  "algorithm pair" for transmitting messages via an unsafe and
  permanently visible channel

Your approach provides zero forward security. As soon as Bobs private key is compromised, all past communication with Bob is compromised as well.

You should use a Diffie-Hellman like handshake protocol for agreeing on a common secret for the actual communication.

You are not providing any form of authentication either.

Right now, Eva can perform a trivial man-in-the-middle attack. While Alice could in theory still verify Bobs identity by comparing the provided public key against a trusted database, Bob in return has no means to verify Alice's identity.

A simple band-aid would be to sign the chosen communication key with Alice's public RSA key, so that Bob has the confirmation that the key was in fact chosen by Alice, and not Eva.

For that, just apply a cryptographic hash function to the key, and encrypt the hash with Alice's private RSA key. Bob then uses Alice's known public RSA key to decrypt the signature and verifies that he can generate the same hash. Alternatively you can hash the encrypted shared secret instead of the plain text, if you don't wish to leak information on the plain text.

Be wary that this is still potentially subject to replay attacks. In order to protect against that, Bob should start the communication with a plaintext nonce which Alice needs to include in the signature. This may be an arbitrary string, but something as simple as the current time stamp suffices.

This is still only authentication though, and does not remove the need to agree on a new key via DH to provide forward security. You need to get rid of the temporary key as fast as possible.

The problem of replay attacks also applies to the actual messages themselves. As each message is only protected by the shared secret, you are unable to detect when Eve maliciously repeats a recorded message of the same session repeatedly.

A practical solution to that, is to append a fresh nonce to each sent message, which is expected to be repeated in the next message. Now you can tell for sure if the order of messages in one direction has been altered.

As for ensuring the coherence of a dialog, you might want to think about acknowledgment messages, which confirm receiving a content message.

byte[] bobsPublicKey = extractedParameters.Modulus;

That's not the public key. You need both the public exponent and the modulus.

using (MemoryStream ms = new MemoryStream(data, iv.Length, 0))
using (ICryptoTransform trans = _aes.CreateDecryptor(sessionKey, iv))
using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Read)
using (StreamReader sr = new StreamReader(cs))
    decryptedMessage = sr.ReadToEnd();

More curly braces and indentation please. The syntax with multiple using directives on the same indentation level should IMHO only be used when the declared disposables are independent. If they are dependent, they can no longer have the same life time, and that should be reflected by the code structure:

using (MemoryStream ms = new MemoryStream(data, iv.Length, 0))
using (ICryptoTransform trans = _aes.CreateDecryptor(sessionKey, iv))
{
    using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Read)
    {
        using (StreamReader sr = new StreamReader(cs))
        {
            decryptedMessage = sr.ReadToEnd();
        }
    }
}


Could you possibly provide more samples of your data? In any case, try this

Regex regex = new Regex(@"^[*]\d+[*]$");

If you actually expect the brackets (e.g. []) using the following:

Regex regex = new Regex(@"^[*][\[]\d+[]][*]$");


Output the average values of binned columns in Excel VBA

Data belongs in an Array

A worksheet *looks* like a grid of data, but there's an enourmous amount of overhead sitting behind it. Every time you do anything to a spreadsheet, events fire, formulas calculate and a million other things happen behind the scenes.

Working with Ranges is computationally expensive, and you're doing it N*105,570*2 times.

Instead, what you want is an Array. An Array is just a grid of data laid out in memory. Because it is *just* data there are no overheads, and so you can read/write to it about a Million times faster.

You can create an Array by reading in a range, like so:

Dim dataRange As Range
Set dataRange = Range("A1:A105570")

Dim dataArray As Variant
dataArray = dataRange.Value

And now, the value in "A1" is in dataArray(1, 1), "A2" in dataArray(2, 1) etc.

Let's re-write your code to use an Array:

Option Explicit

Public Sub BinValues()
    'binns seperation distance values for the creation of variogram

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    Dim dataRange As Range
    Set dataRange = Range("A1:A105570")

    Dim dataArray As Variant
    dataArray = dataRange.Value

    Const NUM_LAGS As Long = 12
    Const LAG_SIZE As Long = 600

    Dim minValue As Double
    Dim maxValue As Double
    Dim lagCounter As Long
    Dim ix As Long

    Dim elementValue As Double
    Dim elementSum As Double
    Dim numElements As Double
    Dim elementAverage As Double

    For lagCounter = 1 To NUM_LAGS

        minValue = (lagCounter - 1) * LAG_SIZE
        maxValue = (lagCounter * LAG_SIZE) - 1

        numElements = 0
        elementSum = 0
        For ix = LBound(dataArray, 1) To UBound(dataArray, 1)
            elementValue = dataArray(ix, 1)
            If elementValue >= minValue And elementValue <= maxValue Then
                numElements = numElements + 1
                elementSum = elementSum + elementValue
            End If
        Next ix

        elementAverage = elementSum / numElements
        Cells(lagCounter, 5) = elementAverage

    Next lagCounter

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub

That alone should take your runtime from 1/2 an hour to a couple of seconds (if that).


Hide and show menu if button clicked and change the icon

Caching Variables and selectors

Whenever selecting an element on the page, if you are going to select it multiple times, try to set the jQuery element as a variable first, and reuse the same variable.

$('.nav-topbar').prepend('

');
...
$('.nav-topbar').find('#menu-topbar-menu').hide();

can become:

var $navBar = $('.nav-topbar');
$navBar.prepend('

');
...
$navBar.find('#menu-topbar-menu').hide();

Caching variables is more performant and can be much easier to read.

You shouldn't have to find by id

IDs are meant to only exist once on the page. By calling .find({selector}), you are effectively saying "Starting from my current element, lets search down the DOM tree until I find something that matches my {selector}"

$('.nav-topbar').find('#menu-topbar-menu').hide();

should be the same as:

$('#menu-topbar-menu').hide();`

If it isn't, then your DOM should be corrected.

== and Type Coercion

As a general rule of thumb, you should always opt for === over == (and conversely opt for !== over !=).

a == b basically means does a sort of equal b. It doesn't take into account the variable's type. "1" == 1 passes as true (even though one is clearly a string, and the other clearly a number).

a === b means does a and b match the same type, and does the value equal each other. In this case, "1" === 1 will return false (because of the difference in type.)

I know this might sound small and nit-picky, but in reality it really isn't. Using == will lead up to unexpected behavior that can be hard to spot.

Additionally, === is faster than ==. === will stop trying to compare two variables if they do not have a matching type.

Simplify Conditional

I want to highlight the following conditional:

if ( $(this).attr('class') == 'ion-android-menu' ) {
    $(this).addClass('ion-ios-close-empty');

    // display menu
    $('.nav-topbar').find('#menu-topbar-menu').show(800);

} else {

    // remove class="ion-ios-close-empty" if condition return false
    $(this).removeClass('ion-ios-close-empty');

    // hide menu
    $('.nav-topbar').find('#menu-topbar-menu').hide(800);
}

You can simplify this conditional to:

var isButtonClicked = $(this).hasClass('ion-android-menu');
$(this).toggleClass('ion-ios-close-empty', isButtonClicked);
$('#menu-topbar-menu').toggle(800);

(Note I strongly recommend using hasClass(...) over .attr('class') == '...', you'll run into less problems in the future this way.

Event Binding

You should try to get into the habit of using $('.parent-class').on('click', '{selector}', function(){}) instead of `$({selector}).click(function(){}).

.click() applies an event handler for every instance of {selector}, whereas the .on() will apply a delegate event handler to .parent-class, and listen for any {selector} within .parent-class. The difference is making 1 event handler compared to making many.

Right here, there shouldn't be too much of a difference. We are assuming that there is only 1 .responsive-menu. But, as you can imagine, using .on() can give huge performance benefits over .click directly.

But, most importantly, by using $({selector}).click(), you are binding the click event to {selector}. Should you remove {selector} and re-add a new {selector} in its place, the click event will be lost.  This is not the case with applying the .on() to a parent element.

Overall approach

Hiding and showing menus has been done a lot, and to be honest, you are applying a lot of javascript for something that can be done mostly with css. I'm not aware of your DOM, however you can move the toggle menu behavior (and even the animation) to your CSS and just have a simple click event handler that fires a toggleClass event.

Example:

    var $wrapper = $('.nav-wrappers');
    $wrapper.on('click', '.responsive-menu', function(){
        $wrapper.toggleClass('showTopBar');
    });
.nav-wrappers .menu {
  background: #ccc;
  padding: 0.5em;
  text-align:center;
  transition: all .5s ease;
  overflow:hidden;
}

.responsive-menu {
  cursor:pointer;
}
.responsive-menu:hover {
  background: #ffa
}

/** Animation Stuff **/

.menu-topbar-menu {
  opacity: 0;
  padding: 0;
  height: 0;
}
.nav-wrappers.showTopBar .menu-topbar-menu {
  opacity: 1;
  height: 1em;
}

Top Menu

Responsive Menu

Hope that helps!


I don't think that there is inherently anything "wrong" with having multiple patterns like this in a single application, especially during a refactoring exercise. I would strongly suggest documenting the patterns that you are changing from and to and the reason for the modification so that future developers understand what is happening.

I would make one substantial modification to your proposed implementation, however: define Enrol at the Student level as an Overridable method.

If there is no default implementation for all students, change Overridable to MustOverride. This will in turn force Student to be declared as MustInherit, but this is ok if you can only call Enrol on instances of Undergraduate or Graduate.


Yes, it is a proper TPT inheritance and yes, you can mark your base class as abstract.


Simple command line parser/dispatcher in Rust

Prefer where clauses when your bounds get the tiniest bit complicated
An if let with an else is often better as a match.
If you match on an Option and return an Option, just use Option::map.
This allows you to remove the temporary variable and just chain functions
The tests module should have #[cfg(test)] to prevent it from even being compiled when not testing.
It's typical to use super::* in a test module.
It's better to let the compiler infer types instead of being explicit. This shows as an error because the compiler can't infer the error type. You could say cmdr: Cmdr<_, &str>, but it's better to actually exercise the error case.
Instead of unwrapping your success / failure, assert against them.
Use assert_eq instead of assert when comapring equality.
Use assert! and is_none instead of pattern matching

lib.rs

pub mod cmd;
use cmd::Cmd;

pub struct Cmdr<T, E> {
    cmds: Vec<Cmd<T, E>>,
}

impl<T, E> Cmdr<T, E> {
    pub fn new() -> Cmdr<T, E> {
        Cmdr { cmds: Vec::new() }
    }

    pub fn add<F>(&mut self, name: &str, cmd: F)
    where
        F: FnMut() -> Result<T, E> + 'static,
    {
        self.cmds.push(Cmd::new(name, cmd));
    }

    pub fn invoke(&mut self, cmd_name: &str) -> Option<Result<T, E>> {
        self.cmds.iter_mut()
            .find(|cmd| cmd.name == cmd_name)
            .map(|cmd| cmd.invoke())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cmdr() {
        let mut cmdr = Cmdr::new();
        cmdr.add("test1", || Ok("test1 executed."));
        cmdr.add("test2", || Err(42));

        // Good commands.
        let test1_msg = cmdr.invoke("test1");
        assert_eq!(test1_msg, Some(Ok("test1 executed.")), "Incorrect test1 message.");

        let test2_msg = cmdr.invoke("test2");
        assert_eq!(test2_msg, Some(Err(42)));

        // Bad command.
        assert!(cmdr.invoke("ghost").is_none(), "Non-existent command somehow returned Some().");
    }
}

cmd.rs

pub struct Cmd<T, E> {
    pub name: String,
    pub invocation: Box<FnMut() -> Result<T, E>>,
}

impl<T, E> Cmd<T, E> {
    pub fn new<F>(invoke_str: &str, invocation: F) -> Cmd<T, E>
    where
        F: FnMut() -> Result<T, E> + 'static,
    {
        Cmd {
            name: String::from(invoke_str),
            invocation: Box::new(invocation),
        }
    }

    pub fn invoke(&mut self) -> Result<T, E> {
        (self.invocation)()
    }
}

  I'm not sure that Cmdr should be living in the root lib.rs file.

In fact, I'd say the opposite is true: I'm not sure that Cmd belongs in it's own file. Unlike many languages, most Rust projects I've read have no hesitation in placing more than one type in a single file. I wouldn't think that Cmd carries enough weight to be separated.

There is some work underway to adjust Rust's module system, so the organization you've shown might return to vogue at some point.

  my namespace would be something stupid like cmdr::cmdr::Cmdr, as my root directory is also named cmdr

You can use the façade pattern to re-export nested types at a higher module:

// lib.rs
pub use cmdr::Cmdr;

  Option<Result<T, E>>

I'd encourage you to try this out a bit; my gut tells me that it won't be the most ergonomic to use.

  Document the code in a Rusty style

Remember that the static type system provides a baseline of documentation and that function and argument names provide a bit more. Don't document the things that are obvious from the name or type of something. Consider making more types to improve the documentation and user experience.

  Eventually, this will be a front end for a DHCP client/server package I'd like to implement in Rust. I may also release it on crates.io, if it matures into something worthwhile.

Please strongly consider not using your own hand-rolled library for such a project. Having a great DHCP server sounds wonderful, but one where the author's time has to be spent maintaining a command-line parsing library or  one that has a substandard command line interface would detract from it.

Of course, that shouldn't stop you from using it to experiment with Rust!


Splitting the input, parsing the parts, figuring the bits and filling the hosts list should all be seperate methods that return the results to main.
Every method should perform a simple task. If you list the steps necessary to perform an action, each step should be a separate method.
Commenting a methods purpose above it will help you and others understand it's inner workings.
Bits and bites are not the same thing.
 double totalbites = Bits - S;
Also variable names should not start with a capital unless they are all capitals.
Variable names like A, B, C, E, X, S are not very helpful. input1, input2,... and num1, num2,... would convey a clearer picture of these variables purpose.
Use comments to explain the actions taking place.


A C++ function to read Code Points from an UTF-8 Stream

Overview
There is a lot of repeated code that could be removed by use of functions.
When bittwiddling like this it would be nice for a human readable explanation of what you are doing. I had to look up the unicode spec to make sure you were doing it correctly.
A lot of UTF-8 files (stream) contain a BOM marker 0xEF, 0xBB, 0xBF as the first code point. This is not part of the text stream and should be discarded if it exists. Though you may do this at the layer of abstraction above this in which case a comment pointing out that the BOM marker is not removed should be added.
You don't validate that the bytes 2 through 4 have the correct pattern for UTF-8 you just make that assumption.
You use exceptions on streams. Normally you would mark the stream as bad and return. The user of the stream is supposed to check the state of the stream before using any output (and further reading will fail).
C++ uses operator>> to read from a stream. It would be nice to be able to read your characters using this operator.
Code Review
The name of the function is not quite correct:
chr_t utf32::get_utf32_char(std::istream &in_stream)

Code points are distinct from there encoding. You are converting an code point that was encoding UTF-8 into UCS-4 (not UTF-32). UTF-32 is another encoding format used for transportation. I would note that UCS-4 and UTF-32 look the same but they are not the same thing.

You read into next (an int) in all locations apart from here:
    int next;
    chr_t out = in_stream.get();

Why not be consistent. I especially worry about corner case and auto conversions with characters and integers. Can't think of anything that would go wrong but why risk it. Read into next (the int) check for EOF then convert to your character representation.

Don't use magic numbers. In this context you should use EOF (not -1).
    if (out == -1 || out < 0x80) {
        return out;

I hate else on the same line as }.
    } else if ((out & 0xe0) == 0xc0) {

But your code your style.
Very few coding standards use this system.
In my opinion (so ignorable) you don't need to crush the code together that much. Extra vertical spacing will make the code easier to read.

Questionablt use of goto:
        if (next == -1) goto invalid_seq;

Why not simply:
        if (next == EOF) {
            throw std::runtime_error(unexpectedESFMessage);
        }

Redesign:
I would have used a more data driven approach:
struct Encoding
{
    char    mask;
    char    value;
    int     extra;
};
Encoding const utf8Info[] = {
                        {0x80, 0x00, 0}
                        {0xE0, 0xC0, 1}
                        {0xF0, 0xE0, 2}
                        {0xF8, 0xF0, 3}
                      };
chr_t decodeUtf(std::istream& stream, chr_t result, int count)
{
    for(; count; --count) {
        int next = stream.get();
        if (next & 0xC0 != 0x80) {
            // Not a valid continuation character
            stream.setstate(std::ios::badbit)
            return -1;
        }
        result = (result << 6) | (next & 0x3F);
    }
    return result;
}
chr_t getCodePoint(std::istream& stream)
{
    // NOTE: Does not remove any initial BOM marker.

    int next = stream.get();
    if (next == EOF) {
        return -1;
    }
    for(auto const& type: utf8Info) {
        if ( next & type.mask == type.value ) {
           return decodeUtf(stream, next & ~type.mask, type.extra);
        }
    }
    // Not a valid first character
    stream.setstate(std::ios::badbit)
    return -1;
}

std::istream& operator>>(std::istream& str, chr_t& out)
{
    chr_t tmp = getCodePoint(str);
    if (str) {
       out = tmp;
    }
    return str;
}

.


Program that converts a number to a letter of the alphabet - follow-up

int letter is not a letter. When printing you call it The number. Name it accordingly: int number.
The condition (1 <= letter && letter <= 26) == false is very hard to follow. As a general rule, avoid boolean constants in conditions. Rewriting it as:

!(1 <= letter && letter <= 26)

immediately calls for a deMorgan transformation into a much more readable form:

(letter < 1 || letter > 26)

It is also recommended to not rely on the operator precedence, which is very easy to get wrong. Use parenthesis instead:

((letter < 1) || (letter > 26))

Avoid raw loops. Each loop represent an important algorithm, and as such deserves a name. The goal of:

while((temp=getchar()) != EOF && temp != '\n');

is to discard the line. Factor it out into a function:

void discard_line()
{
    int temp;
    while((temp=getchar()) != EOF && temp != '\n') {
    }
}

As a perk benefit, temp is no longer cluttering the essential logic.

I also recommend to be a bit more explicit with the empty loops.
Avoid magic numbers. 26 is really strlen(alphabet). Better yet, declare the alphabet as an array, rather than a pointer, and use sizeof.


Submitting callable tasks to a variable number of Threads in a ThreadPool

General concerns

Unrelated to multi-threading: you might want to think about fence post errors -- consider:

Assert.assertEquals(countParallel(8,10,2), countParallel(8,10,1));

Is it obvious that the code you've provided will pass this test?

Also, if a variable is only used within a given scope, it's a good idea to declare that variable within the scope....

for(int i = 0; i < nrThreads; i++)
{
    Future<Integer> countHelper = threadPool.submit(new PrimeCounter(startFrom, startFrom + numbersPerThread));

    // gets the next chunk to be examined
    startFrom += numbersPerThread + 1;

    helperList.add(countHelper);

}

... and within a scope, to declare the variable as close as possible to its first use:

int count = 0;
for(Future<Integer> helper : helperList)
{
    count += helper.get();
}

I find that doing this also reveals refactorings -- for example, collapsing the outputs of all the jobs into a single number is a single idea

int sum(List<Future<Integer>> resultList) {
    int count = 0;
    for(Future<Integer> helper : helperList)
    {
        count += helper.get();
    }
    return count;
}

Multi-Threading

The good: you created an ExecutorService, rather than creating your own threads.  10 out of 10.

The meh: you've completely punted on cancellation.  What should be be done to the jobs that are running if an InterruptedException is thrown?  For toy problems, where you aren't supporting the ability to cancel work in progress, that's fine.  Put it on the list of things to pick up later.

You're also being, perhaps, a little bit timid about dividing up the work.  An alternative to giving each thread it's own pile of work, is to provide lots of slices of work, and let the Executor service decide which thread gets to do what.  There's nothing wrong with submitting 7 jobs to an ExecutorService with 6 threads; for that matter, it could be 70 jobs.  Or 700 jobs.

The situation you would like to avoid is one where most of your threads are idle (because there is no more work available), but one thread is taking a long time because he got all of the hard parts of the problem.

So it might be better to distribute the work more fairly -- tell each PrimeCounter that you are solving the range [1,20.000.000], but the prime counters process every nTh entry in the list (ex: one PrimeCounter checks 0,6,12..., and the next PrimeCounter checks 1,7,13..., and the last one checks 5,11,17....).

  Is there a better way of getting the values from the Future rather than saving them in a list and summing them up afterwards?

I think the answer here is: it depends.  One of the good things you've done here is ensure that values are only written by one thread; this makes lots of things easier to reason about (compared with, for instance, trying to have each PrimeCounter add values to a common accumulator).

Here, where you are using the results so close to the place that you start the jobs, it might be easier to store the intermediate results in the Runnable, wait for all the threads to finish, and then iterate the Runnables to sum up the total.  You could use ExecutorService.awaitTermination to know when the jobs have finished running, or set them up to each signal their results via a CountDownLatch, or ....

I would be more inclined to use a Future if the consumption of the result was "further away" from the calculation; like on the other side of an abstraction layer.