... the problem clearly visible here that I am trying to push event oriented code into my object oriented world

There is nothing wrong with object oriented and event oriented code being intermingled. It's like saying "toast and jam should not be used in the same breakfast." Not only can you mix the two, depending on your needs you should mix the two. The "problem" I think you're referring to is mixing object oriented with functional programming.

Since this is JavaScript, and it handles both programming paradigms good enough, feel free to mix the two. The only thing to consider is "callback Hell" where you have callbacks nested inside callbacks. For this, the Promise Pattern was created.

On to my favorite subject, naming things.

In the StdIn constructor, the argument is called opt_name, yet everything else appears to be written in camelCase. Pick either snake_case or camelCase and be consistent. To be consistent with other API's I would recommend camelCase
The opt_name argument could just be called name since there is not ambiguous reference between the argument and the property on the StdIn object
Rename the rs property to something meaningful, like:

readStream
input
inputStream
stream

Otherwise I don't see any glaring issues.


From a once over:

Your indenting is off, this might be a copy paste problem into the question, consider using jsbeautify
You never use var co = color;, throw it away
(r1 == g1 && r1 == b1 && g1 == b1) consider that if r1 = g1 and r1 = b1, then g1 must be equal to b1 so you can use the simpler (r1 == g1 && r1 == b1)
I am not sure why you update the bitmap AND create a new image, I would do only 1 of these for extra speeds
r0,g0,b0 and r1,g1,b1 are not the most intuitive variable names..
Consider caching the values of colorRGBBound(r0 * (r1 / 255)); , there are only 255 possibilities for the value of r1 and you can use the same cache for r1,g1 and b1


Passwords as plain text!?
If I were using an application or website that stored my password as plain text where anyone with access to the DB seeing this would make me feel very scared:
// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

For the love of your users, please consider password hashing!

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application's database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

Redundancy
This:
public function insert($arg)
{
    $this->_sql .= "INSERT INTO {$arg}";
    return $this;
}

public function columns($arg)
{
    $this->_sql .= " ({$arg})";
    return $this;
}

public function values($arg)
{
    $this->_sql .= " VALUES ({$arg})";
    return $this;
}

And this:
// inserts into database
$query->insert('users')
        ->columns('`username`,`password`')
        ->values('"test","tester"')
        ->execute();

That seems redundant, unless you plan on inserting user names and passwords in different tables/columns. Why not shorten it like this:
public function insert($arg)
{
    $this->_sql .= "INSERT INTO users (`username`, `password`) VALUES ({$arg})";
    return $this;
}


Time Complexity

Although you should always profile when concerned with performance. I'll go out on a limb here and make an educated guess.

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            v.set(x, y);
            if (spots.contains(v, false)) {
                c.a = 1;
                p.drawPixel(x, y, Color.rgba8888(c));
                continue;
            }
            c.a = calcAlpha(v, spots);
            p.drawPixel(x, y, Color.rgba8888(c));
        }
    }

Here spots.contains and calcAlpha are both \$\mathcal{O}(n)\$ where \$n\$ is the number of spots. This means that for example the inner most loop of calcAlpha:

    for (Vector2 v : spots) {
        a += 1f / Math.sqrt(Math.pow(pos.x - v.x, 2) + Math.pow(pos.y - v.y, 2));
    }

is executed \$w \cdot h \cdot \frac{w\cdot h}{5000} = \frac{(w\cdot h)^2}{5000} = 169869312\$ times for 1280x720 (which I gather from your screenshot). Notice the square on \$w\cdot h\$? That's your problem.

How to solve it? Well you can use a HashSet for spots, this reduces spot.contains to \$\mathcal{O}(1)\$ amortized. But you're still left with calcAlpha.

You need to come up with a smarter algorithm that doesn't have to iterate over all the spots for all pixels.

Cache Efficiency

The CPU has a little thing called a "pre-fetcher". Simply put when you ask for memory address x it will also make sure that x+1 and x-1 are in the CPU cache. This means that linear access of memory is much faster than any other way of addressing memory. Particularly, "randomly" accessing memory is bound to give you a metric f-ton of cache misses and your performance will be a proper charlie-foxtrot.

I am not aware of any graphics library or hardware that stores images in column-major mode. This means that you should always process images, row-by-row. Meaning that the x coordinate should always be the inner most loop.

I.e. this:

for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {

should be:

for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {

for maximal performance (note the swapped order of x and y).

Improved Algorithm

The key idea to note for improving the algorithm is that each of the spots has the same influence on it's neighbourhood. I.e. all the distance calculations for each dot are the same, just with a different offset. This means that we can pre-calculate the results once and just blit.

Define radius as the radius in pixels from a spot where you cut off it's influence on the image.

Below is pseudocode to show the idea. It may contain bugs, and there is definitely some assembly required. Like checking image bounds and using a 1D dense array instead of a 2D nested array (which is done for clarity):

// Prepare alpha-map.
// Time: O(radius^2)
float[][] alphaMap = new float[2*radius+1][2*radius+1];
for(int y = 0; y < 2*radius + 1; ++y){
    for(int x = 0; x < 2*radius +1; ++x){
        int dx = x - radius;
        int dy = y - radius;
        int hypot2 = dx*dx + dy*dy;
        if(dx == 0 && dy == 0){
            alphaMap[y][x] = 1.0f;
        }else if (hypot2 < radius*radius){
            alphaMap[y][x] = 1.0f / Math.sqrt(hypot2);
        }
    }
}

// Calculate alpha values for entire image at once
// Time: O((w*h)*radius^2)
float[][] alphaBuffer = new float[height][width];
for(spot : spots){
    int xMin = spot.x - radius;
    int xMax = spot.x + radius +1;
    int yMin = spot.y - radius;
    int yMax = spot.y + radius +1;
    for(int y = yMin; y < yMax; ++y){
        int dy = y - spot.y;
        for(int x = xMin; x < xMax; ++x){
            int dx = x - spot.x;
            alphaBuffer[y][x] += alphaMap[radius + dy][radius + dx];
        }
    }
}

Note that this has the same asymptotic time complexity as OP's own answer \$\mathcal{O}(whr^2)\$. But this computes the reciprocal of the hypotenuse only \$\pi r^2\$ times while OPs answer does it \$\frac{wh}{5000}\pi r^2\$ times. The calculation of the reciprocal of the hypotenuse is the most time consuming part in this algorithm and should dominate the execution time.

Note: The observant reader will have noticed that the alphaMap grid is symmetrical in all quadrants. This means you can reduce the number of calculations of the reciprocal of the hypotenuse to \$\frac{\pi r^2}{4}\$ but that's left as an exercise to the reader.


What I don't like in your solution

In the latest version of Mongoose, save can also return a Promise. The "problem" with your code is that when you are saving you are using a callback, which defeats the purpose of Promises overall.

How I would do it

This is how I would implement using Promises:

function incrementSessionTypesTotal(req, res) {
    return Total.findOne({dP: "xyz"})
        .then(doc => {
            incrementSessionsTypes(req, res, doc));
            return doc.save();
        })
        .then(() => {
            sendJsonResponse(res, 200, data);
        })
        .catch(error => {
            sendJsonResponse(res, 400, err);
        });
}

Following the code flow

Following the code flow, without the callbacks it is clear what you do.

First you findOne
After finding an object, we increment it. If doc===null then the increment function will throw an exception, which will be caught later on.
Then we save it. Remember I said save can also return a Promise? Well, because Promises are monads (sort of) if you return a Promise  within a then, its result will follow the chain!
Save was successful, send message!

Problems with my solution

As you may have guessed ... this solution catches any error and sends the same response for all of them (400).

With this structure, if you want error differentiation, the only thing you can do is to detect an error occurred, build an object with that information and then throw it:

.then(doc => {
    if(doc === null)
        throw {reason: "ObjectNotFound"};

    incrementSessionsTypes(req, res, doc));
    return doc.save();
})
.catch(error => {
    if(error.reason === "ObjectNotFound")
        sendJsonResponse(res, 404, err);
    else if(error.reason === "Something else ")
        sendJsonResponse(/*you get the idea*/);
    else //if we don't know the reasons, its because the server likely crashed
        sendJsonResponse(res, 500, err);
});

Another solution would be to have an ErrorFactory and/or to subclass your errors.

I personally don't find any of these solutions particularly attractive because it means you will have a huge if then else chain of statements in your catch block, if you want error differentiation.

This is an issue I am still fighting with, but its up to you.

Hope it helps!

EDIT EDIT EDIT

In another question I posted what I believe to be the solution to complete error differentiation while using promises (see solution 2):

https://codereview.stackexchange.com/a/159593/59328

That post also has a good example of classical error building and differentiation, alongside an analysis of its limitation (solution 1).

I hope you enjoy!


Prevent multiple ifelse statements in php

Try something like this

<?php

function buildErrorMessage($message, $row = null, $header = null, $fieldValue = null) {

    if ($row) {
        $message .=  ": row {$row}";
    }

    if ($header) {
        $message .=  ", header {$header}";
    }

    if ($fieldValue) {
        $message .=  ", value \"{$fieldValue}\"";
    }

    return $message;
}

// Tests
echo buildErrorMessage('one');
echo buildErrorMessage('two', 2);
echo buildErrorMessage('three', 3, 'header');
echo buildErrorMessage('four', 4, 'header', 'value');
echo buildErrorMessage('five', null, null, 'value');


Event rate limiter
It is important to use the correct terms when defining functions. If you are unsure it is always better to look up the literature to ensure you are using the term correctly.
Debouncing
You have not implemented a de-bounce. De-bounce delays action on an event to prevent it firing in rapid succession.
The term comes from ye old day hardware where the mechanical switch would have a tendency to bounce on the contacts, giving a series of on/off signals when only one was intended.
In Javascript we use de-bounce to prevent events that fire at high rates (eg mouse resize) from firing at a rate higher than is useful, (eg screen refresh rate.)
You could implement a de-bounce as follows
const debounce = {
    debounceTime : 33, // in ms
    timeoutHandle : undefined,
    ondebounced(event) {
        log("Resized");
    },
    event(event) {
        clearTimeout(debounce.timeoutHandle);
        debounce.timeoutHandle = setTimeout(debounce.ondebounced, debounce.debounceTime, event)
    }
}
addEventListener("resize",debounce.event);

It will wait 33ms after the last resize event before calling the de-bounced function.
Rate limiter
You have implemented a rate limiter, that forces an event to fire at a set maximum rate. The difference are minor,

De-bounce fires after the events (signal noise) while a rate limiter fire as soon as possible.
De-bounce delay is indeterminate, while rate limiting has a fixed determinate delay.

Your code
Your code is a little old school. You should keep up with the lates JS version ES8.

