A few comments -

It seems that while your code should work fine as is, it could be improved in the following ways:

A. It seems like you have three methods here when only one or two would be necessary. You may have your reasons for doing this, but the "middle-man" method "EncodeDropDownItem" seems superfluous.

B. The way you are hard-coding the calls to sb.replace, one at a time and with target/replacement values "inlined" might be more effective if they were preformed within a looping structure, with the Axss tags and replacement values retrieved from a custom dictionary. The hard-coded Axss tags and related character representations could then be encapsulated within that custom dictionary class, and re-used in other contexts if necessary.

You may have your reasons for structuring your methods the way you have. However, I make the below suggestions for your code. Note that I am not able to test this, but hopefully you or some other forum readers will catch anything I screw up here . . .

FIRST - a custom dictionary for the Axss tags/values:

    class AntiAxssDictionary : Dictionary<String, String>
    {
        public void AntiAxssDictionary()
        {
            this.Add("&#38;", "&");
            this.Add("&#60;", "<");
            this.Add("&#62;", ">");
            this.Add("&#34;", "\"");
            this.Add("&#92;", "\\");
        }
    }

THEN, a minor rearrangement of your methods (this might be a matter of taste, or function, but this is how I would do it, given what little I know about your code):

    // raising the databound event to to encoding
    protected void ddlCountry_DataBound(object sender, EventArgs e)
    {
        if (ddlCountry.Items.Count > 0)
        {
            //Initialize an AntiAxssDictionary object:
            AntiAxssDictionary tokenProvider = new AntiAxssDictionary();

            foreach (ListItem list in ddlCountry.Items)
            {
                // Encode the AntiAxss string here:
                StringBuilder sb = new StringBuilder(AntiXss.HtmlEncode(list.Text));

                // Iterate through the Axss tags stored as keys in the dictionary:
                foreach (String token in tokenProvider.Keys)
                {
                    // Attempt a replacement for each of the possible
                    // values in the Axss dictionary:
                    sb.Replace(token, tokenProvider[token]);
                }

                // Assign the new value to the list.text property:
                list.Text = sb.ToString;
            }
        }
    }

Hopefully I didn't butcher anything too badly here. I am in the midst of migrating from vb.net to C#, and learning Java at the same time. Hope that helps, and I will be interested to hear commentary and critique from other forum members.


Summing the digits of a sum of digits of a sum

Despite your code being cumbersome, I would like to point out that you did well by writing for x in zstr1, iterating over the characters of the string.  Python beginners often try to iterate over character indexes instead, resulting in unnatural Python code.

I would decompose the problem differently than @jonrsharpe.  sum_digits(n) is a generally useful operation to define as a function.

def sum_digits(n):
    return sum(int(char) for char in str(n))

sum_digits(sum_digits(b_yr + b_mo + b_dy))

Actually, it's not necessary to conflate the summing and the digit breakdown.

def digits(n):
    return [int(char) for char in str(n)]

sum(digits(sum(digits(b_yr + b_mo + b_dy))))

The last line reads just like the problem description: "sum of the digits of the sum of the digits of the year, month, and day".

Here's another implementation of digits(n), using a generator.  This avoids stringification.

def digits(n):
    """Produce the base-10 digits of n from least to most significant."""
    while n:
        yield n % 10
        n /= 10


The Morra game implementation in Haskell

You don't really use the StateT to your advantage. Your play function can be written as

play :: Int -> ([String], Int) -> IO ([String], Int)
play p (ps, n) = do
  let currp = ps !! p
  if length ps == 1
    then return (ps, n)
    else do
      putStr $ "It's now " ++ currp ++ "'s turn. How many fingers will be help up? "
      a <- safeGetLine
      putNewLine
      putStrLn "[INPUT PHASE] Each player now chooses, how many fingers does (s)he hold up."
      fs <- getFingers (length ps)
      putStr "[END OF INPUT PHASE]"
      putNewLine
      if sum fs == a
        then do
          putStrLn $ currp ++ " has guessed right, he's out."
          putNewLine
          let newps = delete currp ps
          play ((p + 1) `mod` length newps) (newps, n + 1)
        else do
          putStrLn $ currp ++ " hasn't guessed right, the game goes on!"
          putNewLine
          play ((p + 1) `mod` length ps) (ps, n + 1)
  where
    putNewLine = putStrLn ""

That's not really surprising, since State s a is more or less just an abstraction of s -> (s, a). Since a is () in your case, we can just get rid of it and end up with s -> IO s. We can use State(T) to our advantage if we have several Stateful functions. However, we only have play.

Speaking about play, there are several nitpicks:

You use length several times, although a single length call would suffice.
You should use guess instead of a as name.

If we apply both, we end up with

play :: Int -> StateT ([String], Int) IO ()
play p = do
  (ps, n) <- get
  let currp = ps !! p
  let plength = length ps
  unless (plength == 1) $ do
      liftIO $ putStr $ "It's now " ++ currp ++ "'s turn. How many fingers will be help up? "
      guess <- liftIO safeGetLine
      putNewLine
      liftIO $ putStrLn "[INPUT PHASE] Each player now chooses, how many fingers does (s)he hold up."
      fs <- liftIO $ getFingers plength
      liftIO $ putStr "[END OF INPUT PHASE]"
      putNewLine
      if sum fs == guess
        then do
          liftIO $ putStrLn $ currp ++ " has guessed right, he's out."
          putNewLine
          put (delete currp ps, n + 1)
          play ((p + 1) `mod` (plength - 1))
        else do
          liftIO $ putStrLn $ currp ++ " hasn't guessed right, the game goes on!"
          putNewLine
          put (ps, n + 1)
          play ((p + 1) `mod` plength)
  where
    putNewLine = liftIO $ putStrLn ""

We didn't  gain that much, did we? So let's split play:

type Player     = String
type Turn       = Int
type MorraT m a = StateT ([Player], Turn) m a
type Morra a    = MorraT IO a

play :: Morra ()
play = do
   pcount <- getPlayerCount
   unless (pcount == 1) $ do
     currp <- getNextPlayer
     guess <- guessFingers currp
     fingers <- getFingers
     if fingers == guess
       then do
         putStrLn' $ currp ++ " has guessed right, they're out!"
         removePlayer currp
       else do
         putStrLn' $ currp ++ " hasn't guessed right, the game goes on!"
         increaseTurnCount
         play
  where
    putStrLn' xs = liftIO $ putStrLn xs >> putStrLn ""

That's easy enough to undestand. We also added some types so that we can change our program in a single line, for example if you want to change the StateT to something else later.

Now we need our helper functions:

players :: Monad m => MorraT m [Player]
players = fst <$> get

That's a convenient small function and makes it possible to change our Morra later without changing too many functions.

For our getNextPlayer we want to get the next player as well as queue them to the back of the line. A list isn't the perfect data structure here, by the way, but we keep it for simplicity:

getNextPlayer :: Monad m => MorraT m Player
getNextPlayer = do
  (p:ps) <- players
  put (ps ++ [p])
  return p

guessFingers looks exactly how you'd imagine it. It doesn't need to be in Morra, as it does not inspect the state, but let's keep it there for simplicity, again:

guessFingers :: Player -> Morra Int
guessFingers p = do
  liftIO $ putStrLn $ p ++ ", what's your guess?"
  liftIO $ safeGetLine

Your variant of getFingers only tells a person to give the PC to the next player, but it does not tell them who the next player is going to be. That can be fixed by using forM instead of replicateM:

getFingers :: Morra Int
getFingers = do
  ps <- players
  fmap sum $ forM ps $ \p ->
    liftIO $ putStrLn $ "How many fingers do you hold up, " ++ p ++ "?"
    liftIO $ getSafeLine

removePlayer looks the same as yours:

removePlayer :: Monad m => Player -> MorraT m ()
removePlayer p = modify $ \(ps, n) -> (delete p ps, n)

Note that a setPlayers or withPlayers function would make both this and getNextPlayer simpler.

increaseTurnCount :: Monad m => MorraT m ()
increaseTurnCount = modify $ \(ps, n) -> (ps, n + 1)

That's it. We now have several functions that can be used independently but act on the same state. By the way, the single increaseTurnCount hints that the amount of Turns isn't really part of the State, but could be used as the return value of play instead.

For completeness, we can provide

runMorra :: Monad m => [Player] -> MorraM m a -> m (Player, Int)
runMorra ps = do
  ([p], n) <- execStateT play (ps, 0)
  return (p, n)

One last remark on safeGetLine. Instead of all isNumber use readMaybe from Text.Read:

safeGetLine :: IO Int
safeGetLine = do
  x <- getLine
  case readMaybe x of
    Just n  -> return n
    Nothing -> putStrLn "Please input a number" >> safeGetLine

Otherwise your safeGetLine isn't safe, since isNumber also returns True on Unicode Characters in the 'Number, Other' Category.


You my also want to have a look at how the Poco library achieves a similar thing using a Tuple class. From the docs:

typedef Poco::Tuple<std::string, std::string, int> Person;
typedef std::vector<Person> People;

People people;
people.push_back(Person("Bart Simpson", "Springfield", 12));
people.push_back(Person("Lisa Simpson", "Springfield", 10));

Statement insert(session);
insert << "INSERT INTO Person VALUES(:name, :address, :age)",
    use(people), now;

Statement select(session);
select << "SELECT Name, Address, Age FROM Person",
    into(people), now;

for (People::const_iterator it = people.begin(); it != people.end(); ++it)
{
    std::cout << "Name: " << it->get<0>() <<
        ", Address: " << it->get<1>() <<
        ", Age: " << it->get<2>() <<std::endl;
}


Looking through the code, I see often the "high level wrapper" returns CLuints and such. I would say that is improper - Why not return the haskell type?

Instead of returning, say, CLint, do

f :: Integral i => ... -> i

so that the user doesn't have to litter his code with those types and fromIntegrals all over the place.

Also, don't leave commented code in the repository. You can always recover via git if you need to.


You made a look-up table. Here's 2 things to note:

Your look up table is between 2 types, but your table is only 1 type. You break type safety. They are enums and it's 'safe' if the enums have the same underlying type, but dirty either way.
A switch frequently generates a look up table for you, and in this case definitely     will on any decent compiler. It will not generate an if-if else-else chain. See the     following:

:

