One things for certain... an array of tuples which is basically being used as a glorified dictionary is never going to suffice as an acceptable data model.  Moreover, an array of bytes isn't really that much useful than what we start with.

So what's clear, we need an actual data model.  So names and data types may need some twiddling, but here's what I started with:

class Information {
    let startTime: UInt32
    let duration: UInt32
    let temperature: UInt16
    let estimatedDistance: UInt16
    let knockCount: UInt8
    let reserved: UInt8

    // TODO: implement initializers
}

This is the model for our data.  This is the easiest way for the entire rest of our app to access the data.  This will be way easier to use.

All that's left is getting from our data packet (<4e5ba256 12190000 22001219 0700>) to an actual instantiated Information object.

I know that we can get from an NSData object to an array of UInt8s, but I notice, we're going to need some UInt16s and some UInt32s.  So, I extended UInt16 and UInt32 to include some constructors for taking an array of bytes:

extension UInt16 {
    init?(bytes: [UInt8]) {
        if bytes.count != 2 {
            return nil
        }

        var value: UInt16 = 0
        for byte in bytes.reverse() {
            value = value << 8
            value = value | UInt16(byte)
        }
        self = value
    }
}

extension UInt32 {
    init?(bytes: [UInt8]) {
        if bytes.count != 4 {
            return nil
        }

        var value: UInt32 = 0
        for byte in bytes.reverse() {
            value = value << 8
            value = value | UInt32(byte)
        }
        self = value
    }
}

If it's not immediately obvious how this is useful, keep reading.  We'll see in a bit.

Now, what do we need to input and what do we need to get in return?  At the end of the day, we need an Information object, which is this class of six variously sized unsigned integers.  What we start with, however, is some raw data.  So ideally, we'd like to simply do something like this:

let myInformation = Information(data: data)

Right?  That'd be nice, eh?

So the end goal is to have an Information initializer which takes an NSData object.

Well, let's start with the simplest initializer for the most ideal case:

init(startTime: UInt32, duration: UInt32, temperature: UInt16, estimatedDistance: UInt16, knockCount: UInt8, reserved: UInt8) {
    self.startTime = startTime
    self.duration = duration
    self.temperature = temperature
    self.estimatedDistance = estimatedDistance
    self.knockCount = knockCount
    self.reserved = reserved
}

If we get the needed values exactly as we need them, we can just directly assign them as such.  This is just a member-wise initializer.

Let's rephrase that initializer in the form of UInt8 (or [UInt8]) though.  This next one will be marked as a failable convenience initializer.

convenience init?(startTimeBytes: [UInt8], durationBytes: [UInt8], temperatureBytes: [UInt8], estimatedDistanceBytes: [UInt8], knockCount: UInt8, reserved: UInt8) {
    if let
        startTime = UInt32(bytes: startTimeBytes),
        duration = UInt32(bytes: durationBytes),
        temperature = UInt16(bytes: temperatureBytes),
        estimatedDistance = UInt16(bytes: estimatedDistanceBytes) {
            self.init(startTime: startTime, duration: duration, temperature: temperature, estimatedDistance: estimatedDistance, knockCount: knockCount, reserved: reserved)
    } else {
        self.init(fail: true)
    }
}

(Don't worry about self.init(faile: true) right now.  I'll paste that implementation in a second.  For now, just note that it's saving me some boilerplate copy-pasta.)

We've got an if let trying to bind four variables using the UInt32 and UInt16 initializers we extended (which of course return optionals).  So if the passed in arrays are of the wrong size, this initializer will return nil, otherwise, it will return us the Information object we need.

So, what's left?  The next step up is the exact initializer that we want... the one that takes the NSData argument:

convenience init?(data: NSData) {
    if data.length == 14 {
        let allBytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
        self.init(startTimeBytes: Array(allBytes[0..<4]), durationBytes: Array(allBytes[4..<8]), temperatureBytes: Array(allBytes[8..<10]), estimatedDistanceBytes: Array(allBytes[10..<12]), knockCount: allBytes[12], reserved: allBytes[13])
    } else {
        self.init(fail: true)
    }
}

We optimize a little bit here by checking the data length (which is also preventing any array index out of bounds exceptions).  And then assuming the data is the right size, we call the previously mentioned convenience initializer.

For the sake of completeness, here's what self.init(fail: true) does:

private init?(fail: Bool = true) {
    self.startTime = 0
    self.duration = 0
    self.temperature = 0
    self.estimatedDistance = 0
    self.knockCount = 0
    self.reserved = 0
    if fail {
        return nil
    }
}

Because of the way Swift initializers work, having this initializer saves us from having to assign every property in every single initializer.  If we know any of our other failable initializers have entered a failure state, we just call this and we're done.

The code, start to finish:

import Foundation

extension UInt16 {
    init?(bytes: [UInt8]) {
        if bytes.count != 2 {
            return nil
        }

        var value: UInt16 = 0
        for byte in bytes.reverse() {
            value = value << 8
            value = value | UInt16(byte)
        }
        self = value
    }
}

extension UInt32 {
    init?(bytes: [UInt8]) {
        if bytes.count != 4 {
            return nil
        }

        var value: UInt32 = 0
        for byte in bytes.reverse() {
            value = value << 8
            value = value | UInt32(byte)
        }
        self = value
    }
}

let bytes: [UInt8] = [0x4e, 0x5b, 0xa2, 0x56, 0x12, 0x19, 0x00, 0x00, 0x22, 0x00, 0x12,0x19, 0x07, 0x00]
let data = NSData(bytes: bytes, length: bytes.count)

class Information {
    let startTime: UInt32
    let duration: UInt32
    let temperature: UInt16
    let estimatedDistance: UInt16
    let knockCount: UInt8
    let reserved: UInt8

    private init?(fail: Bool = true) {
        self.startTime = 0
        self.duration = 0
        self.temperature = 0
        self.estimatedDistance = 0
        self.knockCount = 0
        self.reserved = 0
        if fail {
            return nil
        }
    }

    init(startTime: UInt32, duration: UInt32, temperature: UInt16, estimatedDistance: UInt16, knockCount: UInt8, reserved: UInt8) {
        self.startTime = startTime
        self.duration = duration
        self.temperature = temperature
        self.estimatedDistance = estimatedDistance
        self.knockCount = knockCount
        self.reserved = reserved
    }

    convenience init?(startTimeBytes: [UInt8], durationBytes: [UInt8], temperatureBytes: [UInt8], estimatedDistanceBytes: [UInt8], knockCount: UInt8, reserved: UInt8) {
        if let
            startTime = UInt32(bytes: startTimeBytes),
            duration = UInt32(bytes: durationBytes),
            temperature = UInt16(bytes: temperatureBytes),
            estimatedDistance = UInt16(bytes: estimatedDistanceBytes) {
                self.init(startTime: startTime, duration: duration, temperature: temperature, estimatedDistance: estimatedDistance, knockCount: knockCount, reserved: reserved)
        } else {
            self.init(fail: true)
        }
    }

    convenience init?(data: NSData) {
        if data.length == 14 {
            let allBytes = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(data.bytes), count: data.length))
            self.init(startTimeBytes: Array(allBytes[0..<4]), durationBytes: Array(allBytes[4..<8]), temperatureBytes: Array(allBytes[8..<10]), estimatedDistanceBytes: Array(allBytes[10..<12]), knockCount: allBytes[12], reserved: allBytes[13])
        } else {
            self.init(fail: true)
        }
    }
}

func stringFromTimeInterval(interval:NSTimeInterval) -> String {
    let ti = NSInteger(interval)

    let ms = Int((interval % 1) * 1000)

    let seconds = ti % 60
    let minutes = (ti / 60) % 60
    let hours = (ti / 3600)

    return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms) as String
}

let i = Information(data: data)!
let timestamp = NSDate(timeIntervalSince1970: NSTimeInterval(i.startTime))
let duration = stringFromTimeInterval(NSTimeInterval(i.duration))
let temperature = i.temperature
let estimatedDistance = i.estimatedDistance
let knockCount = i.knockCount
let reserved = i.reserved

And this is the result I get for the given data:


I think the design is pretty good. A few comments:

I'd rename the class to something a bit more descriptive, say RandomGenerator. Then when you implement the class you can declare it with CspGenerator: RandomGenerator or MersenneGenerator: RandomGenerator and it's obvious what the class does.
Comment the get() methods. IMO all public elements should be documented. Get/set could be left out, but that is a matter of preference. In particular I'd like to know what kind of range min anf max is and is used for.
Is getBytes() needed externally? If not, I would consider making it class-level rather than public.

The formatting is good - even in Visual Studio I've seen it get messed up as code is refactored and changed.


Dice rolling program which also counts and stores the result

Roller should not inherit from Dice, as Roller represents a human. Humans being a sub-class of Dice is pretty unintuitive. Rather, Roller should have an attribute: self.dice = Dice()
There's no particular reason Roller.age should be of type str. I'd keep it as an int and only convert to str if you need its string-represantation.
f-Strings are a really convenient tool for creating strings containing variables / expressions. They also handle converting to str for you. Example: print(f'age: {self.age}')
You don't need the empty parantheses in class Dice()
You should put a space after the comma between arguments in a function call: mike = Roller('mike',25) becomes mike = Roller('mike', 25)
roll_multiple should be a method of Dice that can be called by the Roller. This is part of an intuitive API. Users (including yourself) will probably expect to roll the dice, not the human. If you need Roller.roll_multiple, I'd only make it a wrapper for Dice.roll_multiple.
roll_multiple(self, t): t is not a particularly expressive variable name, something like times would be better for readability.
Adding type hints (PEP 484) increases the readability of your code.
It's a convention in Python to name variables, whose values you don't actually use, _. So for i in range(0,t): becomes for _ in range(t):. Notice that you don't need to provide zero as the first argument as it's the default start for range.
Passing sides as a default argument to the constructor of Dice makes the class a whole lot more versatile.

Algorithm
Hardcoding values like
one = 0
two = 0
three = 0
...

should always raise a red flag when writing code. This is neither necessary nor recommended in most situations. You already laid the groundwork by putting Dice.sides in an attribute, now we need to use it. You also don't need to keep a seperate count of the occured values outside of the dict. I implemented it to exactly mirror your functionality (i.e. using string-representations as keys for the dict and only counting numbers that actually occured), inside of class Dice:
from random import randint
from collections import defaultdict
from num2words import num2words

