Saving class including a container with pickle

The pickle module is fine for such a use case, you just have to be
aware of its limitations.
In particular you'd run into problems in case the current class
definition doesn't match the one of the stored object any more, even
something like a renaming of the class is problematic.

Is there a better approach than my solution? I tried to define the
group_companies as a class variable, but then it won't 'unpickle'
(the group_companies dictionary remains empty).

Well, unless you meant to do a class variable it's fine as it is.  At a
glance I wouldn't expect that pickle on an object of a class would
write out class properties anyway, so this all seems like it should
be.  (It wouldn't make sense to write out class properties every single
time an object that's simply an instance of the class is being pickled,
not to mention reading that data back in every single time.)

The next step will involve changing the group_companies from
dictionaries to classes themselves. Will that still work?

Presumably you'd create a Company class and add that to the
dictionary?  That'd work.  Or if you mean you'd change group_companies from a
dictionary to an object, yes, sure, that will work fine as long as the
pickle module understands the objects (which it will in this case).
That said, the code looks fine.  Two small things I'd perhaps change:

Consider using __str__ instead of __repr__ and the difference in
output between group and print(group) in the REPL
(This is group XYZ and <__main.Group object at 0x...> for the
__str__ variant).  repr should return the "canonical string
representation of the object.  [...] eval(repr(obj)) == obj."  That's
a good guideline for how it should behave, while str is simply for
the printed representation of the object (my words, couldn't find a
quote quickly).

self.group_companies should be initialised from the start in
__init__.  This simplifies add_group_company greatly and will
ensure the object is already in a "valid" state from the start.

Btw. del is a statement, so del group is a bit more explicit in what
it does, removing the group name from the local variable bindings.


Is there a better or more compact way of adding items in treeview using LINQ?

Looks perfectly fine to me. That's the first time I've looked at your code and I was able to see quickly what it does.

There is no need to overly-compact things if it is going to make it a pain for someone else to understand in future.


Finding the elements with the most neighbors

This checks if there is a neighbor of an element and if so, adds it to the count.

import operator
def find_max_letter_in_array(neighborhood):
  all_neighbors_with_count = {}
  for neighbor_set in [pair_of_neighbors for pair_of_neighbors in neighborhood if len(pair_of_neighbors) > 1]:
    for neighbor in neighbor_set:
      all_neighbors_with_count.update({neighbor[0]: 1 if neighbor[0] not in all_neighbors_with_count else all_neighbors_with_count[neighbor[0]]+ 1})

  #return all_neighbors_with_count
  return max(all_neighbors_with_count.items(), key=operator.itemgetter(1))[0]

neigh = [['A'],['A','B'],['A','C'],['B','D'],['C','A']]
print(find_max_letter_in_array(neigh))

output:
#{'A': 3, 'B': 2, 'C': 2, 'D': 1}
A

You can loop over lists with conditions in them so that you only iterate over items you actually need

for each_element in [element for element in list if len(element) > 1]:

Another important part is, you can use dict.update to do both insert and update.
You can use the if statement while doing the assignment of a value  as well

x = y if something_is_true else

At the end, using the operator.max, you can simply your code to get the max element key from dictionary based on all keys' values.

Hope it helps in how you can compress your code.


My self-study inheritance and sub-class exercise

