Counting the number of primes in C and C++11

Idiomatic C++ Review
#include <math.h>

C++ has its own version of math header.
#include <cmath>

Difference is all the functions are placed in the std namespace.
Prefer not to use std::endl.
        std::cerr << "Usage: " << argv[0] << " <N>" << std::endl;

Forcing a flush is not normally what you want to do. The streams will automatically flush when required and doing it manually will only make the code less efficient.
Prefer to put one variable per line. Also for loop counters can be declared inside the for statement (see below).
    size_t i, j, res = 0;

Don't dynamical allocate when a local variable will do:
    std::unique_ptr<std::vector<bool> > sieve(new std::vector<bool>(limit));

    // Should be
    std::vector<bool> sieve(limit);

Also std::vector<bool> is special. It is optimized for space not speed. It also has some other quirks that make it undesirable, so prefer std::vector<char> unless you really really need to save space. BUT because of the space saving you can get better caching which may improve time. In this case presumably because of the size of the vector keeping it as bool makes it much more efficient.
see: Comparing std::vector to std::vector
Declare loop variables inside the for:
    for (i = 2; i <= isqrt; ++i) {

    // Usually written like this:
    for(int i = 2; i <= isqrt; ++i) {

The at() method is a checked access to the member. It validates your index is in range (you don't do this in the C code).
        if (sieve->at(i)) continue;

Unless you are using unvalidated user input there is little need to use the at() method, prefer to use operator[].
In C++14 the functions std::begin() and std::end() were introduced to get the iterators for containers. You should prefer to use these as they work with arrays as well as the standard containers.
    for_each(sieve->cbegin() + 2, sieve->cend(), [&res](bool i) { res += !i; });

    // Can be written as:
    auto begin = std::begin(sieve);
    std::advance(begin, 2);
    for_each(begin, std::end(sieve), [&res](bool i) { res += !i; });

Don't bother with a return at the end of main.
    return 0;


Why don't you simply use an array of strings, as in:

String carCodeSet[] = {"FAQ025","QEF025","QEF037AB", /*...*/ };

this seems to me cleaner. Of course the HashSet would have better performance if the list of codes is very long... but maybe for 20 items a linear search on the array is not bad.

The String.contains method poses some problems in the fact that you cannot have the separator (comma) in your strings and, more importantly, that any sub-string would match: for example the code "FAQ" would be found as a sub-string. These might not be an issue in your actual use case, but is something which I would prefer not to have in my code.


QuickCheck properties for function that sorts a list of strings

Correctness of a sorting algorithm consists of showing that the resulting list is in order which your propOrder takes care of and that the resulting list is a permutation of the other list. Your propLength does the latter partially. It prevents you from adding or removing an element out of thin air but doesn't prevent you to replace one with another.

You can write a permutation checker as follows:

First define a subbag relation that is every element of the first list appears in the second.

isSubBag :: Eq a => [ a ] -> [ a ] -> Bool
isSubBag [] ys = True
isSubBag (x:xs) ys = x `elem` ys && isSubBag xs (delete x ys)

Then you can write a permutation checker by applying it both ways.

isPerm :: Eq a => [ a ] -> [ a ] -> Bool
isPerm xs ys = isSubBag xs ys && isSubBag ys xs

Your property comes out as:

propPerm :: [ String ] -> Bool
propPerm xs = isPerm xs (srtStr xs)

Overall, you can improve your process function by eliminating accumulator and using the built-in conjunction. Also a better name for it would be isInOrder

process :: [String] -> Bool
process (x : y : xs) = x <= y && process (y : xs)
process _ = True


Calling a function from a dynamically loaded DLL (version 2)

Certainly a better approach that the original. Only one 'flaw' that I noticed:

You ignore the return value from your convert function.

But I do have a couple of comments:

You may want to consider making line a const char * const (with associated other changes).
Put the type declaration next to the first use. i.e., rather than

HINSTANCE hinstLib;
// several lines
hinstLib = LoadLibrary(dllname.c_str());

do

HINSTANCE hinstLib = LoadLibrary(dllname.c_str());

Since you're in C++, use bool \ false etc rather than BOOL.
Depending on how frequently this would be called, you may want to adopt a RAII approach similar to Windows DLL Module Class. This could lead to some simplifications in the main flow of the code.
LoadLibrary and GetProcAddress are documented as returning NULL rather than std::nullptr. It may be totally silly, but I'd stick with the documentation.
You don't deal with the error case of LoadLibrary failing, with respect to GetLastError and giving a sensible error.
Consider using a reinterpret_cast<CONVERTPROC> rather than (CONVERTPROC).
You only return 1 or 0 from call_convert_from_dll - should it have a bool or enumerated return type?
Depending on what the effect of failure is, you may want to consider using exceptions, catching them further up the chain rather than handling failure in this function.

For your convert function:

The code implies the use of using namespace std. Please don't.
Rather than using an err variable, you could return immediately. The function is short enough to be understandable.
If any exceptions are likely to be thrown by inner code, catch them separately in the catch block and give details rather than 'catch all and dump'. Perhaps something like:

catch (const std::exception& e) {
    std::cerr << "Convert exception: " << e.what() << std::endl;
    return 1;
}
catch (...) {
    std::cerr << "Convert unspecified exception" << std::endl;
    return 1;
}


Modular exponentiation optimisation in Java

However, that solution uses 2 comparisons, 2 multiplications and a division within the loop.

You are doing 3 mod, they are not free, too (mod creates new internal copies and does a divide).

final BigInteger TWO = new BigInteger("2", 16);

I do not understand, why you parse 2 to basis 16? It does not change the result, but i suggest to use:

final BigInteger TWO = new BigInteger("2");

I assume here:

BigInteger compareVal = b.mod(TWO);
    if(compareVal.compareTo(BigInteger.ONE) ==0) {

You want to check for oddnes. You can to this in constant time if you look at the last bit:

if (b.testBit(0)) // then it is odd

And you can get rid of this TWO

Instead of dividing by 2

b = b.divide(TWO);

You can shift:

b = b.shiftRight(1);

This has a better implementation.

The last mod for the return:

return x.mod(c);

is not needed:

return x;

and after all, you can choose better names and you could end up with:

private static BigInteger fastModPow(BigInteger base, BigInteger exponent, final BigInteger modulo) {
    // plan: exploit the binary representation of the exponent, see for example http://en.wikipedia.org/w/index.php?title=Modular_exponentiation&oldid=517653653#Right-to-left_binary_method
    BigInteger result = BigInteger.ONE;
    while (exponent.compareTo(BigInteger.ZERO) > 0) {
        if (exponent.testBit(0)) // then exponent is odd
            result = (result.multiply(base)).mod(modulo);
        exponent = exponent.shiftRight(1);
        base = (base.multiply(base)).mod(modulo);
    }
    return result.mod(modulo);
}

Small and meaningless test with base and exponent length of 50.000:
old: around 20s
new: around 1s
(Java: couple of ms)

If you want further optimization, you have to choose better algorithms. One little trick could be to look into the Java source code. If you are not allowed to use the Java method, noone forbids you to use the code inside?

(One last hint: If you do some non trivial algorithms, add a comment about it)


I think that you should consider an important drawback of your solution: every query execution will read in main memory all the records that satisfy the query, before processing them. This is due to the fact that the sql function performs a fetchAll.

For instance, the php manual says:

  Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources.

So, if your application only does queries that retrieve small quantities of data, I think your solution is ok, since it improves the readability of the program, but if the program sometimes need large quantities of data, you should avoid the use of fetchAll.


Improving function that replaces all instances of x with y in string

This code is nicely written and clear in both code and description.  Good job!  I think there are still some things that might be improved.

Fix the bug

The updated value of start_pos is not being used for each iteration of the loop.  Instead, it should be, so the while loop should be this:

while ((start_pos = string.find(from, start_pos)) != std::string::npos)

Avoid creating copies if practical

I don't have MSVC 2019 available, but I suspect that it's pointing out that you've asked it to make copies of from and to.  That is, instead of this:

for (const auto [from, to] : map)

Write this:

for (const auto& [from, to] : map)

And see if that helps.  Another alternative would be to create a version of replace_all that takes a std::pair<std::string_view, std::string_view> and rewrite the loop as:

for (const auto& pr: map) {
    replace_all(string, pr);
}

Consider using a different data structure

The std::unordered_map used here may seem like a logical and intuitive structure to use but it has some potential problems.  First, the iterator has no defined ordering.  That is, the ordering is implementation defined so the programmer has no control of it.  That might be a problem if we want to do things in a specific order.  For example, replacing literal characters with their corresponding predefined XML entities, such as > to &gt; we typically want to do the & to &amp; conversion first for obvious reasons.  There's no way to do that with the existing version of the code.  Second, we can't create a constexpr version of the map because it has a non-trivial destructor.  I'd suggest allowing something like a std::array of std::pair<std::string_view, std::string_view>.  This is the approach that is used in conjunction with the next few suggestions.

Use using to simplify code

The existing code could be simplified a bit by using using like so:

using MapContainer = std::unorded_map<std::string_view, std::string_view>;
void replace_all(std::string& string, const MapContainer& map)  { /* etc. */ }

Now any place we use the rather long name we can simply write MapContainer.

Use templates for flexibility

Instead of tying the replace_all function to a specific kind of structure, we could pass it a pair of templated iterators instead for flexibility:

template <class ForwardIt>
void replace_all(std::string& string, ForwardIt first, ForwardIt last) {
    for ( ; first != last; ++first) {
        replace_all(string, *first);
    }
}

Now all we need is any forward iterator that returns something that can be used by the inner replace_all.  In fact, we can simplify even further because this is exactly like the definition of std::for_each.

Don't use std::endl if '\n' will do

Using std::endl emits a \n and flushes the stream.  Unless you really need the stream flushed, you can improve the performance of the code by simply emitting '\n' instead of using the potentially more computationally costly std::endl.

Consider creating a parallel version

The current version is simple and straightforward, but makes multiple passes through the string.  It's possible to create a version that makes a single pass through or that makes multiple passes in parallel.  The single pass version could be general purpose, but the parallel version would require that patterns be completely independent (unlike the entity-replacing example I mentioned).

Consider eliminating return 0

You don't need to explicitly provide a return 0; at the end of main -- it's created implicitly by the compiler.  Some people apparently feel very strongly both for and against this.  I advocate omitting it but you can decide for yourself.

Alternate version

Here's what I came up with using all of these suggestions:

#include <string>
#include <string_view>
#include <array>
#include <algorithm>
#include <iostream>

namespace utils
{
    using WordPair = std::pair<std::string_view, std::string_view>;
    void replace_all(std::string& string, const WordPair &pr) {
        for (std::size_t start_pos{ 0 };
            (start_pos = string.find(pr.first, start_pos)) != std::string::npos;
            start_pos += pr.second.length())
        {
            string.replace(start_pos, pr.first.length(), pr.second);
        }
    }
}

int main()
{
    constexpr std::array<utils::WordPair, 5> my_map{{
        {"&", "&amp;"},
        {"<", "&lt;"},
        {">", "&gt;"},
        {"'", "&apos;"},
        {"\"", "&quot;"}
    }};
    std::string my_string{ "This & that aren't \"<>\"." };
    // use a lambda for clarity
    auto repl = [&my_string](const utils::WordPair &p){
            utils::replace_all(my_string, p);
    };
    std::for_each(my_map.cbegin(), my_map.cend(), repl);
    std::cout << my_string << '\n';
}


Code to plot graphs with multiple panels efficiently

I'm not a guru of matplotlib but I'll show how I would approach the problem. Maybe you could get something useful out of it. Also, I'm gonna review all the code, not only the plotting part.

get_data:

def get_data(x, order, scale):
    '''Generates data for this example.'''

    y = scale * (x**order)

    return y

For docstrings use triple double quotes: """Your docstring""".
There is no need to put so many blank lines inside such a small function.
Exponentiation has a higher precedence than multiplication, that means you can remove parentheses: scale * x ** order.
Variable y is redundant, just write: return scale * x ** order.
You can use type hints to help readers understand what types of data your function operates with. Also some IDEs are capable of analyzing them and will highlight places where there are inconsistencies between what is supplied to a function and what that function expected to get.

That gives us:

def get_data(x: np.ndarray,
             order: float,
             scale: float) -> np.ndarray:
    """Generates data for this example."""
    return scale * x ** order

Generating example data:

# generate the example data

orders = [2, 2.2, 2.3]
scales = [1, 2]

scale_grid, order_grid = np.meshgrid(scales, orders)

parameters = list(zip(order_grid.ravel(), scale_grid.ravel()))

my_x = np.arange(0, 10.1, 0.1)
my_ys = []

for ps in parameters:

    my_ys.append(get_data(my_x, *ps))

Obtaining parameters by using np.meshgrid, np.ravel and zip doesn't look good. np.meshgrid will generate 2D arrays which is unnecessary. You can use itertools.product to get a Cartesian product of input parameters: list(itertools.product(orders, scales)).
Docs for np.arange warn:

  When using a non-integer step, such as 0.1, the results will often not
  be consistent. It is better to use numpy.linspace for these cases.

So, instead you should have my_x = np.linspace(0, 10, 101).
There is no need to have blank line after the for-loop first line.
We don't need to keep all the data in the my_ys. We can calculate it on the fly (see below).

That gives us:

import itertools
from typing import Iterable, Iterator, Tuple

def get_my_ys(x: np.ndarray,
              parameters: Iterable[Tuple[float, float]]
              ) -> Iterator[np.ndarray]:
    """Yields data for different parameters"""
    for order, scale in parameters:
        yield get_data(x, order=order, scale=scale)

...

orders = [2, 2.2, 2.3]
scales = [1, 2]
parameters = list(itertools.product(orders, scales))

my_x = np.linspace(0, 10, 101)
my_ys = get_my_ys(my_x, parameters)

Probably, you would want to extend it later for a variable number of parameters.

Generating the graph:

First of all, why is my_colors a dict (my_colors = {0:'r', 1:'b', 2:'g'})? When seeing a dict which keys are 0, 1, 2, ... it makes me think that it probably should be a list instead.
In fig, ax_rows = plt.subplots(3, ncols=2) it looks inconsistent that you specify keyword ncols but not nrows. 3 and 2 are, in fact, lengths of parameters orders and scales, you should tie them together. And, according to docs you could also specify sharex and sharey as True/'all'. So, you wouldn't have to write:

for i, ax_row in enumerate(ax_rows):
    ...
    for ax in ax_row:
        ax.set_ylim(0, 500)
        ax.set_xlim(0, 10)

for each subplot.

# plot the graphs
ax_row[0].plot(my_x, my_ys[i*2], lw=2, color=my_colors[i])
ax_row[1].plot(my_x, my_ys[i*2+1], lw=2, color=my_colors[i])

Several issues here. First of all, if you change the number of parameters in scale and order, this won't work as intended. Next, there is a code duplication on these two lines. And this indexing of my_ys just doesn't feel right. Ideally, this should look like:

for ax, y, color in zip(fig.axes, my_ys, colors):
    ax.plot(x, y, lw=linewidth, color=color)

Note the fig.axes. This will give you a list of all axes in the figure.
Again, this plt.setp(ax_row[1].get_yticklabels(), visible=False) will remove labels only in the second column. But what if you have more parameters and therefore more columns? Actually, we don't need these lines if you are going to use sharex and sharey when creating the figure. It will take care of them automatically.
Instead of checking the indices of the subplots to add labels for x-axis, I suggest simply iterate over the last row of ax_rows returned from plt.subplots:

for ax in ax_rows[-1]:
    ax.set_xlabel(xlabel)

Though, we should be careful with the returned type of ax_rows, because, as docs say, it

  can be either a single Axes object or an array of Axes objects

In order to get all the time an array, we should specify squeeze=False in the plt.subplots call.

ax_row[0].text(0.03, 0.95,'Scale: {0:.2f}\nOrder:
              {1:.2f}'.format(parameters[i*2][1],
              parameters[i*2][0]),
              transform=ax_row[0].transAxes,
              verticalalignment='top')
ax_row[1].text(0.03, 0.95,'Scale: {0:.2f}\nOrder:
              {1:.2f}'.format(parameters[i*2+1][1],
              parameters[i*2+1][0]),
              transform=ax_row[1].transAxes,
              verticalalignment='top')

Same problems here: code duplication, clumsy indexing, and it won't work if you add more input parameters in orders or scales. Here is how I suggest to generate labels:

label_template = 'Scale: {1:.2f}\nOrder: {0:.2f}'
labels = itertools.starmap(label_template.format, parameters)

Here I use itertools.starmap to supply tuples of parameters to the str.format method of the label_template.

In the end, plotting would look like something like this:

for ax, y, label, color in zip(fig.axes, my_ys, labels, colors):
    ax.plot(x, y, lw=linewidth, color=color)
    ax.text(s=label,
            transform=ax.transAxes,
            **text_properties)

where text_properties is a dict that would keep all the properties like positions, alignment, etc.

Revised code:

import itertools
from functools import partial
from typing import (Any,
                    Dict,
                    Iterable,
                    Iterator,
                    List,
                    Tuple)

import matplotlib.pyplot as plt
import numpy as np

TEXT_PROPERTIES = dict(x=0.03,
                       y=0.95,
                       verticalalignment='top')

def main():
    my_colors = ['r', 'b', 'g']
    orders = [2, 2.2, 2.3]
    scales = [1, 2]

    parameters = list(itertools.product(orders, scales))

    my_x = np.linspace(0, 10, 101)
    my_ys = get_my_ys(my_x, parameters)

    label_template = 'Scale: {1:.2f}\nOrder: {0:.2f}'
    labels = itertools.starmap(label_template.format, parameters)
    colors = replicate_items(my_colors, times=len(scales))

    plot(x=my_x,
         ys=my_ys,
         nrows=len(orders),
         ncols=len(scales),
         labels=labels,
         colors=colors,
         xlim=[0, 10],
         ylim=[0, 500],
         xlabel='x (unit)',
         ylabel='y (unit)')
    plt.show()

def get_my_ys(x: np.ndarray,
              parameters: Iterable[Tuple[float, float]]
              ) -> Iterator[np.ndarray]:
    """Yields data for different parameters"""
    for order, scale in parameters:
        yield get_data(x, order=order, scale=scale)

def get_data(x: np.ndarray,
             order: float,
             scale: float) -> np.ndarray:
    """Generates data for this example."""
    return scale * x ** order

def replicate_items(seq: Iterable[Any],
                    times: int) -> Iterable[Any]:
    """replicate_items('ABC', 2) --> A A B B C C"""
    repeat = partial(itertools.repeat, times=times)
    repetitions = map(repeat, seq)
    yield from itertools.chain.from_iterable(repetitions)

def plot(x: np.ndarray,
         ys: Iterable[np.ndarray],
         nrows: int,
         ncols: int,
         labels: Iterable[str],
         colors: Iterable[str],
         xlim: List[float],
         ylim: List[float],
         xlabel: str,
         ylabel: str,
         text_properties: Dict[str, Any] = None,
         linewidth: float = 2,
         fig_size: Tuple[float, float] = (5, 5)) -> plt.Figure:
    """TODO: add docstring"""
    if text_properties is None:
        text_properties = TEXT_PROPERTIES
    fig, ax_rows = plt.subplots(nrows=nrows,
                                ncols=ncols,
                                sharex='all',
                                sharey='all',
                                squeeze=False)
    fig.set_size_inches(fig_size)
    plt.xlim(xlim)
    plt.ylim(ylim)

    for ax, y, label, color in zip(fig.axes, ys, labels, colors):
        ax.plot(x, y, lw=linewidth, color=color)
        ax.text(s=label,
                transform=ax.transAxes,
                **text_properties)
    for ax in ax_rows[:, 0]:
        ax.set_ylabel(ylabel)
    for ax in ax_rows[-1]:
        ax.set_xlabel(xlabel)

    return fig

if __name__ == '__main__':
    main()

I'm sure that there are other things that could be improved. But this should get you going.


I see a number of things that may help you improve your code.

Headers should not contain code

Header files in C++ should generally only contain other headers, definitions and structure and class definitions.  They should not contain code implementations, so neither of these .h files should really be .h files.  Instead they should both be .cpp files because they contain code implementations or they should be split into separate declaration/implementation (.h/.cpp) pieces.

Use objects

The init() function seems to me that it would be better implemented as an object constructor and then the individual functions could be static member functions.  Here's another way to do Morse conversion.

Eliminate global variables

There is really no reason here to have global variables.  Instead, these should be wrapped into an object, or at least a namespace.

Use const where practical

The SPACE variable should be const as should be the arguments to the functions.

Pass complex objects by reference

The std::string arguments to either of the functions should be a reference to avoid an unnecessary copy.  That is the function could instead be:

std::string translateToMorse(const std::string &plainText)

Consider the user

If someone very reasonably tries to translate a callsign such as W1AW they'll get back the string ".----" which is only the Morse code for '1'.  The problem is that the code only accepts lowercase characters and neither throws an error nor gives any indication that the uppercase characters were simply ignored.  That's not very helpful to the user.  Consider instead throwing an exception.  Simply ignoring characters is unlikely to be a desirable behavior in any case.

Eliminate split

The one place that split is used is in the translateFromMorse routine, but it's really not needed there.  Instead you could introduce new functions that would translate a word at a time and use std::stringstream to extract a word at a time for translation.


Cleaning up a multi-model view in Rails3

Firstly (and yes I did read the comments) the signup model seems unessential.

So firstly we should do away with that, if you need to associate payment details then that could easily be done directly on the company model.

Secondly you controller is getting a bit cuddly. In favour of having "fat model, skinny controller" let's move all that signup logic into the company model in the form of a Company::register method.

So far we have changes like this:

# app/models/company.rb
class Company < ActiveRecord::Base
  has_many :users
  accepts_nested_attributes_for :users

  def self.register(params)
    company = self.new(params)

    company.users.first.admin = true
    company.users.first.skip_confirmation!

    if company.save
      company
    else
      false
    end
  end
end

Now your controller can look like this:

# app/controllers/companies_controller.rb
class CompaniesController < ApplicationController

  def new
    @company = Company.new
  end

  def create
    if @company = Company.register(params[:company])
      sign_in_and_redirect(@company.users.first)
    else
      render :new
    end
  end
end

I'm also pretty sure that it's unessential to use that helper you have above. The form builder should be able to work it out from the model accepting nested attributes.


Program to solve variations of the seven thieves & diamonds riddle

Given that this was quick and dirty program to solve a simple problem, it's understandable that some things aren't as "polished" as could be.  Here are some things I spotted:
gcd()
I'm guessing you copy and pasted this function because the style of the braces, the indentation, and the spacing doesn't match the rest of your code.
Overflow
When I ran your program (on a 32-bit system) I couldn't get an answer for 23 thieves because it overflowed.  Here where you compute the lcm:

       lcm = (lcm*i)/gcd(i,lcm);

you can do slightly better like this:
         lcm *= i/gcd(i,lcm);

With that change, I was able to get the answer for 23 (but not for 29).  You might want to use uint64_t instead of long to get the largest range possible (I was able to get the answer for 43 thieves using uint64_t).  Btw, that line was also indented too far for some reason.
Spacing
I personally like more spaces between things such as if(, but it's subjective.  One place that was really hard for me to read was this:

       diamonds = lcm*++i + 1;

Minor ordering change
For this line:

if(isPrime(thieves) && thieves > 1)

I would rather it be like this:
 if(thieves > 1 && isPrime(thieves))

That way you don't end up calling isPrime with some strange negative input that can have unintended consequences.


Use OrderedDict if you want an ordered dictionary.

from collections import OrderedDict
from itertools import islice, cycle

def shift_dict(dct, shift):
    shift %= len(dct)
    return OrderedDict(
        (k, v)
        for k, v in zip(dct.keys(), islice(cycle(dct.values()), shift, None))
    )


Welcome to Code Review!

So, I am assuming that queries is a list of words we are searching for, and any of them being found is a success.  I am also assuming that sentences is a list of strings, with each element subdivide-able into a list of words.

Bugs:

I noticed that your existing code won't see "This is a test." as having the word "test" in it, because of the period.  You may need to separate out commas, periods, parentheses and so on for it to work properly, but perhaps this is by design.  I am unsure.

Add a Break:

The first thing I see that could be improved is you don't need a flag.  Instead of setting exists = False and then keep looping, just add your results if it is there, and then just break.  You don't need to search the entire sentence if you have already found it, and you don't need a flag if you are doing the one operation within the loop.

So:

for word in words.split(' '):
    if word in s:
        results += ' %d' % j if results else '%d' % j
        break

This will save you a few iterations for long sentences if the beginning matches.

Tries:

Now, if you want to completely rewrite the whole thing for O(n) passes, (which is the best you can possibly get for text searching), then you can use a "Trie" data structure.  The way this works is by inserting all of your text, one character at a time per word, into a variation of a tree.  This is O(n) insertion, where n is the number of characters in your input data.  Then, for every search term, you go through and find, letter by letter, which words match.  This is O(n) where n is the number of characters in each search term, so theoretically much less of an impact than the previous one.

I modified the code that was posted here (under public domain): https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1

Most of it is not my own, but I modified it to fit your function.

class Node(object):
    def __init__(self, character):
        self.character = character
        self.children = []
        # A flag to say whether or not we are at the end of our current word.
        self.finished = False
        # How many times this character appeared in the addition process
        self.count = 1

class Trie(object):
    def __init__(self):
        # Create a root node with a non-character attribute so it won't be confused
        # with any of the entries.
        self.root = Node(None)

    def add(self, word):
        # Set our current node to the start/root.
        current_node = self.root
        for char in word:
            in_child = False
            # Search for the character in the children of the present node
            for child in current_node.children:
                if child.character == char:
                    # We found it, increase the counter by 1 to keep track that another
                    # word has it as well
                    child.count += 1
                    # And point the node to the child that contains this char
                    current_node = child
                    in_child = True
                    break
            # We did not find it so add a new chlid
            if not in_child:
                new_node = Node(char)
                current_node.children.append(new_node)
                # And then point node to the new child
                current_node = new_node
        # Everything finished. Mark it as the end of a word.
        current_node.word_finished = True

    def find_term(self, term):
        """
        Check and return
          1. If the prefix exsists in any of the words we added so far
          2. If yes then how may words actually have the prefix
        """
        node = self.root
        # If the root node has no children, then return False.
        # Because it means we are trying to search in an empty trie
        if not self.root.children:
            return False, 0
        for char in term:
            char_not_found = True
            # Search through all the children of the present `node`
            for child in node.children:
                if child.character == char:
                    # We found the char existing in the child.
                    char_not_found = False
                    # Assign node as the child containing the char and break
                    node = child
                    break
            # Return False anyway when we did not find a char.
            if char_not_found:
                return False, 0
        # Well, we are here means we have found the prefix. Return true to indicate that
        # And also the counter of the last node. This indicates how many words have this
        # prefix
        return True, node.count

def textQueries(sentences, queries):
    trie = Trie()
    sentences_list = [s.split(' ') for s in sentences]
    for sentence in sentences_list:
        for word in sentence:
            trie.add(word)

    for words in queries:
        words_list = words.split(' ')
        results_list = []
        for word in words_list:
            results = trie.find_term(word)
            if results[0]:
                results_list.append(results[1])
        if results_list:
            print results_list
        else: print -1

This will return:

Venkee Enterprises:>python test.py
[2]
[1]

for my input data of:

sentences = ["Hello world, this is a sentence.", "This is also a sentence.", "This, however, is an incomplete"]
queries = ["sentence", "Hello"]

As it was able to find 2 words that match for the query "sentence" and 1 word that matched "Hello".

Hope this helps.


Red implementation of Rock, Scissors, Paper

Looks an interesting first project! Some thoughts:

The URL! type does not need a % prefix (they would be interpreted as FILE! and would behave incorrectly were you to operate upon them).
In Red, you can use the WORD! type in place of strings. You can use a LIT-WORD! to get a word without evaluating it. Takes a little getting used to, but is more efficient and expressive:

weapons: [rock paper scissors]
player-choices: [rock 0 scissors 0 paper 0]

player-wins: [
    [rock scissors] "breaks"
    [paper rock] "covers"
    [scissors paper] "cut"
]

select player-choices 'rock

Instead of VALID-CHOICE, you could use SWITCH to drive things:

until [
    switch player-choice: ask "(r)ock, (s)cissors, (p)aper or (q)uit? " [
        "q" [true]
        "r" "s" "p" [
            play-round player-choice
            false
        ]
    ]
]

You can use CASE in place of nested EITHER statements—breaks the choices out a bit:

make-computer-choice: func [
    /local tmp tally
][
    case [
        games-played < 3 [
            random/only weapons
        ]

        (
            tmp: random games-played
            tmp <= tally: select player-choices 'rock
        ) [
            'rock
        ]

        tmp <= tally: tally + select player-choices 'scissors [
            'scissors
        ]

        true [ ; or else
            'paper
        ]
    ]
]

If you want to somewhat keep the game logic separate from the interface, I'd recommend a play-round function called in the same fashion as above. play-round could return false (continues) or true (ends loop when someone wins a certain amount of games).
I notice you define the function make-computer-choice but don't invoke it.


Your code looks correct (apart from the typo in case #4). Note that the final else if is not necessary.
If none of the first 4 tests passes then you necessarily have a tie,
so a simple else is sufficient here.

The winner variable is named badly, as it contains the maximal score and
not the winning player.

But you are using far too many comparisons, and the code does not scale well for a larger number of players. What you need to know is

Which player has the maximum score?
How many players have the maximum score?

Both can more easily determined if all scores are stored in an array.

Since you
are working with Objective-C, I would suggest to take advantage of the
classes and methods that the Foundation framework provides.

First create an NSArray of all player scores. Objective-C collections can only
contain objects, therefore the integers have to be boxed into NSNumber
with @(...):

NSArray *scores = @[@(score1), @(score2), @(score3), @(score4)];

Use Key-Value Coding to find the maximum element:

NSNumber *maxScore = [scores valueForKeyPath:@"@max.self"];
NSLog(@"maximum score is %@", maxScore);

Use indexesOfObjectsPassingTest: to find all objects in the scores array
that are equal to the maximum score:

NSIndexSet *bestPlayers = [scores indexesOfObjectsPassingTest:^BOOL(NSNumber *obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqual:maxScore];
}];

If the index set has only one element then there is a unique winner, otherwise a tie:

if ([bestPlayers count] == 1) {
    NSLog(@"Best player is #%ld", [bestPlayers firstIndex] + 1);
} else {
    NSLog(@"Tie between");
    [bestPlayers enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSLog(@"  Player #%ld", idx + 1);
    }];
}

(Array indices are 0-based, therefore you add one to get the player number.)


Use expect instead of unwrap. This gives you and your users
a better chance at figuring out what went wrong. It's also one step closer
to good error reporting and handling.
Extract an inner_main that returns a Result and thus allows
you to use try!. main can call that method, pattern match on the
Result, print the failure message, have an exit code, etc.
To start with, return a Result<_, Box<Error>>. Box<Error> is an easy
type to build, and try! can convert to it automatically.
Once you are returning Results, theexpects can be transformed into a
ResultusingOption::ok_or`.
One Rust-specific way to think about splitting up functions is
to constrain mutability. Extracting out loading the file allows the
Vec to be mutable in the smallest possible scope.
It may be over engineering, but creating an iterator to handle
finding the embedded PNGs helps separate concerns. For example, I
didn't originally see that i wasn't part of the main finding
logic. It would also allow you to create more focused unit tests on
just this complicated functionality.
The search algorithm itself isn't super efficient; it doesn't
skip as much data as it could in certain places, it seems to always
scan through to the end of the file. What if your data was
something like SIG ... SIG ... SIG ... EOF?
The magic number 130 for the end position is duplicated.
Use a crate like twoway to do
the heavy lifting of searching for byte substrings. This takes care of a
lot of the annoying details.
The data is sliced for the same range multiple times. Any array access is a tiny bit expensive as it has to do range checks. Doing it once is good for both programmer sanity and for the tiny gain in speed.
Using format! to construct the file name may be more obvious than adding a string slice to a String.

extern crate twoway;

use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::{env, process};

const SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
const EOF: [u8; 8] = [73, 69, 78, 68, 174, 66, 96, 130];

fn load_file<P>(path: P) -> Result<Vec<u8>, Box<Error>>
    where P: AsRef<Path>
{
    let mut f = try!(File::open(path));

    let mut buf = Vec::new();
    try!(f.read_to_end(&mut buf));
    Ok(buf)
}

struct EmbeddedPng<'a>(&'a [u8]);

impl<'a> Iterator for EmbeddedPng<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match twoway::rfind_bytes(self.0, &SIGNATURE) {
                None => return None,
                Some(start_idx) => {
                    let (before, after) = self.0.split_at(start_idx);
                    self.0 = before;

                    if let Some(end_idx) = twoway::find_bytes(after, &EOF) {
                        let png_data = &after[..end_idx + EOF.len()];
                        return Some(png_data)
                    }
                }
            }
        }
    }
}

fn inner_main() -> Result<(), Box<Error>> {
    let path = try!(env::args().nth(1).ok_or("No filename provided"));
    let buf = try!(load_file(path));

    for (i, png_data) in EmbeddedPng(&buf).enumerate() {
        let fname = format!("{}.png", i);
        let mut f = try!(File::create(fname));
        try!(f.write_all(png_data));
    }

    Ok(())
}

fn main() {
    if let Err(e) = inner_main() {
        println!("{}", e);
        process::exit(1);
    }
}


Awkward API

It seems strange to initialise a Solution object with various info that we provide again in the call of the method find_words.

Actually, looking for places where self is used makes it pretty obvious: the instance is never used.

It is a good occasion to watch the Stop Writing Classes talk from Jack Diederich.

To be continued ?


I think that, in rollingPrediction, you just need the maxIndex, once that you already can access the max in arr with it.
Also, since that you need the maxIndex to find the class, you can just store the classes in an array with every class stored in the correspondent index.

To find which array has the most predictions, you will receive an array and evaluate it to one value. In cases like this, I think that you can use Array.prototype.reduce():

In the callback function, check which array has the bigger length
The initial value will be [null, []],  to check if there's one bigger array and  to have an array to compare in the callback function.

In indexOfMax you can use Math.max with Array.prototype.indexOf() since performance it's not a problem in this case, but you can use reduce too.

Suggestion: In sumOfArray, you receive an array as parameter and want to evaluate to one value. Maybe you can use reduce once again.

// ...
const classesIndexed = ["0", "10", "5"];
// suggestion: once that you know the classes order, this could be:
// const classesIndexed = Object.keys(allPredictions);

const rollingPrediction = arr => {
  const maxIndex = indexOfMax(arr);
  if(maxIndex === -1) {
    return;
  }
  const maxFixed = parseFloat(arr[maxIndex].toFixed(2));
  allPredictions[classesIndexed[maxIndex]].push(maxFixed);
  queueSize++;

  if (queueSize <= 4) {
    const [className, bigger] = Object.entries(allPredictions)
      .reduce(
        (acc, act) => acc[1].length >= act[1].length ? acc : act,
        [null, []]
      );
    if (!className) {
      const sum = sumOfArray(bigger);
      const prob = sum / bigger.length;
      console.log(`Awareness level ${className} | Probability: ${prob}`);
    } else {
      console.log("No rolling prediction");
    }
    // ...
};
// ...
const indexOfMax = (arr = []) => arr.indexOf(Math.max(arr))


Effective way to find two string are anagrams

anagram seems like a misnomer. A better name for such function would be is_anagram.
I don't see why <set> is included.
Fail early:

if (usr1.length() != usr2.length()) {
    return false;
}

spares you a level of indentation.
Test for pos==usr1.size()-1 is waste of time, because it fails at every iteration except the last one, and still tests for characters at pos.
Sorting inputs is an essential part of the algorithm, and hence shall be performed inside anagram. As written, anagram only tests two string for being identical.
On the other hand, removing spaces does not belong to the core algorithm, and you correctly let the caller do it. You may also want to  remove punctuation, and maybe convert the strings to the lower case. This logic indeed belongs to a caller.
Since you already #include <algorithm>, an std::equal(usr1.begin(), usr1.end(), usr2.begin()) looks more C++ish (if you are open to C++14, a variant std::equal(usr1.begin(), usr1.end(), usr2.begin(), usr2.end()) even spares the test for equal length).

All that said,

    bool is_anagram(std::string s1, std::string s2)
    {
        std::sort(s1.begin(), s1.end());
        std::sort(s2.begin(), s2.end());
        return std::equal(s1.begin(), s1.end(), s2.begin(), s2.end());
    }

As mentioned in comments, an alternative implementation using histograms is very appealing.


Remove \n newline from a list of string dumped from github used for a Italian stopwords vocabulary

Code is very readable, and that's a good start.
file_name is in fact the file_content; splitted (split) should be just stop_words; stopwords_list is a constant, so by PEP 8, should be uppercase STOPWORDS_LIST.
The problem I see here is that you are decoding each word, when in fact you should decode the whole file, just once.
This is just personal preference, but I tend to always use the requests library, because, in my experience, is always a step ahead of what I need. requests tries to understand the encoding, based on the response, so there should be no need to decode.
A bit of data validation is also needed. The file could have been moved, the network or Github could be down, so it always better to be prepared for the worse. In this case, if the network is down (Connection Timeout) or the file is not there (404) there isn't a big difference: your application should handle the exception and the execution should not proceed.
While a connection timeout would normally raise an exception, a 404 (or any other HTTP error) would still be considered a valid HTTP response, that's why requests has a handy method when you just want 2** responses: raise_for_status.
Then, to remove the \n there is actually the method splitlines() which is exactly what you need.
import requests

STOPWORDS_LIST= "https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt"

try:
    response = requests.get(STOPWORDS_LIST)
    response.raise_for_status()
    file_content = response.text
    words = file_content.splitlines()
except Exception as e:
    print(f"There was an error: {str(e)}")

This piece of code should put inside a function, so it is clearer what it does and restrict its scope. I'm also adding a type to the function, that can be useful to avoid errors at compile time. Maybe some day you will have stopwords in other languages, so I'm just writing a main as example.
from typing import List

import requests

def download_stop_words(url: str) -> List[str]:
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.text.splitlines()
    except Exception as e:
        print(f"There was an error: {str(e)}")

if __name__ == '__main__': # this avoids the program being executed when the module is imported
    STOP_WORDS = {
        "it": "https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt"
    }
    for lang, url in STOP_WORDS.items():
        stop_words = download_stop_words(url)
        print(f"In '{lang}' there are {len(stop_words)} stop words")


Querying a phone directory until end of input is reached

Take care to adhere to PEP 8 code formatting guidelines.  In particular, there should be a space before and after each = and +.  The KeyError handler should have just one level of indentation.

The phonebook could be constructed using a one-liner.  I consider it good practice to specify maxsplit=1, though it makes no practical difference when you are assured that the input will be well formed.

Getting the rest of the input using for line in sys.stdin is not a bad approach, I think.

import sys

n = int(input())
phonebook = dict(input().split(maxsplit=1) for _ in range(n))
for line in sys.stdin:
    key = line.strip('\n')
    try:
        print('{0}={1}'.format(key, phonebook[key]))
    except KeyError:
        print('Not found')


Listing my StackEchange communities user id

I see 2 errors and have some more advice.
The Shebang is wrong.
#!/bash/bin
should be
#!/bin/bash

Do not put comment after the \ escape for a new line
| cut -d"/" -f3,5 \ # stackoverflow.com/3581081
# should be
| cut -d"/" -f3,5 \

I would move all functions (in your case only parse()) to the top of the file.
Use lowercase variables (uppercase is reserved for system variables like PATH).
NETWORK_PROFILE_URL=
# change to
network_profile_url=

Combine cut and sed
read -r ID USER <<< \
    $( cut -d'/' -f5,6 <<< $NETWORK_PROFILE_URL \
        | sed 's/\// /g' \
    )
# can be replaced by
read -r ID USER < <(awk -F "/" '{print $(NF-1) " " $NF }' <<< $NETWORK_PROFILE_URL)
# which is easier to read then
source <(sed -r 's#.*/(.*)/(.*)#ID=\1; USER=\2#' <<< $NETWORK_PROFILE_URL)

When you end a line with a pipe, you do not need to escape the newline with \.
curl "https://stackexchange.com/users/$ID/$USER?tab=accounts" \
    | grep "account-container" -A1 \
    | grep "http" \
    | cut -d"/" -f3,5 \
    | parse
# can be changed into
curl "https://stackexchange.com/users/$ID/$USER?tab=accounts" |
    grep "account-container" -A1 |
    grep "http" |
    cut -d"/" -f3,5 |
    parse

You had a hard job parsing the curl output with different tools. In this situation you won't need to parse large files, the performancy penalty is very small. It is worth the effort for other cases to look for a solution with awk.
The grep -A1 is replaced by setting a flag for parsing the next line.
Fields are found with the delimiter '/'.
Combining substr is only slightly more complex:
curl -s "https://stackexchange.com/users/$ID/$USER?tab=accounts" |
   awk -F "[/]" '
      parse==1 {
         print substr($3,1,index($3,".")-1) ":";
         printf("  url: https://%s\n", $3);
         printf("  id: %s\n", $5);
         parse=0;
      }
      /account-container/ {parse=1}
    '


Is there a better way to do this linq sort?

You're correct, it can be costly.

You can just expand the lambda expression:

Assets.OrderBy(a => {
    var item = a.GalleryItems != null
               ? a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId)
               : null;
    return item != null ? item.SortOrder : 1000;
});

[Quick edit]

The above will work correctly only for LINQ 2 Objects queries.

If you're using EF or any other LINQ database provider, you should leave the query as-is, because it will probably be translated to ISNULL(..., 1000) or something equivalent.


Styling android widgets programmatically

I already answered some questions in a comment here is the code review.

Some tips and suggestions:

Use full names for params and local variables to improve readability
Don't use numbers in the names of methods
Try to use Iterable interface above the List if possible
Follow naming conventions for Android
Use annotations to improve code quality and usage
Use final modifier if possible

'

public static void styleControls(@NonNull final Context context, @NonNull final Iterable<View> controls, @NonNull final Object object) {
    if (object == null) {
        return;
    }
    final File file = context.getExternalFilesDir(null);
    if (file == null) {
        Log.e(TAG, "couldnt get external files dir!");
        return;
    }
    final Resources resources = context.getResources();
    final String filepath = file.getAbsolutePath() + File.separator;
    for (final View view : controls) {
        final Modify modify = null;
        //... instance of checks
        if (modify != null) {
            modify.modify(view);
        }
    }
}

public abstract class ViewModifier implements Modify {

    private static final String TAG = "ViewModifier";

    protected final Object     mObject;
    protected final String     mBasedir;
    protected final Resources  mResources;
    protected final TypedValue mTypedValue;

    public ViewModifier(@NonNull final Resources resources, @NonNull final Object object, @NonNull final String basedir) {
        mResources = resources;
        mObject = object;
        mBasedir = basedir;
        mTypedValue = new TypedValue();
        mTypedValue.density = resources.getDisplayMetrics().densityDpi;
    }

    // some helper codes....
}

public interface Modify<T extends View> {
    void modify(final T t);
}


Do not recompute is-multiple repeatedly by either binding the value:

(defun num-action (i)
  (let ((i3 (is-multiple i 3))
        (i5 (is-multiple i 5)))
    (cond ((and i3 i5) (print "FizzBuzz"))
          (i3 (print "Fizz"))
          (i5 (print "Buzz"))
          (T (print i)))))

or by using if:

(defun num-action (i)
  (if (is-multiple i 3)
      (if (is-multiple i 5)
          (print "FizzBuzz")
          (print "Fizz"))
      (if (is-multiple i 5)
          (print "Buzz")
          (print i))))

PS. please fix indentation


Acquiring and formatting data from a JSON file

I'd suggestion cleaning it up like this:

function MCScrap(ZWA, ZWB, ZWC, ZWD, Number) {
    $(document).ready(function () {
        setInterval(function () {
            $.getJSON("mccount.json", function (machines) {
                var zwa, zwb, zwc, zwd, TScount, YScount;

                zwa = document.getElementById(ZWA);
                zwb = document.getElementById(ZWB);
                zwc = document.getElementById(ZWC);
                zwd = document.getElementById(ZWD);

                zwa.innerHTML = machines.Machines[Number].Ycount;
                zwb.innerHTML = machines.Machines[Number].Tcount;

                YScount = machines.Machines[Number].YScount;
                zwc.innerHTML = YScount + "%";
                TScount = machines.Machines[Number].TScount;
                zwd.innerHTML = TScount + "%";

                function getColor(count) {
                    if (count < 3) {
                        color = 'lime';
                    } else if (count < 5) {
                        color = 'orange';
                    } else {
                        color = 'red';
                    }
                    return color;
                }

                zwa.style.backgroundColor = getColor(YScount);
                zwb.style.backgroundColor = getColor(TScount);

            });

        }, 3000);
    });
}

Types of changes:

Get a DOM element once into a variable and then use it from there rather than calling document.getElementById() more than one for the same DOM element.
Put the color code into a reusable function rather than having two copies which also makes it easier to set the color in just one place rather than three places.
Put zwa, zwb, zwc, zwd blocks of code in order to make it easier to read and follow.

Some other things that seem a little off to me:

Putting $(document).ready() inside another function like this seems a little odd.  Usually, you would call MCScrap() inside a $(document).ready() as that would make your function a bit more reusable.
Setting up an ajax call to run every 3 seconds in perpetuity is generally not a good idea.  For starters, it's horrible for battery life (phone, tablet, laptop).  And, it can get messy if you every get in a situation where the ajax call takes longer than 3 seconds to finish or timeout.  Then, you have multiple ajax calls in flight at the same time and they could be building up.  The safer way to do this is to launch the next ajax call from a setTimeout() that is set in the completion of the previous ajax call.  Then, they can never build up.


Implementation of Factory Method pattern for XML and Excel documents

Although your implementation is superficially correct, my guess is that it is missing some of the finer points of factory method implementation .

A good example that you can look at is URLStreamHandlerFactory in java.

Some minor changes that I would make to your code would be to Introduce an Enum such as

public enum TYPE {
    EXCEL,
    XML

}

Modify my DocumentCreator to

public abstract class DocumentCreator {
    public static Document createDocument(TYPE type) {

        if (type.equals(TYPE.EXCEL)) {
            return new ExcelDoc();
        } else if (type.equals(TYPE.XML)) {
            return new XMLDoc();
        } else {
            // Default Implementation
            return new XMLDoc();
        }

    }

    public static Document createDocument() {

        return new XMLDoc();

    }
}

And my main Class would invoke as follows :

public class MainClass {

    public static void main(String [] args){
       // DocumentCreator docCreator = new XMLDocumentCreator();
        System.out.println(DocumentCreator.createDocument().parse("SOMETHING"));
        System.out.println(DocumentCreator.createDocument(TYPE.XML).parse("SAX"));
        System.out.println(DocumentCreator.createDocument(TYPE.EXCEL).parse("DOM"));
        System.out.println(DocumentCreator.createDocument(TYPE.XML).parse("MSDoc"));
        System.out.println(DocumentCreator.createDocument(TYPE.EXCEL).parse("OpenOffice"));

      }
}

These are just a few minor modifications to your code . I would suggest you to go though this Factory Pattern Explained to understand the finer aspects  of 1) Instantiation control 2) loose coupling 3) improving readability by encapsulation  which is feel is the primary need of using the factory pattern.


Yes, this is a good implementation of the strategy pattern. I don't know if the code you posted is just a simplification or not but I think that you have to prevent a NullPointerException when a client class doesn't specify the strategy to use. You can achieve this task in many ways, for example eliminating the empty constructor or inserting a default strategy in the empty constructor. Another elegant way would be making the strategy a parameter of the fight() method (obviously only if it used within the method):

public void fight(AIStrategy strategy) {
     strategy.player();
}

Making this way you will make the classes lighter, and it will be more difficult to get a NullPointerException.

public class App {

    public static void main(String[] args) {
        AIPlayer aiPlayer = new AIPlayer();
        AIStrategy stragey = () -> System.out.println("Default strategy");
        Scanner sc = new Scanner(System.in);
        String difficulty = sc.next();
        switch (difficulty) {
            case "chill":
                strategy = () -> System.out.println("The opponent is playing a chill strategy...");
                break;
            case "calculated":
                strategy = () -> System.out.println("The opponent is playing a calculated strategy...");
                break;
        }
        aiPlayer.fight(strategy);
        System.out.println("Is the opponent hurt?");
        boolean isHurted = sc.nextBoolean();
        if (isHurted) {
            strategy = () -> System.out.println("The opponent changed his strategy. Now he is having a holy rage!!"));
            aiPlayer.fight();
        }
        aiPlayer.fight(strategy);
    }
}


Generally, using split and treating a string as an array - only to turn it back into a string - isn't very elegant for find-and-replace task like this. If the input is a string, and the output is a string, making the intermediate step an array seems odd given that JS has some OK string manipulation features.

Your code is also buggy. Since you use toString instead of a plain join, you introduce commas in the string. And you then have to remove those again, but you do that with a global replace. Meaning the string can't have commas of its own, or they'll get eaten too.

Instead of all that, you could simply do join(" "), and get the same result as you would with toString() & replace(/,/g, " ") but without stomping on existing commas.

You're also replying on spaces in the string. But really, the only delimiters you should care about are {{ and }}. I should be able to write a template string like "{{ foo }}{{ bar }}" (no space in between) to get a string like StackOverflow. Or I might use hyphens or something else (e.g. the aforementioned commas) and I wouldn't expect the code to eat them. I would also expect to be able to use two spaces inside the braces - or no spaces at all. Neither thing is handled properly by your code, as it's totally dependent on the whitespace being just so.

Lastly, your code would fail on malformed template strings like "here are two braces {{ and here two more {{". That's not a proper template, and should just be returned unaltered. But your code only looks for the opening braces and assumes there to be two close braces later on. So given the input above, I get "here are two braces  two more " as output, because it aggressively splices away some words.

A couple of minor notes:

/{{/i - the i flag (case-insensitive matching) doesn't matter here. There is no upper- or lowercase for curly braces.
"Split" as an adjective is also "split". So "splitted sentence" isn't quite grammatically kosher.
You could combine the splice calls, since splice both removes and inserts elements in an array. I.e.

splittedSentence.splice(idx, 3, resolveString(splittedSentence[idx+1]));

The resolveString() function is problematic. For one, it's a bit much to wrap property access in a function. In fact, calling the function is longer than just writing template[item]. But more importantly the function relies on the template object being accessible in its scope. Note that fillInTheBlanks, the point of the task, does not make such an assumption; there you must pass in the object. Which means you could call fillInTheBlanks("x", { x: "hi!" }) and it should work. But in your case it would fail, because the template object won't be in resolveString()'s scope.
And as @Jonah pointed out, and which I'd missed, you're using underscore (or lodash) just to do a forEach, when forEach is built in. Sure, some really old browsers lack it, but if that's a concern there's always the plain old for-loop.

Anyway, I said you don't need to split the string as there are string manipulation functions you can use instead. Specifically, the String.replace method accepts a function as its 2nd argument. That function will be passed the matched part(s) of the string, and its return value will be used as the replacement. Add in a regular expression, and you've got a pretty neat solution.

So I imagine that your interviewers were looking for something like this perhaps:

var template = {
  "sentence": "The {{ object }} {{ verb }} ",
  "object": "{{ adjective }} {{ noun }}",
  "verb": "flew",
  "adjective": "colorful",
  "noun": "bird"
};

function interpolate(string, values) {
  return string.replace(/\{\{\s*(.*?)\s*\}\}/g, function (_, key) {
    return interpolate(values[key] || "", values);
  });
}

function fillInTheBlanks(template, key) {
  return interpolate(template[key], template);
}

// output (just for the stack snippet)
document.write( fillInTheBlanks(template, 'sentence') );

In this case, fillInTheBlanks is just there to kick things off. The actual work is done in interpolate. That function looks for instances of {{...}} in its input string, and then replaces it with the value for whatever key is between in the braces (ignoring spaces and such). And it calls itself on the resulting string, in order to achieve the recursive replacement behavior.

The name interpolate comes from "string interpolation", the general name for "filling in the blanks" in a template string.

The regular expression can be explained like so:

\{\{          // look for two opening braces "{{"
\s*           // followed by zero or more whitespace characters
(             // start a capture group
  .*?         // match anything that's matched by the following (ungreedy matching)
)             // end capture group
\s*           // match zero or more whitespace characters
\}\}          // match the close braces "}}"

You could skip the \s* parts, and instead match everything between {{ & }} and use trim to remove any leading/trailing whitespace afterward. However, trim isn't always available while the regex should work anywhere.

Anyway, that should match "{{foo}}", "{{  foo}}", "{{foo   }}", etc.. The capture group (group 1) will only match foo within that. The g flag after the regex means "global" - i.e. "replace all", not just the first match.

So when used with replace, the function passed in will receive the entire matched part of the string (e.g. "{{ foo }}") as its 1st argument. We don't care about the entire thing though, so the argument is just named _ in the above to denote we're not using it for anything (not to be confused with underscore/lodash js).

As its 2nd argument, the function receives the contents of the 1st capture group (e.g. "foo"), which is what we're interested in. (Had there been more capture groups, they would've been passed in as the 3rd, 4th, etc. arguments.) So we take that capture group's contents, and treat it as a key/property name, and look it up in the values object. Should the key not actually exist, values[key] will evaluate to undefined, so we handle that by defaulting to an empty string.

In other words, values[key] || "" reads as "get the value for key, or, if it's missing, use an empty string".

And that is then passed through interpolate again, so the string is  built recursively.

The danger with this is that the templating can itself be recursive. If, for instance, you call:

var values = {
  foo: "{{ bar }}",
  bar: "{{ foo }}"
};

interpolate("{{ foo }}", values);

it'll endlessly bounce back and forth, replace one with the other. In practical terms, JavaScript will of course just give up (i.e. raise an exception and stop dead) because the stack level - interpolate calling interpolate ad infinitum - will get too deep.

Your solution would enter an infinite loop instead, as it uses a while loop.

How to deal with such pathological input is outside the scope of this review, but would've been a good question to ask the interviewers. (Personally, I'd just let JS give up; the best you can do is write a bunch more code... and also give up, since there's no good solution. You can be more graceful about it and provide an error message, but that's about it.)

On a side note, the task seems a little weird. Why have fillInTheBlanks take a "raw" key, when the task is supposedly about templating? It'd make more sense to skip straight to interpolate("{{ sentence }}", template), as that's the core of the task. It's also why I chose to expose interpolate in the same scope as fillInTheBlanks - it could just as well be nested inside fillInTheBlanks, but it's far more useful when it's accessible.

I'd also wonder why the object holding the keys and values is called template. That makes no sense and is in fact backwards: The template is the string, and the object holds the values you use to fill in that template. Hence why I called it values in my function.


How can I make this code (that is usually in a loop) faster and efficiently?

Cache the instance of Graphics and Font objects so that you don't need to create them  each time you measure the length of string. I've created a small test to see which part takes most of the time:

private static void Main()
{
    Stopwatch stopwatch = Stopwatch.StartNew();

    stopwatch.Restart();
    for (int i = 0; i < 1000000; i++)
    {
        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
        {
            var size = g.MeasureString("asdasdf", new System.Drawing.Font("Arial", 14)).Width;
        }
    }
    Console.WriteLine("Current solution - create a new Graphics per measure: {0} milliseconds", stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();
    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
    {
        for (int i = 0; i < 1000000; i++)
        {
            var size = g.MeasureString("asdasdf", new System.Drawing.Font("Arial", 14)).Width;
        }
    }
    Console.WriteLine("Measure the string with Graphics cached: {0} milliseconds", stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();
    using (System.Drawing.Graphics g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
    using (var font = new System.Drawing.Font("Arial", 14))
    {
        for (int i = 0; i < 1000000; i++)
        {
            var size = g.MeasureString("asdasdf", font).Width;
        }
    }
    Console.WriteLine("Measure the string with Graphics and font cached: {0} milliseconds", stopwatch.ElapsedMilliseconds);
}

Results on my computer are:

Current solution - create a new Graphics per measure: 26864 milliseconds
Measure the string with Graphics cached: 6588 milliseconds
Measure the string with Graphics and font cached: 803 milliseconds

So by caching Graphics you'll reduce the time consumption by 75%, and by caching both Font and Graphics you get a nice 33.5X performance boost :).


Let me point out some things that I know can be improved so that other answers can focus on my problem.

SELECT *

I shouldn't be selecting all like this. Even if there's not really a performance hit because open query needs to get all of the meta data anyway, this is a bad habit to get into. Selects should be explicit in what we're selecting.

'SELECT  SUBSTR(NAME, 1, 3) AS CATID,

CATID isn't a very good alias. CategoryId would be much better and clearer to someone following me someday.

   WHERE  DBSTATUS IN (1,2)

This needs a comment saying what these DBSTATUSes actually represent. Mr. Maintainer would have to go find the lookup table in order to find out. (And this query gives no hint that the lookup table even exists.)


More elegant solution to create a array of fake data

Since you're iterating for the sole purpose of creating an array, map is somewhat appropriate here.

const productArr = [... Array(dataLength)] // Create a dummy array dataLength elements long
                     .map(_ => ({ // And map over it
                         name: faker.commerce.productName(),
                         category: faker.commerce.department(),
                         price: faker.commerce.price(),
                         description: faker.lorem.paragraph(),
                     }));

I'm mentioning it just in case you aren't aware of map, but it could be argued that this exact usage is an abuse of the function. Really, map is for transforming one list into another list of the same length. In this case though, we're completely ignoring the original contents of the array being iterated over (shown by the fact that the parameter is called _).

I can't say I necessarily recommend map in this case, but I thought I'd mention it.

If however you ever wanted to enumerate the data you're producing, it would be appropriate:

const productArr = [... Array(dataLength).keys()] // [0, 1, 2, 3, ...]
                         .map(i => ({
                             i: i, // And use the parameter this time
                             name: faker.commerce.productName(),
                             category: faker.commerce.department(),
                             price: faker.commerce.price(),
                             description: faker.lorem.paragraph(),
                         }));

Resource for the "range" on the first line..


It's very difficult to answer you, because what you've posted is a test-bed where your byte arrays are passed around in the context of a high-level language, as opposed to a real situation where you'd have (at the very least) two processes communicating down a pipe, TCP socket or similar. The details of how you do this are crucial; getting them wrong will destroy your security just as easily as if you get the crypto wrong.

I haven't thought about your code very much, but these questions immediately come to mind:

How are you sending and receiving data over the wire - how are your packets delimited and parsed?
How are the crypto keys being generated - specifically, what's their random source?
How are keys being stored at either end?
What RSA padding and AES mode are you using?
How do you know that the key you've got really belongs to the person you think it does, and not some man in the middle? In other words, how do you establish trust in that key?

As others have said, you should be reusing an existing library to use a well-established protocol. You might care to read the stick figure guide to AES: pay particular note to the Foot-Shooting Prevention Agreement; what goes for not inventing your own crypto algorithms, also goes for protocols.


SQL query with GROUP BY to show badges and points by user and course

Directly based on the current tables definition, I agree that it doesn't seem possible to have a better way of querying the needed results.

But it appears that performance might be improved using a slightly different approach, assuming that likely:

the number of courses and badges is reduced, compared to the number of users
courses and badges have relatively stable content (don't change daily!)

In the other hand we can notice that, in the current approach, courseAVG is computed again when the query is launched (more over, I'm not sure the optimizer takes care of computing it only once, rather than for each user/course pair!).

So an alternative approach might be:

add a pointsavg field to the Courses table
compute it in a separate UPDATE query (could be launched through a trigger applying AFTER INSERT and AFTER UPDATE on Badges and Courses

Here is it:

UPDATE Courses c
SET pointsavg = (
  SELECT AVG(points)
  FROM Badges b
  WHERE b.courseid = c.courseid
  GROUP BY courseid
);

Then we can simply use this pointsavg in the main query:

SELECT
  u.username,
  SUM(b.points) AS userCoursePoints,
  c.coursename,
  c.pointsavg AS courseAVG
FROM
  Users u,
  BadgeAssignments ba,
  Badges b,
  Courses c
WHERE ba.userid = u.id
  AND b.id = ba.badgeid
  AND c.courseid = b.courseid
GROUP BY u.username, b.courseid

Note that I took the opportunity to output username and coursename instead of their simple id, supposing it's closer to what is generally needed.

Here is the SQL fiddle:


Print the frequency of characters as a horizontal histogram

When dealing with offset arrrays (using position 0 to indicate character 32), it is important for readability to use symmetrical access patterns for the process. In your case, you load the values as c-' ', but what you use to read them, is accessed by i = 32; i < 127 .... and this asymmetrical access is inconvenient.

You also have no handling for out-of-bound characters.... can you trust your input sources to not have a carriage return, or a tab? Even esoteric null characters, or other binary values. I would have a catch-all 'bucket' for invalid values. That will prevent segfaults or other undefined actions.

You have a small bug in your code. In the print-loop, you increment the last character received.... what is this line for in the 'print' loops:

++histogram[c-' '];

Finally, for code reuse, it is often important to extract your functionality to a single reentrant method, other than the main method. Consider a signature like:

void histogram(const int offset, const int range)

where your histogram can be configured to take an offset position, and range, like:

histogram('a', 'z' - 'a' + 1);

which will count just the lower-case letters...

Something like:

#include <stdio.h>
#include <memory.h>

void histogram(const int offset, const int range) {
  int histogram[range];
  memset(histogram, 0, sizeof(histogram));

  int special = 0;

  int c;
  while ((c = getchar()) != EOF) {
    if (c < offset || c >= (offset + range)) {
        special++;
    } else {
        ++histogram[c - offset];
    }
  }

  for (int i = 0; i < range; ++i) {
    c = i + offset;
    printf("%c ", c);
    for (int j = 0; j < histogram[i]; ++j) {
      putchar('x');
    }
    putchar('\n');
  }

  printf("- ");
  for (int j = 0; j < special; j++) {
    putchar('x');
  }
  putchar('\n');
}

int main(void) {
    histogram(' ', 95);
}


Find minimum window size which includes the subset of characters

The first big issue that crosses my mind: Naming. In particular, commenting variables is always a sign that you did a poor job on giving them good names:

int j = 0; // the trailing position of the sliding window
int i = 0; // the leading position of the sliding window.

There is no reason to name loop variables i and j just because. If they have a meaning beyond just being there for the sake of looping, give them a name representing this. It makes the following code easier to read because the reader won't have to look up and remember their meaning.

After giving them proper names you can also get rid of declaring them outside the loop. Declaring them inside the loop makes the coder smaller, which is good not for the sake of having less lines (LoC is a terrible measurement of quality), but it reduces the overhead when trying to understand what is going on.

This applies especially to i and j, but also to many other names in your program:

What is ch supposed to tell me? I don't need information about the type of a variable – the compiler and IDE do a lot of the work for me here; what I, as a reader, care about is the semantics of variables.
Is there really any need for shortening matchCounter to matchCtr? Your IDE will help you avoid having to type too much. Of course experienced programmers have "ctr" already in their vocabulary and automatically translate it to "counter", but there is not really any reason these days to add this extra translation step.
I'll just leave out the rest, typically the same arguments apply as the ones I stated above.

Let's move on. What was the reasoning for making everything static? You forced yourself to do this:

addCharCount(hasFound, ch[i]);

This is called a side-effect method and unless there is no way around it, it should be avoided. It is counter-intuitive that this method actually mutates  the passed map (and from experience: this can easily cause very messy code and ugly bugs).

Instead, just make your class a normal (non-static) class with state. It allows you to get rid of some method parameters as they just become class members.

What you can do is make the constructor private (as it is now) and add a static method that creates a new instance and calls the proper method on it. This ensures that the caller doesn't call the method twice on the same instance and you won't have to deal with resetting members.

Refactoring this to a proper class will also allow you to avoid this as well as the block following it:

// check if match has been completed.
if (matchCtr >= subset.length()) {
    if ((i - j + 1) < min) {
        min = i - j + 1;
    }
}

Again, comments are good for mostly one thing: they signal code smell. If you have an entire block that needs a comment to be explained, it is time to think about whether the better way to go here is to extract a method with a good name that replaces the comment, because – to me – the single most profound fact about comments is that they rot faster than anything else and even the best comments will soon start lying. In other words: comments tend to become not just useless, but dangerous.

And your method is already big enough; too big, I would say. It does too many things on the same level of abstraction, so I would try splitting it up further.

Now to this:

if (matchCtr < subset.length()) {
    throw new IllegalArgumentException("The subset is not found in the input string.");
}

Is it really an illegal argument? You can argue that it is, but I tend to think that it's not. Is an exception even the right way to go here? Is this exceptional behavior you want the caller to deal with because you can't decide what to do here?

Finally, the tests. Again, the thing that really jumps into my eyes are names. What is test and test2 supposed to tell me about the test case here? Choose proper names describing the test cases, e.g

testShortestWindowAtTheEndOfStringIsFound
testShortedWindowWithinStringIsFound
…

Also, at first glance I fail to see why you chose to split your test cases into two tests as you did. I would say that every single assertion here deserves a test on its own (with proper name). This way, if a test fails, the test name alone is enough to tell you what isn't working, you won't have to first find out which assertion went wrong and you can be sure that the other cases are still working.


Asynchronous query to load products from laravel controller

Your example:

public function ajax(Request $request){
$data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();

foreach ($data['products'] as $product){
    echo $product->name;
}

Attn: I omit commented string.

You do not need to get the query results into $data, especially if before you perform $data = $request->all();. Use another variable, in this case the $products may be okay.

If your 'Product' model is correct, then in the query you not need to use products.id - i.e. table name, need just field name.

Next, when you want pass the result to view, you need to do so as described in Doc:

return view('your_view_name', ['products' => $products]);

As described in official documentation  - versions there are from 5.0 up to 5.8, choose any you need.

So, this part of your code becomes:

public function ajax(Request $request){
    $products = Product::select('id', 'name', 'banner')->get();
    return view('your_view_name', ['products' => $products]);
}

Remember 2 things:

With that query you'll get all products from DB and there may be a huge number of results.
the view has to be a blade type of template.

In your 'view' I see this line:

@foreach($leedManufacturers as $leedsManufacturer)

but I do not see a variable $leedManufacturers in the controller so you have no data for it.

To show $products result use the same but for $products, like:

    @foreach($products as $product)

id: {{$product->id}}, name: {{$product->name}}

{{$product->banner}}

    @endforeach

Also, when you need , you may use this (example)

@if (xxxxxxxxx === 1)
    I have one record!
@elseif (yyyyyyyyyy > 1)
    I have multiple records!
@else
    I don't have any records!
@endif

https://laravel.com/docs/5.3/blade#if-statements

And in view you can use even

@php
    pure php code here
@endphp


Style

Python has a style guide called PEP 8 which is definitly worth reading and and worth following if you do not have good reasons not to. In you case, your function name for instance is not compliant to PEP8. You'll find tools online to check your code compliancy to PEP8 in a automated way if you want to.

Docstrings

There are Python docstring conventions you can find in PEP 257. Instead of

# Takes an integer, returns true or false
def isPrime(number):

You could write :

def isPrime(number):
    """Return whether an integer is prime."""

Please note: the imperative tone, the triple-quote strings under the def line, the ending period.

Do less

If your function isPrime takes an integer as a parameter, you do not need number = int(number).

Also, you can rewrite :

# Check if the only factors are 1 and itself and it is greater than 1
if len(findFactors(number)) == 2 and number > 1:
    return True

return False

as

# Check if the only factors are 1 and itself and it is greater than 1
return len(findFactors(number)) == 2 and number > 1

Different algorithm

You do not really need to find the list of all factors to know if the number is prime. You can stop as soon as a factor is found.


Executing query via nested inner class query handler

I would say that we should be able to execute different query handlers given the same query parameters – for testing purposes. Simple data transfer object (query) being passed to the repository interface allows us to do it in a well-known and understandable way.

The same time the following works well for me (SSAS MDX queries)…

To define MDX I use a partial class in multiple files (example):

// SalesSummary.cs
public static partial class MdxQueries
{
    public static IEnumerable<TradeSummary> SalesSummary(DateTime day, string department) =>
        new MdxQuery($@"MDX SCRIPT WITH PARAMETER={day} AND PARAMETER={department}")
            .Select(r => new TradeSummary
            {
                Product = r["Product"],
                Total = r["Total"]
            });
}

// PurchaseSummary.cs
public static partial class MdxQueries
{
    public static IEnumerable<TradeSummary> PurchaseSummary(DateTime day, string department) =>
        new MdxQuery($@"MDX SCRIPT WITH PARAMETER={day} AND PARAMETER={department}")
            .Select(r => new TradeSummary
            {
                Product = r["Product"],
                Total = r["Total"]
            });
}

Where library classes are:

public class MdxQuery : IEnumerable<MdxRow>
{
    static string ConnectionString => ConfigurationManager.ConnectionStrings["SSAS"]
        .ConnectionString;

    public MdxQuery(string mdx)
        : this(mdx, ConnectionString)
    {
    }

    public MdxQuery(string mdx, string connectionString)
    {
        _mdx = mdx;
        _connectionString = connectionString;
    }

    readonly string _mdx;
    readonly string _connectionString;

    public IEnumerator<MdxRow> GetEnumerator()
    {
        using (var connection = new AdomdConnection(_connectionString))
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = _mdx;
            var reader = command.ExecuteReader();
            while (reader.Read())
                yield return new MdxRow(reader);
        }
    }

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    public static implicit operator MdxQuery(string mdx) =>
        new MdxQuery(mdx);
}

Where:

public struct MdxRow
{
    internal MdxRow(AdomdDataReader reader)
    {
        Values = Enumerable.Range(0, reader.FieldCount)
            .ToDictionary(i => reader.GetName(i), i => new MdxValue(reader[i]));

        ValuesByIndex = Enumerable.Range(0, reader.FieldCount)
            .ToDictionary(i => i, i => new MdxValue(reader[i]));
    }

    public MdxValue this[string column] => Values[$"[Measures].[{column}]"];
    public MdxValue this[int column] => ValuesByIndex[column];
    Dictionary<string, MdxValue> Values { get; }
    Dictionary<int, MdxValue> ValuesByIndex { get; }
}

Where:

public struct MdxValue
{
    public MdxValue(object value)
    {
        Value = value;
    }

    object Value { get; }

    public static implicit operator string(MdxValue value) =>
        Convert.ToString(value.Value);

    public static implicit operator int(MdxValue value) =>
        Convert.ToInt32(value.Value ?? 0);

    public static implicit operator double(MdxValue value) =>
        Convert.ToDouble(value.Value ?? 0);

    public static implicit operator int? (MdxValue value) =>
        value.IsNull ? (int?)null : (int)value;

    public static implicit operator double? (MdxValue value) =>
        value.IsNull ? (double?)null : (double)value;

    public static implicit operator DateTime(MdxValue value) =>
        DateTime.Parse((string)value ?? DateTime.MinValue.ToString());

    public static implicit operator DateTime? (MdxValue value) =>
        value.IsNull ? (DateTime?)null : (DateTime)value;

    public bool IsNull => Value == null;
}

All this stuff is used to implement repositories, which depend on DTO.


Accessing fields in LINQ query for customers with overdue balances

This is a pretty good attempt for someone just starting out. However, there is always a lot to learn and the books never seem to take advantage of all the latest language features.

The first thing I'm going to tell you to do is stop abbreviating everything. You don't pay extra for full naming.

I'll choose you constructor to highlight this:

public Customer(string name, string phn, string addr, decimal         bal)
{
    CustName = name;
    CustPhone = phn;
    CustAddress = addr;
    CustBalance = bal;
}

First, Customer is a great name, name is also good.

Now, string phn I'd guess at phoneNumber but it could also be the name of the Primary Health Network if this was an Australian healthcare customer. string addr - is address really that much harder to type? decimal is a great choice for the balance but bal is a terrible name and there's some extra whitespace which should be removed.

Also, your fields shouldn't start with Cust. They should aslo be camelCase. The old version of the guidelines stated this explicitly but the newer C# standards don't specify a convention for non public fields. Most people use camelCase in my experience. As a commenter has mentioned, you can use auto properties:

public string Name { get; set; }
public decimal Balance { get;set; }

You can set them directly in your constructor.

I'm assuming you're using the latest and greatest C# for the next few points. I can't remember when collection initializers were introduced but it's a while ago now.

This is a very common pattern:

List<Customer> customers = new List<Customer>();
customers.Add(new Customer("Alan", "80911291", "ABC Street", 25.60m));
customers.Add(new Customer("Bill", "19872131", "DEF Street", -32.10m));
customers.Add(new Customer("Carl", "29812371", "GHI Street", -12.2m));
customers.Add(new Customer("David", "78612312", "JKL Street", 12.6m));

It's so common, we have a construct to make it easier:

var customers = new List<Customer>
{
    new Customer("Alan", "80911291", "ABC Street", 25.60m),
    new Customer("Bill", "19872131", "DEF Street", -32.10m),
    new Customer("Carl", "29812371", "GHI Street", -12.2m),
    new Customer("David", "78612312", "JKL Street", 12.6m)
};

That's a lot less typing and a bit easier to scan IMO.

We also now have string interpolation (this one is much newer):

Console.WriteLine("Name = {0}, Balance = {1}", cust.Name, cust.Balance);

Can become:

Console.WriteLine($"Name = {cust.Name}, Balance = {cust.Balance}");

Which is a lot less scanning backwards and forwards to see what goes where.

For the sake of completeness, let's look at your naming here:

var overdue =
    from cust in customers
    where cust.Balance < 0
    orderby cust.Balance ascending
    select new { cust.Name, cust.Balance };

overdue is better as overdueCustomers.
from customer in customers is equally better than using cust which isn't a word.

You could then finally do a foreach (var overdueCustomer in overdueCustomers) to make it obvious everywhere in the code that the reason you're interested in this particular customer is that they are overdue.

Edit

As noted in a comment from Peter Taylor, overdrawnCustomers is an even better name. It doesn't have the date connotation that overdue does.


I am making some assumptions about your code, specifically that listItem is of type SPListItem and that listItem.Properties is a HashTable.  This is mainly to provide context for my explanation, but even if I am mistaken, most of my comments will still hold.  For the sake of context, let's assume your actual method looks like:

 void HandleBooleanListItemProperty( SPListItem listItem ){
    if (bool.Parse(listItem.Properties["Boolean Property"].ToString()) == false){
        // do something if the Boolean ListItem property is false
    }
    else
    {
        // do something if the Boolean ListItem property is true
    }
}

Validate that the object exists before you call ToString().  The way your method is currently written, you will get a NullReferenceException if the key "Boolean Property" is missing or the hashed value that corresponds to the "Boolean Property" key is null.  This refactoring will make the method look like:

void HandleBooleanListItemProperty2( SPListItem listItem ){
     object booleanPropertyValue = listItem.Properties["Boolean Property"];
     if ( ReferenceEquals( booleanPropertyValue, null ) ) {
         // do something if the Boolean ListItem property is missing
     }
     else if (bool.Parse(booleanPropertyValue.ToString()) == false){
         // do something if the Boolean ListItem property is false
     }
     else {
         // do something if the Boolean ListItem property is true
     }
 }

Use bool.TryParse instead of bool.Parse.  If the ToString() value of the hashed value corresponding to the key "Boolean Property" is anything other than "true" or "false" (case-insensitive), a FormatException will be thrown.  This refactoring will make the method look like:

 void HandleBooleanListItemProperty3( SPListItem listItem ){
     object booleanPropertyValue = listItem.Properties["Boolean Property"];
     bool parsedBooleanPropertyValue;
     if ( ReferenceEquals( booleanPropertyValue, null ) ) {
         // do something if the Boolean ListItem property is missing
     }
     else if (bool.TryParse(booleanPropertyValue.ToString(), out parsedBooleanPropertyValue) )
     {
         if(parsedBooleanPropertyValue == false){
            // do something if the Boolean ListItem property is false
         }
         else {
           // do something if the Boolean ListItem property is true
         }
     }
     else {
          // do something if the Boolean ListItem property's ToString() value was something other than "true" or "false"
     }
 }

If the hashed value that corresponds to the "Boolean Property" key is really a bool, then cast it before comparing.  Calling ToString() just throws away .NET's type-safety.  This refactoring will make the method look like:

 void HandleBooleanListItemProperty4( SPListItem listItem ){
     object booleanPropertyValue = listItem.Properties["Boolean Property"];
     if (booleanPropertyValue is bool)
     {
        bool castBooleanPropertyValue = (bool) booleanPropertyValue;
         if( castBooleanPropertyValue == false ){
            // do something if the Boolean ListItem property is false
         }
         else {
           // do something if the Boolean ListItem property is true
         }
     }
     else {
         // do something if the Boolean ListItem property is not a bool
         if ( ReferenceEquals( booleanPropertyValue, null ) ) {
             // do something if the Boolean ListItem property is missing
         }
         else {
             // do something if the Boolean ListItem property is something other than a bool
         }
     }
 }

Eliminate magic strings from your value accessor.  This requires removing the inline "Boolean Property" and declaring with that value, and then using the constant in order to access the value in every usage.  This decreases the possibility that a typos will cause bugs.  An article on magic strings is available at: http://codebetter.com/matthewpodwysocki/2009/03/19/functional-net-lose-the-magic-strings/ .  The resulting refactoring would look like:

 const string BooleanPropertyKey = "Boolean Property";

 void HandleBooleanListItemProperty5( SPListItem listItem ){
     object booleanPropertyValue = listItem.Properties[BooleanPropertyKey];
     if (booleanPropertyValue is bool)
     {
        bool castBooleanPropertyValue = (bool) booleanPropertyValue;
         if( castBooleanPropertyValue == false ){
            // do something if the Boolean ListItem property is false
         }
         else {
           // do something if the Boolean ListItem property is true
         }
     }
     else {
         // do something if the Boolean ListItem property is not a bool
         if ( ReferenceEquals( booleanPropertyValue, null ) ) {
             // do something if the Boolean ListItem property is missing
         }
         else {
             // do something if the Boolean ListItem property is something other than a bool
         }
     }
 }

Use the negation operator (!) instead of comparing to false.  This is much more readable and will save you time in the long run.  This final refactoring looks like:

 const string BooleanPropertyKey = "Boolean Property";

 void HandleBooleanListItemProperty6( SPListItem listItem ){
     object booleanPropertyValue = listItem.Properties[BooleanPropertyKey];
     if (booleanPropertyValue is bool)
     {
        bool castBooleanPropertyValue = (bool) booleanPropertyValue;
         if( !castBooleanPropertyValue ){
            // do something if the Boolean ListItem property is false
         }
         else {
           // do something if the Boolean ListItem property is true
         }
     }
     else {
         // do something if the Boolean ListItem property is not a bool
         if ( ReferenceEquals( booleanPropertyValue, null ) ) {
             // do something if the Boolean ListItem property is missing
         }
         else {
             // do something if the Boolean ListItem property is something other than a bool
         }
     }
 }


Doubly linked list implementation in Python

OK, a few things:

I would make head and size private, you don't want them changed from outside the class.
You should use __len__ instead of __sizeof__ - they have different meanings.
Implement __iter__
After doing #3, format the repr using:

"[{}]". format(", ". join(map(str, self)))


Iterating an Array Object & Assigning the Attributes Values to those that Match the Condition

Hmm i would in a first refactoring change it to this:
this.testCenterAccomodations.forEach((x: { utilityCode: string; isChecked: boolean; isSelected: boolean; }) => {
  if (x.utilityCode != 'PSDQRA') {
    return;
  };
  x.isChecked = this.voiceOverLanguageChecked;
  x.isSelected = this.voiceOverLanguageChecked;
});

The next changes do not have the goal of "shortening" the code. But to make it more readable and easier to change. I would love to hear your feedback about my thoughts.
I would create a small (perhaps local) interface, because { utilityCode: string; isChecked: boolean; isSelected: boolean; } seems to be a recurring thing.
interface UtilityCodeSelection {
  utilityCode: string;
  isChecked: boolean;
  isSelected: boolean;
}

Which will result in
this.testCenterAccomodations.forEach((x: UtilityCodeSelection ) => {
  if (x.utilityCode != 'PSDQRA') {
    return;
  };
  x.isChecked = this.voiceOverLanguageChecked;
  x.isSelected = this.voiceOverLanguageChecked;
});

Then i would replace the magic variable "PSDQRA" by a constant (or by an enum if you have multiple utility codes we are coding against). Then we could use that constant at all necessary places and would be able to change it centraly. ALSO we can easily find out where our code is refering to this specific value.
interface UtilityCodeSelection {
  utilityCode: string;
  isChecked: boolean;
  isSelected: boolean;
}

export enum UtilityCodes {
    PSDQRA = 'PSDQRA', // Or if PSDQRA has in reality a better name, use that for the enum
    ...
}

this.testCenterAccomodations.forEach((x: UtilityCodeSelection ) => {
  if (x.utilityCode != UtilityCodes.PSDQRA) {
    return;
  };
  x.isChecked = this.voiceOverLanguageChecked;
  x.isSelected = this.voiceOverLanguageChecked;
});

And in some cases i would even extract some parts into its own method
this.testCenterAccomodations.forEach((x: UtilityCodeSelection ) => this.setUtilityCodeSelection(x, UtilityCode.PSDQRA, this.voiceOverLanguageChecked));

 private setUtilityCodeSelection(code: UtilityCodeSelection, forCode: UtilityCode, setTo: boolean):void{
    if (code.utilityCode != forCode) {
      return;
    };
    code.isChecked = setTo;
    code.isSelected = setTo;
}

This has some drawbacks. I personaly do not like implict changes (here we change the given code) and prefere to change explicitly (make a copy, change the copy and return the copy). Also the extra method is only useful if there are more similar checks. In general its a bad idea to try to generalize things, if there is (at least now) no need for it.
Therefor the chance is high that in your example, i would not move the code in its own method..
As always... Ask 3 developers about coding style and you will get 4 answers. :-)
And they all will be right in some way.
warm regards