...

def roll(self) -> int:
    return randint(1, self.sides)

def roll_multiple(self, times: int) -> dict:
    count = defaultdict(int)

    for _ in range(times):
        number = self.roll()
        key = num2words(number=number)
        count[key] += 1

    return dict(count)

num2words is a third-party library, that needs to be installed first.
If having keys of type int is fine for your use case, I would recommend using them as they're way more usable for further calculations. You also don't necessarily need to cast to dict, as a defaultdict provides all the same basic functionality. It does make a difference when printing though. Here is the adjusted implementation:
def roll_multiple(self, times: int) -> defaultdict:
    count = defaultdict(int)

    for _ in range(times):
        key = self.roll()
        count[key] += 1

    return count

Suggested code
from random import randint
from collections import defaultdict

class Dice:
    def __init__(self, sides: int = 6):
        """Making a dice instance with a variable number of sides."""
        self.sides = sides

    def roll(self) -> int:
        """Returns the result of a single dice roll."""
        return randint(1, self.sides)

    def roll_multiple(self, times: int) -> defaultdict:
        """Provides the results of a variable number of dice rolls in a defaultdict."""
        count = defaultdict(int)

        for _ in range(times):
            key = self.roll()
            count[key] += 1

        return count

class Roller:
    def __init__(self, name: str, age: int) -> None:
        """Making a Dice Roller Instance"""
        self.name = name
        self.age = age

        self.dice = Dice()

    def describe_roller(self) -> None:
        """Describe the information of the roller"""
        print(f'name: {self.name.title()}')
        print(f'age: {self.age}')

    def roll_multiple(self, times: int) -> None:
        """Roll the dice multiple times and print the result"""
        print(self.dice.roll_multiple(times))


C# Regex to extract bug ID from Bugzilla JSON response

You want to say "any of these characters", so what you want is a character class.

However, if your task is actually to extract a key and value out of JSON, the right tool to use is not a string replacement hack, but a JSON parser.

In this case, the problem with

JsonConvert.DeserializeObject<List<string>>(Json)

… is that you're telling it to parse a key-value pair as a list.  What you want to do is deserialize a dictionary:

JsonConvert.DeserializeObject<Dictionary<string, int>>(Json)

Note that you should check the HTTP status code before trying to process the body of the result.


Speed up script that calculates distribution of every character from user input

Since you are using Counter already, it should be faster to do the whole job with it:

c = Counter()
for i in range(len(df.index.values)):
    c.update(df.ix[i,'input'])

for k, v in c.items():
    print(k, v)


Compiler Options and Warning Checking
It might be a good idea to use the -wall compiler switch. It will provide warning messages that may indicate possible logic errors in some cases. When compiled with -wall this program yields the following warning messages:

D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(89) : warning C4716: 'printBoard': must return a value
D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(104) : warning C4716: 'clear': must return a value
D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(115) : warning C4715: 'freeSpace': not all control paths return a value
D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(133) : warning C4716: 'player': must return a value
D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(142) : warning C4715: 'checkLine': not all control paths return a value
D:\ProjectsNfwsi\CodeReview\tictactoev1\main.c(161) : warning C4716: 'winner': must return a value

In some cases the functions should be declared void rather than int, in other cases there might be a bug when not all control paths return a value, this is certainly true in freeSpace.
Global Variables
Global variables make programs very, very difficult to write, read, debug and maintain. In the C programming language they can cause modules (other .c files) not link if the global variable is declared in multiple modules. Due to the nature of global variables, it is sometimes very difficult to find where they are changed in order to remove a bug.
There is a discussion about global variables in this stackoverflow question
It is much better to pass a variables into functions where they are needed.
Avoid Using exit()
For a number of reasons the use of the exit() function should be avoided. The exit() function should be used when there is a non-recoverable error in a program. Since it is not being used for this purpose in this program it should definitely be avoided. It would be much better if the functions checkLine() and winner() returned values that indicated status.


Is there any more efficient way to code this “2 Sum” Questions

Variables tempA, index1 and index2 seem to be unused.

