Unit Test case for services method in angular

Personally i would create an interface for the expected data from the backend. any is something i try to avoid, because then my IDE can´t help me finding my stupid mistakes.
For example
interface DynamicFormData {
   aValue: string,
   anotherValue: number,
}

async getDynamicFormData(paramName: string, data?: SomeDataType): Promise<DynamicFormData > {
  return await this.http.get(this.HostUrl + paramName).toPromise();
}

It gives you the benefit, that whereever you call that method, the IDE will know how the data will look like and what methods could be performed on it.
Also personally i like working with RxJS more than Promises, but thats a personal habit. But it allows to filter, modify, do stuff on the response. And i stay away from "async/await", because i do not like blocking tasks in my frontend if i can avoid them. But as i said, personal style.
About the init of the testcases, why do you need to import the RouterTestingModule? Its not used in the service at all.
About the test coverage:
When i see a method interface like getDynamicFormData(paramName: any, data?: any) then i would ask myself if "paramName" is mandatory or not. Also test cases are a kind of documentation, therefore i would add a testcase with an empty paramName (for example null).
From a Unit-testing perspective i would avoid hard coded strings like "account-type". You will surely use this strings also at other places in the regular code when you want to call the service. If those strings change, you have to find all places where they are used and replace them. Therefore i would create constants for those and us those constants. Then if the API changes ( e.g. "account-type" changes to "type-of-account") you just have to change it at one place and all (code and unit test) will adept automaticly.
You specificly asked in the comment for "code-coverage".
For that we have to think about what could be the possible results of each method. The Promise could be resolved or fail. Quite easy.
BUT your service is instantiated with a parameter
constructor(private handler: HttpBackend) {
    this.http = new HttpClient(handler);
 }

If you do not provide any input (as you do in your unit test), then its instantiated with this.http = new HttpClient();. I always use the HTTPClient provided directly by Angular, therefor i do not really know the effect of this. From the documentation it seems that this would circumvent the interceptors. But be it as it be, as its an input that may alter the behavior of your service, its something that should be covered by your testcases.
Hope you could use some of the mentioned things. :-)
warm regards
Jan


I’m not sure I can get it any better than \$O(n^2)\$, but I would point you towards the itertools module as a way to tidy up your code by reducing the number of nested for loops. Like so:

def four_sum(A, B, C, D):
    sums = defaultdict(int)
    result = 0
    for (a, b) in itertools.product(A, B):
        sums[a + b] += 1
    for (c, d) in itertools.product(C, D):
        result += sums[-(c + d)]
    return result

I’ve also tweaked the names of some of the variables to make the code easier to follow, and changed it so it only has to compute (c+d) once.


This seems overwrought. Let's start with getCountElements.

It's often a good idea to consider not just the problem at hand, but a more general statement of what it is you're trying to solve. In this case, you're trying to get a frequency count of each distinct element in a list. At this point don't worry about the particulars of your problem (like the fact that you're only supposed to be counting Integers with values [0..9]), frequency counts are a well-defined problem for arbitrary data sets and as such lend themselves to a generalized solution.

So think about what a general solution would look like. Well, to start, your function will be handed a [a] ->, just some list of arbitrary elements. But we need to group up which ones are equal to each other so that implies that we must have an equality constraint, (Eq a) =>. After we find and count the equal elements you'll need to return that count, so -> [Int]. But that doesn't make sense now given our generalized problem, the position of each Int in the list says nothing about which as it represents, so instead we'll return -> [(a, Int)], a list of pairs of an element and the count of that element in the original list. Putting it all together we get—

frequencyCount :: (Eq a) => [a] -> [(a, Int)]

Now we could make this work as-is†, but there's an important optimization we can make by tightening our constraints further. By first sorting the list we are given we can then easily group together identical elements, improving our asymptotic performance to O(n log n). Thus—

frequencyCount :: (Eq a, Ord a) => [a] -> [(a, Int)]

Jumping back to your version before showing the implementation, let's compare what's going on between both already.

getCountOfElements :: [Integer] -> ([Integer],Integer)

Program specifications and logic are threaded all through, from the specification of the domain to Integers, to the encoding of element identity in the position of the list in the return type, through to the inclusion of the largest count in the returned pair (a particularly odd design choice given the name of the function).

Getting back to implementing frequencyCount our implementation should be almost self-evident after having given the type. First we'll sort the elements to efficiently group the similar ones, then we'll run-length encode the list.

frequencyCount :: (Eq a, Ord a) => [a] -> [(a, Int)]
frequencyCount = runLength . sort
    where
        runLength :: (Eq a) => [a] -> [(a, Int)]
        runLength = map (\es -> (head es, length es)) . group

Et, voilà! Let's now contrast some of the properties of the getCountOfElements implementation.

Due to the use of !! for indexing, if the [Integer] we're passed is out of bounds an exception will be thrown. Better filter the whole list of elements beforehand.
count uses take, drop, and of course !!, all of which are O(n) operations on Haskell lists. That's three traversals of the index-encoded list for each element, consider the worst case performer of getCountOfElements (replicate 100000 9). This would have to be cleaned up through use of splitAt.
Using ++ in count will walk the left portion of the accumulator list again, consider again that worst case performer.

In the face of all that, getCountOfElements is an O(n) algorithm (albeit with a very large constant factor) whereas frequencyCount is O(n log n). So despite the constructive beauty of frequencyCount, to do better than getCountOfElements I'll have to steal your algorithm and use it with an appropriate Haskell data structure for constant time indexing and updating.

Data.Array from the array package provides such a data structure for us, and in fact the very first visible code example in the documentation is for a histogram function.

hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
hist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i]

To use this version we have to provide a pair of bounds, in this question's particular case (0, 9).

count09Elements :: [Integer] -> [(Integer, Int)]
count09Elements = assocs . hist (0, 9)

In conclusion, Haskell is a land of contrasts. So, we learned today that there are many different ways to skin a cat. Depending on what you know about your problem domain many different complexity classes of algorithms may be available to you. And don't use linked lists for operations requiring constant time updating.

Appendix

† An inefficient but important frequencyCount implementation. Note that performance is O(n²) (consider e.g., frequencyCount [0..100000]).

import Data.List (partition)

