Rendering explosion of bouncing balls on a canvas

Games and Animation.

Writing games means managing the compromise between the creative and artistic need, performance practicalities, and coding style.

When developing you usually have a top end gaming machine, sadly this is the wrong machine to develop on.

You need to have the minimum spec device you want your game to work well on as the development machine (or at least run on each test cycle) or you will always be frustrated with poor performance. It sucks, but it is easier to add features at run time that take advantage of a high end machine than to remove them to have it run on a low end machine.

Slow downs.

There are three main reasons that your code is slowing down.

Switching colors causes a state change that can be more expensive than the single draw function. It also forces you to draw using a new path for each item.
Rendering arcs is slow.
Rendering invisible or near invisible shapes still requires CPU cycles. You cull particles when their size is less than zero. But your update reduces the size by 0.02 per step so between radius 0.5 and 0 there are 25 near invisible particles rendered.

Also avoid ctx.closePath as for some reason it is mega slow. For arcs that will connect a path if you draw several it is far quicker to draw using

ctx.moveTo(x + r, y);
ctx.arc(x, y, r, 0, Math.PI * 2);

// An order of magnitude faster than

ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.closePath();

Drawing arcs is slow, for small arcs you can not tell the difference between an arc and a rectangle. Test the size and draw rectangles when you are below the size of a few pixels.

Reduce color state changes

To reduce the state change overhead caused by color changes you need to reduce the number of colors used. This can be achieved using a color table with a limited number of colors. You then create the particles in the explosion so that they are grouped by color. This lets you combine renders and reduce state changes.

Seperat concerns

Separating the explosion logic Explosion.update (movement, decay, bouncing) from the rendering allows you to optimise the code for the particular need. The rendering of particles can be independent of the explosion allowing all particles of the same color to be rendered in the same path.

Each time you call ctx.beginPath() you instigate a whole pile of internal functions. This overhead can be avoided by grouping as many path items together. All particles of the same color should be between a ctx.beginPath() and ctx.fill() or ctx.stroke()

Memory management

Creating and de-referencing (deleting) objects adds additional work for the CPU. The deleting workload will manifest as GC hits (garbage collection) that are uncontrollable.

GC hit can be a major problem when writing animations and require attention to how you use memory.

Memory is plentiful, CPU cycles are not so the rule is don't delete during the animation. You can do this using object pools.

Object pools

Object pools are a store of unused object that can be used when needed. When you need to create a new particle you check the pool, if there are available items in the pool you use them, if not you create a new object. When an object's life is up, you copy the reference to the pool for later use.

If well balanced the pools will grow to a size that represents the max number of particles that are visible at one time. This means the pools do not add additional memory load past the max needed to run without pools.

Bubble sort

When handling array of objects that change size rather than splice them out you can use a bubble sort to sort the objects as you process them. The explosion object does this to manage its array of particles. That means the explosion's particle array ids always full and will not incur GC hits, or need allocation when pulled from the pool.

There are many more ways to optimise but the answer would grow out of control.

Significant performance gain

Using the above concepts can give Significant performance benefits. The example below can render 10 times as many particles than your code. Though there are subtle differences, you will be hard pushed to see them and to the casual observer they will appear identical.

Example

To describe all that is contained in the code below would take to long so will let the code speak.

To get the performance there is added complexity, but performance is more important for a game than simple code.

There are two additional objects. explosions and particles that are the pools and management roles for particles and explosions.

The particle behaviour is almost identical apart from,

(12 * 8 = 96) particles per explosion rather than 100
Different decay rates per particle (this is to spread out pooling operations)
8 particle colors rather than many.
Particles are removed when radius is less than half a pixel.
Particles that have a radius less than 2 pixels are rendered as rectangles
Order of color rendering is fixed, the same color will always be on top.

Non performance change

The explosion picks a random direction and speed per particle to give a more spherical appearance to the explosion.

I have added a performance indicator that give time to render, per particle time (PPT) which is the mean render time of a particle, and particles per frame (PPF). This is so you can compare performance between the example code and your code (added under this example).

const width = canvas.width;
const height = canvas.height;
const ctx = canvas.getContext("2d");
Math.PI2 = Math.PI * 2;

requestAnimationFrame(mainLoop);  // start with a frame dont call the function directly

var pCount = 0;
function mainLoop() {
    ctx.clearRect(0, 0, width, height);
    pCount = 0;
    const now = performance.now();
    explosions.update();
    particles.draw();
    const time = performance.now() - now;

    info.textContent = "Render Time: " + time.toFixed(3) + "ms PPT: " + (time / pCount).toFixed(4) + "ms PPF:" + pCount;
    requestAnimationFrame(mainLoop);
}

canvas.addEventListener('click', (e) => {
    const explosion = explosions.create();
    explosion.init(e.offsetX, e.offsetY);
});

// Number of particles per explosion is renderStyleCount * particlesPerStyle
const explosion = {
    renderStyleCount : 8,   // Number of color styles to use.
                            // Can't be more than explosion.colors.length
    particlesPerStyle : 16, // Number of particles to add to explosion
                            // per color style
    colors : ["#0070a8", "#0077b3", "#0081c2", "#1282ba", "#57c7ff", "#66ccff", "#99ddff", "#a5f6ff"],
};

const explosions = Object.assign([], {
    pool : [],
    create() {
        var exp;
        if (explosions.pool.length) {
            exp = explosions.pool.pop();
        } else {
            exp = new Explosion();
        }
        explosions.push(exp);
        return exp;
    },
    update() {
        var i;
        for (i = 0; i < explosions.length; i ++) {
            if (explosions[i].update() === false) { // if false all particles are dead
                explosions.pool.push(explosions.splice(i--, 1)[0]); // send to pool
            }
        }
    },

});
const particles = Object.assign([], {
    pool : [],
    init() {
        var i;
        for (i = 0; i < explosion.renderStyleCount; i++) {
            particles.push(Object.assign([], {color : explosion.colors[i]})); // create style buckets
        }
    },
    create(style) {
        var p;
        if (particles.pool.length) {
            p = particles.pool.pop();
        } else {
            p = new Projectile();
        }

        p.style = style;
        particles[style].push(p);
        return p;
    },
    draw() {
        var i;
        for (const style of particles) {  // If you have many style you should create a pool for the styles as well
            if (style.length > 0) {
                ctx.beginPath();
                ctx.fillStyle = style.color;
                for (i = 0; i < style.length; i ++) {
                    const p = style[i];
                    if (p.dead) {
                        particles.pool.push(style.splice(i--,1)[0]);
                    } else {
                        pCount += 1;
                        const r = p.radius
                        if (r < 2) {
                            ctx.rect(p.x - r,p.y - r,r * 2, r * 2);
                        } else {
                            ctx.moveTo(p.x + r, p.y);
                            ctx.arc(p.x,p.y,r,0,Math.PI2);
                        }
                    }
                }
                ctx.fill();
            }
        }
    },
});
particles.init();

