Keep in mind that there already exist rope structure implementations in Rust, which support utf8, for example an_rope, where your PieceTable::insert is Rope::insert_str: https://docs.rs/an-rope/0.3.1/an_rope/struct.Rope.html#method.insert_str
Your code is really good for someone who just started learning, and nothing stands out as a misuse of language.
Why is index + 1 passed to piece_at, not simply index?
Using VecDeque does give a little potential for speedup in random insertion and removal. Although if I was doing a program like this, my choice of the data structure would be different - I'd use BTreeSet<Piece> instead, and order the Pieces by piece.offset.
You may write a removal and an insert at the same index as a single [] = instead.
About Copy/Clone:

if your Piece derived Copy, the & in &self.table[index] could be omitted. Did you try compiling this code? Can it compile without errors? I doubt it since  the immutable borrow with & will prevent you from removal and insertion later on.
the .clone() in piece_at can be omitted, because piece: usize is Plain Old Data that is copied around with zero overhead (in syntax and in performance as well).

There are two tiny misspellings

text: &string instead of text: &str
(usize,usize>, instead of (usize,usize)>,

I'd change the Err(-1) return to carry the unit value instead as we don't need the i32 to signal anything. We return Err(()) there.


Mars Rover challenge in Python - general feedback

The Plateau class seems to be pretty unused:

It doesn't have actual behaviour, it only hosts the get_plateau_size() method.
That method should have a first parameter named cls by convention. self is only used for instances, but here you get the class itself, not an instance.
By that, it also returns a Plateau, because calling a class creates an instance. This is kind-of confusing, because I'd have expected some kind of size.
Further, the user interaction (input()) was unexpected here. Don't hide such usage details in classes that make sense on their own.
The call contains redundancy as well, Plateau.get_plateau_size() features the term "plateau" twice. Once would have been enough.
Anyhow, the result isn't even used, so this whole class could be removed!

LEFT_ROTATE and RIGHT_ROTATE are both only used in a single function, no need to make them globals.
Take a look at the dataclass decorator ( https://docs.python.org/3/library/dataclasses.html), it could help you structure your classes a bit better. In particular, it would generate __str__ for you.


Simple factory retrieving object by name

In general your code looks fine, though there are some points to improve:

Memory management

Instead of using raw pointers and new delete, you should use a smart pointer to express transfer of ownership explicitly:

template<typename O>
void register_type(const std::string & name) {
    types[name] = [](){ return std::unique_ptr<O>(new O); };
}

std::unique_ptr<object> get_object(const std::string & object_name ) {
    return types[object_name]();
}

Thus it's clear, the caller will own the object instance, and doesn't need to struggle calling delete correctly if the obtained instance goes out of scope.

Template parameter naming

The more usual name for the template parameter is rather T than O

Use a factory class instead of global functions and global map

Consolidate the code of the register_type(), get_object() functions and the types map variable into a class Registry, and provide a single instance of that one.

This would allow to encapsulate the types map as a private class member.

You could consider making that class a Singleton.

Check if the type name is registered

You should check if the string passed to the get_object() function was already registered in the map, rather than blindly calling the default (NOP) function from the map.

Usage of static for a global function

You should be aware that static actually make the register_type() function only visible for the translation unit, it appears in. Actually you should not need it.

BTW, the technique you're using is often seen for unit testing frameworks (like e.g. google-test) as test case factories, also often coming along with stringizing macros for the registered classes.


Regex to parse semicolon-delimited fields is too slow

.*?;.*? will cause catastrophic backtracking. See this post on more details on the problem: http://www.regular-expressions.info/catastrophic.html

To resolve the performance issues, remove .*?; and replace it with [^;]*;, that should be much faster.


Reducing the amount of List in a WebScraper

Review

Creating functions that read and modify global variables is not a good idea, for example if someone wants to reuse your function, they won't know about side effects.
index is not useful, and range(0, n) is the same as range(n)
Using == is more appropriate than is in general, hence response.status_code == 200
If response.status_code != 200, I think the function should ~return an empty result~ raise an exception like said by @Ludisposed.
You use json_data["data"]["items"] a lot, you could define items = json_data["data"]["items"] instead, but see below.
Your usage of i is totally messy. Never use both for and while on the same variable. I think you just want to get the information for each item. So just use for item in json_data["data"]["items"]:.
Actually, print("Getting data from site... please wait a few seconds") is wrong as you got the data at response = get(url). Also, sleep(0.5) and sleep(5) don't make any sense.
Speaking from this, requests.get is more explicit.
You can actually create a pandas DataFrame directly from a list of dictionaries.
Actually, if you don't use the response in another place, you can use the url as an argument of the function.
Putting spaces in column names of a DataFrame is not a good idea. It removes the possibility to access the column named stock (for example) with df.stock. If you still want that, you can use pandas.DataFrame.rename
You don't need to import json.
The discounts are given as strings like "59%". I think integers are preferable if you want to perform computations on them. I used df.discount = df.discount.apply(lambda s: int(s[:-1])) to perform this.
Optional: you might want to use logging instead of printing everything. Or at least print to stderr with:

from sys import stderr

print('Information', file=stderr)

Code

import requests
import pandas as pd

def getShockingSales(url):
    response = requests.get(url)
    columns = ["name", "price", "discount", "stock"]
    response.raise_for_status()
    print("Response: OK")
    json_data = response.json()
    df = pd.DataFrame(json_data["data"]["items"])[columns]
    df.discount = df.discount.apply(lambda s: int(s[:-1]))
    print("Task is completed...")
    return df

URL = "https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&limit=16&filter_soldout=true"
df = getShockingSales(URL)


Today I had to do something that looks like this, so I am posting my answer in case someone needs this.
I needed to create a C struct for passing to pulseaudio in linux, the struct is like this:

struct pa_cvolume{
    uint32 channels;
    uint32 values[32];
}

what I was trying to do was to set newVolume in as much fields as the value of channels was:

let newVolume = 23123 // some random value

var paVolume = pa_cvolume() // create struct
paVolume.channels = 2 // read channels from other place

var volumeChannels = withUnsafeMutablePointer(&paVolume.values) {
  return UnsafeMutablePointer<UInt32>($0)
}

//iterate as if it was C
for i in 0..<Int(paVolume.channels) {  // Int required to subscript UnsafePointers
  volumeChannels[i] = newVolume
}

print(paVolume)

this way you don't need padding (because creating the struct comes with memory already zeroed)


Chart of answered CR posts percentages over time - Part 2

An error and a logic problem.
The code would fail if you ran it as a module or in strict mode due to undefined variable. There is also a problem when parsing the HTML, if there is missing data the timestamps and the percentages will go out of sync because you fail to increase i.
Async functions handle errors by assigning them to the returned promise catch callback. You have wrapped a try catch around code that may throw unrelated development error which you would see as "Error loading data" and not differentiate a legit error from source/logic error.
It is unclear what you intend to happen when fetched data is bad (eg 404 page) asd this will not throw error and you ignore such errors without giving any feedback.
A clearer separation of roles with fetch and parsing as functions rather than the single async function.
Data is also all over the place with the graph settings declared at the top and then more in the function that creates the graph.
General points

You use an undeclared variable contentElement in getGraphData

Why the if (matches.length) { Will that ever happen??? And if it does doesn't that mean that i as index to timeStamps no longer matches the the for loop position?

window is the default object and not needed for direct references. If you are defining globals, clearly define them in the global scope. If they are external use comments to indicate that they external globals.

Why assign to a variable that is never used? window.myLine = new Chart(

Keep it DRY. Axis object could be a function, also several other parts can be reduced using functions.

Reduce number of lines of source code by avoiding single use variable declarations.

Avoid using innerHTML when possible as it is much slower than textContent.

Use direct element id referencing when you are in control of content.

Only wrap the relevant code in try catch. ECMAScript 2018 lets you drop the error object after the catch token. Better yet separate the async part of the function and use promise catch function.

Use the shortest form when possible. Eg you used datasets: [Object.assign(dataset, {data})] that can be datasets: [{...dataset, data}]

Why the if (contents.length === timestamps.length) and no warning if the data is bad?.

Double/same line open [{, ({, or [[... etc should be followed by single indent and matching double close. See rewrite.

Redundant repeated X axis label content " 12:00 AM" can be removed

Graph heading and page heading are different. Maybe assign the graph heading from the page heading??

Possible rewrite
This rewrite reduces the number of lines and encapsulates most of the requirements within a single function reducing the global namespace pollution.
Data vetting was a little unclear so just added that to the graphing function to show a warning if no data found.

"use strict";
// uses chartColors defined in ???.js

document.addEventListener("DOMContentLoaded", displayAnswerRate);

function displayAnswerRate() {
    const CORS_PROXY = "https://cors-escape.herokuapp.com/";
    const url = "https://chat.stackexchange.com/search?q=%22RELOAD!+There+are%22&user=125580&room=8595&pagesize=150";

    const showError = message => {
        errorEl.style.display = "block";
        errorEl.textContent = message;
    }
    getDataURL(url)
        .then(parseDataAndChart)
        .catch(() => {
            loading.style.display = "none";
            showError("Error loading data");
        });

    async function getDataURL(url) { return (await fetch(CORS_PROXY + url)).text() }

    function parseDataAndChart(markup){
        const elsByClass = cName => [...html.querySelectorAll("." + cName)].reverse();
        const html = document.createElement('div');
        html.innerHTML = markup;
        drawChart(
            elsByClass("content").map(el => el.textContent.split("(")[1].split("%")[0]),
            elsByClass("timestamp").map(el => el.textContent.replace(" 12:00 AM",""))
        );
        loading.style.display = "none";
    }

    function drawChart(data, labels) {
        const axis = name => [{display: true, scaleLabel: {display: true, labelString: name}}];
        if (data.length > 0) {
            Chart.defaults.global.legend.display = false;
            new Chart(canvas.getContext('2d'), {
                type: 'line',
                data: {
                    labels,
                    datasets: [{
                        label: 'Answered Percentage',
                        backgroundColor: chartColors.red,
                        borderColor: chartColors.red,
                        data,
                        fill: false
                    }]
                },
                options: {
                    title: {display: true, text: heading.textContent},
                    scales: { xAxes: axis("Date"), yAxes: axis("Percentage") }
                }
            });
        } else {
            showError("No data found???");
        }
    }
}
body {
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
h2 {
  text-align : center;
}
#errorEl {
  display : none;
  color: red;
}

Answered percentage in recent months

  <canvas id="canvas"></canvas>


Finding most common contiguous sub-lists in an array of lists

1. Write a test case

When working on performance of code, the first thing to do is to make a reproducible test case. We'll need to have your code in a function:

from collections import Counter

def subsequence_counts_1(sequences):
    counts = Counter()
    for sequence in sequences:
        input = "".join(sequence)
        for j in range(1,len(input)+1):
            counts = counts + Counter(input[i:i+j] for i in range(len(input)-(j-1)))
    return counts

and then we need some test data:

import random
import string

def test_data(n, m, choices):
    """Return a list of n lists of m items chosen randomly from choices."""
    return [[random.choice(choices) for _ in range(m)] for _ in range(n)]

So let's try a small example:

>>> data = test_data(50, 50, string.ascii_uppercase)
>>> from timeit import timeit
>>> timeit(lambda:subsequence_counts_1(data), number=1)
102.42408156394958

2. Don't build data structures by repeated addition

The main problem with the code is this line:

counts = counts + Counter(...)

which has essentially the same effect as:

new_counts = counts + Counter(...)
counts = new_counts

That is, it creates a new Counter object and populates it with the counts from both of the addends. In particular, this involves copying across the whole contents of counts into the new object.

We can avoid all that copying by using the update method:

def subsequence_counts_2(sequences):
    counts = Counter()
    for sequence in sequences:
        input = "".join(sequence)
        for j in range(1,len(input)+1):
            counts.update(input[i:i+j] for i in range(len(input)-(j-1)))
    return counts

and this is a thousand times faster:

>>> timeit(lambda:subsequence_counts_2(data), number=1)
0.08853063406422734

 3. Further improvements

There are few more minor improvements that we could make:

Instead of having separate iterations over i and j, we can iterate over both at the same time using itertools.combinations.
Instead of calling Counter.update for each sequence, we could do all the work in one comprehension.

This results in the following:

from itertools import combinations

def subsequence_counts_3(sequences):
    return Counter(seq[i:j]
                   for seq in map(''.join, sequences)
                   for i, j in combinations(range(len(seq) + 1), 2))

which is about 60% faster than subsequence_counts_2:

>>> timeit(lambda:subsequence_counts_3(data), number=1)
0.052610712591558695

But it's still not going to be able to solve your problem in a reasonable amount of time:

>>> data2 = test_data(100, 100, string.ascii_uppercase)
>>> timeit(lambda:subsequence_counts_3(data2), number=1)
0.5441978382878006

So to process 100 million sequences of 100 characters would take more than half a million seconds, which is more than six days.

4. Using tuples

If you want to handle other kinds of data, convert the sequences to tuples:

def subsequence_counts_4(sequences):
    return Counter(seq[i:j]
                   for seq in map(tuple, sequences)
                   for i, j in combinations(range(len(seq) + 1), 2))

and then you can use any hashable items:

>>> data3 = test_data(50, 50, list(range(10)))
>>> subsequence_counts_4(data3)[(8, 8, 8)]
5


A text editor driven file renamer in Ruby

RM = '/bin/rm'
MV = '/bin/mv'

In general it's preferable to use the FileUtils class rather than relying on shell utilities. Though in this particular case, you might want to stick at least with mv since the FileUtils.mv method does not have an :interactive option.

tmp = "/tmp/renamer.#{Time.now.to_i}.#{(rand * 1000).to_i}"

Ruby has a Tempfile class which can generate a unique temporary file more reliably than this. You should use it.

from.each {|i| f.puts i}

Calling puts on an array will puts each line individually, so the above can just be shortened to f.puts from.

ENV['EDITOR'] = 'vi' if ENV['EDITOR'].nil?

Can be shortened to ENV['EDITOR'] ||= 'vi'. Though what you have isn't particularly verbose either, so it doesn't really matter much which one you choose.

system("#{ENV['EDITOR']} #{tmp}")

Use system(ENV[EDITOR], tmp) instead. This way you get rid of the string interpolation and the code still works if either ENV['EDITOR'] or tmp should contain a space or other shell meta-character (not that they're particularly likely to, but it's a good idea to use the multiple-argument-form of system where ever possible).

to = File.open(tmp) {|f| f.readlines.collect{|l| l.chomp}}

Usually this could be replaced with to = File.readlines(tmp).collect {|l| l.chomp}. However if you follow my suggestion of using Tempfile, that won't be an option any more.

`#{RM} #{tmp}`

If you use fileutils, this will just be FileUtils.rm(tmp) (or rm(tmp) if you include FileUtils). If you don't want to use FileUtils, you should at least use system(RM, tmp) for the same reasons as above.

However if you use Tempfile, which you should, this becomes redundant anyway.

from.each_with_index do |f, i|
  puts `#{MV} -v --interactive "#{f}" "#{to[i]}"` unless f == to[i]
end

To iterate over two arrays in parallel, use zip:

from.zip(to) do |f, t|
  system(MV, "-v", "--interactive", f, t) unless f == t
end

Note that here using system instead of backticks is especially important since one of the files in from or to containing spaces is actually somewhat likely.

So with all my suggestions, your code should now look like this:

#!/usr/bin/env ruby
require 'tempfile'

MV = '/bin/mv'

from = Dir.glob('*').sort

ENV['EDITOR'] ||= 'vi'

to = nil
Tempfile.open("renamer") do |f|
  f.puts from
  f.close
  system(ENV['EDITOR'], f.path)
  f.open
  to = f.readlines.collect {|l| l.chomp}
end

if to.size != from.size
  STDERR.puts "renamer: ERROR: number of lines changed"
  exit(1)
end

from.zip(to) do |f, t|
  system(MV, "-v", "--interactive", f, t) unless f == t
end


Search a string for barcodes but ignore certain characters

edit: The first time I read your code I mis-interpreted what was happening because of the signature of the function, and I suggested an approach that you were already using ¯_(ツ)_/¯

I like managing the loop using String.Index instead of Int because it saves a lot of casting you'd need to do otherwise (this is all in Swift 3).

let text = "hello"
var position = text.startIndex
while position < text.endIndex {
    let character = text[position] // get substring at range
    print(character)
    position = text.index(after: position) // increment index by 1
}
// -> prints
// h
// e
// l
// l
// o

Here's my approach that I hope gives you some inspiration or ideas!

edit: updated to loop over unicode scalars so it's easier to use exclusions.contains(currentCharacter)

extension String {

    func range(of target: String, ignoring exclusions: CharacterSet) -> Range<String.Index>? {

        var startPosition = unicodeScalars.startIndex

        let limit = unicodeScalars.index(unicodeScalars.endIndex, offsetBy: -target.unicodeScalars.count)

        while startPosition < limit {

            var targetPosition = target.unicodeScalars.startIndex
            var currentPosition = startPosition

            while currentPosition < unicodeScalars.endIndex  {

                // get characters at current & target positions then increment the current position
                let currentCharacter = unicodeScalars[currentPosition]
                let targetCharacter = target.unicodeScalars[targetPosition]

                print("target", targetCharacter, "current", currentCharacter)

                currentPosition = unicodeScalars.index(after: currentPosition)

                if currentCharacter == targetCharacter {
                    // if the current character matches the target character:
                    // - increment the target posistion
                    // - return the range if there are no more characters to match in the target
                    targetPosition = target.unicodeScalars.index(after: targetPosition)

                    if targetPosition == target.unicodeScalars.endIndex,
                        let start = startPosition.samePosition(in: self),
                        let end = currentPosition.samePosition(in: self) {

                        return start..<end
                    }
                }
                else if targetPosition == target.unicodeScalars.startIndex || !exclusions.contains(currentCharacter) {
                    // if:
                    // - we're still at the start of the target; or
                    // - the current chracter isn't one of our valid exclusion characters
                    // then:
                    // - advance the start position and break out of the loop
                    startPosition = unicodeScalars.index(after: currentPosition)
                    break
                }
            }
        }
        return nil
    }
}

Testing

let messy = "Serial: YF 1942-B (Scanned)"

if let range = messy.range(of: "YF1942B", ignoring: CharacterSet.alphanumerics.inverted) {
    // -> Range<String.Index>(8, 17)

    messy.substring(with: range)
    // -> "YF 1942-B"
}


Given that you don't want to use append, this looks great to me. I'm not sure if I can even think of a different way to do it.

My only suggestion would be naming related. l is a terrible name for a variable - it's too close to 1. orig is questionable, since it's not really the original list, it's the list you're currently "popping" (logically, not literally) off of - so you could simply rename both l and orig to something like lst or xs or elems or ....


The stack approach is dubious. It uses too much memory (the entire file is eventually collected, while you only care about its tail). Consider a ring buffer instead.
I don't see the point of #include <stdbool.h>
Casting is unnecessary, as in (char*)stack_top(stack) - and even dangerous, as in (Node*)malloc(sizeof(Node)). Why you shouldn't cast malloc.
Always test that malloc doesn't return NULL.
A declaration

int i = 0;

is unnecessary.
Nitpicking. #define LINE_SIZE 256 is a very optimistic estimate. Try to manage a file with really long lines.


Analyzing records of London Underground outages

That's a fun problem.

Don't use more memory than you have to

with open('input.txt') as file:  # read the input file into a list of lines
    file_input = file.read().splitlines()
# ...
for var in file_input:
    LonUndOutages.append(var.split("|"))

shouldn't be necessary. Rather than calling file.read(), iterate on the file object itself. It will yield lines that you can split on directly.

Naming conventions

LonUndOutages

becomes

lon_und_outages

and similarly for your other variables.

Unpack your line

Assign variables to the results of your split, like so:

date, line, station, notes = outage

Note that there's a nomenclature collision, because your spec describes one column as line, so call each file line a record or an outage.

Separate output from logic

        Prob1Output = Prob1Output + line[2] + "was affected by an outage on July 10, 2019\n"

You're storing output early for two purposes: to eventually show that output, and to know whether there were stations affected. This dual-purpose code is generally not advisable. Store the confirmed outages in a separate list, or yield them from a generator function, to be consumed and formatted by an output function that has no logic at all.

General

Run a linter that will tell you PEP8 hints, or use an IDE that will do the same. Make functions to house your logic.

Example

from collections import namedtuple
from datetime import date, datetime
from typing import Iterable, Set

Record = namedtuple('Record', ('date', 'line', 'station', 'notes'))

def read_file(fn: str) -> Iterable[Record]:
    with open(fn) as file:
        for record in file:
            date_str, *others = record.split('|')
            record_date = datetime.strptime(date_str, '%m-%d-%Y').date()
            yield Record(record_date, *others)

def stations_on_date(records: Iterable[Record], record_date: date) -> Set[str]:
    return set(r.station for r in records if r.date == record_date)

def lines_and_stations_between_dates(
    records: Iterable[Record],
    start: date,
    end: date,
) -> (Set[str], Set[str]):
    matching = [r for r in records if start <= r.date <= end]
    lines = set(r.line for r in matching)
    stations = set(r.station for r in matching)
    return lines, stations

def print_iter(to_print: Iterable[str]):
    msg = ', '.join(to_print)
    print(msg or 'none')

def main():
    records = tuple(read_file('input.txt'))

    date1 = date(2019, 7, 10)
    print(f'Stations affected by an outage on {date1}:')
    stations1 = stations_on_date(records, date1)
    print_iter(stations1)

    start2 = date(2017, 7, 10)
    end2 = date(2017, 11, 14)
    range_desc = f'between {start2} and {end2}'
    lines2, stations2 = lines_and_stations_between_dates(records, start2, end2)

    print(f'Lines with outages {range_desc}:')
    print_iter(lines2)

    print(f'Number of stations affected {range_desc}:')
    print(len(stations2))

if __name__ == '__main__':
    main()

Note:

Output and logic are separated
Use a namedtuple for better structure
Hold onto a date, not a datetime
Use set to avoid duplicates in the output


Random string of variable length generator

Just two remarks:

RandomChar should be a method because it returns a different result each time - this is just a convention that we usually follow in C#

  In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects.

from Choosing Between Properties and Methods

so

  Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.

but

  Do use a method, rather than a property, in the following situations.

amonong many others:

  The operation returns a different result each time it is called, even if the parameters do not change. For example, the NewGuid method returns a different value each time it is called.

You can cast the result to char and don't need the Convert.ToChar

_

private static char RandomChar() => (char)Random.Next(char.MinValue, char.MaxValue);

You can also improve the performance by precalculating the array with chars:

private static readonly char[] Chars =
    Enumerable
    .Range(char.MinValue, char.MaxValue)
    .Select(x => (char)x)
    .Where(c => !char.IsControl(c))
    .ToArray();

the RandomChar method would take the values from this array:

private static char RandomChar() => Chars[Random.Next(0, Chars.Length)];

so building the string can be a simple loop:

for (int i = 0; i < length; i++)
{
    stringBuilder.Append(RandomChar());
}

Without the StringBuilder this seems to be faster in tests by just ~8ms for 100.000 loops and a string lenght of 1.000

var chars = new char[length];
for (int i = 0; i < length; i++)
{
    chars[i] = RandomChar();
}
return new string(chars);

StringBuilder.ToString processes the data in order to build the string. It's quite fast but in this particular situation the minimal overhead is noticable. Generally the StringBuilder is the fastet way to build strings so using it is definitely the right choice.

Changing the Random.Next(0, max) to Random.Next(max) improves the performance by another 10ms for the same tests.


Is there a way to refactor the c# code having multiple conditions?

You've got lots of tests for paymentAuto.PaymentType there, and many of the cases are the same. A switch statement will neaten that up, as it only names paymentAuto.PaymentType once, and it encourages you to put all of the cases nicely aligned together in code:
public static PaymentOptions GetPaymentOptions_Auto(TestConfigurationCDO testConfiguration, int siteId)
{
    var paymentOptionList = SitePaymentRepository.GetSitePaymentInfoBySiteId(
        testConfiguration,
        siteId);

    var lowestPriority = paymentOptionList.Min(x => x.Priority);
    var paymentAuto = paymentOptionList.First(x => x.Priority == lowestPriority);

    PaymentOptions paymentOptions;

    switch (paymentAuto.PaymentType)
    {
        case PaymentMethod.PayPalDirect:
        case PaymentMethod.Braintree:
        case PaymentMethod.BankTransfer:
        case PaymentMethod.AdyenDropIn:
            paymentOptions = new ClientCheckoutOptions()
            {
                paymentMethod = paymentAuto.PaymentType
            };
            break;

        case PaymentMethod.Klarna:
            paymentOptions = new KlarnaOptions();
            break;

        case PaymentMethod.PayPalExpress:
        default:
            paymentOptions = new PaypalOptions();
            break;
    }
}

The initial value you were assigning to paymentOptions wasn't used, so you can leave that variable uninitialised. The compiler will moan at you if you forget to initialise it somewhere in the switch statement.
That .FirstOrDefault() shouldn't fail to find a matching item. To make sure of this, I changed it to .First(), which throws an exception if it can't find a match. .Where(...).First() is the same as .First(...) (but a bit more expensive), so I changed that as well.
Annoyingly there's no .MinBy method in Linq (there are plenty of examples of implementations around, though). If you have this, you can write var paymentAuto = paymentOptionList.MinBy(x => x.Priority).


Python class to implement a list with a size limit

Below,  I have slightly recast your class.  In those changes are incorporated two suggestions.

1) If limiting the size of the structure, do it at the input:

I removed the length check from get_list() and moved it to push()

2) Class attributes are not instance attributes:

You code had a bug whereby the ls attribute was declared on the class and not  on the instance. In the case of:

class MaxSizeList(object):

    ls = []

ls will be shared will all instances of MaxSizeList.  What you need is actually:

class MaxSizeList(object):

    def __init__(self, max_length):
        self.ls = []

In this case, every instance will get its own ls.

I am going to guess that this is why you needed to do the limiting on the output and not on the input.  That combined with using the same test data for the a and the b instance allowed your test cases to pass even with a substantial bug.

Code:

class MaxSizeList(object):

    def __init__(self, max_length):
        self.max_length = max_length
        self.ls = []

    def push(self, st):
        if len(self.ls) == self.max_length:
            self.ls.pop(0)
        self.ls.append(st)

    def get_list(self):
        return self.ls


Good usage of MailboxProcessor/Agent in class rather than mutable field?

Your code looks pretty good to me - I would only change some minor details.

I'd replace UdpClient seq with UdpClient list, because lazy sequences can be subtle. In your code, this doesn't seem to be a problem, but they can cause unexpected GC issues (by capturing a reference) and tricky performance behavior (by re-evaluating things).
I'd probably write the creation of clients differently - I think the following is easier to understand:

let uniAndMulticastUdpClients =
  [ for ip in ipAddresses do
      yield createUnicastClient(ip, port)
      yield createMulticastClient(ip) ]

You're calling closeRunningClients in both branches, so you can extract it and move it before the match construct (and, in fact, you can just use the Seq.iter call without defining a function for it).


Interesting question,

I haven't found an obvious best way to do this.

For sure, sending true as a parameter should always be avoided, I'd rather see

var IS_USER_LOCATION = true;
$scope.addMarker(position.coords.latitude, position.coords.longitude, IS_USER_LOCATION);

though probably I would create 2 functions, 1 called addMarker and 1 called addUserMarker.

Finally, it amused me that the first 2 parameters in both calls are properties of the same object, so why not just ask for a coordinates object ?

$scope.addMarker = function ( coordinates ) {
    $scope.markers.push({
        latitude: parseFloat(coordinates.latitude),
        longitude: parseFloat(coordinates.longitude),
        icon: "img/marker-map.png";
    });
}

$scope.addUserMarker = function ( coordinates ) {
    $scope.markers.push({
        latitude: parseFloat(coordinates.latitude),
        longitude: parseFloat(coordinates.longitude),
    });
}

$scope.addUserMarker(position);

$scope.populateMarkers = function(locations) {
    for (var i = 0; i < locations.length; i++) {
        $scope.addMarker(locations[i]);
    }
}


From the OOP/typing level, you might want to consider having Disk be a type.  If it doesn't need any methods, you could just make it a subtype of int:

from typing import NewType

Disk = NewType('Disk', int)

Some notes on your interfaces:

Since you always use get_last_disk and delete_disk together, why not combine them?  The thing you really want is a pop_top_disk operation that removes and returns the last disk (that's already how you're implementing delete_disk anyway).
add_disk could implement the "no larger disk on a smaller one" rule.
get_whole_tower seems bad because it's exposing the internal data structure of the tower; this violates your entire OOP abstraction.  Note also that in general you should distinguish between "private" and "public" members of your classes.
Rather than making NB_DISKS a global and having Plateau initialize itself from that, Plateau's initializer should take the number of disks as a parameter.
The Pythonic way of making a "print" function is to implement the magic function __repr__ to return a string.
The int values of your disks should be reversed so that bigger numbers represent bigger disks.
This is more an English thing than a Python thing, but the verb form of "motion" is "move" so it would be better to name your method move.  :)

Here's the final code I came up with after implementing the above suggestions:

from typing import NewType

Disk = NewType('Disk', int)

class WrongOrder(Exception):
    def __init__(self, top: int, bottom: int) -> None:
        super().__init__("Can't put a disk of size %d on a disk of size %d" % (top, bottom))

class Plateau:
    """Class for the whole plateau"""
    def __init__(self, nb_disks: int) -> None:
        self._init_plateau(nb_disks)

    def _init_plateau(self, nb_disks: int) -> None:
        self._towers = [Tower(nb_disks), Tower(0), Tower(0)]

    def move(self, from_tower: int, to_tower: int) -> None:
        """Move from one tower to another (towers specified as an int from 1-3).
        Prints an error if the move is invalid."""
        # Convert from 1-index to 0-index.
        from_tower -= 1
        to_tower -= 1
        # Make the move, print exception if it fails.
        try:
            disk = self._towers[from_tower].pop_top_disk()
            try:
                self._towers[to_tower].add_disk(disk)
            except WrongOrder:
                # don't drop the disk!  Put it back where we got it and reraise.
                self._towers[from_tower].add_disk(disk)
                raise
        except Exception as e:
            print('Move failed: ', str(e))
        else:
            self._check_victory()
            print(self)

    def _check_victory(self) -> None:
        """Check if all disks have moved to the last tower (victory condition).
        If the player has achieved victory, reset the game.
        """
        if sum(tower.height for tower in self._towers) == self._towers[2].height:
            print('victory:')
            print(self)
            print('new plateau:')
            self._init_plateau(self._towers[2].height)

    def __repr__(self) -> str:
        """Print the towers"""
        return "\n".join([repr(tower) for tower in self._towers]) + "\n"

class Tower:
    """Class for a tower"""
    def __init__(self, nb_disks: int) -> None:
        """Creation of a tower"""
        self._tower = [Disk(size) for size in range(1, nb_disks + 1)]
        self._tower.reverse()  # order the stack from largest to smallest

    def pop_top_disk(self) -> Disk:
        """Remove and return the top disk on this tower."""
        return self._tower.pop()

    def add_disk(self, disk: Disk) -> None:
        """Add a disk to the top of the tower.
        Raises WrongOrder if the disk being added is too big.
        """
        if len(self._tower) and self._tower[-1] < disk:
            raise WrongOrder(disk, self._tower[-1])
        self._tower.append(disk)

    @property
    def height(self) -> int:
        """Number of disks in the tower."""
        return len(self._tower)

    def __repr__(self) -> str:
        """Print the elements of the tower"""
        return repr(self._tower)

if __name__ == '__main__':
    game = Plateau(3)
    game.move(1,3)
    game.move(1,3)   # Try to move a big disk on a small one
    game.move(1,2)
    game.move(3,2)
    game.move(1,3)
    game.move(2,1)
    game.move(2,3)
    game.move(1,3)


Best practice for Constant Class in Java

Answer to your questions :

Naming Scheme is correct? -

Ideally you should not create class with names like Variables, Parameters, etc. as these names also has literal meanings with them in many languages. Besides that, these classes are going to store Constants! You can simply create single class with name Constants! No need to create different Constant classes till it's absolutely necessary. Perhaps, in that case you should go for enums. Why? Check these links :

Link 1.
Link 2

Constant class structure is among best practices ?

This is answered in above point. Keep your naming convention readable enough so that you won't require separate constant classes.
Always try to implement KISS(Keep it Simple Stupid) and DRY(Don't repeat yourself!)

Should I create separate constant classes or having them encapsulated in a parent Constant class is fine?

Ideally not. If you need such requirement then go for enums. As enums are typesafe, you wont end up creating misleading statements. For ex.
If you write following potentially incorrect code then Constant class won't mind:

String playerType = Constants.MALE;

But, if you use enums, that would end up as:

// Compile-time error - incompatible types!
PlayerType playerType = Gender.MALE;


Recording all instances of a class - Python

Your approach is ok, but I have just one mention (this is based on personal preferences): I'd iterate over a class not a list which is defined outside it. You'll just have to define a metaclass which supports iteration.

class IterPerson(type):
    def __iter__(cls):
        return iter(cls._allPeople)

class Person(metaclass=IterPerson):
    _allPeople = []

    def __init__(self, name, age, height):
        self._allPeople.append(self)

        self.name = name
        self.age = age
        self.height = height

if __name__ == '__main__':
    Jeff = Person("Jeff", 20, "1.6")
    Bob = Person("Bob", 39, "1.4")
    Helen = Person("Helen", 19, "1.3")

    for person in Person:
        print(person.name + " is " + str(person.age))

Magic methods are always looked up on the class, so adding __iter__ to the class won't make it iterable. However the class is an instance of its metaclass, so that is the correct place to define the __init__ method.

Please note that I also put a _ in front of your list. This is how we tell python the list we'll create is private. I have also used if __name__ == "main": which is good practice (it is used to execute some code only if the file was run directly, and not imported)

Second, keep this kind of thing as simple as possible. Don't waste a lot of time and energy on something complex. This is a simple problem, keep the code as simple as possible to get the job done.


"/home/stanek/Downloads/" is used often, consider putting that as a script variable, if it's not already present as an environment variable provided by your shell user profile? Let's assume USER_DOWNLOADS="/home/stanek/Downloads", MUSIC_DIR="/home/stanek/Music" for the suggestions below.

You are invoking find three times, the problem being that new files created during each invocation will be missed by the subsequent one. This may be less of a problem between the first two, but will be for the second and third loops that are separated by a user prompt.

The other question is ask is whether your renaming of files should be done as part of the copying (i.e. later) process, or do you always want to rename the files regardless of whether the copying is done.

If it's the former, then you should only construct the new name within the final loop, for example:

# not *exactly* sanitized for files with spaces, just used as illustration only!
files_to_copy=$(find $USER_DOWNLOADS -iname "*.mp3" -mtime -7 | sort)
echo "Files will be copied:"
for i in $files_to_copy; do basename $i; done
# prompt user
for i in $files_to_copy; do
    new_name=$(basename $i | sed -e 's/.../.../;...');
    cp $i $MUSIC_DIR/$new_name
done

You can string sed commands together: sed -e 's/.../.../;...' as shown above. basename will do the equivalent of your sed "s/\/home\/stanek\/Downloads\///g".

If it's the latter, i.e. same as what you have presented here, then you can leave the first loop aside, but build up your list of files to be copied first:

files_to_copy= # ...
# ...
# prompt user
cp $files_to_copy $MUSIC_DIR
echo "$(awk -F' ' '{print NF}' <<< $files_to_copy) file(s) copied."

To get past filenames with spaces in them, files_to_copy should be constructed as a variable array.


All the sort functions follow the same pattern, with a few key differences:

A field to extract for comparison (.sortprice, .sort1)
A comparison function (numeric, alphabetic, ascending and descending)

These can be parameters for a general-purpose implementation:

sortHelper = function(search, comparator) {
    $('.product-wrapper').each(function() {
        var data = $(this).find(search).text();
        $(this).attr('data-name', data);
    });

    var $products = $('.products'),
        $singleProduct = $('.product-wrapper');

    $singleProduct.sort(comparator);

    $singleProduct.detach().appendTo($products);
};

The price comparator function can be implemented simpler than you did,
considering that it doesn't need to return precisely -1, 1 values,
any other negative and positive values would be fine:

var cmpPrice = function(a, b) {
    var an = a.getAttribute('data-name');
    var bn = b.getAttribute('data-name');
    var numberA = Number(an.replace(/[^0-9\.]+/g, ""));
    var numberB = Number(bn.replace(/[^0-9\.]+/g, ""));
    return numberA - numberB;
};

The string comparator function can be much like it was:

var cmpName = function(a, b) {
    var an = a.getAttribute('data-name');
    var bn = b.getAttribute('data-name');
    if (an > bn) {
        return 1;
    }
    if (an < bn) {
        return -1;
    }
    return 0;
});

The string comparator in descending order can be implemented in terms of the other one in ascending order:

var cmpNameDesc = function(a, b) {
    return cmpName(b, a);
});

And then the main function can be implemented in terms of these helpers:

selectionChange = function() {
    var selectResult = $("#sorting").val();

    if (selectResult == "Sort By Price") {
        sortHelper('.sortprice', cmpPrice);
    } else if (selectResult == "Sort By A-Z") {
        sortHelper('.sort1', cmpName);
    } else if (selectResult == "Sort By Z-A") {
        sortHelper('.sort1', cmpNameDesc);
    }
};


Filter dataframe based on unique values in multiple columns and drop rows based on index

I may have misunderstood what your are trying to achieve. However it sounds like you want to filter your dataframe for a unique list animal, color, age and breed. and from that take that largest, weight and height.
you could achieve this by sorting your data frame by weight then height this will sort from lowest to highest.
you can then drop duplicates based on the animal, color, age and breed and specify to the drop method to keep the last row(This will be the biggest since the table is ordered from low to high).
We can write this in a general function that will accept three parameters, a df, a list to sort by and a list to filter by.
def my_df_filter(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -> pd.DataFrame:
    sorted_df = df.sort_values(by=sort_by)
    dropped_df = sorted_df.drop_duplicates(subset=drop_by, keep='last')
    return dropped_df

This could actually all be returned in a single line by chaining them together. However I have broken it down for more readability. But you could write as
def my_df_filter1(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -> pd.DataFrame:
    return df.sort_values(by=sort_by).drop_duplicates(subset=drop_by, keep='last')

using your original code and a dataset of 100,000 rows. it reduced it from 100k rows to 54 rows and running it 100 times via timeit on my laptop took around 18 seconds.
import pandas as pd
import numpy as np
import timeit
from typing import List

def my_df_filter(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -> pd.DataFrame:
    return df.sort_values(by=sort_by).drop_duplicates(subset=drop_by, keep='last')

data_len = 100000
half = int(data_len / 2)
fifth = int(data_len / 5)
data = {
    'Animal': ['Cat'] * data_len,
    'Color': ['White'] * half + ['Black'] * half,
    'Age': np.random.randint(1, 10, data_len),
    'Breed': ['A'] * fifth + ['B'] * fifth + ['C'] * fifth + ['D'] * fifth + ['E'] * fifth,
    'Weight': np.random.uniform(1, 100, data_len),
    'Height': np.random.uniform(1, 100, data_len)
}
df = pd.DataFrame(data)

print(df.shape)
print(my_df_filter(df, sort_by=['Weight', 'Height'], drop_by=['Animal', 'Color', 'Age', 'Breed']).shape)

func = lambda: my_df_filter(df, sort_by=['Weight', 'Height'], drop_by=['Animal', 'Color', 'Age', 'Breed'])
print(timeit.timeit(func, number=100))

OUTPUT
(100000, 6)
(54, 6)
18.2784114

Having a general function means that its much easier to increase or reduce the number of columns to filter or sort by without having to change much code.


Recursion generally isn't more efficient, just easier to program and understand. For simpler examples it also leads to much neater code however can be harder to understand if you have multiple levels of recursion jumping around.

Each function call will add stuff to the stack as such it will use more memory and take longer as it has to allocate and initialize that memory, even when using pointers/references. You might also find you run into a depth limit in the form of a stack overflow (like the site name ☺).

With that said for most JSON it wouldn't likely be an issue, unless someone was sending malicious JSON your way which you should assume for any external input.


Replacing thrown exception with more descriptive exception during file I/O

Give your code some room to breathe with a few new lines, they're free.

Before:

public MyUpdater(...)
{
    _reader = ...;
    try {
        // Open immediately to ensure we can read the file:
        _reader.AccessForReading();
    } catch (IOException ioex) {
        var extype = ioex.GetType();
        if (extype == typeof(FileNotFoundException) || extype == typeof(DirectoryNotFoundException)) {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw new InvalidOperationException("File to update does not exist! It may have been moved because of foobar reason xyz ...", ioex);
        } else {
            // re-throw all other
            throw;
        }
    }
}

After:

public MyUpdater(...)
{
    _reader = ...;

    try
    {
        // Open immediately to ensure we can read the file:
        _reader.AccessForReading();
    }
    catch (IOException ioex)
    {
        var extype = ioex.GetType();

        if (extype == typeof(FileNotFoundException) || extype == typeof(DirectoryNotFoundException))
       {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw new InvalidOperationException("File to update does not exist! It may have been moved because of foobar reason xyz ...", ioex);
        }
        else
        {
            // re-throw all other
            throw;
        }
    }
}

Secondly, catching, filtering and then rethrowing seems wasteful here, why not just catch the explicit exceptions you hope to catch?

public MyUpdater(...)
{
    _reader = ...;

    try
    {
        // Open immediately to ensure we can read the file:
        _reader.AccessForReading();
    }
    catch (FileNotFoundException ex)
    {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw new InvalidOperationException("File to update does not exist! It may have been moved because of foobar reason xyz ...", ex);
    }
    catch (DirectoryNotFoundException ex)
    {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw new InvalidOperationException("File to update does not exist! It may have been moved because of foobar reason xyz ...", ex);
    }
}

Granted, this breaks DRY a little, but it is significantly easier to read. You can reduce duplication further by extraction your exception creation to another method.

public MyUpdater(...)
{
    _reader = ...;

    try
    {
        // Open immediately to ensure we can read the file:
        _reader.AccessForReading();
    }
    catch (FileNotFoundException ex)
    {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw CreateUpdateFileMissingException(ex);
    }
    catch (DirectoryNotFoundException ex)
    {
            // This is an explicit failure scenario in which case we do not want the raw IOException to escape
            throw CreateUpdateFileMissingException(ex);
    }
}

public InvalidOperationException CreateUpdateFileMissingException(Exception ex)
{
    return new InvalidOperationException("File to update does not exist! It may have been moved because of foobar reason xyz ...", ex)
}

On the other hand this bonus is negated if there are a lot of exception types you want to catch, so if that list grows, then sticking with your filtering method may be the better course of action.

As for what exception you should be throwing here, it appears that the error is that the file cannot be found, so what's wrong with a FileNotFoundException with a different message?

Lastly, the comment // re-throw all other is simply describing what your code is doing. That is your code's job. Comments should explain why you have made certain choices. If the code is too complex to understand it should be refactored and comments explaining what code does should only be considered in extreme circumstances where refactoring is a poor choice.


Checking whether a host has a second-level domain from a list

You can change your function to be much faster if you use a set.
You can also use re to reduce the amount of code too.

The regex that you can use is an optional non-capturing group of anything ending with a  ..
And a capturing group at the end of the string with one period:

(?=.+\.)?([^\.]+\.[^\.]+)$

Using this you can lop off the second-level domain, and do a single check.

def get_url_category(url):
    host = urlparse.urlparse(url.strip()).netloc
    domain = re.search(r'(?=.+\.)?([^\.]+\.[^\.]+)$', host)
    if domain is not None:
        domain = domain.group(1)
        if domain in domains_a:
            return 'a'
    if not host:
        return 'empty'
    return None

To make this faster you should change domains_a to a set:

domains_a = {'foo.com', 'bar.com', 'fur.net', 'beer.org'}

And finally to make the program easier to write you can change the domains to be a dictionary of sets.
To use this just loop through the items via domains.iteritems().
And if the host is found then you return the group.

domains = {
    'a': {'foo.com', 'bar.com', 'fur.net', 'beer.org'},
    'b': {'door.com', ...},
    'c': {'doom.com', ...}
}

def get_url_category(url):
    host = urlparse.urlparse(url.strip()).netloc
    domain = re.search(r'(?=.+\.)?([^\.]+\.[^\.]+)$', host)
    if domain is not None:
        domain = domain.group(1)
        for group, domains_ in domains.iteritems():
            if domain in domains_:
                return group
    if not host:
        return 'empty'
    return None

Finally I think returning None is a bit strange, but is fine.


To answer your (1) yield return in a recursive method ... Eric Lippert does it in Producing Permutations series, Part Three , specifically in his HamiltonianPermutationsIterator recursive method.

I won't dive into your (2) only to suggest that perhaps you read all of Eric Lippert's series to learn more.

Braces Need Improving

On coding style, your use (or lack thereof) of braces could be improved.  The C# convention is to put the opening brace on a new line (this differs from Java).

More importantly is that you lack braces on so many one-liners.  This is heavily discouraged.

I would suggest cleaning your code to change a snippet from this:

if (r > 1) {
    list.Swap(startPos, i);
    foreach (var permute in GetPermutations(list, r - 1, startPos + 1))
        yield return new List<T>().AddRange(list[startPos].AsEnumerable(), permute);
    list.Swap(startPos, i);
} else
    yield return new List<T>() { list[i] };

To this:

if (r > 1)
{
    list.Swap(startPos, i);
    foreach (var permute in GetPermutations(list, r - 1, startPos + 1))
    {
        yield return new List<T>().AddRange(list[startPos].AsEnumerable(), permute);
    }
    list.Swap(startPos, i);
}
else
{
    yield return new List<T>() { list[i] };
}

Swap Method

You really don't do anything with the bool returned from the Swap method.  Plus I see little reasoning in not swapping 2 values that happen to be equal.  This method could simply be void.

You are also encouraged to have meaningful names in C#, so i1 would be better named as index1.  Ditto for i2.

public static void Swap<T>(this IList<T> list, int index1, int index2)
{
    var temp = list[index1];
    list[index1] = list[index2];
    list[index2] = temp;
}


This implementation of the Front Controller Pattern has knowledge over too many concerns. The Single Responsibility Principal states that a class should only have one reason to change. From what I can see if any of the following things change, this class will be affectetd:

The location of controller class files
The name of the controller classes
How controller classes are instantiated
The pattern used to match URLs
How view files are loaded
How controller methods are invoked
Which views correspond to which methods on a controller

All of these concerns mixed into one class means it is near impossible to unit test a very critical part of your application.

To be honest, if this is a small application it isn't too bad. If your application grows in size and complexity this will quickly show its limits.

The answer?

Split each concern into it's own class (Single Responsibility Principle)
Have each class interact with the others through an interface (Interface Segregation Principle)
Pass these objects to each other through their constructors (Dependency Inversion Principle)

Going with a minimum of 4 classes and interfaces gives you a lot more flexibility for your application to grow.

First, the interfaces:

interface IUrlRouter {
    function getRoute(Request $request) : UrlRoute;
    function getErrorRoute() : UrlRoute;
}

interface IControllerFactory {
    function createController($controllerName);
}

interface IActionResultExecutor {
    function executeResult($result);
}

Then your "front controller" really just becomes "the application" which handles the Big Picture steps of the process:

class MvcApplication {
    private $controllerFactory;
    private $resultExecutor;
    private $router;

    public function __construct(IUrlRouter $router, IControllerFactory $controllerFactory, IActionResultExecutor $resultExecutor) {
        $this->router = $router;
        $this->controllerFactory = $controllerFactory;
        $this->resultExecutor = $resultExecutor;
    }

    public function handleRequest(Request $request) {
        try {
            $route = $this->router->getRoute($request);
            $controllerName = $route->getControllerName();
            $actionName = $route->getActionName();
            $controller = $this->controllerFactory->createController($route->getControllerName());
            $result = $controller->$actionName($route->getParams());

            $this->resultExecutor->executeResult($result);
        }
        catch (Exception $ex) {
            $route = $this->router->getErrorRoute();
            $controller = $this->controllerFactory->createController($route->getControllerName());
            $controller->error($request, $ex);
        }
    }
}

And then just a smidgen of boiler plate code to kick start the process:

$app = new MvcApplication(new UrlRouter(), new ControllerFactory(), new ActionResultExecutor());
$request = new Request($_SESSION, $_SERVER, $_GET, $_POST);
$app->handleRequest($request);

And this doesn't even touch on user input validation, or resolving a view and then rendering it.


Count the number of digits in an integer using F# and log10

Your code contains a bug. What happens if number is 0? log10 0 should  return -Infinity, so we end up with the smallest int plus one. Therefore, we need to check whether input is 0 first:

let digitCount number = if number == 0 then 1 else (int) (log10 ((float)number)) + 1;

At that point we're not really succinct anymore, so there's no harm in using a recursive function instead:

let rec digitCount number = if number < 10 then 1 else 1 + digitCount (number / 10)

However, that's not tail recursive, so we would want to rewrite it using a loop that's tail recursive. That's left as an exercise, though.

That being said, one can optimize counting digit a lot.

Andrei Alexandrescu held a talk about optimizing digits_base_10 in C++ several years ago. The original talk is offline, unfortunately, but the slides are still there.


The first [] case is unnecessary, since break'' already handles empty lists.

g is unnecessary, since f is in scope.

break'' has two nearly identical base cases, which could be combined into one (you may need to use head and tail instead of pattern-matching). That's a line shorter but IMO no clearer.

My previous advice to reverse the accumulator contained a subtle flaw: it needs to find the boundary before it returns anything, so it's not lazy enough. (This is a subtlety of lazy data structures; if you don't understand it yet, don't worry about it.) This occasionally matters in cases like this:

let (a, b) = break (==' ') $ "abc" ++ undefined in head a

The actual implementation avoids this by simply adding x to the result of the recursive call, without using an accumulator:

break _ xs@[]           =  (xs, xs)
break p xs@(x:xs')
           | p x        =  ([],xs)
           | otherwise  =  let (ys,zs) = break p xs' in (x:ys,zs)


Validating a form and alerting the server if passed

Its only a small Quibble with your code but I find the naming of formObj a little odd. For me I see this as a FormValidator or FormExtender or some such.

Another point would be the for(i in ....) should be for(var i in ...) it will run either way and I believe it is just a matter of coding style.

Also you have functions like:

validate: function(theForm, required({....

I think it helps debugging if you do this instead:

validate: function FormValidate(....

It has the disadvantage of polluting the namespace but makes debugging easier as the function is now not anonymous.

If you were making this a class to instantiate you would write it like so:

var FormValidator = function(theForm)
{
    this.formElement = theForm;
    return this;
}

FormValidator.prototype = {

     validate : function(theForm, required) {
            //...
     },
     inputListener : function(theField) {
            //...
     },
     ajaxSubmit : function(formToSubmit) {
            //...
     }

};

var mainForm = new FormValidator(document.forms[0]);

If you were doing a  Singleton pattern something like:

var FormValidator = function()
{
    return this;
}

function GetFormValidatorInstance()
{
    return window.__formValidatorInstance || new FormValidator();
}

These last two are probably overkill if you just want a simple Component. A more in depth example of the above can be found at https://codereview.stackexchange.com/questions/1658/javascript-code-class-structure


Lock-free thread-safe Fibonacci number generator

I have taken this problem on as a little study in to lock efficiency, performance, and contention. As a result, I am posting a second answer with some additional information, and a different sort of review.

Note: The full console output from my harness is here in pastebin.com

First, my conclusion is that lock-free fib generator is a mistake. Reentrant locks are also a problem, and that the best performance comes from plain old synchronization.

So, to test this all, I created a basic interface:

package fibgen;

import java.math.BigInteger;

public interface FibGen extends AutoCloseable {

    /**
     * Get the next Fibonacci number in this sequence
     * @return the next number
     */
    public BigInteger next();

    /**
     * How many retries were needed in spin loops.
     * @return the retry count
     */
    public long retryCount();

    /**
     * because there may need to be some clean up in some generators.
     */
    public void close();

}

Right, that's a tool to generate Fibonacci numbers in a way that is independent of the implementation.

Now, putting your original question code in to that framework, so you can see what I did using a familiar starting point, I got:

package fibgen;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public class FibonacciSequence implements FibGen {

    @Override
    public void close() {
        // nothing
    }

    private static class FibonacciNumber {
        protected final BigInteger prev;
        protected final BigInteger curr;

        public FibonacciNumber(BigInteger prev, BigInteger curr) {
            this.prev = prev;
            this.curr = curr;
        }

        public FibonacciNumber next() {
            return new FibonacciNumber(curr, prev.add(curr));
        }

        public BigInteger value() {
            return curr;
        }
    }

    private static final class FirstFibonacciNumber extends FibonacciNumber {

        public FirstFibonacciNumber() {
            super(null, BigInteger.valueOf(0L));
        }

        public FibonacciNumber next() {
            return new FibonacciNumber(curr, BigInteger.valueOf(1L));
        }

    }

    private final AtomicReference<FibonacciNumber> currentFibNumberRef;
    private final AtomicLong retries = new AtomicLong();

    public FibonacciSequence() {
        currentFibNumberRef = new AtomicReference<>(new FirstFibonacciNumber());
    }

    @Override
    public BigInteger next() {
        while (true) {
            FibonacciNumber currFibNumber = currentFibNumberRef.get();
            if (currentFibNumberRef.compareAndSet(currFibNumber, currFibNumber.next()))
                return currFibNumber.value();
            retries.incrementAndGet();
        }
    }

    @Override
    public long retryCount() {
        return retries.get();
    }

}

OK, now you know how it hangs together, let's look at some of my output. After doing a lot of output, and running on my dual-core-with-hyperthreading laptop, I get the best results from 6 strategies as:

       fibgen.FibGenQueue Retries        0 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=7.632us Calc=0.610us all in 104.814ms
 fibgen.FibonacciSequence Retries    74188 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=5.206us Calc=1.280us all in 91.571ms
        fibgen.FibGenLock Retries        0 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=6.338us Calc=0.551us all in 91.333ms
       fibgen.FibGenRolfl Retries  4451265 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=4.677us Calc=0.618us all in 72.015ms
        fibgen.FibGenSync Retries        0 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=4.695us Calc=0.611us all in 67.888ms

Let me explain the above results, using your generator:

 fibgen.FibonacciSequence Retries    74188 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=5.206us Calc=1.280us all in 91.571ms

Your generator needed to spin-loop almost 75,000 times in order to generate 50,000 values in the sequence. A quality-checking XOR function has some value 212738101 (this is a good thing, I will explain later), and the average latency on the 'next()' call was 5.2 microseconds, the time to calculate the XOR function was an average of 1.3 microseconds, and the whole sequence was completed, in many threads, in 91.5 milliseconds.

Put another way, you ran 4 threads at 100% for 91.5 milliseconds, and you generated 125,000 fibonacci numbers (but only used 50,000).

Note, when I ran your code, I did it 10 times (after warmups), with the following results:

 fibgen.FibonacciSequence Retries    70284 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=7.813us Calc=0.677us all in 132.730ms
 fibgen.FibonacciSequence Retries    88643 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=6.030us Calc=0.695us all in 107.690ms
 fibgen.FibonacciSequence Retries    81224 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=7.501us Calc=0.879us all in 121.851ms
 fibgen.FibonacciSequence Retries    90017 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=7.992us Calc=0.749us all in 113.700ms
 fibgen.FibonacciSequence Retries    89161 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=7.785us Calc=0.964us all in 117.558ms
 fibgen.FibonacciSequence Retries    87775 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=5.022us Calc=0.912us all in 93.947ms
 fibgen.FibonacciSequence Retries    80012 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=6.034us Calc=0.650us all in 105.458ms
 fibgen.FibonacciSequence Retries    71632 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=4.862us Calc=0.640us all in 110.539ms
 fibgen.FibonacciSequence Retries    74188 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=5.206us Calc=1.280us all in 91.571ms
 fibgen.FibonacciSequence Retries   105237 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=6.891us Calc=0.905us all in 103.621ms

Note that the fastest run (91.5ms) has the slowest 'Calc' time. I am not sure why this happened. I believe the variances I see in your code are in part caused by the increased thrashing your algorithm puts on the garbage collector. The other algorithms result in more stable performance.

Compare your fastest time to the alternatives. I suggested one in the answer code I supplied before. In my test framework, it looks like:

package fibgen;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public class FibGenRolfl implements FibGen {

    @Override
    public void close() {
        // Nothing here..
    }

    protected final AtomicReference<BigInteger> nextRef = new AtomicReference<>(BigInteger.ONE);
    protected final AtomicReference<BigInteger> currRef = new AtomicReference<>(BigInteger.ZERO);
    protected final AtomicLong retries = new AtomicLong();

    @Override
    public BigInteger next() {
        BigInteger current = null;
        long tries = -1L;
        do {
            // spin loop while someone else is updating the reference.
            // updating is indicated by a null value in the reference.
            tries++;
            current = currRef.getAndSet(null);
        } while (current == null);
        BigInteger next = nextRef.get();
        nextRef.set(next.add(current));
        currRef.set(next);
        if (tries > 0L) {
            retries.addAndGet(tries);
        }
        return current;
    }

    @Override
    public long retryCount() {
        return retries.get();
    }
}

Now, I claimed this is an improvement over your code, and, is it? It produces the result:

fibgen.FibGenRolfl Retries  4451265 Statistics: 50000 BigIntegers with hashXOR 212738101 - Next=4.677us Calc=0.618us all in 72.015ms

It ran about 25% faster overall than your code. The individual average latency on each next() call is slightly faster at 4.7us (instead of 5.2). The big difference, is that your code calculations are significantly slower, so my code 'spins' a lot faster.... While your code retried 75,000 times, my code retried 4.5million times. The difference is that your code computes and throws-away a fib number, whereas my code uses it as a spin-lock and only computes the fib number when it is free to do so.... hopefully that reduces memory churn... maybe. I create no garbage in my spins, your code makes two objects each wasted cycle.

So, I run all threads at 100%, but I get results slightly faster, on average, and my overall run time is reduced. I believe the imprved latency is because the BigInteger.add operation is relativey slow, and in your code, the 'latency' of each call is in increments of that time. For example, if an add takes 4us, then your code will return in either 4us, 8us, 12us, 16us, etc. My code, on the other hand, can 'delay' for partial amounts of time, and then return after a single 4us calculation.

But, if the partial delay is beneficial, would a blocking system be better than a spin system? Note that your algorithm kept 4 threads busy for 91.5ms, and mine kept threads busy for 72ms. Combined that's 370ms of CPU time vs. 290ms CPU time

I tried using a Reentrant lock instead, with the code:

package fibgen;

import java.math.BigInteger;
import java.util.concurrent.locks.ReentrantLock;

public class FibGenLock implements FibGen {

    @Override
    public void close() {
        // Nothing here..
    }

    private BigInteger nextRef = BigInteger.ONE;
    private BigInteger currRef = BigInteger.ZERO;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public BigInteger next() {
        lock.lock();
        try {
            BigInteger current = currRef;
            currRef = nextRef;
            nextRef = current.add(currRef);
            return current;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public long retryCount() {
        return 0;
    }
}

That code is has about the same latency and overall elapsed time as your code, but, in terms of used CPU time, it blocks all threads except one, so it is 4-times more efficient than your code.

Now, the fastest result was using plain-jane synchronization. I believe it is fastest because there's only one memory-barrier activity (just one synchronization - whereas the Reentrant lock has two - a lock, and an unlock).

Here's the code:

package fibgen;

import java.math.BigInteger;

public class FibGenSync implements FibGen {

    @Override
    public void close() {
        // Nothing here..
    }

    private BigInteger nextRef = BigInteger.ONE;
    private BigInteger currRef = BigInteger.ZERO;

    private final Object lock = new Object();

    @Override
    public BigInteger next() {
        synchronized(lock) {
            BigInteger current = currRef;
            currRef = nextRef;
            nextRef = current.add(currRef);
            return current;
        }
    }

    @Override
    public long retryCount() {
        return 0;
    }
}

Note that this runs in 67ms, and has the same latency as the tight spin-lock mechanism. The major difference is in the fact that it wastes no CPU cycles. It's much more efficient.

That's the best algorithm.

As an aside, I through it would be interesting to try a queue, where one thread feeds Fib numbers in to the queue, and the other threads read it out. It was significantly slower than the alternatives, more complicated, and just generally ugly... here's the code for your reference:

package fibgen;

import java.math.BigInteger;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class FibGenQueue implements FibGen, Runnable {

    private final ArrayBlockingQueue<BigInteger> queue = new ArrayBlockingQueue<>(64);
    private AtomicBoolean active = new AtomicBoolean(true);
    private AtomicLong retries = new AtomicLong();

    public FibGenQueue() {
        Thread t = new Thread(this, "FibGen");
        t.setDaemon(true);
        t.start();
    }

    @Override
    public BigInteger next() {
        try {
            do {
                BigInteger fib = queue.poll(1, TimeUnit.SECONDS);
                if (fib != null) {
                    return fib;
                }
                retries.incrementAndGet();
            } while (active.get());
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        throw new IllegalStateException("Attempt to read from an invalid queue");
    }

    @Override
    public long retryCount() {
        return retries.get();
    }

    @Override
    public void run() {
        BigInteger current = BigInteger.ZERO;
        BigInteger next = BigInteger.ONE;
        try {
            while(true) {
                if (queue.offer(current, 1, TimeUnit.SECONDS)) {
                    BigInteger tmp = next.add(current);
                    current = next;
                    next = tmp;
                } else {
                    if (!active.get()) {
                        return;
                    }
                }

            }
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        } finally {
            queue.clear();
            active.set(false);
        }

    }

    @Override
    public void close() {
        active.set(false);
    }

}

Now, how was this all tested? Using the following framework, and some Java-8 magic:

package fibgen;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FibTester {

    private static final class BigIntCollector {
        private long nextTime = 0L;
        private long calcTime = 0L;
        private long runTime = -1L;
        private int count = 0;
        private int hasXOR = 0;

        public void accumulate(int index, FibGen gen) {
            long start = System.nanoTime();
            BigInteger big = gen.next();
            long next = System.nanoTime();
            hasXOR ^= big.hashCode();
            long done = System.nanoTime();
            nextTime += next - start;
            calcTime += done - next;
            count++;
        }

        public BigIntCollector merge (BigIntCollector toMerge) {
            nextTime += toMerge.nextTime;
            calcTime += toMerge.calcTime;
            count += toMerge.count;
            hasXOR ^= toMerge.hasXOR;
            return this;
        }

        @Override
        public String toString() {
            double factor = (1000.0 * count);
            return String.format("Statistics: %d BigIntegers with hashXOR %d - Next=%.3fus Calc=%.3fus all in %.3fms", count, hasXOR,
                    nextTime / factor, calcTime / factor, runTime / 1000000.0);
        }

        public void runTime(long time) {
            runTime = time;

        }

    }

    public static final String benchmark(Supplier<FibGen> supplier, int volume) {
        long start = System.nanoTime();
        try (FibGen gen = supplier.get()) {

            BigIntCollector coll = IntStream.range(0, volume).parallel()
                .collect(BigIntCollector::new, (c, i) -> c.accumulate(i, gen), (a,b) -> a.merge(b));

            coll.runTime(System.nanoTime() - start);
            return String.format("%25s Retries %8d %s", gen.getClass().getName(), gen.retryCount(), coll.toString());

        }
    }

    public static void main(String[] args) {
        List<Supplier<FibGen>> suppliers = new ArrayList<>();
        suppliers.add(FibonacciSequence::new);
        suppliers.add(FibGenRolfl::new);
        suppliers.add(FibGenQueue::new);
        suppliers.add(FibGenSync::new);
        suppliers.add(FibGenLock::new);
        dump(suppliers, 100);
        for (Supplier<FibGen> supplier : suppliers) {
            System.out.println(benchmark(supplier, 1000));
        }
        for (int i = 0; i < 100; i++) {
            for (Supplier<FibGen> supplier : suppliers) {
                benchmark(supplier, 1000);
            }
        }
        for (Supplier<FibGen> supplier : suppliers) {
            System.out.println();
            for (int i = 0; i < 10; i++) {
                System.out.println(benchmark(supplier, 50000));
            }
        }
    }

    private static void dump(List<Supplier<FibGen>> suppliers, int count) {
        FibGen[] gens = suppliers.stream().map(s -> s.get()).collect(Collectors.toList()).toArray(new FibGen[suppliers.size()]);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= count; i++) {
            sb.setLength(0);
            sb.append(String.format("%5d ", i));
            for (FibGen fg : gens) {
                sb.append(String.format("%20s ", fg.next()));
            }
            System.out.println(sb.toString());
        }

    }

}


Printing the max of groups of three random ints

The first thing about your code are the two lines inside your class Thing:

private Random r = new Random();
private int a = r.nextInt(), b = r.nextInt(), c = r.nextInt();

If Random r is used just to initialize the array and not in other methods inside the class , it is better to use it in the costructor of the class :

public Thing() {
    Random r = new Random();
    this.arr = new int[] {r.nextInt(), r.nextInt(), r.nextInt()};
}

You can check I initialize directy here the array of ints instead of defining variables a, b, c.
A good thing is also override the String method to print the internal state of a object:

@Override
public String toString() {
    return Arrays.toString(arr);
}

Now you can print the state of your Thing object in this way:

for (int i = 0;i < 10; ++i){
    things[i] = new Thing();
    //print 3 numbers in each Thing object
    System.out.println(i + ": " + things[i]);
}

Your iterations with Stream are ok, but instead of use Stream because you are working with int values you can use instead IntStream simplifyng the code:

Stream.of(things).forEach(t -> System.out.println(Arrays.stream(t.getArr()).max().getAsInt()));

Below the code of class Thing including all my modifies:

package codereview;

import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;

public class Thing {

    private int[] arr;

    public Thing() {
        Random r = new Random();
        this.arr = new int[] {r.nextInt(), r.nextInt(), r.nextInt()};
    }

    public int[] getArr() {
        return arr;
    }

    @Override
    public String toString() {
        return Arrays.toString(arr);
    }

    public static void main(String[] args) {
        Thing[] things = new Thing[10];
        for (int i = 0;i <10; ++i){
            things[i] = new Thing();
            //print 3 numbers in each Thing object
            System.out.println(i + ": " + things[i]);
        }
        System.out.println();
        Stream.of(things).forEach(t -> System.out.println(Arrays.stream(t.getArr()).max().getAsInt()));
    }
}


Review
At reading the problem I thought it needed to be a lossless compression algorithm to generate a unique id.
The most basic compression is run length encoding on the bits that make the url. Or a dictionary compression on bit patterns such as Lempel, Ziv, Welch compression  AKA LZW or LZ compression. However there is some storage overhead and for short URLs you will have trouble getting a smaller url than the original.
Random id?
Your solution stores the original url mapped to a random index. There is no need for a compression or even a hash as all you need is a unique id per URL.
To generate an unique id you need only the number line. JS Number can generate 9e15 unique ids, that's a new id every millisecond for the next quarter million years (twice that if you include negatives).
You can also compress the id by converting the id to base 36 (the max base for Number.toString(radix)) thus the longest encoding is "2gosa7pa2gv" and the shortest is "0" and you need store only one 64bit double for the short url.
See Example
Bug?
Your function returns a different short url for the same long url.
Example

Simple index encoding, there is room for lots of optimization in storage.

Produces safe urls using only a-z0-9 to encode.

There is a limit as it does rely on the hashing function (Chance of a clash) of the JS engine.

Checks if a url has already been encoded

You can avoid the JS hash functions (and possible clash), by using an array or set of arrays (if number of urls high) but that comes with a huge CPU cost of locating the URL if the data set is big will require a linear search of the stored urls when encoding. Decoding will still be fast as the encoded url contains the index of the original url
const PREFIX = 'http://tinyurl.com/';
const urls = {
    short: new Map(),  // can be array use id to index
    long: new Map(),   // can be array and use find rather than has and get
    value: 0,
    get id() { return urls.value++ },
};
function encode(url) {
    if (urls.long.has(url)) { return PREFIX + urls.long.get(url).id.toString(36) }
    const urlEntry = { url, id: urls.id };
    urls.long.set(url, urlEntry);
    urls.short.set(urlEntry.id, urlEntry);
    return PREFIX + urlEntry.id.toString(36);
}
function decode(url) {
    return urls.short.get(parseInt(url.split(PREFIX)[1], 36)).url;
}


Check whether an integer's leftmost bits are ones in Rust

The problem is that have the feeling that there must be a much simple solution to this problem.

You're right! Integers in Rust have many useful bitwise operations (as well as other useful ones like wrapping and saturating arithmetic), most of which are exposed as methods on the type. To see the full list, look at the generated documentation for the type, e.g. u128.

Here's a simple way to write is_valid_ipv6_mask:

fn is_valid_ipv6_mask(value: u128) -> bool {
    value.count_zeros() == value.trailing_zeros()
}


Do you really want the properties of DatabaseConfiguration to be settable?

  public string Server { get; set; }

If time is not an issue, I would make the call of each property "lazy":

public string Server => Get<string>("server");


Java Stream wants to return only failure list

Just because you can do it in streams, that doesn't mean you should. What you really want is the following:

public static List<String> deleteDeliveryTemplates(String... deliveryTemplateNames) {
    List<String> failures = new ArrayList<>();
    for (String templateName : deliveryTemplateNames) {
        try {
            deleteDeliveryTemplate(templateName);
        } catch (Exception e) {
            // LOG THIS EXCEPTION!
            failures.add(templateName);
        }
    }
    return failures;
}

This code is clean, simple, does one thing. Note that I removed the overspecification of generics on the right-hand-side of the failureList declaration and changed the names of your local variables a bit to make use of the surrounding context.

I also slightly reformatted the brace positions in try-blocks to be more in line with the usual Java conventions. As long as you're consistent, there's nothing wrong with your style though.


Web API with IoC and database integration tests

I eneded up initializing the database of my tests in the AssemblyInitialize instead of in TestInitialize. This way my database is created once at the beginning of all tests, and after each test it is rolled back to contain only thr content of the Seeding


The interface to quicksort:

quicksort(A, &A[n-1]);

In C I would expect to see a pointer and a size.
In C++ I would expect to see two iterators (like above), but generally the end point is usually one past the end (if you want to be consistent with C++ idioms and the STL way of doing things).

quicksort(A, A+n); // This is what I would expect to see.

Change!
I would normally call this swap()

void change(int *i, int *j)
{
    int temp = *j;
     *j = *i;
     *i = temp;
}

Also in C++ I would pass the values to be swapped by reference. And there is already a std::swap() that works perfectly well.

Your for() loops that do nothing in the body.

for(; *i<=*start && i<=end; i++);

These are hard to read when doing maintenance. At first glance it looks like you accidentally did not indent the code correctly you need to study the code to understand it is correct. I find it best to put an empty body (maybe even with a comment /* Deliberately Empty */

for(; *i<=*start && i<=end; i++)  { /* Empty */ }

In your loops you are testing the loop variable against start and end. Should they not be tested against each other?

while(i<=j)
{
for(; *i<=*start && i<=end; i++);
for(; *j>=*start && start+1<=j; j--);

// Should be:

for(; *i<=*start && i <= j; i++) { /* Empty */ }
for(; *j>=*start && i <= j; j--) { /* Empty */ }

Your quick sort seems to work but is slightly non traditional in a couple of features.

The pivot point *start. Values that are equal seem to go into both sub buckets. Traditionally they would go into a specific bucket.

You always use the first element as the pivot point. This case leads to worst case behavior of quicksort when the list is already sorted. Either choose a random element or the one in the middle of the partition.

Currently your code works with pointers to integers. But really you are using pointers as iterators. So you should templatize it so the inputs are not pointers but are generic iterators this then allows you to use the algorithm on any container type (with the side affect that it works with any type that implements the <= operator.


You could use itertools.takewhile to keep on taking tuples until they are not the same count anymore:

from collections import Counter
from itertools import takewhile

def integer_frequency(integers):
    int_freq = Counter(integers)
    most_common = int_freq.most_common(1)[0]
    return list(takewhile(lambda x: x[1] == most_common[1],
                          int_freq.most_common()))

I also renamed your integer_list to integers, because it can be any iterable of integers.

Alternatively, you could use itertools.groupby to group the tuples by their frequency and return the group with the highest frequency, as @Gareth Reese has suggested in the comments:

from collections import Counter
from itertools import groupby

def integer_frequency(integers):
    return list(next(groupby(Counter(integers).most_common(),
                             key=lambda x: x[1]))[1])

This approach is consistently faster (by a small amount):

However, both beat your algorithm by quite a lot:


You can do it in a more robust way, using expl3.

\documentclass{article}
\usepackage{xparse}
\usepackage{mfirstuc}

\ExplSyntaxOn
\NewDocumentEnvironment{countwords}{+b}
 {
  % typeset the contents and add \par at the end
  #1 \par

  % save the contents of the environment in a token list variable
  \tl_set:Nn \l_tmpa_tl { #1 }
  % blank lines generate a \par, change it into a space
  \tl_replace_all:Nnn \l_tmpa_tl { \par } { ~ }
  % split the token list at spaces
  \seq_set_split:NnV \l_tmpa_seq { ~ } \l_tmpa_tl
  % remove blank items
  \seq_remove_all:Nn \l_tmpa_seq { }
  % print the word count
  Word~count:~\int_to_arabic:n { \seq_count:N \l_tmpa_seq }
 }{}
\ExplSyntaxOff

\begin{document}

\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}

\begin{countwords}
One paragraph.

Another paragraph which is longer.

\end{countwords}

\begin{countwords}
The third paragraph.

I am glad to see this works.
\end{countwords}

\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}

\end{document}


This looks fine to me, but then again it's sample (boilerplate) code ;)

Consider "use strict";
If it was not for the onComplete, you could simply return the result of $.each

I like your options handling, graceful fallback to jQuery, style, it's all good.


These are the things that stuck out to me:

Your copy constructor and move constructor don't result in an identical Property<T1> as they increment the id. Why is that? (There is no documentation anywhere in this that helps the consumer of your Property class.)
Your value constructor Property(T1 value) should probably initialize value with std::move(value). It has already received a copy (perhaps moved), so it is safe to move from value.
Your copy constructor uses what appears to be a superfluous static_cast<T1> and uses the constructor body instead of an initialization list. I would suggest this be more like the move constructor just without the call to std::move.
As nothing appears to change the value of id after it has been constructed, I don't see the benefit of id being atomic. I do understand the value of id_count being atomic, but making them both atomic seems to be asking for unnecessary overhead. Related, perhaps the usage of id_count should be moved to a static function so that it cannot be subverted.

static PropertyID getNextId() {      // assumes PropertyID is non-atomic
    static AtomicPropertyID id = 0;  // and AtomicPropertyID is conditionally atomic
    return id++;
}

I don't quite understand how Property<T1> is expected to be used. Does it go in a collection of properties? Is it used to declare as members of another type? If the former, the implementation of operator< doesn't seem to provide any useful characteristics for finding the right property. If the latter, the encapsulation seems to be a very long winded way of conditionally making a member atomic - since there is no business logic in the setter or getter methods, and no way to provide that other than inheriting, I'm unclear what the benefit is of using this class.


You are working too hard. Java has a Base64 class that does most of the work for you, all you need to do is combine it and the constructor for BigInteger, and you are done.

public static String base16to64(String hex){
    return Base64.getEncoder().encodeToString(new BigInteger(hex, 16).toByteArray());
}

For the linked example input:

  49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d

We get the correct output:

  SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

If you wanted to implement the base 64 conversion yourself, note that you are still doing too much work. Your base16to10 function could be replaced with

BigInteger value = new BigInteger(hex, 16);

One function completely cut out.

However, if you don't want to use BigInteger at all (this is generally a bad idea, but for programming practice, you might want to), notice that log(64)/log(16) == 1.5. Thus, for every 1.5 hex digits, we can obtain 1 base 64 digits.

So take the last 2 hex digits of the hex string: 6d. In binary, this is 01101101. We only need to consider 101101, which is 45. So we take the 45th element of the base 64 alphabet: t. That's the last digit of the base 64 string. Now just shift the hex string over by 6 bits, and repeat (note, shifting by 6 bits won't be clean, so it's probably easier to instead process 3 hex digits to 2 base 64 digits, and take off the last two elements of the hex string).

But noticing the "Cryptopals Rule":

  Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing.

You should probably parse the hex string into a byte[] or ArrayList<Byte> before working on it. Honestly, I think this is way easier to do using BigInteger.


Reduce code handling start and end datepickers

From a once over;

This code does not do what the tin says:

// If selected start date is later than currently selected
// end date, set end date to start date + 1 day
var date = $('#startDate').datepicker('getDate');
if (date) { date.setDate(date.getDate() + 1); }

what this actually does is always set the first possible date to startdate + 1
Not sure about this :)

<option value="2">Any Future Date</option>
<option value="3">Any Future Date</option>

The continued checks for input.id are a good indication that perhaps you need 2 distinct functions
The id's 1 and 2 are rather meaningless, they could be meaningful strings, or even better they could be function names that need to be executed.
There a number of non-sensical assignments like here:

dateMax = null;
if ($('#startDate').datepicker('getDate') != null) { dateMax = null; }

if you set dateMax already to null, then why would you set dateMax again to null?
Your code dies when the user tries to select an end date without first selecting first a starting date in 30 days mode with Cannot read property 'getFullYear' of null because you are indeed trying to calculate on an empty field..
I am not sure why in 30 day mode the start date is impacted by the end date, especially since clearing out the end date opens up the calendar again.

All in all, I would go with something like this:

$('#startDate, #endDate').datepicker({
    beforeShow: setDateRange,
    dateFormat: "mm/dd/yy",
    firstDay: 1,
    changeFirstDay: false,
    onChange: function () {
        $(this).valid();
    }
});

var dateLogic = {

    addDays: function addDays(initialDate, dayCount) {
        var newDate = new Date(initialDate);
        newDate.setDate(newDate.getDate() + dayCount);
        return newDate;
    },
    openWide: {
        minDate: null,
        maxDate: null
    },
    futureDays: {
        startDate: function startDateFutureDays(currentStart, currentEnd) {
            return !currentEnd ? dateLogic.openWide : {
                minDate: null,
                maxDate: dateLogic.addDays(currentEnd, -1)
            }
        },
        endDate: function endDateFutureDays(currentStart) {
            return {
                minDate: currentStart,
                maxDate: null
            }
        }
    },
    thirtyDays: {
        startDate: function startDateThirtyDays(currentStart, currentEnd) {
            return !currentEnd ? dateLogic.openWide : {
                maxDate: currentEnd,
                minDate: dateLogic.addDays(currentEnd, -30)
            };
        },
        endDate: function endDateThirtyDays(currentStart) {
            return !currentStart ? dateLogic.openWide : {
                minDate: currentStart,
                maxDate: dateLogic.addDays(currentStart, 30)
            }
        }
    }
};

function setDateRange(input) {

    var opt = $('#select1'),
        startDate = $('#startDate').datepicker('getDate'),
        endDate = $('#endDate').datepicker('getDate');

    return dateLogic[opt.val()][input.id](startDate, endDate);
}

$('#select1').change(function () {
    $('#startDate, #endDate').val('');
    $('#startDate, #endDate').removeAttr('disabled');
});

You can play with this on http://jsfiddle.net/konijn_gmail_com/rc0kr718/