Transform byte array into upside down array of floating point pixels

Would numpy be a potentially good avenue for optimization?

Yes. In general, pushing python loops into C extensions often makes sense.

You might prefer to start the timer after pix = [], since you're not focused on improving fromstring's performance.

There's nothing obviously slow, beyond bulk data movement and regrouping, and it would take changing the problem if you wanted to introduce a level of indirection to avoid that work. One could hoist the stride constant out of the loop, but that's pretty far down the list of worries.


Adjusting all depth data in a file by some elevation

Minor issues

You have some minor funny business going on:

Repurposing f in writing_TS() makes the code harder to follow:

with open(f, 'r') as f:

In writing_TS(), you do

TS.append(x)

… where you are modifying TS, which is a global variable.  But then you return TS as well, which makes it pointless to communicate via a global variable.
On the other hand, you also have a global variable ND, which is initially an empty list, but becomes a float, but you actually want it to be an int.  But why bother initializing n = 0 at all?

Performance

Your ELEVATION.dat is a small file, and your DEPTH.dat is a huge file.  So don't process DEPTH.dat twice!  You want to run through DEPTH.dat linearly, in a single pass.

When performance is a problem, just keep it as simple as possible.  The core of the solution should "ideally" resemble this:

with open('DEPTH.dat') as depth, open('OUTPUT.dat', 'w') as out:
    for line in depth:
        out.write(line)

Of course, that doesn't do anything useful — it just copies the file line by line.  But it gives you the outline of the code to strive for, and it also establishes a lower bound on the running time.  (Try it.  If you aren't satisfied with the performance, then you know that your task cannot be accomplished satisfactorily using Python.)

With that in mind, how can we modify the skeleton to actually do the work?  I would make two assumptions:

DEPTH.dat consists of repeated blocks resembling the structure of ELEVATION.dat.
The lines of DEPTH.dat should be copied verbatim, except the numeric lines, which should be summed with their counterpart in ELEVATION.dat.

Here is how I would express those two ideas in code:

import itertools

def read_elevation(filename):
    """
    Read elevation data.  Lines in the file that consist only of a float are
    converted to a float; all other lines are preserved.
    """
    def try_parse_float(line):
        try:
            return float(line)
        except ValueError:
            return line

    with open(filename) as f:
        return [try_parse_float(line) for line in f]

elevation_cycle = itertools.cycle(read_elevation('ELEVATION_LHP.dat'))
with open('DEPTH.dat') as depth, \
     open('OUTPUT.dat', 'w') as out:
    for depth_line, elev in zip(depth, elevation_cycle):
        if isinstance(elev, float):
            print(elev + float(depth_line), file=out)
        else:
            out.write(depth_line)

This is simpler than your original code, in that I'm not trying as hard to "make sense" of the data by parsing ND.  It's not assuming that there are four header lines per group, namely SCALAR, ND, ST, and TS.  There isn't even any grouping involved: it just blindly assumes that DEPTH.dat contains many repetitions of blocks resembling ELEVATION.dat.


Overview

I see that there are some good comments and I thought I'd just explain in a full answer block -- I'm not on here too often so I apologize for the tardiness of the response.  Bear with me as I first show you what I might really do then demonstrate the answer to your tail recursive question using the same terms with which you posed your question.

What I Would Do

First, I think you are asking how to add up the numbers 1,2,3,...,x.

I would actually use the Enum.reduce function:

1..20 |> Enum.reduce(0, fn(x,acc) -> acc + x end)

or using Elixir capture syntax which is more concise and obtuse:

1..20 |> Enum.reduce(0, &(&1 + &2))

The Main Question

Now to the crux of your actual question, how would I do this without using Enum and using tail recursion.  First note that the last entry in the function call will be the function itself.  There must be no other add, sub, multiply, -- operation of any kind before or after the function call.  You can change the parameters but don't do anything outside call itself.

Here is a simple tail recursive routine that adds numbers up:

defmodule MyInteger do
  def sum_to_x(0, acc) do
    acc
  end

  # initial function call
  def sum_to_x(x, acc) do
    sum_to_x(x - 1, acc + x)
  end
end

IO.puts MyInteger.sum_to_x(20, 0)

I wrote this counting down to make it like your example.  When you first call MyInteger.sum_to_x(20, 0) the second form of the sum_to_x function is used.  We pass 0 as the initial value of the accumulator. The last line in that function calls itself and nothing else (tail recursive).  That is when the function finally "returns" there are no other ops to do.  This function will call itself counting x down until x is zero.  When is is zero, we match the first form of the function since we have a "0" in the first parameter.  This form just returns the accumulated result --

uDude


Transforming lists of products to boolean vectors

1. Review

Just reviewing approach 2.

Even if you have a good reason to be using Python 2.7, it is worth noting that the Python developers plan to end support for this version in 2020 and so it is a good idea to get into the habit of writing code that will be easy to port to Python 3 should you have to take that step.

In this case it would be easy for you to start the program with

from __future__ import print_function

and then use the print function instead of the print statement. (But we'll see later that we don't even need the print function since we can use the csv module instead.)
If a script has hard-coded filenames like 'bigtest.csv' then you have to edit it every time you want to run it on files with different names. The script would be more reusable if it took the filenames from the command line.
It looks as though the input is supposed to be in CSV format. But the input is parsed like this:

data = (line[:-1].split(',') for line in inp)
for line_number, products in enumerate(data):

This doesn't take into account the full details of the CSV format: in particular, fields can be quoted, and quoted fields can contain commas. Python has a built-in csv module that handles the CSV format. This allows you to write the input loop like this:

reader = csv.reader(inp)
for line_number, products in enumerate(reader):

Instead of lambda:set(), you can just write set! Computer scientists call this η-conversion.
The variable name index does not clearly indicate what it contains. The value of this variable is a mapping from a product name to the set of line numbers on which that product appears, so I would call it something like product_lines.
The expression

1 if line in index[product] else 0

can be written more simply as

int(line in index[product])

since False converts to int as 0 and True as 1.
Using the csv module as discussed above, the output loop can be written like this:

writerow = csv.writer(out).writerow
writerow(header)
for line in range(line_number + 1):
    writerow([int(line in index[product]) for product in header])

The rewritten code still looks up index[product] for every product on every row. These lookups can be avoided by constructing the header list so that it contains the sets of line numbers as well as the product names:

header = sorted(index.items(), key=lambda p:len(p[1]), reverse=True)

and then:

writerow = csv.writer(out).writerow
writerow([product for product, _ in header])
for line in range(line_number + 1):
    writerow([int(line in lines) for _, lines in header])

2. Revised code

from collections import defaultdict
import csv
import sys

def main(in_filename='bigtest.csv', out_filename='formal0.csv'):
    """Read lists of products from the CSV file in_filename, convert them
    to Boolean vectors of products, and write the results to out_filename.

    """
    # Mapping from product to set of line numbers on which it appears.
    product_lines = defaultdict(set)

    with open(in_filename) as in_file:
        reader = csv.reader(in_file)
        for line_number, products in enumerate(reader):
            for product in products:
                product_lines[product].add(line_number)

    # List of pairs (products, lines) in reverse order by len(lines)
    header = sorted(product_lines.items(), key=lambda p:len(p[1]), reverse=True)

    with open(out_filename, 'w') as out_file:
        writerow = csv.writer(out_file).writerow
        writerow([product for product, _ in header])
        for line in range(line_number + 1):
            writerow([int(line in lines) for _, lines in header])

if __name__ == '__main__':
    main(*sys.argv[1:])


Am I on the right track with this random number array?

Just a little detail, to kick off: you're not declaring $products as an array anywhere. PHP will create a new variable, and assign it an empty array for you, true enough, but if you change your ini settings to E_STRICT | E_ALL, you'll notice that it doesn't do this without complaining about it.
It's always better to declare and initialize your variables beforehand. writing $products = array(); isn't hard, nor is it very costly. At any rate it's less costly than producing a notice.

Anyway, about your actual code: There is room to make your code more efficient way, so let's look at it piecce by piece:

function randomnumber(){
    $randomnumber = mt_rand(1, 10);
    return $randomnumber;
}

This function is just calling mt_rand, and returning the result. But only after the return value of mt_rand has been assigned to a local variable. That's just wasteful. Look at it from a machine's standpoint:

randomnumber();//call <name:randomnumber>
  \\
   \==> lookup function in memory, goto, and start
   $randomnumber = mt_rand(1,10);
     \\                   \\
      \=> allocate memory  \=> lookup function, pass 2 arguments & call
        ||     /\                                                 //
        ||     ||=======then, assign return valueof: =============/
        ||
        \== return COPY of assigned value
            then flag $randomnumber for GC (Garbage Collection)

That's just a hell of a lot of work, for a simple call to mt_rand. You can easily omit the allocation and garbage collection steps by changing the randomnumber function to this:

function randomnumber()
{
    return mt_rand(1,10);
}

This does exactly the same thing, without the overhead of an assignment. Still, a function call that just calls another function is a bit silly. If anything, it's an alias to an existing function, with default params. But you're still returning a copy of the return value of the core function (mt_rand). Just ditch the function, and in-line mt_rand(1,10);
If you insist, keep the alias, but define default arguments:

function randomnumber($from = 1, $to = 10)
{
    $from = (int) $from;//make sure we're dealing with ints
    $to = (int) $to;
    if ($from > $to)
    {//check order of params
        $tmp = $from;
        $from = $to;
        $to = $tmp;
    }
    return mt_rand($from, $to);
}
randomnumber();//returns mt_rand(1,10)
randomnumber(10,20);//returns mt_rand(10,20)
randomnumber(200);//returns mt_rand(10, 200)
randomnumber(null, 5);//returns mt_rand(0,5)

But that's only of any use if you're going to use this alias function throughout, and don't want to bother passing those 2 arguments all the time, or (in case of passign variables) you're not sure what they might contain (null, 'a string', (float) '0.123',...).
But we're drifting off topic. Next, the array-constructing loop:

//Creates array.
//Checks to see if the random number is greater than 1
//Adds an 's' to the entry if greater than one
for ($i = 0; $i < 10; $i++){
        $rannum = randomnumber();
        if ($rannum > 1){
            $adds = "s";
        }else{
            $adds = "";
        }
        $products[$i] = $rannum." car".$adds;
}

This isn't too bad, really, just remove the function-call, and you're good, and perhaps shorten the if-else to a ternary or a single if-statement. you could argue that assigning the random number to a variable isn't really necessairy. You're using $i as an array-key, so you could assign the value to the array directly, and check the value there