FAddressType maptype(CfgFruitType cfgtype)
{
    switch(cfgtype)
    {
    case CFGNoFruit:    return AddressTypeUnknown;
    case CFGApple:      return AddressTypeApple;
    case CFGApricot:    return AddressTypeUnknown;
    case CFGBanana:     return AddressTypeUnknown;
    case CFGMango:      return AddressTypeUnknown;
    case CFGKiwi:       return AddressTypeUnknown;
    case CFGFig:        return AddressTypeUnknown;
    case CFGGrape:      return AddressTypeUnknown;
    case CFGMelon:      return AddressTypeUnknown;
    case CFGLemon:      return AddressTypeUnknown;
    case CFGNectarine:  return AddressTypeUnknown;
    case CFGPineapple:  return AddressTypeUnknown;
    case CFGWatermelon: return AddressTypeUnknown;
    case CFGCherry:     return AddressTypeCherry;
    case CFGPear:       return AddressTypePear;
    case CFGStrawberry: return AddressTypeStrawberry;
    default:            assert(!"Not a valid CfgFruitType!"); return AddressTypeUnknown;
    }
}

Shorter code, very clear, easy to add new cases, very likely to outperform (by a negligible margin) your code.

Or, you could be less explicit and make it really short:

switch(cfgtype)
{
case CFGApple:      return AddressTypeApple;
case CFGCherry:     return AddressTypeCherry;
case CFGPear:       return AddressTypePear;
case CFGStrawberry: return AddressTypeStrawberry;
default:            return AddressTypeUnknown;
}


Find all strings matching a giving regex pattern in files in a directory (including all subdirectories)

Some improvements

Style

Please indent your file properly, since indentation is important in Python, those lines like

if path.isdir(pth):   res.update(regex_search(regex, pth))

Are frowned upon, instead do

if path.isdir(pth):
    res.update(regex_search(regex, pth))

Use glob for listing files in a directory

With Python3.5+ glob is the easiest way to list all files in a directory and subdirectory, before you should use os.walk()
Use generators when appropriate

This will save some memory space, as it doesn't have to append to the temporary list all the time
Use argparse over sys.argv[]

Argparse is the module for CLI input, easy to use and has a ton of features I definitely recommend it!

Code

import argparse
import glob
import re
import os
import pathlib

def regex_search(regex, directory):
    for f in glob.glob(f"{directory}**/*.*", recursive=True):
        with open(f) as _file:
            for i, line in enumerate(_file.readlines()):
                if regex.search(line):
                    yield f"In file {f} matched: {line.rstrip()} at position: {i}"