function Explosion(x, y) {
    this.particles = [];
    this.size = 0;
}
Explosion.prototype = {
    init(x, y) {
        var i, j, p, idx = 0;
        for (i = 0; i < explosion.renderStyleCount; i ++) {
            for (j = 0; j < explosion.particlesPerStyle; j ++) {
                this.particles[idx++] = p = particles.create(i);
                p.init(x, y);
            }
        }
        this.size = idx;
    },
    update() {  // implements a bubble sort to keep live particles grouped at the start of the array

        var head = 0, tail = 0;
        const particles = this.particles;
        const size = this.size;
        while (head < this.size) {
            const p = particles[head];
            p.x -= p.vx * 1;
            p.y -= p.vy * 1;
            p.radius -= p.decayRate;
            if (p.radius < 0.5) {  // particle is too small to see
                p.dead = true; // semaphore for particles object  to know when to pool particle
                head += 1;
            } else {
                p.collide();
                if (tail  0;
    },

}

// Capitalize Object name
function Projectile() {
    // hints the optimiser to type
    this.decayRate = this.style = this.radius = this.vy = this.vx = this.y = this.x = 0;
    this.dead = true;
}
Projectile.prototype = {
    init(x, y) {  // creates using direction and speed to make explosion more
                  // spherical in appearance.
        this.x = x;
        this.y = y;
        const dir = Math.random() * Math.PI2;
        const speed = Math.random() ** 0.5 * 10
        this.radius = 2 + Math.random() * 4;
        this.decayRate = Math.random() * 0.01 + 0.01;
        this.vx = Math.cos(dir) * speed;
        this.vy = Math.sin(dir) * speed;
        this.dead = false;
    },
    collide() {
        const p = this;
        if (p.x > width) {
            p.x = width;
            p.vx *= -1;
        }
        if (p.x < 0) {
            p.x = 0;
            p.vx *= -1;
        }
        if (p.y > height) {
            p.y = height;
            p.vy *= -1;
        }
        if (p.y < 0) {
            p.y = 0;
            p.vy *= -1;
        }
    },
}
#info {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas" width="500"  height="500"></canvas>

Orignal code.

The next snippet is the original question code with some timing information added to compare the performance.

I made some minor changes to your code to add the timing information.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var explosions = [];
var mouseX;
var mouseY;

canvas.addEventListener('mousemove', setMouse, false);

canvas.addEventListener('click', function() {
    explosions.push(new explosion(mouseX, mouseY));
}, false);

var pCount = 0;
function loop() {
    ctx.clearRect(0, 0, 500, 500);
    pCount = 0;
    const now = performance.now();
    drawExplosion();
    const time = performance.now() - now;

    info.textContent = "Render Time: " + time.toFixed(3) + "ms PPT: " + (time / pCount).toFixed(4) + "ms PPF:" + pCount;
    requestAnimationFrame(loop);
}
loop();

function drawExplosion() {
    if (explosions.length === 0) {
        return;
    }

    for (let i = 0; i < explosions.length; i++) {
        const explosion = explosions[i];
        const projectiles = explosion.projectiles;

        if (projectiles.length === 0) {
            explosions.splice(i, 1);
            return;
        }

        const projectilesRemove = projectiles.slice();

        for (let ii = 0; ii < projectiles.length; ii++) {
            const projectile = projectiles[ii];

            // remove projectile if radius is below 0
            if (projectile.radius < 0) {
                projectilesRemove.splice(ii, 1);
                continue;
            }

            // draw
            ctx.beginPath();
            ctx.arc(projectile.x, projectile.y, projectile.radius, Math.PI * 2, 0, false);
            ctx.closePath();
            ctx.fillStyle = 'hsl(' + projectile.h + ',' + projectile.s + '%,' + projectile.l + '%)';
            ctx.fill();

            pCount++;
            // update
            projectile.x -= projectile.vx * 1;
            projectile.y -= projectile.vy * 1;
            projectile.radius -= 0.02;

            // collisions
            if (projectile.x > 500) {
                projectile.x = 500;
                projectile.vx *= -1;
            }

            if (projectile.x < 0) {
                projectile.x = 0;
                projectile.vx *= -1;
            }

            if (projectile.y > 500) {
                projectile.y = 500;
                projectile.vy *= -1;
            }

            if (projectile.y < 0) {
                projectile.y = 0;
                projectile.vy *= -1;
            }
        }

        explosion.projectiles = projectilesRemove;
    }
}

function explosion(x, y) {
    this.projectiles = [];

    for (let i = 0; i < 100; i++) {
        this.projectiles.push(
            new projectile(x, y)
        );
    }
}

function projectile(x, y) {
    this.x = x;
    this.y = y;
    this.radius = 2 + Math.random() * 4;
    this.vx = -10 + Math.random() * 20;
    this.vy = -10 + Math.random() * 20;
    this.h = 200;
    this.s = Math.floor((Math.random() * 100) + 70);
    this.l = Math.floor((Math.random() * 70) + 30);
}

function setMouse(e) {
    mouseX = e.offsetX;
    mouseY = e.offsetY;
}
#info {
    position: absolute;
    top: 0px;
    left: 0px;
    }
<canvas id="canvas" width="500"  height="500"></canvas>


PHP MySQL make insert and update large amount of users faster

Well, the key point would be to wrap all your inserts in a transaction to make them dramatically faster.

Other points of less significance but rather a matter of sanity are:

connect once
prepare once and also make sure you are using a non-emulated prepared statement
get rid of the useless SELECT

So it should be like

$db = dbConnect();
$query = $db->prepare(
  "INSERT INTO USERS(id, name, `group`) VALUES(:id, :name, :group)
   ON DUPLICATE KEY UPDATE name=values(name), group=values(`group`)"
);

$userList = getFromAPI();
$db->beginTransaction();
foreach ($userList as $userId){
    // assuming you have a code to define these variables
    $query->execute([
    "id"=>$id,
    "name"=>$name,
    "group"=>$group
      ]);
}
$db->commit();


Efficient way of finding perfect squares

You could easily find the number of perfect squares up to (and including) a number by simply using (int)sqrt(x)

If you want the number of squares between two numbers, you should simply need to do this:

(int)sqrt(max) - (int)sqrt(min)

Though note if min is a perfect square, it is excluded/subtracted from the range. You can use a +/- 1 if you want to exclude the max number (if it's a perfect square), or include the min number (if it's a perfect square), from the range.


1. Review

I don't like comparative reviews, so I only looked in detail at the first version of your code. Possibly some of these comments apply to the other version too.

The code does not return the correct answer if there are repeated letters in pattern. For example, given S = 'ABCA' and T = 'AA', the minimum window should be the whole string. But:

>>> minWindow('ABCA', 'AA')
(1, 3)

To fix this, use len(pattern) instead of len(targetCount).
It would be better to raise an exception if no window is found rather than returning the meaningless result (4294967295, -1).
sys.maxint is not portable to Python 3. If you need a starting value that's bigger than any integer, use float('inf'). But it's possible to reorganize the code so that there's no need for a starting value — see the revised code below.
Instead of defaultdict(int), use Counter, which you can initialize directly from an iterable:

targetCount = Counter(pattern)

Instead of iterating over indexes into source, use enumerate:

for end, c in enumerate(source):
    if c not in targetCount:
        continue
    if currentCount[c] < targetCount[c]:
        validCount += 1
    currentCount[c] += 1
    # ... and so on ...

This avoids lots of lookups of source[index].
There's repetition of lines like start += 1 and                 currentCount[source[start]] -= 1. It would be easy to reorder the code so that each line appears only once.
Similarly, instead of maintaining and incrementing a start index, create an iterable that enumerates the source string:

window_start = enumerate(source)

and call next each time you need another character from it:

start, c = next(window_start)
if c not in targetCount:
    continue
# ... and so on ...

This avoids lots of lookups of source[start].
The inner loop is:

while validCount == len(targetCount):

but validCount does not change on every loop iteration (only on loop iterations where the start character causes one of the current counts to drop below its target). So some of these tests are wasted. Instead, you could loop using:

for start, c in window_start:

and then exit the loop only after reducing validCount:

    validCount -= 1
    if validCount < len(pattern):
        break

The test:

if source[index] not in targetCount:
    continue

is not necessary — the algorithm works just as well without it. And similarly for the corresponding test in the inner loop.

2. Revised code

In this implementation I've tried to emphasize the symmetry between the outer and the inner loop. Really what we have here is a pair of coroutines, each iterating over the input, and yielding to the other one at the appropriate point.

from collections import Counter

def min_window(source, pattern):
    """Return the shortest substring of source that contains all the
    characters in pattern (with the required multiplicity). Raise
    ValueError if there is no such substring.

    """
    def windows():
        pattern_length = len(pattern)
        target = Counter(pattern) # character -> required count
        current = Counter()       # character -> count in current window
        matched = 0               # matched characters in current window
        window_start, window_end = enumerate(source), enumerate(source)
        for end, c in window_end:
            current[c] += 1
            if current[c] <= target[c]:
                matched += 1
                if matched == pattern_length:
                    for start, c in window_start:
                        current[c] -= 1
                        if current[c] < target[c]:
                            matched -= 1
                            if matched < pattern_length:
                                yield end + 1 - start, start
                                break
    length, start = min(windows())
    return source[start: start + length]


Algorithm that combines same objects to single common key

It is not much less code but I believe it is clearer and easier to reason about:

function forEach(target, fn) {
    var keys = Object.keys(target);
    var key;
    var i = -1;
    while (++i < keys.length) {
        key = keys[i];
        fn(target[key], key);
    }
}
function transform(target, fn, accumulator) {
    if (accumulator === undefined) {
        accumulator = Object.create(target);
    }
    forEach(target, function (value, key) {
        return fn(accumulator, value, key);
    });
    return accumulator;
}
function aggregateHours(hours) {
    var agg = [];
    return transform(hours, function (result, spans, day) {
        spans.forEach(function (span) {
            var found = agg.find(function (el, i) { return el.hours.from === span.start.hour && el.hours.to === span.end.hour; });
            if (found) {
                found[day] = true;
            }
            else {
                agg.push({ hours: { from: span.start.hour, to: span.end.hour } });
                agg[agg.length - 1][day] = true;
            }
        });
    }, agg);
}

aggregateHours(deliveryHours);

Basically I have stolen the foreach and transform from my library: goodcore but written it all in javascript here so that you don't have to use it.


No warnings with very pedantic clang flags, good job!

You have this in the destructor:

tmp = head;
head = head->next;
delete tmp;

You can replace this with a call to std::exchange:

delete std::exchange(head, head->next);

Use move semantics. Node::Node unnecessarily copies value into data. It should be data(std::move(value)) so that no copy is made. Same goes for LinkedList::insert and so on.
Single characters should be in single quotes, not double quotes. I won't claim it's more efficient, because any compiler worth its salt is going to optimize the call to std::strlen.
In LinkedList::recursiveReverse the first overload, you don't need to  copy head because the other overload you're calling isn't modifying its arguments (no pass by reference). You should also be able to merge both functions.
It might be "better" to keep a pointer to the last node in your linked list. That way, insertion is O(1) instead of O(n).
Mark functions that do not throw noexcept, if you compile with exceptions.
Mark classes that one shouldn't inherit from with final.
You could provide a constructor taking an std::initializer_list, so you could specify the elements of the list directly on construction.
Sometimes you use the implicit conversion to bool for pointers and sometimes not. It might be better to be consistent.
You can use in-class initializers for example for Node::next.
You can provide an iterator interface, so that your container works with the range for loop. For example, you can provide a public iterator, const_iterator alias to basically pointers to the individual elements inside nodes and provide begin and end as functions.
Please provide a copy and move constructor and assignment operator. This is known as the Rule of 5. If I copy your list, then I will probably get a double delete error at runtime, but this is not guaranteed.


A few observations.

comments - These online code challenges don't tend to encourage code comments because, really, who's ever going to see it? After completing the challenge you will probably never return to it. Still, if it's going to be offered for code review you might pretty it up to make things easier for the reviewers.

unused - val seen is never referenced.

magic numbers - So 2 is "safe" and 1 is "unsafe" and ... This calls out for an enumeration. Then you could if (color_of(i) == Color.SAFE), and .withDefaultValue(Color.UNKNOWN), etc.

0 until graph.size - Use graph.indices instead.

return - Idiomatic Scala almost never uses return. In your case it's understandable since there are a couple of places where you want the iterations to terminate ASAP. Scala has a few different options for achieving that. One of the most common is using recursion.

if..else - In Scala the if..else construct is an expression, with a return value, and not a statement. For this, and other reasons, idiomatic Scala seldom invokes an if without a concluding else.

mutables - Perhaps the most obvious anti-Scala practice in the code is the use of mutable data structures. This isn't surprising since there is often a slight performance penalty when adhering to FP principles of immutability. Many of these online code challenges are much more difficult, if not impossible, without mutation.

So, can this be solved without mutation? I don't know. I came pretty close by using only the mutability inherent in the received Array.

def eventualSafeNodes(graph: Array[Array[Int]]): List[Int] = {

  def isSafe(xs :Array[Int], seen :Set[Int]) :Boolean =
    xs.isEmpty || xs.forall(x => !seen(x) && isSafe(graph(x), seen+x))

  graph.indices.foldRight(List.empty[Int]){ case (x, acc) =>
    if (isSafe(graph(x), Set(x))) {
      graph(x) = Array.empty[Int]  //leave marker - safe
      x :: acc                     //save index
    } else {
      graph(x) = Array(x)          //leave marker - unsafe
      acc                          //accumulator unchanged
    }
  }
}


Here's my best effort (8 lines):

from pygame import *
init()
screen = display.set_mode((1000,720))
for e in iter(event.wait, event.Event(QUIT)):
    col = {(1, 0, 0): 'white', (0, 0, 1): 'black'}.get(mouse.get_pressed())
    if col and e.type in (MOUSEBUTTONDOWN, MOUSEMOTION):
        display.update(screen.fill(Color(col), Rect(mouse.get_pos(), (20, 20))))
quit()

Notes:

from module import * is normally deprecated because you don't know all the names you're importing, and some of these might conflict with or shadow names from other modules. But in simple cases like this, with no other dependencies, it's justified because it results in code that's easy to read. You can always go through and change X to pygame.X if you want.
In this program there's nothing that animates, so there's no need for a clock, and the display only needs to be updated when it changes.
You didn't post your images brush.jpg and white.png so I've used solid colour rectangles. (Also, why a JPEG? JPEGs are lossy, so not appropriate for bitmap graphics.)
By changing the program to draw white-on-black I can avoid the initial screen.fill and save a line.
I've used colour names 'white' and 'black' which are clearer than RGB tuples like (255, 255, 255).
I've used the two-argument form of iter to avoid the test for event.type == QUIT. (This feature is useful when you want to exit an iteration on a special value.)
By using event.wait instead of event.get I can reduce the two loops to one.
I've changed the user interface so that the left mouse button draws and the right mouse button erases. This is done by looking up the tuple returned by mouse.get_pressed in a dictionary, to get the colour for the fill.
Surface.fill returns the rectangle that was filled, which is exactly the part of the display that needs to be updated, so I can pass it directly to display.update.


Rather than a global count, I would suggest using either a parameter, or to return a tuple that keeps the count during each recursive call.  This would also assure you thread safety.

def merge_sort(li, c):
    if len(li) < 2: return li
    m = len(li) / 2
    return merge(merge_sort(li[:m],c), merge_sort(li[m:],c),c)

def merge(l, r, c):
    result = []

Since l and r are copied in merge_sort, we can modify them without heart burn. We first reverse the two lists O(n) so that we can use s.pop() from the correct end in O(1) (Thanks to  @ofer.sheffer for pointing out the mistake).

    l.reverse()
    r.reverse()
    while l and r:
        s = l if l[-1] < r[-1] else r
        result.append(s.pop())

Counting is separate from the actual business of merge sort. So it is nicer to move it to a separate line.

        if (s == r): c[0] += len(l)

Now, add what ever is left in the array

    rest = l if l else r
    rest.reverse()
    result.extend(rest)
    return result

unsorted = [10,2,3,22,33,7,4,1,2]

Use a mutable DS to simulate pass by reference.

count = [0]
print merge_sort(unsorted, count)
print count[0]


Technically there are no errors, however there is some redundancy in your code. You only need be concerned with the terminator of one string. Therefore you can test for NULL in this manner;

mstrc:     cmp     byte [rsi], 0          ; Are we at EOS (end of string)
           jz      stop
           cmpsb                          ; Lookup why this works
           jz      mstrc
stop:

Those 4 instructions almost accomplish the exact functionality your looking for except your code expects source and destination to be exactly the same.  Mine however determines that as many characters in destination are equal to source.

Conformity to strcmp

mstrc:    lodsb
          or      al,  al
          jz      stop
          sub     al, [esi]
          jnz     stop
          inc     esi
          jmp     mstrc
stop:


Parsing n lines to count vowels - HackerEarth

Type signatures

You should add type signatures to all top-level bindings. processLine's returned value and main should have the same type, which can be checked with the type checker, if you add type signatures. The following code would compile, since main will have the type IO Int:

processLine 0 = return 0

But that's not what you've intended. Therefore, make sure to add type-signatures to all your top-level bindings:

main :: IO ()
main = …

processLine :: Int -> IO ()
processLine n = …

By the way, processLine's type signature makes n's type unambigous, and therefore you don't need an explicit type in (read numberOfTestCases :: Int) anymore.

Use syntactic sugar

['a','e','i','o','u'] is "aeiou", which is easier to change and to read (in my opionion). That way, we get:

countVowels :: String -> Int
countVowels line = length $ filter (`elem` "aeiou") $ map toLower line

By the way, if you use "aeiouAEIOU", you don't need to import Data.Char.

Keeping things pure(?)

  More specifically, I would like the processLine function to not have a side effect, but I don't know how can I do that.

At some point, you need to read the line. You've chosen processLine to do so. Note that it is not feasible to remove IO from processLine, because you would end up with processLine = countVowels.

Still, we can have a look at processLine to see what we can do. We can read the code literally:

If n is 0, do nothing
If n is greater than zero, do

read a line
count the vowels of the line
print the number of vowels
call processLine with n decreased by one

Or we can interpret it as

repeat the following action n times:

read a line
count the vowels of the line
print the number of vowels

return nothing

If we have a look at the modules in base, we'll notice that Control.Monad contains replicateM_, which does exactly the "repeat-n-times"-part:

processAllLines :: Int -> IO ()
processAllLines n = replicateM_ n processSingleLine

processSingleLine :: IO ()
processSingleLine = do
    line <- getLine
    print $ countVowels line

Note that processSingleLine can get shortened into getLine >>= print . countVowels, but I'm not sure whether you're ready for that yet.

Keeping things actually pure

Alright, we've seen how one could use standard functions to process all those lines. But it's still in IO. Can't we do anything?

Well, what would the alternative be? We still need to process a bunch of lines. A "bunch of something" can be easily expressed with a list, so let us write the type signature of our potential candidate.

processList :: [String] -> [Int]

The implementation comes rather easy:

processList = map countVowels

Now we just need to get a list of strings. Since we now want to get something from the user, we have to use IO:

getUserLines :: Int -> IO [String]

Seems familiar, doesn't it? "repeat-an-action-n-times". This time, it's getLine. Since we don't want to throw the result away, we use replicateM (note the missing _):

getUserLines n = replicateM n getLine

We're now missing two last ingredients. First, we need to print a list of Int so that the challenged site accepts it:

printSolutions :: [Int] -> IO ()

Exercise: write printSolution. Note that there is a function that might help you in the process.

We end up with the following main:

main :: IO ()
main = do
  numberOfTestCases <- readLn
  userLines         <- getUserLines numberOfTestCases
  printSolutions (processList userLines)

Further remarks

Search some of the base modules whether they provide the functions you're looking for. And have a look at Prelude. You've used read after getLine, which is provided as a single function readLn (see above).

For completion, here's how I would (probably) solve the challenge:

import Control.Monad (replicateM_)

main :: IO ()
main = do
  numberOfTest <- readLn
  replicateM_ numberOfTest $ getLine >>= print . countVowels

countVowels :: String -> Int
countVowels xs = length $ filter (`elem` "aeuioAEUIO") xs


Oh gosh... that looks horrible, whoever is teaching you has no idea of JS whatsoever.

I'll give you a quick start on "good" structure.

A bit on naming:

UPPERCASE = Constant
UpperCamelCase = Class
everythingElse = method / function / variable

Write a helper for defining namespaces, everything else will become unmaintainable soon.

namespace('Desktop.Windows');

Desktop.Init = function() {

};

Desktop.Windows.prototype = {

    buildWindow: function() {

    },

    showMenu: function() {

    }

};

No idea what bgChange is supposed to be, a sub-class?

If you want to have "sub class" behavior:

namespace('foo.Base');
foo.Base = function(a, b, c) {

};

// Write your self a generic extend(a, b, c...) function which copies the values from b, c... onto a
extend(foo.prototype, {

    show: function() {

    },

    other: function() {

    }

});

namespace('foo.Extended');
foo.Extended = function(a, b, c, d) {

    foo.Base.call(this, a, b, c);
    // use d

};

extend(extended.prototype, foo.prototype, {

    // "Overwrite"
    show: function() {
        foo.Base.prototype.show.call(this, ...); // "super call"
    }

});


Access case class parameter inside a map with default

Map has a getOrElse option:

myMap.getOrElse(myKey,defaultParameter).valueParameter


There isn't any need to name all your Sx variables and copy+paste the code to build each one; just build them in another loop.  You can do both loops as list comprehensions very concisely:

data = np.array([
    [(r[i+s*N, 0] - rcom[s, 0])**2 for i in range(N)]
    for s in range(400)
])


Extracting and normalizing URLs in an HTML document

Some stuff you could perhaps do differently:

# your code
if url is None or ' ' in url or '<' in url or '>' in url:
    continue

# the alternative
if url is None or any(char in url for char in ' <>'):
    continue

Also, you can call the split method directly, without the if statement, as it will return a single item list with the full string inside if the character is not in the string:

# your code
if '?' in url:
    url = url.split('?')[0]
if '#' in url:
    url = url.split('#')[0]

# the alternative
for splitter in '?#':
    url = url.split(splitter, 1)[0]

Notice the micro-optimization of using the second argument of split, so that the string is only split at the first occurrence if there is more than one.


Use a HashSet then it will only contain unique values, duplicates will be discarded when calling Add based upon the hashcode of the string. This should be far more efficient than calling Distinct.

List<EmailClass> splittedList

HashSet<string> listOfAdresses = new HashSet<string>();

// HashSet does not contain an AddRange method.
foreach (var emailClass in splittedList)
{
    listOfAdresses.Add(emailClass.MailAdresse);
    listOfAdresses.Add(emailClass.MailAdresseCC);
}

listOfAdresses.Add(anotherMailAddress);
listOfAdresses.Add(justAnotherMailAdresses);

string joinedAdresses = String.Join(";", listOfAdresses.ToArray());

--

Following the "feedback" from Almaz, here's a basic benchmark to show the performance difference (using unique values for each address):

private static void Main(string[] args)
{
    List<EmailClass> splittedList = Enumerable.Range(1, 100000).Select(i => new EmailClass
    {
        MailAdresse = i.ToString() + "@email.com",
        MailAdresseCC = i.ToString() + "cc@email.com"
    }).ToList();

    OriginalMethod(splittedList);
    HashSetMethod(splittedList);
    LinqMethod(splittedList);

    Console.ReadLine();
}

private static void OriginalMethod(List<EmailClass> splittedList)
{
    var sw = new Stopwatch();
    sw.Start();
    List<string> listOfAdresses = new List<string>();

    listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresse));
    listOfAdresses.AddRange(splittedList.Select(x => x.MailAdresseCC));
    listOfAdresses.Add("someone@email.com");
    listOfAdresses.Add("someone.else@email.com");
    var joinedAdresses = String.Join(";", listOfAdresses.Distinct().ToArray());
    sw.Stop();
    Console.WriteLine("OriginalMethod");
    Console.WriteLine(sw.Elapsed);
}

