Try every option for a command and make anagrams out of the successful ones

Some of the commands in the web scraping part can be simplified.

Instead of awk '{ print $(NF-2) }', why not simply awk '{ print $2 }'?

Instead of sed -nr '/rm|wget|less|shutdown|<h3>/!p', it would be simpler and more portable to use grep -vE 'rm|wget|less|shutdown|<h3>'.

Using a Bash array is a bit overkill,
because the output of the pipeline is guaranteed to be one word per line,
no other white space.
So using a simple variable and word splitting should do the job, and simpler:

commandList=$(
  curl 'http://www.thegeekstuff.com/2010/11/50-linux-commands/' 2> /dev/null \
    | grep -o '<h3>\([0-9].*[a-z][a-z][a-z].*\)</h3>' \
    | awk '{ print $2 }' \
    | grep -vE 'rm|wget|less|shutdown|<h3>'
)

for command in $commandList; do

Many improvements are possible here:

timeout -k 5 5 "$command" -"$option" > /dev/null 2>&1;
    if (($? == 0)); then
        printf "$option" | tr -d '\n'
    else
            :
    fi

In Bash, you can use &>/dev/null to redirect both stdout and stderr.

Since $option only contains a single letter and printf doesn't print a trailing newline like echo, the tr command there is pointless.
The double-quotes around $option are also unnecessary.
The empty else branch should be removed.

Instead of using a condition on $?, you could use the command itself directly:

if timeout -k 5 5 "$command" -$option &> /dev/null; then
    printf $option
fi

You could rewrite the final sed simpler using double-quotes:

sed "s/^/ $command -/" >> commandOptions.log

I also removed a pointless \ from in front of a space within the quoted expression.


First of all, you did well splitting it up into those methods.

The major issue I have with your code is that the natural translation from the English answers yes/no to Java is to use a boolean. Where true means yes and false means no.

So your isVowel method should be written like this:

static boolean isVowel(char c) {
    if ( (c == 'a') || (c == 'e') || (c == 'i')
        || (c == 'o') || (c == 'u') || (c == 'y') ) {
        return true;
    }
    return false;
}

Now the next thing you need to know is that a check like c == 'a' is already a boolean, and that the || operator combines 2 booleans into a new boolean. Since we want to return a boolean, instead of writing

if (<boolean check>) {
    return true;
} else {
    return false;
}

we should just write the following:

return <boolean check>;

which in your case would be:

static boolean isVowel(char c) {
    return (c == 'a') || (c == 'e') || (c == 'i')
           || (c == 'o') || (c == 'u') || (c == 'y');
}

A final issue with this method is that it's actually package-visible. There is no reason to use this method outside of this class, so it should be private.