Since you are only interested in if(j - i > 0){, you can start right there
for (int j  = i + 1; and omit the conditional.

Further the condition if(j < Results[1] || Results.length == 0){ should be flipped around to if(Results.length == 0 || j < Results[1]){ to avoid accessing undefined index.

But actually the variable Results is uselesss because you can return the pair as soon as you find it. Just iterate in the desired directions.

function twoSum(input, targetSum){
  const limit = input.length;
  for(var j = 1; j < limit; ++j){
    var temp = targetSum - input[j];
    for(var i = 0; i < j; ++i){
      if(temp == input[i]){
        return [i + 1, j + 1];
      }
    }
  }
  return [];
}


Optimize a regex validating a version string

Since the second and third segment are similar, you can put them in a non-capturing group with quantifier.

If you allow/want the first digit to be \$ 0 \$ in your first group, the expression is ok as it is. Otherwise, you can restrict the first digit to be [1-9].

You can have + quantifier instead of {1,} as they are essentially the same :)

^[0-9]{2}(?:\.[0-9]{1,2}){2}\.[0-9]+$

and for unpadded version matches:

^[1-9][0-9](?:\.[0-9]{1,2}){2}\.[0-9]+$


Modifying an array during a foreach loop

If you are worried about modifying the array while looping, don't because foreach copies the array. Try

$array = array('foo');
foreach ($array as $k => &$item) {
  $array[] = 'bar';
}
var_dump($array);

And see it terminates just fine. foreach ($array as $k => &$v) is a shorthand for foreach (array_keys($array) as $k) $v = &$array[$k] so while there still is a copy of the array (that's why I used &$item in my example so you can see, if you modify the array then it'll be modified in the reference!

$array = array('foo', 'bar');
foreach ($array as $k => $item) {
  echo "$item\n";
  if (!$k) {
    $array[1] = 'baz';
  }
}
$array = array('foo', 'bar');
foreach ($array as $k => &$item) {
  echo "$item\n";
  if (!$k) {
    $array[1] = 'baz';
  }
}

the first dump foo and bar, the second foo and baz.


Process files in all subdirectories and save output to new files based on their current path

(...) this seems overly verbose, and might contain hidden errors.

This is pretty good as it is.
I cannot think of a substantially shorter and more readable way.
I don't think there are hidden errors either.

  mkdir silently fails if the dir exists, so it'll work for multiple files in the same dir, but maybe this entire script should be done in a loop in order to only call mkdir once per new dir.

mkdir doesn't fail. The -p flag makes it exit with success if the directory already exists, so technically, it succeeds.
It's true that strictly speaking this is not the most optimal way.
It would be ideal to make the script in a way that it doesn't repeatedly call  mkdir -p for the same directory.
But it's just not worth it.
It will make the script more complicated,
for benefit so negligible that probably you cannot even measure it.
Very often, the simplest solution is the best, even it's not 100% optimal in terms of "performance".
If you consider readability and complexity,
then it might actually be optimal overall.

  ${1/data/out} only replaces the first occurence of data, which should always exist and be the outermost directory in the variable (since relative paths are used). I'd prefer it if this was done in a more automatic and safe way though, if possible.

If you always want to replace the first path element with out,
whatever it is, not only data,
then you can write this way:

find data/ -name "*.xml" -exec bash -c \
    'out=out/${1#*/}.xml2; mkdir -p $(dirname "$out"); ./testscript.sh > $out' - {} \;

The output will be the same as in your example,
and will still be the same for find other/ or find blah/.

It might be useful to add the -v flag for the mkdir.
This is for verbose mode,
it will print the directories it creates (if your system supports the -v flag).

Finally, it's probably good to chain the mkdir and the script following it with &&. So that in case you don't have permission to create directories the script doesn't need to run and double the errors printed on the script.

find data/ -name "*.xml" -exec bash -c \
    'out=out/${1#*/}.xml2; mkdir -vp $(dirname "$out") && ./testscript.sh > "$out"' - {} \;

Finally++, as you properly quoted $out in $(dirname "$out"),
you should do the same when redirecting to it: > "$out"


Test_Questions and User_Answers are not necessary since they do not hold any attribution and are one-to-one relationships with Test and User, respectively. It is always suspect when you have a plural table name.

However, the model fails to support the ability of a User to take multiple Tests. To fix that, User.testTaken should be replaced by User.testsTaken and made into a one-to-many relationship with Test.

Also, it seems a bit odd that a Test can only be taken by a single User, but if that's your requirement, then so be it.


Imported data from CSV successfully, but slow

I would try a couple of improvements.

Don't call Location.find_by(code: row[0]) on each iteration. Load all the locations once at the beginning with locations = Location.pluck(:id, :code) and then use origin_location_id = locations.find { |l| l[1] == row[0] }.
Do the same with the other attributes where you need a location: destination_location_id, n1st_pol_id, etc...
Do the same with OceanRoute and ServiceLane
Load the user user = User.find_by(name: 'yo') before the cycle and use it in every iteration: val.created_by = user
Use the fastest implementation of ActiveRecordImport: https://github.com/zdennis/activerecord-import/wiki/Examples#import-using-columns-and-arrays

Do these steps one by one to improve your performance.


Code for finding repeated entries with different data

Your code uses several constructs that have a bit of smell in R.

Foremost is how you write the loop. An immediate replacement would be to replace the repeat with a for(i in seq_len(nrow(project))) (especially the hard coded 394 reeks)

Also you don't need to initialize the variables you will not use outside the loop - that will just prevent them from getting cleaned up after the loop.

A more R like way would be to use some higher level verbs that operate on the whole table. Such as provided by dplyr. Supposing you have something like an id in the lines you would write something like

left_join(project, project, on=c('HOUSE.NO')) %>% filter(id.1<id.2)

such commands are usually easier to read and usually much faster than looping.


Method to generate a List containing permutation of an input string

Before making some general remarks about the C# code, I would like to explain why the complexity of this algorithm is already optimal, even though it is not the standard approach to tackle this problem.

Complexity Analysis

As already stated in a comment, your complexity analysis is way off. The problem is your assumption that the loop over list only multiplies the runtime by the length \$n\$ of the source. However, the list grows each iteration of the outer loop.

How complex is it really?

To determine the real complexity, we have to have a closer look at what happens inside the outer loop. By design, the list will contain all permutations of the first \$(k-1)\$ elements when the \$k^{th}\$ iteration starts. Each element of list has length \$(k-1)\$, accordingly, and there are \$(k-1)!\$ of them. So, in the \$k^{th}\$ iteration, we generate \$((k-1)+1)\cdot(k-1)! = k!\$ new permutations. Since we have to save a new string of length \$k\$ each time, which takes time \$k\$, up to a constant offset and multiplication with a constant, for each iteration we need \$k\cdot k!\$ character operations. This leaves us with a total runtime of \$\sum_{k=1}^nk\cdot k!\$.

It is not really straight forward that this is smaller than a multiple of \$n\cdot n!\$, i.e. that the complexity of the algorithm is \$O(n\cdot n!)\$. As a first step, we can reduce the problem a bit using the fact that \$k\leq n\$.

\$\sum_{k=1}^nk\cdot k! \leq n \cdot \sum_{k=1}^nk! = n \cdot n! \cdot \sum_{k=1}^n\frac{k!}{n!}\$

Now, let us make a convenient approximation for the items in the sum on the rhs, using that \$ \frac{1}{m} \leq \frac{1}{l} \$ for \$ m \geq l \$.

\$ \frac{k!}{n!} = \frac{1}{\prod_{m=k+1}^n m} \leq \frac{1}{\prod_{m=k+1}^n (m-k)} = \frac{1}{\prod_{l=1}^{n-k}l} = \frac{1}{(n-k)!} \$

This approximation allows us to get on the track of the argument used in the complexity analysis of the approach to generate permutations more often used in literature, namely generating all prefixes of permutations of the string of increasing length via recursion.

\$ \sum_{k=1}^n\frac{k!}{n!} \leq \sum_{k=1}^n\frac{1}{(n-k)!} = \sum_{m=0}^{n-1}\frac{1}{m!} \leq \sum_{m=0}^{\infty}\frac{1}{m!} = e\$

In the second equation, we used the the substitution \$m=n-k\$, which turns the summation order around. Moreover, for the last argument, one has to know that the exponential function is defined as function \$e^x = \sum_{n=0}^\infty \frac{x^n}{n!}\$.

The argument about convergence to a constant is similar in nature to that in the analysis of the average insert time into a dynamic array, which is often presented in CS classes. That argument uses a different series, though.

Why is this optimal?

To see that a \$O(n\cdot n!)\$ is optimal is not too hard. We know that there are \$n!\$ many permutations and that we have to generate a string of length \$n\$ for each, which each takes a number of character operations proportional to the length. So, we end up with at least \$n\cdot n!\$ character operations.

General Remarks

To be honest, I cannot find a lot to improve here regarding the coding style. One could separate the contents of the outer loop into a separate private function Permutations(List<string> permutationsOfPrefix, char nextCharacter), but I think it is equally as valid to keep the algorithm contained in one single method, especially since it is not very long. I also do not think that using LINQ here would improve the readability.

One point I think could be improved is there, though, the naming of variables. 'list' is a very generic name. I think permutationsOfPrefix would be more fitting. Accordingly, tempString could be permutation or permutationOfPrefix and beingBuilt could be permutationsWithNextCharacter. That would describe a bit better what is going on. Similarly, the i in the for loop could be named insertionIndex.

Another possible improvement is to explicitly check whether the input string is null or empty at the start, to return an empty list in this case and, otherwise, to initialize list with the first character contained. This would allow to remove the if-else-statement inside the outer loop. However, it would require to iterate over source.Drop(1) in the outer loop.


That's a lot of code indeed, and for all that code it is not very flexible: the "slot" name is fixed, you force multiple inheritance on your users, so they can have only one such type of timer - what if I want one to call processThing() and another to do processOtherThing?

You should use the signal/slot mechanism to your advantage - that's what it is there for, and get rid of your interface and class entirely: a single (global/static) function is enough.

Consider something like this (QTimer::singleShot itself is a good example of how you should be doing it):

void limited_timer(int interval, int duration, QObject *target, const char *slot)
{
  QTimer *timer = new QTimer;
  QObject::connect(timer, SIGNAL(timeout()), target, slot);
  QTimer::singleShot(duration, timer, SLOT(deleteLater()));
  timer->start(interval);
}

Usage (in one of your main window's methods):

limited_timer(100, 2000, this, SLOT(processTimer()));


Round a number and replace trailing zeros by spaces

Apparently, printf already has a feature for padding data to a specific length, see for example https://stackoverflow.com/q/34346389/1201032. So you can do:

f <- function(x, n) {
  rounded_x <- as.character(round(x, n))
  num_lead_chars <- nchar(sub("[.].*", ".", rounded_x))
  sprintf("%-*s", n + num_lead_chars, rounded_x)
}

The function is vectorized for both inputs:

f(c(0.1, 0.1111999, 0.12, 0.1234), n = 4)
# [1] "0.1   " "0.1112" "0.12  " "0.1234"
f(0.1, n = 1:4)
# [1] "0.1"    "0.1 "   "0.1  "  "0.1   "


Dim Hero & Add Background to Nav on scroll

Bearing in mind that you already were able to abstract the functionality of toggling the class name into a separate function, I see other changes that can be made to clean up the code:

Toggle Method: Use the toggle() method of classList to shorten the function changeClass()

function changeClass(offset, clsName) {
    document.body.classList.toggle(clsName, window.scrollY >= offset);
}

DOM access method: Use getElementById() to select the element with Id heroArea instead of querySelector(). While it may likely never be noticeable on a sample page this small, it generally works faster. Check out this Sitepoint forum
and this SO question and its answers (and related posts).
Combined event handlers: The scroll event handlers can be combined to a single function that calls changeClass() twice.

window.addEventListener("scroll", function() {
    changeClass(bottomOfNav, 'fixed-nav');
    changeClass(middleHero, 'dim-hero');
});

Arrow functions: Because ecmascript-6 features like const are used, others like arrow functions could be used for the functions- e.g.

const changeClass = (offset, clsName) =>  document.body.classList.toggle(clsName, window.scrollY >= offset);

Though some would argue that is too long for a single line, so brackets can be used:

const changeClass = (offset, clsName) =>  {
    document.body.classList.toggle(clsName, window.scrollY >= offset);
};

CSS: combine selectors for common styles: I noticed there are two selectors that both have the same background style - those can be combined to a single ruleset:

.fixed-nav nav,
.text-block-two {
  background: #333;
}

The changes have been applied to the sample code below.

const hero = document.getElementById("heroArea");
// Finds the top third of the element by adding the top of the element to the height of the element then divide by 3
const bottomOfNav = hero.offsetHeight / 3;
const middleHero = hero.offsetHeight / 2;
const changeClass = (offset, clsName) =>  document.body.classList.toggle(clsName, window.scrollY >= offset);

window.addEventListener("scroll", function() {
  changeClass(bottomOfNav, 'fixed-nav');
  changeClass(middleHero, 'dim-hero');
});
* {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}

nav {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  color: #fff;
  padding: 15px;
  text-align: center;
  text-transform: uppercase;
  font-family: sans-serif;
  transition: .3s;
}

.fixed-nav nav,
.text-block-two {
  background: #333;
}

.hero {
  height: 100vh;
  background: black;
  opacity: 1;
  transition: .3s;
}

.dim-hero .hero {
  opacity: 0;
}

.text-block {
  height: 50vh;
  background: #555;
  color: #fff;
  font-size: 30px;
  text-align: center;
  padding: 40px;
}

  Navigation

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eos ipsum et, omnis sit vero ab doloremque quia dolores mollitia. Doloremque maxime dolores quo eius ea. Ad, reiciendis minus. Dolorum, hic.


First of all, I object to the get… naming convention.  "Get" implies that you are retrieving something that already exists (usually, though not always, paired with "set").  You wouldn't call Math.getCos(theta), would you?

The problems stem from accepting arrays in the first place.  The class would be much more useful as an accumulator, like this:

Statistics stats = new Statistics();
stats.datum(3);
stats.datum(4);
stats.datum(5);
System.out.println(stats.mean());
System.out.println(stats.stdDev());

A simple way to calculate the mean, variance, and standard deviation is to keep running totals \$\sum x_i^0\$ (i.e., the count), \$\sum x_i^1\$ (i.e., the sum), and \$\sum x_i^2\$ (i.e., the sum of the squares).  However, see Algorithms for calculating variance for a discussion of the merits of this method compared to others.

You could write

import java.util.OptionalDouble;

public class Statistics {
    private int sum0;
    private double sum1, sum2;

    public void datum(double x) {
        this.sum0++;
        this.sum1 += x;
        this.sum2 += x * x;
    }

    public int count() {
        return this.sum0;
    }

    public double sum() {
        return this.sum1;
    }

    public OptionalDouble mean() {
        if (this.count() == 0) {
            return OptionalDouble.empty();
        } else {
            return OptionalDouble.of(this.sum() / this.count());
        }
    }

    public OptionalDouble variance() {
        if (this.count() == 0) {
            return OptionalDouble.empty();
        } else {
            return OptionalDouble.of(
                   (this.sum2 - this.sum() * this.sum() / this.count())
                   / //////////////////////////////////////////////// /
                                     this.count()
            );
        }
    }

    public OptionalDouble stdDev() {
        if (this.count() == 0) {
            return OptionalDouble.empty();
        } else {
            return OptionalDouble.of(Math.sqrt(this.variance().getAsDouble()));
        }
    }
}

The median is trickier to calculate, as you would have to keep a list of all of the values.

Note that DoubleStream already gives you count(), sum(), and average().


Adding order actions like "Print" or "RePrint"

There aren't too many ifs in this code. However, what you can reduce is indentation and it will help readability.

This code:

public async Task AddOrderActionAsync(...)
{
    if (!string.IsNullOrWhiteSpace(value))
    {
        // Everything here
    }
}

Can be rewritten as:

public async Task AddOrderActionAsync(...)
{
    if (string.IsNullOrWhiteSpace(value))
        return;

    // Everything here
}

With the nice side-effect to also remove negation.

Looking into the code you check orderAction != null, it seems you try to be defensive here but it's misleading because it can't be null. Ever. Also orderAction.Count() > 0 is equivalent to orderCount.Any() which is shorter, faster and communicates better the intent. Content of the else clause is repeated then one of them should be dropped:

if (orderAction.Any())
    _context.tbl_OrderActions.RemoveRange(orderAction);

await AddOrderActionAsync(_context, identity, value, order_number);

In your query you're using .ToList() but it's unnecessary and without it EF (or ORM you're using) might be able to optimize database calls (if not then you at least gain in clarity).

It's not a rule but an accepted convention in C# to do not use underscore to separate words, a variable named order_number should be orderNumber.

You're catching a specific exception, nice! However I think it can be thrown only by AddOrderActionAsync() then it should be the only part inside try/catch:

try
{
    await AddOrderActionAsync(_context, identity, value, order_number);
}
catch (AddOrderActionException ex)
{
    // ...
}

Really don't ignore t3chb0t's suggestion about dependency injection, sending e-mails like that it's definitely not something you want to happen inside your unit testing...


Sure, you can use event delegation for this. For the uninitiated, event delegation in JavaScript means attaching the event listener to a container element and using the target property of the event to identify which sub-element was acted upon.

You'll still need to crawl your way up the DOM tree to get to the root element, which can be done without knowing the DOM structure as long as you have a sentinel you can check, such as the root element's class name, to determine whether you've reached the root.

Once you've made it to the top, so to speak, you can use query selectors to find your way back down to specific child nodes within the root element, again allowing you to grab or modify specific elements without knowing the HTML structure--all you'll need to know is a reliably query-selectable combination of attributes (such as an element class).

Here's a working example with comments:

(function() {
  var dropDownClosed = "js-drop-down",
    dropDownButtonList = document.querySelectorAll(".drop-down-wrapper");

  function init() {
    for (var i = 0; i < dropDownButtonList.length; i++) {
      dropDownButtonList[i].addEventListener('click', initDropdown, false);
    }
  }

  function initDropdown(e) {
    e = e || window.event;
    var target = e.target || e.srcElement,
      validElement = false;
    while (!hasClass(target, "drop-down-wrapper")) { /* crawl up the DOM until reaching "root" element */
      target = target.parentNode;
      if (!validElement) { /* track whether user clicked on the open or close buttons */
        if (hasClass(target, "drop-down-open") || hasClass(target, "drop-down-closed")) {
          validElement = true;
        }
      }
    }
    if (validElement) { /* Only toggle content if open/close button was clicked. */
      /* Get the desired content based on its attributes rather than its DOM position: */
      var contentWrapper = target.querySelector(".drop-down-content");
      var content = contentWrapper.querySelector("*");
      var closedButton = target.querySelector(".drop-down-closed");
      var contentHeight = content.offsetHeight;
      if (hasClass(contentWrapper, dropDownClosed)) {
        removeClass(contentWrapper, dropDownClosed);
        contentWrapper.style.height = contentHeight + 'px';
        closedButton.style.opacity = '0.0';
      } else {
        addClass(contentWrapper, dropDownClosed);
        contentWrapper.style.height = 0 + 'px';
        closedButton.style.opacity = '1.0';
      }
    }
  }

  function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  }

  function addClass(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += " " + cls;
  }

  function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
      var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
      ele.className = ele.className.replace(reg, '');
    }
  }

  init();

}());
.drop-down-wrapper {
  position: relative;
  border: 2px black solid;
  margin-bottom: 20px;
  padding: 20px 0;
}
.content-wrapper {
  padding: 15px;
  margin: 30px 0;
}
.drop-down-open {
  position: absolute;
  top: 0;
  border: thin red solid;
}
.drop-down-closed {
  position: absolute;
  top: 0;
  border: 2px solid green;
}
.drop-down-content {
  background-color: #fff;
  overflow: hidden;
  height: 0;
}

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit

I did change your variable named event to target to make it more clear that it represents an element in the DOM tree that we're climbing.

You could improve this further by executing the relevant query selectors at or before the time the event listener is being attached, caching the results so that you don't have to requery the DOM every time an event is triggered.


Class to parse a file sanitizing each line with a set of methods

def __init__(self, **kwargs):

I don't understand why you didn't write def __init__(self, lines=[], file_path='data/data_ts.utf8', entries_count=None)

        __location__ = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))

Better to just name it location. Also, cwd can change between calls to your class, so this code seems "too tricky". Better to have init() nail down a fully qualified pathname once, and store it.

filters = ['_filter_comments',
           '_filter_new_lines',
           '_filter_empty_entries']

It's not obvious why quoting these, and using methodcaller(), is a Good Thing. Why not simply have a list of three function references, rather than three quoted strings?

The contract on each filter is "assign some or all of lines back into lines". Rather than evaluate each filter for side effects, you might have their API return some or all of lines, and make the _sanitize driving loop responsible for assignment. Or better, you might make them functions accepting a single line, that return a single modified line or None to suppress it. When you eventually write unit tests you'll find such an API is simpler to test.

                  if not line.startswith(("#", "#!"))]