private static void HashSetMethod(List<EmailClass> splittedList)
{
    var sw = new Stopwatch();
    sw.Start();
    HashSet<string> listOfAdresses = new HashSet<string>();

    foreach (var emailClass in splittedList)
    {
        listOfAdresses.Add(emailClass.MailAdresse);
        listOfAdresses.Add(emailClass.MailAdresseCC);
    }

    listOfAdresses.Add("someone@email.com");
    listOfAdresses.Add("someone.else@email.com");

    string joinedAdresses = String.Join(";", listOfAdresses.ToArray());
    sw.Stop();
    Console.WriteLine("HashSetMethod");
    Console.WriteLine(sw.Elapsed);
}

private static void LinqMethod(List<EmailClass> splittedList)
{
    var sw = new Stopwatch();
    sw.Start();
    var emails = splittedList.SelectMany(emailClass => new[] { emailClass.MailAdresse, emailClass.MailAdresseCC })
        .Concat(new[] { "someone@email.com", "someone.else@email.com" })
        .Distinct();

    var joinedAdresses = String.Join(";", emails);
    sw.Stop();
    Console.WriteLine("LinqMethod");
    Console.WriteLine(sw.Elapsed);
}

Results run in release mode without debugger attached:

OriginalMethod: 00:00:00.0789540
HashSetMethod:  00:00:00.0488568
LinqMethod:     00:00:00.0668056