frequencyCount :: (Eq a) => [a] -> [(a, Int)]
frequencyCount []       = []
frequencyCount xs@(e:_) = (head es, length es) : frequencyCount xs'
    where
        (es, xs') = partition (== e) xs


Detecting over-/underflow for uint64+int64

I really like that you put those tests together in the playground, thanks!

I am not a fan of losing information that may be useful. You will always need to check 0-value results to see if they indicate an overflow/underflow condition, so it's just simpler to return a useful result for those times when overflow is OK.... why return 0 when the actual remaining result is just as good?

More specifically, you will always have code like:

value, ok := addUintInt64(x, y)
if !ok {
   ....
}

so why force the 0 in to the value for !ok?

In addition, the magnitude of an int64 is never going to exceed half the magnitude of a uint64, so a double-overflow is not possible, and the logic required to check an overflow condition is a case of checking the change, or the direction of the change, of the sign-bit of the equivalent int64 value.

Perhaps this is best described if you handle the complete calculation in int64 space, and convert the result to uint64 - and realize that the MSB of the uint is the sign bit of the int.

The following conditions are all OK:

the sign bit does not change after the addition, then there's no overflow condition (no possibility of wrap)
the sign bit changes, but the int value was positive and the source sign bit was not set
the sign bit changes, but the int value was negative and the source sign bit was set

This is easy to codify in Go as:

result := uint64(int64(x) + y)
before := x >> 63
after := result >> 63
ok := before == after || (before == 0 && y >= 0) || (before == 1 && y < 0)

The above calculates in int64 space, wraps back to uint64 space, and computes the overflow conditions....

Using your same test cases (with the 0 return value for !ok) you can see this in the playground.

I would rather return the result though even if !ok, to avoid the additional check, so it would be the function:

func addUintInt64(x uint64, y int64) (uint64, bool) {
    result := uint64(int64(x) + y)
    before := x >> 63
    after := result >> 63
    ok := before == after || (before == 0 && y >= 0) || (before == 1 && y < 0)
    return result, ok
}


HackerRank Binary search tree validation

The prev_val handling is slightly clumsy.  I would personally prefer using the pairwise() recipe from itertools.  You could then replace the loop altogether with all(…), which more clearly expresses your intentions.

I would also prefer to see the generator yield node.data instead of yield node.

from itertools import tee

def checkBST(root):
    a_iter, b_iter = tee(in_order_traversal(root))
    next(b_iter, None)
    return all(a <= b for a, b in zip(a_iter, b_iter))

def in_order_traversal(node):
    if node.left:
        yield from in_order_sort(node.left)
    yield node.data
    if node.right:
        yield from in_order_sort(node.right)


The usage of target is not consistent:

target: resb 4      ; 4 bytes of storage (enough for a 32bit number)
...
mov     [target], rdx ; store 8 bytes

That's easy to improve, just use edx.

Using rand like this is not very random, it's some function of the time in seconds. Seconds are long, you could easily start the program twice in the same second. Maybe that's fine for a simple number guessing game. On not-too-old processors there is a simpler and more random way to get a random number though:

.rand_retry:
    rdrand eax
    jnc .rand_retry

But that doesn't work on some older processors (Intel processors older than Ivy Bridge, for example Nehalem or Core2, and AMD processors older than Excavator), and can actually be slower than calling rand. Seeding the random number generator with the TSC value is more portable and less predictable than using time:

rdtsc ; read TSC into edx:eax
mov ecx, eax
call srand
call rand

Since you asked for performance tips (this program is obviously limited by waiting for user input but you can still learn useful things from this):

This remainder calculation is inefficient:

mov     rcx, 100
div     rcx     ; 64bit div, quite slow
inc     rdx

There are other options. For example, for a 232 input range (which rand normally does not deliver but rdrand does), a very similar-looking fixed-point scale can be used:

mov     ecx, 100
mul     ecx
inc     edx

The mul, combined with using the upper half of the result, effectively multiplies the input by 100 / 232 so 0xFFFFFFFF maps to 99 and so on. This method can be adjusted for smaller ranges such as up to RAND_MAX by multiplying by a higher constant, namely 100 * 232 / (RAND_MAX + 1)

The too low/too high cases could be less branchy and can share some code - admittedly they call an IO function anyway, but still. For example:

    cmp     r8d, [target]
    jne     .not_equal
...
.not_equal:
    lea     rcx, [too_high]
    lea     rdx, [too_low]
    ;; if "less than", use the too_low string
    cmovl   rcx, rdx
    call    printf
    jmp     .check


Throughout your code you use for loops.  Java 8 has been around for 4 years now. It is time you start using the new (now quite old) collection streams. Here are some snipets to get you started:

string.chars().forEach(letterThere -> {
  ...
})

IntStream.rangeClosed('a', 'z').forEach(i -> {
  ...
})

regarding whereInLetterCtr() : you advance comparisonLetter from 'a' to 'z' with the ++ operator so you realize that the letters form a sequence of numbers and that you can apply mathematical operations on them.
so...
instead of the whole loop you can get the result by doing letter - 'a'


Asking 2 values, feet and inches, and it converts them to centimeters

This code is pretty compact already so there isn't much room to reduce the size of it. Typically separating the error handling, calculations, and output of content are separated so you may want to look into that for code improvements but that won't make the code any smaller.
Better data sanitation
It's great that you do your best to sanitize user input before you use it. But, there's better ways to go about it. Since
both inputs are expected to be floating point numbers you can use PHP's built in filter_var() with the
FILTER_VALIDATE_FLOAT flag to sanitize the value to a floating point number:
$pies     = filter_var($_REQUEST["pies"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$pulgadas = filter_var($_REQUEST["pulgadas"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);

Combine/remove your IF statements
When you see an IF statement followed by another IF statement that's usually a sign that you could combine the two into one as all of them must be true for the following code to be executed:
if ( !empty($pies) && !empty($pulgadas) && (s_numeric($pies) && is_numeric($pulgadas) ) {

The above line can then be shortened thanks to the better sanitation used above. The checks to is_numeric are no longer
needed since filter_var() will return a number or false which will be caught by the empty() checks. So you can now safely remove them:
if ( !empty($pies) && !empty($pulgadas) ) {

You can eliminate your check to see if $pies >= 0 by passing an extra flag to filter_var() to only allow positive numbers and zero.
if ( filter_var($pies, FILTER_VALIDATE_INT) && $pies >= 0 ) {

becomes
if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {

You also forgot to add this check for $pulgadas.
Other notes
Use constants to store values that will remain the same and are unchangeable
Your variables containing the ratios for converting the measurements are better off set as constants than variables since they will remain the same and are unchangeable. (i.e. constant)
$converPC = 30.48;
$converPlC = 2.54;

becomes (notice the use of all capital letters as that is the expected format of constants in PHP)
define('CONVER_PC', 30.48);
define('CONVER_PLC', 2.54);

Omit closing PHP tag
When the closing tag is the last line of a PHP file you can safely omit and it is the standard practice as set forth by
the PSR-2 coding standard for PHP. There are lots of good reasons to do this.
Use echo over print()
print() is an alias of echo but there are minor differences between the two. Although they don't come into play here, it is the PHP convention to use echo for outputting content.
Unnecessary parenthesis
If your IF statements you have parenthesis around each conditional. That is not necessary. You only need to use them when you need to clarify scope. When there's only one condition there is nothing that needs clarification.
Outcome
This code is untested but should give you the idea of what the comments above mean.
define('CONVER_PC', 30.48);
define('CONVER_PLC', 2.54);
$pies     = filter_var($_REQUEST["pies"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
$pulgadas = filter_var($_REQUEST["pulgadas"], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
if ( !empty($pies) && !empty($pulgadas) ) {
    //Apartado de los pies
    if ( filter_var($pies, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {
        $resultadoPI = $pies*CONVER_PC;
        echo "CONVERSIÓN PIES - CENTÍMETROS
";
        echo "$pies pies son $resultadoPI centímetros

";
    } else {
        echo "Error en pies
";
        echo "Debe introducir un número entero mayor o igual que cero

";
    }
    //Apartado de las pulgadas
    if ( filter_var($pulgadas, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) ) {
        $resultadoPU = $pulgadas*CONVER_PLC;
        echo "CONVERSIÓN PULGADAS - CENTÍMETROS
";
        echo "$pulgadas pulgadas son $resultadoPU centímetros";
    } else {
        echo "Error en pulgadas
";
        echo "Debe introducir un número mayor o igual que cero";
    }
} else {
    print "Para que todo funcione, debe rellenar TODOS los campos del formulario";
}


Before anything, I reckon you should have a look at PEP 8 which is the usual Style Guide for Python Code. Among other things, your names for variables and functions does not follow the lowercase_with_words_separated_by_underscores convention.

In :

def checkAllVersions(self, currentVersion, allHist):
    historyLength = len(allHist)
    for i in range(historyLength):
        if(allHist[i] == currentVersion):
            return False
    return True

this does not correspond to the pythonic way of looping over a container. There's a cleaner way that doesn't involve indices.

def checkAllVersions(self, currentVersion, allHist):
    for e in allHist:
        if(e == currentVersion):
            return False
    return True

As an additional tip, there's a cool way to write this using all or any :

def checkAllVersions(self, currentVersion, allHist):
    return all(e != current version for e in allHist)

Edit:

And there is an even more obvious way to write it and I completely missed it :

def checkAllVersions(self, currentVersion, allHist):
    return currentVersion not in allHist

In :

def loadAllVersions(self, hist):
    historyLength = len(hist)
    l =[]
    for i in range(historyLength):
        if i >= 1:
            l.append(hist[len(hist)-i].get("version"))
    return l

instead of iterating from 0 to historyLength-1 and then consider only values i such that i >= 1, you could just iterate from 1 to historyLength-1. Just use range(1,historyLength).

def loadAllVersions(self, hist):
    historyLength = len(hist)
    l =[]
    for i in range(1,historyLength):
        l.append(hist[len(hist)-i].get("version"))
    return l

However, it seems like something even smarter could be done here.

At the end of the day, my assumption is that what you want to do is just to iterate over hist from the beginning to the end and call .get("version") on each element. This is not what you are currently doing because you are not processing the first element of the list (index is 0 and would correspond to i  = historyLength).

You have more than one way to do it but the most straight-forward solution involves looping over your list in reversed order with reversed :

def loadAllVersions(self, hist):
    l =[]
    for e in reversed(hist):
        l.append(e.get("version"))
    return l

and then, this calls for list comprehension :

def loadAllVersions(self, hist):
    return [e.get("version") for e in reversed(hist)]

It is now time to have a look at def compareVersions(self,parent,componentTarget, write), a much bigger chunk.

First thing I'd like to point out, you do no follow this part of PEP 8 :

  Comparisons to singletons like None should always be done with is or
  is not, never the equality operators.

I'd like you to confirm my assumption about loadAllVersions before going any further.


Showing a unique result based on options selected

I am not familiar enough with JavaScript to write out the code while I am travelling, but I can at least describe a simple algorithm to do so generally in a faster and slightly simpler way. I here assume that you have access to the raw results and don't need to re-interpret them from the collected string.

For each answer we assign a 0 or 1 to the result, and then join them together as a bit mask, by shifting each answer by the 0-indexed numbering of the question it is an answer to. You can then construct an array of all the possible results,
and when you want to know which result a response corresponds to, you can just construct an integer from the above bit mask and use it as an index for the array's result you want. If you have unique results for every response, then this is about as good as you can do (remember you can put a function in the array and call it if you want to do the compilation lazily). If you can construct the results from some kind of pattern, then you can find the right indexes by filtering the indexes with and based bit masked (with not applied to the result if you want the ones which have 0's in those masks).


Just return the data and leave it to the consumer what to do with it. That way, branches becomes a generic data grabber. If you want to have printer functions, keep them separate from the raw command.

Your Promise wrapper appears to expect the output of the branches command. Move the use of lines to the branches function instead.

Also, arrow functions with single arguments can omit the parens.

const promiseExec = (cmd) => new Promise((resolve, reject) => {
  cp.exec(cmd, (err, stdout, stderr) => {
    if (err) reject(err);
    else resolve(stdout);
  });
});

const branchLines = (str) => str.trim().split(os.EOL).map(line => line.trim().replace(REGEX_STAR, ''));

const branches = () => promiseExec('git branch -a').then(res => branchLines(res));

const printBranches = () => branches().then(res => console.log(res));

// Print manually
branches().then(res => console.log(res));

// or have a printer function do it
printbranches();


Yes, on both counts (although putting it in the main package is not).

Typically I would return a logFile from createLogger (calling it newLogger is idiomatic), and defer closing the result.

If you're building a logger to work across your whole app, I'd look at how the standard library does it.

Essentially, create a new package my_app_logger with an initializer which sets up the logger. That way, every package that includes my_app_logger gets the same logger instance.


Merging client names into orders using RxJS

Looks good. Yeah, sometimes APIs are hard to work with.

Instead of the loop clientsData.forEach, you might want to reduce the client data down to an object, where the keys are the client id (ie. index on the id). Then, map through your orders, and use this object to add in the client name. This will be O(N) vs. O(N^2)

I'd also probably use a different object for orders vs. the orders with the name... just to avoid mutation, which I didn't expect... This is obviously more a style question, though. I favor immutable code, especially when it's more functional like this.


Generating double linear sequence in Haskell

Repeatedly sorting is asympotically slower than keeping a sorted data structure, nub takes quadratic time, head . drop (x-1) = (!!x), and try to use library-defined recursion combinators instead of explicitly using recursion.

import qualified Data.Set as S

generateSeq :: [Integer]
generateSeq = unfoldr (fmap foo . S.minView) $ singleton 1 where
  foo :: (Integer, S.Set Integer) -> (Integer, S.Set Integer)
  foo (x, s) = (x, S.insert (2*x+1) $ S.insert (3*x+1) s)

looks up comonad stuff on a hunch

import qualified Data.Set as S
import Control.Comonad

generateSeq :: [Integer]
generateSeq = unfoldr ((fmap . extend . uncurry) foo . S.minView) $ singleton 1 where
  foo :: Integer -> S.Set Integer -> S.Set Integer
  foo x = S.insert (2*x+1) . S.insert (3*x+1)


Design

References are different from pointers in two ways:

they are designed to be aliases to the objects they refer to, so syntactically they are treated with special care;
they cannot be rebound.

You cannot always emulate the first bullet with an optional — for example, there's no general way to make opt.f() call opt.value().f().  You still have to resort to some other syntax like opt->value().  Therefore, my advice is to simply treat opt_ref<T> like an immutable nullable pointer that does not own the referred-to object — don't follow std::reference_wrapper.

Code Review

using type = typename std::reference_wrapper<T>::type;

typename std::reference_wrapper<T>::type is just T.  Also, the standard terminology is value_type.

T& get() { return data.value().get(); }
const T& get() const { return data.value().get(); }
bool has_value() const { return data.has_value(); }
T& value_or(T&& other) const { return data.value_or(other); }

has_value is noexcept.  Why does value_or take an rvalue reference?  To introduce dangling references as in opt.value_or(1)?  Take an lvalue reference instead.

bool operator == (const T& t) { return data.value() == t; }
bool operator == (const std::nullopt_t&) {return !data.has_value(); }

I'm not sure this is the right approach.  The first == compares values (and throws an exception if there is no value), whereas the second == compares the references themselves.  You can imitate the behavior of std::optional:

bool operator==(const opt_ref<T>& a, const opt_ref<T>& b)
{
    if (a.has_value() != b.has_value()) {
        return false;
    } else if (!a.has_value()) { // and !b.has_value()
        return true;
    } else {
        return a.get() == b.get();
    }
}

operator T&() { return data.value().get(); }
operator const T&() const { return data.value().get(); }
operator std::reference_wrapper<T>() { return data.value(); }
operator const std::reference_wrapper<T>() const { return data.value(); }

As I said before: are you sure you want this (especially the implicit conversions to reference_wrapper)?

Other functionalities

Consider:

operator* and operator->;
explicit operator bool;
has_value;
...


How do I compare two integer value hashes?

Here's a version that is a bit more DRY. It also makes use of ruby's default value for hashes, and I threw in a dummy class in order to make the tests actually run.

This could probably be done even better, but one thing you really should try to achieve when writing ruby code (or any code at all, for that matter) is to try not to repeat yourself too much. That's where DRY come in.

class CostCalculation
  attr_accessor :wood, :stone, :gold

  def initialize(reqs)
    self.wood = reqs[:wood] || 0
    self.stone = reqs[:stone] || 0
    self.gold = reqs[:gold] || 0
  end

  def has_resources?(cost)
    report = Hash.new(true)
    cost.default = 0

    attributes.each do |key, value|
      report[:"has_#{key}"] = cost[key] <= value
    end

    if report.values.include?(false)
      report[:has_resources] = false
    end

    report
  end

  def attributes
    { wood: self.wood, stone: self.stone, gold: self.gold }
  end
end

...and here are some specs for it as well:

describe CostCalculation do
  it "has enough resources for something that's free" do
    report = CostCalculation.new({}).has_resources?({})
    report[:has_resources].should == true
  end

  %w[wood stone gold].each do |resource|
    it "does not have enough resources if #{resource} is missing" do
      cost = {resource.to_sym => 1}
      report = CostCalculation.new({wood: 0, stone: 0, gold: 0}).has_resources?(cost)

      report[:has_resources].should == false
      report[:"has_#{resource}"].should == false
    end
  end
end


I created an extension method for DataTable to convert them into a List<T>

public static class Helper
{
    /// <summary>
    /// Converts a DataTable to a list with generic objects
    /// </summary>
    /// <typeparam name="T">Generic object</typeparam>
    /// <param name="table">DataTable</param>
    /// <returns>List with generic objects</returns>
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}

Example:

DataTable dtTable = GetEmployeeDataTable();
List<Employee> employeeList = dtTable.DataTableToList<Employee>();


There's a good article about performance to get your started: Slow Code: Top 5 ways to make your Powershell scripts run faster; at first sight, here are applicable both parts of Problem #2 & #3: Appending stuff:

Appending to files: Export-CSV -Append repeats roughly 133 times (= 4E+6/30E+3 i.e. 4E+6 rows written in chunks of 30E+3 rows each) which could considerably worsen performance for big output file;
Appending to arrays: (heart of the matter) when the += operator is used, it's actually destroying the array and creating a new one (source).

To eliminate appending to arrays, you can use .NET array list object as follows (merely a hint): replace

$output = @() with $output = [System.Collections.ArrayList]::new(), and
$output += $CSVLine with [void]$output.Add($CSVLine).

Note: do not compute one-purpose variable $CSVLine at all; instead, use

[void]$output.Add(
    [pscustomobject]@{
        Key = $json.Register.Key
        CompanyID = $json.id
        Eventtype = $item.type
        Eventdate = $item.date
        Eventdescription = $item.description
    })

Read the remark about the generic List<T> class and Performance Considerations as well:

  In deciding whether to use the List<T> or ArrayList class, both of
  which have similar functionality, remember that the List<T> class
  performs better in most cases and is type safe. If a reference type
  is used for type T of the List<T> class, the behavior of the two
  classes is identical.


It seems you need through and split to do the piping right. You do not need sprintf as you could build the number formatting yourself. You also do not need fs, you do not use it anywhere.

Something like

var through = require('through');
var split = require('split');

var linenum = 0;

function alignRight( s, n )
{
  s = s + "";
  return s.length > n ? s : new Array( n - s.length + 1 ).join(" ") + s;
}

var number = through(function (line) {
  this.queue( alignRight( ++linenum, 6 ) + "\t" + line + "\n"  );
});

process.stdin.pipe(split()).pipe(number).pipe(process.stdout);

Does the trick for me. While it seems overkill, the nice thing is that you can pipe data between functions yourself, not needing to rely on the OS shell.


Complexity Of Determining Tree is balanced?

Your getHeight method could be simpler (and more correct) if it was handling the null case.

int getHeight(Node N) {
    if (N==null) return 0
    return 1 + Max(getHeight(N.L),getHeight(N.R));
}

Also, I think you should have a read at this quite similar question.


Attempt at checking whether two words are permutations

Basic Review

Look below for algorithm ideas:

You are not modifying the input strings. So they should be passed by const reference to prevent accidents:

void checkPermut(std::string const& sentence1, std::string const& sentence2)
                             ^^^^^                         ^^^^^

You don't need to check if a value exists in a map like this:

        if (dict1.find(c) == dict1.end())
        {
            dict1.insert(std::pair<char, int>(c, 1));
        }
        else
        {
            dict1[c] == dict1[c] + 1;
        }

Use operator[] If it does not exist the item will be created (the value is "zero" initialized" and returned as a reference. You can replace the above code with the line:

        ++dict1[c];

Be careful when getting things by reference (accidental modification can happen). Unless you need to modify something, get by const reference.

    for (char const& c : sentence2)
              ^^^^^

But in this case I would get by value:

    for (char c : sentence2)

There is an easy way to make pairs that does not require all the type info:

            std::pair<char, int>(c, 1);

Simpler to write:

            std::make_pair(c, 1); // The function gets the type from
                                  // the parameters and creates the
                                  // correct type of underlying pair.

As a side note. technically you may not want to make the assumption that std::map uses a pair internally. This is why std::map has an internal type value_type so you can use that and not make any assumptions about the type used internally.

 using Map      = std::map<char, int>;
 using MapValue = typename Map::value_type;
 Map  dict1;
 ...
 dict1.insert(MapValue(c, 1));

There is a subtle bug here:

    for (char & c : sentence2)
    {
        if (dict1.find(c) == dict1.end())
        {
            arePermut = false;
            std::cout << "Not permutations." << std::endl;
            break;
        }
        else if (dict1[c] != dict2[c])
        {
            arePermut = false;
            std::cout << "Not permutations." << std::endl;
            break;
        }
    }

You check all the letters from sentence2 are exactly the same as in sentence1. But that may not be enough. You need to check the other way.

    // Assume:
    Sentence1 = "BigZ"
    Sentence2 = "Big";  // Your algorithm will match.

Note most containers are comparable.

There is a subtle bug here:

        if (dict1 != dict2)
        {
            std::cout << "Not permutations." << "\n";
        }
        else
        {
            std::cout << "Not permutations." << "\n";

Note: The operator>> reads a single space separated word. Your code above suggests sentences. Is this what you want?

    std::cin >> somestring1 >> somestring2;

Use std::getline(std::cin, somestring1) to read a line.

This is redundant in main():

    return 0;

Algorithm

We know you can simply compare the containers. But you can optimize this. By subtracting characters from sentence two from the container. If any become negative then you can exit early.

Also do you want to compare space characters? This makes it really hard to have anagram sentences if the word count has to be the same.

bool checkPermut(std::string const& sentence1, std::string const& sentence2)
{
    using Map = std::map<char, int>;
    Map count1;
    Map zero;

    for(auto c: sentence1) {
        if (std::isspace(c) {
            continue;
        }
        ++count1[c];
        zero[c] = 0;
    }
    for(auto c: sentence2) {
        if (std::isspace(c) {
            continue;
        }
        if (--count1[c] < 0) {
            return false; // exit early if we go negative.
        }
        zero[c] = 0;
    }
    return count1 == zero;  // Make sure all letters have reached zero.
}


Translating code numbers to item descriptions in PostgreSQL query

You should put all the mapping between itemId values and whatever constant strings in a separate table (2 columns) and do a join with it.
This allows you to update the mapping (by changing the table content) without even changing the query later on.
(and this is not specific to PostgreSQL, will work with any RDBMS)


Don't make errors a part of your program flow
If an error doesn't cause you to prematurely end your Sub/Function, then it should be handled less severely, or your program needs restructuring. I also caution against using GOTOs. They are sometimes necessary, but they have the potential to cause far more problems than they solve.
This is the only situation in which I regularly use GOTOs in VBA:
    Public Sub DoThing()

        On Error GoTo CleanFail

        ...

        ...

        ...

CleanExit:

        '/ Clean Up
        Exit Sub

CleanFail:

        '/ Error Handling
        '/ Error handling
        '/ Error handling
        Resume CleanExit

    End Sub

Handling Conditions
If you are going to continue your macro anyway, but want to avoid running some code if a condition fails then why not just:
[Check Condition]
If [condition] Then
    DoThing
End If

In the specific case of the Sheets() Collection, you have a number of options.

Option #1: Write a utility function to do the checking for you
    Public Function GetSheet(ByRef targetBook As Workbook, ByVal sheetName As String) As Worksheet
        '/ Tries to return the sheet object.
        '/ If the sheet does not exist, return Nothing

        Dim targetSheet As Worksheet
        On Error GoTo CleanFail
            Set targetSheet = targetBook.Worksheets(sheetName)
        On Error GoTo 0

CleanExit:
        Set GetSheet = targetSheet
        Exit Function

CleanFail:
        On Error GoTo 0
        Err.Clear
        Set targetSheet = Nothing
        Resume CleanExit

    End Function

And now your code can be structured like so:
    Dim targetSheet As Worksheet
    Set targetSheet = GetSheet(ThisWorkbook, sheetName)
    If Not targetSheet Is Nothing Then
        ' do stuff here (don't do it if SheetName doesn't exist)
    End If

Much cleaner.

Option #2: Use a data structure that supports .Exists()
For VBA, this would be a Dictionary. You'll need to set a reference to the Microsoft Scripting Runtime library in Tools --> References. Then do the following:
    Dim sheetnames As Dictionary
    Set sheetnames = New Dictionary

    Dim sheetName As String
    Dim sheetObject As Worksheet
    For Each sheetObject In ThisWorkbook.Sheets()
        sheetName = sheetObject.Name
        sheetnames.Add sheetName, sheetName
    Next sheetObject

    If sheetnames.Exists("Some sheet name") Then
        ' do stuff here (don't do it if SheetName doesn't exist)
    End If

Option #3: Restructure your program to make the check redundant
I don't know if this is a good idea for your code. I'd have to know more about its' wider purpose, structure and context, but it's always worth thinking about.


Calculate sum of multiple series within array

int pairs[MAXN][2]; wastes memory. You don't need to read all the queries at once:
  for(int i = 0; i < q; i++)
  {
      cin >> L >> R;
      cout << sumBetween(L - 1, R - 1) << endl;
  }

works equally well. Besides, the problem statement doesn't say how many queries are there; it could be way more than the size of the array.

Your feeling that you use the wrong algorithm is well founded. Bruteforcing is almost always wrong. Look at the underlying math first. I don't want to spell out everything, just a couple of hints:

\$1*a_{L} + 2*a_{L+1}+ ... + 2^{R-L}*a_{R} = \dfrac{2^L*a_{L} + 2^{L+1}*a_{L+1}+... + 2^R*a_{R}}{2^L}\$

The numerator above is a difference of two partial sums of the \$2^n*a_{n}\$ sequence.

\$1000000007\$ is a prime number, so division by \$2^L\$ modulo 1000000007 is a multiplication by a multiplicative inverse of 2 modulo 1000000007 (which is trivial to find) to the same power.

I hope it is enough to get you going in the right direction. You should be able to answer each query in constant time.


If you perform all calcuclations dynamically your method becomes a simple few lines long loop:

private IEnumerable<DateTimeRange> GetYearsBetweenDates(DateTime startDate, DateTime stopDate)
{
    for (int i = startDate.Year; i <= stopDate.Year; i++)
    {
        yield return new DateTimeRange
        (
            start: new DateTime(i, startDate.Month, startDate.Day),
            end:
             i == stopDate.Year
             ? new DateTime(i, stopDate.Month, stopDate.Day).AddYears(1)
             : new DateTime(i, startDate.Month, startDate.Day).AddYears(1)
        );
    }
}

So what I have I changed?

The method returns an IEnumerable<T> and uses the yield return which makes it deferred (this means it is executed only if enumerated).

The T is a new struct that is easier to understand than a Tuple:

struct DateTimeRange
{
    public DateTimeRange(DateTime start, DateTime end)
    {
        Start = start;
        End = end;
    }
    public DateTime Start { get; }
    public DateTime End { get; }
}

To get all dates you call it with ToList or ToArray

var dates = GetYearsBetweenDates(startDate, endDate).ToList();

or you put it in a foreach loop

foreach(var range in GetYearsBetweenDates(startDate, endDate))
{
    // do something
}

You can also exagerate and make it pure LINQ method without any manual loop but personaly I think the for loop looks better:

private IEnumerable<DateTimeRange> GetYearsBetweenDates3(DateTime startDate, DateTime stopDate)
{
    return Enumerable.Range(startDate.Year, stopDate.Year - startDate.Year + 1)
        .Select(x => new DateTimeRange
        (
            start: new DateTime(x, startDate.Month, startDate.Day),
            end:
             x == stopDate.Year
             ? new DateTime(x, stopDate.Month, stopDate.Day).AddYears(1)
             : new DateTime(x, startDate.Month, startDate.Day).AddYears(1)
        ));
}

What else?

var list = new List<Tuple<DateTime, DateTime>>();

You should always choose meaningful names for all variables. You did it well for the others. This could have been results or dates.

var oneYear = TimeSpan.FromDays(365);

It's safer to use the AddYear(1) method rather then hardcoding the number. Especially if you don't want to care about leapyears.


I suggest you should use a configuration array like this:

 $config = [
      ip => FILTER_VALIDATE_IP,
      email=> FILTER_VALIDATE_EMAIL
 ]

and simplify the code like this:

if(in_array($config, $data_type)) {
     if($filter_VAR($data, $config[$data_type]) {
          $output = $data;
     }
}

In your code, length is checked only if both min and max are set. Is it the expected behavior? In some cases, only min or max checks are required.
Generally, you should avoid repeating code, in favor of calling functions. This makes it more readable. Plus, you can create test cases for small functions with predictable results, rather that a big complicated thing.
With security I have no idea what this function is designed to protect against.


Code structure

The most common and widely accepted structure found in Python scripts from a high-level point of view looks something like:

# imports
import
...

# functions and classes, aka "library code"
class Foo:
    ...

def bar(batz):
    ...

if __name__ == "__main__":
   # part that is supposed to be run as script
   ...

Your code on the other hand does not follow this structure since there is some script code at the top (start = time.time()), then come your functions, followed by another block of script code. I highly recommend to follow that structure.

Further reading: Explanation of if __name__ == "__main__": from the official Python documentation.

The code itself

bouncy

The most striking aspect of bouncy from a stylistic point is the capital N as parameter name that goes against the official Style Guide for Python Code (often just called PEP8). Usually parameter and variable names are written in snake_case, e.g. small letters, possibly separated by underscores.

With that said, let's look at the actual algorithm:

number = list(str(N))
n1 = list(str(N))
n2 = list(str(N))

Lots of repeated code here. An easy way out would be to do the conversion once, and copy the results afterwards. This can be done using slicing like n1 = number[:], the list constructor n1 = list(number) or the copy module. Also, sorted would create a copy indirectly, so no need to do this manually (see the next point).

The next thing you do in your code is sorting those lists. Once ascending, then descending. Since the second one should by definition be the mirror of the previous one, you can use slicing again to avoid that second sort.

sorted_number = sorted(number)  # <- also does a copy

Oh, and did you know that sorted does work on strings as well and simply returns a new list? (sorted_number = sorted(N))

You could also use the result of the condition directly as return value of your function.

With some other minor changes you might end up with something like

def is_bouncy(number):
    '''Function determines whether arbitrary number N is a bouncy number.'''
    digits = list(str(number))
    sorted_digits = sorted(digits)
    return digits != sorted_digits and digits != sorted_digits[::-1]

find

find is almost as straightforward as it gets. I would advise to change the variable name bou to bouncy or n_bouncy now that the checking function is called is_bouncy. IMHO current would also likely be a better name for start. Also find_bouncy_boundary, maybe even with an optional "expected bounciness percentage" might be worth a thought.

From an optimization point of view, you could also start from 1000 if you're only looking for that 99%, since the task description tells you that there are exactly 525 bouncy numbers below 1000 ;-) But there is likely not much to gain from that.

The rest

Now all there is left to do is to take the spread out script code, wrap it up in if __name__ == "__main__":, and collect it at the bottom of the script:

if __name__ == "__main__":
    start = time.time()
    print(find())
    print(time.time() - start)

If the script part becomes more complex, this part is often put into a separate main() method.


Simplicity

To rotate a string, only the string itself and the offset of rotation are needed.

A class is a way to store data in an orderly manner, but for the task of rotating a string, you do not need such storage.

In Java not needing a class is signalled by the use of static methods.

Also, using  String.substring you can avoid the manual looping. In short all your program can be reduced to:

public static String rotate(String s, int offset) {
  int i = offset % s.length();
  return s.substring(i) + s.substring(0, i);
}

The example usage is also simplified, as you do not need to build a new class:

public static void main(final String... args) {
  for (int i = 0; i < 6; i++) {
    System.out.println(rotate("abcdefg", i));
  }
}

The drawback of this approach is that it may be slower and/or use more memory, but unless you want to rotate a string tens of millions of times per second it should not matter.


SQLite UPDATEs for persons and a subclass

Schema

I'm glad to see that you defined a foreign key.  However, I find it odd that you specified NO ACTION, since that means that SQLite will not enforce your data integrity.  I would expect either RESTRICT or CASCADE.

Your approach to inheritance is closest to Concrete Table Inheritance.  I'm not convinced, though, that such a complication is justified.  Single Table Inheritance would be much simpler.  In fact, I'm not even convinced that only mechanics should be allowed to have nicknames, so perhaps no inheritance at all would be the most appropriate design.

Wrapper

The effort to ensure that the connection gets closed is clumsy.  Since Java 7, the preferred way to close a connection is using a try-with-resources block.  The Statement should be closed using try-with-resources as well, which you neglected to do.

But you really should not be opening a new connection for every query, because there is a large overhead involved in establishing a connection.  Once you make the connection explicit, much of the motivation for having any wrapper at all on top of JDBC disappears.

(There is a middle ground: connection pooling.  With connection pooling, "closing" the connection doesn't actually close it, but merely releases it into a pool so that it can be reused.)

The UPDATE queries

Splitting "UPDATE " into a separate string constant is weird and unhelpful.

You have SQL injection vulnerabilities due to the way you misused the JDBC API.  The statements should use placeholders:

"UPDATE Pessoa SET telephone=?, celular=?, nome=? WHERE CPF=?"

To update a Mecanico, you need to make updates to two tables.  The two updates should probably be grouped into one transaction, so that either both updates succeed or neither update has any effect.


Mutability, ST and pure code

Whenever you can use ST instead of IO use ST. ST limits the effects that can happen, and runST (or its variants) make sure that no STRefs (or variants) leave the ST. That is, you can always embed a ST s a where you want to use a. You cannot do the same for IO a.

Unfortunately, update has \$\mathcal O(n+m) \$, and therefore every call of swap is \$\mathcal O(n) \$. That's not a problem when you have a single Vector, e.g.

V.foldr (\x a -> x + 2 * a) 0 . V.map sin . (// foo) . fromList

will generate a single vector due to fusion, not three intermediates. Depending on the used vector version and optimization level, you might even end up with a single loop and no generated vector at all. So immutability doesn't prevent optimizations.

Quick Sort on the other hand really needs mutability. So a ST variant (STUArray or MVector) is more appropriate.

Interface

Now that we know that it's fine to use an ST variant, let's have a look at your code. First we look at qsort's type:

qsort :: (IOArray Int Int) -> Int -> Int -> IO ()

An end user has no idea what Int and Int shall be. They want to sort an array, not ponder the right arguments. Therefore, we add a variant that doesn't use that arguments:

import Control.Monad
import Control.Monad.ST
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as M

sort  :: Ord a => V.Vector a -> V.Vector a
sort v = -- left as exercise, should use sort'

sort' :: Ord a => M.STVector s a -> ST s ()
sort' v = qsort v 1 (M.length v)

This interface is easy to use and hard to get wrong. I use the vector variants since I'm more familiar with those, but the same holds for STArray. Note that I relaxed the Int to Ord a => a`.

Internals

Next, we have a look at qsort itself. I'll keep its type for now. First of, instead of

if condition then return () else action

use

when (not condition) action

After all, return does not return prematurely, which can be misleading to Haskell newcomers. Next, try not to shadow Prelude names like min and max. Let's call the arguments lower and upper instead.

Furthermore, you call the value at an index arr_idx. That's misleading. And p is usually used as predicate, so let's call it piv instead. And final_i is just the new midpoint we found with our piv. We end up with.

qsort :: Ord a => (IOArray Int a) -> Int -> Int -> IO ()
qsort arr lower upper =
    when (upper - lower >= 1) $ do
        piv <- readArray arr lower
        midpoint <- foldM (partitioner p) (lower+1) [(lower+1)..upper]
        swap lower $ midpoint - 1
        qsort arr lower   (midpoint - 2)
        qsort arr final_i upper
    where
        swap i j = do
            arr_i <- readArray arr i
            arr_j <- readArray arr j
            writeArray arr i arr_j
            writeArray arr j arr_i

        partitioner piv i idx = do
            value <- readArray arr idx
            if value > piv then
                return i
            else do
                swap i idx
                return $ i+1

Exercise: Try to rewrite qsort with M.Vector or even Data.Vector.Unboxed.Mutable (the latter only needs an additional constraint).

Bottom line

Other than that your mutable code looks fine. I would change swap slightly so that there is only one temporary element, though:

        swap i j = do
            tmp <- readArray arr i
            readArray arr j >>= writeArray arr i
            writeArray arr j tmp

That's personal preference.


JavaScript function names should start with a lowercase character, and "staircase" is one compound word in English.

Since every line is nearly the same, and only one character changes at a time, you should take advantage of that and use an array as a buffer.

function staircase(n) {
    var line = Array(n + 1).fill(' ');
    line[n] = '\n';
    for (var i = n - 1; i >= 0; i--) {
        line[i] = '#';
        process.stdout.write(line.join(''));
    }
}


Yes, there's a shorter (pythonic) way to do this using set comprehensions:

d = {
    'ABC' : {'0' : [(1,0.5), (2, 0.25)], '1' : [(1,0.4), (3,0.35)]},
    'DEF' : {'1' : [(1,0.5), (4, 0.15)], '2' : [(2,0.3), (3,0.25)]},
    'GHI' : {'0' : [(3,0.2), (4, 0.05)], '2' : [(2,0.2), (2,0.25)]},
}
print {j for i in d.itervalues() for j in i}
# set(['1', '0', '2'])

Then if you just want a list object you can use list() to convert the set to list.

More, in your example you could just make keys2 a set to begin with and call keys2.add instead of extend.

And some benchmarks from your solution, mine and other answers:

import timeit
from itertools import chain

def m1(d):
    return {j for i in d.itervalues() for j in i}

def m2(d):
    keys2 = []
    for small_d in d.itervalues():
        keys2.extend(small_d.keys())

    return set(keys2)

def m3(d):
    return set(chain.from_iterable(d.itervalues()))

def m4(d):
    keys2 = set([])
    for small_d in d.itervalues():
        keys2.update(small_d.keys())
    return keys2

d = {
    'ABC': {'0': [(1, 0.5), (2, 0.25)], '1': [(1, 0.4), (3, 0.35)]},
    'DEF': {'1': [(1, 0.5), (4, 0.15)], '2': [(2, 0.3), (3, 0.25)]},
    'GHI': {'0': [(3, 0.2), (4, 0.05)], '2': [(2, 0.2), (2, 0.25)]},
}

print(timeit.timeit(setup='from __main__ import m1, d', number=100000000))
print(timeit.timeit(setup='from __main__ import m2, d', number=100000000))
print(timeit.timeit(setup='from __main__ import m3, d', number=100000000))
print(timeit.timeit(setup='from __main__ import m4, d', number=100000000))

0.00136395591689003
0.0012866411345431158
0.0011429587956683193
0.0011374851827588035


View model with properties that represent years and months

You can use a format string to ensure that there are at least 2 digits in the format without having to check first.  The format: {0:00} ensures there are at least 2 digits, but allows for more.  It will prefix 0 to any single-digit input.

string.Format also has an overload which takes in an IFormatProvider, so my personal preference is just to collapse that into the string.Format call.  It also happens to line up nicely :)

With that, you can create a method with appropriate parameters which can handle both cases:

  public IEnumerable<SelectListItem> Years2 { get { return BuildList (1900, 112); } }
  public IEnumerable<SelectListItem> Months2 { get { return BuildList (1, 12); } }

  public IEnumerable<SelectListItem> BuildList (int start, int count)
  {
     return new SelectList (
         Enumerable.Range (start, count)
         .OrderByDescending (val => val)
         .Select (val => new SelectListItem
         {
            Value = val.ToString (CultureInfo.InvariantCulture),
            Text = string.Format (CultureInfo.InvariantCulture, "{0:00}", val)
         }
     ), "Value", "Text");
  }

Note: I suffixed my properties with 2 so I could run them side-by-side and compare results to be sure I didn't miss anything.

Note2: as Jesse suggests, you should ideally cache the results.


Optimizing MD5 OpenSSL Implementation in C for Precomputed Hash

I'll start with a review of your current code before suggesting possible performance
improvements.

Various comments in your code do not add information and can be removed, for example

//------------------------------Main Function------------------------//
int main()

free(string); //free string

exit(EXIT_SUCCESS); //Program Ends

Always use curly braces { } with if-statements, even if the if or else part consists only
of a single statement. That helps to avoid errors if the code is edited later.

Declare variables at the narrowest scope where they are used, and not at the top
of the function. For example

FILE *infile = fopen("file.txt", "r");
if (infile == NULL) {
    exit(EXIT_FAILURE);
}

FILE *outfile = fopen("MD.txt","w");
if (outfile == NULL) {
    exit(EXIT_FAILURE);
}

or

for (int md5 = 0; md5 < MD5_DIGEST_LENGTH; md5++) { ... }

Declaring md5 at the top does not increase the performance.

Some variable names can be improved (of course this is partially opinion-based):

char *string is actually the current line.
size_t len is not the length of the current string,
but the capacity of the buffer (re)allocated by getline().
ssize_t read is – strictly speaking – not the number of bytes read into the
buffer because it excludes the NUL character.
int md5 is not an MD5 value but an index into the buffer containing the
MD5 hash.
I would rename unsigned char result[MD5_DIGEST_LENGTH] to md5hash.

Fix compiler warnings:

MD5(string, strlen(string), result);
// Passing 'char *' to parameter of type 'const unsigned char *' converts between pointers to integer types with different sign

You already use different exit codes to indicate success or failure of the program,
which is good. In addition, it is helpful to print some message (to standard error)
in the error case.

According to the C11 standard, the declaration of main should be one of

int main(void) { /* ... */ }
int main(int argc, char *argv[]) { /* ... */ }

(see for example What should main() return in C and C++?
on Stack Overflow). The final return statement can be omitted, there is an implicit
return 0.

Performance improvements

After reading a line from the input file, the string is traversed twice:

while ((read = getline(&string, &len, infile)) != -1) {
    string[strcspn(string, "\n")] = 0; // Remove newline '\n'
    MD5(string, strlen(string), result);

    // ...
}

First to find a terminating newline character, and then again to determine the length.
This is not necessary because getline() returns the number of characters written to
string, i.e. a newline character can only be at position read - 1:

while ((read = getline(&string, &len, infile)) != -1) {
    // Remove trailing newline character
    if (read > 0 && string[read - 1] == '\n') {
        read -= 1;
        string[read] = 0;
    }

    MD5(string, read, result);

    // ...
}

However, the impact of this change depends on the line length, and I could not observe
a significant difference in my test.

In order to find further performance bottlenecks, I profiled the program now with
Xcode/Instruments (using the input file generated by ./crunch 7 7 1234567890)

This immediately revealed that most of the time is spent in fprintf():

Possible reasons are:

String formatting is slow.
All stdio print operations are thread-safe, and therefore have to aquire and release
locks for each call.

The solution is to:

Write a custom function for converting the MD5 hash to a hex string.
Call printf for the entire string instead of each single byte so reduce the number
of function calls.

On my computer (a 1.2 GHz Intel Core m5 MacBook) this reduced the time for processing
the above file from 24.5 seconds to 4.4 seconds.

Putting it together

With all those modifications, we have

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>

// Format the data as a hexadecimal string. The buffer must have
// space for `2 * length + 1` characters.
const char *hexString(unsigned char *data, size_t length, char *buffer) {
    const char *hexDigits = "0123456789abcdef";
    char *dest = buffer;
    for (size_t i = 0; i < length; i++) {
        *dest++ = hexDigits[data[i] >> 4];
        *dest++ = hexDigits[data[i] & 0x0F];
    }
    *dest = 0;
    return buffer;
}

int main(void) {
    FILE *infile = fopen("file.txt", "r");
    if (infile == NULL) {
        perror("Cannot open input file");
        exit(EXIT_FAILURE);
    }
    FILE *outfile = fopen("MD.txt","w");
    if (outfile == NULL) {
        perror("Cannot open output file");
        exit(EXIT_FAILURE);
    }

    // Read file line-by-line
    char *line = NULL;
    size_t linecap = 0;
    ssize_t lineLength;
    while ((lineLength = getline(&line, &linecap, infile)) != -1) {
        if (lineLength > 0 && line[lineLength - 1] == '\n') {
            // Remove newline character
            lineLength -= 1;
            line[lineLength] = 0;
        }

        // Compute MD5 hash
        unsigned char md5hash[MD5_DIGEST_LENGTH];
        MD5((unsigned char*)line, lineLength, md5hash);

        // Print hash as hex string
        char hexBuffer[2 * MD5_DIGEST_LENGTH + 1];
        fputs(hexString(md5hash, MD5_DIGEST_LENGTH, hexBuffer), outfile);
        fputc('\n', outfile);
    }
    free(line);

    // Close output files
    fclose(infile);
    fclose(outfile);
}

Further suggestions

The names of input and output file are compiled into the program, which makes it inflexible. Possible alternatives are

Pass the file names as arguments on the command line, or
Make your program read from standard input and write to standard output.

Implement a -h option to show a short help/usage of the program.


Setting value of controller controls for domain objects with Reflection

Is my use of Java Reflection an OK design?

Well, no, the usage of reflection is usually an indication of bad design. Honestly, it is almost always. Actually, you have to change the question and ask, when is it okay, to use reflection. The answer is something similar like this: Use reflection, when you do not know how a class looks like during runtime. But this is your code, so, why would you increase complexity and make your code more error prone?

In general, I have some worries, when I read the code:

@Node(name = "lastNameField", type = TextField.class)
private StringProperty lastName = new SimpleStringProperty();

Now, it might be a language or a definition subject, but if Employee is a domain model, it must not have dependencies to the view layer, at least no direct dependencies.

@Edit(controller = EmployeeController.class)
public class Employee extends Item {

The Employee itself is in control, of who controls itself. Shouldn't you tell the EmployeController, which model it shall edit?

Double-clicking on a ListCell would call .edit() on the domain object.

Same thing. The presentation code calls the domain object, then, the domain objects calls someone and says "someone wants to edit me". If I understood it correctly.

There's some other fishy stuff, but I'll conclude now, because in my opinion there are some problems even without the reflection stuff: It seems like an over engineered approach for an easy problem. Or: It looks like the solution of a problem, which probably isn't even a problem. It certainly is, from my point of view, the wrong tool for "the problem". The usage of reflection makes maintaining the code harder and more error prone, at least in my experience. The usage of annotations, too, by the way.

I'd suggest to take a step back to the solution before you implemented reflection and analyze what object oriented principles are violated (e.g. SOLID, coupling, cohesion,...) and what patterns can help you get rid of those problems. Now, that's the major point: Ask what design patterns help you get rid of your design problems, do not ask would reflection get rid of the design problems?.

I recommend fowler's web page about gui architectures: https://martinfowler.com/eaaDev/ (presentation patterns). It's not exactly a "good read", but it certainly is educational. It helps you to understand, which presentation patterns suits your application best and gives you some guidelines about how to implement you presentation layer.


Is this the right way to space four news blocks right from each other?

I wouldn't say that there's a right or a wrong way to do it.  The only problem with what you're doing is that it only works well when you have a device that is wide enough to display all of those items on one line (ie. it doesn't work so well for handheld devices).

My recommendation would be to use the CSS multi-column module, which is responsive by default without having to use media queries.

http://jsfiddle.net/cTM3L/1/

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

Lorem ipsum dolor sit amet, consectetur adipisicing elit

fasdfasf

The CSS:

@import url(reset.css);
 body {
    background: url("../img/bg.jpg") repeat-x;
}
#wrapper {
    margin: 0 auto;
}
#header {
    height: 70px;
}
#logo img {
    float: left;
    margin-top: 20px;
}
#headNews {
    margin-top: 20px;
    -webkit-columns: 242px;
    -moz-columns: 242px;
    columns: 242px;
    -webkit-column-gap: 10px;
    -moz-column-gap: 10px;
    column-gap: 10px;
    list-style: none;
    padding-left: 0;
}
.headNewsItem {
    margin-right: 4px;
    width: 242px;
    -webkit-column-break-inside: avoid;
    page-break-inside: avoid; /* Moz is weird */
    break-inside: avoid;
    margin-top: 10px;
}
.headNewsItem:first-child {
    margin-top: 0;
}
.headNewsItem a, .headNewsItem img {
    display: block;
}
.textContainer {
    font-family: Arial;
    line-height: 21px;
    font-size: 14px;
    color: #c8cbcb;
    height: 40px;
    padding: 10px 15px;
    background-image: linear-gradient(#262828, #1c1e1e);
}
#midSection {
    width: 100%;
    margin-top: 20px;
    background-color: #FFF;
}

There's quite a few other things I would change here, but most of them are not relevant to the requested reviewed.  Just make sure you're using the most specific tag that appropriately describes your content: avoid using div for everything (check out some of those HTML5 tags you seem to have missed such as header, figure/figcaption, aside, etc.).  Also, there are better ways to clear floats than to use more floats.


Program to check if a date is valid or not

Good work! While there is certainly room for improvement, it is good that you stuck it out and discovered a solution on your own.

def monthcheck(month):
    if month > 0 and month <= 12: ## If month is between 1 and 12, return True.
        return True
    else:
        return False

Can be more succinctly written as

def monthcheck(month):
    return 0 < month <= 12

While writing comments for practically every line of code can help you learn, and is a good way to keep track of where you are when working through pseudocode, don't just write what the code already told you.
PEP 8 - the style guide for Python - recommends using snake_case for naming functions, so monthcheck would become month_check.
What happens if I input "test" when asked for a date? The program crashes. It's a good idea to validate that any input from the user is in the format you expect.
The program asks for input in the format mm/dd/yyyy but will accept m/d/y, which probably isn't desired.
Don't compare explicitly to True / False

if monthvalidity == True and dayvalidity == True and yearvalidity == True:

Can be more easily read if it is written as

if monthvalidity and dayvalidity and yearvalidity

daycheck has several locations in which it could be improved. You could use a dictionary (as heather does), but if you haven't learned about those yet, you can still improve the algorithm.

Python's in operator can also check if a value is in a list, so instead of looping over monthlist1 and monthlist2, you can just check if month in monthlist1.
Since monthlist1 doesn't really describe what is in the variable, and I am having difficulty coming up with a better name, I would just inline the list with if month in [1, 3, 5, 7, 8, 10, 12] and add a clarifying comment.

Don't be afraid to use natural sounding variable names. I believe monthcheck is better named is_month_valid.
What about negative numbers? 1/1/-111 is apparently a valid date. This might be desired, but probably deserves a comment.
Converting numbers to strings to determine the size is generally not a good idea, and can get you into trouble in more complex cases with floats / doubles. I would prefer the check 1 <= year < 10000.
There is no need to have str() around an input function, input returns a string already.

Python, as a "batteries included" language, has a feature that can do this for us! In production code, this is what you should use.

from datetime import datetime

def main():
    user_input = input('Enter the date in mm/dd/yyyy format: ')

    try:
        datetime.strptime(user_input, '%m/%d/%Y')
        print('The date {} is valid.'.format(user_input))
    except ValueError:
        print('The date {} is invalid'.format(user_input))

if __name__ == '__main__':
    main()

This was rather long, but don't worry! It is completely normal to get a lot of feedback when you are starting out. The more you code, the more natural it becomes.


Here's a more efficient solution:

# an example data frame
results <- data.frame(user = c(1,2,3,4,3,4,2,1,3,4,6,7,7), a = 1)

# the solution
results[duplicated(results$user), ]

How it works: duplicated returns a logical vector indicating whether a value was also present at a preceding position in the vector (for each value of results$user).

This logical index is used to choose the appropriate lines of the orginal data frame. This is achieved by using this vector as the first argument for [ and using an empty second argument (to select all columns).

The result:

   user a
5     3 1
6     4 1
7     2 1
8     1 1
9     3 1
10    4 1
13    7 1


Unit testing extension for equality testing

It's perfectly OK. As an example SharpTestEx is a whole library with such an extensions.


As I didn't get any answer, I propose the following improvements.

First I didn't change the functions create_circle and coords_circle.

I found a more satisfying solution for the display function. Indeed, I create a class Display and implement the former display function in its __init__ method.

class Display:
    """Define the window used to display a simulation"""

    def __init__(self, balls, step, size):
        """Initialize and launch the display"""
        self.balls = balls
        self.step = step
        self.size = size

        self.window = tk.Tk()
        self.canvas = tk.Canvas(self.window, width=self.size, height=self.size, bg="black")
        self.canvas.pack()
        self.canvas.focus_set()
        self.drawing = self.create()
        self.started = False

        start_button = tk.Button(self.window, text="Start", command=self.start)
        stop_button = tk.Button(self.window, text="Pause", command=self.stop)
        start_button.pack()
        stop_button.pack()

        self.window.mainloop()

In this way, I can define the animate and stop functions as methods of the class Display rather than inside __init__.

The objects balls, step, size, window, canvas, drawing, start_button and stop_button become attributes of the class Display. So I don't need to put them in arguments of create and update methods.

def create(self):
    """Create a drawing item for each solver.Ball object

    return a dictionary with solver.Ball objects as keys and their circle drawings as items
    """
    return {ball: self.canvas.create_circle(ball.position[0], ball.position[1], ball.radius, fill="white") for ball in self.balls}

def update(self):
    """Update the drawing items for a time step"""
    solver.solve_step(self.balls, self.step, self.size)
    for ball in self.balls:
        self.canvas.coords_circle(self.drawing[ball], ball.position[0], ball.position[1], ball.radius)
    self.canvas.update()

Moreover, the start button calls the start method that calls the animate method only if the value of started is False. Thus, we don't have the bad behaviour raised in the question (need to push the pause button twice after pushing the start button twice).

def start(self):
    """Start the animation"""
    if not self.started:
        self.started = True
        self.animate()

def animate(self):
    """Animate the drawing items"""
    if self.started:
        self.update()
        self.window.after(0, self.animate)

def stop(self):
    """Stop the animation"""
    self.started = False

You'll find the complete code here.


Calculating a page size to execute a subset of jobs at a time

There are a few ways which this method could be made more readable.

The first if-statement is negated, making the control flow slightly more complicated; the statement can be negated (again) to clarify the flow:

private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)
            => totalNumberOfJobs % deleteBatchSizeMax == 0
            ?  totalNumberOfJobs / deleteBatchSizeMax
            : (totalNumberOfJobs / deleteBatchSizeMax) + 1;

Secondly, the statement is currently checking if totalNumberOfJobs is an even divisible of deleteBatchSizeMax. The computation totalNumberOfJobs / deleteBatchSizeMax is used three times. When (double)totalNumberOfJobs / (double)deleteBatchSizeMax doesn't contain a decimal place, then it implies totalNumberOfJobs % deleteBatchSizeMax == 0, and vice-versa.

To simplify the pattern, consider the following: when A divides B with no remainder, then divide it, otherwise divide it and add one. Therefore, Math.Ceiling can be used:

private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)
    => (int)Math.Ceiling((double)totalNumberOfJobs / (double)deleteBatchSizeMax);

The Math.Ceiling function "rounds" up to positive infinity; so 4.5 -> 5, 4.00001 -> 5 and so on. This emulates the original loop condition.

Edit: the second double conversion is not required as it is upcasted to a double.

private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)
    => (int)Math.Ceiling((double)totalNumberOfJobs / deleteBatchSizeMax);


Norms, rules or guidelines for calculating and showing ETA/ETC for a process

Your approach looks reasonable if one makes the assumption that the average time for item processing is roughly the same for each item.

Updating the UI once a second is ok, updating it more often does not make much sense since the typically user cannot follow that visually either. If this really becomes a bottleneck, you might consider to add some code like

if(timeWhenUIWasUpdated < currentTime-1.0)
{
    this.Text = String.Format(/*...*/);
    timeWhenUIWasUpdated = currentTime; // unit: seconds
}

(you will have to introduce those two variables timeWhenUIWasUpdated and currentTime into your code).

Of course, when your progress event gets called more often (for example, several 10,000s a second), you will have to think about further optimizations, since even without the UI you will have to do some time value management or calculations. But as long as this is not the case, keep things simple.

This one here

if (avrage.Count > 30)
     avrage.RemoveRange(0, 10);

looks like premature optimization, I guess

     avrage.RemoveRange(0, 1);

will give you a more smooth behaviour (and I guess you won't notice the difference in running time in most real-world cases).

Furthermore, for testing purposes, you may consider to refactor the average-time calculation into a SlidingAverageCalculator class, separating the logic fully from the background worker and the UI display. This will make it really easy to write unit tests for that part of the code.


Chop off trailing newline for Swift's NSAttributedString

Your method works correctly, as far as I can see.

For a read-only computed property, you don't need to enclose the
getter method in get {  }:

var trailingNewlineChopped: NSAttributedString {
    guard self.length > 0 else {
        return self
    }
    let lastCharRange = NSMakeRange(self.length - 1, 1)
    let lastChar = self.attributedSubstringFromRange(lastCharRange).string
    guard lastChar == "\n" else {
        return self
    }
    let mutableCopy = NSMutableAttributedString(attributedString: self)
    mutableCopy.deleteCharactersInRange(lastCharRange)
    return mutableCopy
}

Checking for a trailing newline character can be done with
the hasSuffix() method on the underlying string.

Instead of creating a mutable copy and removing the last character,
you can extract the first length-1 characters instead.

The method then becomes

var trailingNewlineChopped: NSAttributedString {
    if self.string.hasSuffix("\n") {
        return self.attributedSubstringFromRange(NSMakeRange(0, self.length - 1))
    } else {
        return self
    }
}

You can even omit the implicit self., but that is a matter of personal
preference:

var trailingNewlineChopped: NSAttributedString {
    if string.hasSuffix("\n") {
        return self.attributedSubstringFromRange(NSMakeRange(0, length - 1))
    } else {
        return self
    }
}

NSMakeRange will not be available in Swift 3 anymore, so it could
be a good idea to start replacing that by
NSRange(location:, length:) in your code.

Update: Swift 3 changed how Objective-C methods are imported
into Swift:

extension NSAttributedString {

    var trailingNewlineChopped: NSAttributedString {
        if string.hasSuffix("\n") {
            return self.attributedSubstring(from: NSRange(location: 0, length: length - 1))
        } else {
            return self
        }
    }
}


Building a list using append in a for loop is not only slow, it is an anti-pattern. Use list comprehensions instead:

searclist = [cell.internal_value for i in range(len(sheetlist)) for row in wb[sheetlist[i]].iter_rows() for cell in row if cell[1] == 'B']

This is not as readable as the previous form, lets try to fix that by iterating over sheet names directly instead of using an index, it will also speed things up.

searclist = [cell.internal_value for sheet in sheetlist for row in wb[sheet].iter_rows() for cell in row if cell[1] == 'B']

Not entirely better. In such cases you can try using a generator: simply wraps your loops into a function that yield results instead of appending them in a list:

def files_in_xl(filename):
    workbook = load_workbook(filename, use_iterators=True)
    for sheet in workbook.get_sheet_names():
        worksheet = workbook[sheet]
        for row in worksheet.iter_rows():
            for cell in row:
                if cell[1] == 'B':
                    yield cell.internal_value

You can then easily create searclist using:

searclist = list(files_in_xl('test.xlsx'))

But we’re not done. First off, you iterate over that list again to remove file extensions; why not do that when getting the file name:

yield os.path.splitext(cell.internal_value)[0]

Second, openpyxl documentation suggest using read only mode for reduced memory footprint:

def files_in_xl(filename):
    workbook = load_workbook(filename, read_only=True)
    for sheet in workbook.get_sheet_names():
        worksheet = workbook[sheet]
        for row in worksheet.rows:
            for cell in row:
                if cell[1] == 'B':
                    yield os.path.splitext(cell.value)[0]

Third, you will use searclist only to check if values are in there. Lists are terrible for that purpose since the in operation is \$O(n)\$. Use sets instead, this operation is \$O(1)\$:

patterns = set(files_in_xl('test.xlsx'))  # Renamed searclist to patterns

Now on to your search function; which is poorly named since it both search and copy:

You used os.path.splitext previously to separate the filename from its extension and here you try to do it manualy: it is both inefficient and lead to duplicated code.
You swallow meaningful information by using a bare except: if something goes wrong, the user is only left with your "there was an error" message and nothing to get a hint at what the error was. Never use bare except, always specify the kind of exception you’re expecting; and only expect exceptions you are ready to handle (printing a message is useless here since the traceback has so much more informations).
Use os.path.join to build paths instead of manually concatenating a '/'.
You should also allow the user to pass the "in" and "out" path as parameters.

Proposed improvements

# -*- coding: utf-8 -*-
"""
Created on Wed Mar  9 14:26:22 2016

@author: DalalNS
"""

from openpyxl import load_workbook
import os
import shutil
import traceback

def files_in_xl(filename):
    workbook = load_workbook(filename, read_only=True)
    for sheet in workbook.get_sheet_names():
        worksheet = workbook[sheet]
        for row in worksheet.rows:
            for cell in row:
                if cell[1] == 'B':
                    yield os.path.splitext(cell.value)[0]

def filter_and_copy(in_dir, out_dir, search_patterns):
    for root, dirs, files in os.walk(in_dir):
        absolute_root_path = os.path.abspath(root)
        for _file in files:
            filename = os.path.splitext(_file)[0]
            if filename in search_patterns:
                src_path = os.path.join(absolute_root_path, _file)
                dest_path = os.path.join(out_dir, _file)
                try:
                    shutil.copyfile(src_path, dest_path)
                except (OSError, SameFileError) as e:
                    # Alert the user if we couldn't copy and continue with other files (you may want something better than that).
                    print('Error while copying', src_path, 'to', dest_path)
                    traceback.print_exc()
                else:
                    print(src_path, 'copied to', dest_path)
            else:
                print(filename, "not found")

if __name__ == '__main__':
    patterns = set(files_in_xl('test.xlsx'))
    filter_and_copy(
        'C://Users/DalalNS/Desktop/Mapping/a/b',
        'C://Users/DalalNS/Desktop/Mapping/output',
        patterns)

I also changed shutils.copy to shutils.copyfile as it might be a little bit faster. Check the documentation for your version of Python to change the exceptions you want to handle accordingly.


Indent your code.
There is no need to define functions for multiplication and division. It is just as clear to say a * b as mult(a,b).
getValueA and getValueB do exactly the same thing, except with a different global. The return value of these functions is ignored. It would be better to merge these into one and use the return value.
Don't use valA and valB for variable names. Use local variables with names like volt.
Don't use a global for the result. Pass it as a parameter to displayResult, like this:

case 1:
    double amps = getValue("Amps");
    double ohms = getValue("Ohms");
    displayResult(amps * ohms, "volts");

You can, and should, avoid global variables completely here, as valueA and valueB are never used in the global context, they can be removed.
If the user types "no" or "N" it is treated as Yes. Handle this more carefully. For example, consider only the lowercase of the first letter.


Given a series of characters from stdin, print their squared integer ASCII counterparts

while (1)
    while(scanf("%c", &d), d != '\n') {
        printf("%d\n", d * d);
    }

It's better to consistently add braces around the body of statements like while and if.
A common mistake is to write something like this:

while (1)
    while(scanf("%c", &d), d != '\n') {
        printf("%d\n", d * d);
    }
    printf("...");

This may mislead a reader to think that the last printf is part of the outer loop, when it isn't. Just put the braces around the body always.

Another negative point in this version is having two statements inside the inner while. This is not easy to read. It's better to write in a way that there is no more than one statement per line. More generally, I recommend to avoid the , operator entirely.

The same point applies to this line in the 3rd version:

while((d = getchar()) != '\n') {

That is, there is an assignment within the conditional statement.
Avoid such "clever" writing style.
Stick to one statement per line.

And one more variation of the same issue, in the 4th version:

while ((d = getchar())) {


Determining whether one vector is a prefix of the other

Ok first, we want to determine if some condition is true or not based on some input. That calls for a boolean function! In particular, our inputs are two vectors. :

bool isPrefixOf(const std::vector<int>& smaller, const std::vector<int>& larger)
{
    ...
}

I named the first variable smaller, but it might not actually be smaller! Let's make sure that it is:

    if (smaller.size() > larger.size())
    {
        std::swap(smaller, larger); // this very efficiently swaps our vectors
                                    // in constant time
    }

Now once we got that, the algorithm in your j == k is exactly correct, but pretty hard to read. The convention is to use variables like i, j, k solely as indices in loops, not as important variables. So I'll rewrite it like this:

    for (int i = 0; i < smaller.size(); ++i)
    {
        if (smaller[i] != larger[i])
        {
            return false; // clearly not a prefix
        }
    }

    return true; // we match up, so we must be done!
}

So cool, we got our function that checks if a smaller vector is a prefix of a larger vector, so now our main just has to determine which way we call it:

int main()
{
    vector<int> vec1{0, 1, 1, 2};
    vector<int> vec2{0, 1, 1, 2, 3, 5, 8};

    cout << "vec1 is a prefix of vec2?: " << isPrefixOf(vec1, vec2) << endl;
}

Which should print true. So in general, your variable names don't line up with convention, and you coded the same logic twice - don't repeat yourself! Take advantage of functions to encode conceptually distinct functionality.


Bugs

This function will accept invalid strings as valid Roman numerals, e.g. IXC, XCX, IIIII, DD, VL, or A.

You always advance by one character.  If you're going to do that, you should use a state machine so that you know what you expect next.  Then you'd be able to check that D can't follow D and other invalid entries.  Part of the problem is that you can't compare just adjacent characters, e.g. IX and XC are valid substrings but IXC is not.

Repeated initialization

You initialize your roman map each time.  It would be better to initialize it once.  Consider a pattern like

static map<char, int> value_of;
if ( 0 == value_of.size() ) {
    initialize_digits_map(value_of);
}

Note that I used snake_case for the function name, as that's the standard for C++.  I also prefer it in general as it's easier to tell where each word ends and begins for people who may not use the English alphabet natively.

Even better would be to create a conversion class.  Your toArab function could then use the conversion class.  As could your isValidRomanNumeral function.  That would get rid of the unnecessary conversion to string.

Don't repeatedly process an expression with a static value

    for(size_t i=0; i<roman.size()-1; i++){

It's not a big difference, but it can be slightly more efficient to say

    for (size_t i = 0, n = roman.size() - 1; i < n; i++) {

That way you only call the function once and only perform the subtraction once.  In this case, the function call will likely get inlined, but the subtraction might not be.

It's generally easier for humans to read if you add more spaces.  This won't matter to the compiler but can help people read your code more quickly.


Fix the indentation

Before I say anything, let's reformat your code,
for everyone's sake,
because as you posted it, it just doesn't work,
because indentation is crucial in Python.
Please be more careful next time.

class Node(object):
    def __init__(self, data, next):
        self.data = data
        self.next = next

class getLinkRest():
    head = None
    tail = None

    def insert(self, data):
        node = Node(data, None)

        if self.head is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
        self.tail = node

    def showFromItem(self, data):
        curr_node = self.head
        flag = None
        while curr_node is not None:
            if curr_node.data == data or curr_node.data > data:
                print curr_node.data
                flag = 1
            curr_node = curr_node.next

        if flag is None:
            print "Not exist"

s = getLinkRest()
s.insert(1)
s.insert(2)
s.insert(3)
s.insert(4)
s.insert(5)
s.showFromItem(3)
s.showFromItem(7)

Purpose of the code

  Finding the kth to last element of a singly linked list

This is not what the posted code does.
The showFromItem function searches for an element with the specified value,
and prints that element and the rest of the elements until the end of the linked list that are bigger than the the specified value, or else it prints the text "Not exist".
For example:

s.insert(11)
s.insert(12)
s.insert(13)
s.insert(4)
s.insert(15)
s.showFromItem(13)

The above code will print 13 and 15.

That's a very unusual logic, and somehow I doubt that this was really your intention.

It's good to have a clear purpose, and to include a clear problem statement in a question.

Unused constructor argument

The next value of the constructor is never used.
So you could simplify it:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.next = None

Instead of using flag with None and 1 as values,
it would be more natural to make it a boolean, like this:

    found = False
    while curr_node is not None:
        if curr_node.data == data or curr_node.data > data:
            print(curr_node.data)
            found = True
        curr_node = curr_node.next

    if not found:
        print("Not exist")

You can write this condition shorter:

if curr_node.data == data or curr_node.data > data:

Like this:

if curr_node.data >= data:


Socket chat room made with Tkinter Python

This is a nice snippet which makes it useful for teaching! Here are some points:

Make imports explicit

Though import socket, threading is valid in Python, importing in two lines improves readability

import socket
import threading

Two lines after imports

Add two lines after imports. From this:

import socket
import threading
host = socket.gethostname()
...

to this:

import socket
import threading

host = socket.gethostname()
...

Constants in caps

port = 4000 should be PORT = 4000

Use string formatting

From this:

"%s has left the chat." % data

to this:

"{} has left the chat.".format(data)

In case of curly braces, you escape using {{}} as in the following case:

'Welcome {}! If you ever want to quit, type {{quit}} to exit.'.format(data)

Broadcast before handle_client

Since in handle_client you use broadcast, define it first

def broadcast(msg, prefix=""):
    ...

def handle_client(conn):
    ...

Add a message function

enclose:

bytes(msg, "utf8")

in a function called message:

def message(text):
    return bytes(text, "utf8")

then it becomes neater to use:

broadcast(message('hi'))

More explicit messages:

1) Server message

When first connecting, the server console states for me:

jPC
Server is ready...

And then when running clients, you get asked:

Enter server name:

I had to deduce that jPC is my server name. Modifying to the following might be more explicit:

Server name: jPC
Server is ready...

2) Enter username

Enter username in the textbox might be a better message. Coupled with the fact that you did not use a placeholder for the entry, users are confused.

3) Quiting without username

If someone quits without setting a username the server says:

{quit} has left the chat.

Adding a default id for clients might be better

{
    '<id2>': {
                'username': None,
                'connection_ip': '192.168.56.1:50325'
    },
    '<id2>': ...
}

you can use the uuid module for id or use the ip itself as id

Add placeholder effect

Add a placeholder effect by adding the line:

entry_field.bind("<FocusIn>", lambda args: entry_field.delete('0', 'end'))

Setting the font color to gray completes the effect.

Miscellaneous

Use snake case for variables. serverRunning becomes server_running
Use a geometry manager like grid for better display


Wrapper classes for objects returned by 3rd party APIs

You're almost there. You have the right idea, but you missed the execution of the idea a little bit.

public class ClientCustomer
{
  public ClientCustomer(ICustomer c)
  {
    this.customer = c;
  }

  public string Name

You've put a boundary in between yourself and the third party interface, but then you've turned around and coded against an implementation. We should code against interfaces whenever possible.

Right now you're probably confused.

  But I can't code against that interface. I need to insulate myself from it.

You're right. You do need to insulate yourself from the third party interface. It's their boundary, not yours. You need the Adapter pattern.

You need to create your own interface that your code will work with.

interface IClientCustomer
{
    string Name { get; }
}

Then your class implements your interface.

public class ClientCustomer : IClientCustomer

And all of the client code works with classes implementing the IClientCustomer interface.

  public ViewModel(ICustomerService svc)
  {
    this.svc = svc;
    Customers = new List<IClientCustomer>();

This way, if you ever swap the libraries out, you're truly insulated. You create a new class that implements your interface and it is much easier to swap one for another. If you make this small change, I'd say you've got it right.


Markup

Your markup has a case of divitis.  In years past, this was considered necessary, but now there are more semantic choices available like header, footer, nav, etc.  If you'd like to learn more about the HTML5 elements, I personally found HTML5 Doctor very helpful.

You have an image in your "nav" section, but it is unclear as to how it is related to navigation.  I don't know what it looks like so I used a picture of Bill Murray, which makes it look even more out of place.

Redundancy

Unless you're mixing ul and ol, there's no reason to specify ul in any selector containing li (eg. .nav ul li).  The li element must be a child of ul according to the rules of HTML.  The only exception is if you're trying to target a specific li of a specific ul in the case of nested lists (eg. .nav > ul > li).  Use the shortest selector necessary to target the element you want.

Navigation

There's nothing hacky about removing the margin the first element of your list.  If anything, you should be more concerned about your method for removing whitespace between your elements.  The font: 0 technique does not work on certain mobile browsers (plus it's terrible for not allowing you to use ems).

There are lots of ways to remove the undesirable whitespace between your inline elements.  Personally, I favor commenting it out.

Rather than setting paddings and unsetting them later, it is more efficient to only set the paddings on the elements you want:

.nav li ~ li {
    padding-left: 1em;
}

Though, if you're expecting your elements to wrap (eg. due to narrow viewport for mobile devices), negative margins would be better:

.nav ul {
    margin: 0 -.5em;
}

.nav li {
    margin: .5em;
}


PHP script to connect to MySQL database using PDO

I don't use PHP often, but here are a few comments:

Use Objects to Manage Resources

Like any other language with object-oriented capabilities, PHP serves you best when you  manage resources with objects. I'd strongly recommend holding your PDO object within a custom class that manages the connection. This makes the code easier to maintain and doesn't actually have to change much about what you did. The code will also be more extensible. Also, introducing OOP is a very good lesson for students starting out.***

You could then also show them lazy-loading, making sure the PDO isn't opened until there is actually communicating between the server and the database.

Password length

Of course you'd want to point out to your students that you'd need a decent password and not the one you're using for illustrative purposes here. For example, a password that was not a real world and more than 4 letters in length. This is more of a teaching point to make sure everyone has some common sense!

Error handling

Perhaps show your students what you would really do with the error message. For example, how could they wait and call the connection again? It could be helpful to show students they can do something in response to an error message apart from printing it out (like trying again, or waiting and trying again, or redirecting to a different page, or sending a warning email to the sys admin, etc).

***I first learned to make a dynamic website with Robin Nixon's much villified book. When I first learned from it, I didn't understand why people poo-poo the book so much. The reason is that it gets folks off the on the wrong foot. I resisted object-oriented design for websites for a long time because I started with that book and wanted to keep things simple, but of course nothing stays simple for long. If I ever teach coding to beginners, I will start them with objects on day 1!


Limiting Q promise concurrency in JavaScript

Your code looks good to me. Promises/A are a great pattern - however it can be hard to grasp in the beginning, I personally still got problems in understanding the Q library and Promises/A spec to wrap my head around

Your implementation looks familiar to control flow patterns presented here:
http://book.mixu.net/node/ch7.html

Here is another nice presentation on Promises and control flow issues:
http://trevorburnham.com/presentations/flow-control-with-promises/#/

and here is a list of other Promise/A spec implementations:

JQuery

http://api.jquery.com/promise The #1 choice in jQuery-land

Promises/A+

http://github.com/kriskowal/ The #1 choice in Node-land
http://github.com/tildeio/rsvp.js The most lightweight choice
http://github.com/cujojs/when The speediest choice
http://github.com/promises-aplus/promises-spec/blob/master/implementations.md