If it starts with '#', then we already saw True and won't consider '#!'.

    self.lines = [line.strip('\n') for line in self.lines]

Idiomatic code would say rstrip.

You contemplated putting _sanitize() in the setter property of self.lines. That is feasible, but a bit odd, and would put a greater documentation burden on you, starting with renaming to class SanitizingParser. Perhaps there is some motivating use case where that makes life easier on the caller, but I'm not yet seeing it.

Consider writing generator(s) that yield a line at a time, rather than manipulating the entire list of lines. Then you can process giant files using a small memory footprint.

EDIT: Suppose the three filter functions have an API of accepting a str (not None) and returning that same input line or a trimmed line or None. Then a generator might look like this:

filters = [
    _filter_comments,
    _filter_new_lines,
    _filter_empty_entries,
]

def read_sanitized_file(file_path):
    with io.open(file_path) as fin:
        for line in fin:
            for filter in filters:
                if line:
                    line = filter(line)
            if line:
                yield line


You could validate $option and $country before you put them in a query. One needs to be true or false, and the other should be two letters A-Z. You need some kind of error handling for that.

For the rest: This is such a simple class, and the context is missing, what would you want us to say?


A utility class for running up to two Tasks serially, where the last task to be queued "wins"

I suggest to make m_currentTask non-nullable by replacing usages of null with a completed task. It will simplify the code as you can always await on this field, and assume it is the "current" task running.

You would need to introduce locking in order to synchronize access to the continuation task, and ensure that the taskFunc is only called when it was a winning bid. Also, you would need a double-checked locking to ensure that your task is the winner:

public class LastTaskWins
{
    private readonly object m_pendingToken = new object();
    private Task m_currentTask = Task.FromResult(true); //It will always have a non-null value that you can await on
    private Func<Task> m_nextTaskFunc;

    public async Task<bool> TryRunAsync(Func<Task> taskFunc)
    {
        lock (m_pendingToken)
        {
            //No need in double-checked locking as the last wins
            m_nextTaskFunc = taskFunc;
        }

        // Current task is always present, and may already be completed (in which case await would run synchronously).
        await m_currentTask;

        Task currentTask;

        //Using double-checked locking to make sure we don't have concurrency issues around continuation task, and we only call taskFunc when going to await on it
        if (m_nextTaskFunc != taskFunc)
            return false;

        lock (m_pendingToken)
        {
            if (m_nextTaskFunc != taskFunc)
                return false;

            currentTask = m_currentTask = taskFunc();
            m_nextTaskFunc = null; //just to clean up the reference, as may represent a memory leak otherwise
        }

        await currentTask;
        return true;
    }
}


This is shorter:

import csv

def reformat_ul(original_ul, formated_ul):
    with open(formated_ul, 'w') as output2:
        output2.write('USER,PERM\n')
        with open(original_ul) as user_list:
            dict_reader = csv.DictReader(user_list)
            for row in dict_reader:
                user = row['USER']
                for key in sorted(row)[:-1]:
                    if row[key]:
                        output2.write("%s,%s\n" % (user, row[key]))

reformat_ul('user_list.csv', 'output.txt')

The highlights:

It doesn't waste memory by storing the rows in a temporary list. Using the two nested with there, it outputs while reading the output, piping properly
In sorted(row)[:-1] I take advantage of the fact that I know the column names, and that USER will come after all the PERM1..PERM8. If you need a more flexible implementation then you can amend the deepest if there, for example if key.startswith('PERM') and row[key]


Python Code for List of Month Names starting with current month

Instead of hard-coding month names - delegate all the work to respective libraries.

I would suggest 2 approaches:

calendar.month_abbr

from datetime import datetime
from calendar import month_abbr

def get_forward_month_list():
    month = datetime.now().month   # current month number
    return [month_abbr[(month % 12 + i) or month] for i in range(12)]

dateutil.relativedelta.relativedelta

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

def get_forward_month_list():
    now = datetime.now()
    return [(now + relativedelta(months=i)).strftime('%b') for i in range(12)]

Both approaches will return the expected/needed list of month names:

print(get_forward_month_list())
['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']


python Improve a function in a elegant way

Numpy has built in functions for most simple tasks like this one. In your case, numpy.ndindex should do the trick:

>>> import numpy as np
>>> [j for j in np.ndindex(3, 5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),
 (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

You can get the same result in a similarly compact way using itertools.product :

>>> import itertools
>>> [j for j in itertools.product(xrange(3), xrange(5))]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4),
 (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)]

EDIT Note that the (now corrected) order of the parameters is reversed with respect to the OP's get_IDgrid.

Both expressions above require a list comprehension, because what gets returned is a generator. You may want to consider whether you really need the whole list of index pairs, or if you could consume them one by one.


Election vote-counting, result-posting chatbot

To address your first concern, the way you're doing colors is fine... If you're not running Windows. If you try to use raw ANSI codes like this on windows, you're going to run into some issues. Personally, I'd recommend using the Colorama. It's pretty easy to use. For example, if I wanted to print yellow text with a red background, I'd do this:

from colorama import init, Fore, Back

init()

print(Fore.YELLOW + Back.RED + "Text!")

Secondly, using str.lower on input, isn't really all that hacky, and it's done quite a lot when obtaining user input. In short, it's okay.

Finally, I'm noticing that you're using string concatenation to display variables in a string. The proper way to do this would be to use str.format. Here's how that'd be done:

# Normal str.format without positional or
# named parameters.
print "{} {}".format("Hello", "world")

# str.format with positional parameters (*args)
print "{1} {0}".format("world", "Hello")

# str.format with named parameters (**kwargs)
print "{word1} {word2}".format(word1="Hello", word2="world")


Generate new latitude and longitude in decimal

Bugs
You have a couple of bugs in your code which will crop up occasionally. The first I noticed is this:

