PHP program which extracts attribute lists from custom tag

Here are some things I noticed:

The function splitByDelimiter() is no more than a wrapper around explode(). Why not use explode() directly?
The function stripQuotes($str) can be a lot shorter: trim($str," '\"");. Note: You should never use ' or " inside attributes, use their HTML equivalents.
Inside parseAnswerTag() you use a foreach loop. Inside it you assign values back into $arr, but under the wrong keys because array_slice() will have generated new numeric keys.
I don't understand why you select for scale and point?

I'm sorry but I cannot help you with other details, because I'm unsure about the origin of the HTML, and what you exactly are trying to accomplish. I did make a shorter version of your function:

function parseAnswerTag($tag)
{
    $inside = trim($tag,'<> ');
    $input  = explode(' ',$inside);
    array_shift($input);
    foreach ($input as $attr)
    {
        $parts = explode('=',$attr);
        $name  = trim($parts[0]);
        $value = trim($parts[1]," '\"");
        $output[$name] = $value;
    }
    return $output;
}

echo '<pre>';
print_r(parseAnswerTag('<answer scale="10" points="7">'));
echo '</pre>';

So trimming can be very useful.

Keep in mind: Algorithms like these are almost always slightly flawed. A simple thing like a double space could trip it up. It's very hard to get it completely right. Especially if you make it complicated or use regular expressions.

I also have to point out that PHP has a build in DOM to deal with HTML code. You can load HTML into it, and manipulate it there. See:

http://php.net/manual/en/class.domdocument.php

In more complex cases this is the preferred way to deal with HTML.


I think the suggestion in the link you mention is to not bother with making your object files "intermediate".  I tend to agree.

If make deletes the object files after the link step then it has to re-build them all at the next invocation of make.  Without this, the next time you make, it can look at the dependencies of the object files (as specified by the makefile, the part after the :) and only rebuild them if the stated dependencies have a later timestamp.

You might also want a make clean target to remove the objects via rm, so that you can delete them when you really want to.  But the typical workflow for using make is to keep your object files around for extended periods and type make when you want to build what you've changed.


Minor things

The java naming standard for classes is CamelCase (DiceSimulation instead of diceSimulation)

A constant of THOUSAND is not helpful, especially when the value is 10,000. A more meaningful name, say ROLLCOUNT, would be better.

Similarly, diceValue is not clear.  It contains the counts for each double occurence, so perhaps, doubleCounts - note the plural for an array indicating that it contains multiple values.

We have many dice but each one is a die -> die1 and die2.

Comments that just restate the obvious code can be omitted
e.g.

/**
* Declare variables and store dice max roll in Thousand
*/

// create new instance of random

// If statement to check if values are the same or not

Coding

We are working with 6 sided dice so we only need 6 entries in the array to store the double counts not 7 - it is more standard to adjust the index when outputting (e.g., add 1) than to make the arrays larger and use then as 1 based arrays..

We can easily store the number of sides in a variable (constant) to make consistency easier - a named value instead of a literal 6 in multiple places - and even allow us to use this for dice with other numbers of sides if we desired.

We can put the 'roll' functionality into a function so that to reduce duplication and allow us to change the implementation if desired (say for testing)

We check if dice1 == dice2 but then in the loop check if both dice1 == i && dice2 == i - if dice1 == dice2 then the second check can never fail.

If we index into the array, we don't need the loop

if (die1==die2){
    doubleCounts[die1-1]++;
}

If have sized the array to the number of elements then we should loop from 0 not 1 (and single character variable names, even for loops, are generally frowned upon)

System.out.format is a nicer way - simpler to use than the concatenation - for writing the output line

import java.util.*;

public class DiceSimulation {

    private static Random rollDice = new Random();

    public static void main(String[] args) {

        final int ROLLCOUNT = 10000;
        final int SIDES = 6;
        int counter, die1, die2;

        //an array with elements to keep count
        int [] doubleCounts = new int [SIDES];

        // display welcome message. no other purpose but trial
        welcome ();

        /**
         * Set counter to start from 1 and go till desired constant number
         * Rolling two separate dices and storing values in dice1 & dice 2       respectively
         */
        for (counter=1; counter<=ROLLCOUNT;counter++){

            die1=roll(SIDES);
            die2=roll(SIDES);

            if (die1==die2){
                doubleCounts[die1-1]++;
            }

        }

        // Display results totals of paired rolls
        for (int idx=0; idx<doubleCounts.length; idx++){
            System.out.format(" You rolled set of %d %d times\n",(idx+1), doubleCounts[idx]);
        }
    }
    private static int roll(int sides){
        return rollDice.nextInt(sides) +  1;
    }
    public static void welcome () {
        System.out.println("welcome to dice world!");
    }
}


Extended Euclidean algorithm and modular multiplicative inverse element

This looks like a bug in the input validation:

if (args.num_1 == 0) and (args.num_2 == 0):
    print("Please enter two positive integers.")
else:
    print(xggt(args.num_1, args.num_2))
    print(modinv(args.num_1, args.num_2))

The message "Please enter two positive integers." contradicts with the condition:
if both numbers are 0. I think you meant more like this:

if args.num_1 > 0 and args.num_2 > 0:
    print(xggt(args.num_1, args.num_2))
    print(modinv(args.num_1, args.num_2))
else:
    print("Please enter two positive integers.")

I also removed redundant parentheses.

You had redundant parentheses in other places too:

    return(num_2, 0, 1)
    # ...
    return(gcd, lin_fact_2, lin_fact_1)

These are all unnecessary, so I recommend to remove them.

You can simplify x = x - ... with x -= ..., for example here:

# instead of this:
# lin_fact_1 = lin_fact_1 - num_1 // num_2 * lin_fact_2
lin_fact_1 -= num_1 // num_2 * lin_fact_2

Other than these minor issues, I think this is good and clean code! The names seem quite fine to me.


Graph adjacency list implementation in C++

Overall, it seems good. One problem that I find here though is the lack of vertical spacing at some places. This is very subjective, I agree, but adding a blank line to separate unrelated things can improved readability. I once read somewhere that code should be split into "paragraphs". That's an interesting thought to keep in mind. Giving an example, this is one possible way I would space the method graph::addNode():

void graph::addNode(const int key, const std::vector<std::pair<int,int> > &input) {

    nodes[key].setKey(key);

    for (std::vector<std::pair<int,int> >::const_iterator it = input.begin(); it != input.end(); ++it) {

        std::pair<int,int> entry = *it;
        nodes[key].addNeighbour(entry.first, entry.second);

        if (!directed) {
            nodes[entry.first].addNeighbour(key, entry.second);
        }
    }
}

Another minor point, but you don't need to add inline to a method when it is already defined directly inside the class body. In such case, adding the keyword is just unnecessary verbosity.

Huge lines like in those for loops:

for (std::list<std::pair<int,int> >::const_iterator it = neighbours.begin(); it != neighbours.end(); ++it)

Can be greatly simplified using auto or range-based for, if you have access to C++11. Failing that, I'd suggest that you typedef your list type to avoid having to replicate std::list<std::pair<int,int> > so many times (remember the DRY principle).

typedef std::list<std::pair<int, int> > ListType;

And as for the search algorithms, you didn't provide any implementation for them, but I don't see a reason why they shouldn't be members of graph. Personally, I don't see much purpose for a node to exist on its own without a graph, so I would make node a private inner class of graph and make all of its members public. Node seems like an implementation detail to me. Your interface apparently deals in terms of ints only.


C++ how to use std::any_cast and avoid else if statements

First, this call to __cxa_demangle returns a buffer allocated with malloc and which must be freed. This isn't freed, so this code has a memory leak.

Second, as I understand it, __cxa_demangle does not exist in MSVC, so this is not portable.

Third, the .find("string") catches more than std::string. It would match std::wstring, std::stringstream, void (*)(std::string).

Fourth, this code relies essentially on knowing the potential types that are in that std::any. That is knowledge at a distance, and if you allow more types at the place of construction, you need more types here.

Fifth, if the type isn't one of those types, the error is silent and the output is the type contained, not the value. That could be harmless, but it could be a real problem. If you allowed type Foo in the any, and neglected to update this location, you wouldn't be able to tell if the output Foo was that type name or the value of a string stored in the any.

The suggestion of the other answer is to constrain the types stored using the type storing them. Instead of any use std::variant<std::string, long long, unsigned long long, double>. I added the string and unsigned options relative to the other answer. Then just visit:

std::visit([&](const auto& value) { out << value; }, n.value);

This is a very strong option.

A second option would be to erase not almost every aspect of the type (as with std::any) but instead leave the interface you need, e.g. erase everything but the stream operator if that's all you need:

    printable p = 2.3;
    std::cout << p << "\n";
    p = "foo";
    std::cout << p << "\n";

Example: https://godbolt.org/z/NtJqWk

(edit: added a missing virtual destructor to impl_base)


Adding/removing map values: unsymmetric implementation

I agree that the lack of symmetry in your implementation of place-reservation using merge-with and union is bothersome. Fortunately, there's a function to fix that!

fnil

The fnil function allows you to create a function that acts like an existing function, but replaces the first argument with something else in the case that it's given nil:

(conj nil :x)
;=> (:x)