First of all, I'd change how the Point class functions because like David Harkness said, your Point class resembles that of a Line.  I would have it representing two values (x, y) and include functions that would make it easier to find the area of a shape.  Here's an example:

    public class Point {

        public float x;
        public float y;

        public Point(float x, float y) {
            this.x = x;
            this.y = y;
        }

        public static float distanceTo(Point from, Point to) {
            // Distance formula
            return Math.sqrt(Math.pow(to.x - to.y, 2) + Math.pow(from.x - from.y, 2));
        }

Using that point class, I could implement it into a Shape class to centralize a getArea() function.  To have different types of shapes, you could extend the Shape class from other classes and specify how many points each class or override the getArea() function.


You mention accuracy, but talk about the number of bytes, so I'm going to assume that you apply a cut-off point to number of bytes and convert it to binary variable behind the screen. Now the answer:

The reason why the performance is so low is most probably lack of feature engineering. You should definitely inject as much domain knowledge as possible. Let's go over it step by step:

You are, if I understand correctly one-hot encoding IP addressees - however, it could be done in more concise and pythonic way without casting dataframe to matrix:

dummies = pd.get_dummies(df['sourceaddress'], prefix='ip')  # also called one-hot encoding
df = df.merge(dummies, left_index=True)

Protocol should be one-hot encoded as well, as it is a categorical variable.

Now you might want to group IPs by geographic region - this will allow the algorithm to pick up any correlations between not only particular IP but a country or continent. That's how you can add such a feature:

df['region'] = determine_region([df['sourceaddress'])

If you write determine_region(ip) in a way that allows array-wide operations (in other words using numpy), it will be applied to whole dataset at once. This vectorization tends to be faster than .apply, especially for complex functions. And you should also one-hot encode the regions.

Same probably applies to sourceport (not an expert on web technology, so making assumptions here) - there are certain ports that are used in general for some thing and not for others, so another feature that reflects that could be crafted and then one-hot encoded (all your features are categorical so far, tough luck).

Now, speculating here, but maybe combination of region and sourceport is meaningful as well? Really think about anything and everything that might explain the value of your target and create a feature out of that. Then you could choose the most relevant features, using one of the feature selection techniques, but that's not nearly as important as creating features in the first place.
Next, I expect that your dataset is highly imbalanced, which means that your algorithm will be biased towards majority class. What is typically done is rebalancing. Depending on the size of your dataset, you either upsample the minority class (with replacement obviosuly), or downsample the majority class (without replacement, that's important). An example of downsampling when majority class is ~total_bytes - so normal amount of bytes:

df_majority = df[~df['total_bytes']]
df_minority = df[df['total_bytes']]
df_majority_downsampled = resample(df_majority,
                               replace=False,
                               n_samples=len(df_minority),
                               random_state=0)
df_downsampled = pd.concat([df_majority_downsampled, df_minority])

Now the amount of positive and negative examples is equal, so no bias.

Then you should try to tune the hyper parameters. Good way to do that is gridsearch with crossvalidation. Docs are excellent, so no need to explain further here.

Doing all this should improve the performance of your model.


What's up with static?
Your class is build like a utility class:

UtilityClasses are classes that have only static methods that perform some operation on the objects passed as parameters. Such classes typically have no state.

but it's not really one as it has state, you have a $user property you need to pass around, and your functions depend on it. You are writing procedural code using classes, and there really isn't any reason for that, if procedural programming feels more natural with you, go with it, object orientation is not the one true paradigm. PHP supports both paradigms equally, and they are both equally valid.
The only benefit of using static like this is namespacing your functions, but that's not a real benefit as PHP supports namespaces. You should either write your class as an object oriented class, or a set of namespaced utility functions, everything in between is just bad form.
Since you mentioned execution speed, yes calling a static function is faster than instantiating an object and then calling the function, but the difference is in the range of a fraction of a millisecond. A more convincing argument for using static would be memory use, not execution speed, as the instantiated object will take up some memory. Still the argument is moot as there's absolutely no reason to write procedural code with classes, other than perhaps a misguided notion that everything needs to be object oriented.
Public properties
public static $user;

Assuming you rewrite this to be an object oriented class you should avoid public properties, or you'd be breaking encapsulation. All your class properties should be private and accessible through getters and setters, you should even avoid protected if you are not going to extend the class.
Global
global $db;

Don't. Please forget the global keyword even exists, and pass your dependencies through method parameters:
public static function attempt(PDO $db, $username, $password) {
    ...
}

Note the added benefit of type hinting. If you need that PDO object anywhere else in your class, then you should really transform this into an object oriented class and feed the dependency through its constructor:
class Auth {

    private $pdo;

    public function __construct(PDO $pdo) {
        $this->setPDO($pdo);
    }

    public function setPDO(PDO $pdo) {
        $this->pdo = $pdo;

        return $this;
    }

    public function getPDO() {
        return $this->pdo;
    }

    ...

}

Auth::setPDO() and Auth::getPDO() are mutator methods, keeping the class in line with encapsulation and any half decent IDE can generate them automatically for you. Notice that I return $this; in the setter? That's because I like chaining my methods, up to you if you want to follow my style.
Session
$_SESSION is also a global, and suffers from everything global variables do, but given that it's a native (almost) always on global, we can live with it. Obviously your class would be useless if at some point you decide to store session information in a different storage, but let's worry about than when and if it happens. However you need to keep in mind that $_SESSION is an external dependency, and your class needs to compensate for the rare occasion that you forgot to call session_start(). For example this:
public static function login($user_id)
{
    if ($user_id)
    {
        $_SESSION['user_id'] = $user_id;
    }
}

will fail. Either call session_start() before your class definition or in the constructor. In either case, do check if $_SESSION already exists before calling it.
Further reading

Why is Global State so Evil?
SOLID - Don't cheat, read all the linked articles.
Dependency inversion principle
Dependency injection
Inversion of Control Containers and the Dependency Injection pattern
When to Use Static Classes in C# - Not really C# specific, at least not the top voted answer.


var clear map[string]func()

To handle OS specific implementations you may consider using Golang tags feature. See it in action:

flashcard_windows.go

// +build windows

package main

import(
    "os"
    "os/exec"
)

func Clear() {
    cmd := exec.Command("cmd", "/c", "cls")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

flashcard_unix.go

// +build linux

package main

import(
    "os"
    "os/exec"
)

func Clear() {
    cmd := exec.Command("clear")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

To build run go build with -tags windows or -tags linux arguments.

Now there is no need call panic(). go build will exit if implementation of Clear function is missing.

See this for more information.


Compute power set of a given set in Python

Find the appropriate datatype for your problem.

This is actually a problem in the task.
The power set is by definition a set. You use even the variable name power_set so actually it is quite surprising, that it is a list and not a set.

Redundant naming:

It is obvious, that set() is an empty set:
Better use: power_set = [set()]

Don't abbreviate if it is not necessary:

You could write for element in s

Names:

Naming stuff is the hardest part. But I would call a power_set_item simply a subset.

Operators

This is open for debate and perhaps just my taste, but I would use | instead of the union method. This also means to use |= and += instead of update and extend.

Copy

In general the best way to copy is to call the copy method:
new_set = power_set_item.copy().
But in your case it is important to note, that | and .union return a new set, so you could write:

new_sets.append(subset | {element})

All points combined yield the following code:

def get_power_set(s):

    power_set = [set()]

    for element in s:
        new_sets = []
        for subset in power_set:
            new_sets.append(subset | {element})
        power_set.extend(new_sets)

    return power_set

List Comprehension:

As you wrote in your comment, you don't like the new_sets variable. You can easily get rid of it, by using list comprehensions.
In general if you have code like:

A = []
for j in B:
    x = do_stuff(j)
    A.add(x)

Always check if you can't write it in the following way:

A = [do_stuff(j) for j in B]

This gives now the following improvement:

def get_power_set(s):

    power_set = [set()]

    for element in s:
        one_element_set = {element}
        power_set += [subset | one_element_set for subset in power_set]

    return power_set

The line with one_element_set = {element} is to prevent the potentially costly repeated creation of a new object.

Datatype

To come back to the first point. If we take the previous code we can easily change it, to return a set of frozensets:

def get_power_set(s):

    power_set = {frozenset()}

    for element in s:
        one_element_set = frozenset({element})
        power_set |= {subset | one_element_set for subset in power_set}

    return power_set


Unreliable shared memory circular buffer with read-only consumer

Merge cases
In the consumer, you have two separate checks:

            if ((seqno)-1 == count) {
                    /* the message hasn't been completed yet */
                    _mm_pause();
                    continue;
            }

and later:

            if (consumer_count > count) {
                    /* we have incremented the consumer count enough to catch up to the producer */
                    _mm_pause();
                    continue;
            }

Since consumer_count doesn't change in between those two blocks of code, you could move the second check up and merge it with the first one:
            if ((seqno)-1 == count || consumer_count > count) {
                    /* the message hasn't been completed yet, or we have */
                    /* incremented the consumer count enough to catch up to the producer */
                    _mm_pause();
                    continue;
            }

Moving the second check up could actually help you avoid dropping a packet that didn't need to be dropped.


Sleeping and invoking a task in Python 2.X and Python 3.X

You can use next() function in both Python 2.6+ and 3.x. If you need to support Python < 2.6, you can have your own next() function. You can, for instance, check if referring to next throws a NameError and define it if it does:

try:
    next
except NameError:
    _sentinel = object()
    def next(it, default=_sentinel):
        try:
            return it.next()
        except StopIteration:
            if default is _sentinel:
                raise
            return default

Even though getargspec() got deprecated since 3.0, it still can be used and imported. In this case, you can import getfullargspec() and catch the ImportError:

try:
    from inspect import getfullargspec as get_args  # Python 3
except ImportError:
    from inspect import getargspec as get_args  # Python 2

Taking these both points into account, the code would look like:

time.sleep(next(iterator))
if len(arguments) >= len(get_args(task).args):
    task(*arguments)
else:
    print("ERROR: There is a mismatch between the number of"
          " arguments provided in `arguments` and the ones"
          " needed by the task function.")

As far as generally supporting multiple Python versions in a single codebase, six is a must use package.

Also note that instead of using inspect to pre-validate the number of arguments, you can follow the EAFP approach, call the function and handle a TypeError:

>>> f = lambda x, y: 'test'
>>> f(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 2 arguments (3 given)


Creating a basic calculator for integers

Make it robust

Your solution could be a lot more robust. For example, you don't currently validate that x or y are integers - you should check, and if they aren't you should reject them. Additionally, you might want to do some string manipulation of the operator (for example, strip spaces).

It could also be useful to not take strings, but instead create an enumeration (Python 3.4+ Python 3.4-). I'd also advise that you look at the linked stack overflow post from the comments (here for posterity). That makes this into a trivial function, where the only work is in your lookup table.

Use exceptions

Your prompt doesn't define what should happen if you get 0 as the denominator; I'd throw an exception (or if you're using operator let it handle it for you) instead of returning "undefined", as it is much more surprising to get this:

>>> calculate(9, 0, "//") + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

Than it is to get this:

>>> calculate(9, 0, "//") + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in calculate
ZeroDivisionError: division by zero

Additionally, by throwing the expected error other applications that may know how to handle a divide-by-zero event will "just work"TM with your module.

Format your code

Instead of the comment #calculator right above the function definition, which tells us literally nothing, add a docstring that defines inputs, outputs, and purpose of the function.

Additionally, your spacing is a little weird; look up PEP8 and see what it recommends.


Concurrent stack implementations in Ruby (relative performance of mutexes/CAS?)

I took the latest source code from the github and have started review of this project. Here are my benchmarks results:

# Intel(R) Core(TM)2 Duo CPU     P7570  @ 2.26GHz
# ruby 1.9.2p290 (2011-07-09 revision 32553) [i686-linux]
Testing ThreadSafeStack with 1 thread, iterating 1000000x each
  2.250000   0.000000   2.250000 (  2.254392)
Garbage collector ran 0 times
Testing ThreadSafeStack with 5 threads, iterating 200000x each
  2.350000   0.020000   2.370000 (  2.533645)
Garbage collector ran 0 times
Testing ThreadSafeStack with 25 threads, iterating 40000x each
  2.890000   0.780000   3.670000 (  3.170657)
Garbage collector ran 0 times
Testing ConcurrentStack with 1 thread, iterating 1000000x each
  2.840000   0.000000   2.840000 (  2.836545)
Garbage collector ran 54 times
Testing ConcurrentStack with 5 threads, iterating 200000x each
  2.850000   0.010000   2.860000 (  2.871540)
Garbage collector ran 54 times
Testing ConcurrentStack with 25 threads, iterating 40000x each
  2.880000   0.000000   2.880000 (  2.881745)
Garbage collector ran 56 times
Testing RecyclingConcurrentStack with 1 thread, iterating 1000000x each
  3.910000   0.000000   3.910000 (  3.906049)
Garbage collector ran 0 times
Testing RecyclingConcurrentStack with 5 threads, iterating 200000x each
  3.900000   0.000000   3.900000 (  3.910919)
Garbage collector ran 0 times
Testing RecyclingConcurrentStack with 25 threads, iterating 40000x each
  3.960000   0.000000   3.960000 (  4.024026)
Garbage collector ran 0 times

With jruby 1.6.5 (ruby-1.8.7-p330) I encountered a deadlock. With JRruby it is reproduced each time I ran the benchmark, but with MRI I've seed it only once so far. I will try to find the cause and post an update here.

UPDATE

I reviewed the implementation of concurrent stacks and did not found anything that may cause deadlocks or other issues. Looks like deadlock is caused by benchmarking code. With JRuby it just hangs (very frequently). With MRI I received 'deadlock detected' exceptions:

Testing ConcurrentStack with 25 threads, iterating 40000x each
/home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `join': deadlock detected (fatal)
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block (2 levels) in test_with_threads'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `each'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block in test_with_threads'
    from /usr/share/ruby-rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/benchmark.rb:295:in `measure'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:141:in `test_with_threads'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:120:in `test'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:150:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

And

/home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `join': deadlock detected (fatal)
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block (2 levels) in test_with_threads'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `each'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:143:in `block in test_with_threads'
Testing RecyclingConcurrentStack with 1 thread, iterating 1000000x each
    from /usr/share/ruby-rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/benchmark.rb:295:in `measure'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:141:in `test_with_threads'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:118:in `test'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:152:in `block in <top (required)>'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:151:in `loop'
    from /home/alex/Projects/read-write-lock/concurrent-stack.rb:151:in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

As far as I can see, the only thing that may cause deadlock is situation when main thread does QUEUE.broadcast and then does Thread#join on the thread but this thread did not executed QUEUE.wait yet. Then main thread infinitely waits for this thread and MRI may detect such deadlock situation.

When I increased sleep time from 0.001 to 0.01 and more it seemed that deadlock has gone. Looks like this issue is caused by long thread initialization time - sometimes it cannot start block execution for all threads before QUEUE.broadcast call.

Also, as a small improvement, the following code may be extracted into private function like cache_node to improve pop method readability:

FREE_LIST.update do |current|
  node.next = current
  node
end

Stack implementation looks correct and clear, I did not found other issues.

With sleep == 0.05 benchmarks for JRuby are these:

# jruby 1.6.5 (ruby-1.8.7-p330) (2011-10-25 9dcd388) (Java HotSpot(TM) Server VM 1.6.0_26) [linux-i386-java]
Testing ThreadSafeStack with 1 thread, iterating 1000000x each
  2.881000   0.000000   2.881000 (  2.881000)
Testing ThreadSafeStack with 5 threads, iterating 200000x each
  2.658000   0.000000   2.658000 (  2.658000)
Testing ThreadSafeStack with 25 threads, iterating 40000x each
  2.885000   0.000000   2.885000 (  2.885000)
Testing ConcurrentStack with 1 thread, iterating 1000000x each
  2.142000   0.000000   2.142000 (  2.142000)
Testing ConcurrentStack with 5 threads, iterating 200000x each
  1.084000   0.000000   1.084000 (  1.084000)
Testing ConcurrentStack with 25 threads, iterating 40000x each
  0.969000   0.000000   0.969000 (  0.970000)
Testing RecyclingConcurrentStack with 1 thread, iterating 1000000x each
  2.628000   0.000000   2.628000 (  2.628000)
Testing RecyclingConcurrentStack with 5 threads, iterating 200000x each
  1.436000   0.000000   1.436000 (  1.436000)
Testing RecyclingConcurrentStack with 25 threads, iterating 40000x each
  1.473000   0.000000   1.473000 (  1.473000)


Errors in the code

This piece

array(i) > array(pivot) .and. i <= length

is not valid code. If i > length you will get an out of bounds access with array(i).
If you rewrite it as

i <= length .and. array(i) > array(pivot)

it is still wrong, because there is no short circuiting in Fortran. Or to be more precise: Fortran operators are neither short-circuit nor eager. The language specification allows the compiler to select the method for optimization. In your case the compiler reorders and short circuits apparently.
The only way to write it reliably correctly is unfortunately:

if (i <= length) then
    if (array(i) > array(pivot)) then
        ...

A declaration with a number literal like real(kind=8) is not portable. You might think, that it is 8 bytes and/or double precision, but the actual integer value for different kinds is implementation dependent. It just happens to be the case, that gfortran and ifort use the kind value 8 to denote double precision, but on another compiler this might be wrong.
You should always use

integer, parameter :: dp = selected_real_kind(15, 307)

if you want to have a certain range and precision or

use, intrinsic :: iso_fortran_env, only: real64

if you want to have a float with 8 bytes.
(Of course these both will be the same on most architectures today.)

There is no implicit none in the module. Strictly speaking this is not an error and you declared all variables correctly, but code without implicit none should be considered faulty.

Major Code improvements

You should always add one of intent(in), intent(out), intent(inout) to the dummy arguments of your procedures.

Fortran arrays can be declared with arbitrary numerical indices. You implicitly assumed in your code, that they start at 1 (which is the default).
If you want your routine to work with differently indexed arrays, it is necessary to query the upper and lower bounds.

do i = lbound(array, dim=1), ubound(array, dim=1)

This makes it also explicit when you really mean the size, and when the bounds.

What I initially wrote is wrong. If you use assumed-shape arrays, the dummy argument becomes again 1-indexed by default.
Had to learn that myself the hard way. Sorry. :-/

I agree you with you that these <40 lines don't require comments for the most parts, but you can write it more readable without comments, by defining a swap subroutine. This would also reduce the clutter of local variables.

If you define a get_pivot function, it will be easy to change to different pivoting strategies.

You have superfluous assignments to length in your code.
IMHO you don't need this variable anyway, because you can insert size(array) at every appearance. Any decent compiler will do common-subexpression-elimination on these calls.

Where possible I would use pure and elemental on your procedures.
They are amazing. ;-)

Architecture

I would always make all names in a module private and export explicitly with public. On the other hand I would only import used names.

In the long run, you want to have a second argument where one can pass a pure logical function that compares two elements. Doing so, the user can sort according to his/her constraints.

Formatting

Thank you for writing Fortran and not FORTRAN code.
If you don't scream at people it is much easier to read your code. ;-)

Of course this is opinion based so, whatever I say, stick to the style of your environment. But for example the whitespace around your binary operators was not consistent. An indentation of two spaces is IMHO too short.

I assume that you are from science and you and your peers use python. In this case it is quite easy to stick to the python formatting guidelines in Fortran.

Minor Code improvements

I agree that the code mostly does not require comments,
but at least public functions of a module should get a docstring on how to use them.

size in the program can be made constant.

The upper and lower bound in array slices can be ommited A(lbound(A, 1) : 5) == A(: 5)

I would not use p as program name. If you do so, you can't use it as variable name anymore.

There is random_number to generate an array of real numbers.

Possible improved version

module sort
    implicit none
    private
    public :: dp, qsort
    integer, parameter :: dp = selected_real_kind(15, 307)

    abstract interface
        logical pure function compare_t(a, b)
            import :: dp
            real(dp), intent(in) :: a, b
        end function
    end interface

contains

    !> @brief
    !>      Sort array inplace according to comparison function comp.
    !>
    !> @details
    !> The comparison function has to be a pure, logical function
    !> that compares two elements of array in a strict partial order.
    !> That means equality has to evaluate to false.
    pure recursive subroutine qsort(array, comp)
        real(kind=dp), intent(inout) :: array(:)
        procedure(compare_t) :: comp

        integer :: pivot, i, j

        i = 0
        j = 0
        pivot = get_pivot(array)
        if (size(array) > 1) then
            i = lbound(array, dim=1)
            j = ubound(array, dim=1)
            do while (i <= j)
                do while (comp(array(i), array(pivot)))
                    i = i + 1
                end do
                do while (comp(array(pivot), array(j)))
                    j = j - 1
                end do
                if (i >= j) exit
                call swap(array(i), array(j))
                i = i + 1
                j = j - 1
            end do
            call swap(array(pivot), array(j))
            call qsort(array(: j - 1), comp)
            call qsort(array(j + 1 : ), comp)
        end if
    end subroutine qsort

    pure subroutine swap(a, b)
        real(dp), intent(inout) :: a, b
        real(dp) :: temp
        temp = a
        a = b
        b = temp
    end subroutine

    pure function get_pivot(array) result(res)
        real(dp), intent(in) :: array(:)
        integer :: res
        res = lbound(array, dim=1)
    end function
  end module sort

program test_qsort_procedures
    use sort, only: dp, qsort
    implicit none
    integer, parameter :: size_ = 100
    real(kind=dp), allocatable :: b6(:)

    allocate(b6(size_))
    call random_number(b6)

    print *, "unsorted: ", b6
    call qsort(b6, increasing)
    print *,"increasing a= ", b6
    call qsort(b6, decreasing)
    print *,"decreasing a= ", b6

    contains

    logical pure function increasing(a, b)
        real(dp), intent(in) :: a, b
        increasing = a < b
    end function

    logical pure function decreasing(a, b)
        real(dp), intent(in) :: a, b
        decreasing = a > b
    end function
end program test_qsort_procedures


How to speed up the code for LeetCode "Container with most water" task?

My suggestion about your current solution:
def max_area(height) -> int:
    areas = []
    coords = {x: (x, y) for x, y in enumerate(height)}
    for x in coords:
        higher = [k for k in coords if coords[k][1] >= coords[x][1]]
        area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1]
        areas.append(area)
    return max(areas)

Keep track of the biggest area so far, instead of using the list areas.

def max_area(height) -> int:
    coords = {x: (x, y) for x, y in enumerate(height)}
    result = 0
    for x in coords:
        higher = [k for k in coords if coords[k][1] >= coords[x][1]]
        area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1]
        result = max(result, area)
    return result

This reduces memory usage but is not enough to pass the challenge.
The solution can be considered a brute force approach which is typically not enough to solve medium/hard problems on LeetCode.
The constraint is \$n <= 3 * 10^4\$, where \$n\$ is the length of the input list. Generally, with such constraint, we should look at a solution with a time complexity less than \$O(n^2)\$.
Let's consider the example on LeetCode where the input list is:

height = [1,8,6,2,5,4,8,3,7]

For each two bars, the biggest area is given by the lowest bar. In the example, the two bars are 8 and 7, so the area is 7 * (8 - 1) = 49. Note that (8 - 1) is the difference between the indices of the bars. This is an \$O(n)\$ algorithm:
Initialize l to 0
Initialize r to the right most index
Initialize max_area to 0
while l is lower than r
    find the area as: lowest bar * (r - l)
    update max_area
    increment l if points to the lower bar, else decrement r
return max_area

Next time you can check the "hints" and the tab "Discuss" for help or alternative solutions.


I'll echo what 200_success said about the schema. But working with what you have, I would think breaking it down into two steps (via temp table if this is a one-time aggregation, or via a view if repeat query) may improve performance. Then just perform your SUM() operations on the temp table/view. Preferably though, I would think a better organized schema would be more useful, but this may not be an option in your situation. I would also use a more explicit JOIN to reduce the amount of guessing the SQL engine has to do. I'm less familiar with what seems to be Oracle syntax but here is my take on it based on SQL Server syntax. Anyone else feel free to correct any Oracle-related syntax errors I make.

-- Create temp table, leaving out group by clause
select || d.ntt_id || '_' || d.deal_nummas, p.*
INTO #tmp_nummas
from profiles p
inner join deals d on d.deal_id = p.deal_id and d.deal_scope='Y'
inner join runs r on r.deal_cnt_id = d.deal_cnt_id
where r.run_id=7 and d.deal_nummas!=0 and d.deal_nummas is not null;

-- Perform operation
select 'Master' ntt_id || '_' || deal_nummas, prof_currency
sum(prof_ts1), sum(prof_ts2), sum(prof_ts3), sum(prof_ts4), sum(prof_ts5),
sum(prof_ts6), sum(prof_ts7), sum(prof_ts8), sum(prof_ts9), sum(prof_ts10),
sum(prof_ts11), sum(prof_ts12), sum(prof_ts13), sum(prof_ts14), sum(prof_ts15),
sum(prof_ts16), sum(prof_ts17), sum(prof_ts18), sum(prof_ts19), sum(prof_ts20),
sum(prof_ts21), sum(prof_ts22), sum(prof_ts23), sum(prof_ts24), sum(prof_ts25),
sum(prof_ts26), sum(prof_ts27), sum(prof_ts28), sum(prof_ts29), sum(prof_ts30),
sum(prof_ts31), sum(prof_ts32), sum(prof_ts33), sum(prof_ts34), sum(prof_ts35),
sum(prof_ts36), sum(prof_ts37), sum(prof_ts38), sum(prof_ts39), sum(prof_ts40),
sum(prof_ts41), sum(prof_ts42), sum(prof_ts43), sum(prof_ts44), sum(prof_ts45),
sum(prof_ts46), sum(prof_ts47), sum(prof_ts48), sum(prof_ts49), sum(prof_ts50),
sum(prof_ts51), sum(prof_ts52), sum(prof_ts53), sum(prof_ts54), sum(prof_ts55),
sum(prof_ts56), sum(prof_ts57)
from #tmp_nummas
group by ntt_id, deal_nummas, prof_currency;


Unused Loop Variables

for i in range(self.n):
    self.job_queue.put(None)

can be written like this

for _ in range(self.n):
    self.job_queue.put(None)

and any place where you don't use the loop variable. The _ lets you and other programmers know that that variable isn't used and should be ignored.

Naming

p should be process to be descriptive. While p in self.processes can be obvious, it's good to get in the practice of descriptive variable names.

Type Hints

This

def add_task(self, task_id, task, arg_list):

can instead be (assuming task is a str and arg_list is a list)

def add_task(self, task_id: int, task: str, arg_list: list) -> None:

Using type hints allows you to see/show what types of parameters are accepted, and what type(s) is/are returned from the function.


Evaluating formulas greater than 255 characters

The function is implicitly public, takes an implicitly ByRef parameter that has no reason to not be passed ByVal, and returns an implicit Variant that should be explicit.

It's also side-effecting, which makes it unusable as an actual UDF.

ThisWorkbook.Worksheets("Scripting Worksheet") suggests the procedure is using a purposely-made bogus (hidden?) sheet just for that. So why does that sheet need to be dereferenced 3 times in the same scope? Give it a meaningful code name, and use it!

Public Function AdvancedEvaluate(ByVal expression As String) As Variant
    With ScriptingSheet.Range("A1")
        .Formula = expression
        AdvancedEvaluate = .Value
        .ClearContents
    End With
End Function

Now, that's the exact same logic, just more explicit and unnoticeably more efficient in the handling of object references.

To the extent that the idea is to somehow get Excel's calc engine to do the work, other than getting the Excel devs to lift the 255-char limitation in the object model, I think that's as good as it's going to get. It's not a UDF though: in Excel a User-Defined Function refers to a function that can be invoked from a cell - but this function will only ever return an error value to Excel; VBA code can merrily consume it though.


Class for measuring distance as feet and inches

When designing a class for your program, whether it's for homework or a real production application, you want to always consider how that class is going to be use and what its responsibilities should be. Each function and method should do one thing/task and it should be reflected by the method's name. Additionally, you want to keep to a consistent easy-to-read coding style when you actually start writing the code. With those two points in mind here's some things to consider in your code:

Distance::distanceSum is doing two tasks here.

It's not only summing feet and inches but it's printing them out as well.

Unnecessary type conversion.

In your default Distance() ctor, there's an implicit conversion because you're assigning 0 to a float type. You should have gotten a warning from your compiler. Consider using an initializer list like so:

Distance::Distance() : feet(0), inch(0.0)
{
}

Code doesn't take advantage of const correctness.

Which parameters aren't suppose to change? Which methods will be modifying your Distance class? For example, your Distance::Distance(int a,float b) isn't changing a or b. Have the compiler enforce that promise by using const:

Distance::Distance(const int a, const float b)

Similiarly:

void Distance::distanceSum(const Distance &d);

Inconsistent indentation and spacing.

Consider indenting the methods under public: the same way you did with private:. Add spaces to your assignments to help readability. eg. feet = a;

No module separation by file.

class Distance should probably be in a separate header/implementation file rather than putting everything in one main file.

Ninja comments.

Comments? What comments? Exactly. Consider adding a block comment at the top of your Distance class that explains the purpose for its existence. The block comment should answer questions like how is this class suppose to be used and what details is it abstracting away? Adding a comment to clarify how the feet and inch data members are going to be used. For example, it's not clear if your distance class is maintaining the same distance measurement but with different units or it's really meant to be used as one whole unit. eg. 6 feet 2 inches or 6 feet 72 inches?

With the above considerations, here's one way I would refactor your code:

In distance.h header file:

#ifndef DISTANCE_H
#define DISTANCE_H
class Distance
{
    private:
       // feet and inch is one unit.
       // invariant: inch_ < 12.
       int   feet_;
       float inch_;
    public:
       Distance(const int feet = 0, const float inches = 0.0);
       void      setDistance(const int feet, const float inches = 0.0);
       int       getFeet() const;
       float     getInch() const;

       // returns this instance. Permits method chaining for Distance class.
       Distance& Add(const Distance &d);
};
#endif

In distance.cpp implementation:

#include "distance.h"
Distance::Distance(const int feet, const float inches)
         : feet_(feet + inches / 12), inch_(inches % 12)
{
}

void Distance::setDistance(const int feet, const float inches)
{
    feet_ = feet + inches / 12;
    inch_ = inches % 12;
}

int Distance::getFeet() const
{
    return feet_;
}

float Distance::getInch() const
{
    return inch_;
}

Distance& Distance::Add(const Distance &d)
{
    setDistance(getFeet() + d.getFeet(), getInch() + d.getInch());

    return *this;
}

Here are the major changes above:

Distance no longer uses cin/cout for explicit IO. You can push that code into main.
class definition and implementation are now in their respectively named files.
Removed an extra constructor definition by taking advantage of default parameters.
feet and inch data members are used together to represent the measurement in distance. inch cannot be > 12 because that would mean there's enough for a foot. We enforce this by dividing feet and inches by 12 when setting distance's data.
const is used to clearly indicate what can and can't change the distance object.
Changed distanceSum to Add to better reflect what it's doing. Notice that Add is implemented only through Distance's public methods -- it does not manipulate feet_ and inch_ directly.


You code is well-written.
You may want to

add a docstring to the function
rename the loop variable i to _, since it is not being used.

You may also want to consider using itertools.repeat, which is said to be slightly faster than for _ in range(N).


Array view adaptor class for static polymorphism over network header parsing

Could be more generic

Let's consider one of your constructors:

template<std::size_t N>
basic_array_view(const std::array<T, N> &a) noexcept :
    array(a.data()),
    len(N)
{}

I don't see any particularly good reason this should/must be restricted to being used with an std::array. I think I'd write the code more like this:

template<class Container>
basic_array_view(Container const &a) noexcept :
    array(a.data()),
    len(a.length())
{}

Now it can be used with an std::array or other containers like std::vector, std::deque, etc.

Incomplete

The basic point of something like an array_view is (at least usually) to provide the same interface as existing collections. It does provide a substantial part of that, but it's missing a number of things like as the normal typedefs for value_type, reference_type, iterator_type, and so on. It's also missing iterator access to the contents; given that you're dealing with a contiguous array, that can be provided quite trivially (begin() and end() that return pointers to beginning and one past the end respectively). The latter would allow use with standard algorithms and such as well.

Naming

I'd try to pick one naming convention and stick with it. Either snake_case throughout or PascalCase throughout--but combining array_view with StreamLikeArrayView is somewhat jarring.

I also think subview_right is kind of a poor name--it seems as if subview is entirely adequate.

Duplication

In some ways this is the biggest question of all. You could get the functionality of your StreamLikeArrayView by simply dumping the data into a stringstream, and letting your existing code read from there. The (primary?) gain is that you avoid copying the data as you would with a normal stringstream.

If your real intent is to provide functionality like a stringstream's, but avoiding copying by having it use a buffer that isn't owned by the streambuf, then I think it would be better to provide that more directly:

struct array_buffer : public std::streambuf {
    array_buffer(char const *begin, char const *end) {
        char *b = const_cast<char *>(begin);
        char *e = const_cast<char *>(end);

        setg(b, b, e);
    }

    template <class Container>
    array_buffer(Container const &c) : array_buffer(&*std::begin(c), &*std::end(c))
    { }
};

[I should add: this is also somewhat incomplete--it doesn't try to support all possible stream buffer operations, but it supports at least as much as the classes above.]

To go with that, we can provide a stream class to save the user some work in constructing a stream based on our buffer type:

class buffer_stream : public std::istream {
    array_buffer buf;
public:
    template<class... Args>
    buffer_stream(Args&&... args) : buf(std::forward<Args>(args)...), std::istream(&buf)
    { }
};

To go with that, some demo code to show how we can build an istream of this type from any of a number of sources, and how the usual ways of reading from an istream work with this istream:

int main() {
    char input[] = "This is some input";

    // Create a buffer stream reading from an array
    buffer_stream b(input);

    std::string s;

    // Do some normal stream reading from it:
    while (b >> s)
        std::cout << s << "\n";

    // Create another from an `std::array`, read some from it:
    // Sorry, but I'm too lazy to hand-craft a very interesting array here:
    std::array<char, 3> more_input { 65, 66, 67 };

    buffer_stream c(more_input);

    while (c >> s)
        std::cout << s << "\n";

    // Create one from a string and read from it:
    std::string still_more_input { "This is the last piece of input" };

    buffer_stream d(still_more_input);

    // Read the first few words:
    char buffer[11];
    d.read(buffer, sizeof(buffer));
    std::cout.write(buffer, sizeof(buffer));
    std::cout << "\n";

    // Skip " last "
    d.ignore(6);

    // Then read the remainder into a string:
    std::getline(d, s);
    std::cout << s << "\n";
}

The obvious advantage of providing a class derived from istream is that it works with essentially everything that reads from an istream, not just with a couple of your own select functions that template the stream-like object, and restrict themselves to two specific ways of reading from the stream.

The obvious disadvantage of this approach is that is probably adds more overhead, and some people (especially anybody who hasn't delved into streams, buffers, etc.) may find it harder to understand. There's also the fact that by being a stream buffer class, people may assume this supports everything that any stream buffer might, which is a bit more than it actually delivers.


Ehh, let's look at the biggest issue here: the SQL-Injection vulnerability.

$object = json_decode(file_get_contents("php://input"), true);

if (isset($object['email']) && isset($object['password']) && isset($object['firstName']) && isset($object['lastName'])) {
    $email = $object['email'];

    $validationQuery="select * from members where email='$email'";

All I have to do is provide a bad string in that JSON for email and now I can destroy your database easy.

Solution: prepared statements.


Making a selection in a dropdown based on several possible values

If speed is important, then you should avoid unnecessary dom lookups.
For example,
if sizeVal is not undefined, then you'll never need another dom lookup for sizeVal2.
You can rearrange the code accordingly:

    var sizeVal = $("#size option").filter(function() {
        return $(this).html() == sizePref;
    }).val();

    if (sizeVal !== undefined) {
        $("#size").val(sizeVal);
    } else {
        var sizeVal2 = $("#size option").filter(function() {
            return $(this).html() == "L";
        }).val();
        $("#size").val(sizeVal2);
    }

I would go even further an cache the $("#size option"),
and also move the repeated logic into a function:

var options = $("#size option");

function findSize(target) {
    options.filter(function() { return $(this).html() == target; });
}

var size = findSize(sizePref).val() || findSize("L").val();
var $("#size").val(size);


Write into the same CSV file multiple times

If you want to avoid the creation of the *Writers on each call of writeToCsvFile() method, one of solutions would be as follows.

Change OutputWriterService class to implement AutoCloseable interface. This will allow to put its instances into a try-with-resources block. The Writers created inside the original method will become constants in the changed class and they will be closed inside the close() method when the routine exits from the block (normally or with an exception):

public class OutputWriterService implements AutoCloseable {

  private static final String FILE_NAME = "FILE";

  private final FileWriter fw;
  private final BufferedWriter bw;
  private final PrintWriter out;

  public OutputWriterService() throws IOException {
    this.fw = new FileWriter(FILE_NAME, true);
    this.bw = new BufferedWriter(fw);
    this.out = new PrintWriter(bw);
  }

  @Override
  public void close() throws IOException {
    this.fw.close();
    this.bw.close();
    this.out.close();
  }

  public void writeToCsvFile(List<CustomTypeDescription> descriptions){
    // ...
  }

}

writeToCsvFile() method becomes shorter:

public void writeToCsvFile(List<CustomTypeDescription> descriptions){
  try {
    for(CustomTypeDescription description : descriptions){
      out.println(description.toString());
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

By the way, the code of the original createOutputFile() method looks very suspicious. A cleaner way would be to use

Files.createFile(Paths.get(FILE_NAME));

The instance of the BufferedWriter can also be created differently:

Files.newBufferedWriter(Paths.get(FILE_NAME),
                        StandardCharsets.UTF_8,
                        StandardOpenOption.APPEND);

This makes the FileWriter instance unnecessary.

Now, the user of your OutputWriterService class should proceed as follows:

try (OutputWriterService service = new OutputWriterService()) {

  // May be called as many times as desired, depending on the algorithm
  // The same instances of the writers will be reused.
  service.writeToCsvFile(descriptions);

} // + process the exception or rethrow it


Are nested fmap calls idiomatic Haskell?

Sometimes you can wrap the "nested functors" in a newtype which is itself a functor, use a single fmap on the newtype, and unwrap. In your case:

import Data.Functor.Compose

let z = getCompose . fmap (:[]) . Compose $ text

We are composing the ((->) s) and Scraper a functors.

The problem with this is that it trades newtype noise for nested fmap noise.


How to fill in this HashMap neatly without code duplication?

Then I would use a static method to put the entries in the map:

HashMap<String,MyClass> myHashMap = new HashMap<String,MyClass>();
addEntry(myHashMap, "foo",2,4);
addEntry(myHashMap, "bar", 0,10);
addEntry(myHashMap, "a", 0,0);
addEntry(myHashMap, "b", 0,1);
addEntry(myHashMap, "c", 0,0);
addEntry(myHashMap, "d", 0,42);
// ...

private static //
void addEntry(HashMap<String,MyClass> map, String name, int arg1, int arg2){
  map.put( name, new MyClass(arg1,arg2) );
}

I recommend reading the data from a file and call addEntry(myHashMap, ...); in a loop until end of file is reached.


Code readability is a subjective quantity, however it is still considered as on-topic here at Code-Review.
General readability points
Note that code in isolation is must rely on presumptions. The scope, naming, and missing defines may force some of the following points to change if known.

Use simplest statements possible. For example the statement if (!isMulti) { can be simplified to if (isMulti) { and swapping the code blocks.

Avoid breaking lines unless they extend past the right of screen.
Some people use 80 columns (a little last century in my book (word warp is standard in IDE's these days)), 120 or even 160 will be readable in all but the smallest of devices.

Avoid repetition. You test isAddress twice within the listener. This can be done once outside the returned function. See rewrite.
This may not be considered a readability issue, but part of good code readability is clearly showing intent.
To read the two lines testing isAddress I immediately questioned why in the event? This is already known? I had to check as your intent was muddied.

The function onFieldChange is not an event listener, it returns a listener. The the prefixed on obfuscates its usage.
The name would be better as just createFieldChangeEvent, fieldChangeListener, or fieldChange depending on the functions scope.

Semicolons go a long way to improve readability, especially for coders that are swapping between C like languages.

The string literals should be constants, however without the full scope and usage of these strings it is hard to define where and how to declare. So I leave them as is (apart from changing to double quotes)

Rewrite
Two rewrites to contrast the subjective nature of readability.
General rewrite
Using the above points the code can be rewritten as
const fieldChangeListener = (key,  index = 0, isMulti = false, isAddress = false) => {
  const [field, internalKey] = isAddress ? [key, "addresses"] : ["value", key];
  const isTypeKey = key === "type";
  return event => {
    const value = event.target.value;
    const updated = {...contact};
    if (isMulti) {
      updated[field][index][internalKey] = value;
    } else {
      updated[key] = value;
      const isTypeIndividual = value === "Individual" && isTypeKey;
      if (isTypeIndividual && contact.entityFormationDate) {
        delete updated.entityFormationDate;
      }
    }
    setContact(updated);
  }
}

Is it more readable. We that depends on the readers level of experience and skill.
Compact rewrite
Personally I would have compacted the code further as its the total quantity (lines of code) that make code navigation the crucial readability factor. Code is seldom read in isolation.
const fieldChange = (name,  idx = 0, isMulti = false, isAddress = false) => {
  const [internal, fieldName] = isAddress ? ["addresses", name] : [name, "value"];
  const isType = name === "type";
  return event => {
    const [updated, value] = [{...contact}, event.target.value];
    if (isMulti) {
      updated[fieldName][idx][internal] = value;
    } else {
      const canDelete = (updated[name] = value) === "Individual" && isType;
      canDelete && contact.entityFormationDate && (delete updated.entityFormationDate);
    }
    setContact(updated);
  }
}

Defined readability
Code readability is very dependent on code standards used in projects. Standards must be defined in writing.
This is a document that all project coders should be thoroughly versed in and defines the styles, naming, layout, language features, etc... used and not to use in each project.
It can be argued that a comprehensive code standards document makes it impossible to write unreadable code.
To start a project without a standards document has already failed the first rule of readability. "Subjectivity is unreliable".
Example standards (as un-categorized points) I used for "Compact rewrite"

Fields to have names not keys.
index is always written idx.
Short circuited end clauses must be grouped.
Single line expression with multiple assignments must group each assignment.
Use semicolons.
Prefer declarations using destructuring assignments over multi-line declarations.


Your implementation is pretty similar to this one: https://programming-pages.com/2012/01/31/binary-search-in-clojure/

I think the overall algorithm is OK.
You should avoid using def inside function - that should be used only for global top-level vars -> use let instead.
Also, the code formatting is incorrect - use 2 spaces and proper indentation:

(defn log-search
  [elements elem-to-find]
  (loop [left 0
         right (dec (count elements))]
    (when (<= left right)
      (let [m (int (Math/floor (/ (+ left right) 2)))
            actual (nth elements m)]
        (cond
          (= actual elem-to-find) m
          (< actual elem-to-find) (recur (+ m 1) right)
          (> actual elem-to-find) (recur left (- m 1)))))))


This is basically a canonicalizing URL prettifier that redirects clients to a shorter URL.

The RewriteCond operating on %{THE_REQUEST} is weird, since it works directly at the HTTP protocol level.  I understand that you want to avoid redirecting POSTs, since a redirect would convert POSTs into GETs, and such breakage would be an unacceptable consequence for having nicer-looking URLs.  However, it would be better to test %{REQUEST_METHOD} instead.

In the worst case, you could end up redirecting the client three times:

GET /path/to/directory/index.php/:
GET /path/to/something/index.php
GET /path/to/something/index
GET /path/to/something

By combining the first two rules, you could eliminate the third request.

# Strip off /index.php or /index or .php
RewriteCond %{REQUEST_METHOD} =GET
RewriteRule (.*)(/index\.php|/index|\.php)$ $1 [R=301,L]

In the trailing slash cleanup, you have a superfluous RewriteCond:

# Remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)/$ $1 [R=301,L]

I would tweak your last rule a bit.  Do the string analysis check before the filesystem check.  Use $0 instead of %{REQUEST_URI} and $1.

RewriteCond $0 !(/|\.php)$
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php


Python function to match filenames with extension names

.endswith() accepts a tuple:

#!usr/bin/env python
import os

fileextensions = ('.doc', '.o', '.out', '.c', '.h')
for filename in os.listdir(os.curdir):
    if filename.endswith(fileextensions):
       print(filename)


HackerRank "Manasa and Stones" in Python

Since a, b can be equal, I wrap this list into a set to produce my
  code below.

Why not just handle this case separately? It's then simple to prove that if a != b, we don't have repeated values, and we can just generate them in increasing order.

def last_stone(a, b, n):
    if a == b:
        return [a * (n - 1)]
    if a < b:
        return last_stone(b, a, n)
    return [i * a + (n - i - 1) * b for i in range(n)]


Inner Join only if satisfies If condition

I did something like this

CREATE PROCEDURE [dbo].[spGetItemCategory] (@ShopID INT)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT ItemCategory.ItemCategoryID
        ,CategoryName
    FROM ItemCategory
    INNER JOIN ShopitemCategory ON (
            ShopitemCategory.shopid = @ShopID
            AND ShopitemCategory.itemcategoryid = ItemCategory.ItemCategoryID
            )
        OR (@ShopID = 0)
END


Indentation

You should indent 4 spaces. Here's the PEP 8 guidelines on this.

Equality

Instead of

while (sum(player) <= 21 and stay == False and play_again == True):

do this

while(sum(player) <= 21 and not stay and play_again):

You don't need to == True/False, as those variables will equate to those boolean values already within the statement. This applies to other parts of your program as well.

Operator spacing

There should be a space before and after every operator (+ - * / =, etc.) in your program. This increases readability and makes your code look nicer.

Unnecessary parentheses

You don't need parentheses around simple if statements, unless you're trying to group specific conditions with each other. But something like this:

if (str_bet == ''):

should just be this

if str_bet == '':


Algorithm to remove duplicates array leaving at most 2 elements

You're just reimplementing collections.Counter.

def remove_duplicates(lst):
    return sum(min(x, 2) for x in collections.Counter(lst).values())

By the way, \$O(2n)\$ is equivalent \$O(n)\$. However, the bound is actually tighter: \$O(n + m)\$, where m is the number of distinct elements.

This is, however, an average bound, because it relies on a dict. If the worst case hash collisions happen, you get \$O(m(n+m))\$


A Get method for an API, with three modes

Let's think about what your possible URIs would look like.

http://example.com/WorkItem?id=5
http://example.com/WorkItem?id=5&scope=GetAll

That's not how I'd expect the API to work. Typically, calling the resource without an id will return all of them.

// returns all work items
http://example.com/WorkItem

// returns work item by id
http://example.com/WorkItem/5

And then, to get the details for an item, we add an action to the end of the URI.

// returns details for specified item
http://example.com/WorkItem/details/5

To get the last part, you'll need to wire up a custom route, but it's not that difficult to do. You can then overload the Get methods to implement this. It's a much cleaner API to work with and, honestly, results in a much cleaner & maintainable controller.

I take it back, you won't need a custom route. MVC comes "out of the box" with a {controller}/{action}/{id} route, so for the Detail route, all you need to do is create the proper method.

[HttpGet]
public async Task<IEnumerable<WorkItemDto>> Details()

And

[HttpGet]
public async Task<IEnumerable<WorkItemDto>> Details(int id)

Will give you routes that look like this.

http://example.com/WorkItem/Details
http://example.com/WorkItem/Details/5


Which linq statement is better to find there is an overlap between two lists of ints?

Assuming LINQ to objects (i. e. these are in-memory collections not LINQ to Entities IQueryables or something):

  Will statement 2. call GetMyListB() for each item in ListA?

Yes. If you want to avoid this, you'll have to store the result of GetMyListB() outside the function.

  Which is more readable?

In my opinion two are about equally readable, although I would change #2 to be:

bool overlap = GetMyListA().Any(GetMyListB().Contains); // 2.

As far as performance, #1 will probably perform better in most cases, since it will dump all of one list into a hash table and then do an O(1) lookup for each element in the other list. Two exceptions to this that I can think of are (1) if the lists are very small, then building the hash table data structure might not be worth the overhead and (2) option 2 can theoretically return without having considered every element in either list. If the lists are large lazy enumerables and you expect this to return true in most cases then this could lead to a performance increase.


Enumerating AWS instances in Rails, with error handling

The rescue in your fetch_aws_instances method is pointless. Rescuing errors just to re-raise them identically, is the same as not rescuing them at all.

You should only rescue when you want to customize what happens if the error is raisedd. Unless you want to move the Rails.logger calls to the fetch_aws_instances method, you should only have the rescues when you call it (as you do in your second code block)


Your implementation will not produce correct results in general.

In the base case of b = 0, result should be 0.  In the case of even b, result is double a times half b (which you have done correctly).  In the case of odd b, result should be a + (double a times half (b - 1)).

(define (times a b)
  (cond ((= 0 b) 0)
        ((even b) (times (double a) (halve b)))
        (else (+ a (times (double a) (halve (- b 1)))))))

To make this definition iterative, add an accumulator, like so:

(define (times a b)
  (times-iter 0 a b))

(define (times-iter acc a b)
  (cond ((= 0 b) acc)
        ((even b) (times-iter acc (double a) (halve b)))
        (else (times-iter (+ a acc) (double a) (halve (- b 1))))))


Checking if entity exist in Google App Engine Datastore using JPA 1

It looks fine. You could omit the boolean flag if you return immediately when you know the answer:

public boolean isExist(final String genreName) throws PersistenceException {
    final EntityManager em = EMF.get().createEntityManager();
    try {
        final Genre genre = em.find(Genre.class, genreName);
        if (genre != null) {
            return true;
        }
        return false;
    } finally {
        em.close();
    }
}


Implementation of API to create a company account in a database

Prelude

I'll assume the following code :

trait BaseModel{
  def pk:String
  def id:String=pk
}
case class Account(name:String) extends BaseModel{
  override val pk = name
}

As the internal structure of the Account class. I made it extends BaseModel so it can be used with the following fake DAO and my sample compiles. I had to add an insert which takes both an Account and a company Id.

class AccountDAO extends CRUDDAO[Account]{
  override def insert(model: Account): Future[Any] = Future.successful(model)

  def insert(model: Account,companyId:String): Future[Any] = model.id match{
    case "account1"|"account2" => Future.successful(model)
    case _ => Future.failed(new RuntimeException("Unable to save account"))
  }

  override def update(model: Account): Future[Int] = ???

  override def get(pk: String): Future[Option[Account]] = pk match {
    case "account1" => Future.successful(Some(Account(pk)))
    case "account2" => Future.successful(None)
    case _ => Future.failed(new RuntimeException("no such account"))
  }

  override def all: Future[Seq[Account]] = ???

  override def all(page: Int, perPage: Int): Future[Seq[Account]] = ???
}

I made the original code sample compile by adapting the bottom of the code as Created(account) wouldn't compile here is what it looks like.

Initial code

class Companies @Inject()(primaryDAO:AccountDAO)(implicit ec:ExecutionContext) extends Controller {
  implicit val AccountReads = Json.format[Account]

  def create = Action.async { implicit request =>
    if (request.body.asJson.isEmpty) {
      Future.successful(BadRequest("Missing body"))
    }
    else {
      val body = request.body.asJson.get.as[JsObject]
      val companyID = (body \ "company" \ "id").validate[String]
      val parsedAccount = (body \ "account").validate[Account]

      // Check that we have all of the fields we need
      if (parsedAccount.isError) {
        Future.successful(BadRequest("Missing account data"))
      } else if (companyID.isError) {
        Future.successful(BadRequest("Missing company data"))
      }
      else {
        // Insert the new account
        val account = parsedAccount.get
        (for {
          _ <- primaryDAO.insert(account, companyID.get)
          account <- primaryDAO.get(account.id)
        } yield account).map {
          case Some(a) => Created(a.id)
          case None => InternalServerError("Unable to create Account")
        }.recover {
          case e => BadRequest(e.getMessage)
        }
      }
    }
  }
}
object Companies extends Companies(new AccountDAO)(play.api.libs.concurrent.Execution.defaultContext)

Following are some sample request/reponses using httpie:

$> echo '{"company":{"id":"1"}, "account":{"name":"account1"}}'| http :9000/foobar
HTTP/1.1 201 Created
Content-Length: 8
Content-Type: text/plain; charset=utf-8
Date: Thu, 28 Apr 2016 20:17:19 GMT

account1

$> echo '{"company":{"id":"1"}, "account":{"name":"account2"}}'| http :9000/foobar
HTTP/1.1 500 Internal Server Error
Content-Length: 24
Content-Type: text/plain; charset=utf-8
Date: Thu, 28 Apr 2016 20:18:45 GMT

Unable to create Account

$> echo '{"company":{"id":"1"}, "account":{"name":"account3"}}'| http :9000/foobar
HTTP/1.1 400 Bad Request
Content-Length: 22
Content-Type: text/plain; charset=utf-8
Date: Thu, 28 Apr 2016 20:21:19 GMT

Unable to save account

$> echo '{ "account":{"name":"account3"}}'| http :9000/foobar
HTTP/1.1 400 Bad Request
Content-Length: 20
Content-Type: text/plain; charset=utf-8
Date: Thu, 28 Apr 2016 20:21:44 GMT

Missing company data

$> echo '{"company":{"id":"1"}, "account":{}}'| http :9000/foobar
HTTP/1.1 400 Bad Request
Content-Length: 20
Content-Type: text/plain; charset=utf-8
Date: Thu, 28 Apr 2016 20:22:07 GMT

Missing account data

Embracing the HTTP framework

Now there is a way to write this using early returns, I'll show it for completeness sake but you really really don't want to do that as I'll explain below. Return doesn't have a type so you are forced to explicitely provide a return type which is impossible in an anonymous function (the block after Action.async is just an anonymous function). You can easily extract your code to a named method with explicit types and use that as the action body:

class Companies @Inject()(primaryDAO:AccountDAO)(implicit ec:ExecutionContext) extends Controller {
  implicit val AccountReads = Json.format[Account]

  def doCreate(implicit request:Request[AnyContent]):Future[Result]={
    if (request.body.asJson.isEmpty) {
      return Future.successful(BadRequest("Missing body"))
    }

    val body = request.body.asJson.get.as[JsObject]
    val companyID = (body \ "company" \ "id").validate[String]
    val parsedAccount = (body \ "account").validate[Account]

    // Check that we have all of the fields we need
    if (parsedAccount.isError) {
      return Future.successful(BadRequest("Missing account data"))
    }
    if (companyID.isError) {
      return Future.successful(BadRequest("Missing company data"))
    }

    // Insert the new account
    val account = parsedAccount.get
    (for {
      _ <- primaryDAO.insert(account, companyID.get)
      account <- primaryDAO.get(account.id)
    } yield account).map {
      case Some(a) => Created(a.id)
      case None => InternalServerError("Unable to create Account")
    }.recover {
      case e => BadRequest(e.getMessage)
    }
  }
  def create = Action.async(doCreate)
}
object Companies extends Companies(new AccountDAO)(play.api.libs.concurrent.Execution.defaultContext)

I said that doing this is wrong and you really don't want to do this. Quoting Rob Norris (tpolecat) :

  If you find yourself in a situation where you think you want to return early, you need to re-think the way you have defined your computation

So let's do some rethinking :) I'll posit that What you really want isn't so much using early returns as it is avoiding deep nesting of if/else clauses.

Let's have a look at the types we are manipulating :
request.body.asJson returns an Option[JsValue]. The current implementation tests to check if it is empty and returns a
BadRequest. Play offers a similar and much cleaner way to check that you actually receive an application/json body for your endpoint (I'll leave the wrapping code to concentrate on the action itself for now) using a specific body parser:

def create = Action.async(parse.json) { implicit request =>
 val body = request.body
 val companyID = (body \ "company" \ "id").validate[String]
 val parsedAccount = (body \ "account").validate[Account]

 // Check that we have all of the fields we need
 if (parsedAccount.isError) {
   Future.successful(BadRequest("Missing account data"))
 }
 if (companyID.isError) {
   Future.successful(BadRequest("Missing company data"))
 } else {
   // Insert the new account
   val account = parsedAccount.get
   (for {
     _ <- primaryDAO.insert(account, companyID.get)
     account <- primaryDAO.get(account.id)
   } yield account).map {
     case Some(a) => Created(a.id)
     case None => InternalServerError("Unable to create Account")
   }.recover {
     case e => BadRequest(e.getMessage)
   }
 }
}

Using a body parser in the action will enforce the media type for the endpoint (in this case it will have to be a form of json). Trying to call it with a content type such as application/x-www-form-urlencoded will fail with a 415 Unsupported Media Type error, passing an invalid json body will yield a 400 BadRequest for you :

$> echo 'coucou'| http --form :9000/foobar
HTTP/1.1 415 Unsupported Media Type
Content-Length: 2163
Content-Type: text/html; charset=utf-8
Date: Thu, 28 Apr 2016 20:41:15 GMT

$> echo "coucou"| http :9000/foobar
HTTP/1.1 400 Bad Request
Content-Length: 2289
Content-Type: text/html; charset=utf-8
Date: Thu, 28 Apr 2016 20:43:30 GMT

Embracing the Json library

The next step consists of leveraging play-json's validation facilities. First let's define a reader which enforces all the protocol constraints for your endpoint :

import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val CreateDTOReads =
 (
   (__ \ "company" \ "id").read[String] and
   (__ \ "account").read[Account]
 ).tupled

Now we can use that to fully validate the incoming payload and reject it if it is incorrect:

def create = Action.async(parse.json) { implicit request =>
  val createDto:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
  // Check that we have all of the fields we need
  if (createDto.isError) {
    Future.successful(BadRequest("Missing account or company data"))
  } else {
    // Insert the new account
    val (companyId,account) = createDto.get
    (for {
      _ <- primaryDAO.insert(account, companyId)
      account <- primaryDAO.get(account.id)
    } yield account).map {
      case Some(a) => Created(a.id)
      case None => InternalServerError("Unable to create Account")
    }.recover {
      case e => BadRequest(e.getMessage)
    }
  }
}

Notice that at this point we have lost a bit of precision since I don't distinguish between the two errors anymore. The information is still there, captured in the errors of the JsResult. You could use pattern matching or even a cast to get a JsError out of the JsResult and once you have a JsError you get the list of all validation errors for each path which you can manipulate and translate as you like. For instance :

def create = Action.async(parse.json) { implicit request =>
    val createCommand:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
    // Check that we have all of the fields we need
    if (createCommand.isError) {
      val errors = createCommand.asInstanceOf[JsError]
      Json.prettyPrint(JsError.toJson(errors))
      Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors))))
    } else {
      // Insert the new account
      val (companyId,account) = createCommand.get
      (for {
        _ <- primaryDAO.insert(account, companyId)
        account <- primaryDAO.get(account.id)
      } yield account).map {
        case Some(a) => Created(a.id)
        case None => InternalServerError("Unable to create Account")
      }.recover {
        case e => BadRequest(e.getMessage)
      }
    }
  }

returns something like :

$> echo '{"coucou":""}'| http :9000/foobar
HTTP/1.1 400 Bad Request
Content-Length: 173
Content-Type: text/plain; charset=utf-8
Date: Fri, 29 Apr 2016 08:41:35 GMT

{
  "obj.account" : [ {
    "msg" : [ "error.path.missing" ],
    "args" : [ ]
  } ],
  "obj.company.id" : [ {
    "msg" : [ "error.path.missing" ],
    "args" : [ ]
  } ]
}

This is still not looking very nice since this is not the idiomatic way to extract information from a JsResult. The proper way is to fold over the JsResult. The fold method signature on a JsResult is fold[X](errors: (Seq[(JsPath, Seq[ValidationError])]) => X, valid: (A) => X): X). In our case we want X to be a Future[JsResult], and can write it like this :

def create = Action.async(parse.json) { implicit request =>
  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
  // Check that we have all of the fields we need
  createCommandResult.fold(
    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),
    createCommand => {
      val (companyId,account) = createCommand
      (for {
        _ <- primaryDAO.insert(account, companyId)
        account <- primaryDAO.get(account.id)
      } yield account).map {
        case Some(a) => Created(a.id)
        case None => InternalServerError("Unable to create Account")
      }.recover {
        case e => BadRequest(e.getMessage)
      }
    }
  )
}

Single Responsibility Principle

Now we are getting there but the valid case is not looking so good. This is because the create action handles too many responsibilities. At the REST endpoint level you should only handle HTTP protocol concerns :

content negotiation
deserialization of the payload (can include some validation)
serialization of the responses

Let's extract the business logic, however simple, to an AccountService class :

@Singleton
class AccountService @Inject() (primaryDAO: AccountDAO){
  def createAccount(companyId:String,account:Account)(implicit ec: ExecutionContext) : Future[Option[Account]] =
    for {
      _ <- primaryDAO.insert(account, companyId)
      account <- primaryDAO.get(account.id)
    } yield account
}

Now our endpoint only handles the HTTP translation logic :

def create = Action.async(parse.json) { implicit request =>
  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
  // Check that we have all of the fields we need
  createCommandResult.fold(
    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),
    createCommand => {
      val (companyId,account) = createCommand
      val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)
      createdAccountF.map {
        case Some(a) => Created(a.id)
        case None => InternalServerError("Unable to create Account")
      }.recover {
        case e => BadRequest(e.getMessage)
      }
    }
  )
}

The error handling code:

createdAccountF.map {
  case Some(a) => Created(a.id)
  case None => InternalServerError("Unable to create Account")
}.recover {
  case e => BadRequest(e.getMessage)
}

Is a good candidate for abstraction. If you wanted to always return Json for instance you could have the following  :

object JsonResultMapper extends Results {
  import play.api.libs.json.Writes

  def jsonOk[A](subject: A)(implicit writer: Writes[A]) = Ok(Json.toJson(subject))

  def jsonNotfound(msg: String) = NotFound(Json.obj("reason" -> msg))

  def exception2Location(exception: Exception): String =
    Option(exception.getStackTrace)
      .flatMap(_.headOption)
      .map(_.toString)
      .getOrElse("unknown")

  def jsonInternalServerError(msg: String, cause: Exception) = {
    val jsonMsg = Json.obj(
      "reason" -> msg,
      "location" -> exception2Location(cause)
    )
    InternalServerError(jsonMsg)
  }

  def toJsonResult[A](subjectOptionFuture: Future[Option[A]],noneMsg: => String = "NotFound")
                             (implicit writer: Writes[A]): Future[SimpleResult] = {
    subjectOptionFuture.map {
      case Some(subject) => jsonOk(subject)
      case None          => jsonNotfound(noneMsg)
    }.recover {
      case e: Exception => jsonInternalServerError(e.getMessage, e)
    }
  }
}

and then write your action as  :

def create = Action.async(parse.json) { implicit request =>
  val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
  // Check that we have all of the fields we need
  createCommandResult.fold(
    errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),
    createCommand => {
      val (companyId,account) = createCommand
      val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)
       JsonResultMapper.toJsonResult(createdAccountF, s"Unable to create account")
    }
  )
}

You could stop there and I will for the purpose of this review, but there are still things which can probably be improved. I'll give you a couple leads to further improve:

PrimaryDao protocol

The Future[Option[Account]] may not be a good signature for primaryDAO.get(account.id) or for AccountService#Create.

As you can see, it has 2 errors paths and 1 happy path. However when serializing it, the happy path and first error path are processed together in the same block, then the second error path (exception raised) in a different block.

Some would argue that one error path is a business error while the other is a technical error which makes it ok.

Whether we hide this in the ResultMapper or not I personally don't like it. To get rid of it an depending on your team standards, you can go for:

A BusinessException such as AccountNotFound which is thrown instead of returning an Option
A custom composition of Future and Option (see http://www.edofic.com/posts/2014-03-07-practical-future-option.html and http://loicdescotte.github.io/posts/scala-compose-option-future/ )
A ScalaZ monad transformer which does the same as the previous option in a generic way

In the same logic Future[Any] is not a very good signature for :

trait DAOInsert[A <: BaseModel] extends DAOGet[A] {
  def insert(model: A): Future[Any]
}

I strongly suggest changing that to

trait DAOInsert[A <: BaseModel] extends DAOGet[A] {
  def insert(model: A): Future[A]
}

and having the insert return the saved instance if it is possible. This would allow you to distinguish between : there was an error while inserting vs I couldn't read the instance which are not necessarily the same.

Using specific types

customerId is a string which carries very little information, creating and using a CustomerId type would probably prove very useful if it is used throughout your application.

Disclaimer

I don't know enough of the business to properly name things in my refactoring. Naming is probably the single most important thing when writing code and it is known to be one of the hardest (with invalidating caches).

Final code

package controllers.company

import scala.concurrent.{ExecutionContext, Future}

import com.google.inject.{Inject, Singleton}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}

trait BaseModel {
  def pk: String

  def id: String = pk
}

case class Account(name: String) extends BaseModel {
  override val pk = name
}

trait DAOGet[A <: BaseModel] {
  def get(pk: String): Future[Option[A]]

  def all: Future[Seq[A]]

  def all(page: Int, perPage: Int): Future[Seq[A]]
}

trait DAOInsert[A <: BaseModel] extends DAOGet[A] {
  def insert(model: A): Future[Any]
}

trait DAOUpdate[A <: BaseModel] extends DAOGet[A] {
  def update(model: A): Future[Int]
}

trait DAODelete[A <: BaseModel] {
  def delete(pk: String): Future[Int]
}

trait CRUDDAO[A <: BaseModel] extends DAOGet[A] with DAOInsert[A] with DAOUpdate[A]

class AccountDAO extends CRUDDAO[Account] {
  override def insert(model: Account): Future[Any] = Future.successful(model)

  def insert(model: Account, companyId: String): Future[Any] = model.id match {
    case "account1" | "account2" => Future.successful(model)
    case _ => Future.failed(new RuntimeException("Unable to save account"))
  }

  override def update(model: Account): Future[Int] = ???

  override def get(pk: String): Future[Option[Account]] = pk match {
    case "account1" => Future.successful(Some(Account(pk)))
    case "account2" => Future.successful(None)
    case _ => Future.failed(new RuntimeException("no such account"))
  }

  override def all: Future[Seq[Account]] = ???

  override def all(page: Int, perPage: Int): Future[Seq[Account]] = ???
}

@Singleton
class AccountService @Inject() (primaryDAO: AccountDAO){
  def createAccount(companyId:String,account:Account)(implicit ec: ExecutionContext) : Future[Option[Account]] =
    for {
      _ <- primaryDAO.insert(account, companyId)
      account <- primaryDAO.get(account.id)
    } yield account
}

@Singleton
class Companies @Inject()(accountService: AccountService)(implicit ec: ExecutionContext) extends Controller {
  implicit val AccountReads = Json.format[Account]

  import play.api.libs.functional.syntax._
  import play.api.libs.json._
  implicit val CreateDTOReads =
    (
      (__ \ "company" \ "id").read[String] and
      (__ \ "account").read[Account]
    ).tupled

  def create = Action.async(parse.json) { implicit request =>
    val createCommandResult:JsResult[(String,Account)] = request.body.validate(CreateDTOReads)
    // Check that we have all of the fields we need
    createCommandResult.fold(
      errors => Future.successful(BadRequest(Json.prettyPrint(JsError.toJson(errors)))),
      createCommand => {
        val (companyId,account) = createCommand
        val createdAccountF: Future[Option[Account]] = accountService.createAccount(companyId, account)
        createdAccountF.map {
          case Some(a) => Created(a.id)
          case None => InternalServerError("Unable to create Account")
        }.recover {
          case e => BadRequest(e.getMessage)
        }
      }
    )
  }
}

object Companies extends Companies(new AccountService(new AccountDAO()))(play.api.libs.concurrent.Execution.defaultContext)


Angular pipe to suppress sensitive information

I would avoid the for loop to generate the "suppressed string".

My approach would be:

export class SuppressInfoPipe implements PipeTransform {

  transform(valueToSupress: string, unSuppressedCount = 0): string {
    const suppressedCount = valueToSupress.length - unSuppressedCount;
    const valueToRemainUnsuppressed =
    valueToSupress.substring(suppressedCount, valueToSupress.length);

    return Array(suppressedCount + 1).join('*') + valueToRemainUnsuppressed; // suppressedCount + 1: since join will a string of length "suppressedCount"
  }
}

In this case:

Array(n) will return an array of length n.

.join("*") will join the list and return a string equivalent of length n-1.


Creating an associated object on create/update

Updated Answer: It's funny, because now that I've revisited this since your comment, I've flip-flopped my thinking a little. I still feel like the BoardGenerator class is unnecessary.

  Revisiting this, I noticed you mentioned the BoardGenerator being unnecessary. If that was the case how would a board know when to be created or updated without having some sort of link to a boardable?

The real issue is keeping the board name synchronized with the album or artist, and coordinating the creation of these dependent objects. The "boardable" should be the one responsible for this synchronization operation.

First, let's think about this problem from the standpoint of code using the Artist class.

When creating a new "boardable" I would expect this:

artist = Artist.create(name: "Prince")
puts artist.board.name # Prints "Prince"

The board is created automatically and gets the same name as the artist. Your code accomplishes this through the use of a separate class. Since it is the Artist that needs the board, and the Artist needs the board to have the same name, this behavior should be encapsulated within the Artist class completely. You can accomplish this by utilizing the after_initialize callback in ActiveRecord:

class Artist < ApplicationRecord
  has_one :board, as: :boardable, dependent: :destroy

  after_initialize -> (artist) { create_board(name: artist.name) unless artist.persisted? }
end

Now there is the issue of updating the name of the board when a "boardable" updates its name. Again encapsulation is our friend. Overriding the name= method on a "boardable" allows the names to be synchronized:

class Artist < ApplicationRecord
  has_one :board, as: :boardable, dependent: :destroy

  after_initialize -> (artist) { create_board(name: artist.name) unless artist.persisted? }

  def name=(new_name)
    super.name = new_name
    board ||= create_board(name: new_name)
    board.name = new_name
  end
end

Now when we get proper synchronization on update as well, without this logic leaking to other classes, or requiring another class that has little logic in it at all:

artist = Artist.find 23
artist.name = "The Artist Formerly Known As Prince"
puts artist.board.name # Prints "The Artist Formerly Known As Prince"

It's been a while since I've written much Ruby, but I feel like this behavior could be pulled out into its own Module and included as a mixin to both the Artist and Album classes.

Original Answer: I used to think the Board should be responsible for this stuff, but I've since reconsidered (see above).

I don't see an issue with your design, other than the BoardGenerator seems unnecessary. I would just go with static methods on the Board class itself. No need to separate this logic.

Responses to comments:

Carl Edwards asked:

  Creating static methods wouldn't violate the principle of single mode responsibility?

The Single Responsibility Principal states that a class or method should only have one reason to change.

The rule is, if a Board is attached to a Boardable, keep the names of the two things in sync. The name of the Board is what gets affected, and the Board class should be responsible for that.

Encapsulating this logic in the Board class is much more important that tightly adhering to the SRP for one simple reason: encapsulation.

Encapsulating data and behavior is far more important in this case. I also don't see how it violates the SRP. If it does violate the SRP, encapsulation is far more important than a "principal," because encapsulation is one of the foundational aspects of good object oriented code.

Wow. I've written "encapsulation" a lot in the last two paragraphs, but I hope it really drives the point home that encapsulating the data and behavior of a Board is the most important aspect here.


I am also relatively new to Clojure, but here are my first thoughts:

I like that you work with a vector, because random access of vectors with (nth) and assoc is faster. I also like your naming. thanks for providing a deftest, but please, user a proper inlining.
(assoc)'s do not need to be nested: (assoc (assoc c n+ v+) n- v-) is the same as (assoc c n+ v+ n- v-).
(last (take n x)) can be written as (nth x n).
Warning: you use the name 'first in yout (let), but this name is already defined in clojure.core.
For a style guide, please see https://github.com/bbatsov/clojure-style-guide

That is all for now, and I hope you found some advice useful.


fn str_to_vec3(s: &str) -> Option<Vec3> {
    let bits: Vec<&str> = s.split(" ").collect();
    if bits.len() != 3 {
        return None;
    }

    Some(Vec3 {
        x: bits[0].parse().unwrap(),
        y: bits[1].parse().unwrap(),
        z: bits[2].parse().unwrap(),
    })

}

For some errors, you panic (if parsing fails) and for other errors you return None. You really should pick one strategy and stick with it. If you want to avoid panicing it is more idiomatic to return Result than Option when it is an error.

Much of your code repeats the same basic action: split/parse/return. You can combine some of the code with a function like this:

fn split_parse<T: std::str::FromStr>(text: &str, split: &str) -> Result<Vec<T>, T::Err> {
    text.split(split).map(str::parse).collect()
}


As this looks like a school assignment, I'm answering with a bunch of questions for the student of algorithms to ponder:

Why do you think an empty list should be invalid input?
Could you think of a more descriptive name for the parameter than a?
You have a loop from 1 to length of array. This looks like an off by one error. Normally one would loop over indexes of 0..length-1. Could this loop be improved so it doesn't look suspicious?
Why are you using an outer for-loop and an inner while loop? Why not not in reverse? Why not use the same looping construct for both?
As this is an insertions sort, how do you perform an insertion to Python list, and where in this code is that insertion used?
How can you make sure that this solution really works? Could you write an automated test to check that it's correctly sorting various inputs?


In all three of your examples you limit yourself to using arrays.

This is not very C++ like (even if you templatize the object). I would change the interface to use iterators. That way your sort can be applied to any container with a random access iterator.

template<typename I>
void selection_sort(I begin, I end) {
    std::size_t size = std::distance(begin, end);


Finding the minimum number of swaps to sort a list

1. It's accidentally quadratic

The line:

midpoint = (first + last)

should be:

midpoint = (first + last) // 2

The consequence of this mistake is that binarySearch takes \$Θ(n)\$ to find the location, instead of the intended \$O(\log n)\$. And binarySearch is called for every item in the list, making the overall runtime \$Θ(n^2)\$ instead of the intended \$O(n \log n)\$.

2. Review of binarySearch

There's no docstring. What does it do? What arguments do I pass? What does it return?
The Python style guide (PEP8) recommends:

  4 spaces per indentation level

and:

  Always surround these binary operators with a single space on either side:  [...] comparisons (<=), [...]

Following PEP8 will make it easier for you to collaborate with other Python programmers.
A local variable found is used to exit the while loop. But Python's break statement also exits a loop, and if you used this you'd avoid the need for the variable.
else: if can be written elif:, saving a level of indentation.
Consider using the built-in bisect module.

3. Alternative approach

The rearrangement of items that happens when you sort a list is known as a permutation. For example, let's take this list of items:

When we sort the list, each item moves to a new position in the list, shown by the arrows:

We can draw the same arrows on a single row of items, showing where each item goes in the permutation:

The structure of the permutation becomes clear if we rearrange the items so that none of the arrows are crossing. Every permutation consists of one or more cycles: in this case there is a 1-cycle sending 6 to itself, a 2-cycle swapping 3 and 5, and a 7-cycle sending 4 to 9 to 2 to 1 to 8 to 7 to 0 to 4.

It takes \$n-1\$ swaps to implement a cycle of length \$n\$. So if the sorted permutation of a list can be decomposed into cycles with lengths \$a, b, c, \ldots, z\$ then the minimum number of swaps needed to sort the list is \$(a - 1) + (b - 1) + (c - 1) + \cdots + (z - 1)\$.

Here's an implementation that finds the cycles first and then uses their lengths to count the swaps. (It's not actually necessary to find the cycles, you could just count the swaps as you go along, but I think this is clearer to begin with.)

def cycle_decomposition(permutation):
    """Generate cycles in the cyclic decomposition of a permutation.

        >>> list(cycle_decomposition([7, 2, 9, 5, 0, 3, 6, 8, 1, 4]))
        [[0, 7, 8, 1, 2, 9, 4], [3, 5], [6]]

    """
    unvisited = set(permutation)
    while unvisited:
        j = i = unvisited.pop()
        cycle = [i]
        while True:
            j = permutation[j]
            if j == i:
                break
            cycle.append(j)
            unvisited.remove(j)
        yield cycle

def minimum_swaps(seq):
    """Return minimum swaps needed to sort the sequence.

        >>> minimum_swaps([])
        0
        >>> minimum_swaps([2, 1])
        1
        >>> minimum_swaps([4, 8, 1, 5, 9, 3, 6, 0, 7, 2])
        7

    """
    permutation = sorted(range(len(seq)), key=seq.__getitem__)
    return sum(len(cycle) - 1 for cycle in cycle_decomposition(permutation))


Helper function to find rotation of Caesar Cipher

First off, you should follow PEP8.
This will make your code more readable for Python programmers, and there is quite a few tips in there to make your code more Pythonic.
The amount of whitespace that you use is actually pretty good! It's mostly your names that 'let you down'.
But you're following a convention of camelCase. Which is also ok, but snake_case is preferred.

I don't like the re-definition of letterFreq and lines on ever function call.
This leads to a performance hindrance.
And so I'd move them out of the function to make them global.
Also as they are constants you may want to follow PEP8 and name them LETTER_FREQ and WORDS.

After this I'd look into removing the recursion. In Python recursion is cute, and un-reliable, nothing more.
I'd recommend that you don't use it, and instead you can use a for loop.
Using range starting at iterator and ending at len(LETTER_FREQ) we can remove the need for the recursion.

I'd also remove the print, instead of calling it in the function you should do it outside of the function.
If I'm using this function I don't want a print there ever couple of minutes.

Finally your turnery is a bit awkward and so I'd change it to use the modulo function, %.
This allows you to remove the if/else as -1 % 26 == 25 and so we can replace it with chr((ord(letter) - rot - 65) % 26 + 65).

Adding all the above together lead me to:

LETTER_FREQ = "AEIOTU"

with open('words.txt', 'r') as f:
    WORDS = [word.upper().strip() for word in f.readlines()]

def find_rotation(word1, word2, iterator=0):
    for index in range(iterator, len(LETTER_FREQ)):
        rot = ord(word1) - ord(LETTER_FREQ[index])
        letters = ''.join([chr((ord(letter) - rot - 65) % 26 + 65) for letter in word2])
        if letters in WORDS:
            return rot
    return None

For an additional speed you can also change WORDS to be a set, WORDS = set(WORDS), this is as it'll then be \$O(1)\$ look up in the if letters in WORDS: line, rather than \$O(n)\$. This is good as if the words list is large then it'll take a significantly larger amount of time then it would with a set.


Shell script that creates and deletes symbolic links

If you're worried about it being safe, probably verifying that what you're deleting is a symlink and bailing out if not would be a good start:

if [[ ! -h $TARGET_LOCATION/.$file ]]; then
    printf >&2 "%s is not a symlink!\n" "$TARGET_LOCATION/.$file"
    return 1
fi

Also, your deploy script doesn't seem to much care if there are existing .vim/.vimrc files to deal with, so I have to wonder: why bother juggling the configs? If there's any possibility someone else's config will be there, best check for it

if [ -e "$TARGET_LOCATION/.$file" ]; then
    printf >&2 "%s exists, cowardly refusing to clobber it\n" "$TARGET_LOCATION/.$file"
    return 1
fi

You might also consider placing this at the top of your script:

set -e

This will cause your script to cease execution immediately if any command in the pipe returns a non-0 status and isn't caught by an explicit check (if/then, &&/||, etc -- see manpage for the gory details). Generally, I recommend to always write shell with this on, but especially so if you're doing something you're nervous will misbehave.

I am not sure about this:

SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Is that how you are getting an absolute path? I would be cautious, if for some reason that command fails, even set -e won't catch it (launched in a subshell), then you have an unset $SCRIPT_DIRECTORY. That may cause find to fail, but it might cause it to walk your CWD, too.. hard to tell at a glance. I personally use a set of functions I tote around that do path normalization and has proper abspath() function to use, but in the interest of keeping this simple, consider skipping the clever tricks and set an explicit path (assuming it's not going to be changing). If that's not an option, I would add a sanity check to make sure what I'm walking and copying is what I expect. This can be as simple as checking a file is there that wouldn't be in ~ already.

And just throwing this out there: Consider making your dotfiles permanent but with a different name, then use an alias/function to set the desired config, e.g.: myvim () { vim -u "$HOME/.my.vimrc" "$@"; }. Not sure of your situation, but it might be more pleasant/less sketchy way to handle it.