// check if the decimal is 9 or 8 we are gointo round up
location = multiply - float64(seconds)
if location > 0.5 {
    seconds += 1
}

There's two things in there, firstly, the comment is a lie ;-) The code does nothing with 8 or 9 decimals... it rounds "half-up".
The second issue is that the rounding is inaccurate if/when the location is something like 59.8, which your code will round-up to 60. This is a problem, because it should round up to 0, and the minutes should be increased (and, worse, if the minutes is 59, you need to round up the degrees... for example, rounding the value 8°59'59.8" should be 9° 0' 0" seconds - but your code gives 8° 59' 60")
Half-up rounding
There's an easy trick for half-up rounding when dealing with integer-casting in programs, the trick is to add a half-unit to the source value before doing any calculations, and then truncating the result as an integer. For example, to half-up round a float value n to an int, you do int(n + 0.5) You can use this in your code quite nicely.
I would also reverse the logic you have in your toDegrees function... convert everything to seconds (half-up rounded in int) and then extract the values from that. Note that you can express the location in total seconds, total minutes, and total degrees, and then get the "remainder" (modulo) to get just the incremental part:
func ToDegree(location float64) LocationDegree {
    // get the location in seconds, rounded up if needed
    seconds := int(location * 60.0 * 60.0 + 0.5)
    minutes := seconds / 60
    degrees := seconds / (60 * 60)

    return LocationDegree{
        Degree:  degree,
        Minutes: minutes % 60,
        Seconds: seconds % 60,
    }
}

Simplified ToDecimal
Similarly, for the ToDecimal function, I would keep most of the calculation in integer space... Your code is not to bad, but can be improved:

func ToDecimal(locationDegree LocationDegree) float64 {
    var result float64
    result = float64(locationDegree.Seconds) / 60.0

    result += float64(locationDegree.Minutes)

    result = result / 60.0

    result += float64(locationDegree.Degree)

    return result
}

I would have it like:
func ToDecimal(locationDegree LocationDegree) float64 {
    totalSeconds := locationDegree.Degree * 60 * 60
    totalSeconds += locationDegree.Minutes * 60
    totalSeconds += locationDegree.Seconds
    return float64(totalSeconds) / (60.0 * 60.0)
}

General issues
Your code relies on the global values lat and lon. These should be declared in a struct, and your methods should be on that struct:
type Position struct {
    Lat float64
    Lon float64
}

func (p Position) RandomLatLong(seconds int) (float64, float64) {
        location := []float64{p.Lat, p.Lon}
    ....
}

Random adjustments
Your code converts the float64 positions to °'" in order to add an adjustment of minutes and seconds. There is no need to do that. Just have the adjustment in the format of a float64 and apply it directly. For example, for the seconds, have:
randomSeconds := float64(rand.Intn(seconds))

and for the minutes have:
randomMinutes := float64(rand.Intn(minutes)) * 60.0

Now you can add those directly to the value


Read in parameters with links from textfile

Rather than creating a series of lists, you should just iterate over the lines of the file directly. You don't need to maintain state between any two lines – just process them as you get them.

A few idioms you should also note:

Use the with open(...) constructions. This ensures the file is always closed, even if the script throws an exception. (Your script never closes the file.)
Rather than using if string.find('='), use if '=' in string.
Rather than using string[(string.find('=')+1):] to get the portion after the equals sign, I think it's neater and more Pythonic to use string.split('=', maxsplit=1)[1]

Here's a version of the script that doesn't use any lists:

import os

with open('C:\\Users\\config.txt') as f:
    for line in f:
        if '=' in line:
            path = line.split('=', maxsplit=1)[1].strip()
            components = path.split('\\')
            print(os.path.join(*components))


Tail-recursive query string builder in F#

As Mauricio suggested:

let ComposeUrl valuePairs =
    if Seq.isEmpty valuePairs then ""
    else
        let values = valuePairs |> Seq.map (fun (k, v) -> sprintf "%s=%s" k v)
        "?" + String.Join("&", values)


How can I improve my Java MethodPointer?

It seams like there is a lot of work going on there for just a simple concept. I suspect you don't need all the flexibility and structure that this implementation gives you. Instead, I suggest you use a simple interfaces. Here is the Function interfaces that Guava uses:

public interface Function<F,T> {
    T apply(F input);
    boolean equals(Object object);
}

All you have to do is implement apply() and you are done. If it is a one off, then you can just create an anonymous class. If you are calling the same type of function repeatedly in a number of places or you need something slightly different, you can make a concrete class for those cases.

The good news is that Java 8 will make this much easier. The introduction of lambdas and method references makes it much easier to pass code to be called into a function. The Method Reference page has examples of lambdas and method references.


Use given digits and operators to generate an expression that yields a requested value

The logic in normalize_input() is a bit bizarre. First, to your credit, you are doing DbC (design by contract) and enforcing a pre-condition. I would rather see the not all test performed immediately upon entry, rather than after computing new_digits. But then your error check raises and immediately catches. Please don't do that. Just use an if instead. Returning an exception to the caller might be better than returning an empty list. If we're going down the type safety route, I guess I'm wondering why a DigitsSequence would let a bad input to sneak in in the first place. I'm a little sad that we need to admit potentially non-numeric str, and can't make that type the output of some validation function.

You wrote "Digits must be an iterable containing strings." where "Digits must be a numeric string." seems more accurate. A different test would have been to assert str(int(digits)) == digits. You're using defensive programming, but it's not clear just who you're defending against.

I'm looking at any_order. I am relatively new to PEP484 annotations. I feel allow_repeats: bool=True completely makes sense, but OTOH length: int=None seems a bit odd, as None clearly doesn't appear on the number line. Would a sentinel of -1 instead of None maybe be a better idiom here? Or should I be viewing this in terms of the java int vs Integer distinction, where potentially we can always have a null object? If None is the appropriate pythonic way to phrase it (definitely true before PEP484), then should we maybe dispense with annotations for that particular parameter?

The specification is fairly clear:

  Each number should be used exactly one time,

therefore I recommend deleting the REPEAT_NUMBERS global, and inverting the allow_repeats default value.

expression = zip_to_str(zip(digits, operators)) + digits[-1]

This is insane. I think you're making the observation that len(digits) = 1 + len(operators), but the code never enforces that. I would much much rather see zip(digits[:-1], operators) and then tack on the last element. Say what you mean and mean what you say.

solver() has a 2nd parameter of solution. For consistency, I would prefer to see Answer have a 2nd parameter of solution.

I have my doubts about DigitsSequence:
(1) maybe it's the sort of thing that offers false assurances, which gives type systems a bad name, or
(2) maybe what we really wanted was to pass in the results of list(map(int, digits)).

I am reading this line:

for operators in any_order(ALLOWED_OPERATORS, length=len(all_digits)-1):

I have no idea why the signature of any_order mentions length: int=None. That makes no sense to me. I recommend no default for that parameter.

I am reading this line:

    for digits_option in any_order(all_digits, allow_repeats=REPEAT_NUMBERS):

It essentially asks for permutations of all_digits. I'm not understanding how digits_option reflects that; it appears to me to be an ill-chosen name. I recommend digit_permutation instead.

It appears to me that Answer is not quite an accurate name - PotentialAnswer or CandidateAnswer seem closer. To retain the current name, we'd have to push the if answer.solution == solution test down into that class.


Adding push to array inside the class that is being pushed

The reason I am asking is that it might not be the responsibility of Person to add himself to the list.

I think you should ask youself a question "Why am I doing this?" Why do you need to keep the @index inside a Person?

Is it just an id? If so why don't you use _.uniqueId('person') from Underscore JS? That would be much cleaner.
Do you use it for ordering so you could for example sort an array of people by it? If so uniqueId would still suit your needs well.
Do you use it to search for person by it's index in the list later on? Basically I can envision two kinds of data processing.

You iterate over a list of people. In this case you'll be fine with Underscore's each method:

_.each people, (person, index) ->
    // your code here     ^----- see that? ;)

You got a person data from some external source and you want to reuse the associated Person object. In this case you should still use an ID and search for your object with find or select methods.

Some notes:

Both your solutions are totally fine if you certain that they don't complicate the code of your application. They also apply in cases when your collection is very large and find takes too much time. BUT you can speed up selection on later invocations:

indexFor = (targetPerson) ->
  unless person.index // we search for index once and then store it for later use
    _.find people, (person, index) ->
      person.index = index if found = (person.id == targetPerson.id)
      found
  targetPerson.index

uniqueId uses internal counter so the ID is always increasing. It cannot be reset which may not be always convenient. For example if you need to save your collection and reload it later you won't be able to tell the generator to increase the counter accordingly. In that case I would still go with uniqueId for presentation code but use some other ID generation scheme for persistence. I would go with UUIDs:  but you can also try timestamps though I wouldn't recommend it since generally time is way too difficult to get right.
You should definitely check out other methods in Underscore library. Whenever you encounter a kind of low-level task you should ask if Underscore does it for you already. If it doesn't check jQuery or whatever library you use for UI. If you're still out of luck ask Google or StackOverflow. I'm sure you're great coder and you can solve many of those tasks yourself but why should you spend your time and effort reinventing stuff instead of creating something new? Know your libraries and use them. It's like a new language or a new text editor - at first it's painful but it pays off later on.


Firstly, the logic of the removeNthFromEnd function can be split into these parts:

calculate length of list
calculate index \$i\$ from the beginning of the list, based on B
remove \$i\$th element from the beginning

1. Calculating the length

def list_len(head):
  length = 0
  while head:
    head = head.next
    length += 1
  return length

2. Calculating index from the beginning of the list

i = list_len(A) - B

3. Removing \$i\$th element

def remove_ith(head, i):

  if i == 0:
    return head.next

  lst = head
  for _ in range(i-1):
    lst = lst.next

  lst.next = lst.next.next

  return head

So your removeNthFromEnd function will look like this:

def remove_nth_from_end(head, n):
  length = list_len(head)
  i = length - n

  if not (0 <= i < length):
    return head

  return remove_ith(head, i)

I took the liberty and renamed removeNthFromEnd to obey PEP8, a Python style guide, according to which function names should be in lower_snake_case.

I also renamed parameters from A, B to head, n. Descriptive names with some meaning are always better than just some random letter, even if it's more typing. However sometimes a letter is enough, such as in case of n or i. Especially if the function name is removeNthFromEnd – one would expect such function takes an argument n.