Ramping up to 1,000,000 items

OriginalMethod: 00:00:00.8189667
HashSetMethod:  00:00:00.6891028
LinqMethod:     00:00:01.0157357

As you can see, the HashSet approach is substantially faster than the OP and significantly faster than the Linq approach.


looks alright enough. i would change is replace all those unset() lines with just $_SESSION = array();

and check the manual, it has a sample to clear your session cookies if you have them enabled.


Pythonic way to do strategy design pattern,avoid use switch base on string compare

Yes. The most flexible approach would use getattr.

def extract(attr, datetimeindex):
    return [getattr(x, attr) for x in datetimeindex]

# Now, for example:
extract_day_of_year = partial(extract, attr='dayofyear')

# or
def extract_day_of_month(datetimeindex):
    return extract('dayofmonth', datetimeindex)

Alternatively with attrgetter:

def extract(attr, datetimeindex):
    return map(attrgetter(attr), datetimeindex)

I've also converted the for loop into a list comprehension (first) or map() (second), both of which spare you from needing to name a temporary variable.


Too many swaps
The "standard" selection sort finds the minimum element and swaps the first element with the minimum element once per loop. In total there should be N swaps. Your version of selection sort can swap up to (N^2)/2 times.
Unnecessary variable
I'm not sure why you use the variable result and return it.  You can just operate on the array that is passed in (list) directly.  When I first read your code I thought you were making a copy of the array, because you had this extraneous variable.
The "standard" selection sort
Here is an example of a "standard" selection sort:
public static void selectionSort(int[] list)
{
    int len = list.length;
    for (int i = 0; i < len - 1; i++) {
        int smallestIndex = i;
        int smallestValue = list[i];
        for (int j = i + 1; j < len; j++) {
            if (list[j] < smallestValue) {
                smallestIndex = j;
                smallestValue = list[j];
            }
        }
        if (smallestIndex != i) {
            list[smallestIndex] = list[i];
            list[i] = smallestValue;
        }
    }
}


Hash Table: adding and finding functions

For one thing, this:

   // Add holiday to Hash Table
   if (hashTable[murmurHash(key, strlen(key))] == NULL)
   {
       addition->next = NULL;
       hashTable[murmurHash(key, strlen(key))] = addition;
   }
   else  //If there is already an element at the index, add current holiday to beginning of list
   {
       addition->next = hashTable[murmurHash(key, strlen(key))];
       hashTable[murmurHash(key, strlen(key))] = addition;
   }

can simply be this:

   // Add holiday to Hash Table
   size_t idx = = murmurHash(key, strlen(key));
   addition->next = hashTable[idx];
   hashTable[idx] = addition;

Which cuts at least one invoke of the hash function, and in the process a similar number of strlen invokes. There is little sense is "checking" for a NULL in the hash table slot, because that is precisely what you want the next pointer of your new node to be anyway.

Not entirely clear either is whether you intended on your keys being unique. Both code snippets above (yours and mine) do not enforce unique keys. It is worth a thought to determine whether that feature is needed or not.

And (not really) finally, try and make a habit of creating hash functions that are independent of the hash table size. Though that may sound odd, it makes sense from the perspective of reuse. A hash function ideally returns a "value". That value is then massaged (usually via a modulo with the hash table size) to drive the final key into a slot within the table constraints. But that operation is separate from the hash function itself, which should be restricted only by the domain of the return type. In other words, this:

size_t murmurHash(const void *key, size_t len)

should simply return a value between 0 and the maximum value of a size_t on the platform. Period. No table size should be involved in the has function itself. Just chew on data and return some size_t. The caller of the function (the inserter, the lookup, etc), then takes this value and restricts it down to the table size (usually via a modulo of some kind). This makes the invocation look something like this:

   // Add holiday to Hash Table
   size_t idx = = murmurHash(key, strlen(key)) % hashSize;
   addition->next = hashTable[idx];
   hashTable[idx] = addition;

Though it may seem a little odd at first, it makes your hash functions more robust. They are not restricted by some table size. The user of the hash function does that step; not the function itself. This is the approach used by the standard C++ library std::hash<> template, and it is a good design to emulate.

Best of luck.


Tiny question ;)

As @Rotora mentioned, now is not a fantastic parameter name, it conveys that I need to only pass who late it is 'now', add is a verb, also not brilliant as parameter naming goes
addHours( -500 , -100 ) returns -0, is that what you want ?
You have 4 lines of comment, 3 lines of code, 1 blank line, perhaps you have to much comment ? Try to not need comments by working harder on parameter names.
Since adding is commutative ( order does not matter ), I would consider naming the function sumHours and name the parameters hours1 and hours2

function sumHours(hours1, hours2){
    var sum = (hours1 + hours2) % 24;
    return sum < 0 ? 24 + sum : +sum;
};


Check for palindrome in singly linked list

Your inconsistent and unconventional indentation makes your code harder to read than it should be.

Although Java accepts multiple top-level classes in the same file as long as no more than one is public, it is poor form.  Every top-level class, interface, and enum should have its own file, whether public or not.  Among other things, this makes it much easier to find all the classes, both for you and for the compiler.

It is a bit questionable that you're willing to destroy the list in order to test whether it's palindromic, but inasmuch as you are willing to do so, you could perform your palindrome test more efficiently.  You would use two primary Node references, one that advances one position for every two that the other advances.  Using the trailing reference, you would reverse the front portion of the list as you go, so that when the lead reference finds the end of the list, the trailing reference is at the midpoint, with a reference to the reversed first half already in hand.  I'm sure you see how to proceed from there.

You could also consider using an auxiliary data structure to build the reverse half-list or an equivalent; in particular, pushing the nodes one by one onto a stack would have a comparable effect.  This could be done in a way that does not destroy the original list.

Or on the third hand, if you were willing to change to a doubly-linked list, and especially if you were willing to represent the list itself with a separate data structure that contained a reference to the tail in addition to the reference to the head, then the palindrome test could be performed much more simply.  You would just start at both ends and work towards the middle.  That doesn't modify the list, either.


The code looks ok. I would just comment on two things:

Why do you keep individual fields as properties in your view controller when you can just retain a reference to a Car object?
You don't need to connect outlets to all labels unless you're planning to change them in the code (localize or customize them for example)


If you pass a long text to the code generator, the resulting program will overflow its memory. This is because you do >+++.> for each character, but you never come back to clean up behind you. Instead of >+++.>, the generated code should be >+++.[-]<, which is slower but can handle arbitrary long text.

You say that your text contains mostly ASCII characters. Therefore it is probably more efficient to add or subtract the difference of the characters. In pseudo code:

curr = 0
for ch in str:
    if ch > curr:
        emit_add(ch - curr)
    if ch < curr:
        emit_sub(curr - ch)
    emit_putchar()
    curr = ch
emit_setzero()

Emitting only the difference is especially efficient for long runs of lowercase ASCII letters.

Regarding your Python code: are you sure that Python really does not have a repeat string function? The letter_to_brainfuck function would become a one-liner then.


From a design and interface point of view, I find the use of:

auto a = heap.allocate("A");
cout << a->value << endl;

unnatural. I would expect a to act like a pointer to std::string since it's the value returned from a function named allocate using an object of type Heap<std::string>.

It would be more natural if:

*a evaluated to std::string& (std::string const& if a were const)
a-> evaluated to std::string* (std::string const* if a were const)

Then, you could replace a->value by *a.

auto a = heap.allocate("A");
cout << *a << endl;

P.S. I haven't spent enough time delving into the implementation of Heap to suggest how it can be done.


JavaScript string manipulation with certain logic in it

Minor upgrades, nice idea for the prepop result Raynos

result = ["0 0"]; // Outside of loop

// ...

if (is2PixelRatio) width /= 2;
width += 10; // [Insert magik number explanation here]

result.push(  -(i * width) + "px 0"  ); // Negative numbers will convert to "-30"


Filtering out neighboring ascending digits in quaternary numeral system

We are dealing with a runtime upperbounded by something like 4^n here.

If you are building a list of strings anyway, why not reuse the list of valid strings in the list and append these values to a digit to get a new value?

public static void calculateQuarternary(int n) {

    int startPtr, endPtr;
    startPtr = endPtr = 0;

    ArrayList<String> alTemp = new ArrayList<String>();
    ArrayList<String> alCurrent = new ArrayList<String>();

    alCurrent.add("0");
    alCurrent.add("1");
    alCurrent.add("2");
    alCurrent.add("3");

    for (int i = 1; i < n; ++i) {

        endPtr = alCurrent.size();
        alTemp.clear();

        for (int j = 0; j < endPtr; ++j) {

            for (int k = 0; k < 4; ++k) {
                if (shouldAdd(alCurrent.get(j), k)) {
                    alTemp.add(k + alCurrent.get(j) + "");
                }
            }
        }

        alCurrent = new ArrayList<String>(alTemp);
    }
    System.out.println(alCurrent.size());
}