You should be using const when you intended variables not to change.
Use arrow functions.
Use the spread / rest tokens for passing unknown arguments. See example

You also are mixing a variable's use. The var timeout. This may not cause you trouble at the moment and seem like a good idea to reduce code size by doubling a variables meaning, (means timeoutHandle, and Block events) But will bite if in future you make changes and forget that timeout is more than just a handle.
Never mix a variables meaning without making it clear in the name
Example
The following is an example of how you could implement a rate limiter.
The functionality is encapsulated and access is only via getters and setters to prevent miss use. See comments for more. This is only an example, not a definitive how too.

    // Encapsulated rateLimit event utility
    const rateLimit = (()=>{
        const rate = 2000;  // the max rate in ms

        // the limiting functions, pass the event to call
        // returns an API for handling the events.
        return function (eventFunc){
            var handle;  // for unblock event
            var blocked = false;  // true if blocked
            var event;  // the event to call if not blocked
            // this function handles the incoming event
            const eventHandler = (...eventArgs) => {
                if(blocked){
                    log("Event blocked. Too fast.")
                }else{
                    API.block = true;
                    if (event) { event(...eventArgs) }
                }
            }

            // the API
            // block bool (write only) set to true will block events for
            // rate but only if not already blocked. Set to false to clear any blocking
            // blocked returns (read only) bool for current blocking state
            // onlimitedevent  read/write function to call on event. If not a function then clears the event
            // event read only gets the event to attach to the listener
            const API = {
                set block(value) {
                    if (value && !blocked) {
                        handle = setTimeout(()=>API.block = false, rate);
                        blocked = true;
                    } else if (!value && blocked) {
                        clearTimeout(handle); // incase unblock is from outside
                        blocked = false

                    }
                },
                get blocked() { return blocked },
                set onlimitedevent(func) { event = typeof func === "function"  ? func : undefined },
                get onlimitedevent() { return event },
                get event() { return eventHandler },

            }
            API.onlimitedevent = eventFunc;
            return API;
        };

    })();

    const clicker = rateLimit(() => {log("clicked")});
    document.body.addEventListener("click", clicker.event);
    log("Ready, click me to test.");

    function log(...data) { out.appendChild(Object.assign(document.createElement("div"),{textContent : data.toString()})) }


It's likely not a huge improvement, because the vast majority of this program's time will be spent going over the network, but there is a micro-optimization you can make here.

Instead of latebinding like this

With CreateObject("msxml2.serverXMLHTTP")

You can early bind your objects, eliminating the time COM takes to do a dynamic lookup. However, the time this saves will be minuscule compared to the total runtime.

I'm not bashing on VBA, I <3 VBA, but it's just not the right tool for the job if you need it to run faster than this. What you really need is a language that's capable of multi-threading and asynchronous programming to make the most of the CPU time while you're waiting for those Http requests to return. Sounds like it's time to learn some C# or F# to me. Even Powershell may be a good option.


The first example is a violation of the open/closed-principle. You shouldn't need to extend the class in order to change the routes. There doesn't seem to be any other way to use the class without extending it.

class Router {
    protected $routes = [];

    protected function getRoute(Request $req) {
        // ...
    }

    public function handle(Request $req, Response $res) {
        $fn = $this->getRoute($req);
        call_user_func($fn, $req, $res);
    }

    public function setRoutes(array $routes)
    {
        $this->routes = $routes;
    }

    public function addRoute($method, $path, $fn) {
        $this->routes["$method $path"] = $fn;
    }
}

Instead of setting method as values for the routes, use a callable. This can be a function, method, closure or invokable object.

A user may still choose to extend it and initialize in the constructor if he really wants to.

class GeneralRouter extends Router {

    public function RootRoute (Request $request, Response $response){
       // ...
    }

    public function PageRoute (Request $request, Response $response){
       // ...
    }

    public function __construct() {
        $this->setRoutes([
            'GET /' => [self::class, 'RootRoute']
            'GET /:page/' => [self::class, 'RootRoute']
        ]);
    }
}

Adding a get, post and delete method to the Router class would just add micro framework syntax for those who like it, but it wouldn't fundamentally change the router.

Last, do not invent your own custom Request and Response objects. Use PSR-7 to ensure interoperability with libraries and test suites. There is Zend Diactorors and Jasny HTTP message (developed by me).


var zipFile = ZipFile.OpenRead(ChapterLocation);
    ...
    zipFile.Dispose();