This basic solution has the same performance disadvantage as your solution – in the worst case, you traverse the list twice.

That's not very efficient, at least not time-wise. So I did a little optimization, which in this case might be considered cheating: I convert the linked list into a list of nodes. That way the linked list is only traversed once and you have constant-time access to all nodes. The disadvantage is of course increased memory usage, which is \$O(n)\$ compared to \$O(1)\$ of your solution, where \$n\$ is the length of the list. Optimally you would use a doubly-linked list. That way you would traverse the list at most once (on average only half of the list would be traversed), and the auxiliary space complexity would be constant, as with your original solution.

def remove_nth_from_end_(head, n):

  as_list = []
  node = head

  # Convert linked list to "array".
  while node:
    as_list.append(node)
    node = node.next

  # Calculate index from beginning.
  i = len(as_list) - n

  # Check that the list is not empty (in which case nothing can be removed)
  # and the index is within the bounds of the list.
  if as_list and i in range(len(as_list)):

    if i == 0:
      # Removing first element – just shift the head.
      head = head.next

    else:
      # Set next-pointer of the previous element to the next element.
      # This is where the constant-time access happens.
      as_list[i-1].next = as_list[i].next

  return head

To further optimize the space complexity, you could only keep the last n+1 elements while traversing the list. That would reduce the auxiliary space complexity to \$O(i_{e})\$, \$i_{e}\$ being the index of the removed element based from the end of the list.


A doubly linked list implementation using C++ smart pointers

This review will focus on ListNode.
ListNode
The constructor takes its argument by copy, whether the argument is a char or a 1'000'000 element std::vector<>. Additionally, there is no exception specification.
Before:
ListNode(T data) : data(data) {}
//                 ^^^^^^^^^^ another copy is made here
//       ^^^^^^ a copy is made here

In order to prevent the first copy, you should pass it as T const&.
Use type traits to add an exception specification.

After:
#include <type_traits> // for the std::is_nothrow_xxx family of template traits

ListNode(T const& data) // the argument is now taken by const&
noexcept(std::is_nothrow_copy_constructible<T>::value) // correct exception specification
    : data(data) // now, only one copy is made: here.
{}

Additional remarks:

Consider adding a constructor that takes a T&& for efficiency.
Consider having only one constructor that directly initializes data by using a variadic template and perfect forwarding.

The std::unique_ptr<> and std::shared_ptr<> types model ownership semantics. Meaning that the smart pointer instance itself owns the memory it points to. In a linked list, the list owns the nodes and their values.
Currently, when ListNode's destructor is called, it will start a recursive chain of calls: freeing a node requires freeing its next data member, which requires freeing the next data member's next data member, and so on.
This is inefficient and limits the number of elements that your list can contain to the recursive limit that your stack allows; it is reason enough to remove ownership semantics by using raw pointers over std::shared_ptr<>.
To deal with this change, you simply define a destructor for LinkedList:
~LinkedList() noexcept(std::is_nothrow_destructible<T>::value)
{
    for (ListNode* current = head, *next; current;)
    {
        next = current->next;
        delete current;
        current = next;
    }
}

Note that this will require you to provide the proper move and copy operations for your LinkedList type by hand as well.

From looking at your declaration (not your implementation), here's some points for:
LinkedList<T>

Provide a size_type alias for your container. Assuming I want to fill the linked list up to its theoretical maximum size, I need to know how many elements it can support. This is determined by the maximum value of the length data type. The only way to guess at its type is by checking GetLength()'s return type.
The Append(), Prepend() and Delete() member functions all take their arguments by copy just like ListNode's old constructor. Consider similar fixes without forgetting to adapt the exception specification according to the operations you do.
Your data members comply with the requirements needed to mark your default constructor as constexpr and as noexcept.
Printing should not be a member function. Instead, provide operator<< as a free function.
As Loki Astari mentioned, consider using sentinel nodes in order to avoid having to check for nullptr values.
Provide an exception specification for non-throwing functions such as GetLength().


Checking whether one string contains all the characters of another string

function scramble(world, seed) {
    var arr = new Array(256);
    var i = 0;

    for (i = 0; i < 256; i++) {
      arr[i] = 0;
    }

    for (i = 0; i < world.length; i++) {
      arr[world.charCodeAt(i)] += 1;
    }

    for (i = 0; i < seed.length; i++) {
      arr[seed.charCodeAt(i)] -= 1;
      if (arr[seed.charCodeAt(i)] < 0) {
        return false;
      }
    }

    return true;
}

console.log(scramble('rkqodlw','world'));
console.log("should be true");

console.log(scramble('cedewaraaossoqqyt','codewars'));
console.log("should be true");

console.log(scramble('katas','steak'));
console.log("should be false");

console.log(scramble('scriptjava','javascript'));
console.log("should be true");

console.log(scramble('scriptingjava','javascript'));
console.log("should be true");

console.log(scramble('jscripts','javascript'));
console.log("should be false");

console.log(scramble('aabbcamaomsccdd','commas'));
console.log("should be true");

Pretty sure it's much faster. As for why, it's about complexity. First a loop of 256 iterations (so nothing), then a loop O(n), then another O(n) loop, where n is the length of either string.

Your code is O(n*n): a loop on the string's length, then the .replace call which is also O(n).

Explanation of the code

Each letter is an ASCII character. ASCII characters have a number representation from 1 to 128 (in the code 256 to be safe).

So I create an array of 256 values, filling it with zeros. Then I count the letters in the first string: increasing the count for the corresponding letter by one. I get the number representation of the letter with .charCodeAt.

Then, for the second string, I decrease the count of each letter by 1 as I encounter the characters. If I end up with a negative number, it means there was more of said letter in the second string than in the first string, and I return false.

The end result is a much faster algorithm.

To be fair, anyone doing C or C++ would come up with this solution.

Another solution

Another solution, less efficient but still meeting the speed criterion I assume, using objects:

function scramble(world, seed) {
    var obj = {};
    var i = 0;

    for (i = 0; i < world.length; i++) {
      arr[world[i]] = (arr[world[i]] || 0) + 1;
    }

    for (i = 0; i < seed.length; i++) {
      arr[seed[i]] = (arr[seed[i]] || 0 ) - 1;
      if (arr[seed[i]] < 0) {
        return false;
      }
    }

    return true;
}

It's another way of doing things even if you don't know the concept of number representation for letters.


Calculating the results of bit operations

private static int a;
private static int b;
private static byte byteOperation;
private static short int16Operation;
private static int int32Operation;
private static long int64Operation;

That whole chunk of static instance fields should be passed around as parameters.

They're only static so that you can use them from static context. static is like plague, a virus; it creeps and expands its tentacles across your entire code base if you let it.

Since this is just a learning exercise, I'll let it slip this time and won't say a thing about all the static methods being called from Main. But the fields shouldn't exist.

Now this is confusing:

bool numberA = int.TryParse(Console.ReadLine(), out a);
bool numberB = int.TryParse(Console.ReadLine(), out b);

numberA and numberB are Boolean variables, but if you don't pay attention, it's very easy - WAY too easy, to glance at the code and think they're numbers... that's what their names say!

if (!numberA || !numberB) Console.WriteLine("Input can be only numbers !");
else

That's a very confusing and dangerous way to write conditional code. Always use braces around scopes. - this would be much, much, much clearer and less error-prone:

 if (!numberA || !numberB)
 {
     Console.WriteLine("Input can be only numbers !");
 }
 else

What you really need, is a separate method that gets the two numbers and only returns once you have valid input. You also need a way to break out of the loop and sanely quit the program! How many concerns is that? How many methods should it be written with?

private static Tuple<int,int> PromptForTwoNumbers()
{
    var value1 = PromptForValidNumber();
    if (value1 == null)
    {
        return null;
    }

    var value2 = PromptForValidNumber();
    if (value2 == null)
    {
        return null;
    }

    return Tuple.Create(value1, value2);
}

private static int? PromptForValidNumber()
{
    while (true)
    {
        Console.WriteLine("Please enter a number:");

        int value;
        var input = Console.ReadLine();
        if (IsUserTiredOfThis(input))
        {
            return null;
        }

        if (int.TryParse(input, out value))
        {
            return value;
        }

        Console.WriteLine("Input must be a number!");
    }
}

private static bool IsUserTiredOfThis(string input)
{
    return string.IsNullOrEmpty(input) || input == "quit"
}

Now, all xxxxOperation variables are misnamed. They're not operations, they're results.

Your WriteLine method is also confusing: until you get to the actual implementation, there's no way of telling that method is going to actually be writing 7 lines to the console.

The way you're writing is awkward:

    Console.WriteLine("Byte : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 8 - {1}" + " = {2}", a, b, byteOperation);
    Console.WriteLine("Int16 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 16 - {1}" + " = {2}", a, b, int16Operation);
    Console.WriteLine("Int32 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 32 - {1}" + " = {2}", a, b, int32Operation);
    Console.WriteLine("Int64 : {0} " + ch1 + " {1} " + ch2 + " {0} " + ch3 + " 64 - {1}" + " = {2}", a, b, int32Operation);

Don't mix string-formatting and + concatenations. And name things for Pete's sake! "ch2" rings like "channel 2" in my mind, and tells me nothing about what that thing is supposed to be.

Your Int64 stuff is operating on Int32's. In fact, none of your operations are operating with the types they're claiming to be:

byteOperation = (byte) (a | b);

Should be:

byteResult = (byte)((byte)a | (byte)b); // yuck!

You're just working off Int32's and casting the result to a given type. Which means... you're probably missing an unchecked scope around these operations to let them overflow without blowing everything up.

Or was overflowing your "clean way out" of the app?


How can I refactor this oversized Ruby method into smaller bits and have unit tests for them?

Create a model to hold all the logic and call that with parameters and have tests for the model methods:

  Unit Tests

require 'spec_helper'