public static boolean shouldAdd(String s, int k) {

    int firstChar = (int)(s.charAt(0) - 48);
    return k + 1 != firstChar;
}


I am trying to refactor these three methods into one

That would be, uh, de-factoring. I don't know of any merge methods refactoring - when people refactor code, they tend to extract functionality so as to have more methods (or classes and/or interfaces) that are also more simple, which means they do very little.
Taking 3 methods that do 3 different (albeit similar) things, and merging into one, would be a very bad idea. You have redundant code though, and that can be refactored.

Refactoring 1: Extract Method
All 3 methods have a dependency in common:

var webQueryInputProperty = new WebQueryInputProperty();

...and they all do the same thing with it (that would be even more obvious if the two properties were set in the same order in all 3 methods):

webQueryInputProperty.WQIP_Key = id;
webQueryInputProperty.WQI_Key = onlineReportId;
var webQueryInputProperties = new List<WebQueryInputProperty>{webQueryInputProperty};

There's this instruction, too, that the AddProperty method isn't calling:

_queryPermissions.GetInputPropertyByKey(id, ref webQueryInputProperty);

This means you could have a 4th, private method like this, whose job is to provide the other 3 methods with a list that contains a webQueryInputProperty object:
private IEnumerable<WebQueryInputProperty> GetWebQueryInputProperties(int id, int onlineReportId, bool isNewItem = false)
{
    var webQueryInputProperty = new WebQueryInputProperty();
    if (!isNewItem)
    {
        _queryPermissions.GetInputPropertyByKey(id, ref webQueryInputProperty);
    }

    webQueryInputProperty.WQIP_Key = id;
    webQueryInputProperty.WQI_Key = onlineReportId;

    return new List<WebQueryInputProperty> { webQueryInputProperty };
}

Notice the method is returning an IEnumerable<T>, not a List<T> - you could just as well return an inline array, like this:
    return new[] { webQueryInputProperty };

That is, if the 3rd-party library methods you're passing it to don't actually require a List<T>.
At this point you have this already:
public StatusReturn UpdateProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId);
    return _queryPermissions.UpdateWQInputProperties(properties);
}

public StatusReturn AddProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId, true);
    return _queryPermissions.UpdateWQInputProperties(properties);
}

public StatusReturn DeleteProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId);
    return _queryPermissions.DeleteWQInputProperties(properties);
}

That's nice, but the bool parameter is sticking out like a sore thumb. It's begging for an abstraction:
private enum DataOperation
{
    Update,
    Add,
    Delete
}

And then:
private IEnumerable<WebQueryInputProperty> GetWebQueryInputProperties(int id, int onlineReportId, DataOperation operation)
{
    var webQueryInputProperty = new WebQueryInputProperty();
    if (operation == DataOperation.Add)
    {
        _queryPermissions.GetInputPropertyByKey(id, ref webQueryInputProperty);
    }

    ...

Which turns the call sites into this:
public StatusReturn UpdateProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId, DataOperation.Update);
    return _queryPermissions.UpdateWQInputProperties(properties);
}

public StatusReturn AddProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId, DataOperation.Add);
    return _queryPermissions.UpdateWQInputProperties(properties);
}

public StatusReturn DeleteProperty(int id, int onlineReportId)
{
    var properties = GetWebQueryInputProperties(id, onlineReportId, DataOperation.Delete);
    return _queryPermissions.DeleteWQInputProperties(properties);
}

Refactoring 2: Rename
WQI_Key and WQIP_Key are bad names. Don't use underscores in the middle of an identifier, and don't use abbreviations. If WQI_Key is supposed to be a report ID, why not call it ReportId?
If the class this code is written is is cohesive, then you can drop the Property suffix (the type name says Property too, right?) and have Add, Update and Delete methods instead of AddProperty, UpdateProperty and DeleteProperty.
If it's not cohesive, then you have an AddXxxx scheme and you probably have a whole other class to extract.
you're way too verbose here:

var webQueryInputProperty = new WebQueryInputProperty();

I would have had this:
var property = new WebQueryInputProperty();

I suspect _QueryPermissions is a typo; the leading underscore makes me believe it's referring to a private or private readonly field (in which case the correct naming is with the lowercase q).

Lastly, StatusReturn is a bad name for a type - literally anything with a Return suffix is a bad name for a type.
Actually, it's probably a bad idea to even have to deal with that type in the first place, let alone to spread it into your own code.
Instead of leaving it to the client code to verify the status and - I bet - make sure no error occurred and that the method call was successful, you could have a private static method to analyze a StatusReturn, and throw an exception in case of a non-successful method call.
Assuming ReturnResult is an enum (and that you create custom exception types as needed), it could look something like this (don't default to success!):
private static void ValidateResultOrThrow(ReturnResult result)
{
    switch (result)
    {
        case ReturnResult.Success:
            return;

        //case ReturnResult.ConnectionError:
        //    throw new NoNetworkException("Unable to connect.");

        //case ReturnResult.InvalidIdError:
        //    throw new ArgumentException("Specified id doesn't exist.");

        case default:
            throw new UnknownResultException("Something bad happened.");
    }
}

And then your methods could return void, and either succeed or throw - which is probably what the client code would be expecting - and you keep the ReturnResult ugliness nicely abstracted away:
public void Update(int id, int reportId)
{
    var properties = GetWebQueryInputProperties(id, reportId, DataOperation.Update);
    var result = _queryPermissions.UpdateWQInputProperties(properties);
    ValidateResultOrThrow(result);
}

public void Add(int id, int reportId)
{
    var properties = GetWebQueryInputProperties(id, reportId, DataOperation.Add);
    var result = _queryPermissions.UpdateWQInputProperties(properties);
    ValidateResultOrThrow(result);
}

public void Delete(int id, int reportId)
{
    var properties = GetWebQueryInputProperties(id, reportId, DataOperation.Delete);
    var result = _queryPermissions.DeleteWQInputProperties(properties);
    ValidateResultOrThrow(result);
}

Hmm.. Perhaps the GetWebQueryInputProperties calls would read better if the DataOperation parameter was first. A reorder parameters (or change signature) refactoring would fix that.


Your code looks fine to me. If you wish, you could use Greek letters. This makes the formula easier to read, but if you expect to modify it often, it may be too much trouble to enter the Greek letters. You might find it helpful to split up long formulas, as I've done for pdf. If you can think of more meaningful names than foo and bar, this might be a good idea. However, if this is a well-known formula in your field, splitting it up might actually make it less recognisable. It's a judgement call.

If you wrote this in literate Haskell, you could include a nicely-formatted version of the formula using LaTeX. That might be useful if you're writing code with a lot of formulas.

import Math.Gamma

γ :: Double -> Double
γ = gamma

pdf :: Double -> Double -> Double -> Double -> Double
pdf μ α β x = foo ** bar ** β
  where foo = ( β / (2 * α * γ  ( 1/β) ) )
        bar = exp ( -1* ( abs(x - μ )/α ))

cdf :: Double -> Double -> Double -> Double -> Double
cdf μ α β x = 0.5 + signum(x - μ) * ( lowerGamma  (1/β) ((abs(x-μ) / α)**β) / (2 * γ(1/β)))

main = do
    let x = pdf 0 1 2 0.5
    print x
    let y = cdf 0 1 2 0.5
    print y


Logging a message and the stack trace of caught exceptions

I agree it’s a false positive. Sonarqube is way too strict on this issue in my view and creates many false positives with that rule. Often, when catching a specific exception, we know exactly where it came from.

For this rule, I gave in and logged the exception on TRACE in addition to what I already logged at whatever different level. Sonarqube is satisfied, and the log stays clean unless you explicitly ask for verbose output.


Get all recipes from database with the cheapest ingredients

I found two issues after some investigation

The first is that my "precio" column is float and that a bad idea to store currencies. I turn this into a double data type by using the following command:

ALTER TABLE PRODUCTOS MODIFY COLUMN precio double;

The second issue is the way I use the subquery to get the cheapest product price in every single product. Instead, I've changed my PRODUCTS table inside of my FROM case to a  minified version. Basically, what I've done is get all the products with the cheapest price by ingredient and removes the need of use subqueries. Please, see the fixed version:

SELECT ...
FROM (
    SELECT * FROM PRODUCTOS AS P WHERE ingrediente is not null and P.precio = (
    select MIN(precio) from PRODUCTOS where P.ingrediente=PRODUCTOS.ingrediente group by PRODUCTOS.ingrediente LIMIT 1)
) AS PRODUCTOS
INNER JOIN INGREDIENTES ...

The result returned is exactly the same and I've moved from 1.8 seconds to 0.15 which I think is a great improvement.


As you have already been made aware, you should not be using &mut Vec<T> unless you plan on adding or removing items from the Vec. Using &mut [T] better expresses the contract of the function and is more flexible, allowing you to also sort arrays and anything else that can be expressed as a slice.
where clauses go on a separate line. This allows them to be easily found, which is important considering how much they affect the behavior of the function.
There's no need to declare the type of pos. Type inference will take care of it.
There's no need to redeclare pos just to make it mutable and decrement it. Just make the variable binding in the function declaration mut.
There's no need to return the unit value (()). Just return will suffice.
slice::swap exists. In the broader world, so does mem::swap.
With the power of swap, you can remove the need for the Copy bound.
Quickcheck is an invaluable tool for problems like this. You can create a property that can be validated across a wide range of automatically generated input.

pub fn insertion_sort<T>(values: &mut [T])
    where T: Ord
{
    for i in 0..values.len() {
        for j in (0..i).rev() {
            if values[j] >= values[j + 1] {
                values.swap(j, j + 1);
            } else {
                break
            }
        }
    }
}

#[macro_use]
extern crate quickcheck;

#[test]
fn test_insertion_sort_empty() {
    let mut values: [i32; 0] = [];
    insertion_sort(&mut values);
    assert_eq!(values, [])
}

#[test]
fn test_insertion_sort_one() {
    let mut values = [1];
    insertion_sort(&mut values);
    assert_eq!(values, [1]);
}

#[test]
fn test_insertion_multi() {
    let mut values = [9, 8, 7, 11, 10];
    insertion_sort(&mut values);
    let values_expected: Vec<_> = (7..12).collect();
    assert_eq!(values_expected, values);
}

quickcheck! {
    fn test_insertion_everything(xs: Vec<i32>) -> bool {
        // Macro doesn't allow `mut` in the `fn` declaration :-(
        let mut xs = xs;

        let mut expected_sorted = xs.clone();
        expected_sorted.sort();

        insertion_sort(&mut xs);

        expected_sorted == xs
    }
}


Asking the user to select a test subject and difficulty level

Use of Exceptions/Errors

Raising the DoWork error when input validation succeeds seems strange. Errors are usually raised by a function when, for some reason, it could not do what it was supposed to. Raising an error from is_it_correct if the input was not correct seems like fair game - in fact, there is a built-in ValueError that is meant to be raised when a function is called with values that are somehow malformed.

However, since your method is called is_it_correct already, why not just return a boolean that answers the question that is the method name?

Call signature

Right now, is_it_correct takes one argument per valid choice. What if, at some point, you want to add another test to your program? You would have to create a method that takes an additional valid choice as argument. But then, you would run into trouble with the difficulty selection - it still only has two valid choices.

I recommend using an array for the valid choices for extensibility's sake.

Separation of concerns

Right now, the is_it_correct method is in charge of validating the correctness of the input as well as printing out an error message. I recommend moving the error message to the point in your code where other user interaction takes place already - namely close to the input calls.

With all of the above recommendations considered, is_it_correct and its usage could look like this:

def is_it_correct(choice, valid_choices):
    return choice in valid_choices

while True:
    test = input()
    test_choices = ["computer science", "history", "music"]
    if is_it_correct(test, test_choices):
        break
    else:
        print("Sorry, you didn't input valid settings. Available choices: " + ", ".join(test_choices))

Deduplication

You have two while True loops doing something very similar - prompting the user for one of a given set of choices and displaying an error message if he fails to enter a valid choice. Why not wrap that up in a method?

def require_input(prompt, choices):
  # generate a readable list of choices
  choices_string = "{} or {}".format(", ".join(choices[:-1]), choices[-1]).capitalize()

  # build the prompt message dynamically
  msg = "{} {}?\n".format(prompt, choices_string)

  while True:
    user_choice = input(msg)
    if is_it_correct(user_choice, choices)
        return user_choice
    print("Please input either " + choices_string + ".")

tests = ["computer science", "history", "music"]
test = require_input("What test do you want to take?", tests)

difficulty_levels = ["easy", "medium", "hard"]
difficulty = require_input("How difficult do you want the test to be?", difficulty_levels)


Setup ordering in priority blocking queue

You currently couple your SocketHolder class with the environment it exists in, as you have the comparable interface implemented in SocketHolder which in turn uses Utils.CURRENT_DATACENTER.get().name(). I don't think that this is a good idea, as this dependency seems unnecessary and makes isolated testing difficult. (Or in other words: bad gut-feeling ;-))

Suggestion: as you set up your priority queue in a specific environment, and at that place it is probably OK to know the environment. So, use the constructor for priority queue where you pass a Comparator explicitly, and write a comparator which basically does the same as the compareTo-method you have in your SocketHolder right now.


Helper methods for working with the WPF Dispatcher

anonymous methods to the rescue! I saw somebody griping about this syntax recently on a blog and found it unfortunate they were dissimenating this. The cleaner new and happy way to define a delegate, is quite simply:

The method signature without a name or types, so for example:

Sum(int a, int b)

becomes:

(a, b)

Follow this with our trusty lambda operator => and then our method body! This may be in a statement block between our trusty {} or just in a single line the same way you can put a single line after an if or while etc.

So in conclusion there are 3 ways to create a method:

Standard (must be declared as class member level):

public int Sum(int a, int b)
{
  return a+b;
}

Delegate (can be declared and instantiated as a method local):

delegate(int a, int b)
{
  return a+b; // god help me if this syntax is correct, I haven't created a delegate in years
}

Anonymous method (can be declared and instantiated as a method local):

(a, b) => { return a+b; };

Back to your example...

ThreadContext.InvokeOnUiThread(
    delegate()
    {
        MessageBox.Show("Hello world!");
    });

In anonymous method format becomes:

ThreadContext.InvokeOnUiThread(() => { MessageBox.Show("Hello world!"); });

Or if you prefer:

Action actionToInvokeOnUiThread = () => { MessageBox.Show("Hello world!"); };
ThreadContext.InvokeOnUiThread(actionToInvokeOnUiThread);


Linq group by with multiple where, sum clauses in select causes a timeout

You could try to set the joins on the already filtered table:

(from inv in Dbcontext.tblSalesInvoices.Where(inv => inv.InvoiceDate >= FeedSearchCriteria.FromDate && inv.InvoiceDate <= FeedSearchCriteria.ToDate
    && inv.InvoiceStatusId != Constants.REVERSED_INVOICE)
    join det in Dbcontext.tblSalesInvoiceDetails on inv.SalesInvoiceId equals det.SalesInvoiceId
    join item in Dbcontext.tblItems on det.ItemId equals item.ItemId
    join itemGroup in Dbcontext.tblItemGroups on item.ItemGroupId equals itemGroup.ItemGroupId
    join loc in Dbcontext.tblLocations on inv.LocationId equals loc.LocationId
    group new { det.Quantity, itemGroup.ItemGroupCode, item.Weight, item.ItemCode, det.LineTotal } by loc.LocationName into g
    select new LocationCount()
    {
    LocationName = g.Key,
    FeedBagCount = (int?)g.Where(x => x.ItemGroupCode == "FEED").Sum(x => x.Quantity),
    SupremeKg = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.Weight * x.Quantity),
    SupremeValue = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.LineTotal),
    DocCount = (int?)g.Where(x => x.ItemCode == "DOC").Sum(x => x.Quantity)
    }).OrderBy(x=>x.LocationName).ToListAsync();