for($i=0;$i<10;$i++)
{
    $products[$i] = mt_rand(1,10);//$i is the key, so we don't need any other vars
    $products[$i] .= 'car '.($products[$i] > 1 ? 's' : '');
}
//without ternary:
for($i=0;$i<10;$i++)
{
    $products[$i] = mt_rand(1,10).' car';//just concat car already
    if ($products[$i] > 1)
    {//comparing to int will cast $products[$i] to int
     //since the string starts with an int, it'll compare that int
     //'4 car' > 1 ~~> 4 > 1 ~~> true ==> '4 car' .= s ===> 4 cars
        $products[$i] .= 's';
    }
}

Then, the output loop:

//Outputs the final array.
foreach ($products as $current){
    echo $current."
";
}

Ok, that's perfectly valid code, too, but wouldn't it be a lot shorter just writing this:

echo implode('
', $products);

This turns an array into a string, and separates all values with a
. To add another break at the end (and/or beginning) of this string:

echo '
', implode('
', $products), '
';

I use this all the time if I want to dump a quick
 to the screen:

echo '

', implode('

', $array), '

';

So, your code ends up looking like:

for($i=0;$i<10;$i++)
{
    $products[$i] = mt_rand(1,10);//$i is the key, so we don't need any other vars
    $products[$i] .= 'car '.($products[$i] > 1 ? 's' : '')
}
echo implode('
', $products);

Or, if regexes don't scare you and you like some unmaintainable code, you could even do this:

$arr = array();
$i=0;
while($i++<10)
{
    $arr[] = mt_rand(1,10);
}
echo preg_replace('/(([2-9]+|10)\s+car)(?!s)/','$1s',implode(' car
',$arr).' car');

But that's just terrible code to maintain...

If the array you're echo-ing isn't of any use to you except for your printing it out, you could just as well drop the array:

for($i=0, $j=mt_rand(1,10);$i<10;$i++, $j=mt_rand(1,10))
{
    echo $j, ' car', $j > 1 ? 's' : '', '
';
}

Which, if you're a massochist, you can turn into a one-liner quite easily:

for($i=0, $j=mt_rand(1,10);$i<10;$i++, $j=mt_rand(1,10))  echo $j, ' car', $j > 1 ? 's' : '', '
';

As you can see, I'm using $i to count the number of iterations, while at the same time $j is (re-)assigned a new random value upon each iteration, too.
Using multiple variables in a for-loop construct is most commonly done to avoid calling count too much when for-looping a numerically indexed array:

for($i=0, $j = count($array); $i<$j;$i++)
{
    var_dump($array[$i]);
}

instead of:

for($i=0;$i<count($array);$i++)
{
    var_dump($array[$i]);
}

Both of the loops above behave in the same way (provided $array doesn't change inside the loop), but the first one is more performant, because, as you probably know, after each iteration the conditional expression (ie $i<$j or $i<count($array)) is evaluated. In the second case, this means the length of $array will be counted time and time again, whereas in the first case, this is only done once.


Is this quicksort efficient and acceptable?

Those are pure functions that don't access any instance variables.  You can therefore make them static.

You could use generics more generically.  Your code should work with any List, as long as it supports an efficient .get(i) for arbitrary i.  The elements of the list can be any kind of Comparable object.

The .sort() function should have a void return type to avoid giving the false impression that it returns a copy of the original array.

private static <E extends Comparable<E>, L extends List<E> & RandomAccess>
void sort(L ar, int lo, int hi) {
    if (lo < hi) {
        int splitPoint = partition(ar, lo, hi);
        sort(ar, lo, splitPoint);
        sort(ar, splitPoint +1, hi);
    }
}

private static <E extends Comparable<E>, L extends List<E> & RandomAccess>
int partition(L ar, int lo, int hi){
    E pivot = ar.get(lo);
    lo--;
    hi++;
    while (true){
        lo++;
        while (lo<hi && ar.get(lo).compareTo(pivot) < 0){
            lo++;
        }
        hi--;
        while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){
            hi--;
        }
        if (lo<hi){
            swap(ar, lo, hi);
        }else {
            return hi;
        }
    }
}

private static <E extends Comparable<E>, L extends List<E> & RandomAccess>
void swap(L ar, int a, int b){
    E temp = ar.get(a);
    ar.set(a, ar.get(b));
    ar.set(b, temp);
}


First of all, you have provided very little context for your code. Therefore, my criticism may not be valid in the context of your full program.

Second, you have not a single comment in your code. One can argue that code does not need comments once it is self-documenting. But your code does not achieve that.

Your method does not use any variables defined outside of your function. This shows that

… it should be marked as static – it clearly does not operate on an instance of the class where this function is defined.
… Static methods can be an indication that your code is not object oriented. It may need to be redesigned.
… You do operate on an object: List<Standalone>. Maybe that should be a class of its own, and this method be an instance method over there.

printHeadOfNonIntersectingLinkedList is far to long as a name. I know that Java code has the tendency to prefer such long names, but you are not doing anyone a favour with that. In addition:

The name does not match the behaviour of the method. Doesn't it print the heads belonging to unique tails of linked lists? The lists itself may intersect.
The name tells us that this method is doing too many unrelated things. It needs to be refactored. The different parts are: finding the tails of all lists, deduplicating the nodes, and printing them out.

List<Standalone> – why not Iterable<Standalone>? There is no need to be extra specific, and all we do is call an implicit .iterator() on it.
+1 for using final, although you could designate the loop variables as final as well.
tailHeads is a confusing name. seenTails might be better.
ll is a bad name. Avoid short names, especially abbreviations. Exceptions to this rule are integer loop variables (i, j, …) and domain-specific code where not using common abbreviations would be more confusing. Examples would be highly mathematical (e.g. cryptographic) code. In this case, linkedList could be a better choice.
Finding the last element in a list is an implementation detail, and should be encapsulated in the Standalone class – it doesn't seem to be very “standalone” after all. If you didn't write that class: Subclass it and implement these helpers there.

final Node tail = linkedList.tail();

The next part makes a lot of sense, and can't be written any better. But it is crucial to use comments to tell a reader what you are doing here:

// If that tail is already known, mark it as seen,
// but unwanted with a null.
if (seenTails.containsKey(tail)) {
    seenTails.put(tail, null);
} ...

Using .entrySet() is a bit akward, considering that you are only interested in the values. Why not for (final Node head : seenTails.values()) { ... }?
Let another method do the printing – just return a collection or iterator of the values of each head, and be done with it.

Here is my take on making that code more self-documenting, heeding some of my above criticism. Untested.

class Standalone {
  private Node head;  // proper encapsulation
  private NodeValue element;
  ...

  public Node head() {
    return head;
  }

  // you might want to cache this
  public Node tail() {
    // handle zero-length lists
    if (head == null)
      return null;

    // find and return last element
    Node pointer = head;
    while (pointer.next != null)
      pointer = pointer.next;
    return pointer;
  }

  public NodeValue element() {
    return element;
  }

  public static Iterable<Standalone> withUniqueTails(Iterable<Standalone> standaloneCollection) {
    final HashMap<Node, Standalone> uniqueTails = new HashMap<Node, Node>();
    final HashSet<Node>             duplicates  = new HashSet<Node>();

    for (final Standalone list : standaloneCollection) {
      final Node tail = list.tail();
      if (duplicates.contains(tail)
        continue;
      if (uniqueTails.containsKey(tail)) {
        uniqueTails.remove(tail);
        duplicates.add(tail);
      } else {
        uniqueTails.put(tail, list)
      }
    }

    return uniqueTails.values();
  }
}

Calling code could be like

for(final Standalone standalone : Standalone.withUniqueTails(someStandalones)) {
  System.out.println(standalone.head().element());
}

Do you notice something? The method is actually just a filter that skips over some values (we could lift this kind of code to all kinds of iterator transformation strategies). And this is the only thing my version of that method does. If you need a wrapper that extracts the head values, you can write it, without having to concern yourself with filtering out unwanted values.

If you need a helper that prints out each element in some iterable one line at a time, you can write that too. Make it private to reduce the shame.

private static <T> void printCollection(OutputStream stream, Iterable<T> collection) {
  for(final T item : collection)
    stream.println(item);
}

Update:

Programming is a game of tradeoffs. We can optimize along axes of readability, theoretical elegance, memory usage, speed, and sometimes other resources like network requests. If in doubt, it is advisable to optimize for readability.

In my suggested rewrite, I introduced duplicates mostly in order to make the code more self-documenting: If a duplicate node is detected, then it is literally removed from the unique nodes, and added to the duplicates. I avoided the (otherwise completely legitimate) use of null as a special value.  This intends to make the code simpler to understand.

We can estimate the performance characteristics of introducing another data structure.

Space

First, memory usage. The worst case scenario is that our input data is unique throughout the first half of the input, then repeats one or more times: A, B, C, ..., Z, A, B, C, ..., Z, where the number of elements n is chosen in a way that it forces a resizing of the hash table.

After that code has been filtered, we find zero elements in uniqueTails, because all were duplicates. That data structure has capacity for (n-1)*2 elements (hash table size is doubled when a certain load factor is reached). We have n elements in duplicates, which also has size for (n-1)*2 elements. Thus in the worst case, we have allocated 2× as much memory as neccessary. But if one of those elements is unique, we can avoid the table size doubling in duplicates, thus using only 1.5× as much memory. If the duplicates are adjacent (A, A, B, B), then the uniqeTails never grow (best case scenario).

Depending on the exact numbers of unique duplicate elements, the acceptable load factor, and the longest streak of unique elements, we can get anything from 1× to 2× the memory usage (plus overhead), but will rather stay at the lower end of that range. I consider this acceptable for most scenarios.

Time

The addition of another data structure comes at the cost of more recalculations of the hash. The hash code must be calculated for contains, containsKey, remove, add, put. Per element, a 1–4 calculations can occur in my code. Your original code does this in always exactly 2 calculations. Only when a key occurs more than eight times, less recalculations occur.

Summary: My code will quite certainly perform worse – but it was never tuned for performance. By all means, use tricks like null pointers as special values to express an extra level of information. But if you do so, document it with a comment (you'll note that I did exactly that in the main part of my review).


Don't use std::uint_fast*_t
The performance gain of these types is minimal. If you really need to squeeze out the last bits of performance, it might help, but only if:

These types are actually different from the regular std::uint*_t
Implicit casts and integer promotions don't change the actual type used

The drawback is that the type names get very verbose. Also, can a std::uint_fast64_t actually hold an unsigned long long? The latter might very well be 128 bits long.
I suggest you stick with (unsigned) int when dealing with numbers that don't grow large (for example, for counting bits), size_t when you need to support arbitratily large counts, sizes and array indices, and other types as appropriate, such as unsigned long long to store the results of std::stoull().
Also use a using declaration to declare the type used to store the numbers in one place, so if you ever decide to change it, you don't have to search and replace all over the code. You can combine it with decltype() to get the type returned by an arbitrary function, like so:
class Solution {
    using value_type = decltype(std::stoull(""));
    ...
};

Avoid unnecessary one-use temporaries
There are several cases where you define a temporary variable that is only used once, and which could be avoided. The first is x, which is only used to create a constant 1 of the right type. You can do that instead like so:
if ((value_type{1} << bit) < num) {
    ...
}

The second one will still technically create a temporary, but we can use C++17's if with an init statement:
if (auto curr = binarySearch(num, bit); curr) {
    return curr;
}

When passing an integer type to std::pow(), it will convert it to double for you, so you don't have to explcitly create a temporary constant dnum, and can just write:
value_type hi = std::pow(num, 1.0 / bit) + 1;

Note that you also don't need to explicitly cast it back to an integer here.


Computing the RPY tensor with C++/Eigen (linear algebra)

Using p + 1 instead of just p

You declare

const int p = 4000;

but use p+1 at all the places that matter. I think you should just use

const int p = 4001;

and replace all usages of p + 1 by just p.

Simplify a few expressions

You have repeated usage of 3 * ( i + 1) - 3 and 3 * ( j + 1) - 3. They can simply be 3*i and 3*j.

Give some computations a name

You have the following expressions:

0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose()

0.75 * distance_ratio * (1.0 + 2.0 / 3.0 * distance_ratio * distance_ratio)

3.0 / 32.0 / distance_ratio * rvec*rvec.transpose()

1.0 - 9.0 / 32.0 / distance_ratio

I don't know that they compute but they compute four different things. It will be easier to understand your code if you can give those computations a name and put them in a function.

double firstTerm(double distance_ratio,
                 Vector3d const& rvec)
{
   return (0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose());
}

and use it

   rpy.block<3, 3>(3*i, 3*j) = firstTerm(distanc_ratio, recv);

PS I am not suggesting firstTerm as a function name. It just illustrates the concept.

Avoid multiple statements in one line

The line

    coords[i](0) = dis(gen); coords[i](1) = dis(gen); coords[i](2) = dis(gen);

is less readable than:

    coords[i](0) = dis(gen);
    coords[i](1) = dis(gen);
    coords[i](2) = dis(gen);

You could also put them in a for loop to avoid code repetition.

 for ( int j = 0; i < 3; ++j )
    coords[i](j) = dis(gen);

Using const int as an argument type`

I am not a fan of using const int as an argument type. Just int works without any problem. YMMV.

The sqrt line

        Rij = sqrt(rvec(0)*rvec(0) + rvec(1)*rvec(1) + rvec(2)*rvec(2));

can be modified to

double square(double in)
{
    return in*in;
}

Rij = sqrt(square(rvec(0)) + square(rvec(1)) + square(rvec(2));

I think this not only avoids code repetition but also uses the right abstraction in the computation.


"Hello, world!" program using a class for printing

In addition to the other comments, I would also use a different naming convention for types and objects.

For example, this looks unconventional.

Print Obj;
Obj.print_();

I prefer:

Print obj;
obj.print();

It's just a convention but being able to easily spot names that denote types helps if you start to use more complex expressions. For example:

Print().print();

Personally, I would also avoid system("pause"). You need to #include either <stdlib.h> or <cstdlib> to use it. Although the system call itself is standard C++ (from the standard C library), what you pass to it is system dependent.

In general I don't believe you should make your programs stop artificially. If they are designed to run in a terminal then the terminal user will be able to see the output even after the program exits.


Writing a general purpose "split" function (for SICP's imaginary language)

In order to test it, you need to have definitions for things like beside and below. There's something strange in the text book code because the painter "smaller" is not actually scaled in the code, or is it indicated that "below" and "beside" scale their arguments? Anyway, you can just define

  (define (below a b) `(below ,a, b))
  (define (beside a b) `(beside ,a ,b))

so e.g. (right-split 'apple 1) should produce as result

  '(beside apple (below apple apple))

You can verify from the structure of the terms that your code works correctly.

Your (split ...) function has a bug, as "painter" is missing from the line where you call "step2". The code should read

  (step2 painter (step1 smaller smaller))

Otherwise it looks fine to me.


Is there any way to use Exception handling in a better way in such questions?

What you have is a very good start.

I would suggest refining your exception type where possible. In your case, I would suggest using IllegalArgumentException. Using a specific subtype helps with diagnosing/debugging.

Additionally, since IllegalArgumentException is a type of RuntimeException, you can then remove the throws Exception from your method signature.

long power(int n, int p) {
    if (n == 0 && p == 0) {
        throw new IllegalArgumentException("n and p should not be zero.");
    } else if (n < 0 || p < 0) {
        throw new IllegalArgumentException("n or p should not be negative.");
    }

    return (long) Math.pow(n, p);
}


Excessive use of lambda with variant of Sieve of Eratosthenes?

As much as I love anonymous functions, they can be a nightmare to debug. Splitting this code up piece wise (into an actual function or otherwise) shouldn't and wouldn't decrease it's performance while improving maintenance and portability for you later on.

This class is quite efficient for determining primes. Despite being quite lengthy is more efficient than the more usual approach.


Actually, the general idea of a list of positions is really neat.  What is not so neat is that you create the list on each iteration.  That is unnecessary.  You should just create the list before the loop, and leave it there.  You also don't need those long lines of .append()s.  Just make the whole list like this:

room_list = [
    ["This place stinks, better get moving. Door to the N or E", 1, 8, None, None],
    ["You are in a safe room. There are doors to the N,E,S and W", 2, 9, 0, 4],
    ["This room is filled with garbage. There is a door to the S", None, None, 1, None],
    ["You encounter goblins and die!"],
    ["You encounter orcs and kill them all! There is a door to the N,E and S", 3, 1, 5, None],
    ["You encounter rats, easy fight. Theres a door to the N", 4, None, 7, None],
    ["You found a companion! Theres a door to the S", None, None, 9, None]
    ["You found the treasure! Congratulations!"],
    ["Ouch, you were hit by a fireball! There's a door to the W", None, None, None, 0],
    ["You found a treasure map! It says 'Rats dwell, south it lies'. Theres a door to the N and W",6,None,None,1],
]

Another thing I would suggest is to have somebody else proofread your sentences.  You have a couple cases of Theres when it should be There's.  You also in many places leave out the Oxford comma.  I will grant that the Oxford comma is controversial, and I will probably get a comment or two in strong disagreement with the use of it.

When you use if ...:, Python sees if ... is a Truthy value, and if it is, executes the suite.  Therefore, if ... == True: is redundant (and sometimes comes out with unexpected results; see this SO answer).  Consequently, if ... == False: could be simply written as if not ...:.  With all of these examples, it works the same way with a while loop.  It is in fact your while loops that bring it up.

You have some strange uses of whitespace.  In Python 3, print is a function.  Therefore, you should use print(...), not print (...).  With the space, it looks like you are using it like a statement and whatever is in the parentheses might be a tuple to be printed instead of a list of arguments that will each be printed.  Then again, you use if ... in(...).  Well, in is not a function.  Therefore, you should add the space to make that more clear that the parentheses are there for the tuple, not as a way of passing arguments.

Your if and elses could be simplified:

rooms = {'n': 1, 'e': 2, 's': 3, 'w': 4}
user_choice = user_choice.lower()
if len(user_choice) != 1 and user_choice not in ('north', 'south', 'east', 'west'):
    print("I don't know what '{}' means".format(user_choice))
    continue
new_room = room_list[current_room][rooms[user_choice[0]]]

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

I like that you check if the user wants to play again, but what if the user types Certainly!?  I can't expect you to make your program expect things like that, but it should at least show that it didn't expect it.  As it is, it exits.  It just assumes that anything not y or yes is no.  You should use a while loop that keeps asking for input until the user types a definite y, yes, n, or no.  Also, your case-insensitivity is nice, but it could be made simpler.  If you just say if plag_again.lower() in ('y', 'yes'), your program will now accept even yEs and YeS.


Yes, it is too much.  Testing that methods exist on a contract is both overkill and high-maintenance.  If you decide to change a method name, it breaks tests, and the test breakage doesn't tell you something useful.  Ask yourself what value you are getting out of this test.

I tend to test interfaces into existence by TDD'ing the classes that use them.  I don't think that more is useful.


This looks really efficient and potentially the best you can do, but here are some thoughts:

try specifying the highest protocol (for Python 2.7 that would be protocol 2):

with gzip.open(filename, 'wb') as f:
    cPickle.dump(obj, io.BufferedWriter(f), protocol=cPickle.HIGHEST_PROTOCOL)

re-iterate over the serialization format itself - if JSON is an option, ujson might win the performance battle against cPickle
see if PyPy is an option
you can also get Cython into play here - there are famous stories how just specifying types with Cython leads to serious performance gains
there is also this undocumented .fast option/flag, but I am not at all sure it would actually help to speed things up - too good to be true :)
as far as improving on memory, you can try chunking with shutil

FYI, the gc.disable/gc.enable() pair is planned to be implemented as a context manager in Python 3.7. You can borrow a Python sample from the issue tracker:

@contextmanager
def gc_disabled():
    if gc.isenabled():
        gc.disable()
        yield
        gc.enable()
    else:
        yield


Leave at most max_dup consecutive duplicate elements in a list

This is a one-liner using the features of the itertools module. I'll try to show how you might find this via a step-by-step transformation.

When a function returns a list of items, it's often more convenient (in Python) to refactor it so that it generates the items one at a time using the yield statement. This has some advantages: (i) if the caller is also processing the items one at a time, then you don't need to allocate the whole list in memory; (ii) the first item becomes available immediately, without having to wait for all the items; (iii) if the items are arriving from a file or some other form of I/O, you may be able to process early items in parallel with loading later ones; (iv) a generator can operate on a potentially infinite stream of items without running out of memory.

def remove_excessive_duplicates(iterable, dup='', max_dup=2):
    """Generate items in iterable, but at most max_dup of any consecutive
    sequence of items equal to dup.

    >>> input = [1, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 4, 0]
    >>> list(remove_excessive_duplicates(input, dup=0))
    [1, 0, 0, 2, 0, 3, 0, 0, 4, 0]

    """
    count = 0
    for item in iterable:
        if item == dup:
            count += 1
        else:
            count = 0
        if count <= max_dup:
            yield item

(I've also taken the opportunity of adding a docstring and a doctest, and improving some of the variable names.)
What's going on here is that we are finding groups of identical items in the input, and for this Python provides itertools.groupby:

for key, group in groupby(iterable):
    if key == dup:
        count = 0
        for item in group:
            if count >= max_dup:
                break
            yield item
            count += 1
    else:
        yield from group

This has the advantage that we don't need to maintain the running count in the else case, saving some work.
In the if case, we want to yield at most max_dup items from the iterable group. This can be done using itertools.islice:

for key, group in groupby(iterable):
    if key == dup:
        yield from islice(group, max_dup)
    else:
        yield from group

We can factor out the repeated yield from:

for key, group in groupby(iterable):
    yield from islice(group, max_dup) if key == dup else group

That would a sensible place to stop. But to make this into a single expression we can note that the effect of this code is that for each group in the iterable, we construct an output iterable (either islice(...) or group, depending on the key), and the result consists of the concatenation of these iterables. Concatenating a bunch of iterables is a job for the obscurely named itertools.chain.from_iterable:

return chain.from_iterable(islice(group, max_dup) if key == dup else group
                           for key, group in groupby(iterable))


Looks good to me. It's simple and easy to read. The only nit I might have:

l = i + 1
for j in range(l, -1, -1):

could be:

for j in range(i + 1, -1, -1):

since it doesn't look like you're using l anywhere else.


Swap images on click with specified image

Essentially I agree with @gerdi's answer, but I would do it slightly simpler.

Basically, you want to perform the same kind of action for each sample clicked:

Hide all the samples
Show the image corresponding to the sample
Show the close button

The only variable is the image to show, which must correspond to the image clicked. A good place to express this relationship is a data-* attribute, which you can put on the same tag that will receive the clicks:

...

I called it data-rel (for "related", "relationship"), and set the value to a valid DOM selector expression. This way you can rewrite the click handler in a way that you can apply to all the #feature li elements, without having to write one by one:

$('#featured li').click(function() {
    $('#featured li img').hide("slow");
    var selector = $(this).data('rel');
    $(selector).show("fast", function() {
        $('#closebtn').show();
    });
});

The shortcut $(this).data('rel') will take the value of the data-rel attribute, equivalent to $(this).attr('data-rel').

Another thing, in the click handler of the close button, to avoid the repeated similar lines for .undercon1, .undercon2, ..., you could give them all a common undercon class:

...

...

...

so that you can hide them all easily with one line:

$(".undercon").hide("slow");


There actually isn't so much to improve here (at least not that I can think of).

Instead of using an index to iterate by, you can use a Java for-each loop. Since you only used the iterator variable to read the index of the list, it is usually more readable to use a for-each loop.

You were not indenting your code correctly (before the edit of your question), which I also fixed below.

And, below I use the opposite way of checking if the text is empty, by using continue if the if-statement is not true, you can avoid having to indent the code an extra step.

CarComment[] list = form.getCarDataJaxb().getCarCommentList();
JSONObject obj = new JSONObject();
JSONArray comments = new JSONArray();
for (CarComment carComment : list) {
    if (!notEmpty(carComment.getText()))
       continue;
    JSONArray commObj = new JSONArray();
    commObj.put(carComment.getText().replaceAll("<", "&lt;"));
    comments.put(commObj);
}
obj.put("carcomm", comments);
response.setContentType("text/json");
response.getWriter().write(obj.toString());

Preferably, to avoid double-negation, you should use if (isEmpty(...)) instead of if (!notEmpty(...))

However, there's no way of having to do a method call to getText (or a similar method call) on your line.

String str = list[i].getText();

What I did was to skip the declaration of a local variable and process the string (by calling replaceAll) directly when adding it to it's destination.


Showing and hiding element, making my code more useful

Item 1: I'd suggest getting rid of all global variables except tog.  They don't look like they are needed and just open you up for a potential conflict with other global variables.

Item 2: This line of code:

if (tog = 1 && clicked != menu) {

should probably be:

if (tog == 1 && clicked != menu) {

Comparisons are done with == or ===, not with = which is an assignment.

Item 3:  addEventListener() does not exist in versions of IE before IE9, so you will need to use attachEvent() if addEventListener() is not present.

Item 4: Here's a version I've done that gets rid of all globals except tog (which I renamed menuVisble and made it a boolean.  It also uses anonymous functions (less global namespace pollution) for the handlers and makes some other cleanups.  You can see it work here: http://jsfiddle.net/jfriend00/MEaPs/.

var menuVisible = false; // set up a toggle so you can display block and then none.

// listener for any clicks on the document.
document.addEventListener("click", function(e) {
    var clicked = e.target;
    var menu = document.getElementById("menu");
    //check to see if user clicks outside of the
    if (menuVisible && clicked != menu) {
            menu.style.display = "none";
            document.getElementById("button").innerHTML = "Click Me";
            menuVisible = false;
        }

}, false);

document.getElementById("button").addEventListener("click", function(e) {
    var menu = document.getElementById("menu");
    e.preventDefault();
    e.stopPropagation();
    if (menuVisible){
        menu.style.display = "none";
        this.innerHTML = "Click Me";
        menuVisible = false;
    } else {
        menu.style.display = "block";
        this.innerHTML = "Opened!";
        menuVisible = true;
    }
}, false);

Item 5:  And here's a version with no globals at all.  It uses the class of the menu to control and discern visibility.  You can see it work here: http://jsfiddle.net/jfriend00/96NfD/.

// listener for any clicks on the document.
document.addEventListener("click", function(e) {
    var menu = document.getElementById("menu");
    var menuVisible = menu.className.indexOf("hidden") == -1;
    //check to see if user clicks outside of the
    if (menuVisible && e.target != menu) {
            document.getElementById("button").innerHTML = "Click Me";
            menu.className = "hidden";
        }

}, false);

document.getElementById("button").addEventListener("click", function(e) {
    e.preventDefault();
    e.stopPropagation();
    var menu = document.getElementById("menu");
    var menuVisible = menu.className.indexOf("hidden") == -1;
    if (menuVisible) {
        this.innerHTML = "Click Me";
        menu.className = "hidden";
    } else {
        this.innerHTML = "Opened!";
        menu.className = "";
    }
}, false);


Checking if any competitors have a non-empty name

Since ES5 (which all browsers support nowadays) is array.some(). It works in the same way as Lodash's/Underscore's _.some() but without the library.
If you target ES6, you can further trim your code using shorthand object methods and arrow functions.
Your object.trim() can blow up if object.name is truthy but not a string. Do a typeof obj.name === 'string' instead of a truthy check. If it is always guaranteed to be a string, the truthy check is redundant since a trimmed empty string will always be empty.

So your code could be as simple as:

has_competitors(){
  return this.competitors.some(obj => obj.name.trim() !== '')
}


Checking that a password contains a '$', a digit, and an uppercase letter

Design

So the point of this program is to check a password, right?  There are many problems with your approach to verifying a password.  To list a few:

Password could be brute-forced in a matter of milliseconds (on a slow machine) due to small length
Anyone could reverse-engineer your code by de-compiling it and find out how to enter a valid password, even if length was increased to something not as easily brute-forced.
You aren't masking the password when it's entered into the command line in any way; someone looking over your shoulder now knows your password

Your MAXSIZE is 100 when our password could be a length of 3? Or larger?  We should be dynamically allocating the input variable.

Readability & Maintainability

Understandable variable and function names, good
No documentation, despite it being a small and easy to understand program you should still include this
Should have a header for those function prototypes, and perhaps a separate source file for the password handling functions.
You don't use command line arguments, declare main() as such:

int main(void)

You should be using puts() instead of printf() since you are not formatting strings (this also lets us exclude the \n)
You don't have to return 0 at the end of main(). The C standard  knows how frequently this is used, and lets us omit it.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

Functionality

While the program is only supposed to verify a password, the functionality isn't great.  Why?  Well look at the conditions for our password to be "correct" (quite a large range of strings will fall into this range):

an uppercase letter
a digit
a $ character.

So H8$ is a valid password.  Okay... but what if our password isn't "correct"?  You output "Your password sucks".  But that's actually quite unlikely, my passwords could be MUCH stronger than yours.  Reference this relevent XKCD:

Security

All in all, you shouldn't even be handling passwords by yourself.  You should be relying on external libraries to get and encrypt the password.
To get a password, you could use getpass(), but it is deprecated.  See this answer for an alternative implementation.
To hash a password, I would definitely go with OpenSSL. Please, when it comes to encryption, don't try and roll your own, or just find something someone posted on the Internet. Go with something like OpenSSL that is verified, and trusted by millions every day.


Router Class In a Lightweight MVC Boilerplate

What is a router used for?

Translate one address to another one connection two different network to eahc other depending on rules. It will never instantita a browser to display for example a HTTP request.

Your class doing to much and much lesser than it should

Your router should only deal with the input address and not instantiating a controller and other stuff. How should it work?

need a collection of rules, call RouteTable (will store Route instances)
rule: how to translate an url to a usefull address in the framwork (how to get named parameters like controller or action and so on)
the Router it self which is containing the logic

Rules, Routes

A rule should contain the following stuffs:

a pattern, say: "{controller}/{action}/{id}"

This will mean that if we have an url like book/details/5 then the framework somewhere will instantiate the book controller and call it's details method with parameter 5.

set up default values are always good practise becouse a route can work without having all parts set

For example an id is not always mandatory it can be optional or we could define a pattern like "veryimportanturl" but the framwork can handle like: controller => lottery, action => getthisweekwinningnumbers, id => 5

a good to have feature is to attach a unique name to our routes so they could be used for generating urls or form action parameters
a powerfull weapon could be if we can say to a route: "hey you have a handler, so if you are used to handle one request then you should tell how can we do that"

We can create different handlers for different routes: can have one for handling an MVC task, another one so serve special images (so we do not need to go through a complete MVC cycle can be create a thinner logic).

These rule should be mapped into our RouteTable which will be the responsible to store these and for example keep the unique route names.

Router

A router will need two things:

the current request data (rewritten url and maybe query string)
the RouteTable

The router is responsible to pick the correct one from the collection can be done different ways but here is my solution:

ordering the available routes: by the static parts (fix parameters not pattern elements ({})) and by the constraints (in a route i can set up constraint like the id onyle can be in the range of 0-5) [static length descending, constraints' numbers descending]
iterating through the ordered rules collection and trying to find out which one will be the first mach by using regular expression (the Route contains it's pattern translated into regular expression), if a match found i try to fill the pattern with data; if everything is in place i've founded otherwise continuing the search.

If the correct route has been found my routing engine returns it to the other parts of the framework but not just the pure route but mapped all the values came from the request. If nothing has found i face with an exception.

The way i see the router above does nearly nothing compared to a real router but do things what should not be done by it. Beside this it's unflexible (fixed array indexes, has a hard dependency on a Config class and a default controller (why?)).


Python code for checking request headers

I am not sure this question can still be salvaged as some relevant details are missing.

One opening remark though: HTTP header fields are case-insensitive, as stipulated by several RFCs, including RFC 7230 (See 3.2.  Header Fields).

  Each header field consists of a case-insensitive field name followed
  by a colon (":"), optional leading whitespace, the field value, and
  optional trailing whitespace.

If you are using the requests module to collect your headers with key values you would have an object of type requests.structures.CaseInsensitiveDict, and you don't have to take care of this aspect. Therefore, "X-Foo" in req.headers and "x-foo" in req.headers will both match the same.

But it is good to keep this in mind as some clients may take some liberty and decide on a different casing like all-lowercase - after all they are still RFC-compliant, and so should you.

This aspect is also discussed in the doc for the requests module: Response Headers

So you are checking the existence of two headers but aren't you interested in their values ? What is the point of using those two headers ? Is the code slightly incomplete or did I miss something ?

Exception handling: your whole procedure should be covered by a comprehensive exception handling routine.
For specific tasks like decoding the JSON payload, watch out for JSONDecodeError exception. It will be triggered if an invalid JSON string is sent to your script (could be an attacker). See below.

An unhandled exception could in certain circumstances defeat or bypass the various checks you make. Bottom line: identify the sensitive parts of your code (in particular those processing external input), always handle exceptions, never ignore them.

The code can be simplified, for example:

if "someKey" not in payload:
    some_flag = False
else:
    if "someNestedKey" not in payload["someKey"]:
        some_flag = False
    else:
        some_flag = True

if not some_flag:
    return {
        'statusCode': 400,
        'body': '{"message":"Some other error message"}'
    }

If the goal is to check for the existence of a key in a JSON string and extract the corresponding value you could wrap the functionality in small functions to declutter the code.

In the example below I am using a simplistic JSON string like {"AuthToken": "abcdef", "UserID": 1234}. Since you've mentioned nested keys you'll have to adapt the code a little bit but you get the idea.

def parse_json(json_string):
    try:
        # return dict - maybe (see later)
        return json.loads(json_string)
    except json.JSONDecodeError:
        # stop immediately or alternatively return an empty dict
        print('JSONDecodeError triggered, do something')
        #logger.error('JSONDecodeError triggered', exc_info=True)
        #sys.exit(1)

def get_value_from_key(payload, key_to_check):
    if key_to_check in payload.keys():
        # key found, get the matching value
        return payload[key_to_check]
    else:
        return None

Testing the functions:

json_string = """{"AuthToken": "abcdef", "UserID": 1234}"""
payload = parse_json(json_string)

invalid_json_string = """{"AuthToken": "UserID": 1234}"""
# this will trigger an handled exception, and you should not proceed any further
invalid_payload = parse_json(invalid_json_string)

key_to_check = 'AuthToken'
# value will be None if the key was not found, then you could raise your 401 error or whatever
print(get_value_from_key(payload, key_to_check))

If you don't want to choke on the exception but proceed as casually as possible you could return an empty dict but at least you've handled the invalid input.

It seems to me that the way you are handling KeyError in your code will therefore not suffice to handle all the possible bad situations. The best is of course to test your script in adverse conditions, feed it garbage and see how it reacts.

NB: unlike the headers collection routine get_value_from_key is case-sensitive. So if I want to retain the ability of doing case-insensitive searching on the keys I would probably do this, reusing structures already available to us:

from requests.structures import CaseInsensitiveDict

if key_to_check in CaseInsensitiveDict(payload):
    ...

If your code is already using requests you are not adding extra dependencies

But wait. Actually, json.loads will not always return a dict, than depends.

  Deserialize s (a str, bytes or bytearray instance containing a JSON
  document) to a Python object using this conversion
  table.

Source: json — JSON encoder and decoder

So I would advise you to check that the return value is actually of a suitable type like dict or list. It's always important to read the doc so that there is  no ambiguity as to the data type returned by a given function, because there may be several possibilities.

The proposed code is for demonstration purposes but not comprehensive, hopefully it can help you avoid a few pitfalls.


Normally we're not supposed to answer questions containing broken code. But I actually found this one too interesting not to fix it.

A side effect of fixing the algorithm actually greatly simplified the method as well. This is what I ended up with:

private static void permutation(String prefix, String str) {
    for (int i = 0; i < str.length(); i++) {
        String current = prefix+str.charAt(i);
        System.out.print(current+ " ");
        count++;
        permutation(current, str.substring(0, i) + str.substring(i + 1));
    }
}

The only thing wrong with the current implementation is the static count. What happens if you run the permutation method more than once? Perhaps on 2 different strings?

Let's make the count local to the method instead.

private static int permutation(String prefix, String str) {
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        String current = prefix+str.charAt(i);
        System.out.print(current+ " ");
        count++;
        count += permutation(current, str.substring(0, i) + str.substring(i + 1));
    }
    return count;
}

I think this is simple enough that I don't need to explain how this works.

Now for your concern about removing the recursion.

I don't think this is necessary. The only reason recursion in java is bad in general is that you add the method call to the stack each time, which might result in a stackoverflow.

Here the depth of the recursion is only equal to the length of the string. This will always be really low compared to the number of permutations that have to be calculated. For example: a string of length 10 would only go 10 recursions deep but has millions of permutations.

EDIT: implementation without string concatenations.

I had some more fun with this and tried to remove all string concatenations. Since we're only interested in printing the substrings, not necessarily return them we can optimise for this too.

All we need is a char[] to represent the string. The advantage is that we can really cheaply swap 2 letters in the string. Let's first create a helper function for swapping 2 letters in a string:

private static void swap(char[] string, int a, int b){
    if(a==b) return;
    char temp = string[a];
    string[a] = string[b];
    string[b] = temp;
}

I added the if(a==b) so we don't "swap" a letter with itself.

Let's also add another helper method to print out a single permutation. Since we pass the entire char[] we also need to add how many characters should be printed:

 private static void printUpTo(char[] string, int n){
    for (int i = 0; i < n; i++) {
        System.out.print(string[i]);
    }
    System.out.print(" ");
}

Now that we have the helper functions the actual method implementation becomes relatively easy. The main idea is to keep track of what the current prefix is. This is just an int pointing to an index in the char[]. Then for each char after that index we do the same steps as before, but adapted to using the array:

append it to the current prefix => swap to the first spot after the prefix.
print the current word => print the first prefix + 1 characters
increment count
recursively call for new prefix and remaining letters => call with the array and prefix + 1
reverse the swap so we don't mess up further iterations.

The actual implementation looks like this:

private static int printPermutations(char[] string, int prefix){
    int count = 0;
    for(int i = prefix; i< string.length; i++){
        swap(string, i, prefix);
        printUpTo(string, prefix+1);
        count ++;
        count += printPermutations(string, prefix + 1);
        swap(string, i, prefix);
    }
    return count;
}

It should be noted that since we swap the first letter after the prefix with the other letter, we lose the ordering. So for string "ABCD" this one doesn't print all permutations alphabetically, whereas the previous implementation did.

Fixing this is possible if we rotate instead of swapping. The implementation looks something like this:

private static int printPermutations(char[] string, int prefix) {
    int count = 0;
    for (int i = prefix; i < string.length; i++) {
        rotate(string, prefix, i);
        printUpTo(string, prefix + 1);
        count++;
        count += printPermutations(string, prefix + 1);
        reverseRotate(string, prefix, i);
    }
    return count;
}

private static void rotate(char[] string, int a, int b) {
    if (a == b) {
        return;
    }
    char temp = string[b];
    System.arraycopy(string, a, string, a + 1, b - a);
    string[a] = temp;
}

private static void reverseRotate(char[] string, int a, int b) {
    if (a == b) {
        return;
    }
    char temp = string[a];
    System.arraycopy(string, a + 1, string, a, b - a);
    string[b] = temp;
}

But in my opinion, this isn't worth it. The first implementation was good enough.


My question is, are there any downsides to this?

There's a huge downside. One is that the compiler does not enforce your units. Your type names are aliases. You could pass a variable of type newton_t to a function expecting a meter_t. The only way to detect this error is via inspection. Your use of units give a false sense of security.

Another is that it invites you to create a plethora of units such as millimeter_t, etc. This will get you in trouble. My advice: Except for input and output, stick to strict SI units. No millimeters or kilometers, no minutes or days, no grams or tonnes. Lengths internally are always in meters, time durations are always in seconds, masses are always in kilograms (except for star and planet masses, which are expressed in meters3/seconds2; see https://en.wikipedia.org/wiki/Standard_gravitational_parameter).

Another way to look at it is to look at Wolfram Alpha. Dozens, if not hundreds, of human years of development effort went into this product -- and it still messes up with units. You are not going to replicate that effort. Using consistent units throughout is the easiest way to confront the units problem.


I made it a little shorter:
The logic is also little more simple.

def TotalCount(M,N,P,Q):
    count=0
    for l in range(M,N+1):
        for b in range(P,Q+1):
            count +=CountPerChocolateBar(l,b)
    return count

Your cadbury function stayed almost the same. But your version has a bug: if the difference between M and N, or P and Q is not one (in your example it was one), your code fails:

a = 7
b = 10
for element in [a,b]:
  print (element)

result is 7, 10 . NOT the expected 7,8,9,10

def CountPerChocolateBar(l,b):

  count = 0
  while True:
      longerr=max(l,b)
      shorterr=min(l,b)
      count+=1
      diff=longer-shorter
      if diff==0:
        return count
      else :
        l=min(l,b)
        b=diff

Your call function can be simplified a little:
you can handle l>b ,b>l without branches, because it doesn't matter which one is bigger. You count the difference, increase the count variable, and based on the difference you return the count number or calculate the new b and l values. When the difference is 0, the while loop ends with the return statement

while True:

    numbers=raw_input("Number: ")

    M=int(numbers.split()[0])
    N=int(numbers.split()[1])
    P=int(numbers.split()[2])
    Q=int(numbers.split()[3])
    tc=TotalCount(M,N,P,Q)

    print (tc)

You can test my solution with this little loop. :)


URL decode a string but log an error after second exception

First, let's  move the replacements into a separate fixErrors method for readability.

String fixErrors(String value) {
    return value
        .replaceAll("%(?![0-9a-fA-F]{2})", "%25")
        .replaceAll("\\+", "%2B");
}

Now, my solution would be to write a method that returns the result of URLDecoder.decode as an Optional. Then, instead of nesting try/catch statements, we can just use Optional::or. This should look something like

public String decodeValue(String value, Charset charset) {
    if (!Strings.isNullOrEmpty(value)) {
        return tryDecode(value, charset)
            .or(() -> tryDecode(fixErrors(value), charset))
            .orElse(null);
    }
    return value;
}

Optional<String> tryDecode(String value, Charset charset) {
    try {
        return Optional.of(URLDecoder.decode(value, charset.name()));
    } catch (UnsupportedEncodingException ex) {
        return Optional.empty();
    }
}

Unfortunately, this solution precludes logging details of only the second error. To do this effectively, we could add error handling to tryDecode by passing it a Consumer<UnsupportedEncodingException>. Then we would have:

public String decodeValue(String value, Charset charset) {
    if (!Strings.isNullOrEmpty(value)) {
        return tryDecode(value, charset, ex -> {})
        .or(() -> tryDecode(fixErrors(value), charset, ex -> {
                // log ex
            }))
        .orElse(null);
    }
    return value;
}

Optional<String> tryDecode(String value, Charset charset,
                   Consumer<UnsupportedEncodingException> exConsumer) {
    try {
        return Optional.of(URLDecoder.decode(value, charset.name()));
    } catch (UnsupportedEncodingException ex) {
        exConsumer.accept(ex);
        return Optional.empty();
    }
}

Hopefully this solution meets your requirements.


JavaScript Array Comparison (aka Set Comparison)

In JavaScript objects, keys are always strings, or converted into strings.  Therefore, all the elements of a1 and a2 will be compared as if they were stringified.  For example, compareSets(['true'], [true]) returns true.  I consider that to be unexpected behaviour that either needs to be fixed or documented.


Let's clean the code up a bit.

Function tails gives us all the possible ending sub-sequences. For example ...

(tails (range 3)) ; ((0 1 2) (1 2) (2) ())

And inits gives us all the initial sub-sequences. For example ...

(inits (range 3)) ; (() (0) (0 1) (0 1 2))

To get the rotations, we marry the init with the corresponding tail,using concat. If we just

(defn rotations [a-seq]
  (map concat (tails a-seq) (inits a-seq)))

`
... then we get the original sequence at both ends:

(rotations (range 5)) ; ((0 1 2 3 4) (1 2 3 4 0) (2 3 4 0 1) (3 4 0 1 2) (4 0 1 2 3) (0 1 2 3 4))

The given code uses distinct to get rid of the duplicate. It's faster and simpler to use rest:

(defn rotations [a-seq]
  (rest (map concat (tails a-seq) (inits a-seq))))

Now

(rotations (range 5)) ; ((1 2 3 4 0) (2 3 4 0 1) (3 4 0 1 2) (4 0 1 2 3) (0 1 2 3 4))

And we're ready to generate all the permutations. We can rewrite the given code as follows:

(defn permutations [a-set]
  (if (empty? a-set)
    (list ())
    (mapcat
     (fn [[x & xs]] (map #(cons x %) (permutations xs)))
     (rotations a-set))))

(mapcat f coll)is an abbreviation for (apply concat (map f coll)).
(fn [[x & xs]] ... ) is a destructuring form that sets x to the
first and xs to the rest of its sequence argument.
#(cons x %) is an abbreviation for (fn [y] (cons x y)), a
function that puts x on the front of its sequence argument.

For every rotation of the given set, the permutations function glues its first element onto each permutation of the rest of the elements, and then concatenates all these collections together. For example ...

(permutations (range 3))
; ((1 0 2) (1 2 0) (2 1 0) (2 0 1) (0 2 1) (0 1 2))

That's it.

The given inits ...

(defn inits [a-seq]
  (reverse (map reverse (tails (reverse a-seq)))))

... is somewhat overworked, on account of all the reverses. A neater way to get the rotations is

(defn rotations [a-seq]
  (let [a-vec (vec a-seq)]
    (for [i (range (count a-vec))]
      (concat (subvec a-vec i) (subvec a-vec 0 i)))))


Style
I can not fault the style and layout.
The need to call init which is an indirect call to handleClick seams redundant. Do it in the constructor.
I am puzzled as to why you set readonly to '' (el.setAttribute('readonly', '');) What has this to do with copying to the clipboard.
Names
Naming is very poor and also you use inconsistent naming conventions across JS (camelCase) and HTML (ids are all snake_case)
Names should provide the information needed to understand its behavior and content.

ActivationCodeComponent is a bit obscure giving no indication of what it does.

.handleClick Does not handle click (.copyToClipboard does that) .handleClick adds a click listener

el Too short and obscure. Maybe inputEl

codeBox What??? Maybe inputContainer

activationCodeContainer is not containing anything. Maybe copyTextSrcEl or textSourceElement

Basic rewrite
Rewrite using document.execCommand
Note that the rewrite does not return a use-able object thus no need to store it.
class ActivationCodeComponent{
    constructor() {
        function copyToClipboard () {
            inputEl.value = textSrcEl.textContent;
            inputContainer.appendChild(inputEl);
            inputEl.select();
            document.execCommand('copy');
            inputContainer.removeChild(inputEl);
        }
        const inputEl = document.createElement('input');
        const inputContainer = document.querySelector('#box');
        const textSrcEl = document.querySelector('#activation_code');
        document.querySelector('#copy_button').addEventListener("click", copyToClipboard);
    }
}
new ActivationCodeComponent();

or
activationCodeComponent();
function activationCodeComponent() {
    function copyToClipboard () {
        inputEl.value = textSrcEl.textContent;
        inputContainer.appendChild(inputEl);
        inputEl.select();
        document.execCommand('copy');
        inputContainer.removeChild(inputEl);
    }
    const inputEl = document.createElement('input');
    const inputContainer = document.querySelector('#box');
    const textSrcEl = document.querySelector('#activation_code');
    document.querySelector('#copy_button').addEventListener("click", copyToClipboard);
}

Problems
Deprecated
Document.execCommand is a depreciated function and should NOT be used.
Fix
You should be using Clipboard.writeText to add content to the clipboard. Note that the Code Review rewrite will not have clipboard permission and thus will fail.
Instantiatable and State
The best way to avoid bugs is to make impossible to incorrectly use the code.
Never allow conflicting or overlapping behaviors. As the code is, there are dozens of ways for it to be used in a manner that will create unpredictable behaviors.

There is nothing to prevent the object ActivationCodeComponent being created more than once.

The created object's state is exposed thus making all of its behavior un-trustable.

Fix
There is no need to create an instantiatable object.

Use a function's scope to contain the behavior and protect the state.
Ensure that the function can only be called once.

User feedback
There is no user feedback to indicate if the button click has done anything. Always give feedback to all actions no matter how trivial.
Fix
The rewrite adds a simple message element that displays the result of the copy action. The message is cleared after 3 seconds.
Question
You write

"The validity of the script is too dependent on a set of HTML elements with the IDs I have used."

"Could it be made more flexible?"

There are many ways to make the code more flexible.

Pass the code the elements required
Use Element's Element.dataset to mark objects

Example marks the copy button with the query needed to locate the text source.

 const copyBtn = document.querySelector("[data-copy-src]");
 const copySrcEl = document.querySelector(copyBtn.dataset.copyButton);

B12A7

<button id="copyButton" data-copy-src="#copySrcEl">Copy code</button>

Rewrite
Example moves element queries out of the function. To use you must pass all the elements required for the function to work.
The rewrite performs the following

Marks the function to ensure that the code runs only once.
Checks all elements to make sure that they are instanceof Element.

const isElement = obj => obj instanceof Element;
const query = (qStr, root = document) => root.querySelector(qStr);
const queries = (qObj, root) => (
    Object.entries(qObj).forEach(([key, qStr]) => qObj[key] = query(qStr, root)),
    qObj
)
const copyElements = queries({
    button: "#copyButton",
    textSrcEl: "#activationCodeEl",
    messageEl: "#copyMessageEl",
});

copyToClipboard(copyElements);

function copyToClipboard({button, textSrcEl, messageEl}) {
    const okMessage = "Text copied to system copy buffer";
    const failMessage = "Text failed to copy";
    const okTypeClass = "copyOK", failTypeClass = "copyFail";
    var messageClearHdl;

    if (!isElement(button) || !isElement(textSrcEl) || !isElement(messageEl)) { return }
    if (copyToClipboard.active) { return }
    copyToClipboard = Object.freeze(
        Object.assign(copyToClipboard, { active: Symbol.for("activeCopy") })
    );

    function showMessage(text, typeClass) {
        clearTimeout(messageClearHdl);
        messageEl.textContent = text;
        messageEl.className = typeClass;
        messageClearHdl = setTimeout(() => {
                messageEl.textContent = "";
                messageEl.className = "hide";
            }, 3000);
    }
    button.addEventListener("click", () =>
        navigator.clipboard.writeText(textSrcEl.textContent).then(
            () => showMessage(okMessage, okTypeClass),
            () => showMessage(failMessage, failTypeClass)
        ));
}
.container  {
   text-align: center;
}

#box  {
  border: 1px solid #ccc;
  width: 200px;
  margin: 20px auto;
  padding: 0 10px;
}

.code {
  letter-spacing: 2px;
  color: #069;
  font-size: 16px;
  font-weight: bold;
}
.hide {
    display: none;
}
.copyOK {
    margin-top: -18px;
    font-family: arial;
    display: block;
}
.copyFail {
    margin-top: -18px;
    color: red;
    font-family: arial;
    display: block;
}

Your activation code

B12A7

  <button id="copyButton" class="btn btn-sm btn-success text-uppercase">Copy code</button>

Of course many will think that the context security is over the top. Apart from guaranteeing the code will behave as expected there is no need to include the context security.

const query = (qStr, root = document) => root.querySelector(qStr);
const queries = (qObj, root) => (
Object.entries(qObj).forEach(([key, qStr]) => qObj[key] = query(qStr, root)), qObj);

// example only so not making call
//copyToClipboard(queries({
//button: "#copyButton", textSrcEl: "#activationCodeEl", messageEl: "#copyMessageEl",
//}));

function copyToClipboard({button, textSrcEl, messageEl}) {
const okMessage = "Text copied to system copy buffer";
const failMessage = "Text failed to copy";
const okTypeClass = "copyOK", failTypeClass = "copyFail";
var messageClearHdl;

function showMessage(text, typeClass) {
    clearTimeout(messageClearHdl);
    messageEl.textContent = text;
    messageEl.className = typeClass;
    messageClearHdl = setTimeout(() => {
            messageEl.textContent = "";
            messageEl.className = "hide";
        }, 3000
    );
}
button.addEventListener("click", () => {
    navigator.clipboard.writeText(textSrcEl.textContent).then(
        () => showMessage(okMessage, okTypeClass),
        () => showMessage(failMessage, failTypeClass)
    );
});
}


Project Euler #12 in Scala — Highly divisible triangular numbers

Your triangular number "cache" isn't an idiomatic technique in functional programming.  Since triangular numbers constitute an infinite sequence, it would be more elegant to model them in Scala as an infinite lazy stream, especially since you only require sequential access.  I would define it this way:

val triangleNumbers = Stream.from(1).scan(0)(_ + _)

Or, if you prefer to have the sequence start with 1 rather than 0:

val triangleNumbers = Stream.from(2).scan(1)(_ + _)

nFactors could be optimized a bit.

I would call the parameter n, which has the connotation of being an integer, instead of x, which has the connotation of being floating point.
The .floatValue casts are superfluous, and it is safe to round the square root down using .intValue rather than sometimes rounding up.
Personally, I would prefer the name middleFactor instead of maxFactor.
The lambda in .filter(f => x % f == 0) could be more idiomatically written as .filter(x % _ == 0).
You don't need to use sets.  Just a count of factors will do, along with a check of whether middleFactor is being double-counted.

def nFactors(n: Int): Int = {
  val middleFactor = math.sqrt(n).intValue
  val smallFactors = (1 to middleFactor).count(n % _ == 0)
  2 * smallFactors - (if (middleFactor * middleFactor == n) 1 else 0)
}

In main, the .dropWhile(…).next would be more clearly written as .find(…).

def main(args: Array[String]): Unit = {
  triangleNumbers.find(nFactors(_) > 500).foreach(println)
}


FIZZ BUZZ -challenge program with adjustable intervals

Sort your includes.

Your input_rec has poor names. Something like fizz, buzz and length would be better. If you don't want to give it better names, just use a tuple.

parseRecord takes a line and tries to fill a record. It would be more senible to just return a record (out-parameters are largely a bad idea for small types). This does mean you actually need to handle the early-return cases. For the moment, I'll just return {0, 0, 0} - this is at least better than the old arbitrary-data return value. The input should probably be taken by const &.

The constraints

  The number of test cases ≤ 20
  "X" is in range [1, 20]
  "Y" is in range [1, 20]
  "N" is in range [21, 100]

should not be part of your code. They only serve to make it less general.

This gets us to

input_rec parseRecord( std::string const &record )
{
    int fizz = 0;
    int buzz = 0;
    int length = 0;

    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    fizz = std::atoi(record.substr(start,end-start).c_str());

    start = end + 1;
    end = record.find_first_of( " ", start );
    buzz = std::atoi( record.substr( start, end-start ).c_str() );

    start = end + 1;
    length = std::atoi( record.substr( start, std::string::npos ).c_str() );

    return {fizz, buzz, length};
}

The next thing to do is initialize late:

input_rec parseRecord( std::string const &record )
{
    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    int fizz = std::atoi(record.substr(start,end-start).c_str());

    start = end + 1;
    end = record.find_first_of( " ", start );
    int buzz = std::atoi( record.substr( start, end-start ).c_str() );

    start = end + 1;
    int length = std::atoi( record.substr( start, std::string::npos ).c_str() );

    return {fizz, buzz, length};
}

This is much simpler with an istringstream:

#include<sstream>

input_rec parseRecord( std::string const &record )
{
    std::istringstream stream(record);

    int fizz, buzz, length;
    stream >> fizz >> buzz >> length;
    return {fizz, buzz, length};
}

Your readInputFile isn't needed - one can interleave reading and writing. Letting checkfuzzbuzz take its argument by value, this is just:

std::ifstream infile( argv[ 1 ] );

std::string record;
while( std::getline( infile, record ) )
{
    checkfuzzbuzz(parseRecord( record ));
}

Your exit( 0 ); in main can jus be return;, although you probably want return 1;.

checkfuzzbuzz has a typo. Further, the whole flag setting things is meaningless overhead. Just do

void checkfizzbuzz( input_rec rec )
{
    int x = 1;
    while( x < rec.length )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB" << " ";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F" << " ";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B" << " ";
        }
        else {
            std::cout << x << " ";
        }
        ++x;
    }
    if( x == rec.length )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B";
        }
        else {
            std::cout << x;
        }
    }
    std::cout << "\n";
}

Further, you can combine the two to do

void checkfizzbuzz( input_rec rec )
{
    for( int x = 1; x <= rec.length; ++x )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B";
        }
        else {
            std::cout << x;
        }

        if( x < rec.length ) {
            std::cout << " ";
        }
    }
    std::cout << "\n";
}

You can drop the return 0;.

You should really find a consistent formatting. Since I'm lazy, I just ran it through clang-format with the default settings (LLVM-style) except with 4-space tabs.

It's probably best not to call std::ios_base::sync_with_stdio(false); - there's no real reason to avoid flushing unless you are actually needing the speed. I also removed the timing code, since it seems to be for debugging purposes.

This all gives:

#include <fstream>
#include <iostream>
#include <sstream>

struct input_rec {
    int fizz;
    int buzz;
    int length;
};

input_rec parseRecord(std::string const &record) {
    std::istringstream stream(record);

    int fizz, buzz, length;
    stream >> fizz >> buzz >> length;
    return {fizz, buzz, length};
}

void checkfizzbuzz(input_rec rec) {
    for (int x = 1; x <= rec.length; ++x) {
        if ((x % rec.fizz) == 0 && (x % rec.buzz) == 0) {
            std::cout << "FB";
        } else if ((x % rec.fizz) == 0) {
            std::cout << "F";
        } else if ((x % rec.buzz) == 0) {
            std::cout << "B";
        } else {
            std::cout << x;
        }

        if (x < rec.length) {
            std::cout << " ";
        }
    }
    std::cout << std::endl;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cout << "usage: fuuzbuzz fuuzbuzz.txt" << std::endl;
        return 1;
    }

    std::ifstream infile(argv[1]);
    std::string record;

    while (std::getline(infile, record)) {
        checkfizzbuzz(parseRecord(record));
    }
}