describe "Prepare Search methods" do

  describe "PrepareSearch#start_date" do

    subject { PrepareSearch.start_date('2000') }
    it { should == DateTime.new(2000,1,1) }

  end

  describe "PrepareSearch#end_date" do

    subject { PrepareSearch.end_date('2009') }
    it { should == DateTime.new(2009,12,31) }

  end

  describe "PrepareSearch#groups" do

    subject { PrepareSearch.groups(['1','2','3']) }
    it { should == " and group_id in (-1,1,2,3)" }

  end

  describe "PrepareSearch#versions" do

    before(:each) do
      @versions= {:version => 0, :version_comparison => '>=', :include_blank_version => true}
    end
    subject { PrepareSearch.versions(@versions) }
    it { should == " and (version_number >= 0.0 or version_number is NULL or version_number = '' )" }

  end

  describe "PrepareSearch#dates" do

    subject { PrepareSearch.dates(Date.new(2009), Date.new(2012) ) }
    it { should == " and ((content_date is NULL) or( (content_date >= \"2009-01-01\") and (content_date <= \"2012-01-01\") ) )" }

  end

  describe "PrepareSearch#basic_search" do

    subject { PrepareSearch.basic_search("test") }
    it { should == ["(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)","%test%","%test%","%test%"] }

  end

  describe "PrepareSearch#text_search" do

    subject { PrepareSearch.text_search("tests","or","rs") }
    it { should == " and ( (url_address LIKE \"%tests%\" or alt_text LIKE \"%tests%\" or version_number LIKE \"%tests%\") or (url_address LIKE \"%rs%\" or alt_text LIKE \"%rs%\" or version_number LIKE \"%rs%\") )" }

  end

end

  New Model "PrepareSearch"

class PrepareSearch

  def self.start_date(start_year)
    (start_year + '/01/01').to_date
  end

  def self.end_date(end_year)
    (end_year + '/12/31').to_date
  end

  def self.groups(groups=[])
    @groups_comparison= ' and group_id in (-1'
    groups.each do |group_id|
      @groups_comparison << ','+group_id
    end
    @groups_comparison+= ')'
  end

  def self.versions(version_information={} )
    @version = version_information[:version].to_f
    @version_comparison = ' and (version_number ' + version_information[:version_comparison] + ' ' + @version.to_s
    if version_information[:include_blank_version]
      @version_comparison+= " or version_number is NULL or version_number = '' )"
    else
      @version_comparison+= " and version_number is not NULL and version_number <> '' )"
    end
  end

  def self.dates(from, to)
    @from= from
    @to= to
     ' and ((content_date is NULL) or( (content_date >= "' + @from.to_s + '") and (content_date <= "' + @to.to_s + '") ) )'
  end

  def self.text_search(words_1,comparison_operator='',words_2='')
    @words_1 = words_1
    @words_2 = words_2
    @comparison_operator= comparison_operator
    if @words_2.length > 0
      @text_search = ' and ( (url_address LIKE "%'+@words_1+'%" or alt_text LIKE "%'+@words_1+'%" or version_number LIKE "%'+@words_1+'%") '
      @text_search+= @comparison_operator
      @text_search+= ' (url_address LIKE "%'+@words_2+'%" or alt_text LIKE "%'+@words_2+'%" or version_number LIKE "%'+@words_2+'%") )'
    else
      ' and (url_address LIKE "%'+@words_1+'%" or alt_text LIKE "%'+@words_1+'%" or version_number LIKE "%'+@words_1+'%")'
    end
  end

  def self.basic_search(words)
    @words = words
    @conditions = ['(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)', "%"+@words+"%", "%"+@words+"%", "%"+@words+"%"]
  end

end

  Refactored index action

  def index
    @from = PrepareSearch.start_date(params[:from] ||= '1991')
    @to = PrepareSearch.end_date(params[:to] ||= '2299')

    if params[:search_text_1st_phrase] # both simple and advanced search use this field.
      @words_1 = params[:search_text_1st_phrase]
      if params[:commit].downcase == 'advanced search'
        @join_operator = params[:join_operator].downcase
        @words_2 = params[:search_text_2nd_phrase]
        @text_search = PrepareSearch.text_search(@words_1, @join_operator, @words_2)
        @groups_comparison = PrepareSearch.groups(params[:groups])
        @version_information = { :version => params[:version], :version_comparison => params[:version_comparison], :include_blank_version => params[:include_blank_version] }
        @version_comparison = PrepareSearch.versions(@version_information)
        @date_comparison = PrepareSearch.dates(@from, @to)
        @conditions = '1=1' + @groups_comparison+ @version_comparison+ @date_comparison + @text_search
      else
        @conditions = PrepareSearch.basic_search(@words_1)
      end
    else
      @conditions = ''
    end
    @links = Link.all(:joins => :group, :include => :group, :order => 'groups.group_name, links.position', :conditions => @conditions)
    session[:full_details] = (params[:full_details] == 'true') ? 'true' : 'false' rescue 'false'
    respond_to do |format|
      format.html
    end
  end

Also (next steps):

Write controller/integration tests to check actual search results for various combinations of parameters.  Needs a bunch of test data.  Probably at least 20 links and 4 groups for useful testing data.
consider making an object for all the params and passing them to one method call.


Calculate query coverage from BLAST output

One serious bug is that you open results.txt for each line of input.  It's almost always better to open files in a with block.  Then, you won't have to worry about closing your filehandles, even if the code exits abnormally.  The with block would have made your results.txt mistake obvious as well.

Since you want to treat your q_start, q_end, and q_len as numbers, I wouldn't even bother to assign their string representations to a variable.  Just convert them to a float as soon as possible.  Similarly, q_cov should be a float; I would just stringify it at the last moment.  I would also postpone rounding just for the purposes of formatting the output, preferring to preserve precision in q_cov itself.

Put your import statements at the beginning of the program.

import re

with open('file.txt') as input, open('results.txt', 'a') as output:
    for line in input.readlines():
        fields = re.split(r'\t+', line.strip())
        q_start, q_end, q_len = map(float, (fields[0], fields[1], fields[3]))
        q_cov = 100 * (q_end - q_start) / q_len
        print >>output, '\t'.join(fields + [str(round(q_cov, 1))])


Outputting the names of cars, without repetitions, with the number of occurrences in order of decreasing repetitions

Problems I see:
My problem with your code is that you are newing a lot of stuff that should just be objects.
map<string, int> *lines = new map<string, int>();
multimap<int, string> *lines_by_count = new multimap<int, string>();

Both of these should just be plain objects.
map<string, int>        lines;
multimap<int, string>   lines_by_count;