StringTokenizer is an OK solution, but I think that String.split() would lead to a less verbose solution.

Here is a Java 8 solution that uses split():

public static String reverseDomainNameString(String s) {
    List<String> components = Arrays.asList(s.split("\\."));
    Collections.reverse(components);
    return String.join(".", components.toArray(new String[0]));
}

Without Java 8's String.join(), though, the solution would be more tedious.  Note that it might be a good idea to ensure that the string is non-empty, otherwise components[0] (or st.nextToken() in your original solution) would crash.

public static String reverse(String s) {
    if (s == null || s.isEmpty()) return s;
    String[] components = s.split("\\.");
    StringBuilder result = new StringBuilder(s.length());
    for (int i = components.length - 1; i > 0; i--) {
        result.append(components[i]).append(".");
    }
    return result.append(components[0]).toString();
}


It's more of a style preference, but instead of the paragraph with if and elif's, I would do

winnings += payouts_dictionary[numb_wins]

where

payouts_dictionary = {6: WIN_SIX, 5: WIN_FIVE, 4: WIN_FOUR, 3: WIN_THREE, 2: 0, 1: 0, 0: 0}

is defined as a constant before the loop.


Function for timing executions (inspired by MATLAB tic toc)

I have a minor stylistic point, but you don't need (and shouldn't use) brackets around return values. Neither the lambda itself nor the lambda's return value.

return lambda: time() - t

It is minor but it actually confused me and made me think there was more of an expression there because of how rarely brackets are used like this.


Java app for getting metadata of millions of files in a directory

I suspect that using the old File class of Java is the possible root problem of your solution right now. Since you're using Java 7, you should use those new classes. I've seen that you use some of them like Path, so it shouldn't be too difficult. I don't what your class look at moment so I've changed some method base on what I'm use to do. So the class I will be using is SimpleFileVisitor since this is the basic implementation of FileVisitor.

So I've created a class Walker (this is a very bad name, you should change it for something clearer for you, since I have no good idea right now) that extends SimpleFileVisitor. The class has an attribute extractFile that correspond to the filename of the csv. This class will have the preVisitDirectory, visitFile and visitFileFailed that we will override from the FileVisitor. I've also added your method writeCsvFileDtl, createDate (thanks to @unholysampler, you should read his answer too).

So the class should look like that :