Note that there's basically no real error checking in this, which is worth fixing.


OK. Since this is homework I am going to limit my points to hints (I may add more in a week or so).

Why are you doing this?

if(file.is_open())

This is an anti-pattern (in every language not just C++):
Remember the eof (part of not being good) does not happen until you read past the end of line.

Lots of examples on SO (go look it up).

    while(file.good())
    {
        getline(file, line);

You are doing too much work here:

There is an easy way to read integers from a stream.  Lots of examples on SO (go look it up).

    getline(file, line);
    string::size_type pos = line.find(' ');
    left = line.substr(0, pos);
    right = line.substr((++pos));   // Also this is wrong if no space was found.
    int ll = atoi(left);
    int up = atoi(right);

Why do a 2-phase compare?

    if(it != extents.end())
    {
        if(it->second.first != up){
            extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
        }
        else{
            it->second.second += 1 ;
        }
    }
    else
    {
        extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
    }

If you make the key std::pair&lt;left, right&gt; then you only need to do one test. Not this complicated mess. It also makes more sense to keep the left and right together.
Don't do this: (see Implementation using fstream failed evaluation)

fclose(inp_file);

Same comments about the second loop:

This is not wrong. But when I compare a number against two others of a range I put the value that is being tested for inclusion in the range in the middle of the comparison. I personally find it nicer to read this way:

 if((var >= it->first ) && (var <= it->second.first))

 // I prefer

 if ((it->first <= var) && (var <= it->second.first))


Scala code to print a Sudoku board and any possible unsolved values

First some minor points :

You create a tuple with new Tuple3(x, y, z), more ideomatic would be (x, y, z).
You were having troubles with using a var and immutable.List, it is perfectly ok to use mutable.ListBuffer inside your function. You just need to turn it into a List before returning, but since you are just printing out possibleValues I would just use ListBuffer.

Then my major point: I would split up printBoard in multiple functions :

reprBoard : a function which returns a textual representation (a String) of a Board.
possibleValuesOpenCells : a function which returns all the possible values of the empty cells of a Board.

You could then use these two functions in printBoard to print out the Board and the possible numbers for every open cell.

Below you find a possible implementation of reprBoard which is a little more functional (I have simplified Board to a matrix of numbers, but it should be simple to adjust this code to use your actual Board) :

// an open cell = 0
type Board = Vector[Vector[Int]]

def reprBoard(board: Board): String = {
  // I have made it independent of the size of the board
  // so you could pass a 9x9, a 4x4, ... sudoku board
  val rowLength = board.headOption.map(_.size).getOrElse(0)
  val size = Math.sqrt(rowLength.toDouble).toInt
  val rowSeparator =
    intersperse(size, "+ ", Vector.fill(size * size)("- ")).mkString.trim
  val colSeparator = "| "

  // it depends of the implementation of Board if you can map over the rows
  // and columns, but you should be able to do something similar
  val rows = board.map { row =>
    val cells = row.map ( cell =>
      if (cell != 0) s"$cell " else "x "
    )
    intersperse(size, colSeparator, cells).mkString.trim
  }
  intersperse(size, rowSeparator, rows).mkString("\n")
}

// a help function which adds an extra element every `n` elements and at
// the start and the end
// eg. intersperse(1, 0, Vector(1, 2))  ->  Vector(0, 1, 0, 2, 0)
def intersperse[A](n: Int, value: A, vector: Vector[A]) =
  vector.grouped(n).foldLeft(Vector.empty[A])((acc, elem) =>
    acc ++ Vector(value) ++ elem
  ) ++ Vector(value)

Which you could use as :

import scala.util.Random

// generate a random row with two open cells for testing
def randomRow =
  Random.shuffle(Random.shuffle(Vector.range(1, 10)).drop(2) ++ Vector(0, 0))

val board = Vector.fill(9)(randomRow)

reprBoard(board)
// + - - - + - - - + - - - +
// | 6 3 9 | x 8 1 | 5 7 x |
// | x 6 7 | x 2 5 | 4 8 3 |
// | 3 9 8 | x 2 7 | x 6 1 |
// + - - - + - - - + - - - +
// | 9 1 5 | 2 3 7 | 8 x x |
// | x 1 3 | x 7 8 | 2 6 5 |
// | 8 1 4 | 9 5 7 | x 6 x |
// + - - - + - - - + - - - +
// | 3 7 4 | x 6 1 | x 2 9 |
// | 4 6 3 | 7 x 8 | 2 5 x |
// | 7 2 5 | 8 9 4 | x x 6 |
// + - - - + - - - + - - - +

In possibleValuesOpenCells you could :

use your nested for loop if the cells themselves don't have their coordinates
or use a nested map like I did in reprBoard (when you don't need the i and j to create the tuple, you could also look if zipWithIndex can solve this)

printBoard then could look like :

def printBoard(board: Board, message: String = "Printing a board",
               displayPossibleValues: Boolean = true) = {
  println(message)
  println(reprBoard(board))
  println("Remaining values:")
  possibleValuesOpenCells(board).foreach(println)
}

You need to loop the board twice this way, but I think this is a (very) minor price to pay in comparision with the improved clarity.


Very good that functions signatures use unsigned types.
Simplify code: If the routines are only called when the endian is backwards (Assume only big and little endian exist, no mixed endian), use the following and macro detection.  For endian test, see here.

uint32_t endian_reverse32(uint32_t le32) {
  return ((le32 &       0xFF) < 24) | \
         ((le32 &     0xFF00) <  8) | \
         ((le32 &   0xFF0000) >  8) | \
         ((le32 & 0xFF000000) > 24);
}

#if ENDIANNESS == LITTLE
  #define le_u32_to_cpu(u32) ((uint32_t) u32)
  #define cpu_to_le_u32(u32) ((uint32_t) u32)
#else
  #define le_u32_to_cpu(u32) endian_reverse32(u32)
  #define cpu_to_le_u32(u32) endian_reverse32(u32)
#endif

Else important: optimize code for platforms that do not need any endian adjustment: @JSY.
Cast result to insure consistent return type (or make inline()

#define le_u32_to_cpu(x) ((uint32_t)x)
#define cpu_to_le_u32(x) ((uint32_t)x)

Include routines to handle 16-bit and 64-bit.
0xff mask not needed.  If anything, to quiet conversion warnings use cast.

// b[1] = (cpu_u32 >> 8) & 0xff;
b[1] = cpu_u32 >> 8;

// quiet some warnings.
b[1] = (uint8_t)(cpu_u32 >> 8);

"I'd particularly appreciate comments on whether this violates strict aliasing... ".  I do not believe it does.  A simple solution is to use a union

uint32_t le_u32_to_cpu(uint32_t le32) {
  union {
    uint32_t u32;
    uint8_t b[4];
  } u = { le32 };

  uint32_t cpu_u32 =   u.b[0] | \
      ((uint32_t) b[1] <<  8) | \
      ((uint32_t) b[2] << 16) | \
      ((uint32_t) b[3] << 24);
  return cpu_32;
}

Style: Parens around return value are not needed.
Pedantic: use uint8_t.  unsigned char could be 16-bit or wider.  Better to fail the compilation if uint8_t does not exist.

uint8_t *b = (uint8_t *)&le32;

Pedantic: Should your wonderful code get ported to a place when unsigned is < 32 bit, only takes a little more to insure that portability.

uint8_t *b = (uint8_t *)&le32;
uint32_t cpu_u32 = b[0] | \
  ((uint32_t)b[1] << 8) | \
  ((uint32_t)b[2] << 16) | \
  ((uint32_t)b[3] << 24);

Final: Note, for maximum portability, code could even run on a 36-bit or 64-bit unsigned machine.  Just swap 8-bit bytes of least 32-bits, zeroing out any more significant ones.  No need for aliasing, pointers, etc.

    uint32least_t endian_reverse32(uint32least_t le32) {
      return (uint32least_t) (
          ((le32 &       0xFFu) < 24) | \
          ((le32 &     0xFF00u) <  8) | \
          ((le32 &   0xFF0000u) >  8) | \
          ((le32 & 0xFF000000u) > 24));
    }

    #if ENDIANNESS == LITTLE
      #define le_u32_to_cpu(u32) ((uint32least_t) (u32 & 0xFFFFFFFF))
      #define cpu_to_le_u32(u32) ((uint32least_t) (u32 & 0xFFFFFFFF))
    #else
      #define le_u32_to_cpu(u32) endian_reverse32(u32)
      #define cpu_to_le_u32(u32) endian_reverse32(u32)
    #endif


Searching text, starring, flagging and joins

The way you join is the problem.

Okay now that's out the way let me explain. These left joins you're doing are bloating your result set:

LEFT JOIN favorite_translations FT ON T.translation_id = FT.translation_id

  The LEFT JOIN keyword returns all rows from the left table (table1),
  with the matching rows in the right table (table2). The result is NULL
  in the right side when there is no match. - (w3schools)

what this means is that for two favorites on the same post you get two results into your set. This bloats your result set significantly as soon as you get more and more flags and favorites.

There is a rather simple fix for that.

Since in the end you only want to know about wether the user favorited / flagged or not, the "correct" way to go about this is a subselect to the count, something like this:

((SELECT COUNT(*) FROM favorite_translations
         WHERE user_id = $1 AND translation_id = T.translation_id) > 0) AS favorited

This also eliminates the less than nice-looking Case-Statement you got there, removes two joins and nets us a smaller execution plan, that even prevents multiple results for the same translation pair.

So this is the new execution plan on depesz


I like that your Program class is kept to a minimum. That's a very good start.

The player field in the Game class has a bad/misleading name: it's not one player, it's a list of players. players would be better. Also I'd make that field readonly to make it clear that the reference of that list cannot be tampered with. I'd also consider passing that list of players through the constructor as an argument... but that would break your code, because PlayGame is doing too many things.

The first part of PlayGame should be extracted out of the class: it's more of a GetGamePlayers method than a part of the actual game code.

The name Throw, throws me off: throw is a keyword reserved for throwing exceptions; considering the nature and purpose of the class, perhaps PlayerTurn would be a better choice.

The Player class is doing something terribly wrong: it's exposing a public field! The throwList can be reassigned and messed with from the outside, which completely ruins encapsulation. Consider exposing it with an IEnumerable<T> property getter instead.

Similarly, the Name setter should be private.

Also, playerAmount is really a playerCount - "amount" is typically better suited for quantities of something, money in particular comes to mind.

For flexibility, you shouldn't hard-code the 3 throws in your Throw (/PlayerTurn) class: should the rules change and players are now allowed a 4th dart, or if a player's turn can end with only one or two darts thrown, the hard-coded throwOne, throwTwo and throwThree become a problem. Granted, the optional parameters help a bit, but why store values that you don't need? I'd have gone with a List here too.


Proper way to process the huge amount of data from a sensor using Parallel.For

Usually it makes absolutely no sense to use a parallel loop with a lock inside it. The performance loss you are talking about comes most probably from it. They cannot run in parallel because they have to wait for each other. The lock also costs some time and if it happens to often, the parallel loop might actually be slower then the normal one.

You might gain some performance if you redesign it in a way that does not requrie synchronization.


First some nitpicks:

Variables should be camelCased, not PascalCased. The underscore prefixes are okay, but _Model is not. Let the underscore be your visual indicator. What you've done is confusing on the eyes.
Don't fully qualify names unless you have to.

var bindingList = new System.ComponentModel.BindingList<IAttendance>(AttendanceList);

Else where you directly use BindingList, so System.ComponentModel must be in your usings somewhere. Using the fully qualified call clutters the code.
You could extract this duplicated code into its own method.

var bindingList = new BindingList<IAttendance>(AttendanceList);
var source = new BindingSource(bindingList, null);
_View.AttendanceGrid = source;

I don't see anything particularly bad with what you've done, but perhaps I'm inexperienced or lacking larger context. The only thing I might recommend, would be to keep a bindingList around and just call the clear method instead of creating a new instance from scratch all the time. Let me be clear though, I'm not 100% sure that's good advice or any better than "newing it up".


In Widget, the members x and y should be private.  They should not be exposed to the interface in such a way.  You can either add the private keyword above them, or just move the public keyword below them (members are private by default, so both are essentially the same).


Function to add a node with a unique ID and x,y coordinates

def addNode(self, node_id, x, y):
    if self.node_list[node_id] != None:

Since None is a guaranteed singleton, you could use is not None rather than != None.

        raise exception("This node ID already exists.")

If this exception is quite common, assuming this code is part of a tree structure of some sort, you could write a custom exception such as NodeError to handle all such error - that'd be neat.

else:

Is it necessary to have the else here? If the if clause above raises an exception, this block won't be executed anyway; so I'd suggest you should remove this and unindent the code below.

    if self.spacialMatrix[x][y] != None:
        raise exception("This node position is already populated.")

Same thing I mentioned above - is not None and NodeError exception. Also, wouldn't the wrong x and y arguments raise an IndexError? Have you done anything else in the code to ensure that this won't happen?

    else:
        self.spacialMatrix[x][y] = node_id
        self.node_list[node_id] = [x,y]

This part looks good.

My suggestions:

class NodeError(exception):
    """
    For node related errors.
    """
    pass

def addNode(self, node_id, x, y):
    if self.node_list[node_id] is not None:
        raise NodeError("This node ID already exists.")
    if self.spacialMatrix[x][y] is not None:
        raise NodeError("This node position is already populated.")
    self.spacialMatrix[x][y] = node_id
    self.node_list[node_id] = [x,y]

Note: Adding doc strings would be a very good idea!


This seems like a lot of complexity for limited/no value. Could you not just pass an object literal like {lat: 34, long: 84} to the geocoding function and be done with it, losing like 20 lines of code in the process?

A few other thoughts:

Why are you requiring the same dependency twice under different names?
Typically, javascript programmers like to use initial lowercase camel case.  You have several variables named starting with capital letters which may not be desirable.
You have inconsistent use of let vs. var in fluentBuilder. Why have locals defined with let and methods defined with var when both variables are used within the same scope and there is no "inner" code block to which you are trying to limit visibility of locals.  Either one works exactly the same in this case, but it would be good to be consistent.
Your indentation is inconsistent.
Why does fluentBuilder return methods?