This one fact would have caused you to be rejected. I would have seen this and I would not have read any-further into your code straight onto the reject pile. This fundamental flaw in your style shows that you are not a C++ programmer.
Next the objects you new are stored in RAW pointers. This is a dead give away that you are not an experienced C++ programmer. There should practically never be any pointers in your code. (All pointers should be managed by an object). Even though you manually do delete these two it is not done in an exception safe way (so they can still potentially leak).
You are reading a file incorrectly.
while (in.good())
{
    getline(in, tmp);

This is the standard anti-pattern for reading a file (even in C). The problem with your version is that the last successful read will read upto but not past the EOF. Thus the state of the file is still good but there is now no content left. So you re-enter the loop and the first read operation getline() will then fail. Even though it can fail you do not test for that.
I would expect to see this:
while (getline(in, tmp))
{
    // Line read successfully
    // Now I can processes it
}

Next you are showing a fundamental misunderstanding of how maps work:
    if (lines.count(tmp) == 0)
    {
        lines[tmp] = 0;
    }
    lines[tmp]++;

If you use the operator[] on a map it always returns a reference to an internal value. This means if the value does not exist one will be inserted. So there is no need to do this check. Just increment the value. If it is not their a value will be inserted and initialized for you (thus integers will be zero). Though not a big problem its usually preferable to use pre-increment. (For those that are going to say it does not matter. On integer types it does not matter. But you have to plan fro the future where somebody may change the type to a class object. This way you future proof your code against change and maintenance problems. So prefer pre-increment).
You are doing extra work you don't need to:
// trim initial space (also skips empty strings)
for (i = 0; i < tmp.length() && !isalnum(tmp[i]); i++);

The streams library already discards spaces when used correctly. Also the ';' at the end of the for. This is considered bad practice. It is really hard to spot and any maintainer is going to ask did he really mean that. When you have an empty body it is always best to use the {} and put a comment in their  {/*Deliberately empty*/}
Here you are basically lower casing the string.
    for (i = 0; i < tmp.length(); i++)
    {
        if (!isalnum(tmp[i]))
        {
            tmp[i] = ' ';
        }

You could use the C++ algorithms library to do stuff like this:
std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower());
                           //                       ^^^^^^^^^^^ or a custom
                           //                        functor to do the task

Const correctness.
void reorg_by_count(map<string, int> &lines, multimap<int, string> &bycount)

The parameter lines is not mutated by the function nor should it be. I would expect it to be passed as a const reference as part of the documentation of the function that you are not going to mutate it. This also helps in future maintenance as it stops people from accidentally mutating the object in a way that later code would not expect.
My final thing is I did not see any encapsulation of the concept of a car. You treated it all as lines of text. If you had invented a car object you can define how cars are read from a stream and written to a stream etc. Thus you encapsulate the concept in a single location.
I would have done something like this:
Probably still overkill.
#include <algorithm>
#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <cctype>

class Car
{
    public:
        bool operator<(Car const& rhs) const {return name < rhs.name;}
        friend std::istream& operator>>(std::istream& stream, Car& self)
        {
            std::string   line;
            std::getline(stream, line);

            std::stringstream linestream(line);
            linestream >> self.name;  // This strips white space

            // Lowercase the name
            std::transform(self.name.begin(), self.name.end(), self.name.begin(), ::tolower);
            // Uppercase first letter because most are proper nouns
            self.name[0] = ::toupper(self.name[0]);
            return stream;
        }
        friend std::ostream& operator<<(std::ostream& stream, Car const& self)
        {
            return stream << self.name << "\n";
        }
    private:
        std::string   name;
};

int main(int argc, char* argv[])
{
    if (argc < 2)
    {    exit(1);
    }
    std::ifstream      cars(argv[1]);
    std::map<Car,int>  count;

    Car  nextCar;
    while(cars >> nextCar)
    {
        ++count[nextCar];
    }

    // PS deliberately left the sorting by inverse order as an exercise.
    for(auto const& car: count) {
        std::cout << car.first << ":   " << car.second << "\n";
    }
}


Generating non-repeating random integers in a fixed range

Any simple generator whose output is equivalent to its internal state will generate a non-repeating sequence. In fact, most will generate a permutation of the range [0, P) where P is the length of the period. Or [1, P), if state == 0 is forbidden.

Pick any simple generator with period P ≥ 2,704,000 and Bob's your uncle.

The simplest is the Golden Weyl generator (the 'Golden' is my moniker for it):

x = (x + 0x9E3779B9u) mod 2^32

The net has a wide choice of suitable Linear Congruential Generators (LCGs) of the form

x = (a * x + c) mod 2^32

Julienne Walker has written a brilliant explanation of LCGs, and the Weyl generators are just a special case with multiplier 1.

However, regardless of which type of generator you choose, its period P is likely to be too long.

Extracting a shorter non-repeating sequence of values [0,M) from a longer sequence of non-repeating values [0,P) is not trivial. In particular, if you map the [0,P) values to the [0,M) range in some fashion - e.g. by scaling, or by computing the remainder modulo M - then you lose the property of non-repetition. Stuffing P values into a smaller number M of pigeon holes means that some values must end up in the same hole.

One strategy that works well is rejection: inspect the generator output and if you don't like the value for some reason, throw it away and call the generator again. This method is perfect for generating even the most outlandish output distributions, in the sense that it does not introduce any bias at all and it leaves properties like non-repetition intact. The downside is that you have to do more work if a lot of stuff gets thrown away.

The trick, then, is to pick a non-repeating generator whose period length is as close to M = 2,704,000 as possible, and then use rejection with that.

LCGs modulo powers of 2 have the special property that any lower k bits cycle with period 2^k. I.e., the lowest bit is strictly alternating, the low 2 bits cycle with period 4, and so on. This means that these generators can be reduced modulo any power of 2 without losing the property of non-repetition. In other words, any LCG modulo 2^x is also a generator modulo 2^k for all k that are less than x. These subsequences can be extracted by throwing away (masking off) the unwanted higher bits.

The first power of two that is not less than the modulus M = 2,704,000 is 2^22. Masking with 2^22 - 1 = 0x3FFFFF we only have to reject the 35% of outputs that are in the range [M,2^22). This means the generator will have to be cycled 1.55 times on average for each good value in the range [0,M). That's less than two MULs for a non-repeating random value with an off-beat modulus.

Simple and effective.

An example for a suitable generator of higher quality (where the lower bits do not cycle with their own lower periods) is a 22-bit Tausworthe. Think of it as a single barrel of the four-barrelled lfsr113 that powers games like Dragon Age, whose long-awaited newest chapter is due to be released in a few hours.

x = (((x ^ (x << 1)) & 0x3FFFFF) >> (22 - 17)) ^ (x << 17);

return (x & 0x3FFFFF) - 1;

This generator has period 2^22 - 1 because 0 is a forbidden (sticky) state, hence the decrement after masking the output. The rejection method is then essentially the same as above.

I wrote (22 - 17) because the 17 corresponds to parameter s in the usual descriptions of the algorithm (and 22 equals k). Other possible choices for s are here: 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 19 and 20. The algorithm is usually described in a way that makes the 'live' k bits sit at the upper end of the larger x:

x = ((x ^ (x << q)) >> (k - s)) ^ ((x & m) << s);

I took the liberty of shifting the whole shebang down to the lower end, so that the live bits can be extracted with simple masking. The output sequence is the same.


Tic Tac Toe Program: Are there any ways to make this code more readable?

There are a couple easy gains to be had.

Python Version

Use Python 3. Python 2 is end-of-life as of 2020-01-01.
In Python 3,

# -*- coding: utf-8 -*-

is no longer needed: Python 3 is UTF-8 by default.

Python 3.6 introduced f-strings, where the syntax is:

x = 3
text = f"You have {x} items!"

Much clearer and shorter than the .format() syntax.
The % string formatting syntax should not be used at all anymore.
f-strings are also fast.

PEP8

PEP 8 is a collection of style guidelines. It is highly recommended to make use of them, otherwise other Python developers will never stop reminding you. Use an editor that can format or at least warn you automatically. For this, look into tools like Pylint or black.

PEP8 examples relevant to your example:

global variables are all UPPERCASE
commas generally have trailing spaces: ["X", "O"]

Another note (not part of PEP8) is that I highly prefer double quotes (") over single-quotes (').
This is because empty strings (your code has them) can be confusing with the latter style (''), whereas they are impossible to confuse with double quotes ("").

Function attributes

Functions attributes are

def func(x):
    func.y = 3

That is, objects attached to the function object and accessible via dot notation, among other things. I don't think (and hope) that they are not part of any introductory books. Probably better to avoid them completely, especially when just starting. Thus, your display_board function would become (with PEP8-formatting through black):

def display_board(board):
    """
    Takes the board list as an argument
    and displays it as a Tic-Tac-Toe board
    when the game is running

    """

    row3 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[7], board[8], board[9])
    row2 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[4], board[5], board[6])
    row1 = "{0:^5s}||{1:^5s}||{2:^5s}".format(board[1], board[2], board[3])
    spaces = "{0:5s}||{1:5s}||{2:5s}".format("", "", "")
    board = [row3, row2, row1]

    for row in board[:2]:
        print(spaces + "\n" + row + "\n" + spaces)
        print("=" * 20)
    print(spaces + "\n" + row1 + "\n" + spaces)

Much better and clearer!

Function attributes can introduce a nasty state.
This is definitely not what a function should do.
For a given input, the return should always be the same.
Functions can have side effects, but the return value should be perfectly predictable, i.e. deterministic.
But using function attributes, this principle can be violated (snipet uses ipython):

In [1]: def func(x):
   ...:     return func.y + x
   ...:

In [2]: func.y = 3

In [3]: func(2)
Out[3]: 5

In [4]: func.y = 5

In [5]: func(2)
Out[5]: 7

It is clear how func(2) should always return the same thing (whatever that may be).
If states are required, that is you need an object that "remembers", use classes and their version of functions, methods.

Bare try/except

Never leave an except statement naked, that is:

try:
    position = int(input("Choose your next position: (1-9)\n"))
    break
except:
    print('Invalid input. Try again!')

Should be:

try:
    position = int(input("Choose your next position: (1-9)\n"))
    break
except ValueError:
    print('Invalid input. Try again!')

since you only try to catch the failed conversion to int for invalid input.
In trying out your game, the except also caught KeyboardInterrupt, which is hugely confusing to the user. There has to be a way to exit the game anytime.

Specifying a specific exception (can also be multiple, separated by commas) is much clearer, easier to understand and your program will actually break when something unexpected (unexcepted?) happens. This is what you want to handle such cases properly. It is poor practice if you try to catch a specific exception to handle it, but also catch another, unrelated one and handle that case also, but of course entirely wrong. This is unpredictable behavior that will be hard to debug.


Your indentation is consistent, but non-standard. Someone else inheriting that code might not be bothered with lining up all the end-of-line comments in the same column, and if their editor sets indent spaces to 4 instead of 2 they're likely going to turn it into a bit of a mess.
Unless they're using Smart Indenter or Rubberduck to automate the indentation. If you are not using a tool to achieve that indentation, then you're wasting your time lining up all these comments.
But are they good comments worth keeping around?

Comments are supposed to make plain what the code does not tell us already.

Good code seldom needs comments.

Good comments say why, not what.

https://codereview.stackexchange.com/a/90113/23788

From what I can see, every single comment is merely rephrasing the code and brings absolutely nothing to the table. If I were maintaining that code, I'd wipe them all out. All of them.
There are a number of other issues with the code:

Set rFind = sheet.Cells.Find("Index", [H2], xlValues, xlWhole, xlByColumns, xlNext)

[H2] is evaluated off the active worksheet, which may not be the sheet that's being iterated. That makes the .Find call hard to parse, and makes me wonder if it works as it should. In 15 years I've never ever needed to use a bracketed expression anywhere. I'd replace it with sheet.Range("H2") to be safe.
I like that your Public members are explicitly public - because by default they're implicitly so. I also like that you're passing your parameters ByVal - especially since the default in VBA is an implicit ByRef.
iRow As Integer is potentially problematic: an Integer is a 16-bit signed integer type with a maximum value of 32,767... and an Excel worksheet can have many times more rows than that. Regardless of how many rows you think you need or can possibly deal with, you should always use Long instead of Integer, at least when referring to sheet rows.
I like how you used sheet as an identifier for a Worksheet object. I'm not sure what the r is doing in rRange, or what i does in iRow, or the s in sCol. These prefixes are an incarnation of the bad kind of Hungarian Notation and should be killed with fire.

iRow As Integer could be destinationRowIndex As Long if that's its purpose (not clear from the posted code). Notice iRow As Long defeats the Hungarian prefix, and lRow As Long uses a lowercase l which can easily be confused for an 1 in the VBE's default font... which is uselessly confusing, since legal identifiers can't start with a digit in VBA.
sCol As String could be destinationColumnHeading As String again if that's its purpose. Note that the distinction between Index and Heading reveals an implementation detail of your PostNumbers procedure; you're definitely using them to concatenate some Range address. Why not give it a single Range parameter then?
rFind As Range could be findResult As Range. At least it wasn't an oRange... although, oranges are tasty ;-)

Note, these are suggestions - I'm not saying destinationColumnHeading is the ideal name to use here. What I am saying, is that an identifier should convey its purpose, not its type. The IDE tells you what the type is already.

I agree with your refactoring. What you've done here is called extracting a method, and it's a very good way to eliminate redundancies in code. Redundant code is bad for several reasons; the DRY (Don't Repeat Yourself) principle exists to remind us that it's always better to have one single place to make a change, than having multiple places to fix in order to make the same change - and run the risk of forgetting one and introducing bugs, as Victor's answer points out.
IMO, macros (procedures attached to some worksheet button) should be tiny little things, so I like what I'm seeing with these two one-liners that call a lower-abstraction procedure.


How to reduce code in hash created using Database and Params in rails

Not sure if it's what you're looking for, in terms of readability:
data = User.where(id: sample_params.pluck(:user_id))
           .pluck(:department_id, :id).group_by {|u| u.shift }

results = data.map do |department_id, user_ids|
  users = user_ids.flatten.map do |id|
    email = sample_params.find { |user| user[:user_id] == id }[:email]
    {user_id: id, email: email}
  end
  { department_id: department_id, users: users }
end

About saving memory because of the array, there will be always the queried data to the db in memory, besides this new array you're generating. The garbage collector won't take care of all these until your http request has been finished, so I'm not sure if there's something here you can do to improve the use of space.
If this is the case where there are thousands of users mapped to this json, maybe you should consider to use .find_each, maybe caching data or another approach, but only you know what's the nature of the data you're querying.