private static boolean isVowel(char c) {

The same reasoning applies to the isBeautiful method. So let us also make this private and return a boolean.

private static boolean isBeautiful(String w) {
    for (int i = 0; i < w.length() - 1; ++i) {
        if (w.charAt(i) == w.charAt(i + 1)) {
            return false;
        }
        if (isVowel(w.charAt(i)) && isVowel(w.charAt(i + 1))) {
            return false;
        }
    }
    return true;
}

Notice how I also simplified the check for 2 consecutive vowels so that it now actually reads: if this character is a vowel and the next character is a vowel.

Now the last thing left to do is use this new isBeautiful method. This means we will change this code:

int result = isBeautiful(w);

if (result == 1) {
    System.out.print("Yes");
} else
    System.out.print("No");

to this:

if (isBeautiful(w) {
    System.out.print("Yes");
} else {
    System.out.print("No");
}

Notice I also added the {} after the else. It's best practice to add curly braces after each if/else/for/while.

One last tip is that you can also rewrite the isVowel method like so:

private static final String VOWELS = "aeiouy";

private static boolean isVowel(char c){
    return VOWELS.contains(c);
}

But this doesn't mean that it's bad to check each character separately - it's just an alternative way.


Script for keeping track of teams in a class

I like your argument names for fillInTeam. I think they were good choices.
You declare the variable first and only use it here.

for (var z = first; z < numbers.length; z++) {

You can just set z = i + 1 instead.

for (var z = i + 1; z < numbers.length; z++) {

Speaking of, use j instead of z. Loop counters traditionally start with i and work their way up the alphabet as nesting goes deeper.
theNum1 and y are both absolutely atrocious names. Find something better and more meaningful for them, or better yet, just get rid of them entirely. Just use i and j to access the array elements directly.

function fillInTeam(value, numbers){
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  for (var i = 0; i< numbers.length; i++) {
    for (var j = i + 1; j < numbers.length; j++) {
      var cell = spreadsheet.getDataRange().getCell(numbers[i], numbers[j]).setBackground('yellow');
      cell.setValue(cell.getValue() + value);
    }
  }
}

getDataRange().getCell() was the right choice here. getRange() is your other option, but it only takes A1 notation. That would have been less flexible in the long run.
Getting the DataRange inside of the loop is a bit inefficient. Instead of declaring spreadsheet as a variable, declare a dataRange variable and use it to access the individual cells.

function fillInTeam(value, numbers){
  var dataRange = SpreadsheetApp.getActiveSpreadsheet().getDataRange();
  for (var i = 0; i< numbers.length; i++) {
    for (var j = i + 1; j < numbers.length; j++) {
      var cell = dataRange.getCell(numbers[i], numbers[j]).setBackground('yellow');
      cell.setValue(cell.getValue() + value);
    }
  }
}

One last transformation. setBackground() returns a cell, so you can chain the calls together like this. (Note that I like chaining, but I might have taken it too far and made it less clear by getting rid of the cell variable.)

function fillInTeam(value, numbers){
  var dataRange = SpreadsheetApp.getActiveSpreadsheet().getDataRange();
  for (var i = 0; i< numbers.length; i++) {
    for (var j = i + 1; j < numbers.length; j++) {
      dataRange.getCell(numbers[i], numbers[j])
        .setBackground('yellow')
        .setValue(cell.getValue() + value);
    }
  }
}

updateTeams() has a definite smell to it, but I suspect that's because you're manually changing those prior to each run. I'm not sure what to do about it though.

clearBackgrounds() is a little clunky. It could definitely benefit from a spreadsheet variable like you have in fillInTeam().

I also don't like this.

.getRange('B2:O15').setValue('');

What happens if you add columns to your spreadsheet beyond O? You'll have to update your code to handle it. I'm thinking you can use getLastRow and offset to do this instead. Something like this untested code here.

var dataRange = spreadsheet.getDataRange();
dataRange.offset(1,0,dataRange.getLastRow() - 1, dataRange.getLastColumn()).setValue('');

I'm admittedly unhappy with how far it scrolls, but it's dynamic at least.


Binary Serialization
Is a bit more complex that what you have implemented.
You have serialized the content of the memory that is occupied by an object of type Building. Which is not quite the same as binary serialization of an object.
Problem 1: Integers are not represented the same on all platforms.
Problem 2: Floats are not represented the same on all platforms.
Those are the obvious two. The not so obvious ones are packing added by the compiler to the object. Changing the compiler or even just the compiler flags can change both the packing (and thus alignment) and the size of the object.
Assuming all the above is handled and does not change. The above code is very fragile to any change. It assumes all the data is in the object. This is usually not the case (think of a string, most of the data is at the other end of a pointer). So just because you serialize the memory occupied by an object does not always mean you get all the data that belongs to an object.
To use an optimal binary serialization. I would serialize each member individually. That way at least you avoid the issues with packing introduced by the compiler.
Design
Not sure what m_buildingQualityDecimals is used for or why it is useful. If you are worried about the exactness of floating point then you should retain the data as a string or integer (depending on the situation).
Never make assumptions about a class
    file.write((char*) &b, sizeof(b)); // writing file to binary by casting to a char*

Here the external user is serializing the class. But has no idea what is inside the class. This makes this code impossibly brittle to change. It will almost certainly break over time.
What you should do is ask the object to serialize itself to the stream. The object understands itself and its members. So it can optimally serialize itself to the stream.
       b.write(file); // b can serialize itself to the stream.

  class Building
  {
     // Stuff
     void write(std::ostream& out)
     {
         char version = 1;
         out.write(&version, 1);
         out.write(&m_age, sizeof(m_age));
         out.write(m_locationCode, 7);
         out.write(&m_buildingQuality, sizeof(m_buildingQuality));
      }

The same applies to the read.
  file2.read((char *) b2, sizeof(*b2));
  // I would write...
  b2->read(file);

Normal serialization
// Testing process
std::cout << "Age: " << b2->getAge() << "; Loc: " << b2->getLoc() <<
            "; Building Quality:" <<  std::setprecision(b2->getDecimals()) << b2->getQuality() <<std::endl;

Again you are providing geter methods to access the member and retrieve values that you then use to perform an action. Geter methods break encapsulation and expose the internal types of the object. You should never use them like this. What you should do is ask the class to serialize itself to the stream. There is even a standard idiom for this in C++ and it is called the output operator.
  class Building
  {
       friend std::ostream& operator<<(std::ostream& out, Building const& value)
       {
           return out << "Age: " << value.m_age
                      << "; Loc: " << value.m_locationCode
                      << "; Building Quality:" << value.m_buildingQuality
                      << "\n";
        }

Prefer "\n" over std::endl
The only difference between the two is that std::endl also flushes the stream. The stream will flush itself automatically when it needs to and thus forcing a flush is only going to make it less efficient. Humans are notoriously bad at making this decision; the code is actually very good at. So let the code decide when to flush.
Don't use pointers in C++
    Building* b2 = new Building(0, "000-000", "0.0");

    // what happens if an exception happens between these two points?

    delete b2;

Using pointers is very C like and its not done much in modern C++ (unless you are implementing a container class or smart pointer or trying to do some tricky low level optimization).
In normal code you very rarely see them. The problem is that they do not show ownership semantics (the owner of a pointer is responsible for calling delete on it). So it is not clear who should delete them. So in most cases normal variables are a preferred and if you must dynamically create an object then you should be using a smart pointer so that the ownership semantics are specified.
In this case a normal object is best.


line.split(";") is being called twice, so you can assign it to a variable to remove one of the calls.

Since we know there's only one ; per line, we can use indexOf to find it, and substring to extract the relevant parts of the string. This may be a little bit faster than calling split(";").


Kotlin function which counts standard deviation

You may want to be more idiomatic when working with collections, for an instance:
import kotlin.math.pow
import kotlin.math.sqrt

fun sd(data: DoubleArray): Double {
    val mean = data.average()
    return data
        .fold(0.0, { accumulator, next -> accumulator + (next - mean).pow(2.0) })
        .let { sqrt(it / data.size )
    }
}

BTW, I don't think that data.size - 1 is correct


layout - The code is clear and easy to read but I find your use of blank lines a bit excessive.
braces - Both the push() and size methods consists of a single line of code so surrounding braces, {..}, are optional. You drop them in one and keep them in the other. Inconsistent.
types - The size method declares its return type but push() and pop don't. It's usually a good idea to include them in all but the smallest, simplest method definitions.
mutation - The mutating collection, list, is kept local and private, which is good. I might argue that it's better to keep a mutable collection, such as Buffer for example, in a val variable instead of keeping an immutable collection, List, in a var variable.
mutating methods - For methods with no arguments that mutate an internal state, such as pop does, the Scala Style Guide recommends declaring the method with empty parentheses, def pop() ..., as an indicator to the end user.
safety - The code will throw an exception if you try to pop an empty stack. That may be as you want it. I prefer methods that return Option[A] instead of throwing.
convenience - If I was trying to use StackDS in my code, I'd want to know why stacks have to be created empty. Why can't I create a populated stack? e.g. new StackDS(8,4,11) It would require a small modification to the existing code.
What I think your code clearly demonstrates is that a simple List does most of what we need from a Stack. So even though the Standard Library includes a full featured Stack implementation, it's not often used.


The Odin Project - Project Ruby: Translating from English to Pig Latin

Some notes:

expect(translate("three")).to eq("eethray"). Be consistent, use always a local variable or don't. I think this way looks pretty cool.
Isn't the code inside a module/class?
translate. This methods is unnecessarily verbose. You don't need to check if there is a space or not, since the algorithm works just the same if there is not.
Those two nexts are redundant.
rearrange: This method would look so much nicer if you don't use imperative style.
If a regular expression can express the rules, you should consider using it. It will be easier to read and much more compact.
Side note: The rules are pretty simple. If they ever get more complex, a manual processing will be undecipherable and regexps will come short. Then you'll need something more sophisticated, like a parser (i.e. grammy).

I'd write:

def translate(phrase)
  phrase.split(" ").map { |word| rearrange(word) }.join(" ")
end

def rearrange(word)
  match = word.match(/^((?:qu|[bcdfghjklmnpqrstvwxz])*)(.*)$/)
  match ? match[2] + match[1] + "ay" : word
end

If you have trouble reading that regular expressions, consider using multi-line regexps with named captures:

def rearrange(word)
  match = word.match(%r{
    ^
    (?<leading_consonants>(?:qu|[bcdfghjklmnpqrstvwxz])*)
    (?<rest>.*)
    $)
  match ? match[:rest] + match[:leading_consonants] + "ay" : word
end


Both approaches are acceptable, but the one using a Dictionary feels cleaner to me, and brings some advantages at no significant cost.

A Dictionary will detect a duplicate key, whereas it could be easily overlooked in an if-else construct, leading to a possibly baffling bug
It could be modified in run-time, eg. for debugging purposes.
It's more flexible: it could be injected from outside, easily refactored towards a DI-based approach etc.

This being said, it could be overengineering for simple cases. It's hard to say without knowing broader context. All info you've provided is that there's 5 cases, which is quite a few already, and it makes me guess there's a chance for more to come; if all I knew was that there's 2 or 3, I would say keep it simple.


Feedback

The script looks pretty good. For a small script that runs on your local machine it appears to suffice for your needs.

Is the goal to only show the latest link? Or would there be a use for showing previous links?

Suggestions

Variable naming

This variable naming might be misleading:

$chars_length = strlen($charset) - 1;

Because the value is one less than the length of the string. If I was working with that code, I would ask you to rename it to something more appropriate, like:

$max_index = strlen($charset) - 1;

since that value is ultimately used to determine the maximum index used to get a character out of the string.

Use uuid() or uuid_short()

Bearing in mind that you might likely need to alter the length of the id column, instead of generating your own random string, you could consider using MySQL's uuid() or uuid_short() function. That might eliminate the need to repeat the loop of calling random_string() and running a query just to see if the return value isn't used by any records.

One other approach to a really short URL would be to just have an auto-increment integer field starting at 1... up until there are 9,999 records, the id would have 1-4 digits...

Unspecified parameter $charset

$charset doesn't appear to be passed by the one place that the function is called. Unless you plan to utilize that, the default value could be made a constant:

define('CHARSET', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');

function random_string($length) {
    $chars_length = strlen(CHARSET) - 1;

for vs foreach

I thought about suggesting you use foreach(range(0, $length) but after reading posts like this it might not be wise to get into a habit of that, in case you work on code that deals with large amounts of data.

If you were more used to using foreach, range() can allow you to use foreach like a for statement:

foreach(range(1, $length) as $i) {
    $str .= $charset[random_int(0, $chars_length)];
}


Create multiple divs inside a containing div

Descriptive names

As a global function name, generate is too vague: it should tell what it's generating, something like generateChart. As a method name it would be ok because the object itself would be what's being generated or doing the generation (e.g. chart.generate()).

(I'm aware that the function doesn't actually generate a chart as it currently is, but I assume that the "hello world" part is later replaced with the actual code that does it.)

Class names like "container2" and "block" aren't descriptive enough to tell what their meaning is. "Block" might be descriptive in context, but "container2" certainly isn't.

Too broad parameters

You're passing an object chartData to the function, but only use its bindto property. You could pass the property directly to the function, as it seems to only tell where to put the chart.

Mixing jQuery and native DOM methods

As a general rule when doing low-level element manipulation you should either always use jQuery or never use it, but not mix the two. In the code you're using jQuery only to add class names, which could easily be done with plain JavaScript.

Browser compatibility

.append() isn't supported by any version of Microsoft or Android browsers so if you're targeting any of those browsers you'll have to use other methods, add a polyfill, or use jQuery. Note that .append() on native DOM elements is a different method than jQuery's .append().

Miscellaneous

myNode points to container (because .appendChild() returns the child element). Having two variables for the same element is confusing, so you should only use container.

Variable declarations should be at the top of the function if possible. Variables shouldn't be declared inside a loop, unless you're using let.

The variable text should be declared outside the loop. It's always the same so re-declaring it 10 times is unnecessary.

The number 10 in the for loop is a magic number - you should replace it with a descriptive constant, especially if it's used somewhere else too to refer to the number of blocks in the chart.

Single and double quotes should be used consistently to delimit strings, so either use single quotes everywhere or double quotes everywhere.

Revised code

Putting it all together, plain JavaScript version:

var BLOCKS_PER_CHART = 10;

function generateChart(chartContainer) {
  var container = document.createElement("div");
  var text = "Hello World!";
  var blockDiv, textSpan;  // used in the for loop

  container.className = "container2";
  document.getElementById(chartContainer.replace("#", "")).appendChild(container);

  for(var i = 0; i < BLOCKS_PER_CHART; i++) {
    blockDiv = document.createElement("div");
    blockDiv.className = "block";
    textSpan = document.createElement("span");
    textSpan.append(text);  // see note about browser compatibility
    blockDiv.append(textSpan);
    container.append(blockDiv);
  }
}

jQuery version:

var BLOCKS_PER_CHART = 10;

function generateChart(chartContainer) {
  var container = $("<div>").addClass("container2").appendTo(chartContainer);
  var text = "Hello World!";
  var blockDiv;  // used in the for loop

  for(var i = 0; i < BLOCKS_PER_CHART; i++) {
    blockDiv = $("<div>").addClass("block").appendTo(container);
    $('<span>').text(text).appendTo(blockDiv);
  }
}

Both of these assume that the function is called with what used to be chartData.bindto. Also, I don't know the purpose of "container2" so I've left its name for you to change.

Note that this could be further improved if latest ECMAScript features like const can be used.


ActiveRecord extension to find next / previous record(s) in one query

I will stick to reviewing the code you've posted, although it seems tied to other code.

First of all: Use descriptive variable names. x, y, q, and so forth aren't great for legibility. Use query, position and similar full words. Especially since you're dealing with complex nested arrays.

There also seems to be some logical issues/dangerous assumptions. I don't know if you check/sanitize your input elsewhere, but if you don't things will get weird. E.g.:

# This will fail if x[i] is nil
x_cond = [x[i][0].presence, x[i][1]]

q << x_cond if x_cond[0]

if i >= 1
  # 1. This *may* append ["AND"] etc. directly to an empty array,
  #    if x_cond[0] was nil above, resulting in a nonsense query.
  # 2. This will fail if y.count < i - 1
  q << ['AND'] << y[i - 1]
end

In other words, if x_cond[0] isn't present, you don't append anything to the array. Yet the following if block assumes that something definitely was appended. And there's no check for the length of y so y[i - 1] may fail. And x[i][0].presence will fail if x[i] is nil to begin with.

I also see some (dangerous) redundancy, like the n = x.length method parameter. There's no reason for this to be a method parameter. In fact, it's detrimental, because the n value is never checked, so you can pass any value like n = -42 which wouldn't make sense.

Moreover, the code doesn't actually match its description: Your comment for build_query_factory states that the result should be something like:

x0 OR y0 AND (x1 OR y1 AND (x3 OR y3))

but the method returns:

x1 OR (x2 AND y1 OR (x3 AND y2))

Notice that a) the structure is very different, and b) y3 doesn't even appear.

Now, assuming that you want the result you give as an example in the comment (and not the result the method actually returns), I would do something like this:

def build_nested_query(x, y)
  # zip the two arrays (x, y, x, y, x, y, ...)
  ordered = x.zip(y)

  # split into conditions and parameters
  ordered = ordered.map do |x, y|
    [ [x.first, y.first], [x.second, y.second] ] # still confusing, to be honest
  end

  conditions = ordered.map(&:first)
  parameters = ordered.map(&:second).flatten # thanks to ActiveSupport for Array#second, by the way

  [ nest_conditions(conditions) , parameters ]
end

def nest_conditions(conditions)
  # create "x OR y" string
  branch = conditions.first
  branch = branch.join(" OR ")

  # nest the remaining recursively, appending them with " AND "
  remaining = conditions[1..-1]
  if remaining.any?
    nested = nest_conditions(remaining)
    branch += " AND (#{nested})"
  end

  branch
end

That'll do something like this:

x = [["x1", [:x1]], ["x2", [:x2]], ["x3", [:x3]]]
y = [["y1", [:y1]], ["y2", [:y2]], ["y3", [:y3]]]

query = build_nested_query(x, y)
query[0] #=> "x1 OR y1 AND (x2 OR y2 AND (x3 OR y3))"
query[1] #=> [:x1, :y1, :x2, :y2, :x3, :y3]

Which I believe is what you want. You'll want to do some sanity-checking/sanitizing of x and y beforehand, to make sure they make sense.

Of course, if you find a better way to supply the method parameters in the first place, the code can be cleaned up even more.

I would also consider encapsulating conditions and parameters somehow to avoid the non-descriptive [0] and [1] (or first/second) stuff in favor of something more descriptive (Rails no doubt already has an internal class for this structure. Otherwise, a simple Struct-based class should do.)

I haven't looked closely at where_relative, but again I see some strange logic:

def where_relative(spec, mode)
  ord = spec.order

  # I assume `values` is an instance variable?
  # Anyway, why assign `value` here? It's only used in
  # the else-block, and so should be assigned there
  value = values[spec.name]

  if ord.is_a?(Array)

    # ...

    # Wait, now you're assigning something to `values`?
    values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos

    # and apparently, that something can be nil, since you're
    # checking for that here - but you didn't check for that
    # before you called `values[spec.name]` above
    return EMPTY_FILTER unless values.present?

    # ...

  else

    # ...

    # And here you use `value` (i.e. values[spec.name])
    ["#{spec.col_name_sql} #{op} ?", [value]]

  end
end

Now, I admit I don't know the exact sequence of events, but the above looks/smells like dangerous assumptions and nasty side effects. If the method is called several times per object instantiation, results get unpredictable. First time it's called, I assume values is set to something. But it might get set to nil by the method. This will cause the next call to the method to crash on values[spec.name]. If the method is so completely dependent on values, it should be a parameter.

Lastly, this line should really be reworked:

values = mode == :after ? ord.from(pos + 1) : ord.first(pos) if pos

Don't use a ternary and postfixed if on the same line - it's very confusing.


Instead of getting the positions of the maximum value and then retrieving the values thanks to the positions, you can directly ask numpy to retrieve the maximum values:

tmp = sig.reshape((trial_num, step, dims))
max_res = np.max(np.max(tmp, axis=1), axis=1)

I suggest you, however, to use a function to encapsulate this behaviour. It could take the amount of steps per cycle as a parameter and compute the rest from there:

def max_peak_values(data, steps_per_cycle=30):
    length, dims = data.shape
    trials = length // steps_per_cycle
    new_shape = trials, steps_per_cycle, dims

    return np.max(np.max(data.reshape(new_shape), axis=1), axis=1)

and use it like:

max_res = max_peak_values(sig, 30)


Angular service for fetching and passing data with observables

One of the improvements would be to use an HttpClient instead of Http for making the API calls.

If you use HttpClient, you won't have to call the res.json() everytime you subscribe to the response.

To use HttpClient, you'll first have to import HttpClientModule from @angular/common/http. Then you'll have to add it to the imports array of your @NgModule decorator.

Then you can inject HttpClient as a dependency and you will have access to the usual Http methods on the instance of HttpClient as well.

With that, you first part of the code will be reduced to:

private itemUrl = "http://fooserver/api/get/item/details";
getItemDetailsUrl(productId): Observable < any > {
  return this.http
    .get(this.itemUrl, {
      params: {
        productId: productId
      }
    })
    .flatMap(res => this.getItemDetails(res.itemUrl));
}

Also, I figured, there was a redundant map operation after the flatMap which wasn't really required. Rest all, I guess is in place in your code and I'm not really if it can be improved further. But I'll be looking out for answers to this question just in case.


It's often helpful to explain the problem to someone else just to see things clearer and come up with a possible solution. Here is what I've just realized.

We don't actually need to keep the complete list during our calculations and only need a single row at a time. Let's reuse it and recalculate the cell values in the loop:

MODULO = 10 ** 9 + 7

class Solution(object):
    def checkRecord(self, n):
        lates = [1, 1, 0]
        absences = [1, 0, 0]

        for i in xrange(2, n + 1):
            sum_lates = sum(lates)
            lates = sum_lates % MODULO, lates[0], lates[1]
            absences = (sum_lates + sum(absences) % MODULO, absences[0], absences[1])

        return (sum(lates) + sum(absences)) % MODULO

I think I've seen this technique before and, if I remember correctly, it is called "Rolling Array".


Well, my first impression is that your formatting is broken. Generally, before you even consider checking in a new revision to your local source-control or showing it to anyone, the code should be properly formatted, preferably automatically.
Importing big / open-ended namespaces is a bad idea. Read "Why is “using namespace std;” considered bad practice?" for the reasons.
You are missing the header for std::string. The unused header for C-Strings does not make up for that omission.
nextpalin() is quite a non-obvious Abbreviation, nor does it follow any of the conventions for multi-word-names. Why abbreviate at all?
Mark functions and variables only used in the local TU as TU-local using static. That reduces chances for conflicts and encourages inlining.
nextpalin() uses brute-force without any consideration for efficiency. Work smarter not harder, and you might avoid TLE.
Consider using an unsigned type when a negative number makes no sense. Can your input be negative? I doubt it, but you should know better.
Don't arbitrarily restrict the domain of your function without good reason, and document it if you do. Specifically, why doesn't it handle zero, and what business does main() have dealing with it instead?
Always check whether input succeeded. There are any number of ways it could fail.

First, there are smarter ways to check whether a given number is a palindrome in some arbitrary base than conversion to string. See "Palindrome numbers - Project Euler Problem 4". Not that it matters, because incrementing and testing is incredibly inefficient already.

Next, there are smarter ways to go from a number to the next one which is a palindrome than just checking one after the other. One possible algorithm:

n < 0 || n >= max_palindrome => 0
Increment n.
Take the upper half of the number (including middle if odd size).
If it is smaller than the reversed lower half (including middle if odd size), increment it.
Re-generate the bottom half from the top half to get the full number you wanted.

Finding the biggest palindrome, necessary for wrap-around and avoiding overflow:

template <unsigned long long base = 10, class T>
constexpr bool is_power(T n) {
    static_assert(base >= 2, "The base must be at least 2.");
    constexpr T base = BASE;
    if (n > 0)
        while (!(n % base))
            n /= base;
    return n == 1;
}

template <unsigned long long BASE = 10, class T>
constexpr T last_palindrome(T n) {
    static_assert(base >= 2, "The base must be at least 2.");
    constexpr T base = BASE;

    n = n > 0 ? n - 1 : std::numeric_limits<T>::max();
    if (is_power<BASE>(n))
        return n - 1;

    T top = n, rbottom = 0;
    for (; n >= base; n /= base * base) {
        rbottom = rbottom * base + top % base;
        top /= base;
    }
    if (n)
        rbottom = rbottom * base + top % base;

    top -= top > rbottom;

    for (n = n ? top / base : top; n; n /= base)
        top = top * base + n % base;
    return top;
}

An implementation of the algorithm itself:

template <unsigned long long BASE = 10, class T>
constexpr T next_palindrome(T n) {
    static_assert(base >= 2, "The base must be at least 2.");
    constexpr T base = BASE;
    constexpr T biggest = last_palindrome<BASE>(T());

    if (n < 0 || biggest > 0 && n >= biggest)
        return 0;
    ++n;

    T top = n, rbottom = 0;
    for (; n >= base; n /= base * base) {
        rbottom = rbottom * base + top % base;
        top /= base;
    }
    if (n)
        rbottom = rbottom * base + top % base;

    top += top < rbottom;

    for (n = n ? top / base : top; n; n /= base)
        top = top * base + n % base;
    return top;
}


as you say, it does look like this code is doing exactly what you want. But it also looks like you are repeating yourself in a couple of places.

If it was me, I would prefer to loop through the file only once and check for both Sample Text and Time Taken at the same time, and then only print out if the sample text is there:

def my_read(my_text):
    time_taken, sample_text = False, False
    with open(my_text) as f:
        for i in f:
            time_taken = ' '.join(i.split()) if 'Time Taken' in i else time_taken
            sample_text = 'I have found it!' if 'Sample Text' in i else sample_text

    # now, if sample text was found, print out
    if sample_text:
        print sample_text
        print time_taken
    return

my_read('MyText.txt')

By testing for both, you avoid having to use f.seek(0) and start looping through the file again. Of course, this is based on the sample input above - and assumes that there isn't multiple lines with 'Time taken' or 'Sample Text' in them.

Hope this helps


Calculating the number of primes between 3 and another number

No, I wouldn't say you're using too many variables (except for c, which doesn't appear to be used anywhere).  Not enough functions, though.  And perhaps too many spurious assignments.  Specifically, I'd suggest something like:

#include <iostream>
using namespace std;

bool isPrime(int);
int countPrimes(int);
int main() {
    int userValue;
    cout<< "Enter a number : "<< flush;
    cin >> userValue;

    cout << "There are, " << countPrimes(userValue) << " number of primes from 3 to "<< userValue << endl;
    cout << "hit enter to terminate..."<< flush;
    cin.get();
    cin.get();
}

int countPrimes(int number) {
    int result = 0;
    for (int x = 3; x <= number; x += 2){
        if (isPrime(x)){
            result++;
        }
    }
    return result;
}

bool isPrime(int number){
    for(int i=2; i<number; i++){
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

That will do the same thing as your code.  Also, please consider using variable names that are not just single-letters.


Return timeframes relevant to just-elapsed time period (financial/trading context)

I think you should separate the computation in three different functions, one for minutes, one for hours, and one for days. And generalize each of these functions, so they can be used for other time frames if you ever decide to change them.

Minutes

You can specify an extra parameter in range(), the step: how much is added every iteration. With this the method to check a minute time frame is quite simple:

def minute_timeframe(minutes, timestamp, timeframes):
    for x in range(0, 60, minutes):
        if timestamp.minute == x:
            timeframes.append(f"{minutes}m")

Since your tags say you use Python 3, I used formatted string literals.

Hours

Be careful! You are using the & operator, which in Python is the binary and operation. Since what you want is probably the logical and (i.e. this is true and the other is true), use the and keyword (same for or and not).

By looking at your implementation of hour timeframes, it's pretty easy to generalize:

def hour_timeframe(hours, timestamp, timeframes):
    if timestamp.minute == 0 and timestamp.hour % hours == 0:
        timeframes.append(f"{hours}h")

Days

The same happens for generalizing days. I must comment though, that your original does not seem to follow the PEP 8 Style for the indentations on that part of the code. You also do not need the parenthesis surrounding the if condition.

def day_timeframe(days, timestamp, timeframes):
    if timestamp.minute == 0 and timestamp.hour == 0 and timestamp.day % days == 0:
          timeframes.append(f"{days}d")

Final result

Now that our functions are generalized, in my opinion what would be best is to store a list of the different timeframes you want to use, that way adding new ones or changing them is simple. This is the final function:

# Constants go in ALL_CAPS
MINUTE_TIMEFRAMES = [3, 5, 15, 30]
HOUR_TIMEFRAMES = [1, 2, 3, 4, 6, 8]
DAY_TIMEFRAMES = [1, 2, 3]

def get_timeframes(self):
    timestamp = datetime.datetime.utcnow()
    timeframes = ["1m"]

    for x in MINUTE_TIMEFRAMES:
        minute_timeframe(x, timestamp, timeframes)

    for x in HOUR_TIMEFRAMES:
        hour_timeframe(x, timestamp, timeframes)

    for x in DAY_TIMEFRAMES:
        day_timeframe(x, timestamp, timeframes)

    # Format it correctly and use 'and'
    if (timestamp.minute == 0 and timestamp.hour == 0 and
        calendar.day_name[date.today().weekday()] == "Monday"):
        timeframes.append("1w")


Counting the number of "on" bits in an int

The current implementation

Your implementation is correct, and takes \$O(n)\$ time, where \$n\$ is the number of bits in an int.  One thing you can improve is the initial setting of b_mask.  Currently, you use a loop, but it can be done like this:

unsigned int b_mask = 1u << (sizeof(b_mask)*CHAR_BIT - 1);

Actually, there are two other strategies you can use as well:

Start b_mask at 1 and left shift it instead of right shift it.
Get rid of b_mask and shift the number instead.

For an example of #2:

int on_bits(unsigned int num)
{
    int res = 0;

    while (num != 0) {
        res += (num & 0x1);
        num >>= 1;
    }

    return res;
}

Other implementations

There are a wide variety of ways to count bits.  You should read the wikipedia page on Hamming weight for starters.  I'll briefly mention some here:

Removing one bit per loop

There is a bit trick that removes the lowest set bit.  So instead of looping \$n\$ times (e.g. 32), you can only loop \$m\$ times, where \$m\$ is the number of bits actually set. So if there is only 1 bit set, you only have to loop once.  The code looks like this:

int on_bits(unsigned int num)
{
    int res = 0;

    while (num != 0) {
        num &= num - 1;
        res++;
    }

    return res;
}

Using hardware instruction

Many CPUs have a dedicated instruction for counting bits (e.g. popcnt for X86).  Your compiler probably has a way of accessing this instruction (e.g. __builtin_popcount() for GNU.  This will be the fastest of all implementations but will be hardware and compiler dependent.

int on_bits(unsigned int num)
{
    return __builtin_popcount(num);
}

Using a lookup table

Suppose you created a lookup table with 256 entries that contained the number of bits set in each byte value 0..255.  Then your code would need to loop only 4 times instead of 32:

static const uint8_t bitsInByte[256] = { /* Prefilled in */ };
int on_bits(unsigned int num)
{
    int res = 0;

    while (num != 0) {
        res += bitsInByte[num & 0xff];
        num >>= 8;
    }

    return res;
}

Using parallelism and bit tricks

This is described in the wikipedia article in depth.  Here I give the 32-bit version instead of the 64-bit one:

// Assumes int is 32 bits
int on_bits(unsigned int num)
{
    num -= ((num >> 1) & 0x55555555);
    num  = (num & 0x33333333) + ((num >> 2) & 0x33333333);
    return (((num + (num >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}

One's complement

According to later comments by the OP, being able to handle one's complement is important, and the input argument should be int instead of unsigned int.  You can still use all of the functions above, if you first prepare the input argument by stripping its sign bit, like this:

int on_bits(int num)
{
    int signBit = 1 << (sizeof(int)*CHAR_BIT - 1);
    int res     = (num & signBit) != 0;

    num &= ~signBit;

    // Now, num has its sign bit stripped so it can be right shifted.
    // Res is 1 if the sign bit was set, or 0 if it was not.

    // Do the rest here...
}


Parsing positive integers from CSV file Part-2

Great that you renamed you function according to what it does. I would suggest, that you add a helper function that reads a single line.

Creating small well encapsulated functions is key in writing maintainable code.

Regarding you code there are some small nits:

The code pattern

container[container.size() - 1]

can alway be replaced by

container.back()

Regarding the parsing you could use std::string::find_first_of and search for the next occurence of it.

std::size_t first = 0;
std::size_t second;
while (first != buffer.size()) {
    second = buffer.find_first_of(",\r", first);
    // parse [first, second)
    first = second + 1;
}

That way in the interval [first, second) there would always be the numbers and you would not have to replace the final character or other stuff
Again encapsulation. There is no reason why the this block of code is not inside its own function:

uint_fast16_t parsed_number = 0;
for (const auto& digit : buffer) {
    if (digit == ',') {
        numbers.emplace_back(parsed_number);
        parsed_number = 0;
    }
    else {
        parsed_number = (parsed_number * 10) + (digit - '0');
    }
}

Even better if you encapsulate it you can easily adopt for iterators/positions

uint_fast16_t parse_number(cont std::string& buffer, std::size_t first, std::size_t second) {
    uint_fast16_t parsed_number = 0;
    for (std::size_t i = first; i < second; ++i) {
        parsed_number = (parsed_number * 10) + (buffer[i] - '0');
    }
    return parsed_number;
}

Now you can write the loop as

while (infile.good() && std::getline(infile, buffer)) {
    std::size_t first = 0;
    std::size_t second;
    while (first != buffer.size()) {
        second = buffer.find_first_of(",\r", first);
        numbers.push_back(parse_number(buffer, first,second));
        first = second + 1;
    }
    callback(numbers);
    numbers.clear();
}

I would even suggest to create another function for parsing the single line:

void parse_single_line(std::string& buffer, std::vector<uint_fast16_t>& numbers) {
    std::size_t first = 0;
    std::size_t second;
    while (first != buffer.size()) {
        second = buffer.find_first_of(",\r", first);
        numbers.push_back(parse_number(buffer, first,second));
        first = second + 1;
    }

Together this leads to

while (infile.good() && std::getline(infile, buffer)) {
    parse_single_line(buffer, numbers);
    callback(numbers);
    numbers.clear();
}


Reading one byte at a time is bad idea, because it won't buffer the input. Instead, you'll probably get a system call for each byte which will be really inefficient.

Easiest solution is to use makefile

myfile = sock.makefile('r')

Then you can treat myfile like a file, including using methods like readline. That'll be more efficient then your version.

It seems a bit of waste to have readheaders() convert all the headers into one long string, only to have parseheaders() split it apart again.

if "Transfer-Encoding" in headersdict and headersdict["Transfer-Encoding"] == "chunked":

I'd use if headersdict.get('Transfer-Encoding') == 'chunked':, if the key is not present, get will return None, and you'll have the same effect as before.

Of course, for serious stuff, you'd want to use the builtin python libraries for this sort of thing. But as long as you are doing it to learn, all well and good.


Finding the upper and lower bound using binary search

I am trying to understand what aspect of my code could be made more efficient and faster.

First, the low hanging fruits...

You unnecessarily copy the sequence of integers when passing it to findBound:

int findBound(vector<int> a, int b, bool lower)

should be

int findBound(const vector<int>& a, int b, bool lower)

You dispatch on the bool lower flag in every iteration of the main while-loop:

if(lower) {
   /* ... */
} else {
   /* ... */
}

Consider implementing two separate functions for the starting and one for the end index of the range.
In one of the if-conditions in the middle of the main loop, you compute a.size() - 1. This could be done once at the top of the function and bound to a const-qualified variable. No need to evaluate this in every iteration.

Now, the crucial step...

You are doing unnecessary work when comparing values. The very first if-condition,

if(a[mid]==b) { // ...

tests for the branch with the least likelihood. Instead, check for a[mid] < b and nothing more. If you're wondering how this can be sufficient, check out this part of Sean Parent's Pacific C++ talk from 2018.


Your code does a few things repetitively:

count = 0
playercard1 = list()
while count < n_players:
    card1 = self.deck[count]
    playercard1.append(card1)
    count += 1

for i in playercard1:
    self.deck.remove(i)

I'll go through the problems with this:

You manually increment count, this is something that you should do with range.
You manually index every item.
You manually append to a list.
You manually remove each card from the deck, this causes the list to shift, and causes a small search of the list. (\$O(n)\$ complexity)

Instead you could either:

Pop the amount of cards you need.

pop = self.deck.pop
playercard1 = [pop() for _ in range(n_players)]

Slice the amount of items you need and then delete them.

playercard1 = self.deck[-n_players:]
del self.deck[-n_players:]

You should notice that I take from the end of the list, this is as you aren't using a queue and so they will be faster.

The other main code you use is:

del self.deck[0]
self.flopcards = self.deck[0:3]
del self.deck[0:3]

This uses the same code as before, but burns one card.
You can then just make two functions to do what most of your code is doing at the moment.

def take(self, number_cards):
    pop = self.deck.pop
    return [pop() for _ in range(number_cards)]

def draw(self, number_cards):
    self.deck.pop()
    return self.take(number_cards)

This then makes the rest of your code simple and easy to read and use.

def deal(self, n_players):
    self.playerhand = zip(self.take(n_players), self.take(n_players))

def flop(self):
    self.flopcards = self.draw(3)

def turn(self):
    self.turncard = self.draw(1)

def river(self):
    self.rivercard = self.draw(1)

Other than the above I'd:

Add shuffle to your __init__ so that the cards are pre-shuffled.
Move the deck creation into shuffle to allow more than one game, and
Move values and suites to the global scope as 'constants'.

This results in something like:

VALUES = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
SUITES = ['Heart', 'Spade', 'Club', 'Diamond']
class TexasHoldem:
    def __init__(self):
        self.shuffle()

    def shuffle(self):
        self.deck = [j + " " + i for j in VALUES for i in SUITES]
        shuffle(self.deck)


Object pool with linked list of available objects implementation

Design and architecture:

The design of your Object Pool is somewhat unusual. Since you are declaring the payload of type T by value inside the Object struct, once the vector objs is allocated, all objects will also be allocated beforehand. This is fine, if that was your intention, but will require type T to be default constructible.

Another strange thing is the bool create(T newObj); method. You are actually passing a T instance by value. So the pool will in reality only be storing a copy of an existing object. Usually, object/memory pools will keep a set of instances of something that can be recycled. Thus, I would expect the creation method of the pool to return a pointer to an existing (and possibly recycled) object:

T * Pool::create() { /* ... */ }

Possibly returning nullptr or throwing an exception if out of memory or instances to recycle.

The way you deallocate the objects is also unusual. You are again passing a copy of some value of type T to the removeObj() method, which then scans the array of Objects and if finding a match, marks it as unused. Again you are making the assumption that type T can be compared with operator ==, which is not the case for User Defined Types if you don't explicitly implement operator ==. That seems like and unnecessary constraint. In fact, your whole Object Pool seems to be just a thin wrapper over a vector. What I would have expected to see would be a method that returns a pointer to the pool so that is can be recycled. Something in the lines of:

void Pool::free(T * object) { /* ... */ }

I would like to point you to this implementation of a Pool allocator that you can refer to. This was used by the Doom 3 game. It is also based on a linked list, but it uses a list of arrays of objects. Thanks to some pointer manipulation, removal is also constant complexity. Looking at that implementation might make these things I've mentioned more clear to you.

Code review:

Now focusing on the code presented in the question:

This is a personal preference of mine, but I like to place the public section of a class first in the header file. My rationale is that people using and reading my code will care much more about the public methods of a class, so that's what they want to see first when reading the header file. Private/protected sections of a class are of interest to the programmer maintaining the code, so it makes sense that they don't need that much visibility.
You don't need to implement an empty constructor. Use the new default syntax (C++11):

// In the declaration inside the class body:
Pool() = default;

You should probably make the constructor that takes a single size parameter explicit, to avoid questionable implicit conversions:

explicit Pool(int size);

Since your class has some naked pointers as its members, defining its behavior regarding copy and assignment is very important. Read about The Rule of Three. My suggestion at first would be to just make it non-copyable by deleting the assignment operator and copy constructor. It seems like the safest and simplest option in this case:

Pool(const Pool&) = delete;
Pool& operator = (const Pool&) = delete;

The size member variable is unnecessary. std::vector has a member function with the same name: size().
Initialize the member vector objs in the constructor initialization list:

template <class T> Pool<T>::Pool(int size):size(size)
{
    objs = std::vector< Object >(size);
    ...

By doing that assignment, you are risking a duplicate initialization. It will first be initialized with the default vector constructor and then again with operator =. I'm not sure if the current generation of compilers is optimizing that or not. I'd guess not because this is a bad programming practice that is easy to fix:

 template <class T> Pool<T>::Pool(int size)
     : objs(size)
     , numAlive(0)
     , nextAvailable(nullptr)
 {
     ...
 }

Note that you could also use the uniform initialization style if you wanted (e.g. use { } instead of ( ) when calling the constructors of the member variables).
Avoid repeating types when declaring objects (remember to DRY):

std::vector<T*> avl = std::vector<T*>(numAlive);

No need to type std::vector<T*> twice here. You have two options in this case:

The "classic" style:

 std::vector<T*> avl(numAlive);

The new "auto" style from C++11:

 auto avl = std::vector<T*>{numAlive};

I personally like the first "classic" style, however, the second one is starting to be advocated by some programmers, including Herb Sutter.


Yet another Sieve of Eratosthenes in Java

Documentation
The class shouldn't mention who the intended client is, just what it does.
Most of your comments inside methods are noise. Document why, not what.
Error Handling
You don't handle bad inputs (e.g. negative values). It doesn't make sense for siftTill() to return an ArrayIndexOutOfBoundsException in that case. Explicitly throw a relevant exception, like IllegalArgumentException.
Naming
You use 'till' as an abbreviation for 'until'. Don't! A "till" is a real word which means something different, and it may be confusing, especially since 'until' only has one 'l'.
Best Practices
Don't reassign method parameters.
Declare variables as close as possible to their first use.
Don't use increment/decrement operations inside array references. Junior programmers will not be able to tell the order of operations.
It doesn't make sense to have a getPrimesTill() take an int as the maximum value but return a long[].
You're better off keying loops off of the array's size explicitly, rather than the variable you used to set its length. That way, if either changes your array traversal won't break.
The Primes class should be final and have a private constructor to indicate it should not be instantiated. Alternately, make an instantiable class that can be optionally be reused and runs the sieve for numbers it hasn't yet computed. That lets you keep computed information, such as the number of primes, in a member variable rather than having to walk your sieve array to find it.
Putting it all together might look something like:
import java.util.Arrays;

/**
 * This is a utility class that contains methods related to prime numbers.
 *
 * @author Subhomoy Haldar
 * @version 1.0
 */
public final class Primes {

    /**
     * Returns a boolean array that is essentially a sieve. In order to check
     * if a number is prime, check if the boolean at that index is true. For
     * example,
     *
     *

     *
     *  // ...
     *  boolean[] sieve = Prime.siftTill(someLimit);
     *  int n = (yourNumber);
     *  if (sieve[n])
     *      // ... do operations with the prime number
     *  // ...
     *
     *

     *

     *
Time complexity:

     * O(n log log n)
     *
Space complexity:
 O(n)
     *
     * @param n The number until which the sieve must be generated.
     * @return The sieve in the form of a boolean array.
     */
    public static boolean[] siftUntil(final int n) {

        final boolean[] sieve = new boolean[n + 1];
        Arrays.fill(sieve, true);
        sieve[0] = false;
        sieve[1] = false;

        removePrimeMultiplesFrom(sieve);

        return sieve;
    }

    private static void removePrimeMultiplesFrom(final boolean[] sieve) {
        final int limit = (int) Math.sqrt(sieve.length);
        for (int i = 2; i < limit; i++) {
            if (!sieve[i]) {
                continue;
            }

            for (int j = i * i; j < sieve.length; j += i) {
                sieve[j] = false;
            }
        }
    }

    /**
     * Returns an array of primes up to the given inclusive limit.
     *

     *
Time complexity:

     * O(n)
     *
Space complexity:
 O(n)
     *
     * @param limit The inclusive upper limit.
     * @return An array of primes up to the given inclusive limit.
     */
    public static int[] getPrimesUntil(final int limit) {

        final boolean[] isPrime = siftUntil(limit);

        final int[] primes = new int[countPrimes(isPrime)];
        for (int i = 2, primeIndex = 0; i <= limit; i++) {
            if (isPrime[i]) {
                primes[primeIndex] = i;
                primeIndex++;
            }
        }
        return primes;
    }

    private static int countPrimes(final boolean[] isPrime) {
        int count = 0;
        for (int i = 2; i < isPrime.length; i++) {
            if (isPrime[i]) {
                count++;
            }
        }
        return count;
    }

}


Dynamically call lambda based on stream input: Try 2

It is becoming really good, but there are still a few things that can be done:

There already is a standard way to "clean" a type: std::decay. It does a little bit more than just removing the reference and the const qualification though, but it does basically what you need. Therefore, you can totally get rid of CleanType and use std::decay instead:

using AllArgs = std::tuple<typename std::decay<Args>::type...>;

And since you are using C++14 (I assume this because of std::integer_sequence), you can even use std::decay_t instead:

using AllArgs = std::tuple<std::decay_t<Args>...>;

N3887 also made its way to the C++14 standard. Therefore, if you actually use C++14, you will be able to use the alias template std::tuple_element_t instead of the metafunction std::tuple_element:

ArgumentTupple arguments(row.getValue1<std::tuple_element_t<S, ArgumentTupple>>()...);

This line looks kind of wrong:

typedef typename std::make_integer_sequence<int, size>      Sequence;

When I tried to compile your example, it didn't compile at first because of the typename in this line. std::make_integer_sequence is an alias template, there shouldn't be a typename before it.
You sometimes use ResultRowSet and use ResultSetRow at some other places. It's probably a typo or something like that :p
ArgumentTupple also feels like a typo. It should probably be ArgumentTuple.
std::integer_sequence does not contain anything. Therefore, there is no need to pass is by const&, you can simply pass it by value.


ADL

This can be improved. First - you're requiring a tie() member function, it'd be better to make that more of a customization point. Second - you're putting all the operators in global scope when it'd be better to hide them. Both issues can be solved with some ADL.

The advantage of making an operator a non-member friend declared inline is that it can only be found when comparing precisely what you want. The downside to what you're doing right now is the following compiles:

struct B : Comparable<B> {
    ...
};

struct D {
    operator B() { ... }
};

D d1 = ...;
D d2 = ....;
if (d1 == d2) { ... }

D isn't comparable - but this code would still compile via the B conversion, which may be surprising!

We can instead write equality like so:

namespace cmp {
    template <class T>
    auto tie(const T& val) -> decltype(val.tie()) {
        return val.tie();
    }

    template <class T>
    struct Comparable {
        friend bool operator==(const T& lhs, const T& rhs) {
            return tie(lhs) == tie(rhs);
        }
    };
}

Note that the operator here takes Ts and not Comparable<T>s. We know what the derived type is, so we can just use it. The nonqualified call to tie lets us write something like:

namespace foo {
    struct B : Comparable<B> {
        int i;
    };

    int tie(const B& b) { return b.i; }
}

Customization is nice.

Split it up

EqualityComparable and LessThanComparable are different concepts. If you split up the responsibilities, it'll make your class more useful:

namespace cmp {
    template <class T>
    struct EqualityComparable {
        friend bool operator==(const T& lhs, const T& rhs) { return tie(lhs) == tie(rhs); }
        friend bool operator!=(const T& lhs, const T& rhs) { !(lhs == rhs); }
    };

    template <class T>
    struct LessThanComparable {
        friend bool operator<(const T& lhs, const T& rhs) { return tie(lhs) < tie(rhs); }
        friend bool operator<=(const T& lhs, const T& rhs) { return !(rhs < lhs); }
        // etc.
    };

    template <class T>
    struct TotallyOrdered : EqualityComparable<T>, LessThanComparable<T>
    { };
}

Cross-Compare

If two classes have comparable tie()s, why not support that too?

template <class T, class U>
struct EqualityComparable2
{
    friend bool operator==(const T& lhs, const U& rhs) { return tie(lhs) == tie(rhs); }
    friend bool operator==(const U& lhs, const T& rhs) { return rhs == lhs; }
    // same for !=
};

Go wild.


Checking whether an image is part of another

To answer your second point:

Why not include the foundMatch in the condition of the while?

while (!foundMatch && image.width() < MAX_IMAGE_WIDTH) {

That way you don't run the second loop at all if a match was found in the first.

Having a couple of duplicate lines isn't a bad thing. It's obvious what the lines do and what the difference is between the 2 loops (1 scaling up, the other scaling down). So at least in my opinion there is nothing wrong with having both loops like this.

I'm actually most surprised that you need to handle scaling at all though. One of the most popular image comparison algorithms these days uses SIFT (Scale invariant feature transform) which, as the name implies is scale invariant.


Using Enum in java to store a fixed set of mutable objects

Enums are meant to be immutable. I'd  go with the EnumMap.


First of all, URL encoding is more nuanced than you might think.  Be cautious when applying encoding.

As for your code, the only blatant bug I see is that it can segfault when encoding a non-ASCII string.  The -length method returns the number of Unicode characters in the string.  Since you are working one char at a time, you need the number of bytes instead.

NSUInteger clen = [orig lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSUInteger nlen = 3 * clen;

It would be better to change the method signature to:

NSString *urlEncode(const NSString *orig)

I think that using a for loop would improve readability.  Currently, you declare/initialize *o, test it, and decrement it on three separate lines.  A for loop would provide an instantly recognizable structure to make it obvious how those three lines of code are related:

for (const char *o = cstr + clen - 1; o >= cstr; o--) {
    unsigned char c = *o;
    if (safe[c]) {
        *--p = c;
    } else {
        *--p = digits[c & 0x0f];
        *--p = digits[c >> 4];
        *--p = '%';
    }
}

The null char would be better written as '\0'.

Personally, I would choose to iterate forward rather than backward through the string, as it simplifies the loop by a few instructions, and is easier to understand.  It also gives you the option of calling -maximumLengthOfBytesUsingEncoding (which runs in O(1) time) instead of -lengthOfBytesUsingEncoding.

unsigned char c;
char *p = newstr;
for (const char *o = cstr; (c = *o); o++) {
    ...
}


var decrypted = document.getElementById("decoded");
var encrypted = document.getElementById("encoded");

function startdecrypt() {
    // Original text, split into an array and reversed (for faster pop())
    var originalText = decrypted.textContent.split('').reverse();
    var decryptedText = "";
    var i = 0;

    decrypted.textContent = "";

    var shuffleInterval = setInterval(function(){

      // Generate random strings. You can modify the generator function range
      // (Math.random()*(to-from+1)+from);
      var shuffledText = '';
      var j = originalText.length;
      while(j--) shuffledText += String.fromCharCode((Math.random()*94+33) | 0);
      // You can also use this generator to use only the remaining letters
      // while(j--) shuffledText += originalText[(Math.random()*j) | 0];

      // On every 10 cycles, remove a character from the original text to the decoded text
      if(i++ % 10 === 0) decryptedText += originalText.pop();

      // Display
      decrypted.textContent = decryptedText;
      encrypted.textContent = shuffledText;

      // Stop when done
      if(!shuffledText.length) clearInterval(shuffleInterval);

    // 50ms looks more dramatic
    },50);
}

if (window.addEventListener) {
    window.addEventListener('load', startdecrypt, false); //W3C
} else {
    window.attachEvent('onload', startdecrypt); //IE
}

Changes

Everything in one function
Simplified the code
Using setInterval rather than setTimeout. This is more efficient since you don't create timers everytime
More drama by adding random string generator, instead of just your original set of letters. This adds more mystery to the next letters.
In addition to the code, a monospace font would be more dramatic. It avoids the to-fro movement of the decoding text.


Automatic C++ enum to string mapping macro

I agree with the comments: macros are a mess. Avoid them when possible.

If you're willing to make certain sacrifices (a little repetition), it's possible to avoid macros here. Doing so will also avoid some of the arbitrary limitations in your macro implementation, such as the 10 or so cap on enum values.

Using C++11, it's not hard to wire up Loki Astari's approach to operator<< and operator>> with some type traits template metaprogramming. I personally think enums are much cleaner with the strongly typed enum class ... variant introduced by C++11, so I would suggest that anyway, but the enum_serializable approach I show here works on both strongly and weakly typed enums.

#include <type_traits>
#include <iostream>
#include <https://codereview.stackexchange.com/a/14315/507 by reference>

template <typename Enum>
struct enum_serializable : std::false_type
{};

// enable operator<< and operator>> for `Essai` values
template <>
struct enum_serializable<Essai> : std::true_type
{};

template <typename Enum>
typename std::enable_if<enum_serializable<Enum>::value, std::ostream&
>::type operator<<(std::ostream& os, Enum e)
{
    return os << enumToString(e);
}

template <typename Enum>
typename std::enable_if<enum_serializable<Enum>::value, std::istream&
>::type operator>>(std::istream& is, Enum& e)
{
    return is >> enumFromString(e);
}

It's also not hard to pull Loki Astari's approach into the operator<< and operator>> functions above, removing the separate enumToString and enumFromString functions and the enumRefHolder and enumConstRefHolder structs entirely.

This general approach should be available before C++11 as well, but std::enable_if will have to be implemented instead of #included.


Convert first letter of every word to uppercase

A few observations on improving the code snippet, but using the same basic logic:

If you split the string with components, you can use joined to put them back together.
The ...str.startIndex syntax will crash if you supply a zero length string. I would suggest using prefix and dropFirst to simplify the code.
When writing routines like this, I’d generally suggest using StringProtocol so that it works for both string and substrings. In this case, I would make it an extension of StringProtocol.
This method of capitalizing the first character of every word (regardless of part of speech) is sometimes called “start case” or “proper case”. I would suggest renaming the method accordingly.

Thus:
extension StringProtocol {
    func startcased() -> String {
        components(separatedBy: " ")
            .map { $0.prefix(1).uppercased() + $0.dropFirst() }
            .joined(separator: " ")
    }
}

let string = "this is a test"
print(string.startcased())                                  // This Is A Test

If the in the intent was to achieve “title case”, we often wouldn't capitalize certain parts of speech, e.g., articles and conjunctions. The NaturalLanguage library can be used for more refined capitalization logic:
import NaturalLanguage

extension StringProtocol {
    func titlecased() -> String {
        var capitalizeWordRanges: [Range<String.Index>] = []

        var result = String(self)

        // find words other than conjunctions and determiners

        let tagger = NLTagger(tagSchemes: [.lexicalClass])
        tagger.string = result
        let options: NLTagger.Options = [.omitWhitespace, .joinContractions]
        var isStartOfSentence = true

        tagger.enumerateTags(in: startIndex..<endIndex, unit: .word, scheme: .lexicalClass, options: options) { tag, range in
            guard let tag = tag else { return true }

            print(tag.rawValue, self[range])

            switch tag {
            case .sentenceTerminator:               // see if we're potentially starting a new sentence
                isStartOfSentence = true
                return true

            case .punctuation, .openQuote, .closeQuote, .openParenthesis, .closeParenthesis:
                return true

            case .conjunction where self[range].count < 4,
                 .determiner where self[range].count < 4,
                 .preposition where self[range].count < 4:         // only capitalize conjunctions or articles at the start of a sentence
                if isStartOfSentence { fallthrough }

            default:
                capitalizeWordRanges.append(range)            // otherwise, add this to the array of ranges to t
            }

            isStartOfSentence = false

            return true
        }

        // loop through, doing replacements; do it in reverse order because sometimes the capitalized string isn't the same length, e.g. German ß -> SS

        for range in capitalizeWordRanges.reversed() {
            result.replaceSubrange(range.lowerBound...range.lowerBound, with: result[range.lowerBound].uppercased())
        }

        return result
    }
}

let string2 = "this is a test"
print(string2.titlecased())                                 // This Is a Test

let string3 = #"The sign said, "don't feed the animals.""#
print(string3.titlecased())                                 // The Sign Said, "Don't Feed the Animals."

let string4 = "¿donde está la biblioteca?"
print(string4.titlecased())                                 // ¿Donde Está la Biblioteca?

Note, enumerating through the words solves another problem, namely situations where words may not preceded immediately by a space, but rather, perhaps punctuation, such as the quotation marks before “don't” in string3, above. Just splitting and joining by spaces will only work in the simplest of scenarios. Also, some languages have punctuation at the start of a sentence, e.g. the Spanish “¡Ay, caramba!” or “¿Donde está la biblioteca?” If you iterate through the actual words, rather than relying on spaces, you solve that problem.
This admittedly is not perfect “title case” logic. E.g. it is taking care of the capitalizing of the first character, but not shifting the rest of the word to lowercase (e.g., if the input string was entirely in uppercase). But if you are only worried about the first letter, this is probably better than the naive start/proper capitalization routine. And if you want to implement a richer title case rendition, this routine might be a good starting point.


I'm going to go over a few things in this answer, hopefully it makes them simple enough. Then, at the end, I'm going to go way overboard and significantly over-engineer this programme while still making it shorter.

First, let's talk about your input handling (or lack thereof). As programmers, we should strive to be able to gracefully handle any/all input, and do something appropriate as a result. For invalid input, usually we reprompt (sometimes we just gracefully fail), for valid input, we go to the next step.

You assume all input will be valid, which is a huge potential for problematic behavior. What happens if I enter one for either number? Bad things, my friend, bad things.

So, let's handle all that gracefully. I wrote a specific portion of a library I have written specifically for input handling, and gracefully doing so.

Basically, you need all three files from this GitHub folder. You will also need both the bottom files, from this other GitHub folder. You'll want to modify the namespaces to suit your structure. (You may also just download the entire repo, and build Evbpc.Framework, which I recommend. All of this is beyond the scope of this answer.)

Next, you'll want to create a ConsolePrompt object:

var prompter = new ConsolePrompt(null);

Once you've done that, you can simply use:

var validOperations = new[] { "x", "/", "+", "-" };
var firstNum prompter.Prompt<int>("Enter the first number in your basic equation", PromptOptions.Required);
var secondNum = prompter.Prompt<int>("Now enter your second number in the basic equation", PromptOptions.Required);
var operation = prompter.Prompt<string>("Ok now enter your operation (" + string.Join(", ", validOperations) + ")", PromptOptions.Required, validationMethod: x => validOperations.Contains(x));

Now we've done three things here:

We validate all the numbers and reprompt the user if the number is invalid.
We make sure the user only entered a basic operation for the intended operation.
We make a list of valid operations at the beginning, which means if we add one we can do so easily.

Next, we'll talk about your conditions. You use an if statement for all your operations, but that's unnecessary and creates extra processing in the case that the operation is the last condition. (Each previous if is evaluated before it continues to the next.)

Instead, we'll go to a switch statement:

switch (operation)
{
    case "x":
        answer = firstNum * secondNum;
        break;
    case "/":
        answer = firstNum / secondNum;
        break;
    case "+":
        answer = firstNum + secondNum;
        break;
    case "-":
        answer = firstNum - secondNum;
        break:
}

By using a switch we've made things substantially more clear: our intention is to only evaluate what operation is and do something based on it.

Next, we'll talk about your output. You repeat certain statements excessively, let's find a better way to do that.

We have firstNum and secondNum, as well as operation and answer. So how can we rewrite our Console.WriteLine methods to be more dynamic? Well, with the switch it's easy, right after the end brace for the switch we just write what each value was:

Console.WriteLine(firstNum + " " + operation + " " + secondNum + " = " + answer);

Boom. We don't need the Console.WriteLine in each switch (or if) block. We just need one at the end.

But there's a better way to write this (with C#6.0, that is):

Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");

Using string interpolation we make it much easier to read what's going on.

You also had the idea for a while loop in your head to repeat the calculations, so let's do that:

do
{
    // All our calculator code
} while (prompter.Prompt("Enter exit to quit, anything else to continue", PromptOptions.Optional, "", parseResultMethod: x => x.ToLowerInvariant()) != "exit");

And now it will continue until the user types exit at that prompt.

So, we've improved everything you've got going, but there's still one more improvement we can make: convert all our operations to a dictionary.

What do I mean? Well I'll show you.

var operations = new Dictionary<string, Func<int, int, int>>
{
    {"x", (x, y) => x * y },
    {"/", (x, y) => x / y },
    {"+", (x, y) => x + y },
    {"-", (x, y) => x - y }
};
var operation = prompter.Prompt<string>("Ok now enter your operation (" + string.Join(", ", operations.Keys) + ")", PromptOptions.Required, null, null, x => operations.Keys.Contains(x));
var firstNum = prompter.Prompt<int>("Enter the first number in your basic equation", PromptOptions.Required);
var secondNum = prompter.Prompt<int>("Enter the second number in your basic equation", PromptOptions.Required);
var answer = operations[operation](firstNum, secondNum);

What did we just do? We just replaced the entire switch/if blocks, all the manually typing x, /, +, -, etc. with a dictionary of string -> function. Where does this benefit us? Simple. I want to add exponential calculation.

Simply add:

{"^", (x, y) => (int)Math.Pow(x, y)}

to our operations dictionary. Now all our prompts and whatnot can support the power function.

This brings up a new issue: you have no support for decimal/double/float numbers. This is really easy to modify, simply replace all our int types with double.

Lastly, as for a bonus to this answer, you can also add alias operations. (What do I mean? Well what if I naturally use * instead of x for multiplication?)

This is super easy:

// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));

Simply add them after the var operations statement.

var operations = new Dictionary<string, Func<double, double, double>>
{
    {"x", (x, y) => x * y },
    {"/", (x, y) => x / y },
    {"+", (x, y) => x + y },
    {"-", (x, y) => x - y },
    {"^", (x, y) => Math.Pow(x, y) },
    {"%", (x, y) => x % y }
};

// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));

Boom, now you can use * instead of x for multiplication. (But you can still use x as well.)

Our entire programme is now down to 29 lines with appropriate whitespace, and supports much more than your original did. (Your original was 44 lines.)

var prompter = new ConsolePrompt(null);

Console.WriteLine("Hello, welcome to Alex's basic calculator!");
Console.ReadLine();

var operations = new Dictionary<string, Func<double, double, double>>
{
    {"x", (x, y) => x * y },
    {"/", (x, y) => x / y },
    {"+", (x, y) => x + y },
    {"-", (x, y) => x - y },
    {"^", (x, y) => Math.Pow(x, y) },
    {"%", (x, y) => x % y }
};

// Let's add our alias operations, */x
operations.Add("*", (x, y) => operations["x"](x, y));

do
{
    var firstNum = prompter.Prompt<double>("Enter the first number in your basic equation", PromptOptions.Required);
    var secondNum = prompter.Prompt<double>("Enter the second number in your basic equation", PromptOptions.Required);
    var operation = prompter.Prompt<string>("Ok now enter your operation (" + string.Join(", ", operations.Keys) + ")", PromptOptions.Required, null, null, x => operations.Keys.Contains(x));

    var answer = operations[operation](firstNum, secondNum);

    Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");
    Console.ReadLine();
} while (prompter.Prompt("Enter exit to quit, anything else to continue", PromptOptions.Optional, "", parseResultMethod: x => x.ToLowerInvariant()) != "exit");

Pretty cool, eh?

All-in-all, very good start. Hopefully you learned a lot from this answer and can apply some of it to future applications. :)


If you can pass in the subroutine it makes the code a lot simpler, you also don't have to deal with an unknown string format as the subroutine itself has been passed in.

sub print_result
{
    my $subroutine = shift;
    &$subroutine( @_ );
}

print_result( \&print_result_text, $arg1, $arg2 )

Otherwise I think I'd go with with a hash of subroutine references. It's easily readable and simple to update.

sub print_result
{
    my %print_hash = ( text => \&print_result_text,
                        xml => \&print_result_xml );

    if( exists( $print_hash{ $outformat } ) )
    {
        &{$print_hash{ $outformat }}( @_ );
    }
    else
    {
        printf(STDERR "Error: unsupported output format '%s'\n", $outformat);
    }
}


Is this a good way to receive a message from a server?

One thing I do with reading from sockets is separate receiving of the data from what the data contains.

Meaning, you may get your information in progressive chunks.....  so receive a chunk of data, then see if you have a complete "Message".  If not, wait for the next chunk of data.  When you have your full "Message"  then you can pass that on to whatever wants it.

In fact what I have done is abstract the idea of a streaming connection so I can interchange serial ports / tcp sockets / and any other streaming type connection.  Have something that receives from a connection, and then do interpreting.


Break the method down

You can improve the method by trying to put it in smaller methods.

There is a while loop that is a good candidate for this.

The code becomes:

private static int startGuessing(String originalWord, Scanner input) {
        StringBuilder replacedWord = new StringBuilder(hideRealWord(originalWord));
        int missing = 0;
        boolean wrongGuessing;
        int wordLength = originalWord.length();

        while (wordLength > 0) {
            guess();
        }
        return missing;
    }

Use fields in the GameHangman object

Now, you will notice things will break down, as you need the state from your method in the guess() method. So, you'll need to pass all the information around. You will notice this is kind of hard.

Here comes OOP around. You can store the state in an Object. Currently, your game is all static methods. If you start re-writing the game to use an instance of HangmanGame and use fields it will become easier.

For example, good candidates for object-state are:

Scanner
Current word
Original word
Number of incorrect guesses
Remaining length of the word

Now, it becomes something like this:

public class GameHangman {

    private final static String[] WORDS = { "programming", "fish", "cairo", "arabs", "quraan", "sunnah", "editor",
            "photography", "artist", "software", "write", "read", "gaming", "lunch", "participate", "lunch", "dinner",
            "house", "books", "animals" };

    private Scanner input;
    private String originalWord;
    private int missing = 0;
    private boolean wrongGuessing;
    private int wordLength ;

    public GameHangman()
    {
        this.input = new Scanner(System.in);
    }

    public void start() {

        boolean keepPlaying = true;

        while (keepPlaying)
        {
            // Choose a random word
            this.originalWord = chooseWord();

            // Start guessing game with chosen word and count missed times
            int missed = startGuessing();

            // Display result
            System.out.println("The word is " + originalWord + (missed == 0 ? " you are correct"
                    : " you missed " + (missed == 1 ? " one time" : " " + missed + " times")));

            // Ask for another game
            keepPlaying = userWantsAnotherGame();

        }
    }

    private boolean userWantsAnotherGame() {
        System.out.print("Do you want to start another word? Enter y or no>");
        char gameCase = this.input.nextLine().charAt(0);
        return (gameCase == 'y');
    }

    private  int startGuessing() {
        StringBuilder replacedWord = new StringBuilder(hideRealWord(this.originalWord));
        this.missing = 0;
        this.wordLength = this.originalWord.length();

        while (wordLength > 0) {
            guess(replacedWord);

        }
        return missing;
    }

    private void guess(StringBuilder replacedWord) {

        System.out.print("(Guess) Enter a letter in word " + replacedWord.toString() + " ");
        char ch = this.input.nextLine().charAt(0);
        wrongGuessing = true;
        for (int j = 0; j < this.originalWord.length(); j++) {
            if (this.originalWord.charAt(j) == ch) {
                replacedWord.setCharAt(j, ch);
                wrongGuessing = false;
                wordLength--;
            }
            if (ch == replacedWord.charAt(j))
                System.out.println(ch + " Already in the word");
        }
        if (wrongGuessing) {
            System.out.println(ch + " is not in the word");
            missing++;
        }
    }

    private static String hideRealWord(String originalWord) {
        String hiddenWord = originalWord;
        for (int i = 0; i < originalWord.length(); i++) {
            char ASTERISK = '*';
            hiddenWord = hiddenWord.replace(hiddenWord.charAt(i), ASTERISK);
        }
        return hiddenWord;
    }

    private static String chooseWord() {
        return WORDS[(int) (Math.random() * WORDS.length)];
    }
}

More improvements

Still lots of room for improvement, but at least the startGuessing is shorter and more readable.

More things to improve:

Think of which variables you really need. For example, you don't really need word-length; you just need to check if the currently-guessed word is equal to the original word.
String is immutable, so you use a StringBuilder. While this works, it feels kind of wrong to replace characters in a StringBuilder. Let's use a char[] to store the current state of the word that is being guessed. For easier comparison and character comparison, we can put the original word in a char[] as well.
The main loop of starting a game is called recursively. This might cause a stack overflow if you play many games. Let's convert it to a while loop.

Now, keeping close to your solution, but with these improvements:

import java.util.Scanner;

public class GameHangman {

    private final static String[] WORDS = { "programming", "fish", "cairo", "arabs", "quraan", "sunnah", "editor",
            "photography", "artist", "software", "write", "read", "gaming", "lunch", "participate", "lunch", "dinner",
            "house", "books", "animals" };

    private Scanner input;
    private char[] originalWord;
    private char[] currentWord;
    private int misses;

    public GameHangman() {
        this.input = new Scanner(System.in);
    }

    public void start() {

        boolean keepPlaying = true;

        while (keepPlaying) {
            // Choose a random word
            this.originalWord = chooseWord();
            this.currentWord = hideRealWord(originalWord);
            this.misses = 0;
            while (!this.originalWord.equals(this.currentWord)) {
                guess();
            }

            // Display result
            System.out.println("The word is " + String.valueOf(this.originalWord) + (misses == 0 ? " you are correct"
                    : " you missed " + (misses == 1 ? " one time" : " " + misses + " times")));

            // Ask for another game
            keepPlaying = userWantsAnotherGame();

        }
    }

    private boolean userWantsAnotherGame() {
        System.out.print("Do you want to start another word? Enter y or no>");
        char gameCase = this.input.nextLine().charAt(0);
        return (gameCase == 'y');
    }

    private void guess() {

        System.out.print("(Guess) Enter a letter in word " + String.valueOf(currentWord) + " ");
        char ch = this.input.nextLine().charAt(0);

        //Check if already made this guess
        for (int j = 0; j < this.currentWord.length; j++) {
            if (this.currentWord[j] == ch) {
                System.out.println(ch + " Already in the word");
                misses++;
                return;
            }
        }

        boolean isCorrect = false;
        for (int j = 0; j < this.originalWord.length; j++) {
            if (this.originalWord[j] == ch) {
                currentWord[j]=  ch;
                isCorrect = true;
            }
        }
        if (!isCorrect) {
            System.out.println(ch + " is not in the word");
            misses++;
        }
    }

    private static char[] hideRealWord(char[] originalWord) {
        char[] hiddenWord = new char[originalWord.length];
        for (int i = 0; i < originalWord.length; i++) {
            hiddenWord[i] = '*';
        }
        return hiddenWord;
    }

    private static char[] chooseWord() {
        return WORDS[(int) (Math.random() * WORDS.length)].toCharArray();
    }
}


Should I differentiate object types by calling methods via variables?

Why wouldn't you create a method with a unique name accross all subclasses? In this way you don't have to generically build a function name, which can be a pain to maintain code / refactor

For instance :

var MainPrototype = {
    bind: function() {
        //generic stuff
        if (typeof(this.subBind) === "function") {
            this.subBind();
        }
    }
};

var SpecificType = $.extend(Object.create(MainPrototype, {
    type: 'specific',
    subBind: function() {
        // doSpecifics
    }
});
var OtherSpecificType = $.extend(Object.create(MainPrototype, {
    function: 'other',
    subBind: function() {
        // doSpecifics
    }
})


JavaScript implementation of Symbol Table (Dictionary)

Iterators When you have a data structure that needs to be iterated over sometime, consider providing an iterator to make things easier and more abstract for consumers. That is, you don't really want to write
for(let x = this.first; x != null; x = x.next) {

every time, nor would you want consumers of SequentialSearchST to have to do that if they wanted to examine the data manually. Instead, put an iterator on the class, and call that iterator by using for..of whenever needed.
class SequentialSearchST {
  *[Symbol.iterator]() {
    for (let node = this.first; node; node = node.next) {
      yield node;
    }
  }

Variable names x is not an informative variable name. Like I did above, maybe call a node node instead.
Semicolons Either use semicolons wherever appropriate, or don't use semicolons. Anything in-between looks inconsistent and can result in you eventually getting tripped up by the rules of Automatic Semicolon Insertion. If you're a beginner in JS, I'd highly recommend using semicolons. You can use a linter to enforce a particular style - to warn you of potential bugs before they turn into runtime errors that you need to spend time tracking down.
Declare your variables before using them. If you don't, you'll either implicitly create a global variable (an easy source of bugs), or an error will be thrown (in strict mode, and strict mode is recommended). Change
st = new SequentialSearchST();

to
const st = new SequentialSearchST();

Class usage A class is useful when you need to tie together data with methods that operate on that data. If you have only data, a class doesn't provide any benefit, and is simply noise, IMO. If I were you, I'd remove the Node class and change
this.first = new Node(key, val, this.first);

to
this.first = { key, val, next: this.first };

null Rather than assigning null as the initial value, and returning null when no matching node is found, you might consider if simply omitting a return statement entirely would do the trick. It's perfectly fine for a function call to return undefined; omitting null requires less code, less potential for inconsistencies, and one less thing to think about. (If this is for an exercise that requires null to be used, that's fine)
(If you do use null, make sure to verify it by using !== null, not != null; sloppy comparison requires more cognitive overhead than strict comparison)
This is how I'd refactor it:

class SequentialSearchST {
  *[Symbol.iterator]() {
    for (let node = this.first; node; node = node.next) {
      yield node;
    }
  }
  get(key) {
    for (const node of this) {
      if (node.key === key) {
        return node.val;
      }
    }
  }
  put(key, val) {
    for (const node of this) {
      if (node.key === key) {
        node.val = val;
        return;
      }
    }
    this.first = { key, val, next: this.first };
  }
}

const st = new SequentialSearchST();
st.put('s', 0)
st.put('e', 1)
st.put('a', 2)
st.put('r', 3)
st.put('c', 4)
st.put('h', 5)
st.put('e', 6)
st.put('x', 7)
st.put('a', 9)
st.put('m', 10)
st.put('p', 11)
st.put('l', 12)
st.put('e', 13)
console.dir(st.get('s'));

Another approach Maps hold key-value pairs. (Objects do too, but objects can only contain string and symbol keys, which is a limitation.) If this was a real-world problem I had to solve, I'd just use a Map:

const st = new Map();
st.set('s', 0)
st.set('e', 1)
st.set('a', 2)
st.set('r', 3)
st.set('c', 4)
st.set('h', 5)
st.set('e', 6)
st.set('x', 7)
st.set('a', 9)
st.set('m', 10)
st.set('p', 11)
st.set('l', 12)
st.set('e', 13)
console.dir(st.get('s'));


Print odd and even numbers using two threads in Java

In Print both variables count and isOdd should be marked as volatile then it would be thread safe, but not very efficient.

In Print2 you assume that no one else could wake up your thread which is incorrect as thread could be awaked by many things - in such light you need to have additional if check there to check if it really should print the variable - like this isOdd in the Print. Having this wait/notify with a volatile isOdd check would be a solution that is both tread safe and efficient by not spinning the loops unnecessarily, count should also be volatile as it is shared beetwen threads.

If you want to learn java concurrency well you can read a book "Java Concurrency in Practice" - it will give you a good understanding of this subject and will allow you to pass inteview questions like this one.

You can ask here or on SO for specific things about java concurrency, but I think that it would be hard and inefficient for you to learn it this way. Much better (faster, less painfull)  approach would be to read this book first and then ask questions if something will stay unclear for you. Good wishes!


Correct implementation of the factory pattern in php

No, this is not 100% true to the Factory Pattern - almost, but not 100%.

From Wikipedia:

  In class-based programming, the factory method pattern is a creational pattern (1) that uses factory methods to deal with the problem of creating objects without having to specify the exact class (2) of the object that will be created. This is done by creating objects by calling a factory method (3)—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor (4).

(emphasis, mine)

The key points here are:

This is a creational pattern (it creates objects) - Your code satisfies this
Objects get created without having to specify the exact class. The factory pattern deals with inheritance - You are specifying an exact class, and only have one class.
A method is used to create the object
Code using the "factory" doesn't call a constructor directly

Your code satisfies points 3 and 4, with one fatal problem: The createOrganization method also INSERTs a record into the database. If a factory method is written correctly, the only thing it does is create an object. A factory method or class should never do anything else.

The major reason why you haven't actually created a "factory" is because you do not utilize inheritance, where you create a concrete instance and return it as an abstract parent class or interface.

Instead, what you have created is a Data Access object.

Now, a data access object can utilize a factory. Let's pretend your Organisation class is abstract, and it has two concrete child classes:

Business
NonProfitOrganisation

Sample code:

class OrganisationDataAccess
{
    private function createOrganisation($data) : Organisation {
        if ($data['type'] == 'business') {
            return new Business($data['ID'], $data['Name'], $data['Created']);
        } else if ($data['type'] == 'non-profit') {
            return new NonProfitOrganisation($data['ID'], $data['Name'], $data['Created']);
        }

        throw new Exception('Invalid organisation type: ' + $data['type']);
    }

    public function getOrganisation($id) {
        $data = // get from database

        $org = $this->createOrganisation($data);

        // Populate $org with more data

        return $org;
    }
}

Now the createOrganisation class is a true factory method. It instantiates concrete child classes and returns them as the abstract parent.

Now, simply because you aren't 100% true to the definition doesn't mean your createOrganisation method isn't useful - it eliminates duplication of code when creating new objects. But I would suggest a name change for your class: OrganisationDataAccess or OrganisationRepository is a better fit.

If, in the future, you really do need sub classes you have the option of adding an OrganisationFactory class if need be.


I assume you have set up the links in the menu properly, i.e. they reference the elements they correspond to, something like

Home

Referenzen

So you can just search for the corresponding link with the attribute selector [docs] and get the enclosing li element:

$('#home, #referenzen, ...').bind('inview', function (event, visible) {
    var $menu_element = $('#menu a[href=#' + this.id + ']').closest('li'),
        // get the '#nav li' element at the same position
        $nav_element =  $('#nav li').eq($menu_element.index());

    $menu_element.stop().animate(
        {backgroundPosition: visible ? '(0 0)' : '(-200px 0)'},
        {duration: 500}
    ).find('a').css({color: visible ? 'white' : 'black'});
    $nav_element.stop().animate({opacity: visible ? 1 : 0.2}, 500);
});

If you don't have set up the links correctly (you really should), give the li items in the #menu (and maybe #nav) list a (for example) data-id attribute with a value corresponding to the element's ID and again, use the attribute selector to get them.


Everything looks good.

That said, array.indexOf wasn't supported in Internet Explorer until version 9.

If you need that support, the Mozilla Developer Network has a handy function you can include in your code to provide support for those browsers:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}


You are trying to recreate functionality that is already provided out of the box.

Reference Configure an ASP.NET Core App

From documentation it supports providers for INI, JSON, and XML.

  Each configuration value maps to a string key. There's built-in binding support to deserialize settings into a custom POCO object (a simple .NET class with properties).

Reference ASP.NET Core 1.0 Configuration Deep Dive

For XML, you need to add this NuGet package: Microsoft.Extensions.Configuration.Xml and the format that provider uses would look like this for your settings

Note: It matches closely to version 1 in your example

<configuration>
    <identityOptions>
        <password>
            <RequireDigit>true</RequireDigit>
            <RequiredLength>8</RequiredLength>
            <RequireNonAlphanumeric>false</RequireNonAlphanumeric>
            <RequireUppercase>true</RequireUppercase>
            <RequireLowercase>false</RequireLowercase>
            <RequiredUniqueChars>6</RequiredUniqueChars>
        </password>
    </identity>
</configuration>

And the following would be added as part of configuration

//...
.AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true)
//...

If using JSON then

{
  "IdentityOptions": {
    "Password": {
      "RequireDigit": true
      "RequiredLength": 8
      "RequireNonAlphanumeric": false
      "RequireUppercase": true
      "RequireLowercase": false
      "RequiredUniqueChars": 6
    }
  }
}

And the following would be added as part of configuration

//...
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
//...

You appear to already be setting up IOptions, which is good.

//...
// Register the ConfigurationBuilder instance which IdentityOptions binds against.
services.Configure<IdentityOptions>(Configuration);

//...

This will allow constructor dependency injection with IOptions<TOptions> to access settings

private readonly IdentityOptions options;

public MyClass(IOptions<IdentityOptions> identity) {
    options = identity.Value;
}