One word: using.

    using (var stream = z.Open())
    {
        using (var mstream = new MemoryStream())
        {
            stream.CopyTo(mstream);
            mstream.Position = 0;

            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = mstream;

            bitmap.EndInit();
            bitmap.Freeze();

This needs a comment explaining why mstream is necessary and you can't just use stream.

I suspect that really mstream is either unnecessary or insufficient. If it's necessary then it's probably because of threading issues due to multiple ZipArchiveEntry streams all reading from one backing stream, and in that case doing the read with stream.CopyTo might be reducing the probability of the problem surfacing rather than actually fixing it.

    foreach (ZipArchiveEntry z in zipFile.Entries)
    {
        Thread t = new Thread(() => BitmapLoad(z));
        t.Start();
        t.Join();
        Debug.WriteLine(z.Name);
    }

Ah, it's not really multi-threaded after all. If you want to do old-school multithreading then you need to spin off all of the threads before calling Join().

I say "old-school" because a more modern approach would be to use Parallel Linq. Bearing in mind my previous comment about streams, the approach would probably be to map the entries to (string Name, MemoryStream ms)s in one thread and then map those tuples to Pages in parallel threads. I think that this can be written as

Pages = zipFile.Entries.
    Select(z => Read(z)).
    AsParallel().
    Select(tuple => LoadPage(tuple)).
    OrderBy(page => page).
    ToList();

but I haven't really used Parallel Linq myself, and I don't guarantee that this does the Read calls all in the same thread.


I rewrote parts of your code (see below).  I did not have enough time to complete the refactoring, so it is far from I would really want to see, but at least it is not Fortran anymore.

You can use trait instead of abstract class.  It is more flexible.
The names, pretty much all names, are very uninformative.  Why uDev for a distribution?
You should separate the printing of reports from the actual algorithm (separation of concerns).  This advice applies to all languages, not just Scala.
Avoid using recursion.  It is like the assembly language of functional programming.  Use reduce and such instead.
It looks like you don't know about "string" + " " + "concantetation" or, even better, interpolation: s"Hello, ${name}".
In an if expression, when the code at the start of both if and else is the same, you should pull that code out.
You call min(sigs) twice in a row.  You should set a variable with that value and use it twice.
You can shorten the imports: import math.{log, sqrt}.  You should also explicitly write out all imports instead of doing a bulk import (import breeze.linalg._).  I was confused by where min was coming from.
Terminating a recursive loop on l == 1 looks odd in Scala; it's usually on 0.
I'm usually a big fan of breaking everything in small functions, but metCheck is so important that I think the computation should be left as code where it is called.
Don't pass acc to hmcUpdate.  That function has no business dealing with that accumulator (separation of concern).
The OO/functional design was pretty much inexistent.  I did some, but it is currently very poor due to lack of time.  A good design greatly improves readability.  You should spend some time to properly break everything down in classes.  And then think some more about it and do it, etc.

After some partial refactoring:

  val unifDist = new Uniform(0.0, 1.0)
  val normDist = new Gaussian(0.0, 1.0)

  // Poor names.  I don't know what they are.
  val l = ul
  val ep = ue

  type Position = DenseVector[Double]
  type Momentum = DenseVector[Double]
  case class HamState(q: Position, p: Momentum)

  def leapFrogStep(potentialEnergy: PotentialEnergy, uep: Double)(hamState: HamState): HamState = {
    val q = hamState.q + (hamState.p :* uep)
    val p = hamState.p - (potentialEnergy.calcGradU(hamState.q) :* uep)
    HamState(q, p)
  }

  def leapFrogMomemtumHalfStep(potentialEnergy: PotentialEnergy, uep: Double)(hamState: HamState): HamState = {
    val p = hamState.p - (potentialEnergy.calcGradU(hamState.q) :* uep) / 2.0
    HamState(hamState.q, p)
  }

  trait PotentialEnergy {
    def calcU(q: Position): Double
    def calcGradU(q: Position): DenseVector[Double]
    def computeTotalEnergy(hamState: HamState) = calcU(hamState.q) + (hamState.p dot hamState.p) / 2.0
    // I don't have the slightest idea what uep is...
    // I put it in this class, but it certainly does not belong here.
    def uep(): Double
  }

  case class WhateverSigsIsPotentialEnergy(sigs: List[Double]) extends PotentialEnergy {
    override def calcU(q: Position) = calcU_(q, sigs)
    override def calcGradU(q: Position) = calcUgrad_(q, sigs)
    // uep does not belong here.  It should not access "global" ep or uDev.
    override def uep = ep * min(sigs) * min(sigs) * (0.9 + 0.2 * unifDist.sample()) // perturb ep, l pm 10% to avoid cyclic orbits
  }

  def hmcStep(potentialEnergy: PotentialEnergy)(q: Position): Option[Position] = {
    val uep = potentialEnergy.uep
    val nSteps = (l.toDouble * (0.9 + 0.2 * unifDist.sample())).toInt

    val p = DenseVector(normDist.sample(q.length).toArray)
    val h = potentialEnergy.calcU(q) + (p dot p) / 2.0
    val initState = HamState(q, p)

    def halfStepper = leapFrogMomemtumHalfStep(potentialEnergy, uep)(_)
    def fullStepper = leapFrogStep(potentialEnergy, uep)(_)
    def fullPathTransform = (halfStepper :: List.fill(nSteps - 1)(fullStepper)) :+ halfStepper
    val state = fullPathTransform.foldLeft(initState) { (state, stepper) => stepper(state) }

    val energyChange =
      potentialEnergy.computeTotalEnergy(state) - potentialEnergy.computeTotalEnergy(initState)
    if (unifDist.sample() < math.exp(-energyChange))
      Some(state.q)
    else
      None
  }

  type GibbsSomethings = List[Double]
  case class PositionAndGibbs(pos: Position, gibbs: GibbsSomethings)

  /**
   * @return Boolean true if the generated position is different than the previous one.
   */
  def hmcAndGibbsStep(potentialEnergy: PotentialEnergy)(positionAndGibbs: PositionAndGibbs): (PositionAndGibbs, Boolean) = {
    var posOption = hmcStep(potentialEnergy)(positionAndGibbs.pos)
    var pos = posOption.getOrElse(positionAndGibbs.pos)
    var gibbs = gibbsUpdate(pos)
    (PositionAndGibbs(pos, gibbs), (pos != None))
  }

  def hmcRunner(potentialEnergy: PotentialEnergy)(maxIt: Int, prevState: PositionAndGibbs): List[PositionAndGibbs] = {

    val infiniteStream: Stream[(PositionAndGibbs, Boolean)] = {
      def loop(stateAndBool: (PositionAndGibbs, Boolean)): Stream[(PositionAndGibbs, Boolean)] =
        stateAndBool #:: loop(hmcAndGibbsStep(potentialEnergy)(stateAndBool._1))
      loop((prevState, false))
    }

    val finiteStream = infiniteStream.take(maxIt)

    val visitedStates = finiteStream.foldLeft(List[PositionAndGibbs]()) {
      case (visitedStates, (posAndG, isNew)) =>
        posAndG :: visitedStates
    }
    visitedStates

    // To print some report every "iter" iterations:
    //  1) change the foldLeft above so it also counts the "isNew"
    //  2) instead of calling once ".take(maxIt)", write a function that
    //     only takes "iter" at a time an then prints out some report.
    //     Call that method until the total number of iterations reaches "maxIt".
  }


Yes, in this case it is. As you stated yourself it has "no more meaning". It only exists for the purpose of styling.

This is what the MDN has to say about div:

  The HTML Content Division element () is the generic container for
  flow content. It has no effect on the content or layout until styled
  using CSS.

  As a "pure" container, the  element does not inherently represent
  anything. Instead, it's used to group content so it can be easily
  styled using the class or id attributes, marking a section of a
  document as being written in a different language (using the lang
  attribute), and so on.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div


The require line in the first file means that ruby runs the second file before the first file, which is before the version method is declared...

Doing it the other way around will work, since only when  included is called is the module Element is required.

dialect/dialect.rb:

module Dialect
  def self.included(caller)
    caller.extend Dialect::Generator::Element
  end

  def self.version
    "Dialect v#{Dialect::VERSION}"
  end
end

dialect/generators/elements.rb:

require 'dialect/dialect'

module Dialect
  module Generator
    module Element

      puts Dialect.version

    end
  end
end

Alternatively, you could also write a file declaring only the version:

dialect/version.rb:

module Dialect
  def self.version
    "Dialect v#{Dialect::VERSION}"
  end
end

Edit

To answer your question - this is not a good way to do this. The problem you encountered with the require hints to circular dependency - Dialect calls Element, which uses Dialect on its creation.

The correct resolution is to break this dependency by using my version.rb suggestion above, so the code will look like this:

dialect/version.rb:

module Dialect
  def self.version
    "Dialect v#{Dialect::VERSION}"
  end
end

dialect/generators/elements.rb:

require 'dialect/version'

module Dialect
  module Generator
    module Element

      puts Dialect.version

    end
  end
end

dialect/dialect.rb:

require 'dialect/version'
require 'dialect/generators/elements'

module Dialect
  def self.included(caller)
    caller.extend Dialect::Generator::Element
  end
end


Determining which octant has a specific point

I am convinced that it is possible to make a shorter and more readable code.

To implement the discrete analog of atan2((B.y - A.y), (B.x - A.x)):

x, y  = (B.x - A.x), (B.y - A.y)
octant = [([1, 2], [8, 7]), ([4, 3], [5, 6])][x < 0][y < 0][abs(x) < abs(y)]

It is shorter, I don't know about readability. It is easy to write tests that check all possible variants including the behavior on the boundaries.


First off, I see no reason to define p1 and p2, then put them into the playerlist, it would be more concise to simply define them inside plist's definition.

eg.

plist = [Player(1,'X'), Player(2, 'O')]

As for the repetition of the if statements, you could set a global variable "gameOver" that gets set true upon a game ending event.

eg.

#Before loops
gameOver = False

...

    #In for loop
        if not win and i<9:
            pass
        elif not win and i==9:
            gameOver = True
            print('The match is a tie.')
            break
        else:
            gameOver = True
            break
    #In first while loop
    if gameOver:
        break
    else:
        pass

This last part is just personal opinion, but I feel like asking the user for row and column would be more intuitive than cell number.

Edit: I just realized you could just do while not gameOver, no need for the if else.


Calculating the distance between each pair of points is expensive. Since the coordinates are all integers, you can first calculate which delta-x and delta-y can lead to the distance 2018 at all. Define a function candidates(point, set) that filters the possible candidates. To do this efficiently, group the points by their x coordinate. Then, for a given x, you only have to look at a few of these groups.

Grouping the points improves performance because grouping has complexity around \$\mathcal O(n)\$, where \$n\$ is the number of points.

Afterwards, finding the candidate points is a simple lookup: for each delta in (-2018, -1680, -1118, 0, 1118, 1860, 2018) you need one lookup, which again sums up to \$\mathcal O(n)\$.

In summary, the number of comparisons will be much less than the \$n\cdot n\$ from your current code.


Determine if one string occurs at the end of another

A few notes:

Analyzing your code, I see a simple bug that isn't accounted for.  Consider the following case:

char *s1 = "Man is a rope stretched over an abyss.";
char *s2 = "an abyss..c9f0c50bc2e417b078e3b0bf82d5386d418cfba4";

Your method still returns 1 even though it clearly shouldn't, because you only checked for \0 in *s and not in *t.  You need to check if the NULL terminators are in matching positions.  Also, s2 is clearly a larger string than s1, we never compared the lengths to see if s2 could even fit into s1.
You are somewhat approaching this inefficiently.  You are comparing all of the characters in the string.  You don't need to do this, we can just compare at the index strlen(s) - strlen(t).
You could shorten your while loop a bit.

    while (*s == *t) {
        if (!(*s)) {
            return 1;
        }
        s++;
        t++;
    }

Increment *s and *t inside of your while test conditional.
You could also forgo the while loop completely and use the standard function strncmp().  However, I would use memcmp() since it is faster.
You wouldn't need the function prototype if you define your strend() function before you define main().
What if you pass an invalid string to your function?  Right now it can't handle it and will throw a "Segmentation fault".  That's not any fun, so let's implement a simple test to check for that.

if (!s || !t) return 0;

Based on the discussion between @RolandIllig and myself, I have decided to not implement this check.  Why?  Because this is a runtime check that comes with a certain overhead time to process.  That time may not be much, but on certain systems (such as embedded ones) that processing power would be better used somewhere else.  Therefore, I decided to follow the philosophy behind the design of the C standard library: that the programmer is ultimately in the best position to know whether a runtime check really needs to be performed.
I'm not sure how you want to handle empty strings.  I'm not going to mess with that too much since there was nothing stating so in the exercise.
You should document all of your code.  Even for a simple function such as this.

Final Product

#include <string.h>  // strlen(), memcmp()

/**
 * @fn int strend(const char *s, const char *t)
 * @brief Searches the end of string s for string t
 * @param s the string to be searched
 * @param t the substring to locate at the end of string s
 * @return one if the string t occurs at the end of the string s, and zero otherwise
 */
int strend(const char *s, const char *t)
{
    size_t ls = strlen(s); // find length of s
    size_t lt = strlen(t); // find length of t
    if (ls >= lt)  // check if t can fit in s
    {
        // point s to where t should start and compare the strings from there
        return (0 == memcmp(t, s + (ls - lt), lt));
    }
    return 0; // t was longer than s
}

Tests and Benchmarking

Here are a few trial runs I did of the method, and their output.  All seems well by the tests.

strend("Man is a rope stretched over an abyss.", "an abyss..c9f0c"); returns 0.
strend("Man is a rope stretched over an abyss.", "an abyss"); returns 0.
strend("Man is a rope stretched over an abyss.", "an abyss."); returns 1.
strend("Man is an man man.", "an man."); returns 1.
strend("an abyssan abyssan abyssan abyss.", "an abyss."); returns 1.
strend(NULL, NULL); returns 0.

Using a benchmarking program I wrote to profile the code, I tested your function as well as the others supplied against mine.  Here are the results, averaged out over 100000000 test iterations:

Search string: simple
End string: le
syb0rg's function average runtime: 1.47728e-08 seconds
ao2130's function average runtime: 1.87163e-08 seconds
Edward's function average runtime: 2.29287e-08 seconds
Josay's function average runtime: 2.58304e-08 seconds

Search string: this is a test
End string: test
syb0rg's function average runtime: 1.81173e-08 seconds
ao2130's function average runtime: 4.7522e-08 seconds
Edward's function average runtime: 2.31506e-08 seconds
Josay's function average runtime: 4.62652e-08 seconds

Search string: this is a longer string and may cause certain functions to take a bit longer to process
End string: a bit longer to process
syb0rg's function average runtime: 3.17312e-08 seconds
ao2130's function average runtime: 2.44403e-07 seconds
Edward's function average runtime: 3.33028e-08 seconds
Josay's function average runtime: 3.25736e-07 seconds

As you can see, my function runs a tiny bit faster than yours and the other functions supplied here (watch the scientific notation).


How to collect reference values from hashmap?

unsafe {
        key.as_bytes_mut().sort();
    }

This works as long as you are working in Ascii, but will have undefined behavior if there is any unicode in the string.
 (*map.entry(key).or_insert(vec![])).push(s);

You don't need the dereference *, calling a method will automatically take care of that.
Its a bit tricky to help with your main question since I don't know what exactly you tried and why that didn't work.
A pretty direct translation of what you wrote into iterator syntax works:
map.values()
    .map(|v| v.iter().cloned().cloned().collect::<Vec<String>>())
    .collect()

I would however suggest doing something more like your second code block, and avoid cloning the strings:
    map.values().cloned().collect::<Vec<Vec<String>>>()

I'd do this:
 map.into_iter()
    .map(|(_key, values)| values)
    .collect()

By consuming the iterator we avoid cloning the vectors.
Alternatively, take the strings as input by reference and return them by reference:
pub fn group_anagrams(strs: &[String]) -> Vec<Vec<&String>> {
    let mut map: HashMap<String, Vec<&String>> = HashMap::new();
    for s in strs {
        let mut key = s.clone();
        unsafe {
            key.as_bytes_mut().sort();
        }
        (*map.entry(key).or_insert(vec![])).push(s);
    }

    map.into_iter()
        .map(|(_key, values)| values)
        .collect()
}


Trait for specifying a type parameter for Into::into

The most common way to handle type-hinting Into::into in stable Rust today is via temporaries. So for the use case you have here, I'd probably write something like:

let clip = {
    let clip: models::Clip = clips::table_find(id).first::<db::Clip>(&*conn)?.into();
    clip.with_associations(&*conn)?
};

But honestly, I don't think anyone will get up in arms about you using TypedInto. I know I've typed .into::<Type>() a couple times, and the common place you'd see the turbofish, .collect::<Vec<_>>(), is exactly this.

For this specific case, why don't you make a common db::T -> model::T conversion? It seems to be a common thing that happens, so making it explicit may be beneficial.

But that said, why don't we take a look at nightly feature gates? Because since 2015 the RFC for Type Ascription has been merged. It introduces an expr : ty syntax to the language meant to address cases like this. So rewriting your example to use type ascription,

let clip = ((clip::table.find(id)
    .first(&*conn)? : db::Clip)
    .into() : models::Clip)
    .with_associations(*&conn)?;

Unfortunately, the binding of type ascription, while the same as as, is lower than method call syntax (.), so the parenthesis are necessary (and rustfmt would probably not approve of the formatting I used here). There is a patch written which would cause type ascription to bind more tightly than method calls, but it was closed in favor of waiting to later RFC the change (which would be backwards compatible (probably)).

There has been some recent noise around the feature, since it would make working with Futures a lot easier (though impl Trait may also help as well). Stabilization (since it has been approved through RFC) is blocked on ensuring soundness and allowing &[1, 2, 3] : &[u8] to work, so if you'd love to see type ascription stabilize, you can help with one of those.


Should i throw exceptions in the service layer or repository, and catch it on the controller?

the idea that an exception should be thrown in exceptional cases is very vague, for example, if I can't find a user in my data source (repository) I can't continue the flow of my code, can this be considered exceptional?

My personal approach is I raise an exception if encounter a scenario where during code execution, I make a truthy assumption but that assumption turns out to be falsey. So in your example, if you can't continue the expected code execution path without a valid user object returned from the repository, throw an exception at the point where your having a user assumption turns out to be false.
Where to initially throw and exception and where to catch depends on the use case. The rule of thumb I tend to follow is thrown an exception as soon as I can't continue or recover the desired code execution path, then allow that exception to propagate back up the stack to a place that understands how to handle that exception. Don't catch an exception if all you're going to do is re-throw.

Is it "correct" that my repository does not throw exceptions, and only returns null/false when it cannot return an entity? if not, what is the problem?

I would say this is acceptable. There might be occasions where a falsey response from your repository is not exceptional and is perfectly acceptable. I would also argue it's not the responsibility of the repository to decide if a falsey response is acceptable or not (for example when checking the existence of a record).

if my repository throws exceptions, should my service capture them and re-launch them as service exceptions? is this considered flow control?

Catch an exception where you intend to handle that exception. Sometimes it does make sense to catch and re-throw an exception, such as in cases where you want to add information to the exception or cast it to a more meaningful exception for the caller above.

Are the outer layers the "most correct" to capture and handle exceptions? in my example the controller is used, can It know the name of the services/use-cases exceptions?

Catch and handle where it makes sense. In your case it makes sense as the controller is the last caller before returning a response to the client and it's not the responsibility of your service to format an error response for the caller.


Since I'm not sure what you are asking by if you are doing it correctly I decided the quickest and easiest answer is to put your code to use. I created a method called Yates and put your code in it. I then called it 19 times in a simple for loop noted the output. (I limited my output to the first 5 numbers so it is more clear here)

35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...
35 22 23 7 25...

You'll notice it is 19 of the same thing. The problem with Random is that it isn't truly random sometimes, and you just ran across this. simple fix for me was to move the creation of the Random rand outside of the method now when I run it.

13 48 16 39 44...
20 3 10 27 18...
20 38 6 10 9...
1 28 6 33 7...
40 20 7 23 37...
31 22 0 34 18...
51 50 49 1 48...
24 1 44 37 50...
23 1 30 41 3...
41 32 45 23 11...
31 47 32 25 34...
49 8 16 33 32...
21 12 17 32 37...
8 2 40 41 49...
0 15 29 42 39...
39 0 46 20 22...
13 24 3 34 26...
9 10 43 2 39...
36 4 40 45 48...

I know it's not much to go on and I normally give much longer reviews but there isn't much code to review.

Here is the code I used to test against

void Main()
{
    for (int i = 0; i < 19; i++)
    Console.WriteLine($"    {string.Join(" ", Yates().Take(5))}...");
}
Random rand = new Random();
private int[] Yates()
{
    int count = 52;
    int[] deck = new int[count];
    for (byte i = 0; i < count; i++)
    deck[i] = i;
    for (byte i = 0; i <= count - 2; i++)
    {
        int j = rand.Next(count - i);
        if (j > 0)
        {
            int curVal = deck[i];
            deck[i] = deck[i + j];
            deck[i + j] = curVal;
        }
    }
    for (int i = count - 1; i >= 1; i--)
    {
        int j = rand.Next(i + 1);
        if (j != i)
        {
            int curVal = deck[i];
            deck[i] = deck[j];
            deck[j] = curVal;
        }
    }
    return deck;
}

EDIT

After having read everything and considered what you are trying to accomplish I believe that you are getting what are trying to accomplish. That being it looks like you are trying to shuffle a deck of 52 cards. Also with the answer you provided this gives me a little more clue as to what to try to tell you for a better review other than just spitting out the output. So here are my suggestions:

Unit Testing

All programs that are going to be used for "production" (even if production means you are playing your own game) should have some tests in place that exercise your code. Testing randomness isn't always easy but you already thought of 3 tests that you could have written outside of your win forms application.

    for (byte i = 0; i < 52; i++)
    {
        if (hsDeck.Contains(deck[i]))
            Debug.WriteLine("Houston we have a problem");
        if (deck[i] < 0)
            Debug.WriteLine("Houston we have a problem");
        if (deck[i] > 51)
            Debug.WriteLine("Houston we have a problem");
        hsDeck.Add(deck[i]);
    }

This information would have been better served in your question. But the test is simple and is simple to reproduce using MSTest, NUnit, or xUnit. The latter two being among the more popular but MSTest is built into Visual Studio. I see that you put Debug.WriteLine in your "test" so that you can watch the debug screen. Well how about instead of reading the debug screen you watch the test runner screen for a green check or red x for a pass or fail? You could even copy and paste your code but you'd run into an immediate hicup. You have testable code inside a non-testable class. Solution: extract that method into its own very small class.

public class FisherYates
{
    private static readonly Random rand = new Random();
    public static byte[] Shuffle(byte count)
    {
        //removed for brevity
        return deck;
    }
}

Now you can write your test

[TestClass]
public class FisherYatesTests
{
    [TestMethod]
    public void ShuffleWillNotPutAValueBelowZeroOrAboveCountOrReturnDuplicates()
    {
        for (int i = 0; i < 254; i++)
        {
            var shuffled = FisherYates.Shuffle(52)
            if (shuffled.Any(x=> x<0))
                Assert.Fail("Algorithm returned value below zero");
            if (shuffled.Any(x=> x>51)
                Assert.Fail("Algorithm returned value higher than largest index");
            if (shuffled.GroupBy(x => x).Any(x=> x.Count() > 1))
                Assert.Fail("Algorithm returned duplicate values");
        }

    }
}

That test runs very fast. Total time on my pc to compile and run those tests as many times I want is under 3 seconds. Understanding the green or red marks takes next to nothing to understand.

Closeness to algorithm

So you noticed already that there was a bug in your code. I noticed (after having re-read the wiki) page that you implement the algorithm AS WELL AS an alternative.

  The modern version of the Fisher–Yates shuffle, designed for computer use, was introduced by Richard Durstenfeld in 1964[2] and popularized by Donald E. Knuth in The Art of Computer Programming as "Algorithm P".[3] Neither Durstenfeld nor Knuth, in the first edition of his book, acknowledged the work of Fisher and Yates; they may not have been aware of it. Subsequent editions of The Art of Computer Programming mention Fisher and Yates' contribution.[4]

  The algorithm described by Durstenfeld differs from that given by Fisher and Yates in a small but significant way. Whereas a naïve computer implementation of Fisher and Yates' method would spend needless time counting the remaining numbers in step 3 above, Durstenfeld's solution is to move the "struck" numbers to the end of the list by swapping them with the last unstruck number at each iteration. This reduces the algorithm's time complexity to O(n), compared to O(n2) for the naïve implementation.[5] This change gives the following algorithm (for a zero-based array).

-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
    j ← random integer such that 0 ≤ j ≤ i
    exchange a[j] and a[i]

  An equivalent version which shuffles the array in the opposite direction (from lowest index to highest) is: (emphasis mine)

-- To shuffle an array a of n elements (indices 0..n-1):
for i from 0 to n−2 do
    j ← random integer such that i ≤ j < n
 exchange a[i] and a[j]

So to answer your question did you implement it... Yes and No. Yes: you did it twice. No: You did it twice in the same method but the algorithm says once. Does it really matter? No. You want a random deck of cards you'll get it.


Handling click events on ingredients list

Druciferre seems to have found a way to streamline your current code quite nicely (I would add that an "is-value-x-in-array-y?" helper function would greatly improve readability, as all the indexOf comparisons make me cross-eyed. A "remove-x-from-array-y" function would also help DRY the code), so allow me to suggest a different tack altogether; more rewrite than tweak. Reading your description, here are my suggestions.

1. Objects for each recipe

There are plenty of ways to do this, but the simplest, most direct one I can think of is:

var recipes = [
  {
    name: "Pork stew",
    ingredients: ["pork", "stew", "onion"]
  },
  {
    name: "Spaghetti bolognese",
    ingredients: ["spaghetti", "city of bologna", "onion"]
  },
  // ....
];

(can you tell I don't cook much?)

Anyway, the point is that each recipe "contains" its ingredients. A neat logical encapsulation of data.

2. Use underscore.js (or similar, or roll your own) array functions

Underscore's got some neat array functions. Use 'em. Let's say you have both of the above recipes selected. To get all the ingredients needed, you could do

// concatenate every recipe's ingredients into one array
var requiredIngredients = _.reduce(selectedRecipes, function (ingredients, recipe) {
  return ingredients.concat(recipe.ingredients);
}, []);
requiredIngredients = _.uniq(requiredIngredients); // remove duplicates

Edit Changed _.map to _.reduce which is what I meant to write first time around, but somehow messed up.

Thus, requiredIngredients will be:

["pork", "stew", "onion", "spaghetti", "city of bologna"]

So now you have an array of all the ingredients needed to cook those two dishes.

Now, let's say you also have an array of ingredients that the user has manually selected and one that contains those that he/she already has (i.e. manually unselected):

var ownedIngredients = ["onion", "olive oil"];
var selectedIngredients = ["curry"];

// combine manually selected ingredients with recipe ingredients,
// and remove duplicates
var allIngredients = _.uniq(requiredIngredients.concat(selectedIngredients));

// "subtract" unselected ingredients
var shoppingList = _.difference(allIngredients, ownedIngredients);

And, well, that's pretty much it. When you select a new recipe, re-run that code. When you add/remove an ingredient, re-run that code. With just the above you'd get a shopping list of

["pork", "stew", "spaghetti", "city of bologna", "curry"]

Of course, this is me taking a stab in the dark, not knowing the rest of your app. But this, to me, seems like a better approach than manually trying to manage arrays element-by-element.


Base 256 array addition Recursively - Follow up

Limitations

The program has an important limitation:
the two byte arrays must have the same size,
otherwise the result may be incorrect.
If the caller is lucky, the second is shorter than the first,
and the program will crash with an exception.
If the caller is unlucky, the first is shorter,
and the result will be incorrect,
quietly,
without any warning whatsoever.

At the minimum, this limitation should be documented.

Copying an array

When you reach the beginning and there is a carry,
so you need to grow the array to hold the extra value,
converting the array to a list is wasteful.
It would be better to allocate a new array with +1 size,
and use the Array.Copy method to copy the content.

Division is expensive

The use of Math.DivRem may seem clever,
but know that division and remainder computation is usually expensive.
If this operation was natural for your purpose,
that would be fine,
but it's not natural.
What you really need is check that sum >= Base,
and then perform sum -= Base if needed.
It would be better to write the code like that,
simply because that will be more natural to read.


Web-scraping through a rotating proxy script

From your description you want your code to perform these tasks:

Get a list of proxies
That support https
That are actually working

And you want that list to be randomized (from your description without repetition, from your code repetitions are fine).

I would use a couple of generators for that:

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from random import shuffle

def get_proxies(link):
    response = requests.get(link)
    soup = BeautifulSoup(response.text,"lxml")
    https_proxies = filter(lambda item: "yes" in item.text,
                           soup.select("table.table tr"))
    for item in https_proxies:
        yield "{}:{}".format(item.select_one("td").text,
                             item.select_one("td:nth-of-type(2)").text)

def get_random_proxies_iter():
    proxies = list(get_proxies('https://www.sslproxies.org/'))
    shuffle(proxies)
    return iter(proxies)  # iter so we can call next on it to get the next proxy

def get_proxy(session, proxies, validated=False):
    session.proxies = {'https': 'https://{}'.format(next(proxies))}
    if validated:
        while True:
            try:
                return session.get('https://httpbin.org/ip').json()
            except Exception:
                session.proxies = {'https': 'https://{}'.format(next(proxies))}

def get_response(url):
    session = requests.Session()
    ua = UserAgent()
    proxies = get_random_proxies_iter()
    while True:
        try:
            session.headers = {'User-Agent': ua.random}
            print(get_proxy(session, proxies, validated=True))  #collect a working proxy to be used to fetch a valid response
            return session.get(url) # as soon as it fetches a valid response, it will break out of the while loop
        except StopIteration:
            raise  # No more proxies left to try
        except Exception:
            pass  # Other errors: try again

def parse_content(url):
    response = get_response(url)
    soup = BeautifulSoup(response.text, 'lxml')
    for items in soup.select(".info span[itemprop='name']"):
        print(items.text)

if __name__ == '__main__':
    url = 'https://www.yellowpages.com/search?search_terms=Coffee%20Shops&geo_location_terms=Los%20Angeles%2C%20CA&page={}'
    links = [url.format(page) for page in range(1, 6)]
    for link in links:
        parse_content(link)

This actually makes sure that no proxy is reused for each site. The order in which the proxies are tried is different for each site. If you are not fine with trying the same proxies again for a new site, just call get_random_proxies_iter outside of parse_content and feed it all the way down to get_proxy.


As a general rule, if the only thing your getters and setters do is contain a single statement, a return or assignment respectively, there is no need to make the variable private and it should be declared public.

Specifically to your question: Neither of your approaches are considered "best" nor "proper" practice. You should be using an initializer list before the constructor's body:

Note: There is no indication of what order the variables were declared in the class declaration. I've made a guess here, but they are initialized in the order they are declared regardless of what order you put them in the list so if I've got it backwards and fitness is declared first things will silently break at run-time.

Particle::Particle(std::array<double, 30> p, std::array<double, 30> v)
: bestPosition(p)
, position(p)
, velocity(v)
, bestFitness(rastriginEvaluation(p))
, fitness(bestFitness)
{
    /* DO NOTHING */
}


Yes, there is a way to do this better.

Always Option Explicit.

No need (almost always) for .Select, this is a human activity and explicitly referencing the ranges in VBA is more efficient. This also creates extra work for the VBA engine.

You hide your active window, but you do not unhide it.

Don't be afraid to use you favourite search engine to look up even the simplest commands, especially if you are fixing up code generated by the macro recorder. Sometimes these commands have methods and properties that make life easier (e.g. see what I have done with the copy method - look up the "Excel Range.Copy" method to see what gems are there).

However, with the amount of code you have here, I am really surprised that you would notice any slowing down!

Sub CopyData()
    Dim mainWB  As Workbook
    Dim mainWS  As Worksheet
    Set mainWB = ActiveWorkbook
    Set mainWS = mainWB.Sheets(1)

    Dim wbSource As Workbook
    Set wbSource = Workbooks.Open(Filename:="H:\Formatting.xlsx")
    'ActiveWindow.Visible = False ' Why?

    wbSource.Sheets(1).Range("A10:CX15").Copy mainWS.Range("A10:CX15")
    wbSource.Sheets(1).Range("A25:M26").Copy mainWS.Range("A1") 'Haven't tested this line to see what effect the different range size has.
    wbSource.Sheets(1).Range("D49").Copy mainWS.Range("AF8")
    wbSource.Sheets(1).Range("D51").Copy mainWS.Range("AF10")
    wbSource.Close
End Sub

And the usual staples of setting Application.ScreenUpdating, Application.EnableEvents, Application.Calculation will assist in managing what happens or is shown when the routine is run. ActiveWindow.Visible could be handy, but remember to turn it back on after doing the work. Your ActiveWindow may not be what you think it is.


You know what comprehensions are, which is good!
But you've a couple of problems:

str.join(',', text_shift) is abnormal and should probably be ','.join(text_shift).
str.split(text, ',') is equally abnormal and should be changed to text.split(',').
text_split = list(text) is unneeded, as you can loop thought the string the exact same way.
text_split = [ord(i) for i in text_split] can be merged into text_shifts comprehension.
You can change both cipher and decipher to be one-liners.

I'd also change both direction * shift to be a variable, just to ease reading of the comprehension slightly.

And so you should be able to end up with functions that look like:

def cipher(direction, shift, text):
    order = direction * shift
    return ','.join([str(ord(i) + order) for i in text])

def decipher(direction, shift, text):
    order = direction * shift
    return ''.join([chr(int(i) - order) for i in text.split(',')])

Finally, your module level doc-string should have a short description on the first line, and then optionally have two spaces and a longer description.

You used implicit string concatenation, but you kept using \ at the end of the line.
Instead I'd change you string to be wrapped in () to remove these.

I also disliked that you added your whitespace characters to the front of the next string.
It looks odd, and is easier to read/ignore when it's on the other line.

And so in all I'd end up with:

"""
Simple alphabetical cipher

This is a simple alphabetical shift encypter. Enter -1 or 1 for the direction,
your desired shift and laslty, the text to cipher.
   Written by Sami Dena (aurlit@riseup.net)
"""

def cipher(direction, shift, text):
    order = direction * shift
    return ','.join([str(ord(i) + order) for i in text])

def decipher(direction, shift, text):
    order = direction * shift
    return ''.join([chr(int(i) - order) for i in text.split(',')])

if __name__ == '__main__':
   string = ("The encryption step performed by a Caesar cipher is often "
             "incorporated as part of more complex schemes, such as the Vigenère cipher, "
             "and still has modern application in the ROT13 system. As with all single-alphabet "
             "substitution ciphers, the Caesar cipher is easily broken and in modern practice offers "
             "essentially no communication security.")

   encrypted_string = cipher(-1, 4, string)
   print(encrypted_string)
   print(decipher(-1, 4, encrypted_string))


Find 3 elements that sum to zero in an int array

There's a bug:

>>> sum_to_zero([4, 17, -2])
(4, -2, -2)

But -2 only appears once in the input, so this is not a legitimate triple.
The docstring is not quite right. "find 3 elements that sum to 0" — and then what? The docstring should say explicitly what the function returns.
The docstring does not say what happens if no three elements sum to zero. In fact, the function returns None. This is a bad idea: it would be all too easy for the caller to forget to check it. Instead, the function should raise an exception.
Instead of three nested loops, use itertools.combinations:

for triple in combinations(a, 3):
    if sum(triple) == 0:
        return triple

Even when corrected, this function has runtime \$Θ(n^3)\$: it has to examine all possible triples. However, there is a \$Θ(n^2)\$ algorithm:

from collections import defaultdict
from itertools import combinations

class NotFound(Exception):
    pass

def sum_to_zero(a):
    """If three elements of the sequence a sum to zero, return them as a
    tuple. Otherwise, raise NotFound.

    """
    # Map from sum of two elements to a dictionary mapping the index
    # of one element to a set of indexes of the other.
    pair_sums = defaultdict(lambda:defaultdict(set))
    for i, j in combinations(range(len(a)), 2):
        d = pair_sums[a[i] + a[j]]
        d[i].add(j)
        d[j].add(i)
    for k, x in enumerate(a):
        for i, jset in pair_sums.get(-x, {}).items():
            if i != k:
                for j in jset:
                    if j != k:
                        return a[i], a[j], a[k]
    raise NotFound()


There is another much simpler clean way.

Use ControllerAdvice and throw error from Service Layer itself. Build your common error response there. Yeah it is global exception handling.


Is this correct to reassign already intialized variable?

It looks like a useless reassignment.  It must be some refactoring gone wrong.  At worst, it will cause a tiny performance hit.


refactor helper for default state for rails select with enums

Don't know if there's a good way to do this, since your translation isn't 1:1. E.g. your enum differentiates between odd weeks and even weeks, but your helper doesn't.

So you have to do some sort of work to collapse 7 states into 4 options.

If you're already using I18n to do translation, you might be able to put the strings in there, e.g.:

question:
  frequency:
    - weekly
    - biweekly
    - biweekly
    - monthly
    - monthly
    - quarterly
    - quarterly

and the use the standard Rails I18n helpers to fetch the right string. But that's not too pretty either, and really only hides the problem from Rubocop. It's also a more implicit connection, and more error-prone, so, yeah, you probably shouldn't go down this road.

Frankly, I wouldn't bother too much about Rubocop's opinion about method length or cyclomatic complexity in this case. But...

But there's weird stuff going on too:

You're passing in a question and checking its id. But it's not a real Question record? Because you immediately go and fetch one from the database. So what are you passing in that's called question, has an id, but isn't actually a Question?
You're also overwriting the argument variable with the record you fetch, which is not a great idea. Now you have a question that's apparently not really a Question, but then maybe it becomes a question that is actually a Question. Confused? Me too.
Oh, and are you sure you're going to find something when you call find(id)? If not, you'll get a 404 RecordNotFound error. It might be completely intentional to let that happen, but to have the page break due to a helper method is perhaps a little icky.
Why return false? If anything, you should return nil. Ideally, you return a string, but the "opposite" of a string isn't false - at best it's nil. And actually, your method could conceivably return nil already, since you don't have an else branch in your logic. If, for whatever reason, none of the if/elsif conditions are true, your method will return nil.

Anyway, without worrying about the question vs question thing and possible exceptions being thrown, I'd suggest at least using a case statement instead of a lot of elsifs:

case
when question.weekly?
  'Weekly'
when question.odd_weeks?, question.even_weeks?
  'Biweekly'
when question.start_of_month?, question.end_of_month?
  'Monthly'
when question.start_of_quarter?, question.end_of_quarter?
  'Quarterly'
else
  nil
end

Oh, and I capitalized "Weekly" to match the other strings.


Disclaimer: This review is reviewing this as work-in-process, and not as "finished".

On a quick glance this looks mostly correct. I still got a few points, that definitely need to be fixed before proceeding:

Index handling:
You don't do anything with negative indexes. vector.getAt(-1); results in an infinite loop, as well as vector.deleteAt(-1);. I suggest you just check and throw an InvalidArgumentException for any \$index < 0\$
Empty list:
Your empty list throws null-pointer exceptions all around. Don't do that. You should check your head before doing stuff with it, and if it's null, throw IllegalStateException  or similar.
Optimizing pushBack():
There is a relatively simple and quick-to-implement optimization for your pushBack. Your Vect<T> should maintain a "pointer" to the last node. On deleting the last node you need to check for the special-case just like when deleting head, but after that your pushBack becomes dead-simple:

 public void pushBack(T cargo) {
     tail.add(cargo);
     tail = tail.getNext();
     vSize++;
 }


Iterating worksheets and cells, copying data to summary sheet

I have found the answer. What seems to have cause the issue is these lines of code:

Set copyRng = xSheet.Range("A:A")
Set copyRng = xSheet.Cells

All I wanted was to access the entire sheet with all of its non-empty cells. This seems to have been the wrong way of doing that since the code does in fact only take mere fractions of a second if I give it a clear defined range such as "A1:A100" in case of the first instance.


Finding the n th term in Fibonacci series

The code looks fine to me apart from the fact that it can throw an exception. The function fib() powLF() are giving you the complexity of O(log(n)) plus the execution time of the function sum_digits() is 479 ns per loop which is perfectly fine.

> %timeit sum_digits(n)
1000000 loops, best of 3: 479 ns per loop

Take a look at Lecture 3 of the MIT Open Courseware course on algorithms for a good analysis of the matrix approach.

>>> timeit.timeit('fib(1000)', 'from __main__ import fibM as fib', number=10000)
0.40711593627929688
>>> timeit.timeit('fib(1000)', 'from __main__ import fibL as fib', number=10000)
0.20211100578308105


Oracle trigger to keep a copy of deleted records in another table

I am using this trigger to keep a copy of the deleted record from table Orders_Details in table Orders_Details_Deleted.

No, you're not. The code copies all rows from orders_details to order_details_deleted every time the trigger is run.

  Is there any better way [than using a trigger] ?

Yes, there is a better way. Don't reinvent database features but use native functionality instead. Have a look for the following Oracle features:

Flashback Data Archive

  A Flashback Data Archive provides the ability to track and store transactional changes to a table over its lifetime. A Flashback Data Archive is useful for compliance with record stage policies and audit reports.

Auditing

  Auditing is the ability to track changes that users make in the database.

Workspace Manager

  Keep a history of changes to data

  You can navigate workspaces and row versions to view the database as of a particular milestone or point in time. You can roll back changes to a row or table in a workspace to a milestone. A typical example might be a land information management application where Workspace Manager supports regulatory requirements by maintaining a history of all changes to land parcels.


Snakes and Ladders random world generator second implementation

Here's an attempt:

class World
  attr_reader :board

  def initialize(size, snakes_count = 10, ladders_count = 10)
    @board = Array.new(size * size)

    place snakes_count,  :snake
    place ladders_count, :ladder
  end

private

  def free_point
    point = rand(@board.size) until point && @board[point].nil?
    point
  end

  def place(count, entity)
    count.times do
      start_point = free_point
      end_point   = free_point until end_point && end_point != start_point && (entity == :ladder || end_point != @board.size - 1)
      pair = [start_point, end_point].sort
      pair.reverse! if entity == :snake
      @board[pair.first] = @board[pair.last] = pair
    end
  end
end

The idea here is that:

A snake or ladder consists of a point pair. A snake is a desending pair (ie, go back from a higher point to a lower point), while a ladder is an ascending pair (go forward from a lower point to a higher point)
A snake cannot have either of its points be the final point on the board.

The board is represented as a size x size array, so a world of size 12 would produce a board that is 12x12, or 144 squares. Checking for occupation is then as easy as just checking if @board[point].nil?. It also gives you an easy way to iterate the board for rendering or rules checking; as you're playing, if the player lands on square 63, you can check square 63. If it has a value, then check if v[0] > v[1] (snake) or otherwise (ladder).

If desired, you could have #place keep a separate list of snakes and ladders, but it's not strictly necessary, since you can think of them as the same construct (a movement from one point to another), differentiated only by the direction of movement.


Misplaced Responsibility: print()
The class LinkedList (or data class Node, see below) should not print() functions.
Calling print() functions is a separate responsibility and should be done elsewhere in the code:
What if you want your program to support different output formats like JSON or XML and they shall be sent over the network?
Of course, we don't prepare software for all what-ifs.
But we do make the obvious "cuts" between responsibilities.
To get a printable representation, extract the text used by the print() calls into a toString() method.
Then call print(node) from main().
Avoid Feature Envy (from LinkedList on Node)
Feature Envy is a special type of Misplaced Responsibility.
The class LinkedList doesn't have any features of its own, and no state.
Instead, it only operates on everything in the data class Node.
This is a design smell that we call Feature Envy.
Move all the methods from the class LinkedList to the data class Node.
Then remove the class LinkedList.
You will notice that when you fix Feature Envy problems, the lines become shorter: References that have to wander around because of the Feature Envy become the omittable this.
There are situations where this type of Feature Envy is justified:
In cases of specific design patterns like Proxy, Delegate, Facade.
The class LinkedList does not qualify as a Facade because it exposes the type Node<T>.
It would only qualify if its type Node<T> would be hidden from the user, and the only other type the user sees were <T>.
The sitaution would, of course, change once you give class LinkedList fields head and tail.
Avoid error-prone interfaces
The current interface is error-prone.
It allows for broken linked lists.
The fields next and previous should be read-only for the user of Node.
Instead, the user of Node should have to go through a method like insertAfter(), insertBefore(), delete().
After all, insertion and deletion are not atomic operations but should be transactions.
As a next step, you could ponder about the thread-safety of these operations.
Avoid exposing implementation detail
That a LinkedList is implemented with Nodes is an implementation detail that the user doesn't need to know.
The user should be able to focus on the primary purposes of LinkedLists:

Payload (data)
Iteration/Traversal
Insertion and Removal
Your interface is too low-level.

The perfect LinkedList interface is (almost?) indistiguishable from an ArrayList interface. It should be possible to swap one implementation, like LinkedList, for another, like ArrayList, due to performance considerations (O(1) random access for ArrayList, O(n/2) random access for LinkedList vs O(1) insert/delete for LinkedList, O(n/2) insert/delete for ArrayList) without having to change all the code that uses the list.
Null-Checking
Only use Type? if you really need to support nullability.
I recommend to use Type instead of Type? whereever you can.
That the Kotlin compiler can enforce NonNull is one of the many strengths that it has over Java.
Don't squander it by making everything nullable with ?.
BUG: fun nextDeepCopy() doesn't create a deep copy
It doesn't, because it doesn't recurse to itself but calls newDeepCopy(), and that is not recursive.
The correct way to create a deep copy of a LinkedList with additional random pointers would be to

Create a map with the old nodes as key and the new node as value.
Loop over the map, setting the pointers of the new nodes by a lookup in the map.
Traditional ways of copying a LinkedList won't work because of the random pointer.

Also, fun newDeepCopy() does exactly the same thing as the built-in fun copy(), it creates a shallow copy of the current object.
Unit Tests?
There are ways how to prevent bugs like the one above.
I recommend writing unit tests.
Even better, use Test-Driven Development.
Use if-expressions
In Kotlin, if is an expression.
You can make use of it.
The code:
if (condition) return a else return b

can also be written as, more idiomatic:
return if (condition) a else b

This would allow for all of your functions to become expression functions.
Piece of Sample Code
Here's a code snippet to show how your code could look like:
data class Node<T>(
        var data: T?,
        var previous: Node<T>? = null,
        var next: Node<T>? = null,
        var random: Node<T>? = null
) {
    fun shallowCopy() = copy() // You could even omit this
    fun deepCopy(): Node<T> = TODO("Implement this")
    fun toString() = "Node data:${data} previous:${previous?.data} next:${next?.data} random:${random?.data}"
}


The very first thing I do when I'm running into performance issues with my code is answer three questions:

How fast does my code need to be?
How fast is it now?
What is slowing me down?

You're the only one who can provide an answer to the first one, so I'll pass on that for now.  The second and third ones can be answered simultaneously while profiling your code, using cProfile.  I saved your code as "bruteforce_xor.py", so by running

C:\Users\Dannnno\Desktop\> python -m cProfile bruteforce_xor.py

I was able to find out how long it takes to run in total, and what is actually taking so long.  This was the output:

  I don't have any! I let this run for a while and it never finished, which shouldn't come as a surprise once you finish reading below.

Before we apply the (lack of) results of our profiling, lets look at some general improvements.

Imports

In general, each import deserves its own line.  This helps with readability

import itertools
import re
import string
from collections import namedtuple

Whitespace

You generally want whitespace around operators, commas, etc.  Exceptions include the = sign for default values and keyword arguments, and for precedence.

On the flip side, don't put them on the outside of method calls, like

possibles.append( Possible(key, hcount, scount) )

instead, use

possibles.append(Possible(key, hcount, scount))

Naming

Some of your variables could be more clearly named.   Instead of data, I'd call that chunks.  Instead of Possible I'd use Candidate, and possibles -> candidates.  Instead of for k in keys just type for key in keys.  Things of that nature.

Regex

I question the regex you're using...  The regex '....?' will match any 3 or 4 character chunk, because you've made the last one optional.  Based on your comments, you only want 4 character chunks.

Itertools

You use itertools some of the time, but not always.  Use it for zipping and mapping as well.  That being said, I don't really see the point of

map(bytearray, [word, key])

Usually I prefer reserving higher order functions for cases where I don't actually know how many elements there are.  In this case

bytearray(word), bytearray(key)

seems much cleaner

Your speed is going to be very, very hard to improve if you keep using a brute-force algorithm.

string.printable consists of 100 ASCII characters.  When you get the cartesian product of that with itself (4 times) you get 100,000,000 (!!!) combinations.  Then you iterate over each of those combinations.

Inside of that iteration, you then iterate over every "word" in your data.  Using re.findall('....?', blah) you're going to generate 1889 chunks of length 4, and 1890 chunks of length 3, for a grand total of 3779 chunks.  This means that you're essentially doing 377,900,000,000 (!!!!!) iterations of your loop.

That's bad.  That's really bad.  The number one thing you absolutely must try to improve is that - find another method that reduces how many times you look at everything.  I don't have a good suggestion for that - I don't know enough about your problem or what (if any) expectations you can have for the input to provide a good way to filter that.  However, I can give you some other suggestions.

Use lazy evaluation

Like I mentioned earlier, don't call zip and map.  Instead defer the calculations to when you actually need them using itertools.izip and itertools.imap.

Don't repeat calculations

You transform every chunk you have into a bytearray every single time you go through your loop.  Instead of repeating that calculation, why don't you convert them first?  Same for your cartesian products (except here I'd probably convert your string.printable and not the cartesian products themselves)

Finally

Bitwise operations are generally executed in constant time so there isn't a whole lot you can do about that.  All I might suggest is using an LRU cache, but honestly I don't see that speeding up the process.

As a final piece of food for thought, this (poorly timed) code runs (on my admittedly slow netbook) as follows:

import time

start = time.time()
# 377,900,000,000 is too big for an arg to xrange in Python 2.7k
for j in xrange(1000):
    for i in xrange(377900000):
        j ^ i
diff = time.time() - start
print diff

Output:

  None, again.  I ran this for 5 minutes on (again, admittedly crummy netbook) and it couldn't finish.  This is the equivalent number of iterations with a single constant time operation.


Copying orders and prices into another Excel sheet

There's likely many factors at play here, but here's my two cents:

It looks like you're copying whole cell's onto another sheet for calculation, and again to a results sheet.

What will be happening here is that when copying the values, it will be copying all the information about cells and not just the values. By adding a cell to the watch list you can see just how much information is there that in most cases you don't need (this is just a small section of the entire list):

I would suggest reviewing your copy method to copy only the information you actually need (quite possibly just .Value), this will save both memory and processing.


Generate random 10% of file to be used in testing with Ruby

Here's my shot at it:

File.open('english-words-partial.txt', 'w') do |file|
    File.foreach('english-words-full.txt') do |line|
        file.puts(line) if rand(10) == 0
    end
end

In Ruby, you can add an if statement to the end of a line, to conditionally execute that line. This also works with the unless statement.

Also, the rand function can take a number, and produce that many possible numbers from it. So rand(10) will give you a random number from 0 to 9

In Ruby, you usually want to use { } for 1 line blocks, and do/end for multiline blocks, but they both act slightly different. Theres more on that here: https://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby

File.foreach('...') is just a bit shorter and neater then File.readlines('...').each (thanks to @Flambino for this)

And lastly, you can use IO methods on a file object like print and puts, so I liked that better but file.write works too. Thats really personal preference.


Surely there's a better way to write this statement?

As well as some standard indenting, a quick thought could be reversing the item being compared and using some temporary variables for readability.

EDIT:
Ok, so svick pointed out that the original code was fundamentally flawed.  So how about creating an extension method on string to do the Contains for us.  Something like:

// Method would do well with some unit tests ....
public static bool ContainsAny(this string source, string[] findStr)
{
    return findStr.Any(p => source.Contains(p));
}

Then used like

var contentTypes = new [] { "Theme Gallery", "Converted Forms", "Page Output Cache", "Master Page" };
var urls = new[] { "_catalogs", "Style Library", "Cache Profiles" };
var accounts = new [] { "System Account" };

var contentType = item.ContentType.ToString();
var createdBy = item["Created By"].ToString();

if (!createdBy.ContainsAny(accounts) &&
    !item.Url.ContainsAny(urls) &&
    !contentType.ContainsAny(contentTypes))
{
    query.RecordItems(
            item.ID.ToString(),
            item.ContentType.Name,
            item.DisplayName,
            item.Name,
            "",
            item.Url,
            createdBy,
            "",
            Convert.ToDateTime(item["Modified"]),
            item["Modified By"].ToString(),
            Convert.ToDateTime(item["Created"]),
            createdBy);
}

Also, do you need to catch the exception in this method?  Could you not just handle that situation in an if statement as it looks like you are letting the exception handle the case where one of the values is null when a simple null check would suffice??


What is the optimal way to write this small Todo List app

If you had not written this code but were trying to use it, how would you know that the square on either side was a button or what the function of that button was? Buttons need labels and they are generally oval shaped.
When you design or write code for the web you need to consider the user and how they will be using the tool. Even a toy application should follow some basic standards.


Forking with PHP (4 different approaches)

5. All code embedded in a single PHP script. With explanation as requested.

The statements before the fork is executed normally.

After a succesful pcntl_fork(), the running process is cloned, complete with its current state (all variables, including process counter). So two identical processes continue from that point in code.
Almost identical: the only difference is the return values of pcntl_fork(), stored in both $pid's.

The cloned process is the parent, and receives the process_id of its clone.
The clone process is the child, and receives 0.
Depending on this value, both processes go their separate ways, and continue until the hit an exit().
If parent- and child-code are not individually terminated by exit(), then both may continue executing the common code at the end, resulting both processes printing "I am both"!.
Try for yourself, and inspect the output. Then uncomment the exit()'s and run it again.

$mypid = getmypid();
echo "$mypid: I am the parent. I have no child yet.\n";

// fork: a twin process is created
if(($pid = pcntl_fork()) == -1) { exit("Error forking...\n"); }

if($pid == 0) {
        // Child code goes here
        $mypid = getmypid();
        echo "$mypid: I am the child. This is what I do.\n";
        // exit();
}else{
        // Parent code goes here
        echo "$mypid: I am still the parent. I have a child now: it's number is $pid.\n";
        // exit();
}

// Both parent and child execute this code unless
// the exit's above are uncommented.
echo "$mypid: we are both. The pid I know is: $pid\n";

exit();

Output: of the script above. The $mypid at the beginning of the line is the process id of the printing process. The $pid on the right is the return-value of the fcntl_fork().

6346: I am the parent. I have no child yet.
6347: I am the child. This is what I do.
6346: I am still the parent. I have a child now: it's number is 6347.
6346: we are both. The pid I know is: 6347
6347: we are both. The pid I know is: 0

Note: after the fcntl_fork() both processes work independently. So one may go faster than the other; they may run on different processes, etc.
The order of the output may differ on your computer !
You can have them synchronized by making the parent wait for the childs exit.

This was my attempt to give an explanation. Now the answer to your question, wich one is faster or better:

Essentially they are all the same, as far as the fork goes. The differences are only in th extras.

An include makes the 'compiler' translate the code all at once. And only once.
All variables set in the main program (before the fork ! ) are 'inherited' by the child.

An exec cleans all process variables and starts a new program, just as you do from the command line. So this is overhead. And no information is shared from the parent to the child. (unless you  ... well, there are possibilities).
A new process in a clean memory also forces the child code to be compiled in the second process. So the compiler has to be started again; this to is overhead.

So without exec is always better ? No. For example: if your co-worker changes his child-code, his typo's will make the compiler stop compiling your code if is is included.
But executing the other code will clearly show where the typo's are made. Programs are insulated much better this way. At some cost. Depends on how often you want the fork to be executed.


I believe, what's bothering you is a non-total definition of counit, right? (for cojoin one possible variation is lsa.tails) Indeed, a List does not have a valid comonad instance specifically bacause of that. It does have a valid semicomonad instance though.

Things that have a valid comonad instance are, for example: Identity, NonEmptyList, Zipper, Tuple. Here's a reddit question with more examples of comonads.


Checking if two byte arrays are the same

Part of the problem is all the exceptions. There are better ways of handling exceptions, such as Scalaz Validation or Lift's Box. Scala itself comes with Either, which isn't particularly flexible.

On the other hand, you are not returning anything, which actually turns the whole code into a reverse Option: you either have Some(exception) or None.

Now, the test itself, except for checking for nulls, has a name in Scala: sameElements. Only it will not tell you what the problem was.

I can think of two ways of handling it. The first is just a small improvement on your pattern matching:

def assertArray(b1: Array[Byte], b2: Array[Byte]) = (Option(b1), Option(b2)) match {
  case (None, None) =>
  case (None, _) | (_, None) => throw new AssertionError("b1 is null while b2 is not, vice versa")
  case (Some(b1), Some(b2)) if b1.length == b2.length =>
    (b1, b2).zipped.map(_ == _)
    .zipWithIndex.find(!_._1)
    .foreach {
      case (_, i) => throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
    }
  case _ => throw new AssertionError("b1.length != b2.length")
}

The other way would be to turn the problem around completely. It would be like this:

def assertArray(b1: Array[Byte], b2: Array[Byte]) = {
  def isOneNull =
    if ((b1 eq null) ^ (b2 eq null)) Some("b1 is null while b2 is not, vice versa")
    else None

  def areSizesDifferent =
    if (b1.length != b2.length) Some("b1.length != b2.length")
    else None

  def haveDifferentElements =
    (b1, b2).zipped.map(_ == _)
    .zipWithIndex.find(!_._1)
    .map { case (_, i) => "b1(%d) != b2(%d)" format (i, i) }

  def areTheyDifferent =
    if ((b1 ne null) && (b2 ne null)) areSizesDifferent orElse haveDifferentElements
    else isOneNull

  areTheyDifferent foreach (msg => throw new AssertionError(msg))
}

This is longer, and handles nullness in two separate places, and doesn't protect against nullness, but I think it reads much better. To get more than this I need Scalaz:

def assertArray(b1: Array[Byte], b2: Array[Byte]) = {
  def isOneNull =
    (b1 eq null) ^ (b2 eq null) option "b1 is null while b2 is not, vice versa"

  def areTheyDifferent =
    Option(b1) <|*|> Option(b2) flatMap {
      case (b1, b2) =>
        def areSizesDifferent = b1.length != b2.length option "b1.length != b2.length"

        def haveDifferentElements =
          (b1, b2).zipped.map(_ == _)
          .zipWithIndex.find(!_._1)
          .map { case (_, i) => "b1(%d) != b2(%d)" format (i, i) }

        areSizesDifferent orElse haveDifferentElements
    } orElse isOneNull

  areTheyDifferent foreach (msg => throw new AssertionError(msg))
}

Or, to go more full-blown with Scalaz:

def assertArray(b1: Array[Byte], b2: Array[Byte]) = {
  type Params = (Array[Byte], Array[Byte])
  type Func = Params => Option[String]

  def isOneNull =
    (b1 eq null) ^ (b2 eq null) option "b1 is null while b2 is not, vice versa"

  def areSizesDifferent: Func = {
    case (b1, b2) => b1.length != b2.length option "b1.length != b2.length"
  }

  def haveDifferentElements: Func = {
    case (b1, b2) =>
      (b1, b2).zipped.map(_ == _)
      .zipWithIndex.find(!_._1)
      .map { case (_, i) => "b1(%d) != b2(%d)" format (i, i) }
  }

  def areTheyDifferent =
    Option(b1) <|*|> Option(b2) flatMap (
      areSizesDifferent |@| haveDifferentElements
      apply (_ orElse _)
    ) orElse isOneNull

  areTheyDifferent foreach (msg => throw new AssertionError(msg))
}

Scala has an unfortunate overhead compared to Haskell to do these things. Also, Scalaz will be able to do a bit more in the next version, but this works with 6.0.

The gain with Scalaz is not, however, legibility or conciseness (in this code, anyway), but of composition. For instance, in the current Scalaz we can abstract most of the body of areTheyDifferent like this:

def composeFM[M[_]:Plus, F[_]:Applicative, B](f: F[M[B]], g: F[M[B]]): F[M[B]] =
  (f |@| g)(_ <+> _)
type FAB[x] = Array[Byte] => x
def areTheyDifferent = (
    Option(b1) <|*|> Option(b2)
    flatMap composeFM[Option, FAB, Int](areSizesDifferent, haveDifferentElements)
    orElse isOneNull
)

Note that composeFM doesn't know a thing about Option or Function1 -- it applies to the pattern.

Well, anyway, take your pick. Sometimes a problem just isn't worth the trouble, but it is useful to know how to handle the trouble anyway.


Making lists symmetrical by merging elements

It is better to read input and output files using the with keyword because:

  It is good practice to use the with keyword when dealing with file
  objects. This has the advantage that the file is properly closed after
  its suite finishes, even if an exception is raised on the way. It is
  also much shorter than writing equivalent try-finally blocks:

with open('farmin.txt', 'r') as input:
    # Process the code you need here.


Storing global styles and utilizing them throughout view controllers

I think that you would be better off using static methods on a struct or class. This removes the need for you to access your style through the App Delegate. The App Delegate should only be concerned with handling the delegate callbacks from the OS, storing globally accessible values in it messes with the principle of separation of concerns and creates a spider web of dependencies hurting the reusability and understandability of your code.
Lumping Fonts, Colors, Dimensions, Paragraph styles, etc. all into a single level is not very discoverable. I think it would be better to separate them into their own types.
In my experience a single color is not enough to define a style. Colors almost always come associated with other colors like foreground v.s. background, or normal v.s. highlighted.
It doesn't make sense to create multiple constants for a single font of different sizes. Better to have a method that takes in a size and returns the special font with the given size.

I recently started creating a collection of "style" classes for myself. This is what I did for colors:

extension UIColor {
    convenience init(hex : Int) {
        let blue = CGFloat(hex & 0xFF)
        let green = CGFloat((hex >> 8) & 0xFF)
        let red = CGFloat((hex >> 16) & 0xFF)
        self.init(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: 1)
    }
}

struct DepthColor {
    enum Depth {
        case Foreground, Background
    }

    let foreground: UIColor
    let background: UIColor

    init(foreground: Int, background: Int) {
        self.foreground = UIColor(hex: foreground)
        self.background = UIColor(hex: background)
    }

    init() {
        self.foreground = UIColor(hex: 0xFFFFFF)
        self.background = UIColor(hex: 0)
    }

    func colorForDepth(depth : Depth) -> UIColor {
        switch(depth) {
            case .Foreground:
                return self.foreground
            case .Background:
                return self.background
        }
    }
}

struct StyleColor {
    enum Purpose {
        case Normal, Highlighted, Disabled
    }

    let normal : DepthColor
    let highlighted : DepthColor
    let disabled : DepthColor

    init(normal: DepthColor = DepthColor(), highlighted: DepthColor = DepthColor(), disabled: DepthColor = DepthColor()) {
        self.normal = normal
        self.highlighted = highlighted
        self.disabled = disabled
    }

    func depthColorForPurpose(purpose : Purpose) -> DepthColor {
        switch(purpose) {
            case .Normal:
                return self.normal
            case .Highlighted:
                return self.highlighted
            case .Disabled:
                return self.disabled
        }
    }

    func color(_ purpose : Purpose = .Normal, _ depth: DepthColor.Depth = .Foreground) -> UIColor {
        return self.depthColorForPurpose(purpose).colorForDepth(depth)
    }

    static func positiveAction() -> StyleColor {
        return StyleColor(
            normal: DepthColor(foreground: 0x45A332, background: 0xFFFFFF),
            highlighted: DepthColor(foreground: 0x45A332, background: 0xFFFFFF),
            disabled: DepthColor(foreground: 0x888888, background: 0xFFFFFF)
        )
    }

    static func deleteAction() -> StyleColor {
        return StyleColor(
            normal: DepthColor(foreground: 0xF31717, background: 0xFFFFFF),
            highlighted: DepthColor(foreground: 0xD91414, background: 0xFFFFFF),
            disabled: DepthColor(foreground: 0x888888, background: 0xFFFFFF)
        )
    }

    static func neutralAction() -> StyleColor {
        return StyleColor(
            normal: DepthColor(foreground: 0x666666, background: 0xFFFFFF),
            highlighted: DepthColor(foreground: 0x555555, background: 0xFFFFFF),
            disabled: DepthColor(foreground: 0x888888, background: 0xFFFFFF)
        )
    }
}

I can then get a color from a style like so:

var color = StyleColor.positiveAction().color()
color = StyleColor.positiveAction().color(.Highlighted)
color = StyleColor.positiveAction().color(.Highlighted, .Background)

This also allowed me to create subclasses of common UIKit components that allow me to simply set a StyleColor on them to fully configure them to a style:

class StyleButton: UIButton {
    var style: StyleColor = StyleColor() {
        didSet {
            self._configureView()
        }
    }

    init(coder aDecoder: NSCoder!, style : StyleColor) {
        self.style = style

        super.init(coder: aDecoder)

        self._configureView()
    }

    init() {
        super.init(frame: CGRect())

        self._configureView()
    }

    func _configureView() {
        self.showsTouchWhenHighlighted = false
        self.adjustsImageWhenHighlighted = false
        self.adjustsImageWhenDisabled = false
        self.reversesTitleShadowWhenHighlighted = false

        self.setTitleColor(style.color(.Normal, .Background), forState: .Normal)
        self.setTitleColor(style.color(.Disabled, .Background), forState: .Disabled)
        self.setTitleColor(style.color(.Highlighted, .Background), forState: .Highlighted)

        self.setBackgroundImage(UIImage(color: style.color()), forState: .Normal)
        self.setBackgroundImage(UIImage(color: style.color(.Disabled)), forState: .Disabled)
        self.setBackgroundImage(UIImage(color: style.color(.Highlighted)), forState: .Highlighted)
    }
}

As I need it, I will probably build similar structures for other types of styles and potentially some higher level style classes like StyleText that includes a StyleColor, StyleFont, and potentially StyleDimensions for padding.


I hav tried the same thing in G++ (version 4.5 from Ubuntu 11.04 original), and the result is quite impressing me. We now do have a lot more features to generise the solution.

we can now support any number of parameters without modifying the code.
the t2t class is no longer needed as G++ lambda supports accessing all identifiers in scope, including global things.

I also tried write a free template function to access the internal function. And the result looks good. I just wanted to say: it is elegant!

#include <iostream>
#include <functional>

template<typename R, typename... V>
struct fixpoint
{
    typedef std::function<R (V...)> func_t;
    typedef std::function<func_t (func_t)> tfunc_t;
    typedef std::function<func_t (tfunc_t)> yfunc_t;

    class loopfunc_t {
    public:
        func_t operator()(loopfunc_t v)const {
            return func(v);
        }
        template<typename L>
        loopfunc_t(const L &l):func(l){}
        loopfunc_t(){}
    private:
        std::function<func_t (loopfunc_t)> func;
    };
    static func_t Fix(tfunc_t f){
        return [](loopfunc_t x){ return x(x); }
        ([f](loopfunc_t x){ return [f, x](V... v){ return f(x(x))(v...); }; });
    }
};
template<typename T>
struct getfixpoint
{
    typedef typename getfixpoint<decltype(&T::operator())>::fp fp;
};
template<typename R, typename T, typename... V>
struct getfixpoint<std::function<R (V...)> (T::*)(std::function<R (V...)>)>
{
    typedef fixpoint<R, V...> fp;
};
template<typename R, typename T, typename... V>
struct getfixpoint<std::function<R (V...)> (T::*)(std::function<R (V...)>)const>
{
    typedef fixpoint<R, V...> fp;
};
template<typename R, typename... V>
struct getfixpoint<std::function<R (V...)> (*)(std::function<R (V...)>)>
{
    typedef fixpoint<R, V...> fp;
};

template<typename T>
auto getFix(T f) -> typename getfixpoint<T>::fp::func_t {
    return getfixpoint<T>::fp::Fix(f);
};

int main(int argc, char* argv[])
{
    auto fac = getFix([](std::function<int (int)> f) -> std::function<int (int)>{
        return [f](int n)->int { if(n==0) return 1; else return n * f(n-1); };
    });
    std::cout<<fac(10)<<std::endl; //3628800
    return 0;
}


Test if a key-value pair exists in nested object in Typescript

Based on your description of the function, I would expect this test to return true, but your implementation returns false.  So, either your description is unclear, or your implementation is buggy.
const obj ={
   "a":{
      "b":{
         "a3":"v2",
         "c1":["1","2"],
         "c2":"3"
      },
      "b2":"values",
      "b3": {"c5": "v"},
   },
   "a2":["v1","v2"],
   "a3":"v1"
}
checkNestedObjectByKeyValue(obj, "a3", "v2") // false, but I would expect true