def parse_args():
    parser = argparse.ArgumentParser(
        usage='%(prog)s [options] <regex> <directory>',
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument('regex', type=str)
    parser.add_argument('directory', type=str)
    args = parser.parse_args()

    try:
        rgx = re.compile(args.regex)
    except Exception as e:
        parser.error('Regex does not compile')
    directory = pathlib.Path(args.directory)
    if not os.path.isdir(directory):
        parser.error('Directory is not valid')
    return rgx, directory

if __name__ == '__main__':
    regex, directory = parse_args()
    for match in regex_search(regex, directory):
        print(match)

Bonus Round!

grep is a Unix tool that can basically do this by default

grep -Hrn 'search term' path/to/dir

Where:

-H prints the matching line
-r Does a recursive search
-n prints the line number


char* result = strcpy((char*)malloc(str.length()+1), str.c_str());

This seems more suited for a C program than a C++ one. In fact, with C++11, you don't need to write your own function.

Behold: std::remove_if

Note:

  std::remove_if

  Removes all elements satisfying specific criteria from the range
  [first, last) and returns a past-the-end iterator for the new end of
  the range.

  A call to remove is typically followed by a call to a container's
  erase method, which erases the unspecified values and reduces the
  physical size of the container to match its new logical size.

This is what you would do:

str.erase(remove_if(str.begin(), str.end(), ::isspace), str.end());

I am not sure if this is the safest or most efficient method, but I think it's definitely an improvement to what you have done.


Personal questionnaire using JavaScript prompts

You seem to be on the right track, at least with grasping how to do some basic coding.

Right now, I only see one major issue: document.write()

document.write() is used to build pages out of javascript, something that is both impractical and ill-advised (in almost every situation). Moving forward, you should start building your pages in HTML and use javascript to tweak the page from that point.

To do this, you will want to replace document.write() with document.getElementById(). Lets look at an example:

You have the following HTML block:

Now, to insert text into this block, we would do something like this:

var welcomeElement = document.getElementById('welcome');
welcomeElement.innerHTML = "This is my welcome message!";

There's many things you can do with elements once you have gotten them, but I'll leave that for a later experiment.

At this point, I'll leave you to learn how to update your code. If you get confused or stuck however, you can view my rendition of your code here:

http://jsfiddle.net/danthegoodman/v7gLE/


You should not apply len, because that requires that the first argument be at least as strong as a Collection, when zip should not need that guarantee and should only need Iterable which is a weaker type.
Gathering results in memory can be inefficient and lead to memory starvation. It's worth noting that an in-memory approach might actually execute more quickly than a generator but you would want to test this.
Attempt some type hinting. The amount of type-hinting you can do here is fairly limited, but you can do better than nothing.
It's also worth noting that the official documentation has a reference implementation.
Suggested
from typing import Any, Iterable, Tuple

def myzip(*args: Iterable[Any]) -> Iterable[Tuple[Any, ...]]:
    first_iter, *other_iters = (iter(a) for a in args)

    for first in first_iter:
        yield (first, *(
            next(other) for other in other_iters
        ))

for a, b in myzip([1, 2, 3], [4, 5, 6]):
    print(a, b)

Alternate
This version does not need to wrap the first argument in an iterator.
def myzip(first_iter: Iterable[Any], *args: Iterable[Any]) -> Iterable[Tuple[Any, ...]]:
    others = [iter(a) for a in args]

    for first in first_iter:
        yield (first, *(
            next(other) for other in others
        ))


Formatting

It's common to see let-bindings vertically aligned, one per line. You've done that further down in resolve-auction, but even with just two name-value pairs it can be easier to see the logical parts vertically. The closing brackets (any kind) are also usually on the last line of the form, as opposed to indented back out. So

(defn as-trade-result
  [ask bid]
  (let [bid-price (:price bid) ask-price (:price ask)]
    {:traded (<= ask-price bid-price) :bid bid :ask ask}
    )
)

would more idiomatically be formatted as

(defn as-trade-result
  [ask bid]
  (let [bid-price (:price bid)
        ask-price (:price ask)]
    {:traded (<= ask-price bid-price)
     :ask ask
     :bid bid}))

Semantic indentation

Also, the indentation here with (first (partition-by ending the line:

(let [best-asks (sort-by :price asks)
      best-bids (reverse (sort-by :price bids))
      succesful-trades (first (partition-by
          :traded
          (map as-trade-result
               best-asks
               best-bids)))

would more commonly be written in a way that reads left-to-right, top-to-bottom, in terms of expressions. Here are some examples:

(let [best-asks (sort-by :price asks)
      best-bids (sort-by (comp - :price) bids) ; negated :price gives you (reverse) in a single pass
      successful-trades
      (first
        (partition-by :traded (map as-trade-result best-asks best-bids)))]

      ; or

      successful-trades
      (->> (map as-trade-result best-asks best-bids)
           (partition-by :traded)
           first)

The point here is that the indentation is not just a continuation, but actually shows the code structure. Something in the (bottom) right is expected to flow towards the (top) left.

When you get used to this it makes reading code much faster because it's easy to see what is dependent on what, structure-wise.

Side note: since you only want the first group the partition-by is overkill. Consider take-while:

      successful-trades
      (->> (map as-trade-result best-asks best-bids)
           (take-while :traded))

Expose more of the data

There is a balance here between encapsulating complex logic and making things clear. Someone familiar with Clojure knows instantly what assoc, merge, and so on mean. It's less clear exactly what a trade-price-tagger does until one looks it up. For relatively simple cases like that, using an inline function is idiomatic and arguably more clear. Compare:

(defn trade-price-tagger
  [price]
    (fn [trade] (merge trade {:price price}))
  )
...
(map (trade-price-tagger breakeven-price) succesful-trades)

with

(map #(assoc % :price breakeven-price) succesful-trades)

Similarly, accessors like

(defn bid-price
  [trade]
  (-> trade :bid :price))

(bid-price breakeven-successful-trade)

can be useful for deep objects or large programs, but in something short like this (get-in) could be fine:

(get-in breakeven-successful-trade [:bid :price])

In general I think this is readable and reasonably structured. Nice work as someone new to Clojure/Lisp!

My only other suggestion would be potentially to split up resolve-auction. The first half could be a function (defn get-successful-trades [asks bids]), and resolve-auction could just do the tagging of the breakeven point.


PHP pages with multiple conditionally displayed search elements

I think your general approach of moving towards reusable components is one that is very popular across a broad range of applications. Since you pretty much only have trivial code in your question, I will talk more towards the design.

You mentioned a polling feature for search history.  This doesn't make sense to me. You know exactly when a user performs a search, so I don't know why you would need to poll for this information. In initial page load you can load into initial page source, but for asynchronous AJAX searches you should be able to simply update the history in response to the search events.

Be very careful when designing your components to decide what content needs to be loaded on initial page view vs. what content should be loaded asynchronously.

I also find it to be an odd pattern to have this route/switch construct when you are doing nothing but including a separate file anyway. Why not make these different end points on your API?

What is the difference between basic search and advanced search? Should this really be treated as two separate components?


First step would be to extract a function that updates the input:

function modifyProgress(delta) {
  var element = $('#progress');
  var progress = +element.val() + delta;
  element.val( isNaN(progress) ? 0 : progress < 0 ? 0 : progress > 100 ? 100 : progress;
);
}

BTW, never ever use parseInt with out its second parameter (radix). Some browsers interpret numbers starting with a leading 0 (zero) as octal, so that an input of "09" throws an error and "010" to returns 8. Better is to use the unary plus operator.

This simplifies the event handler:

$(document).on('click', '#plus, #minus', function(e){
   modifyProgress(5 * (this.id === "plus" ? 1 : -1));
})

EDIT: You should consider storing your progress value somewhere other inside the input such as a data model (see MVC). Keeping data/logic separate from the GUI is always a good thing. It also avoids needing to re-parse the number every time. And you can "hide" the checking of overflow or underflow inside the model.


Computing a list of divisors of a number

You code is hard to understand. Very hard.

In Python we prefer iteration over recursion, not only does recursion limit you to a maximum depth of 1000 function calls, it also has severe performance impacts.

You should:

Use snake_case in Python not camelCase. The only time you use CamelCase is when creating a class.
Start using generators. In most cases you can just replace list.append with a yield.
Change nthPrime to be a generator, say primes. As I'm not here to re-write nthPrime you can just use itertools.count to get an infinite generator.
Don't duplicate logic before and during a loop. In prime_factorization, you wrote the floor division, n //= prime, twice.
It's simpler to use a for loop and break from it, than while looping with a condition and manually taking the next item.
You can use collections.namedtuple to remove the need to create your own class.

Merging the above together for just prime_factorization can get you:

from collections import namedtuple
from itertools import count

Option = namedtuple('Option', 'value count')

def primes():
    for i in count():
        yield nthPrime(i)

def prime_factorization(n):
    for prime in primes():
        count = 0
        while n % prime == 0:
            count += 1
            n //= prime
        if count:
            yield Option(prime, count)
        if n <= 1:
            break

After this you want to move more code into combinations, so that it's self contained in getCombinationsIncrement, and to rename it combinations.

Change combinations to instead yield a tuple of chosen.
Create chosen within combinations.
Pass a single one dimensional list to combinations so that it's more usable later.
When you finish running through all of options without yielding, you want to stop. To do this you can use the for ... else syntax and just break.

This should be able to get you:

def combinations(options):
    chosen = [0] * len(options)
    while True:
        for i, option in enumerate(options):
            chosen[i] += 1
            if chosen[i] > option:
                chosen[i] = 0
                break
            yield tuple(chosen)
        else:
            break

Finally we want to change combinations_reduce to use combinations.

First you should change options from a 2d lists to two 1d lists. You should want to get values and counts into their own lists. And so you can use zip with the argument unpacking operator, *, to expand the list to \$n\$ 2 long lists.
You want to create combos off the bat, and can use enumerate to get the current index.

Alternately you could try using yield instead, and off-load the sorting to the user.
You can use reduce to replace your innermost loop.
You can change the input to use default variables of operators.mul and 1. This simplifies the usage, as you don't need to specify as much.

This can get you:

def combinations_reduced(options, combine=mul, base=1):
    values, counts = zip(*options)
    combos = [base] * len(counts)
    for i, chosen in enumerate(combinations(counts), 1):
        for j, value in enumerate(values):
            combos[i] = reduce(combine, [combos[i]] + [value] * chosen[j])
    combos.sort()
    return combos

def get_divisors(n):
    return combinations_reduced(prime_factorization(n))


WordPress plugin for obfuscating a file URL

The server is fetching the contents of the URL and then sending it to the user. Unless you accidentally output the URL, via an error or similar, there is no way the user could see it. The server is effectively sitting between them and the remote server.

If you can, it would probably be better to host the files locally otherwise you will be using twice the bandwidth and also have the risk that one of the remote servers might go down.

As long as the user can't specify the remote URL or edit the contents of it, it should be secure.


Get value from an async function in Outlook Web Addin

I would suggest you could use Promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

If you don't want additional library for Promise, you could use Deferred from jQuery also. https://api.jquery.com/deferred.promise/


Redux actions inside a container for a calculator

I would try to extract some of the common functionality into reusable components as follows. The NumericButton and OperatorButton components could either receive selectNumber and selectOperator as props or the components could be connected components with the select* props coming from mapDispatchToProps. The connected component method eliminates the need to pass the prop in every component instance in ButtonContainer, but increases the number of connected components thus adding some complexity.

const CalculatorButton = ({ children, className, onClick, value}) => {
  return <button value={value} onClick={e => onClick(e.target)} className={`buttonStyle ${className || ''}`} type="submit">{children || value}</button>;
};

const NumericButton = ({ className, value }) => {
  return <CalculatorButton className={className} onClick={selectNumber} value={value} />;
};

const OperatorButton = ({ className, value }) => {
  return <CalculatorButton className={className} onClick={selectOperator} value={value} />
};

const ButtonsContainer = () => (
  <React.Fragment>
    <CalculatorButton className="ac" onClick={() => initialize()} value="AC" />
    <CalculatorButton className="ce" onClick={() => clearEntry()} value="CE" />
    <CalculatorButton className="posneg" onClick={changeSign} value="CHANGE">{'+/-'}</CalculatorButton>
    <OperatorButton className="divide" value="/" />
    <NumericButton className="seven" value="7" />
    <NumericButton className="eight" value="8" />
    <NumericButton className="nine" value="9" />
    {/* etc. */}
  </React.Fragment>
);


Mixing function parameters, commands and command arguments in Bash functions

The trick for splitting up the version blurb for just the version number, is to pass the values you want in before the command, and then shift them off $@.
you have done a relatively unfamiliar-to-me parsing mechanism with the resetting the field separators, etc. Using bash as a parser is a problem for me (and I've never hated myself enough to try....).
I would set up a function that takes a co-ordinate of a version as a line/word combination, and rely on out-of-bash tools to do it......
I will probably get nailed for starting 4 sub-processes, but head, tail, and cut are small.... right?  (Forgive me already, you won't be calling this in a tight loop, will you? You're already doing that a bit with the bash $( ...) operator...)
get_version_number() {
    local line=$1
    shift
    local word=$1
    shift

    # echo Line $line Word $word and Commend $@

    # set local variable to executed arguments that is passed in
    echo "$( $@ | head -$line | tail -1 | cut -d ' ' -f $word)"
}

Then you would call it like:
gitver=$(get_version_number 1 3 git --version)
perlver=$(get_version_number 2 4 perl -version)

echo Git and Perl are $gitver and $perlver respectively

which for me, produces:

Git and Perl are 1.7.1 and v5.10.1 respectively

This also allows you to do things like get the redhat version as
rhelver=$(get_version_number 1 7 cat /etc/issue)
javaver=$(get_version_number 1 3 java -version)

and even things like the current time 23:45:08 ;-)
time=$(get_version_number 1 4 date)

Some notes:

historically, it is 'expensive' to start lots of child processes. It still is a problem, but not quite as bad as it was. Doing that hundreds or thousands of times may add up to seconds of time wasted. If you can avoid creating child processes, do it.... but, sometimes it's just easier to be lazy than to be super-bash-smart.
I create an additional 4 processes (actually 5) each time you call the function. One for the $( ... ), one for the $@ inside that, one for head, one for tail, and one for cut. That is almost excessive.... but if you are calling this 100 times, then it's OK, if you are calling it 1000 times, you will be able to save seconds by doing it differently.
the $( ... ) operator is formally called the Command Substitution. What it means is that everything inside the structure is run as if in a 'child' bash process.... (so a new process is created, and the output is substituted in place of the command)
what the shift operator does is take $@ and remove the first item.... so, your function called as get_version_number 1 3 git --version gets 4 parameters, 1, 3, git and --version. We copy $1 off as $line, and then shift $@, so there are now only 3 parameters in $@. We then copy $1 again (but because of the shift, it is a different value) as $word, and then shift again to remove it. We are left with just git and --version as the parameters.

If you wanted, for example, to save one process each time, you could instead do:
get_version_number() {
    local line=$1
    shift
    local word=$1
    shift
    GOTVERSION="$( $@ | head -$line | tail -1 | cut -d ' ' -f $word)"
}

get_version_number 1 3 java -version
javaversion=$GOTVERSION

That saves using the $( .... ) and echo combination, so you save a process, but the code is a bit more complicated.

Edit 2.
'Obviously', what I suggest you do is not necessarily the best thing. Your code was working fine, and the mechanism will be faster (slightly) than mine because it does not do the additional 4 processes and keeps the logic inside bash internal commands.
Here is my 'shift' system applied to your code:
get_version_number() {
    local word=$1
    shift
    # set local variable to executed arguments that is passed in
    local command="$($@)"
    # set up temp variable and assign to global IFS variable
    OIFS=$IFS
    # set up IFS to split the string on empty space
    IFS=" "
    # read commands output into an array and store it in $array variable
    read -a array <<< "$command"
    # clear out IFS back to what it original was for further use
    IFS=$OIFS
    # echo out array at a particular indices that should be passed in
    echo ${array[$word]}
}

and you would call it with the word-number for the version as the first argument:
gitver=$(get_version_number 3 git --version)

But this does not allow you to find versions on multi-line outputs.....


Three minor notes:

From Steve McConnell, Code Complete 2nd Edition, 31.2 Layout Techniques, p737:

  Using blank lines is a way to indicate how a program is organized. You can use them
  to divide groups of related statements into paragraphs, to separate routines from one
  another, and to highlight comments.

It does not make sense if all groups contain only one line.
strtotime($year.'-W'.$week.'-'.$i) is used and duplicated multiple times in the code. You could extract it out to a function to remove the duplication.
If I'm right you are iterating through the days of the week with this loop:

<?php for($i = 1; $i <= 7; $i++): ?>

Renaming $i to $weekday or something similar would make it obvious and help readers/maintainers a lot.


Pure PHP array_diff_assoc_recursive function

The logic looks good but I would like to suggest a few tips to enhance readability and maintainability of your code.

First off: name your variables accordingly $a doesn't say anything to any random person when reading the code. He will have to scroll up and down figuring out what is what.

Second: Split your function into multiple methods. This will enhance readability and will keep an overview of your code. Now you have one very large method which will take a random person at least half an hour to figure out what it all does exactly.

Third: Try to avoid things like continue 2;, break; and more. They don't mean anything when you read code and can be avoided in most cases.

Fourth: Comments rot very quickly! Try and make sure that your methods are selfexplanatory so that you dont need to put comments.


Find the maximum GCD of a number with respect to all the values in an array for competitive programming

gcdn[] is unused.
if n==0, you access a non-existent array element, and even if it isn't, you do the GCD with a[0] twice.
gcd() is called before it is declared, which is bad style and can mess up optimization.
you might think about whether the M or arr[] elements are likely to be larger.  The order you pass values to gcd() can reduce by one loop if you guess right.
The tail recursion on gcd() should be OK as long as you optimize.


Like ojdo has pointed out, using plain regexes to parse something like BBCode is too complicated of a route to take.

It would be too long of a task to educate you on building proper parsers, but here's a short simplified example, of how one would go on parsing something like BBCode.

First tokenize

First off, we transform the input text into some higher level data structure which we can then work on more easily. For the BBCode, let's tokenize the input into begin tags, end tags, and text in between:

function tokenize(input) {
  var m;
  var tokens = [];
  while (input.length > 0) {
    if ((m = input.match(/^\[([a-z]+)(=([^\]]+))?\]/i))) {
      // start tag [foo=*]
      tokens.push({type: m[1].toLowerCase() + "_start", argument: m[3], raw: m[0]});
    }
    else if ((m = input.match(/^\[\/([a-z]+)\]/i))) {
      // end tag [/foo]
      tokens.push({type: m[1].toLowerCase() + "_end", raw: m[0]});
    }
    else {
      // text between tags (this regex always matches)
      m = input.match(/^\[?[^\[]*/);
      tokens.push({type: "text", raw: m[0]});
    }
    // skip forward
    input = input.slice(m[0].length);
  }
  return tokens;
}

Given an input like "[URL=google.com]click here[/URL]", the tokenize function produces an array of tokens like this:

[
  { type: 'url_start', argument: 'google.com', raw: '[URL=google.com]' },
  { type: 'text', raw: 'click here' },
  { type: 'url_end', raw: '[/URL]' }
]

Then produce HTML

Normally one would now transform this list of tokens into a tree structure, but as the BBCode-to-HTML conversion is very one-to-one, we don't really need to, and can pass the list of tokens directly to another function that converts it to HTML:

function tokensToHtml(tokens) {
  var output = "";
  for (var i=0; i<tokens.length; i++) {
    var tok = tokens[i];

    if (tok.type === "url_start") {
      var url = tok.argument;
      // prepend URL-s with http:// if needed
      if (!/^https?:\/\//.test(url)) {
        url = "http://" + url;
      }
      output += "";
    }
    else if (tok.type === "url_end") {
      output += "";
    }
    else {
      // anything else is a text token or an unknown tag
      // which we also treat just as text
      output += escapeHtml(tok.raw);
    }
  }
  return output;
}

function escapeHtml(str) {
  return str.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

As can be see, we simply replace each token with corresponding HTML. When writing out the <a href=... we also take care of prepending the http:// as needed. Additionally we escape all HTML special chars in URL and within rest of the text - using a little escapeHtml utility function.

To tie it all together:

function bbCodeToHtml(input) {
  return tokensToHtml(tokenize(input));
}

It should be fairly obvious how to extend the tokensToHtml to support additional BBCode tags.

One missing feature is to automatically append close tags if one would input something like "[URL=google.com]bla bla". This is left as an exercise for the reader :)


Make a Session instead of issuing individual Requests get; this promotes explicit connection pooling, cookie sharing etc.
There's no need for your current prints. If you find them to be of very high value, convert them into real logging calls
Pre-define your script tag loading via a SoupStrainer
Use urljoin and centralize your root URL definition
Do not keep results as a member; it's the result of a method call
Do not represent results as a list; it can be an iterator so that results can be depaginated and streamed to disk while keeping memory occupation relatively low
Parametrize your fetch function to represent the actual parameters on the web call
Consider using PEP484 type hints
Your open is missing newline=''

Suggested
from functools import partial
from typing import Any, Dict, Iterable, List

import json
import csv
from urllib.parse import urljoin

from bs4 import BeautifulSoup, SoupStrainer
from requests import Session

JSON = Dict[str, Any]

class ZooplaScraper:
    ROOT = 'https://zoopla.co.uk'
    from_root = partial(urljoin, ROOT)

    def __init__(self):
        self.session = Session()

        strainer = SoupStrainer('script', id='__NEXT_DATA__')
        self.load_script = partial(
            BeautifulSoup, features='html.parser', parse_only=strainer,
        )

    def fetch(
        self, query: str = 'London', radius: int = 0,
        sort: str = 'newest_listings', page: int = 1,
    ) -> str:
        with self.session.get(
            self.from_root(f'for-sale/property/{query.lower()}/'),
            params={
                'page_size': 25,
                'q': query,
                'radius': radius,
                'results_sort': sort,
                'pn': page,
            }
        ) as resp:
            resp.raise_for_status()
            return resp.text

    def load(self, html: str) -> List[JSON]:
        script = self.load_script(html)
        data = json.loads(script.string)
        return data['props']['initialProps']['pageProps']['regularListingsFormatted']

    @classmethod
    def serialise(cls, listings: Iterable[JSON]) -> Iterable[JSON]:
        for listing in listings:
            yield {
                'listing_id': listing['listingId'],
                'name_title': listing['title'],
                'names': listing['branch']['name'],
                'addresses': listing['address'],
                'agent': cls.from_root(listing['branch']['branchDetailsUri']),
                'phone_no': listing['branch']['phone'],
                'picture': listing['image']['src'],
                'prices': listing['price'],
                'listed_on': listing['publishedOn'],
                'listing_detail_link': cls.from_root(listing['listingUris']['detail']),
            }

    def run(
        self,
        query: str = 'London', radius: int = 0, sort: str = 'newest_listings',
    ) -> Iterable[JSON]:
        for page in range(1, 5):
            yield from self.serialise(
                self.load(
                    self.fetch(query, radius, sort, page)
                )
            )

    @staticmethod
    def to_csv(results: Iterable[JSON], filename: str = 'zoopla.csv') -> None:
        with open(filename, 'w', newline='') as csv_file:
            first = next(results)
            writer = csv.DictWriter(csv_file, fieldnames=first.keys())
            writer.writeheader()
            writer.writerow(first)
            writer.writerows(results)

if __name__ == '__main__':
    scraper = ZooplaScraper()
    scraper.to_csv(scraper.run())

Experimental
This is an experimental, alternate implementation that:

Streams the HTTP response and does not need the entire response content to complete
Streams the parsed HTML elements and does not need the entire document tree to complete
Streams the JSON body and does not need the entire dictionary tree to complete

It is somewhat iterator-heavy, and built more as a proof of concept to demonstrate that this is possible. Advantages include that worst-case memory usage should be reduced, and that BeautifulSoup is no longer needed. Disadvantages include that a new dependency, JsonSlicer, is needed; and this might introduce subtle HTTP inefficiencies from connections that are reset before complete response transmission.
import csv
import logging
from functools import partial
from html.parser import HTMLParser
from typing import Any, Dict, Iterable, Tuple, Optional
from urllib.parse import urljoin

from jsonslicer import JsonSlicer
from requests import Session, Response

JSON = Dict[str, Any]

class StreamParser(HTMLParser):
    def __init__(self, resp: Response):
        resp.raise_for_status()  # If the response failed, it can't be parsed
        self.resp = resp         # Keep the response so we can stream from it
        self.in_tag = False      # Parser state: if we're in the script tag
        self.done = False        # Whether we're done the script tag
        self.queue = []          # Queue of text element chunks in the script
        super().__init__()       # Initialize the base parser

    def __enter__(self):
        # Start the data chunk iterator
        self.chunks = self.data_chunks()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        # When we're done, tell the HTTP response stream to close
        self.resp.close()

    def data_chunks(self) -> Iterable[str]:
        # Stream in arbitrary-sized chunks from the response
        for chunk in self.resp.iter_content(
            chunk_size=None,  # Get whatever chunks are sent our way
            decode_unicode=True,  # Needed for HTMLParser compatibility
        ):
            logging.debug(
                f'{len(chunk)}-character chunk: '
                f'{chunk[:10]}...{chunk[-10:]}'
            )
            # Feed this chunk to the parser, which will in turn call our handle
            # methods and populate the queue
            self.feed(chunk)
            yield from self.queue
            self.queue.clear()

            # We only care about one tag. Once that's parsed, we're done
            # iterating
            if self.done:
                break

    def read(self, n: Optional[int] = -1) -> str:
        # Will be called by JsonSlicer. We only support partial reads for
        # efficiency's sake; we do not build up our own buffer string.
        if n is None or n < 0:
            raise NotImplementedError('Read-to-end not supported')
        try:
            return next(self.chunks)
        except StopIteration:
            return ''  # end of stream

    def handle_starttag(self, tag: str, attrs: Iterable[Tuple[str, str]]):
        self.in_tag = tag == 'script' and any(
            k == 'id' and v == '__NEXT_DATA__' for k, v in attrs
        )

    def handle_data(self, data: str) -> None:
        if self.in_tag:
            self.queue.append(data)

    def handle_endtag(self, tag: str) -> None:
        if self.in_tag:
            self.in_tag = False
            self.done = True

    def __iter__(self) -> Iterable[JSON]:
        # Iterating over this object will magically produce individual listing
        # dictionaries. We're an iterator; we delegate to the JsonSlicer
        # iterator; and it in turn invokes read() which uses our data_chunks
        # iterator.
        return JsonSlicer(file=self, path_prefix=(
            'props', 'initialProps', 'pageProps', 'regularListingsFormatted', None,
        ))

class ZooplaScraper:
    ROOT = 'https://zoopla.co.uk'
    from_root = partial(urljoin, ROOT)

    def __init__(self):
        self.session = Session()

    def fetch(
        self, query: str = 'London', radius: int = 0,
        sort: str = 'newest_listings', page: int = 1,
    ) -> StreamParser:

        resp = self.session.get(
            self.from_root(f'for-sale/property/{query.lower()}/'),
            params={
                'page_size': 25,
                'q': query,
                'radius': radius,
                'results_sort': sort,
                'pn': page,
            },
            stream=True,
        )

        return StreamParser(resp)

    @classmethod
    def serialise(cls, listing: JSON) -> JSON:
        # Convert from the site's representation of a listing dict to our own
        return {
            'listing_id': listing['listingId'],
            'name_title': listing['title'],
            'names': listing['branch']['name'],
            'addresses': listing['address'],
            'agent': cls.from_root(listing['branch']['branchDetailsUri']),
            'phone_no': listing['branch']['phone'],
            'picture': listing['image']['src'],
            'prices': listing['price'],
            'listed_on': listing['publishedOn'],
            'listing_detail_link': cls.from_root(listing['listingUris']['detail']),
        }

    def run(
        self,
        query: str = 'London', radius: int = 0, sort: str = 'newest_listings',
        max_pages: int = 4,
    ) -> Iterable[JSON]:
        for page in range(1, max_pages + 1):
            with self.fetch(query, radius, sort, page) as stream:
                for n_listings, data in enumerate(stream):
                    yield self.serialise(data)
            logging.info(f'Page {page}: {n_listings} listings')

    @staticmethod
    def to_csv(results: Iterable[JSON], filename: str = 'zoopla.csv') -> None:
        with open(filename, 'w', newline='') as csv_file:
            first = next(results)
            writer = csv.DictWriter(csv_file, fieldnames=first.keys())
            writer.writeheader()
            writer.writerow(first)
            writer.writerows(results)
        logging.info(f'Write to {filename} complete')

if __name__ == '__main__':
    # Will include debugging statements from urllib3
    logging.basicConfig(level=logging.INFO)  # Switch to DEBUG for more verbosity

    scraper = ZooplaScraper()
    scraper.to_csv(scraper.run())


I forced @proxy156 to start a new question which we discussed here
Finding and pasting images into a specific cell

I just can't figure out how the formatting works in comments here.
The problem here is that it takes a minute to delete about ~3000 pictures
Also there was a problem with different shape objects that should not be deleted (Buttons)

This code should work a bit better

Sub DeleteAllPics()

    Dim wks         As Worksheet
    Dim shp         As Shape
    Dim picArray()  As String
    Dim index       As Integer

    On Error GoTo ErrorHandler

    Set wks = ActiveSheet
    index = 1
    For Each shp In wks.Shapes
        If shp.Type <> msoFormControl Then
            ReDim Preserve picArray(1 To index)
            picArray(index) = shp.Name
            index = index + 1
        End If
    Next shp

    wks.Shapes.Range(picArray).Delete

ExitRoutine:
    Set wks = Nothing
    Set shp = Nothing
    Erase picArray
    Exit Sub

ErrorHandler:
    MsgBox Prompt:="Unable to find photo", _
           Title:="An error occured", _
           Buttons:=vbExclamation
    Resume ExitRoutine

End Sub


I'll give it a shot since CQRS is something I'm still learning.

In CQRS we are supposed to separate our read model from our write model. Is this what you have done?

Then the read model should be designed to be a perfect fit for the thing that needs to read it:

Your query looks very complex. Is it derived from the write model, or do you indeed have separate tables for the queries?
Why a Func as a parameter? It seems strange to me that the criteria should be a negotiation between client and query.
Why do you put the query method onto the DbContext? That class will soon enough be cluttered with too many queries.

Here are some suggestions to simplify things:

Let the DbContext mimic the database tables only and nothing else. That means your DbContext will only have public properties for the tables you are going to query.
Don't call it a Repository, but a Query. Split the Query-class when it grows too big.
Let the Query class take the DbContext as a dependency. Query the DbContext-properties, don't use Set<T>.
Let each query-method accept one criteria object as parameter, then build the query expression from that inside the method.
Linq is tricky. While not entirely true, a rule of thumb is that a Func runs client side, while an Expression runs server side. That's also why I don't like the Func-parameter.
Consider using only non-generic query-methods. Yes, there will be some duplication, but you want your peers and the future you to understand the queries two months from now.

I meant to post some code examples, but Chrome crashed again and edits got lost :-(


With the new board representation, the brute-force pattern matching is gone, which is good.  Still, I personally prefer the 1–9 numbering for simpler user interface — perhaps a translation function could be implemented.  Note that you forgot to adjust the introductory message for the new coordinate system.

Instead of the showTile function, you should use the standard Show typeclass:

instance Show Tile where
    show EmptyTile = " "
    show X         = "X"
    show O         = "O"

In showBoard you used both let … in and where.  Pick one or the other (I prefer where).

As mentioned in my previous answer, all of your functions that accept a Board should place the board parameter last, since the board is what they all operate on.  With tileWins :: Tile -> Board, for example, you can define p1wins = tileWins X using the point-free style.

data Player = Player1 | Player2 isn't doing anything useful for you.  You are hard-coding the Player1 ↔ X and the Player2 ↔ O correspondence all over the place, in main, p1wins, p2wins, and compMove.

With this second version, then, I would say that the greatest improvement can be made in handling the two players.  Here is my suggestion:

humanTurn :: Tile -> Board -> IO Board
humanTurn t b = do
    putStrLn $ showBoard b
    move
    where
        move = do
            row <- prompt "Row: "
            col <- prompt "Col: "
            let newboard = put b t (read row) (read col)
            case newboard of
                Nothing -> do
                            putStrLn "Invalid move."
                            move
                Just b' -> return b'

computerTurn :: Tile -> Board -> IO Board
computerTurn t b = do
    (row, col) <- getRandomEmpty b
    let (Just b') = put b t row col
    return b'

main :: IO ()
main = do
    putStrLn "This is the classic tic tac toe game."
    putStrLn "Enter the coordinates for each move according to this scheme:"
    putStrLn showTileNumbers
    play player1 player2 emptyBoard
    where
        player1 = (X, humanTurn, "You win!")
        player2 = (O, computerTurn, "You lose.")
        play p@(tile, turn, winMsg) p' b = do
            b' <- turn tile b
            if tileWins tile b' then do
                putStrLn $ showBoard b'
                putStrLn winMsg
            else if checkFull b' then do
                putStrLn $ showBoard b'
                putStrLn "Tie."
            else
                play p' p b'

This turns main into a leaner state machine.  As evidence of the superiority of this design, observe that you can make a human-vs.-human game simply by changing two lines to…

       player1 = (X, humanTurn, "X wins.")
       player2 = (O, humanTurn, "O wins.")


Bucketizing time (e.g., 4 min => 0-5 min)

Here are some thoughts for you. I'm guessing other folks will (hopefully) tackle things from a variety of perspectives.

print_reading_time

How about changing this function to reading_time and returning nothing but the estimated time.  Perhaps change the declaration to:

reading_time($content, $wpm=180)

This function can be adjusted based on the reader and does not really need to know anything about the time buckets or how the output will be generated. You are mixing in additional concepts and that is likely to make it harder to reuse or extend the functionality.

minutes_to_time_label

Based on your descriptive language I'd probably go with something like:

minutes_to_time_bucket($minutes, $initial_bucket_size)

From here I think I'd immediately jump into a determination of whether or not the estimate is greater than 1 hour.

if ( $minutes > 60 )
{
  $low = floor($minutes/60);
  $high = $low + 1;

  // return time label here
}

If we are below 60 minutes we can go into the particulars of how to scale the buckets (and do all of our work in minutes).

$bounds = array(0,5,10,15,30,60);
foreach ($bounds as $key => $val)
{
  if ( $minutes >= $val && $minutes <= $bounds[$key+1] )
  {
    // generate label using $bounds[$key] and $bounds[$key+1]
  }
}

// If we get here there is an error, quit with error message

If you want to support bounds more dynamically, you could generate the bounds array based on the initial_bucket_size passed in until you end up with a value of 60 or greater.

You could use an array of multipliers to do this. The multipliers using a bucket size of 5 would be 0, 1, 2, 3, 6, 12. If you optionally passed in the multipliers as an array you'd be able to change boundary definitions on the fly.

Note

I've assumed the options array and use of two functions related to label output was additional complexity to handle units. If you wanted that flexibility back you could add a parameter or two to the minutes_to_time_bucket function.

As an extension, you could perhaps support multiple languages by passing in the text to display for minutes and hours to override English defaults.

In short, my feedback would be to consider ways to keep your functions focused on a single concept. In this case we have a calculation of reading time and a method of generating a text time range based on a reading time. Some controlling code will mash those concepts together (not the functions themselves).

Beyond that, consider how to generalize those functions to support a wider variety of use within that focus. For example, an ability to use the readers own reading speed or output language doesn't change the focus of the function but will allow for use in a wider set of scenarios.


Tableview Subclass implementing delegate datasource

Personally I don't like the way UITableViews work with a delegate and dataSource yet there's no real way to say "Here's the data". You are kind of forced to either send around copies of your data or put everything into one class. There's tons of mixing of the M, V and C layers in one class going on.

However, it should be possible to use a separate implementation of the dataSource and `delegate. While in this example there's little code, in some cases you might cross (my personal) soft limit of 200 lines of code or even the hard limit of 300 in one file.

In my Objective-C / Storyboards days I actually had implementations where I would use several objects all linked together via @IBOutlets. So a delegate, dataSource and tableView. The delegate could have a weak ref to the dataSource and the dataSource had the actual data. Not using the selected mechanism for button-like actions could allow you to sever the ties between the delegate and the data.

So I don't disapprove of what you're doing because you're trying to do your best with the bad hand of cards that Apple dealt you. But you could try to have the data only exist on the dataSource implementation. Also I see you doing a lot of stuff to the cell in dequeue, that should definitely move to the implementation of the cell because it's doing V code in an M class. I use a configure(with: *someData*) function that sets it up further.

If you try to separate the M from the V and the C you will see pretty clearly where you should cut it up.


Resolve (domainless) machine name from DNS alias

However, what I need is the URI with just the machine name, http://server1/path/to/resource. Of course I can use this, but string manipulation seems seems a bit kludgey:
builder.Host = Dns.GetHostEntry(builder.Host).HostName.Split(new[] { '.' }, 2)[0];

Also this seems to be a little bit strange, I don't know another way, only a cleaner way.
private Uri GetUriFromAlias(String alias)
{
    UriBuilder builder = new UriBuilder(alias);
    IPHostEntry entry = Dns.GetHostEntry(builder.Host);

    builder.Host = GetMachineName(entry);
    return builder.Uri;
}
private String GetMachineName(IPHostEntry entry)
{
    return entry.HostName.Split(new[] { '.' }, 2)[0];
}


As usual, when dealing with singletons, consider that you probably shouldn't be making a singleton at all.

Read this, for example. A singleton is almost certainly not what you actually need, even if it is implemented correctly and in a thread-safe manner.

A plain old global might be a better option, or perhaps you should simply pass a reference around to those who need it.


Instead of

i = 0
while i < len(text):
    j = ord(text[i])
    ...
    ...
    ...
    i += 1

and using text[i] for accessing individual elements (which is NOT a Pythonic way).
Get rid of i and write simply

for c in text:
    j = ord(c)
    ...
    ...
    ...

    j = ord(text[i])
    k = bin(ord(text[i]))
    l = hex(ord(text[i]))
    m = oct(ord(text[i]))

After performing the first of those commands is ord(text[i]) already in the variable j, isn't it? So why not reuse it in the rest of them:

for c in text:
    j = ord(c)
    k = bin(j)
    l = hex(j)
    m = oct(j)

Instead of

print(text[i], " ", j, " ", k, "", l, "", m)

use the format() method and replacement fields {}:

print("{}   {}   {}  {}  {}".format(text[i], j, k, l, m))


Which is the best approach for searching the dictionary items?

None of the above.

  OR if there is any other approach you would recommend please let me
  know.

The whole point of using dictionaries is that you don't need to search anything and can access everything in O(1) (on average) instead of the O(n) in all of your suggestions.

  names are unique in the list
  There will be definitely a name in each dictionary.

So, instead of using a list of dictionaries, use a dictionary of dictionaries using the name as the outer key.

Instead of

items = [{'name': 'a', 'age': 22, ...},
         {'name': 'b', 'age': 30, ...}]

you should have

items = {'a': {'age': 22, ...},
         'b': {'age': 30, ...}}

Now you can access each dictionary directly by using the name.

name = 'b'
print(items[name]['age'])
#  30

No loops, no searches, O(1) access.


Any performance difficulties related to List?

As was said in the comments, I don't think List<T> makes any significant difference over an array.

But with a bit of LINQ you can reduce the nesting a bit:

foreach (var b in map.bases)
{
    foreach (var c in map.points.SelectMany(cc => cc))
    {
        CalculatePointValues(c, b, los);
    }
}

And it could be worth trying to profile it with some Parallel looping as well:

Parallel.ForEach(map.bases, b =>
    {
        foreach (var c in map.points.SelectMany(cc => cc))
        {
            CalculatePointValues(c, b, los);
        }
    });


Generate another random path through a complete graph

From your code I'm guessing that you're doing some 2-opt for the TSP. And yes, it is possible to make it faster. The secret actually lies within your code, and is also the reason why your code isn't working.

Disclaimer: I am no expert at C++

When you do newPath = oldPath, you're making newPath a vector that is identical to, but not the same as oldPath. Then you push all elements from oldPath onto newPath, thus making it twice as big as oldPath.

But since you already have a concise way of copying all values to a new vector, let's use that to speed things up:

std::vector<City> GetRandomPathFast(std::vector<City> oldPath)
{
    std::vector<City> newPath = oldPath;

    int randPoint = rand() % (oldPath.size()-1);
    int randPoint2 = rand() % (oldPath.size()-1 - randPoint) + randPoint;

    int k = 1;
    for(int i=randPoint; i < randPoint2; i++)
    {
        newPath[i] = oldPath[randPoint2-k];
        k++;
    }
    return newPath;
}

By only modifying the values between randPoint and randPoint2, we get a significant speedup. We also get a path of the correct length, with a part of it reversed.

For benchmarking, I changed both your function and my new to use std::vector<int>, but numbers should carry over to your implementation.

Vector of length 1000, 10000 iterations of each function:
Time for GetRandomPath: 280.624 ms
Time for GetRandomPathFast: 22.136 ms


Can someone review my implementation of a KeyValuePair?

You shouldn't need to throw ClassCastException explicitly; it would be thrown automatically by the JVM if the cast actually fails.

However, you shouldn't have to deal with casting at all if you use Java Generics properly.

public class KeyValuePair<K extends Comparable<K>, V>
        implements Comparable<KeyValuePair<K, V>> {

    private K key;
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public int compareTo(KeyValuePair<K, V> item) {
        return this.key.compareTo(item.key);
    }

    public K getKey() {
        return this.key;
    }

    public V getValue() {
        return this.value;
    }
}

Edit: As @ortang points out, there's more work to be done!  Since the key and value are immutable, marking them final is helpful.  Also, the class needs to override .equals(), and when that happens, .hashCode() needs to be overridden too.  Finally, it may be worthwhile to handle some odd cases in .compareTo().

public class KeyValuePair<K extends Comparable<K>, V> implements Comparable<KeyValuePair<K, V>> {

    private final K key;
    private final V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // Arbitrarily decide to sort null keys first.  Values are disregarded for
    // the purposes of comparison.
    @Override
    public int compareTo(KeyValuePair<K, V> item) {
        if (this.key == null) {
            return (item.key == null) ? 0 : -1;
        } else {
            return this.key.compareTo(item.key);
        }
    }

    public K getKey() {
        return this.key;
    }

    public V getValue() {
        return this.value;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || !this.getClass().equals(other.getClass())) {
            return false;
        }
        KeyValuePair item = (KeyValuePair)other;
        return (this.key == null   ? item.key == null   : this.key.equals(item.key)) &&
               (this.value == null ? item.value == null : this.value.equals(item.value));
    }

    @Override
    public int hashCode() {
        return ((this.key == null)   ? 0 : this.key.hashCode()) ^
               ((this.value == null) ? 0 : this.value.hashCode());
    }
}


Looping through Radgrid in JS is slow, can this be faster?

welcome to Code Review and thank you for your question. You need to profile the code to see for yourself where it is slow. Firebug and Chrome can do this. Only then will you be able to optimize your code.

Side note: Be careful about variable names, some of them seem to be in French (dossier).


Convert mixed-format phone numbers to pure numbers

You can extract that logic to a simple dedicated method.

Your solution is over-complicated for such a simple task so I will offer an alternative solution.

Let's inspect the problem -

You get some string as an input. This string might contain digits and it might also contain words that represent numbers. If there are such words we want to replace them with the respective digit.

We humans know that 'Zero' means 0 and 'One' means 1 because this is part of our vocabulary, if we are uncertain of some word we can look it up in the dictionary right? The human dictionaries are structured mostly in the following way - Word - Meaning.

Well luckily C# also has such data type. Conveniently enough it's called Dictionary! Using this data type we can construct much more readable and extendable code.

Let's start by declaring a Dictionary:

private static readonly Dictionary<string, int> numbers = new Dictionary<string, int>
{
    ["Zero"] = 0,
    ["One"] = 1,
    ["Two"] = 2,
    ["Three"] = 3,
    ["Four"] = 4,
    ["Five"] = 5,
    ["Six"] = 6,
    ["Seven"] = 7,
    ["Eight"] = 8,
    ["Nine"] = 9,
};

From here it's trivial to write a short method that does the job utilizing the dictionary numbers:

private static string ConvertFromMixedToStandardNumbers(string input)
{
    string result = input;
    foreach (var number in numbers)
    {
        result = result.Replace(number.Key.ToLower(), number.Value.ToString());
    }
    return result;
}

Or even shorter with LINQ:

private static string ConvertFromMixedToStandardNumbers(string input)
{
    return numbers.Aggregate(input,
        (current, number) => current.Replace(number.Key.ToLower(), number.Value.ToString()));
}

As you can see it's extremely easy to write short and humanly understandable code when you use the proper data structures and C# techniques.

You can even add an enum to the mix and create the dictionary from it:

private enum Number
{
    Zero,
    One,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}

private static readonly Dictionary<string, int> numbers = MapEnum(typeof(Number));

private static Dictionary<string, int> MapEnum(Type enumType)
{
    return Enum.GetValues(enumType).Cast<object>()
        .ToDictionary(value => value.ToString(), value => (int) value);
}


Instance variables and do loops in ruby on rails

If you work with database you can do this more efficiently with sql request:

LineItem.where(:card_id => @card.id).sum('quantity')

This is equivalent sql query

SELECT SUM(items.identity) FROM items WHERE items.card_id = ?;


Escape the Trolls, or just walking through a maze

Looks clean enough IMO, separate functions, a record for the maze -
perhaps create one for the player too?

When run from the terminal the (println player' player) is just
noise, I'd remove it.  Also, the maze should be printed once before
any commands are entered.
A lot of the lets can be inlined as they're only used once.
I'd perhaps pass coordinates in pairs instead of single numbers, then
you save a parameter every time and keep those two values that belong
together in one place.  OTOH the update code will be a little bit more
complex.
For is-game-finished? the threading macro ->> looks like overkill,
it's not like the expression is very complicated.
The return value of play-maze doesn't really matter, does it, so
maybe just drop the true and use when instead.

Perhaps add a way to clear the screen before printing the maze, then
at least on the terminal it's less cluttered.
Perhaps also switch to reading single characters so you don't have to
constantly press the Enter key.


Small program to get binary diff offset between two small files

To understand your program better, I cleaned up up your code.

diff.go:

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    files := os.Args[1:]
    if len(files) < 2 {
        fmt.Fprintln(os.Stderr, "expecting at least 2 files")
        return
    }

    bufs := make([][]byte, len(files))
    for i, file := range files {
        var err error
        bufs[i], err = ioutil.ReadFile(file)
        if err != nil {
            fmt.Fprintln(os.Stderr, "error reading file %s: %v", file, err)
            return
        }
    }

    minLen := len(bufs[0])
    for _, b := range bufs[1:] {
        if len(b) < minLen {
            minLen = len(b)
        }
    }

    for i := 0; i < minLen; i++ {
        v := bufs[0][i]
        for j := 1; j < len(files); j++ {
            if v != bufs[j][i] {
                fmt.Printf("first difference at offset %[1]d = %#[1]x\n", i)
                return
            }
        }
    }

    fmt.Println("no differences found")
}

Code should be readable. Drop references to os.Args; It's files.

For example, unreadable code and messages:

if len(os.Args) < 3 {
    fmt.Println("expecting at least 2 arguments")
    return
}

and so on.

Readable code and messages:

files := os.Args[1:]
if len(files) < 2 {
    fmt.Fprintln(os.Stderr, "expecting at least 2 files")
    return
}

and so on.

Also, error messages go to stderr.

In Go, lengths are pre-calculated. Delete

nfi := len(os.Args) - 1

nfi is simply the efficient and meaningful len(files).

Why is it so complicated to read file data?

    fi, err := os.Open(fn)
    if err != nil {
        fmt.Printf("error opening file %s: %v", fn, err)
        return
    }
    defer fi.Close()

    bufs[i], err = ioutil.ReadAll(fi)
    if err != nil {
        fmt.Printf("error reading from file %s: %v", fn, err)
    }

Note: defer fi.Close() doesn't work the way you want it to. The defers don't run until main returns.

Simplify, just ReadFile,

    var err error
    bufs[i], err = ioutil.ReadFile(file)
    if err != nil {
        fmt.Fprintln(os.Stderr, "error reading file %s: %v", file, err)
        return
    }

You wrote

    if l < min {
        min = l
    }

It's more readable to line them up

    if min > l {
        min = l
    }

I found the variable name min a little terse. I used minLen. And, again, l := len(b) is redundant. len(b) is pre-calculated.

// get a minimum len of all the buffers
min := len(bufs[0])
for _, b := range bufs[1:] {
    l := len(b)
    if l < min {
        min = l
    }
}

became

minLen := len(bufs[0])
for _, b := range bufs[1:] {
    if minLen > len(b) {
        minLen = len(b)
    }
}

You write:

fmt.Printf("first difference at offset %d = 0x%x\n", i, i)

Why 0x%x?

Why  i, i?

Using the fmt package documentation:

fmt.Printf("first difference at offset %[1]d = %#[1]x\n", i)


Pythonic way of removing one word entries from compound list

# Get all lines with more than one word
more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList]))

The function split splits by whitespaces by default, there is no need to pass the explicit argument
Lines have been stripped already when reading the file, using strip seems unnecessary
Using list comprehension should be enough, without the function compress and list

For example:
more_than_one = [line for line in myList if len(line.split()) > 1]

Or:
more_than_one = [line for line in myList if ' ' in line]

Same observations for Get all lines with only one word

# Keep only unique set of initial words of more_than_one
unique_first_words = list(set([e.split(" ")[0] for e in more_than_one]))

Not sure why the set is converted to a list. Checking for unique words in a set is much faster than in a list

Functions: would be better to include all the operations in a function, for easier testing and reuse
PEP 8: function and variable names should be lowercase, with words separated by underscores as necessary to improve readability. myList should be my_list. More info.

A function that does the same could be the following:
def remove_duplicates(lines):
    seen = set()
    for line in lines:
        first_word, *tail = line.split()
        if tail:
            seen.add(first_word)
    return [line for line in lines if line not in seen]

An use it like:
print(remove_duplicates(['a','a b','b','c','c d','z']))
# Output: ['a b', 'b', 'c d', 'z']


Iteration over "zipped" tuples (for_each_in_tuples)

template<typename T, typename... Ts>
struct First { using Type = T; };

template<typename... Ts>
using First_t = typename First<Ts...>::Type;

This can be done using std::tuple_element in conjunction with std::tuple.

template <typename... Ts>
using First_t = std::tuple_element_t<0, std::tuple<Ts...>>;

template<auto value, auto... values>
inline constexpr auto all_same = (... && (value == values));

For an empty pack, do you really want the value to be undefined?  The default behavior with empty packs are && is considered true and || is considered false.

static_assert(sizeof...(Tuples) > 0);

Instead of failing, maybe try to call the function with 0 arguments and see what happens?

static_assert(impl::all_same<impl::tuple_size<Tuples>...>);

If you want zipped-like behavior, you'll want to zip tuples until one of the tuples has exhausted its elements (min size instead first size).

  Is this implementation correct and can it be simplified?

Yes. Use an iterative approach, like sequential expansion, over recursion.

  Which name is better, for_each_in_tuple or for_each_in_tuples (or ...)?

Maybe for_each_zipped.  Tuples can be gathered from the signature of the function.

If you want to avoid the recursion, use fold expressions, std::index_sequence, and std::make_index_sequence.

Start with a simple helper to just invoke the function with elements across all the tuples at a specific index.

template <std::size_t Index, typename Function, typename... Tuples>
constexpr void invoke_at(Function&& func, Tuples&&... tuples) {
    func(std::get<Index>(std::forward<Tuples>(tuples))...);
}

Now we need a way to sequentially call it (invoke_at<0>(args), invoke_at<1>(args), ..., invoke<N>(args)).  Use fold expressions like you did for all_same, but with the comma operator and unary right fold ((invoke_at<N>(args), ...)).  To generate the Ns that gets expanded, we use std::index_sequence.

template <std::size_t... Indices, typename Function, typename... Tuples>
constexpr void apply_sequence(Function&& func,  std::index_sequence<Indices...>, Tuples&&... tuples) {
    (((void)invoke_at<Indices>(std::forward<Function>(func), std::forward<Tuples>(tuples)...), ...));
}

Finally, write your function that does checks for preconditions, creates the index sequence, and forwards the arguments to the above helper.

template <typename Function, typename... Tuples>
constexpr void tuple_for_each(Function&& func, Tuples&&... tuples) {
    static_assert(sizeof...(tuples) > 0, "Must be called with at least one tuple argument");

    constexpr auto min_length = std::min({std::tuple_size_v<std::remove_reference_t<Tuples>>...});
    if constexpr (min_length != 0) {
        impl::apply_sequence(std::forward<Function>(func),
                             std::make_index_sequence<min_length>{},
                             std::forward<Tuples>(tuples)...);
    }
    else {
        func();
    }
}

Note - The expansion has a cast to void that disables any overloaded shenanigans abusing the comma operator.


Optimize ineffiecient Jquery - UX list to grid view

You can simply use JS to toggle a list class. In CSS, you can simply override the style to either display block (item per row, list style), or display inline-block (several items side-by-side per row, grid style).

A simple demo here:

JS:

$('.btn.grid').click(function (event) {
    event.preventDefault();
    $('.results').addClass('grid');
});
$('.btn.list').click(function (event) {
    event.preventDefault();
    $('.results').removeClass('grid');
});

CSS:

/* default list mode */
.results li{
    padding: 0;
    margin: 0;
    display : block;
}

/* grid mode */
.results.grid li{
    display:inline-block;
    width: 100px;
}

.results img{
    display:block;
    width: 100%;
}


About these assignments
As someone who’s been teaching C++ for 15 holy shit, almost 20 years now, I have to say that these assignments are pretty terrible… especially the “vector” one. (To be clear, I mean the assignments are terrible… not the attempts. The attempts aren’t bad at all.)
I’ve always found the logic of “let’s teach by reimplementing what’s in the standard library” to beginners to be a little idiotic. As far as teaching useful skills goes:

it just wastes the learner’s time learning how to do something they (almost certainly) will never need to do again; and
in the vast majority of cases, it requires such terrifyingly advanced C++ knowledge to properly replicate a standard library facility, that in order to make it doable at all you have to dumb it down to the point where it’s almost broken… which only gives the learner a false sense of confidence thinking they understand how to do the thing when they really don’t.

In this case, it looks like the goal is to reimplement std::optional and std::vector… but only half-assed, broken, functionally-useless variants of both. I see beginners attempting these things all the time, but what they don’t seem to understand is that those are INCREDIBLY difficult tasks, requiring knowledge of C++ that is WAY beyond what any beginner should be expected to have. Even some expert level C++ programmers don’t have the knowledge necessary to do these things. In particular, reimplementing std::vector properly is among the hardest things you can possibly do in C++. Just because it’s easy to use doesn’t mean it’s easy to make.
I wish it would become more commonly understood that reimplementing standard library facilities is a pants-crappingly stupid way of teaching C++. Reimplementing standard library facilities is an excellent project… for highly advanced C++ programmers. But beginners? No. Don’t teach beginners to reimplement the standard library… teach them to fricken’ use it!
Anywho, the problem here isn’t the learner—it’s the teacher who gave these crappy assignments—so I won’t rant any more about that. Instead I’ll just focus on the code.
I’m only going to review the first program here. The second program, I’ll review in a second reply. It looks like the recommendation is to split the two programs into two separate questions; so you should probably do that.
Code review
using namespace std;

Never, ever do this at file scope. This is a terrible practice. In fact, you should probably never do this ever, not even at function scope.
Among the many reasons this is bad: Today your code compiles because there is nothing called ValueStore in the standard library. But if some future version of the standard adds something with that name… boom, your code is now broken. And that’s if you’re lucky. What might also happen is that something new gets added to the standard library that silently changes the behaviour of your code. That’s a nightmare scenario.
Just use std:: where necessary.
  ValueStore(T val) {
    value = val;
    hasValue = true;
  }

The first issue with this constructor is that it’s not explicit. That makes it dangerous, because it will silently convert anything that is implicitly convertible to a T. At the very least, that is likely to be inefficient.
In general, any constructor that takes a single argument should be explicit. (Yes, that should actually be the default, but unfortunately, the default was set to implicit way back when C++ was first standardized, and now it’s too late to change.)
The second issue with this constructor is that it doesn’t use member initializer lists. What’s actually happening above is this:
ValueStore(T val)
:
    value{},        // value is default-constructed
    hasValue{false} // hasValue is initialized to false (because of the member initializer where it is declared)
{
    value = val;        // value is copy-assigned using val
    hasValue = true;    // hasValue is move-assigned using true
}

As you can see, value is set up twice. First it is default constructed, then it is assigned (with the actual contents of val).
What you should do, as a start, is this:
explicit ValueStore(T val)
:
    value{val},     // value is copy-constructed using val
    hasValue{true}  // hasValue is initialized to true
{
    // nothing to do here
}

Here you can see value is only set up once: it is initialized right from the start with val, rather than being initialized “empty” (technically default-constructed) then assigned.
But there’s one more improvement you could make. To understand it, consider the following code:
ValueStore<std::string> v1("hello, world");

What’s happening here is:

Before the ValueStore constructor is called:

A temporary std::string is constructed with the contents “hello, world”.
The temporary string is moved to val. (It is moved, not copied, because it is a temporary. As a practical matter, this whole step is usually elided as an optimization, meaning the temporary string is constructed directly into val.)

The ValueStore constructor is called:

The member initializer list runs:

val is copied into value.
hasValue is set to true.

The constructor body is called:

Nothing happens here, because it’s empty.

So a temporary string is constructed, and then moved into val, and then copied into value. The copy is the problem there, because copying a string is expensive. Copying is generally expensive compared to moving, so you want to move whenever possible.
This is an easy fix; just move val into value:
explicit ValueStore(T val)
:
    value{std::move(val)},  // value is move-constructed using val
    hasValue{true}          // hasValue is initialized to true
{
    // nothing to do here
}

That’s all you need to do. Now a temporary string is constructed, then moved into val, then moved into value. In all likelihood, those moves can be elided. But even if not, moves are (usually) fast, especially for strings, and are usually no-fail.
There are a few other improvements you could make to this constructor:
constexpr explicit ValueStore(T val)
    noexcept(std::is_nothrow_move_constructible_v<T>)
:
    value{std::move(val)},
    hasValue{true}
{}

Making the constructor constexpr means you can construct ValueStore objects at compile-time, which can be enormously useful.
If move-constructing value cannot possibly fail, then the whole constructor cannot possibly fail. Adding the noexcept tells the compiler that, allowing it to make additional optimizations. (If move-constructing value can fail, then std::is_nothrow_move_constructible_v<T> will be false.)
  ValueStore() {
    value = {};
  }

This has the same problem as the previous constructor: you’re setting the value of value twice. What’s really happening is this:
ValueStore()
:
    value{},        // value is default-constructed
    hasValue{false} // hasValue is initialized to false
{
    value = {}; // a temporary T object is default-constructed,
                // then move-assigned into value
}

As you can see, that entire value = {}; is just a complete waste of time. All it does is take the already default-constructed value, default-constructs a whole new object, and then moves that into value. If you’d just left value alone, it would already be default-constructed:
ValueStore()
/*
:
    value{},        // value is default-constructed
    hasValue{false} // hasValue is initialized to false
*/
{
    // nothing to do here
}

But wait, there’s more!
Writing the default constructor like ValueStore() {} is actually a bad idea, because if it were possible to trivially-construct ValueStore objects… you just broke that functionality. Trivial construction means the compiler doesn’t actually have to do anything to construct a ValueStore, which means a lot of potential optimizations. It is better to leave the default constructor alone unless you actually need it to do something specific… which you don’t in this case.
So what you should write is:
ValueStore() = default;

And of course, you can add the extra decorations mentioned for the previous constructor to get even more benefits:
constexpr ValueStore() noexcept(std::is_nothrow_default_constructible_v<T>) = default;

(is_nothrow_default_constructible_v<T> is true only if default-constructing a T cannot fail.)
  T getValue() {
    return value;
  }

Since this function doesn’t change the state of the object, it should be const.
You could also add constexpr and maybe noexcept(std::is_nothrow_copy_constructible_v<T> and std::is_nothrow_copy_assignable_v<T>).
Now, this is really getting into complicated territory… but as the default choice for a new API, doing what you’ve done—returning a copy of value—is probably the right choice. However… this is not optimal, because if you don’t actually want a copy of value—if you just want to see what that value is (for example, just to print it like you’re doing in main()—you’re wasting resources by creating the copy.
What you really want to do is return a reference to value… but you have to be careful what kind of reference you return. If the ValueStore object is const, you don’t want to return a non-const reference to value… that would (theoretically) allow users to change the value of your const object, which is absurd. So you need two functions: one for const objects, and one for non-const objects:
constexpr T const& getValue() const noexcept { return value; }
constexpr T&       getValue()       noexcept { return value; }

Oh, but we’re not done yet, not by a long shot. Because there’s still the problem of temporaries. If you have a temporary ValueStore object, and you call getValue() on it, you’ll get a reference to value… but that reference will be dangling because the temporary is destroyed.
So you need to return rvalue references to value when the ValueStore is an rvalue (temporary, basically), and lvalue references when the ValueStore is an lvalue… and you need to take const into account. So what you really need is:
constexpr T const&  getValue() const&  noexcept { return value; }
constexpr T&        getValue() &       noexcept { return value; }
constexpr T const&& getValue() const&& noexcept { return std::move(value); }
constexpr T&&       getValue() &&      noexcept { return std::move(value); }

(Yes, you have to basically write the same function 2–4 times. That’s an unfortunate situation that some people are currently working to fix.)
((Rant mode again: See, complicated crap like this is why reimplementing std::optional is such a terrible project for beginners. And we haven’t even scratched the surface of just how complicated this really gets! You see, your class actually lies: it says hasValue is false if you do ValueStore<double> v3; But v3 does have a value: it is holding a double whose value is 0.0. Zero is a perfectly valid value for a double. Similarly, if you do ValueStore<std::string> v;, v.hasValue will say false… but v does have a value… it is holding a string whose current contents are just “”, but an empty string is still a string.))
That’s pretty much it for the ValueStore class. The only other comments I have are for the main() function.
First: Don’t use std::endl. Just don’t. Ever. Pretty much every use of std::endl I’ve ever seen is wrong… and yes, every single use in your program is wrong.
In particular, this is absurd:
    cout << "v1 has no value." << endl;

If you want a newline, just use a newline:
    std::cout << "v1 has no value.\n";

I know, every tutorial you’ve ever seen probably uses std::endl. Yes, I’m saying they’re all wrong. There is almost never a right time to use std::endl… and for those very, very rare situations where it has a purpose, you’re probably better off calling std::cout.flush() directly anyway, to make clear that’s what you want.
Finally: there is no need for return 0; in main(). main() automatically returns zero. (This is only true for main(); main() is special in a lot of ways.)
Summary
The problem I have with deciding whether this is a solid attempt at this problem or not is that the problem itself is stupid. Given a stupid problem, if someone’s solution isn’t great, is that because the solution is bad or because the problem is bad? It’s not easy to say.
I suppose this is a decent swing at the problem for a beginner. But really, this is not a beginner problem. Not if you take it seriously, anyway.
So long as you understand that hasValue is a lie, I suppose you can walk away from this having learned something. The truth is that your ValueStore always has a value. It can’t not have a value, so long as it has a T data member. Doing value = {} doesn’t set value to “not a value”; it sets it to the default value. Which is a value. There is literally no way to set value to “not a value”; that is literally impossible in C++.
You could cheat a little and do something like this:
template <typename T>
class ValueStore
{
private:
    std::optional<T> value;

public:
    bool hasValue = false;

    constexpr explicit ValueStore(T val)
    :
        value{std::move(val)},
        hasValue{true}
    {}

    constexpr ValueStore() noexcept = default;

    constexpr T const&  getValue() const&  noexcept { return value.value(); }
    constexpr T&        getValue() &       noexcept { return value.value(); }
    constexpr T const&& getValue() const&& noexcept { return std::move(value).value(); }
    constexpr T&&       getValue() &&      noexcept { return std::move(value).value(); }
};

Now ValueStore can have no value, because it is no longer holding a T, it’s holding a std::optional<T>… but now hasValue is redundant: it’s just duplicating value.has_value(). You could just do:
template <typename T>
class ValueStore
{
private:
    std::optional<T> value;

public:
    constexpr explicit ValueStore(T val) : value{std::move(val)} {}

    constexpr ValueStore() noexcept = default;

    constexpr T const&  getValue() const&  noexcept { return value.value(); }
    constexpr T&        getValue() &       noexcept { return value.value(); }
    constexpr T const&& getValue() const&& noexcept { return std::move(value).value(); }
    constexpr T&&       getValue() &&      noexcept { return std::move(value).value(); }

    constexpr bool hasValue() const noexcept { return value.has_value(); }
};

Anywho, back to your code: As I said, I think it’s a decent attempt at a very, very hard problem. In particular, your code is correct, for the vast majority of use cases… it’s just not efficient. Which is not a bad start! It’s always good to get it right first, and get it fast later, if possible.


Calling a Luhn check function when a credit card field changes

$(function() {
  // Always select a context and use it as the second parameter
  // it will make everything far faster and less prone to errors
  var form = $('form');
  var stripCcNum = function(el) {
      return $(this).val().replace(/[^\d]/g, '');
  }

  $('input[name="payment\[cc_number\]"]', form).keyup(function() {

    setSelectValue(stripCcNum(this));

  }).blur(function(ccNum) {

    if (!luhnCheck( stripCcNum(this) )) {
        alert('Please enter a valid credit card number.');
    }

  });

});

Or for the totally and absolute 1337 (meaning you shouldn't do it for something this simple but it demonstrates some useful techniques)

$(function() {
  var form = $('form'),
    handleCcNum = function(doThis) {
      return function() {
        doThis.call(this, $(this).val().replace(/[^\d]/g, ''));
      }
    }

  $('input[name="payment\[cc_number\]"]', form)
    .keyup( handleCcNum(function(num) { setSelectValue(num); } )
    .blur( handleCcNum(function(num) {
       !luhnCheck(num) && alert('Please enter a valid credit card number.');
    }));
});


Determine closest ancestor that has a certain HTML class

Extending native prototypes is a little iffy. Not that this should cause any problems, but in principle it's best to avoid. The reason is mostly that if everyone extend native prototypes, then you're more likely to run into issues (i.e. if you include a library that tramples on your extensions or vice-versa). Hence the general consensus is to try to leave them alone.

All that said, the main point approach it with open eyes, and proceed at your own risk.

In this case, I doubt you risk much, but it's always a good idea to consider something like:

if (!Element.prototype.getAncestorByClassName) {
  // extend the prototype
}

just to only do the extension if the function doesn't already exist. Of course, this is considerably more useful for polyfills, where a standardised function does exist and its signature is known. Here, if a getAncestorByClassName function already exists, it's hard to know if it works the same as yours since either one would be non-standard. Anyway, just something to consider.

As for the code:

The first step you take is to call currentNode.parentElement. This precludes you finding the element itself. Granted the function is called get ancestor, but still... say you call it on an element like body > p > span.highlight, and ask it to find the class highlight: You'd get null back. I'd include the initial element in the search.

Your also doing some unnecessary work in checking for === null inside the loop, since the while loop's condition could do that. Since you always end up exiting the loop somehow, it might as well be apparent in the loop's own condition, rather than have it be explicitly defined as an infinite loop.

And there's no reason to redeclare var currentNode inside the loop; it's already declared.

Also not a fan of the "minimal semicolons"-style, but that's just me. Works without them too.

Cleaned up a bit, it could look like:

Element.prototype.getAncestorByClassName = function(className) {
    var currentElement = this;

    while (currentElement) {
        if (currentElement.classList.contains(className)) {
            return currentElement;
        }
        currentElement = currentElement.parentElement;
    }

    return null;
}

Of course, since you're extending the Element prototype you could be clever and make it recursive. It looks nice, but I'd probably stick to the simpler loop myself:

Element.prototype.getAncestorByClassName = function(className) {
    if (this.classList.contains(className)) {
        return this;
    }

    if (!this.parentElement) {
        return null;
    }

    return this.parentElement.getAncestorByClassName(className);
}


I agree with @mnhg: if you had the collection of cards beforehand, things would simplify dramatically:

players_cards = all_cards.sample(nplayers * ncards_each).each_slice(ncards_each).to_a