((fnil conj #{}) nil :x)
;=> #{:x}

So you can write place-reservation like this:

(defn place-reservation [new-res]
  (swap! known-reservations
         #(update % (:resource new-res) (fnil conj #{}) new-res)))

swap!

As you know, swap! will pass the current state of the atom as the first argument to the function you provide, but you can give values for the other arguments as well. So instead of passing a function that calls update with the current state and some other arguments, you can just pass update and those other arguments directly, and swap! will do the rest:

(defn place-reservation [new-res]
  (swap! known-reservations update (:resource new-res) (fnil conj #{}) new-res))

(defn cancel-reservation [canceled-res]
  (swap! known-reservations update (:resource canceled-res) disj canceled-res))

Global state

Currently, you store known-reservations in a global var. This is a Bad Thing. Even if you don't plan to have multiple atoms of reservation lists in your actual program, it makes your code more painful to test:

(require '[clojure.test :as t])

(t/deftest reservation-test
  (reset! known-reservations {})
  (place-reservation my-res)
  (place-reservation your-res)
  (place-reservation my-res)
  (t/is (= {car #{my-res your-res}} @known-reservations))
  (reset! known-reservations {}))

I suppose you could make this a bit more concise using fixtures, but either way, if you eventually end up with enough tests that you'd like to run them in parallel, you'll be out of luck.

The easiest way to fix this problem is to just take the state as a parameter instead:

(defn place-reservation [known-reservations new-res]
  (swap! known-reservations update (:resource new-res) (fnil conj #{}) new-res))

(defn cancel-reservation [known-reservations canceled-res]
  (swap! known-reservations update (:resource canceled-res) disj canceled-res))

This still isn't great, but it's an improvement:

(t/deftest reservation-test
  (t/is (= {car #{my-res your-res}}
           @(doto (atom {})
              (place-reservation my-res)
              (place-reservation your-res)
              (place-reservation my-res)))))

Pure functions

In place-reservation and cancel-reservation, you complect two things:

The logic of placing or canceling reservations
The fact that you're storing reservations in an atom

You'd be better off writing place-reservation and cancel-reservation as pure functions that take a reservation collection and return a new reservation collection:

(defn place-reservation [known-reservations new-res]
  (update known-reservations (:resource new-res) (fnil conj #{}) new-res))

(defn cancel-reservation [known-reservations canceled-res]
  (update known-reservations (:resource canceled-res) disj canceled-res))

Pure functions are the easiest things in the world to test:

(t/deftest reservation-test
  (t/is (= {car #{my-res your-res}}
           (reduce place-reservation {} [my-res your-res my-res]))))


Simple way to decrement number within a repeating range

Some thoughts:

(i + x) % x == i //For i >= 0 && i < x

Then

(i + x - 1) % x

Gives us the range from 0 to x-1.
We want the range from 1 to x so we change this to:

(i + x - 2) % x + 1;

But I don't think it's particularly readable, so your ternary code might end up being better.


Conditional statements relating to hospital management

Code like the following ...

   if (phone.equals("T"))

        phoneCost = 15 * (double)days;
        //System.out.println(phoneCost);

    else

        phoneCost = X_COST;

... is copy-and-pasted into more than one type of room.

Instead of having a structure like ...

if room type
    calculate nurse cost
    calculate phone cost
    calculate TV cost
else if other room type
    calculate nurse cost again
    calculate phone cost again
    calculate TV cost again

... I suspect it would be better to have a structure like ...

// Calculate TV cost.
TVCost = (room.equals("I") || !TV.equals("V")) ? X_COST : 40 * (double)days;
// Calculate Phone cost
... etc ...
// Calculate nurse cost
... etc ...

Also I don't understand this ...

else if (room.equals("N"))

    nurseCost = 250 * (double)days;
    //System.out.println(nurseCost);

... because that's in a place where you already decided that room.equals("I").


Please never define true to have the value 0, since that value is reserved for the name false. Just include <stdbool.h> instead of defining the type yourself.

Do not call any function from <ctype.h> with a char argument since that can easily lead to undefined behavior.

In the call to fgets fails, the input array may be uninitialized, which would also lead to undefined behavior.

Accessing alphabet[26] leads to undefined behavior since there valid array indices go from 0..25.

The rest of your code looks well-organized and is easy to read. Congratulations on that.

For your primary question of solving the pangram with fewer than 4 for loops, you can find at least 10 different solutions by searching the web since the pangram is a classical programming task.

Forget the above paragraph. I just searched for "pangram c" and found only crappy solutions, and telling these apart from the good ones is impossible for a beginner.

One idea is to remember for each letter whether it was found it not:

bool found[26] = { false };   // This initializes all 26 values at once, but only works for "zero" values.
int remaining = 26;

for (size_t i = 0; input[i] != '\0'; i++) {
    char ch = input[i];

    if ('a' <= ch && ch <= 'z') {
        if (!found[ch - 'a']) {
            found[ch - 'a'] = true;
            remaining--;
        }
    }
}

If, at the end of the loop, there is no remaining character, you have found them all, and the input is a pangram. All with a single loop.

Note: the code I suggested only works when all 26 letters are defined in a contiguous block of the character set. On all modern systems this is the case. When working with IBM machines and EBCDIC encoding, this will not work. On Rosetta Code, the code is perfect and also handles these exotic cases. It uses the same idea and takes care of everything. It looked complicated at first sight, therefore I preferred to explain the basic idea first. But now you should be able to understand the code over there.


Using python and beautifulsoup to iterate through a list of websites to find a particular string

First of all, since you are applying a regular expression pattern to the complete source of the page, you don't need an HTML parser like BeautifulSoup - directly search inside the page.content.

And, if you need to go the HTML parsing route and speed matters, choose either lxml, or lxml parser with BeautifulSoup.

You may also look into reusing the same requests.Session() instance - it may have a positive impact on performance.

Overall though, your approach is blocking/synchronous - your code processes URLs one by one - it would not process the next URL until it is done with the current one. Look into tools like Scrapy to approach the problem in the asynchronous/non-blocking fashion.


jQuery toggle buttons to show matching content in sliding panel

In the click event we will see right away from reading the if statement that you are performing a check to see if the slidingPanel is open by looking for a class of open on the element, so get rid of that first comment, you should also got rid of the //if slider is close, open slider  because that is also obvious from reading the code.  I am unsure of The final comment so I won't make a judgment on it.

Remove the return statement and make it into an if/else statement, because that is essentially what you are doing and it will read nicer.

This is what it turns into

var slidingPanel = $('#sliding-panel');
$(body).on('click', '[data-toggle="slidingPanel"]', function() {
    if(slidingPanel.hasClass('open')){
        slidingPanel.hide("slide", { direction: "right" }, 500).removeClass('open');
        $('.buttonContent').hide();
    } else {
        slidingPanel.show("slide", { direction: "right" }, 500).addClass('open');
        //show content in slider based on button pressed
        $('#' + $(this).attr('id') + 'content').show();
    }
});


I would think on making two changes:

Make one or both Dispose*Resources methods virtual instead of abstract. Though it highly depends on how often do you need to handle unmanaged resources. I can't remember last time I was handling them and I would hate overriding this method in each class just to make it empty.
I would add some logging either to your finalizer method or to Dispose(bool disposing) method in order to catch situations when disposable object wasn't disposed correctly by calling Dispose() method. Most developers are looking for such information and you have a good place to inject it.


Code reuse while keeping meaning clear and avoiding unforseen consequences

These dependencies can't be fixed by naming. They are a symptom of some fundamental design problems. If you're having trouble finding methods, that's
a symptom of an overly coupled design.

You have a class names that really sound like methods in a completely different class.

Without knowing more about the application it's hard to suggest where to go. If you're working in Ruby I highly recommend this book for thinking about class design and re-factoring.

http://www.poodr.com/

You might also look into various code metric tools to help you identify some design problems. There are lot's of these available for Ruby.

https://www.ruby-toolbox.com/categories/code_metrics

These can seem quite pointless and arbitrary at first, but using SOLID object design principals has been shown to be effective in the long run.

http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)


Simple code that finds number of factors crashes my computer. Is there a workaround for a large number?

First, you can easily find the bottleneck in your code by running it with the profiler (ran with number_of_divisors = 100):

~> python -m cProfile t.py
Answer found:  73920
         1926 function calls in 0.522 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.522    0.522 t.py:1(<module>)
      385    0.006    0.000    0.008    0.000 t.py:1(nth_triangle_number)
        1    0.000    0.000    0.522    0.522 t.py:13(get_triangle_number)
      384    0.472    0.001    0.514    0.001 t.py:6(get_number_of_factors)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      769    0.043    0.000    0.043    0.000 {range}
      385    0.001    0.000    0.001    0.000 {sum}

You can immediately see that:

Indeed, get_number_of_factors() slows everything down;
You can slightly optimize things by replacing range with xrange (which does not create a list).

In your case get_number_of_factors() is a good example of a function that requires algorithmic optimization. Currently it has O(N) complexity. As you correctly guessed, iterating only till sqrt(num) will make it faster:

def get_number_of_factors(num):

    limit = math.sqrt(num)
    int_sqrt = int(round(limit))

    if int_sqrt ** 2 == num:
        int_limit = int_sqrt
        quantity = 1
    else:
        int_limit = int(limit) + 1
        quantity = 0

    for i in xrange(1, int_limit):
        if not num % i:
            quantity += 2

    return quantity

Some highlights:

math.sqrt returns a float, so if you want to be extra-safe, you need to convert it to integer properly (if sqrt(4) gives you 3.9999999, just int() will produce 3).
When you are iterating to the square root, each factor you found stands for two factors: i and num / i.
But you do not want to include the root itself, because if num is a perfect root, you only need to count sqrt(num) once.

This makes your algorithm run in O(sqrt(N)).
Edit: if you want even more performance, you can try to implement number field sieve.

To add more performance, you can replace the direct sum in nth_triangle_number() with a known formula for arithmetic progression.
The result is:

import math

def nth_triangle_number(nth):
    """ Sequence of triangle numbers is generated by adding the natural numbers.
        So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
        Using the fact that 1 + ... + n = n * (n + 1) / 2
        """
    return nth * (nth + 1) / 2

def get_number_of_factors(num):

    limit = math.sqrt(num)
    int_sqrt = int(round(limit))

    if int_sqrt ** 2 == num:
        int_limit = int_sqrt
        quantity = 1
    else:
        int_limit = int(limit) + 1
        quantity = 0

    for i in xrange(1, int_limit):
        if not num % i:
            quantity += 2

    return quantity

def get_triangle_number(divisors):
    """ Find the triangle number with the given amount of divisors """
    i = 1
    while get_number_of_factors(nth_triangle_number(i)) <= divisors:
        i += 1

    return nth_triangle_number(i)

if __name__ == '__main__':
    number_of_divisors = 100
    print "Answer found: ", get_triangle_number(number_of_divisors)

And it runs much faster now. For 100:

~> python -m cProfile t.py
Answer found:  73920
         1540 function calls in 0.007 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.007    0.007 t.py:1(<module>)
      384    0.006    0.000    0.006    0.000 t.py:10(get_number_of_factors)
        1    0.000    0.000    0.006    0.006 t.py:28(get_triangle_number)
      385    0.000    0.000    0.000    0.000 t.py:3(nth_triangle_number)
      384    0.000    0.000    0.000    0.000 {math.sqrt}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      384    0.000    0.000    0.000    0.000 {round}

And for 500:

~> python -m cProfile t.py
Answer found:  76576500
         49504 function calls in 5.364 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    5.364    5.364 t.py:1(<module>)
    12375    5.342    0.000    5.349    0.000 t.py:10(get_number_of_factors)
        1    0.010    0.010    5.363    5.363 t.py:28(get_triangle_number)
    12376    0.005    0.000    0.005    0.000 t.py:3(nth_triangle_number)
    12375    0.003    0.000    0.003    0.000 {math.sqrt}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    12375    0.004    0.000    0.004    0.000 {round}


You could do something like this

paginateTo: (id) ->
  deferred   = new $.Deferred
  modelCheck = null

  modelExists = =>
    modelCheck or= @checkModelExists id

  fetchUntilFound = =>
    return deferred.resolve model if model = @get id
    modelExists().fail deferred.reject
    modelExists().done =>
      @fetchNextPage().then fetchUntilFound, deferred.reject

  fetchUntilFound()
  deferred.promise()


Two Knockout computed dependent on each other

I will review and contrast the SO answer that I liked best:

function viewModel() {
    var self = this;

    self.NetPrice = ko.observable(100);

    self.TaxRate = 0.2;

    self.TaxAmt = ko.computed(function() {
        return parseFloat(self.NetPrice()) * self.TaxRate;
    });

    self.Total = ko.computed({
        read: function() {
               return parseFloat(self.NetPrice()) + self.TaxAmt();
        },
        write: function(val){
                var total = parseFloat(val);
                var taxAmt = total - total / (1 + self.TaxRate);
                self.NetPrice(total - taxAmt);
        }
    });
}

It is more standard to create a constructor, then to create an object with object notation and then add functions.
Not to big a fan of using self everywhere instead of this in the SO answer
Do not use console.log in production code
Do not use calc as part of the variable name
Do not use a useNetPrice type of indicator, knockout can figure out the computed values on its own and knows when to recalculate what
write functions do not have to return anything


Finding the number of capital letters in a word grouped by letter

The answer is that I wouldn't use either of those approaches. Counting the number of occurrences on a string isn't complex enough that requires a class of it's own. An extension method however would be a reasonable way to do it, as well as using the LINQ to get the desired result:

public static IDictionary<char, int> GetOcurrences(this string value){
    return value.GroupBy(c => c)
        .ToDictionary(c => c.Key, c => c.Count());
}

Or to count only letters

public static IDictionary<char, int> GetOcurrences(this string value){
    return value
        .Where(char.IsLetter)
        .GroupBy(c => c)
        .ToDictionary(c => c.Key, c => c.Count());
}

Or to count only capital letters

public static IDictionary<char, int> GetOcurrences(this string value){
    return value
        .Where(c => c >= 'A' && c <= 'Z')
        .GroupBy(c => c)
        .ToDictionary(c => c.Key, c => c.Count());
}

Or to count only letters provided by a parameter

public static IDictionary<char, int> GetOcurrences(this string value, string filter){
    return value
        .Where(c => filter.Contains(c))
        .GroupBy(c => c)
        .ToDictionary(c => c.Key, c => c.Count());
}


I put your Swing components on the Event Dispatch thread (EDT) in the main method.
I rearranged your Swing component definitions in the go method to group like things together.  I made sure that the JFrame setVisible method was the last method called in the go method.  I added a call to the JFrame setDefaultCloseOperation so that when you closed the GUI, your application would exit.
Your password field returns a character array.  I had to look up how to do it, but you have to convert the character array to a String to write it to a file.
I added the BufferedWriter to your actionPerformed method.

.

package passwordProgram;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class CreateAccount implements ActionListener {

    JFrame          frame;
    JPanel          panel;
    JTextField      username;
    JPasswordField  password;
    JPasswordField  confirmPassword;
    JLabel          warningLabel;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager
                            .getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                CreateAccount window = new CreateAccount();
                window.go();
            }
        });
    }

    public void go() {
        panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        panel.setBackground(Color.ORANGE);

        frame = new JFrame("Create a new account");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(BorderLayout.CENTER, panel);

        JLabel userLabel = new JLabel("Username:");
        JLabel passwordLabel = new JLabel("Password:");
        JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
        username = new JTextField(15);
        password = new JPasswordField(15);
        confirmPassword = new JPasswordField(15);

        GridBagConstraints right = new GridBagConstraints();
        right.anchor = GridBagConstraints.WEST;
        GridBagConstraints left = new GridBagConstraints();
        left.anchor = GridBagConstraints.EAST;

        right.weightx = (int) 2;
        right.fill = GridBagConstraints.REMAINDER;
        right.gridwidth = GridBagConstraints.REMAINDER;
        // actual GUI

        panel.add(userLabel, left);
        panel.add(username, right);
        panel.add(passwordLabel, left);
        panel.add(password, right);
        panel.add(confirmPasswordLabel, left);
        panel.add(confirmPassword, right);

        JButton createAccount = new JButton("Create this account");
        frame.getContentPane().add(BorderLayout.SOUTH, createAccount);
        createAccount.addActionListener(this);

        warningLabel = new JLabel();
        frame.getContentPane().add(BorderLayout.NORTH, warningLabel);

        frame.setSize(300, 250);
        frame.setVisible(true);
    }

    // This is where the problem is!
    public void actionPerformed(ActionEvent event) {
        if (!(Arrays.equals(password.getPassword(),
                confirmPassword.getPassword()))) {
            warningLabel
                    .setText("Your passwords do not match! Please try again.");
        } else if (password.getPassword().length < 1) {
            warningLabel
                    .setText("That password is not long enough! Please try again!");
        } else {
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(
                        "nuserInfo.txt"));
                writer.write(username.getText() + "/"
                        + new String(password.getPassword()));
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


Finding strings inside of other strings in order in C

Allocating tmp_sub only needs to be the size of sub: if sub is found in base then it will be exactly the same length.

Using this fact, the entire algorithm can be simplified to remove the tmp_sub and calls to strcomp entirely.

In your nested for loops, remove the i loop and continue incrementing j each iteration. Increment i iff sub[i] == base[j]. Then, check i. If i == sub_len return true. If the loop exits (where j is equal to base_len) then return false.

int find_str_in_str(const char* const base, const char* const sub)
{
    int base_len = strlen(base);
    int sub_len  = strlen(sub);
    int i = 0;
    int j = 0;

    for ( ; j < base_len; j++) {
        if (sub[i] == base[j]) i++;
        if (i == sub_len) return 1; // we found all sub chars in order
    }
    return 0; // we reached the end of base without finding all chars
}

Insufficient karma to comment @William Morris
I had returned to write nearly what you have provided as a higher performance / more obscure solution as well. If you exchange the body of your for loop for the obscure trick I had mentioned above (but have now move below) you can avoid one more logic branch in your code.

static int find_str_in_str(const char *base, const char *sub)
{
    // Check arguments for empty string
    for (; *base != '\0' && *sub != '\0'; ++base) {
        sub += (int)(*base == *sub);
    }
    return *sub == '\0';
}

Feel free to edit my answer and remove this lower block if you choose to update your answer.


A multi-threaded Producer Consumer with C++11

Prefer Reference over Pointer

Since the producer and consumer must have a buffer you should pass it by reference (rather than pointer). This also makes sure there is no confusion over ownership of the buffer (the owner of a pointer is responsible for deleting it). By using a RAW pointer you can not tell the owner but by using a reference you are explicitly stating that you are not passing ownership.

class Producer
{
    Buffer&  buffer_;
public:
    Producer(Buffer& buffer)
        : buffer_(buffer)
    {}

Prefer to avoid this->

When you use this-> it means you have scoping issues with your variables (which is a code smell for bad design). Use accurate variable names so that there is no confusion on where the variables belongs.

Member variables over globals.

Looks like your encapsulation of the mu and cond is wrong.

std::mutex mu,cout_mu;

Because they are global, you use a single mutex/condition for all buffer objects. This looks like a design flaw. It seems like the mutex/condition belongs to the class so that you are just locking the buffer you are manipulating (so you can use multiple buffers in the same application).

Sleeping inside lock

        cout_mu.lock();
        std::cout << "Produced: " << num << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        cout_mu.unlock();

@Morwenn already suggested using scoped lock to make sure the mutex were correctly locked and unlocked. But I would also move the sleep outside the lock. This causes the current thread to stall but the other thread can not continue as the lock is still held while it is sleeping.

        {
            std::unique_lock<std::mutex> locker(cout_mu);
            std::cout << "Produced: " << num << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(50));

Prefer '\n' over std::endl

std::cout << "Produced: " << num << std::endl;

The difference between the two is a flush. Usually you do not want to manually flush (the stream have good flushing techniques built in). So it is usually best to let the streams flush themselves when appropriate.

In answer to comments:

class Buffer
{
public:
    void add(int num) {
        while (true) {
            std::unique_lock<std::mutex> locker(mu);
            cond.wait(locker, [this](){return buffer_.size() < size_;});
            buffer_.push_back(num);
            locker.unlock();
            cond.notify_all();
            return;
        }
    }
    int remove() {
        while (true)
        {
            std::unique_lock<std::mutex> locker(mu);
            cond.wait(locker, [this](){return buffer_.size() > 0;});
            int back = buffer_.back();
            buffer_.pop_back();
            locker.unlock();
            cond.notify_all();
            return back;
        }
    }
    Buffer() {}
private:
   // Add them as member variables here
    std::mutex mu;
    std::condition_variable cond;

   // Your normal variables here
    deque<int> buffer_;
    const unsigned int size_ = 10;
};


StringWriter and XmlWriter are both IDisposable hence their usage should be wrapped in a using statement
The prefixing o of your local variables smells a bit of hungarian notation which generally does not convey a lot of useful information.
The encoding has already been mentioned in the comments. In .NET strings are UTF-16 so you use should that instead.
Generally try to declare your variables as close to the point of use as possible. That way it's more obvious from which point on they are being used.

Refactored code:

public static string ObjectToXml(object obj)
{
    var settings = new XmlWriterSettings
    {
        Indent = true,
        OmitXmlDeclaration = false,
        Encoding = Encoding.GetEncoding("UTF-16")
    };

    var namespaces = new XmlSerializerNamespaces();
    namespaces.Add(string.Empty,string.Empty);

    var serializer = new XmlSerializer(obj.GetType());

    using (var stringWriter = new StringWriter())
    {
        using (var xmlWriter = XmlWriter.Create(stringWriter, settings)
        {
            serializer.Serialize(xmlWriter, obj, namespaces);
        }
        return stringWriter.ToString();
    }
}

Update: As pointed out in the comments the suggested refactored code violates point 4 above. This is because I usually try to limit the scope of using blocks so it's easier to see what's going on there.

As pointed out by Jesse you could make some of the local variables class static as they are always the same. If you put generics in the mix then you could also make the serializer class static and the total refactored code could look like this:

public static class SerializerHelper<T>
{
    private static XmlSerializer _Serializer;
    private static XmlWriterSettings _XmlSettings;

    private static XmlSerializerNamespaces _Namespaces;

    static SerializerHelper()
    {
        _Namespaces = new XmlSerializerNamespaces();
        _Namespaces.Add(string.Empty,string.Empty);

        _XmlSettings = new XmlWriterSettings
            {
                Indent = true,
                OmitXmlDeclaration = false,
                Encoding = Encoding.GetEncoding("ISO-8859-1")
            };

        _Serializer = new XmlSerializer(typeof(T));
    }

    public static string ObjectToXml(T obj)
    {
        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, _XmlSettings))
            {
                _Serializer.Serialize(xmlWriter, obj, _Namespaces);
            }
            return stringWriter.ToString();
        }
    }
}


Calculate simple arithmetic string in Scala

You might want to spend some time becoming more familiar with the Standard Library. You're doing a few things that are already provided for.

implicit class Converter(char: Char) {
  def toNum: Int = char - '0'
}

To convert a digit character into the value it represents: char.asDigit. If you have one or more digit characters in a string: digits.toInt

Your solution also fails for expressions like "2*2+3". It looks like the evaluateExpression() code doesn't anticipate that, in the recursive call evaluateExpression(pendingExpression), the value of pendingExpression might be a single digit.

But mostly, with the input under so many tight restrictions, you should consider what shortcuts might be available to you.

def evaluateExpression(s :String) :Int =
  s.split("\\+")
   .map(_.split("\\*")
         .map(_.toInt)
         .product)
   .sum


Attempting to utilize OOP with a user-management class

No, this design is not object-oriented, nor would I recommend you follow your friend's advice. I also would not recommend your original design either. Neither one adheres very well to object-oriented design principles, namely the SOLID principles.

In your friend's rendition, he is proposing a structure that is very active record-like, where a domain object also knows how to persist and retrieve itself. While this pattern is used in many places (Ruby on Rails, CakePHP, etc), it can make testing very difficult, it can cause dependency problems, and it is not single responsibility.

It is difficult to test (especially your rendition) because the object is dependent on the database. Since you instantiate the database object in your method, there is no easy way to mock it or stub it out either.

Nor is there an easy way to substitute different implementations. Your class is tied to the concrete database implementation. It has a dependency that cannot be isolated.

The class has numerous responsibilities that are completely unrelated to representing a user. For example, in the getUser method, we are responsible for:

Getting a database connection object,
Building a query,
Running that query,
Fetching the results,
Translating the results into object properties.

This code has a lot of fingers in a lot of pies, and depends on the specific functionality of a lot of other parts.

Your proposal of simply having a data object, and a separate object to manage persistence is more on track. It falls down a bit in the details, though. To be truly object-oriented, you want to encapsulate your data. Having all public members does not encapsulate anything. The most basic way to make this more object-oriented is to have getters and setters (some may debate this, and there are other routes that can be taken, but this is a good start). This way, if the internal structure of your class changes, you can hide it by adjusting the implementations of the encapsulating methods while preserving the public API.

The pattern you are looking for is the Repository pattern. It allows you to isolate and encapsulate mapping between a persistence layer and domain objects, and allows the domain objects to focus on the single responsibility of representing the business concept they represent.

I would also recommend you learn about dependency injection to help you to understand why instantiating objects inline can cause problems, and what one potential solution is.


Configuring a currency converter to get exchange rate feeds for for multiple currencies

Well the first thing I notice is that your get_currency_rate() function requires a $currencySource to be added as a parameter. Which makes the first if statement a little redundant. The other thing is that get_currency_rate() is setting the variable $rate from get_rate(), but get_rate() doen't return anything.

I think you should ommit the get_currency_rate() function and change get_rate() to handle the XML feed request and return the information you want rather than using two separate functions.

It would look like this.

function get_rate($feed_url, $xmlTagPosition) {
  $xml = new SimpleXmlElement($feed_url);
  $xml_item = $xml->channel->item[$xmlTagPosition];

  // make sure the $xmlTagPosition was valid
  if( empty($xml_item) )
    return false;

  $currency['rate'] = $xml_item->description;
  preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
  $rate = $matches[0];

  $title['rate'] = $xml_item->title;
  $title = explode('/', $title['rate']);
  $title = $title[0];

  return $rate . ' ' . $title;
}

And now your cityConfig.php file can work more like this.

$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/USD/rss.xml';

$cities = array(
  'London' => array(
    'title' => '1 British Pound Sterling',
    'currency_id' => 15
  ),
  'New York' => array(
    'title' => '1 US Dollar',
    'currency_id' => 16
  ),
  'Paris' => array(
    'title' => '1 Euro',
    'currency_id' => 56
  )
);

// now you can easily find and loop through each of your cities
foreach( $cities as $city => $info ) {
  echo '<p>';
  echo "$city - {$info['title']}";
  echo get_rate($theMoneyConverter, $info['currency_id']);
  echo '</p>';
}


It's pretty cool to be able to do this in Bash.

Input validation

There are several issues here:

puppy=$1; [ -z "$puppy" ] && {
    echo "@@@ No args specified."
    exit
}

Code is most readable when there is one statement per line,
so I suggest to separate the variable assignment and the input validation steps.

exit without arguments exits with the code of the last command,
in this case 0 because the echo most probably succeeds,
so the program exits with success.
But it shouldn't. A common practice is to use exit code 2 for invalid usage.

Lastly, instead of not-valid-and-exit I think valid-or-else-exit is a somewhat cleaner logic, and also simpler to write:

puppy=$1
[ "$puppy" ] || {
    echo "@@@ No args specified."
    exit 2
}

Unnecessary $size

The size variable is unnecessary.
You can use ${#swamp[*]} instead, for example in:

right=$((${#swamp[*]} - 1))

Unnecessary $ inside $((...))

You can simplify these:

mid=$((($left + $right) >> 1))
right=$(($mid - 1))

Like this:

mid=$(((left + right) >> 1))
right=$((mid - 1))


Section sequence

That's rather a matter of taste. Programmers used to 68k usually use the sequence .text, .data, .bss, programmers used to Java usually use the sequence .data, .bss, .text. In the assemblers known to me it doesn't make any difference, so it's rather a matter of taste or corporate policy.

Actually, strictly speaking it's not the assembler but the linker who might have a word to say about the sequence, and the linkers that I know don't mind the sequence (even the Keil Linker for 8051, L51, which is really weird stuff).

Functional code

Breaking up bigger chunks of code into smaller parts very often makes sense because very often it increases maintainability.

Basically in Assembler you do a lot of trade-off between maintainability, speed and size.

Your functions are not universally reusable, for example your function to_ascii performs no sanity checks.
In that case, it doesn't always make sense, especially when the function body is just on instruction.

However, as far as I'm aware, on a modern member of the 80x86 family, instructions like call and ret basically come free of cost, thanks to the pipeline and branch prediction, so maybe there is no loss of speed, just of space.

Redundancy

The sequence

mov ecx, num
mov ebx, 1
mov eax, 4
int 80h ; output the current number

is redundant.
I don't think it's entirely bad.
Compared to having a single-instruction function to_ascii it looks, however, inconsistent.

I'd extract this into something like a print_number function.

Exit status

(You fixed this meanwhile.)

Your exit code looks like this:

mov ebx, 1
mov eax, 4
int 80h ; outputs "Blast off!"

mov eax, 1
int 80h ; exits program

The contents of register ebx are still 1 when you call exit.
This is probably wrong.
I do not see any indication why you would want to indicate that your program exits unsuccessfully.
You probably want to insert a mov ebx, 0 like this:

mov ebx, 1
mov eax, 4
int 80h ; outputs "Blast off!"

mov ebx, 0
mov eax, 1
int 80h ; exits program

Asymmetry in to_number vs. to_ascii

to_number accesses [num] itself, whereas in the case of to_ascii, [num] is accessed by the caller.
This is asymmetric, a form of inconsistent.
In bigger programs this might lead to confusion with respect to how APIs work.

Name log

Nowadays when you say log people think of generic logging along the lines of Logging APIs like log4j or sclog4c.

I'd rather call this function something else, in order to prevent confusion.

Formatting

I'm not sure whether this is a convention, but I'd do this:

blank line before every new function (i.e. after a ret that is not followed by code which could be reached by a conditional jmp before the ret).
Use local labels for loop and branch labels inside a function.
Write a small function header on top of each function which describes input, output and access to globals (especially side-effects).

Function header

Here's a sample function header for to_ascii

; Returns the ASCII value of the input digit.
; @param eax digit (value in the range of [0..9]) which is converted into an ASCII digit.
; @return eax ASCII value (in the range of ['0'..'9']).
; @warning If eax is out of the supported range, the behavior is undefined.
to_ascii:
    add eax, '0'
    ret

Local labels vs Global labels

AFAIK this is also true for NASM:

Local labels start with '.' and are valid until the next global label.
Global labels do not start with '.'.

Looking at your code, subtract should be a local label and thus renamed to .subtract.

This is not mandatory, and there is a valid interpretation of your code which includes tail recursion and last call optimization in which your code and label structure are valid.

It's just a bit surprising (maybe even positively) to see such constructs in assembler.

Conditional jumps

At the end of subtract you have two conditional jumps:

jne subtract
je blast_off

While this code is correct, I think the following would be more clear:

je blast_off
jmp subtract

Or in case you want to optimize for speed

jne subtract
jmp blast_off

The point is maintainability.
I found it less error-prone to have the last conditional jmp, which semantically is identical to an unconditional jmp as unconditional jmp indeed.
When you change the conditions, there is less necessity of changing the last jmp, and therefore less risk of getting code which would just go haywire for running unintentionally into the next function, in case the current function doesn't end with ret itself.

Structured Programming regarding _start / subtract?

I personally would almost always follow structured programming even in Assembly language.

At _start / subtract, this is not done because you call subtract.
Maybe that call even is unintentional, as I cannot see where subtract would ever return.

Independently of that, a construct like

    call foo
foo:
    more code

looks confusing, at least to me.
First, foo is called, and everything that is called is expected to return, and then when foo returned, we would run it once more.

I guess in this case, best is to simply remove the call subtract statement.

Structured Programming regarding _start / blast_off?

A similar problem is there with _start and blast_off.
blast_off is not called, so it is not a function - or to be seen as last-call optimization.
I'd actually avoid putting the good-case exit anywhere outside start.

In general, I'd avoid jumping over functions.
I feel jumps should be more local than calls, not the other way round.
The reason is that jumps are where we program conditions and loops, which is transfer of control inside a function, whereas calls is where we call subroutines, which is the transfer of control to another function.
I find it confusing if the transfer of control inside a function is "bigger" in distance than the transfer of control to another function.

Output

The output looks like this:

10987654321Blast off!

You might want to put space in between.

Makefile

You might want to use a Makefile for this.

I wrote the following Makefile for building and running this myself:

AS:=nasm
ASFLAGS:=-f elf
LINK.o:=ld
LOADLIBES:=-m elf_i386 -s

.PHONY: all
all: blast_off

blast_off: blast_off.o

.PHONY: run
run: blast_off
        ./$^

Disclaimer

I am new to NASM / x86 / x64 assembler myself.
I'm very experienced in 680x0, ARM and somewhat experienced in 6502, Z80, 8051, 80251 and CalmRISC but, as said, not (yet) in x86 / x64.


Is there a simple way to use Underscorejs to achieve this?

To be honest, I'd skip underscore for this, and just do

for(var func in requireViews) {
  if(requireViews[func] && typeof this[func] === 'function') {
    this[func]();
  }
}

Otherwise, there are many different ways to go about it.

Here's a needlessly complex one, for instance:

var target = this;
_.chain(requireViews)
  .keys()
  .filter(function (func) { return requireViews[func] })
  .intersection(_.functions(this))
  .each(function (func) { target[func]() });


Finding the longest path, avoiding obstacles in a 2D plane

Well, first of all (as I said in my earlier comment); "Extended algorithmic discussion may be better on Programmers.SE, however performance improvement is definitely on-topic here!".  So, let me start with (1) a quick review of some more basic things, then maybe give you (2) some advice about your approach and (3) the performance of your code.

1:   A Quick Review

1.1) Avoid Magical Complicated One-Liners

The very first thing I see in your code (really, before anything else), is the second line (the implementation of getDirections):

return {(1,0):"n", (-1,0):"s", (0,1):"w", (0,-1):"e"}[(p1[0]-p2[0], p1[1]-p2[1])]

While Python is a particularly powerful language when it comes to doing a LOT of things in one line... This usually (almost always) is not the best idea.  Both for readability, as well as for maintainability.  After all, this isn't Code Golf.

Additionally, you are also constructing the dictionary in each call - this is certainly not best practise performance wise (although in this case Python has probably optimized this for you).
But in general, if you have a lookup data structure that will not change throughout your program, you would make it a global variable, or class variable if you were using OOP.

1.2) Function Naming, and other Coding Standards

Taken from PEP8 section on Function Names:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.
  mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility

Your function names resemble Java methods, rather than Python functions.  This strikes me as particularly unusual since you seem to be coding in a procedural style. (Often Java programmers will name things in a Java way, but they also use OO).

Rather than:

getDirections
findPath
getNeighbours
getMax

You should use a more Pythonic naming scheme, like this:

path_direction
find_path
cell_neighbours
max_path_length

1.3) Argument and Variable Names - Meaning is Important

In a lot (almost all) of your functions, I see some argument names like p1, or mat.  As well as variable names like n, s, i, j, and wlist, etc.

Certainly, at a minimum typing matrix instead of mat is MUCH better.  p1 and p2 can be figured to mean path1 and path2, but I feel the latter is much more expressive and clear.
When it comes to iteration variables like i and j, you are okay using things like this.  But it is better to restructure you loops such that you can do things like for row in matrix:, rather than for i in range(len(mat)):.

2:   A Graphical Approach

2.1) The Idea

As I eluded to in my earlier comment; "have you looked into any of the Graph Search Algorithms, such as Dijkstra and A-star (A)?*" - I (personally) think they key to this answer lays in one or another graph search algorithm.

2.2) Transformation

Let's take the example 3x3 matrix from your question:

0 1 0
0 0 0
1 0 0

Now we want to represent each of these 9 matrix cells as a node in a graph.  Given that 0 represents an empty node, and 1 is a blocked node, such a representation may look like the following:

Note that as the cell at row 0, column 0 is always the start node, we can label it as such.  This is important as most graph search algorithms will require a starting node to work from.

My apologies for the lack of planarity, however a matrix does not lend itself easily to having no cross-overs for 15 vertices!

Note, giving vertices from the blocked nodes back to the end node is (probably, depending on which exact algorithm you use) optional.  I've included it here for completeness, but you may very well decide for performance reasons to just ignore blocked nodes all together.

2.3) Weighting the Graph

The key to this approach, is the different colours links (vertices) in the graph above.
Imagine if each green vertex has a zero (or negative) weight, and each red vertex had some positive weight (say 1).
then an algorithm seeking to find the "best" (*i.e. optimum, in terms of cost) path would naturally visit the most nodes (via green links).

Taking the path produced in your question as an example:

s 1,e 1,s 1,e 1,n 2

This would represent a path with a cost of -1 + -1 + -1 + -1 + -2 + 1= -5.
Which is  cheaper (in terms of aggregated weight cost), than the sub-optimal path:

 s 1,e 2,n 1

Which would have the cost: -1 + -2 + -1 + 1 = -3!

2.4) Finding the Algorithm

Obviously, there are many choices of Graph Search algorithms out there.  And going through and examining each one is certainly not within the scope of an answer on Rode Review.  But there is plenty of information on Google/Wikipedia regarding these.

Essentially, you'll want an algorithm that can avoid cycles (i.e. only visits nodes once), find the "best" (or shortest, or lowest score, etc) path - and (most importantly) can do this in a reasonable time.
Algorithms such as DFS come to mind, although you'll no doubt need to alter most implementations for your purposes.

3:   Performance of Your Code

3.1) Data Structures

The main reason for your codes slow performance is that you appear to not be using the correct data structures for your problem space.

Instead of using lists and tuples for everything, I suggest you take a look at something like Graph-tool and use graph based data structures.

3.2) Use Existing Algorithms

As I mentioned in  §2 (A Graphical Approach) above, your best bet is to find an existing algorithm to accomplish this task (i.e. change the data structures you're working with to fit an algorithm rather than the other way around as you're currently doing).


Creating an object in Python with lots of long arguments

Your TalkDetailsWidget is underdeveloped, I think.  You could say that you have a view but no model, and that is causing you problems.

You want to be able to write

talk = self.talkDetailsWidget
presentation = Presentation(title=talk.title,
                          speaker=talk.presenter,   # ← Why the inconsistent vocabulary?
                      description=talk.description,
                         category=talk.category,
                            event=talk.event,
                             room=talk.room,
                             date=unicode(talk.date.toString(Qt.ISODate)),
                             time=unicode(talk.time.toString(Qt.ISOTime)))

Therefore, you'll need to implement new properties in TalkDetailsWidget.  To avoid copy-and-paste programming in TalkDetailsWidget, I suggest writing those getters using metaprogramming.

class TalkDetailsWidget(QWidget):
    …

    def _field_reader(field, method='text'):
        return property(fget=lambda self: unicode(getattr(getattr(self, field), method)()).strip(),
                        doc="Returns a Unicode string from the %s field with spaces stripped from each end" % (field))

    title       = _field_reader('titleLineEdit')
    presenter   = _field_reader('presenterLineEdit')
    description = _field_reader('descriptionTextEdit', method='toPlainText')
    category    = _field_reader('categoryLineEdit')
    event       = _field_reader('eventLineEdit')
    room        = _field_reader('roomLineEdit')

    @property
    def date(self):
        self.dateEdit.date()

    @property
    def time(self):
        self.timeEdit.time()


Firstly you need to look at the way your code is formatted, you
should increase the indent after every opening brace.
You have a number variables that are declared and not initialised.
System ("pause") could be replaced with printf ("Press enter to continue\n"); fgetc(stdin);
GOTO there is almost never an excuse for using GOTO statements.
Try using functions to breakdown your code and eliminate repeated code, functions should be up to 20 lines long ideally, may be a hundred lines in exception circumstances.
Personally I don't like you Java style brace use.  IMO each brace should be on a separate line.
Namespaces are there to provide a way of resolving ambiguity, the using namespace std; line takes this function away. Personally I think that line should be removed and you should always prefix the calls with the namespace. In this case it will make no difference, but as you progress you might find your self calling a function in the wrong namespace because of this shortcut. Again it's just my opinion and I know people will disagree.

Try recoding it and post it again and see what I can find wrong with it next time :)


In terms of speed, your solution is about as optimized as it can get.  In terms of readability, your solution has much room for improvement.  I prefer readability over speed.  You should try to make your code as readable as possible, then, if you have performance issues, search for bottlenecks using a profiler and optimize them.  The method body of CalclualteFloorValue can be made into a one-liner, which happens to be slower but is much more readable.

private static int CalclualteFloorValue(int[] sortedArray, int key)
{
    return sortedArray.Last(x => x < key);
}

If you wish to keep the speed of your original solution and increase readability, there are many improvements you can make:

Have a consistent parameter naming convention.  _sortedarray has an underscore, but the other parameter names don't.  I prefer to only use underscores for variables declared within classes but not within methods.
_sortedarray should be lowerCamelCase.  That is, sortedArray.
If l will always be zero and r will always be array length - 1, declare them in the method body.  Don't make the method caller do unnecessary work.
Use descriptive variable names instead of single letters.

The beginning of the method will now look like this:

private static int CalclualteFloorValue(int[] sortedArray, int key)
{
    int left = 0;
    int right = sortedArray.Length - 1;


Unit test

The statistical reasoning in this unit test looks sloppy to me:

context 'when the event has multiple outcomes' do
  let(:trials) { 10_000 }

  subject(:event) do
    RandomEvent.from_hash(heads: 51, tails: 49)
  end

  it 'should distribute them' do
    coinflips = trials.times.map { event.predict! }

    heads_variance = (coinflips.count(:heads) - trials/2).abs
    tails_variance = (coinflips.count(:tails) - trials/2).abs

    expected_variance = trials/10

    expect(heads_variance).to be < expected_variance
    expect(tails_variance).to be < expected_variance
  end
end

It looks like you are flipping a slightly biased coin, but for some reason you expect heads and tails each to be 50%.  Then, for 10000 trials, you're requiring the count of heads and tails to be within the 40%–60% range — a very generous band.

The head count should follow a binomial distribution, namely \$B(n=10000, p=0.51)\$.  Applying Hoeffding's inequality

$$
\mathrm{Pr}(X \le k) \le e^{\frac{-2 (np - k)^2}{n}}
$$

for \$k = 4000\$ gives

$$
\mathrm{Pr}(X \le 4000) \le e^{-242} \approx 8 \times 10^{-106}
$$

The conclusion: for 10 coin flips, sure, the outcome can easily vary by 10%.  For 10000 coin flips, due to the Law of large numbers and the Central Limit Theorem, it basically never happens.  (It would be more likely that your computer is smashed by a meteor during the time it takes to run the test.)

Implementation

The convention is to use the ! suffix on methods that mutate the object.  Your predict! method doesn't really mutate the RandomEvent object, so I wouldn't name it with a !.1

Instead of doing the summation loop in predict!, it might be better to establish the cumulative thresholds in add_outcome, since that happens more rarely.

1 Functional programming purists would note that the method consumes randomness from the pseudorandom number generator when predict! calls rand, and thus it does have a side-effect.  By Ruby standards, though, I wouldn't consider it mutation.  Besides, your add_outcome is much more of a mutation than predict!.


Using keywords async/await in database queries (Windows Phone 8)

Before even addressing the actual question, have you actually proven that database queries are harming your responsiveness? Since the queries are to local storage it's possible that they are fast enough to not require using asynchrony, particularly if they are simple queries or the database is small.

Next, I notice you've assumed that the database itself is not threadsafe, i.e. that you must only allow access from one thread at a time. Are you sure that's actually true? Many (most?) database handle concurrency themselves, so you may be adding an unnecessary layer of synchronization. I looked around a bit, but could not find anything specifically documenting concurrent access to isolated storage databases. I would start by researching that, or possibly asking a question on StackOverflow. If the database does allow concurrent access then you just need to worry about update conflicts, which you could hopefully avoid in a single-user phone application.

What I'm getting at here is that multi-threading and locking is hard. Don't do it unless you're sure you have a good reason to do it.

If you really must to multi-threading, then the C# lock keyword is a good place to start. Unfortunately, your example probably will not work properly because each CacheDataUserContext instance will have it's own lock object - so if you create more than one instance they could conflict with each other.

You "Current Variant" actually gets this more right, because your AutoResetEvent is a static variable, so there is only a single instance of it across the system. However, as I understand DataContext it lets you use Linq statements against the database, which will not know anything about your lock and hence will not be synchronized.

I think you'd have to create a separate application layer to wrap the DataContext and expose just the certain operations that your application needs. This is generally called the "Repository Pattern". Inside the repository you could create a single lock object, wrap a lock around all accesses to a DataContext, and use Task.Factory.StartNew inside each of the repository methods to make them asynchronous.


Return a collection of most frequent characters in a string

Text and data structures

C# uses UTF-16 internally, so a char is actually 2 bytes long (and even then not all Unicode characters can be stored in a char). An array of 256 (a single byte can have 256, not 255, different values) is not sufficient. A Dictionary<char, int> would be more suitable here. For example, the following code is not limited to Latin characters, so feeding it some Cyrillic should work just fine:

var charCounts = new Dictionary<char, int>();
foreach (char c in s)
{
    if (!charCounts.ContainsKey(c))
        charCounts[c] = 1;
    else
        charCounts[c]++;
}

You said that you want to ignore space characters, but your code also ignores some control characters (but not all). You may want to use char.GetUnicodeCategory to determine which characters should be counted (there are several categories: various kinds of letters, digits, control characters and so on).

As for returning multiple characters, that's what arrays and lists are for. Instead of appending characters to a string, add them to a list and return that list when you're finished.

Other comments

Don't use 'magic values' (such as that 255 that's appearing several times). When you iterate an array, use its Length property: for (int i = 0; i < cc.Length; i++).
Using a char to index an array makes your code a little confusing to read. I don't see any advantages over using a 'standard' int.
I would also not recommend reusing an indexing variable (c): it's easy to introduce bugs by forgetting to 'reset' its value.
You don't need to initialize an array of ints with 0's: C# already does that for you (0 is the default value for int).
Try using meaningful variable names: text or input instead of s, charCounts or even characterCounts instead of cc, and so on. It'll make your code easier to understand, and that's a good thing when you have to revisit code a few months later.
The easiest way to get the maximum value from a collection is to use Linq's Max method: cc.Max(). There are also several other Linq methods that could make this method easier to write, such as GroupBy, Where and  ToDictionary.


Stem rules:

Spelling out compilation rule for each object file is tedious and error prone.

$(TEMPDIR)/%.o: $(SRC)/%.c
    $(CXX) $(CFLAGS) -c $< -o $@

takes care about all of them.
Autodependencies:

Spelling out dependencies for each object file is tedious and error prone. gcc can do it for you:

$(TEMPDIR)/main.d: $(SRC)/main.c
    $(CXX) $(CFLAGS) -MM -MT $< -o $@

-include $(TEMPDIR)/main.d

Of course you we don't want to spell it out for each source file, which naturally leads us to the next step.
Use macros. Shall you add more source files, only FILES needs to be modified.

FILES = main.c terminal.c
SOURCES = $(patsubst %,$(SRC)/%,$(FILES))
OBJECTS = $(patsubst %.c,$(TEMPDIR)/%.o,$(FILES))
DEPS    = $(patsubst %.c.$(TEMPDIR)/%.d,$(FILES))

$(TEMPDIR)/%.o: $(SRC)/%.c
    $(CXX) $(CFLAGS) -c $< -o $@

$(TEMPDIR)/%.d: $(SRC)/%.c
    $(CXX) $(CFLAGS) -MM -MT $< -o $@

-include $(DEPS)

$(TARGET): $(OBJECTS)
    $(CXX) $(LDFLAGS) $(OBJECTS) -o $(TARGET)


"Quick" save in electron with a conformation dialog

We can make the code simpler with a saveFile function

function saveFile(filename, data) {
    fs.writeFile(filename, content, (error) => {
        if (error) {
            dialog.showErrorBox(
                'Save Failed',
                `An error occured saving the file ${error.message}`,
            );
            return;
        }
        dialog.showMessageBox({
            type: 'none',
            title: 'Ganttron',
            message: 'The chart was successfully saved',
            buttons: ['OK'],
        });
    });
}

const quickSave = () => {
    let saveData = gantt.serialize();
    saveData = JSON.stringify(saveData, null, '\t');
    if (quickSaveFileName === undefined) {
        dialog.showSaveDialog({
                defaultPath: `C:\\Users\\${process.env.USERNAME}\\Documents\\`,
                filters: [{
                    name: 'json',
                    extensions: ['json'],
                }, ],
            },
            (filename) => {
                if (filename === undefined) {
                    return;
                }
                saveFile(quickSaveFileName, saveData);
            });
    } else {
        saveFile(quickSaveFileName, saveData);
    }
};


Thoughts on this conversion of code from Step.js to Q promise library?

Interesting that you're getting .finally() after your first method rather than at the end. Should I read that to mean that your code executed as: connect-->finally-->[DONE] or did control flow somewhere else in the promise chain subsequent to finally?

Regarding the aesthetics - I couldn't agree with your more; ninvoke and its relatives are not the easiest to read. Two main options. One, you can look for a promise-enabled library for this or that. This is probably not my first choice unless the library would be giving you something more than just a promises wrapper. Two, you can get yourself some nicer looking functions by using the denodeify function. Consider if you wrote a module like this (you could of course inline this code as well which I often do for both initial development as well as if I find I really don't need more than a function or two):

var Q = require('q');
var lib = require('someNodeModule');

module.exports = {
   connect: Q.denodeify(lib.connect),
   read: Q.denodeify(lib.read),
   write: Q.denodeify(lib.write)
}

At this point, you have a new module with each of the above functions being promise-returning ones rather than callback-invoking ones. If you require the above as, say libp, you could then replace your various return Q.ninvoke(...) calls with much more clear calls such as a simple return libp.connect(...). The signature of the function stays the same (other than the obvious loss of the final callback).

I will try to return to this later this evening as well regarding the odd .finally() behavior. In the meantime, you might find this Q&A relevant to an issue you did not raise, but may encounter. More generally, the individual providing the answer, Bergi, appears to be quite expert with promises (from other answers I have seen), so you might check out some other answers or even solicit input on this. I am a journeyman, at best, with promises. I think I have a reasonable understanding of the concepts and library, but have not yet accumulated all the idioms that would be helpful.


C++ template Partial Specialization Member Function; Am I doing right?

What you've written does work, and you seem to understand all the concepts (e.g., "you can't partially specialize function templates"), and your coding style (indentation and whatnot) seems fine.

Well, one coding-style improvement: You need those (void)input casts to shut up compiler warnings about unused parameters... in C. But in C++ you don't need those casts; what you do instead is, if you're not going to use a parameter, just don't give it a name.

static void bar(const T&) { ... }

However, your code doesn't really match any common TMP patterns — which is probably just because you're noodling around, learning, instead of trying to solve a specific problem.

If you just wanted to produce the same output with less code, you would do this:

struct Foo
{
    template<class T> auto bar(const T&) -> std::enable_if_t<!std::is_integral<T>::value>
    {
        std::cout << "Generic" << std::endl;
    }

    template<class T> auto bar(const T&) -> std::enable_if_t<std::is_integral<T>::value>
    {
        std::cout << "Specialization for integral type" << std::endl;
    }

    void bar(bool)
    {
        std::cout << "Specialization for bool" << std::endl;
    }

    void bar(const std::string&)
    {
        std::cout << "Specialization for std::string" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.bar(Foo());
    foo.bar(std::string());
    foo.bar(bool());
    foo.bar(int());
    return 0;
}

That is, your code is equivalent to providing two overloads of foo.bar, plus a couple of mutually exclusive templates (one for integral types and one for other types). The specific overloads for bool and std::string will take precedence over the templates.

Alternatively, you could use tag dispatch, as follows. (But I don't recommend it in this case because it turns out to be surprisingly subtle. Replace the second instance of std::true_type with ... and watch that overload silently drop out. I'm not actually sure why.)

struct Foo
{
    template<class T> void bar_impl(const T&, ...) {
        std::cout << "Generic" << std::endl;
    }

    template<class T> void bar_impl(const T&, std::true_type) {
        std::cout << "Specialization for integral type" << std::endl;
    }

    void bar_impl(const std::string&, ...) {
        std::cout << "Specialization for std::string" << std::endl;
    }

    void bar_impl(const bool&, std::true_type) {
        std::cout << "Specialization for bool" << std::endl;
    }

    template<class T> void bar(const T& input)
    {
        bar_impl(input, std::is_integral<T>{});
    }
};

Maybe the best approach would be to use two non-interacting levels of tag dispatch: first, is T integral? and second, what is T exactly?

template<bool IsIntegral> struct BarImpl {
    template<class T> static void bar(const T&) {
        std::cout << "Generic" << std::endl;
    }
    static void bar(const std::string&) {
        std::cout << "Specialization for std::string" << std::endl;
    }
};

template<> struct BarImpl<true> {
    template<class T> static void bar(const T&) {
        std::cout << "Specialization for integral type" << std::endl;
    }
    static void bar(bool) {
        std::cout << "Specialization for bool" << std::endl;
    }
};

struct Foo {
    template<class T> void bar(const T& input) {
        BarImpl<std::is_integral<T>::value>::bar(input);
    }
};


Updating or adding data to an associative array as a cache

Modify the code to this:

//just use the AND operator (&&) to check if it's both existing AND valid
//use strict comparison (===) whenever possible
if(array_key_exists($key,$cachetable) && $cachetable[$key] === $newdata[$key]){
    //data exists and valid
} else {
    //data doesn't exist or isn't valid
    //to assign data, use a single equal (=).
    //A double equal (==) is a loose comparison
    $cachetable[$key] = $newdata[$key];
 }

//this one checks if it's not in the array
//or if it does, it checks if it's not valid
//when either one is true, the condition passes
if(!array_key_exists($key,$cachetable) || $cachetable[$key] !== $newdata[$key]){
    //data doesn't exists or isn't valid
}


C# Class of client methods for interacting with web servers

It's probably fine for test code. There are a few things I noticed. None of these are necessarily a problem. They may never affect your tests. But they're not ideal either.

You're not calling Dispose() on everything that you strictly should (eg, Streams).
You're always encoding your post parameters in ASCII, but reading the responses in UTF8. If you're sticking to basic English characters that'll be fine, but if you try other languages/character sets it may be problematic.
the GetStatusCode() function is using the HEAD method. Not all endpoints will respond properly to the HEAD method, or is the same way that they would to GET or POST.

If you're going to be doing a lot of this then you may want to look at the WebClient class. It's a little bit simpler to use, and may be sufficient for your needs.


Debatable ... and a bug?

constructs like these are one of those things that personal-preference plays in to, but consider:

    if (args.length != 1) {
        System.err.println(args.length > 1 ? "Excessive arguments, only the first will be considered" : "No arguments provided.");
        System.exit(1);
    }

Error handling is boiler-plate that can be made more readable by separating the error conditions out explicitly. In checking/refactoring this, I found an apparent bug, too (which was hard to spot because of the compound exit condition). The bug is that if the arg-count is more than 1, you print the message "Excessive arguments, only the first will be considered" but then terminate anyway..... so much for ignoring the subsequent args...  I would prefer:

private static final void terminate(String message) {
    System.err.println(message);
    System.exit(1);
}

.....

    if (args.length == 0) {
        terminate("No arguments provided");
    }
    if (args.length > 1) {
        terminate("Too many arguments provided. Expect exactly 1");
    }

A distinct advantage I find when you separate out the error conditions, is that maintaining them is simpler, especially when using version-control because the diffs are simpler to understand.

Challenge

Programming challenges are often time-constrained. While for most purposes your code is fast enough, there's a simple technique that can significantly improve performance - do bulk operations (at the expense of using memory). Specifically, it's typically better to "accumulate" the output in a "StringBuilder" and then have a single System.out.println() at the end. The in-the-loop println you currently have will cause the system to "flush" each line, and often that amounts to significant portions of your program time (more than half?).

Similarly, reading in the entire input file in one "gulp" is often faster than a Scanner, or some other operation.

Obviously, "huge" inputs may be a problem, in theory, but I have never yet been found victim to conditions like that in challenges.

Gulping

I would consider using a gulp function to read the entire file - the Java 8  java.nio.files package can help here, and I would choose:

List<String> data = Files.readAllLines(Paths.get(args[0]));

Splitting

A trick of loading an empty-string in to your decode-routine to output a space, will allow you to use a regex to split, and process each line, in a stream:

private static final Pattern charsplit = Pattern.compile(" ");

and then:

String out = charsplit.splitAsStream(line)
             .map(letter -> morseAlphabet.get(letter))
             .collect(Collectors.joining(""));

You can then append that out with a newline, to the output buffer... so that the whole thing ends up looking a little like (untested - see conclusion for working code):

String output = Files.readAllLines(Paths.get(args[0])).stream()
     .map(line -> charsplit.splitAsStream(line)
                           .map(letter -> morseAlphabet.get(letter)
                           .collect(Collectors.joining("")))
     .collect(Collectors.joining("\n");

System.out.println(output);

I would probably take that inner stream and make a real Function<String,String> out of it. I would also make the printing a separate function ... it should not be part of the parsing/decoding.

Conclusion

I put together a working example program here: https://ideone.com/hCpUA1

Note that the version of the code I was happiest with separated out the various functions, and converted the Map<String, Character> to a Map<String, String>. Note that the map also has the "Space" value in it.

Additionally, the reading of the file, and converting to List<String> is expected to be outside the function (in the main method) which cannot be done in ideone.com.

Here's the code in full:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.stream.*;
import java.util.regex.Pattern;

class Morse
{

    private static final Map<String, String> morseAlphabet = new HashMap<>();

    static {
        morseAlphabet.put("", " ");
        morseAlphabet.put(".-", "A");
        morseAlphabet.put("-...", "B");
        morseAlphabet.put("-.-.", "C");
        morseAlphabet.put("-..", "D");
        morseAlphabet.put(".", "E");
        morseAlphabet.put("..-.", "F");
        morseAlphabet.put("--.", "G");
        morseAlphabet.put("....", "H");
        morseAlphabet.put("..", "I");
        morseAlphabet.put(".---", "J");
        morseAlphabet.put("-.-", "K");
        morseAlphabet.put(".-..", "L");
        morseAlphabet.put("--", "M");
        morseAlphabet.put("-.", "N");
        morseAlphabet.put("---", "O");
        morseAlphabet.put(".--.", "P");
        morseAlphabet.put("--.-", "Q");
        morseAlphabet.put(".-.", "R");
        morseAlphabet.put("...", "S");
        morseAlphabet.put("-", "T");
        morseAlphabet.put("..-", "U");
        morseAlphabet.put("...-", "V");
        morseAlphabet.put(".--", "W");
        morseAlphabet.put("-..-", "X");
        morseAlphabet.put("-.--", "Y");
        morseAlphabet.put("--..", "Z");
        morseAlphabet.put("-----", "0");
        morseAlphabet.put(".----", "1");
        morseAlphabet.put("..---", "2");
        morseAlphabet.put("...--", "3");
        morseAlphabet.put("....-", "4");
        morseAlphabet.put(".....", "5");
        morseAlphabet.put("-....", "6");
        morseAlphabet.put("--...", "7");
        morseAlphabet.put("---..", "8");
        morseAlphabet.put("----.", "9");
    }

    private static final Pattern charsplit = Pattern.compile(" ");

    private static final String decodeLine(String line) {
        return charsplit.splitAsStream(line)
                   .map(letter -> morseAlphabet.get(letter))
                   .collect(Collectors.joining(""));
    }

    public static final String decode(List<String> data) {
        String output = data.stream()
             .map(Morse::decodeLine)
             .collect(Collectors.joining("\n"));
        return output;
    }

    public static void main (String[] args) throws java.lang.Exception {
        String out = Morse.decode(Arrays.asList(
               "-.-. --- -.. .  .-. . ...- .. . .--",
               "..--- -. -..  -- --- -. .. - --- .-.",
               "..-. .-. --- --  -.-. --- -.. . . ...- .- .-.."));
        System.out.println(out);
    }

}


I am happy for you, that you are asking for help with refactoring this scary function.
First of all, you must not write more than 2 indentations with if statements, if you want to be a great developer.

Secondly, when you write a program, keep in your mind that every method or function must do one simple task.

Well, what is the responsibility of your function?

check insurance number Length.
check prefix.
check the second string of prefix.
check suffix.
check the numeric body number.

Perfect, why must we create a class instead of keeping your method?

There is one principle, it is KISS(Keep it simple stupid),
the main idea behind this principle is to keep your methods or classes as simple and stupid as possible.

For that, we should create new methods for our responsibilities above. For example to check the first responsibility which is "check insurance number length" we will create a method called isNotValidInsuranceNumberLength to do that for us etc..

Since we have many methods, we should encapsulate all of them within a class, that will be its responsibility to take care of the national insurance number validation.

And this touches on the SRP(single responsibility principle) because we must ensure that our class will have one and only one reason to change(validation of the national insurance number).

I was changing the imbricated if statements by small methods that describe what they do exactly by its name.

  I advise you, that when you write code think like you are writing a
  story.

  another advice: read Uncle Bob clean code's book.

my refactorization is below :

<?php

class  NationalInsuranceNumberValidator
{
    $insuranceNumber = null;

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

    public function validate()
    {
        if($this->isNotValidInsuranceNumberLength())
        {
            echo "Invalid National Insurance Number. isNotValidInsurenceNumberLength";
        }
        elseif($this->prefixIsNotValid())
        {
            echo "Invalid National Insurance Number. prefixIsNotValid";
        }
        elseif($this->secondPartOfPefixIsNotValid())
        {
            echo "Invalid National Insurance Number. secondPartOfPefixIsNotValid";
        }
        elseif($this->suffixIsNotValid())
        {
            echo "Invalid National Insurance Number. suffixIsNotValid";
        }
        elseif($this->isNotNumericBody())
        {
            echo "Invalid National Insurance Number. isNotValidNumericBody";
        }
        else
        {
            echo "Valid National Insurance Number.";
        }
    }

    private function isNotValidInsuranceNumberLength()
    {
        $insuranceNumberLength = strlen($this->insuranceNumber);

        return $insuranceNumberLength < 10 || $insuranceNumberLength > 10;
    }

    private function prefixIsNotValid()
    {
        return preg_match("/[^!@#$%^&*]*(BG|GB|NK|TN|NT|ZZ|D|F|I|Q|U|V)[^!@#$%^&*]*/i", $this->getPrefix()) == 1 ? true : false;
    }

    private function secondPartOfPefixIsNotValid()
    {
        $prefix = $this->getPrefix();

        return preg_match("/[^!@#$%^&*]*(O)[^!@#$%^&*]*/i", $prefix[1]) == 1 ? true : false;
    }

    private function suffixIsNotValid()
    {
        return preg_match("/[^!@#$%^&*]*(A|B|C|D)[^!@#$%^&*]*/i", $this->getSuffix()) == 1 ? false : true;
    }

    private function isNotNumericBody()
    {
        return !is_numeric($this->getNumericBody());
    }

    private function getPrefix()
    {
        return substr($this->insuranceNumber, 0, 2);
    }

    private function getNumericBody()
    {
        return substr($this->insuranceNumber, 2, 7);
    }

    private function getSuffix()
    {
        return substr($this->insuranceNumber, 9, 1);
    }
}

$nationalInsuranceNumber = new NationalInsuranceNumberValidator('AA1220091C');

$nationalInsuranceNumber->validate();


How object oriented is my Crazy Eights game?

I'm just going to look at your OOP design for this review, as you requested.

Your canPlayOn() method does not belong in the Card class.  The purpose of your Card class should be to represent a card, and nothing more.  You should be able to use the same Card class for Blackjack, Bridge, or any other card game.  Logic specific to Crazy Eights does not belong there, and should probably be moved into the Player class.

I was initially thinking that your Hand should consist of a set of cards rather than an array, since the items are distinct and order doesn't matter.  Then I saw that your Pile derives from Hand, and in Pile, order does matter.  Maybe using an array is OK after all, if you accept that a Pile is a subclass of Hand.  I think that such an inheritance relationship is more of a hack than an accurate model, but I can let it slide because it seems to work in this case.

In DrawPile.deal(), I would rename the others parameter to recipient_hands.  Also imports should go at the beginning of the file.

I take issue with Player(Hand) and Computer(Hand).  First of all, I would say that a player has a hand rather than a player is a hand.  That suggest that composition should be favoured over inheritance.  Also, the computer is a kind of player, so there should be an inheritance relationship there.  Furthermore, there is a lot of redundant code between Player and Computer, differing mainly in what the output looks like.  Perhaps your Player and Computer classes could be merged into a Crazy8Player class, with the constructor taking name, narrator, and strategy arguments.


Converting an array-returning function to a lazy evaluator

You've done a lot of things well. Going the route of an iterator was a good choice, and you got the small details of const correctness and references and whatnot correct. There are, however, a few things I think can improved.

Naming

Your names are very undescriptive. In fact, it took me far longer than it should have to realize it's just modelling a linear function over a certain domain. Something like apply_linear for the returning version might be good, and something like linear_iterator might be good for the other one. Also, data_obj is very vague name. Pretty much all objects contain data of some kind. I might call it something like linear_function or something.

Structure

Something about your structure is a little off. I think instead of having obj_iterator take a data_obj for construction, I would have data_obj have begin() and end() methods that return a beginning iterator and an ending one. That way, you don't have to get into any friend stuff (right now data_obj is pretty useless to anything except the iterator since its members are private).

I'm also a bit uncomfortable with func and func2 being hardcoded. What if you want to change them? What if you want them to not be applied? It has essentially tightly coupled data_obj to func and func2, and worse yet, there's not really any reason for it. You can just have A and B be accepted for the values, and then you can apply func and func2 if you want.

That's essentially tightly coupling the linear function to those two functions. Further more, the coupling is super easy to get rid of: instead of taking t and x and applying func and func2, just accept a value that won't be further transformed.

In essence, I'm essentially suggesting that you generalize your thinking a bit farther. Currently you're modeling y(x) = m(t, z) * x + b(t, z). The problem is that m and b are constants, so there's no point in modeling them as part of the function. Instead, you can just model a typical linear function y(x) = m*x + b and take in m and b as constants (m = m(t, z), b = b(t, z)).

Idiomatic Iterator

Like I said earlier, it's good that you went with iterators for this. It's the best (built in) way in C++ to achieve a generator. It would have been a bit nicer if you'd done it more idiomatically though. In C++, iterators are used as pairs of iterators with a currently iterated iterator and an ending iterator. Also, operator++, operator* and operator== (or operator!=) are typically used instead of methods like next(), has_next(), etc.

auto fn = linear_function(2.5, 37.2, {...});
for (auto it = fn.begin(), end = fn.end(); it != end; ++it) {
    std::cout << *it << "\n";
}

A nice side effect of this is that you actually get rewarded for being idiomatic. The standard library becomes a lot more compatible with your stuff, and you can get range based for loops as a happy side effect:

// Wooo standard library!
auto fn = linear_function(2.5, 37.2, {...});
auto sum = std::accumulate(std::begin(fn), std::end(fn), 0.0);

// Wooo pretty loops!
for (auto y : linear_function(2.5, 37.2, {...})) {
    std::cout << *it << "\n";
}

Minor things

These are minor enough that I don't think any of them deserve their own section.

I would consider having data_obj work on a pair of iterators instead of being coupled to vector (what if you want to use it on an array, std::array, std::set, etc?).
I would considering make data_obj immutable.
data should be std::move'd m_data to ensure an extra copy is avoided.

Style

This is all subjective, of course, but:

I'm not a fan of the m_ prefix. I prefer either plain member names (e.g. data), or member names with a trailing underscore if method/member name conflicts are expected (e.g. data_). The m_ prefix is still relatively common, but it seems to be dying off, and personally, I can't wait for it to finish dying.
When function parameters can reasonably fit on one line, they should be on one line.
Indented variables per type is very non-standard. Standard is to have each variable on its own line with its own type declaration.

Putting it together

An example can probably illustrate much more effectively than my rambling words:

// Models a linear function
class linear_function {
private:
    const double m;
    const double b;

public:
    // Construct the function from slop intercept representation
    linear_function(double m, double b) : m(m), b(b)
    { }

    // Evaluate the linear function for a specific value.
    double operator()(double x) const { return m * x + b; }

    bool operator==(const linear_function& other) const {
        return m == other.m && b == other.b;
    }
};

// Iterates over a given domain for a linear function.
template<typename Iter>
class linear_function_iterator { // You'd want to extend or mimic std::iterator in a library-esque implementation
private:
    const linear_function fn_;
    Iter iter_;
    const Iter end_;

public:
    // Whether you want to take a single iterator or a pair is going to depend on typical usecase. Taking
    // a pair makes use a bit safer though since you can do checking to ensure proper use.
    linear_function_iterator(linear_function fn, Iter iter, Iter end)
      : fn_(std::move(fn)), iter_(iter), end_(end)
    { }

    double operator*() const {
        assert(iter_ != end_); // Example of using two iterators instead of one to provide additional error checking.
        return fn_(*iter_);
    }

    linear_function_iterator& operator++() {
        assert(iter_ != end_);
        ++iter_;
        return *this;
    }

    bool operator==(const linear_function_iterator& other) const {
        return fn_ == other.fn_ && iter_ == other.iter_;
    }

    bool operator!=(const linear_function_iterator& other) const {
        return !operator==(other);
    }
};

// Convenience class for a linear function over a given domain.
// Provides both an upfront approach or generator-like.
template<class Iter>
class fixed_linear_function { // This seems like a terrible name, but I'm blanking on anything better.
private:
    linear_function fn_;
    const Iter begin_;
    const Iter end_;
public:

    using iterator = linear_function_iterator<Iter>;

    fixed_linear_function(linear_function fn, Iter domain_begin, Iter domain_end)
      : fn_(std::move(fn)), begin_(domain_begin), end_(domain_end)
    {}

    std::vector<double> evaluate() const {
        std::vector<double> results;
        std::copy(begin(), end(), std::back_inserter(results));
        return results;
    }

    iterator begin() {
        return iterator(fn_, begin_, end_);
    }

    iterator end() {
        return iterator(fn_, end_, end_);
    }

};

// Because I'm lazy
template<typename Iter>
fixed_linear_function<Iter> make_fixed_linear_function(double m, double b, Iter beg, Iter end) {
    return fixed_linear_function<Iter>(linear_function(m, b), beg, end);
}

// Soooooo lazy
template<typename Container>
auto make_fixed_linear_function(double m, double b, const Container& c) -> fixed_linear_function<decltype(std::begin(c))> {
    return make_fixed_linear_function(m, b, std::begin(c), std::end(c));
}

This brings up an interesting note: generality and idiomaticness in C++ often come at a high cost, but also give high reward with regards to reusability and interoperability. This is significantly longer than your code, but it can be used with the standard library, and it's more flexible. In fact, if you were actually going to implement the idiomatic C++ approach like this, you could actually very easily take it one step farther and arrive at a generic generator. All that would be required would be renaming linear_function_iterator to generator, templating out linear_function to be any function (and also likely removing the end iterator since generators typically support infinite iteration), and deducing the return type of operator* instead of assuming its double.

Note: This is strictly an example implementation. Operators are only partially defined, template traits aren't present, and overall, this is missing a lot of the corner cases/optimizations/etc that would make it applicable for real use.

Example usage:

int main() {
    std::vector<double> values{1.0, 3.5, 27.2};
    for (auto y : make_fixed_linear_function(3, 2.5, values)) {
        std::cout << y << '\n';
    }

    auto fn = make_fixed_linear_function(3, 2.5, values);
    std::cout << std::accumulate(std::begin(fn), std::end(fn), 0) << '\n';
}

Generic generator

For toy, or small applications, it's not really going to matter, but if you find yourself doing this a lot in a real application and not some kind of school assignment or throwaway program, you'd likely want to find a well known and highly regarded generator implementation (I think Boost has a generator). It would save you time, it'd be more likely to be correct, and it'd likely be better designed than anything you or I can think of.