import static java.nio.file.FileVisitResult.CONTINUE;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class Walker extends SimpleFileVisitor<Path> {

    private String extractFile;

    public Walker(String extractFile) {
        this.extractFile = extractFile;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr)
            throws IOException {
        populateAndWrite(dir, attr);
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
        populateAndWrite(file, attr);
        return CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        //You should determine if you need this method or not
        return CONTINUE;
    }

    private void populateAndWrite(Path file, BasicFileAttributes attr) {
        ScraperOutputVO so = new ScraperOutputVO();
        if (file.getParent() != null) {
            so.setFilePath(file.getParent().toString());
        }

        if (file.getFileName() != null) {
            so.setFileName(file.getFileName().toString());
        }

         so.setFileType(getFileType(file.toAbsolutePath().toString()));

        if (attr != null) {
            so.setDateCreated(createDate(attr.creationTime()));
            so.setDateLastModified(createDate(attr.lastModifiedTime()));
            so.setDateLastAccessed(createDate(attr.lastAccessTime()));
        }
        if (!attr.isDirectory()) {
            so.setFileSize(String.valueOf(attr.size()));
        }

        so.setAuthors(fileUtil.getOwner(file));

        so.setFolderLink(file.toAbsolutePath().toString());
        try {
            writeCsvFileDtl(extractFile, so);
        } catch (IOException e) {
            log.info("IOException while writing to csv file" +
            e.fillInStackTrace());
            throw new
            ScraperException("IOException while writing to csv file" ,
            e.fillInStackTrace());
        }
    }

    private String createDate(FileTime time) {
        String timeStr = time.toString();
        return timeStr.substring(0, 10) + " " + timeStr.substring(11, 16);
    }

    private void writeCsvFileDtl(ScraperOutputVO scraperOutputVO)
    throws ScraperException {
        try {
            FileWriter writer = new FileWriter(extractFile, true);
            writer.append(scraperOutputVO.getFilePath());
            writer.append(',');
            writer.append(scraperOutputVO.getFileName());
            writer.append(',');
            writer.append(scraperOutputVO.getFileType());
            writer.append(',');
            writer.append(scraperOutputVO.getDateCreated());
            writer.append(',');
            writer.append(scraperOutputVO.getDateLastModified());
            writer.append(',');
            writer.append(scraperOutputVO.getDateLastAccessed());
            writer.append(',');
            writer.append(scraperOutputVO.getFileSize());
            writer.append(',');
            writer.append(scraperOutputVO.getAuthors());
            writer.append(',');
            writer.append(scraperOutputVO.getFolderLink());
            writer.append('\n');
            writer.flush();
            writer.close();
        } catch (IOException e) {
            log.info("IOException while writing to csv file" +
             e.fillStackTrace();
            throw new ScraperException("IOException while writing to csv file",
                    e.fillInStackTrace());

        }
    }
}

The method populateAndWrite is use in preVisitDirectory and visitFile, basically it will populate each attribute of your object ScraperOutputVO and then send it to the the write method. I'm not sure if you to list directories, so if you don't want to just remove preVisitDirectory. I've added some nullcheck since those method can return null if you start at the root directory.

You'll maybe need to tweak some attributes, cause I didn't had access to your fileUtils and getFileType, so you should test to make sure you have the same values.

To launch the class you simply need to something like :

public static void main(String args[]){
    Path root = Paths.get("Path to your directory");
    Walker walker = new Walker("Name of your csv file");
    try {
        Files.walkFileTree(root, walker);
    } catch (IOException e) {
        //you should handle exception here
        //log.info("Problem walking the directory")
        e.printStackTrace();
    }
}

If you need more help just comment on the answer.

Edit: I find another amelioration that would lower the time of the execution. The problem is when you write to the file, you always create a new FileWriter, open the file, write to it and then close it. So for each file you hit, you're opening accessing the file and closing it which is causing a major drawback on performance. By using your current  writeCsvFileDtl it took me like 170 seconds to write 100 000 entries. By leaving open the the FileWriter writing took less than one second. You should do something like that, it is not very elegant (you could probably do something more readable or cleaner) but will enhance the performance.

import java.io.FileWriter;
import java.io.IOException;

public class Writer {
    static FileWriter writer = null;
    public static void openFileWriter() {
        try {
            writer  = new FileWriter("C:/dev/file.txt", true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeToTheFileWithOpenEachTime(){
          try {
                writer.append("firstColumn");
                writer.append(',');
                writer.append("secondColumn");
                writer.append(',');
                writer.append("thirdColumn");
                writer.append(',');
                writer.append("fourthColumn");
                writer.append(',');
                writer.append("fifthColumn");
                writer.append(',');
                writer.append("sixthColumn");
                writer.append(',');
                writer.append("sevenColumn");
                writer.append(',');
                writer.append("eigthColumn");
                writer.append(',');
                writer.append("ninethColumn");
                writer.append('\n');
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    public static void closeWriter() {

        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


Using EqualityComparer to find contained value

if (!(t1.GetHashCode() == t2.GetHashCode())) return false;

Even if JIT compiler generated code will/should be the same negation operator is easy ignored during source code scanning by human beings. Because !(a == b) is effectively a != b I would rewrite it as:

 if (t1.GetHashCode() != t2.GetHashCode())
    return false;

Note I also reintroduced line breaks, it helps readability and for short functions (as they should be) there is not need to reduce vertical space.

Even if you shouldn't (generally) rely on these implementation details please
note that in your equality comparer you do not need to check for hashcode again.
HashSet already does it and it has an advantage over your code: it calculates
hashcode for item you're searching for just once. In your code you have to
calculate both hashes again and again for each comparison (and it may be slow,
according to effective data type and hashing algorithm). Please note that you shouldn't (IMO!) rely on this optimization on generic comparers because you do not have any knowledge of type implementation. Think what hashcode does for integer types, is it faster to calculate hash or to perform direct comparison? What about strings with different lengths? It may be done by a container (for example because hash is used to organize items) but, I think, a generic comparer should be ignorant of this.

if (hs.Comparer is EqualityComparerWithValue<T>)
    valOut = (hs.Comparer as EqualityComparerWithValue<T>).Value;
else
    valOut = hs.First(t => t.Equals(valIn));

You first check for type and then you cast (which implicitly check for type again). It's a waste then you may simply rewrite as this:

var comparer = hs.Comparer as EqualityComparerWithValue<T>;
valOut = comparer != null ? comparer.Value : hs.First(t => t.Equals(valIn));

On the same code block you also have a return then you don't need else, save indentation and make code clearer:

   if (hs.Contains(valIn))
   {
        var comparer = hs.Comparer as EqualityComparerWithValue<T>;
        valOut = comparer != null ? comparer.Value : hs.First(t => t.Equals(valIn));

        return true;
   }

    valOut = default(T);
    return false;

However, beside these minor micro-design stuff, what I don't agree with is solution itself. I wouldn't expect an equality comparer to keep state for at least these reasons:

It would be the only one to do it. Astonishing.
When you use your hashset you have to remember to use that comparer.
It forces you to check for types (and it's something with a pretty bad smell, IMO).
You're putting helpers inside an unrelated class. O(1) search is something related to hashset not to a specific type comparer.
It doesn't work with inherited comparers (what if I want to reuse same code with my own special IEqualityComparer<T> class?)
It's not thread-safe!

However algorithm itself probably isn't for CodeReview. What I would do to mitigate some of these issues? I would accept another
IEqualityComparer<T> as input, you decorate that comparer to keep last match
but you delegate comparison to given implementation:

public sealed class EqulEqualityComparerWithValue<T> : IEqualityComparer<T>
{
    public EqulEqualityComparerWithValue(IEqualityComparer<T> comparer = null)
    {
        _comparer = comparer ?? EqualityComparer<T>.Default;
    }

    public bool Equals(T x, T y)
    {
        if (_comparer.Equals(x, y))
        {
            Value = x;
            return true;
        }

        return false;
    }

    public int GetHashCode(T obj)
    {
        return _comparer.GetHashCode(obj);
    }

    public T Value
    {
        get;
        private set;
    }

    private IEqualityComparer<T> _comparer;
}


Create a matrix where if an element in an M×N matrix is 0, its entire row and column are set to 0

comments

Comments should say why the code is like it is. Any other information to the reader should be given to the reader by the identifiers to chose.

Your comments structure the method in 3 logical sections (the first without a dedicated comment). You should better move this three sections into separate methods with names derived from the comments:

private static int[][] setZeroes(int[][] matrix) {
    boolean[] rowsWithZero = new boolean[matrix.length];
    boolean[] columnsWithZero = new boolean[matrix[0].length];

    findZeros(matrix,rowsWithZero,columnsWithZero);
    transformColumns(matrix,columnsWithZero);
    transformRows(matrix,rowsWithZero);

    return matrix;
}
private static void findZeros(int[][] matrix, boolean[] rowsWithZero, boolean[] columnsWithZero){
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
            if (matrix[i][j] == 0) {
                rowsWithZero[i] = true;
                columnsWithZero[j] = true;
            }
        }
    }
}
private static void transformColumns(int[][] matrix,  boolean[] columnsWithZero){
    for (int i = 0; i < columnsWithZero.length; i++) {
        if (columnsWithZero[i]) {
            transformColumn(i, matrix);
        }
    }
}
private static void transformRows(int[][] matrix, boolean[] rowsWithZero){
    for (int i = 0; i < rowsWithZero.length; i++) {
        if (rowsWithZero[i]) {
            transformRow(i, matrix);
        }
    }
}


Animating the appearance of a title with CSS

This can be achieved with one element and a CSS pseudo-element.

The html

<element class="animate right">Hello world!</element>

Add the animate class to any element that will have this animation
applied to it.
Add a left or right class in order to specify which direction the animation should travel

The pseudo-element

.animate::before {
    content: '';
    position: absolute;
    background: #ff0;
    width: 100%;
    top: 0;
    bottom: 0;
}

The pseudo element is positioned absolute, 100% in width and stretched from top to bottom with top: 0 and bottom: 0.

There are two animations, left and right which have their own class:

.right::before {
    animation: sliderRight 2s forwards;
}

.left::before {
    animation: sliderLeft 2s forwards;
}

The animate class

Any element that you want to add this animation to will be given this class:

.animate {
    position: relative;
    color: transparent;
    padding: 10px;
    overflow: hidden;
    display: inline-block;
    margin: 20px;
    animation: textappear .1s .5s forwards;
}

The position: relative will make the position: absolute ::before pseudo-element child position itself relevant to the .animate parent.
The element must be inline otherwise the wiping animation will take the entire width of the screen (unless you use a width)
The overflow: hidden will cut off the animation correctly

The sliding animations

@keyframes sliderRight {
    0% {
        right: 100%; /*Push the element 100% from the right side*/
    }

    100% {
        right: -100%; /*Pull the element from left to right*/
    }
}

@keyframes sliderLeft {
    0% {
        left: 100%; /*Push the element 100% from the left side*/
    }

    100% {
        left: -100%; /*Pull the element from right to left*/
    }
}

Complete example

.animate {
  position: relative;
  color: transparent;
  padding: 10px;
  overflow: hidden;
  display: inline-block;
  margin: 20px;
  animation: textappear .1s .5s forwards;
}
.animate::before {
  content: '';
  position: absolute;
  background: #ff0;
  width: 100%;
  top: 0;
  bottom: 0;
}
.right::before {
  animation: sliderRight 2s forwards;
}
.left::before {
  animation: sliderLeft 2s forwards;
}
@keyframes textappear {
  100% {
    color: #FFFE02;
  }
}
@keyframes sliderRight {
  0% {
    right: 100%;
  }
  100% {
    right: -100%;
  }
}
@keyframes sliderLeft {
  0% {
    left: 100%;
  }
  100% {
    left: -100%;
  }
}
/*Demo only*/

.animate {
  white-space: nowrap;
}
h1.animate {
  font-size: 5em;
}
body {
  margin: 0;
  padding: 0;
  background-color: #FE4D3D;
  font-family: arial;
}

Hello World!

Hello World!


I believe it's ok to use db data inside a validator's body. As long as all you do with database is reading data, and this data is neccesary for validation. But if you're about to change something in database - that's pretty considerable.

Then, if you can do something with this data, like caching it or smth, you may want to consider moving this part of validator's logic into some abstraction, like CountryCodeHandler or something like this.

I would also point out on your working with string values. I don't think it's good to use those "Not found" or "InvalidRequest" strings. If the string is exactly what you need, i'd advise you to use some static class:

public static class MyHttpStatusCode
{
    public const string NotFound = "Not Found";
    public const string InvalidRequest = "Invalid Request";
}

Thus, you'll get rid of duplicates in your code. Or, if those strings aren't that unavoidable, you can just use HttpStatusCode enum from System.Web (as i recall).

Also in modern versions of C# you don't need the "this" keyword to access to fields and properties those names arent match any variable inside the method or constructor. Unless it's your codestyle that declares such thing.

As for your controller part, i'd recommend you to use the Chain of Responsibility pattern. It will allow you to extend validation results and handle them properly.

public interface ICountryCodeValidationResultFilter
{
    ValidationError[] Filter(List<ValidationError> errors, out HttpStatusCode statusCode);
}
public interface IConcreteCodeValidationResultFilter
{
    bool CanFilter(List<ValidationError> errors);
    ValidationError[] Filter(List<ValidationError> errors, out HttpStatusCode statusCode);
}

public class CountryCodeValidationResultFilter : ICountryCodeValidationResultFilter
{
    private readonly IConcreteCodeValidationResultFilter[] filters;

    public CountryCodeValidationResultFilter(IConcreteCodeValidationResultFilter[] filters)
    {
        this.filters = filters;
    }

    public ValidationError[] Filter(List<ValidationError> errors, out HttpStatusCode statusCode)
    {
        if (errors.Any())
        {
            for (var filter in this.filters) // you may just write "filters" here
            {
                if (filter.CanFilter(errors))
                {
                    return filter.Filter(errors, out statusCode);
                }
            }
        }

        statusCode = HttpStatusCode.OK;
        return new ValidationError[0];
    }
}

public NotFoundCodeValidationResultFilter : IConcreteCodeValidationResultFilter
{
    public bool CanFilter(List<ValidationError> errors)
    {
        return errors.Any(e => e.Code == "Not Found");
    }

    public ValidationError[] Filter(List<ValidationError> errors, out HttpStatusCode statusCode)
    {
        statusCode = HttpStatusCode.NotFound;
        return new[] { errors.First(e => e.Code == "Not Found") };
    }
}

public InvalidRequestCodeValidationResultFilter : IConcreteCodeValidationResultFilter
{
    public bool CanFilter(List<ValidationError> errors)
    {
        return errors.All(e => e.Code != "Not Found");
    }

    public ValidationError[] Filter(List<ValidationError> errors, out HttpStatusCode statusCode)
    {
        statusCode = HttpStatusCode.NotFound;
        return errors.ToArray();
    }
}

Thus, your controller will look like this:

public class CountriesContoller : ApiController
{
    private readonly ICountryCodeValidator countryCodeValidator;
    private readonly ICountryCodeRepository countryCodeRepository;
    private readonly ICountryCodeValidationResultFilter countryCodeValidationResultFilter;

    public CountriesContoller(
        ICountryCodeValidator countryCodeValidator,
        ICountryCodeRepository countryCodeRepository,
        ICountryCodeValidationResultFilter countryCodeValidationResultFilter)
    {
        this.countryCodeValidator = countryCodeValidator;
        this.countryCodeRepository = countryCodeRepository;
        this.countryCodeValidationResultFilter = countryCodeValidationResultFilter;
    }

    public HttpResponseMessage Get([FromUri]string countryCode)
    {
        var errors = countryCodeValidator.Validate(countryCode);
        HttpStatusCode resultStatusCode;
        var filteredErrors = countryCodeValidationResultFilter.Filter(errors, out resultStatusCode);

        return Request.CreateResponse(resultStatusCode, filteredErrors.Any() ? filteredErrors : countryCodeRepository(countryCode));
        // i believe countryCodeRepository is not just Func, huh? perhabs it should be "countryCodeRepository.Get(countryCode)" ?
    }
}


Function to produce unique random numbers

Haskell is very different than other languages.

Here is how I would solve the problem:

import Control.Arrow
import System.Random

uniqueRandomInts :: (RandomGen g, Random a)
    => (a, a) -> Int -> g -> ([a], g)
uniqueRandomInts range n =
  (map fst &&& snd . last) . take n . iterate getNext . randomR range
  where getNext = randomR range . snd

What does this do?

First note that the g (generator) parameter isn't shown in the example, but it is there....  uniqueRandomInts range n returns a function of type

RandomGen g => g -> ([a], g)

so you will still need to apply this parameter in order to get the values.

I've also refrained from specifying the type of the return value at this stage....  This function is a tool that could be used for any type, why artificially bind it at this point?

The iterate getNext $ randomR range g part (where I've shown where the g will be applied) creates an infinite list of (a, g), where the a's are the random values, and the g's are the generators returned at each step.  (for reference, iterate f x is a function that returns [x, f x, (f.f) x, (f.f.f) x, ....]).

Passing around infinite lists is one of those mind blowing things to people who are coming to Haskell from other languages, but remember that the language is lazy, so no actual value will be calculated until requested (this is sort of how the human mind works....  If I ask you to imagine an infinite sequence of 1's, you can reason about it without actually sitting there trying to enumerate all the 1's in your brain before you go on).

We then apply take n to this, to take the first n values of the sequence (thus turning it into something finite before we actually need to calculate any of the values).

Finally, we have the mysterious (map fst &&& snd . last) part.  This isn't actually needed for the calculations themselves, but just to format the values in the way that you wanted them.  (func1 &&& func2) x applies the functions on the value x, and returns (func1 x, func2 x).  We are pulling out the random values in the first slot, and getting the last random generator for the second spot.

You can use this function as follows (because we kept things generic, you need to specify the type)

main = do
  g <- getStdGen
  print $ randomValues (1, 10::Int) 10 g

As to your particular questions:

As to the prefixing, Haskell has a vibrant community ecosystem where many people contribute code to the public, and some sort of prefixing is needed to keep things sane....  Of course this is only needed if you plan to contribute your code.  I personally don't prefix at all when I am writing something small for myself (why complicate things?), and can always add it if I need later.  If a personal project becomes larger, I can always add it.  This is pretty much how I programmed in Java also....
Pre-checking is very common and valuable in Haskell, however....  so is generality.  There is no reason that this particular function shouldn't be used by an numerical type over any range (would you want to rewrite the exact same function for a set of random floats over the range -1.0 to +1.0?).  I would personally place the limit check and type fixing higher up in the code....  And when I did, I would use the Data.Ix.inRange function.
I didn't use explicit recursion (it was used in a lower level function that I used), however I'll answer the general philosophy that I follow to determine if a subfunction should be top level or not....  I make a function top level if it describes a generic tool that others could use.  I usually use a "where" clause generally only for function documentation (ie- when the name of the variable describes what it is doing).  Sometimes you need to define a where clause variable for other reasons (ie- recursion or to avoid repetition), but strangely enough these are usually cases that you are better off writing around anyway (recursion and repetition are usually abstracted away in lower level calls like iterate and (&&&), which are cleaner to use anyway).  This isn't a hard fast rule though!  Not everything can be abstracted in some high level function yet.
I don't know :), however if you ever turn on -Wall in the compiler, it will complain every time you shadow another variable, so to avoid the nagging I usually try to change the name.  Sometimes choosing a different name becomes annoying, so I just turn off -Wall :)

EDIT-----

Oops, as you pointed out, I misread the problem....  You need unique values.

Luckily we can still use all the code above, with a slight addition.  Add this-

removeDuplicatesUsing::Ord b=>(a->b)->[a]->[a]
removeDuplicatesUsing f theList = [x|(Just x, _, _) <- iterate getNext (Nothing, theList, empty)]
  where
    getNext (_, x:xs, used)
      | f x `member` used = (Nothing, xs, used)
      | otherwise = (Just x, xs, insert (f x) used)

Then put one more filter in your randomValue pipeline-

(map fst &&& snd . last) . take n . removeDuplicatesUsing fst . iterate getNext . randomR range

Let me explain what is going on here

There are many algorithms to generate random unique values....  The unique part complicates things a bit, and depending on your circumstances, different algorithms work better.  I will discuss those cases later in this answer, but for now I chose the same algorithm that you used in your answer.
Because Haskell is lazy, adding another function filter in a bunch of composed functions barely takes a speed, memory or latancy performance hit.  Data will flow through the functions from right to left as it is generated, you will start to see results even before all the data has started to flow into the pipeline.  In this way, Haskell function composition is more like Unix pipe chaining than anything else.
In fact breaking things apart like this is my preferred way to do things.  By now I might have more code than if I wrote it all in one function, but each of these are simple, easy to debug tools that you could imagine reusing.
A removeDuplicates function (which I didn't write) would read a stream of values in, and filter out anything that it has previously seen.  This is almost what we need, but we want to base uniqueness on only the resulting random value (if we included the generator, it would always be unique!).  It is common in Haskell to write generalized -Using or -With functions that allow you to pass a function in to give the "key" that you want to use for comparisons (....and note that you can easily define removeDuplicates = removeDuplicatesUsing id).
I wrote the removeDuplicates in the same style as the uniqueRandomInts function (using a list of tuples generated by iterate)....  Writing out using recursion here might be easier to read, I guess it is just a matter of taste.  This feels more Haskell-y to me, and that was the point of this comparison.
I still left out the range check, but after reading your comment I reverse what I said above, I think it is a good idea to put it in!  (I looked too quickly and thought it was a value range, not a count range).

Finally, a note about algorithms (independent on the language chosen to write this).  If you are choosing n unique items from a range of N values....

If N and n are small --- It doesn't matter what algorithm you choose, they will all be fast.
If N is huge and n is small --- the given algorithm above works great.  It breaks down however....
as n approaches N in size --- Once a sizable percentage of N has been filled, you will start hitting many repeat hits (if 90% of the range has already been taken, only one in 10 tries will get something new).  You can of course flip the chosen and not chosen values (ie- generate the 10% you don't want, then return all the others), or you can move on to a solution of this type- https://stackoverflow.com/questions/196017/unique-random-numbers-in-o1.  While this is doable in Haskell, the part where you start swapping values in an array is trickier than in any mutable language (you basically either have to use IO around a mutable array, or start making copies of the initial array, which Haskell can do much more efficiently by reusing parts of the initial array in the copied version, but still, less efficient than just doing mutating swaps....  Someone else might have a better suggestion than this....).
If N is really large, holding all values in an array in memory might not be practical.  In this case, you might want to use some sort of "unsort" command line tool (a few of these exist in Unix), do a one time pass over all the values, and then take the first n elements of the list.
If N is huge, and you don't care that n come out precisely, you can always do something statistical (do one linear pass and accept each value with probability n/N).  This should be much faster than method (4), but of course you won't get exactly n values, and you can't just truncate early, or else you will be favoring earlier values over latter ones.