There appears to be more options for parallelization and async here, and I think the fold overcomplicated what you were trying to do.
#if false
#r $"FSharp.Data"
#endif
open System.Net
open System.IO
open FSharp.Data

let  d01LogUrlWithDate, d02LogUrlWithDate, s01LogUrlWithDate, s02LogUrlWithDate = $"","","",""

module Async =
    let map f x =
        async {
            let! x' = x
            return f x'
        }
    let bind f x =
        async{
            let! x' = x
            return! f x'
        }

let private downloadLogs toDirectory =

    let createFileDirectories (url : string) =
        let directory = @"{toDirectory}\{url.Substring(13, 3)}"

        // if it is going to blow up, let it blow up keeping the entire stack trace
        if not <| Directory.Exists directory
        // I prefer strongly typed ignore, less prone to refactoring issues
        then  Directory.CreateDirectory directory |> ignore<DirectoryInfo>

    let urlWithDateList = // less clutter in scope
        let year = DateTime.Now.Year
        let month = DateTime.Now.Month.ToString("d2")
        let day = DateTime.Now.Day
        [
            d01LogUrlWithDate
            d02LogUrlWithDate
            s01LogUrlWithDate
            s02LogUrlWithDate
        ] |> List.map (fun x -> x + $"{year}-{month}-{day}")

    // create folder for each url file
    urlWithDateList |> List.iter createFileDirectories

    let buildFinalUrlAndRequest number url =
        async {

            try // this area wasn't as complex, so I left the try alone
                // I'd think this should be $"%s{url}-{number+1}.log" or else 1 would stop on zero's output
                let finalUrl = if number = 0 then $"%s{url}-1.log" else $"%s{url}-{number}.log"
                printfn $"Searching for URL: {finalUrl}"
                let! response = FSharp.Data.Http.AsyncRequestStream finalUrl
                if response.StatusCode >= 200 && response.StatusCode <= 299
                then
                    printfn $"URL Ready For Download: {url}"
                    return Ok response
                else // this is never triggered
                    printfn $"Error. Status Code: {response.StatusCode}"
                    return Error $"Status Code: {response.StatusCode}"
            with
                | ex -> return Error $"Request Error: {ex.Message}"
        }

    // if you are just throwing away the Result.Error options, then you don't need to use Results
    let buildRequestList t : seq<Async<Result<HttpResponseWithStream,string>>> =
        seq{0..11}
        |> Seq.map(fun i ->
            async {
                let numberUpdated = i + 1
                let! response = buildFinalUrlAndRequest numberUpdated t
                return response
            }
        )

    let getResponse urls =
        urls
        |> Seq.collect buildRequestList
        |> Async.Parallel
        // these two Async.map calls could be composed together
        |> Async.map(Seq.choose(function | Ok x -> Some x | _ -> None))
        |> Async.map (Seq.map (fun response ->
            async{
                let fileName = Path.GetFileName(response.ResponseUrl.Replace(@"/", "\"")) // fix syntax highlighting here on stack
                let subDir = response.ResponseUrl.Substring(13,3)
                let pathName = $@"{toDirectory}\{subDir}\{fileName}" // fix syntax highlighting here on Stack
                use outputFile = new FileStream(pathName, FileMode.Create)
                do! response.ResponseStream.CopyToAsync(outputFile) |> Async.AwaitTask
                printfn $"File Downloaded: {pathName}"
                return pathName
            }
            |> Async.Catch // this way, no try needed above
            |> Async.map( // map the catch to option, and log the errors
                function
                | Choice1Of2 x -> Some x
                | Choice2Of2 ex -> printfn $"Download error {ex.Message}"; None
            )
        ))
        |> Async.bind Async.Parallel

    urlWithDateList
    |> getResponse
    |> Async.RunSynchronously
    |> Seq.choose id // discard empty values
    |> Seq.toList


There are at least a few things I think I'd do differently, at any rate.

const int MAX_RECV_LEN = 8096;
const int MAX_MSG_LEN= 1024;
const int PORT_NUM =  1200;

The ALL_CAPS convention was originally invented for macros. At least as far as I can tell, it was originally for function-like macros, to give a subtle warning that it might evaluate its argument more than once, so you needed to be careful about exactly how and where you applied it (especially to arguments that might have side effects).

It really doesn't make sense for a situation like this, so I'd prefer to avoid it. Regardless of the exact names you choose, it's probably better to avoid putting these variables in the global namespace any way. I'd consider wrapping the entire class in a namespace instead.

private:
    Sokect(){}

Assuming your compiler is recent enough to support it, I'd prefer to use =delete; to ensure that a ctor can't be accessed, rather than defining it as private.

[ ... ]

void setReuseAddr(int);
void getReuseAddr(int);
void setKeepAlive(int);
void getKeepAlive(int);
void setLingerOnOff(bool);
void getLingerOnOff(bool);
void setLingerSecond(int);
void getLingerSecond(int);
void setSocketBlockFlag(int);
void getSocketBlockFlag(int);

I think rather than embedding these directly into the socket itself, I'd create a separate socket_options (or something similar) struct to hold them. This would allow (for example) storing an entire set of options together, so you can set all the options for a particular socket at once.

//size of send & Receive Buffer
void  setSendBufferSize(int);
void  getSendBufferSize(int);
void  setReceiveBuffferSize(int);
void  getReceiveBuffferSize(int);

Likewise, I'd probably create a small class just to handle the buffering. Then the socket class could just contain two buffer instances, one for receiving and one for sending.

//get systems error
void detectErrorOpenWinSocket(int*,string&);
void detectErrorSetSocketOption(int*,string&);
void detectErrorGetSocketOption(int*,string&);

These seem to me like they merit at least a little more explanation of what they're actually supposed to be/do.


I think the solution you have is likely to be optimal (or close enough) in terms of runtime, and I think your approach of summing over the slice is much better than doing a for loop.

The only downside of this approach is that it's a little hard to grok, and consequently difficult to extend or maintain, because the approach you're taking is so specific to the implementation of the tree and to the particular task you're doing.  In other words, this code would probably not be reusable for a different task that involved traversing the same tree, or for applying the same task to a different tree representation.

If efficiency is of paramount importance, there's a place for tightly optimized code, but in that case I'd recommend having some explanatory comments to speed the reader's comprehension.  Something with a diagram of the tree layout, say:

# Our tree:
#                      arr[0]                      <-  breadth 1, floor 0
#          arr[1]                  arr[2]          <-  breadth 2, floor 1
#    arr[3]      arr[4]      arr[5]      arr[6]    <-  breadth 4, floor 3

# Begin at the second level (top of the left and right subtrees).
breadth = 2  # number of nodes on the current level
floor = 1    # index of the first node on the current level
left = 0     # sum of the left subtree up to this point
right = 0    # sum of the right subtree up to this point

This is the diagram I built in my head when I was reading the code; having it in front of me already would have saved me a couple of minutes.  With that diagram and the explanations of the different values, it's a lot easier to read through the code and visualize what the slices correspond to.

An entirely different direction to go in for this problem would be to build an abstraction that lets you traverse the tree in a more tree-like way:

from typing import List, NewType, Optional

def solution(arr: List[int]) -> str:
    """Takes a binary tree packed into an array root-first.
    Returns 'Right' or 'Left' to indicate which subtree is larger."""

    # Helpers to read and traverse nodes in the tree.
    # The internal representation of our Node is simply an array index, but
    # these helper functions expose derived "properties" as if it were an object.
    Node = NewType('Node', int)

    def make_node(index: int) -> Optional[Node]:
        return Node(index) if index < len(arr) else None

    def left_child(node: Node) -> Optional[Node]:
        return make_node(node * 2 + 1)

    def right_child(node: Node) -> Optional[Node]:
        return make_node(node * 2 + 2)

    def root_node() -> Optional[Node]:
        return make_node(0)

    def value(node: Node) -> int:
        return arr[node]

    # Recursive function to sum the subtree under a node.
    def sum_subtree(node: Optional[Node]) -> int:
        if node is None:
            return 0
        return (
            value(node)
            + sum_subtree(left_child(node))
            + sum_subtree(right_child(node))
        )

    # Get sums of left and right subtrees.
    root = root_node()
    if root is None:
        return ''
    left_sum = sum_subtree(left_child(root))
    right_sum = sum_subtree(right_child(root))

    if right_sum > left_sum:
        return 'Right'
    elif left_sum > right_sum:
        return 'Left'
    else:
        return ''

This approach breaks the logic into layers.  The foundational layer is the five functions that define the Node abstraction, which gives us a way to read the tree that's completely decoupled from the array.  The details of how the tree is stored in the array (e.g. the magic 2 * index + 1 logic) are completely contained inside these functions.  You could also implement this collection of functions as a class (storing a reference to the array as an instance attribute), which would make it easy to use outside this function and unit-test on its own; I've used a NewType wrapper because it makes it easy to see (and typecheck) the abstraction while still giving us the low overhead of a single int at runtime.

This tree abstraction lets us build a sum_subtree helper that recursively sums up everything under a node.  Even if the reader didn't understand the way the tree is packed into an array (or care to), they could read this function and understand how it's navigating the tree to arrive at a sum, and if they wanted to write a similar function they'd be able to do so without having to understand the array representation.

Finally, we have the top-level logic that gets the two top-level subtrees, compares their sums, and returns a result in the expected format.

This solution is a bit less efficient than yours (the recursive call is going to use log(N) space, and the fact that we're iterating through each node one by one will add a few more clock cycles), but in many real world applications "slow and obvious" is preferable over "fast and clever".  :)


Obviously people are going to have different opinions. I think that adding a lambda just makes it more difficult to read, I would put that in a private emethod (which also has the advantage of making it testable)

There is a bug in your code:

def children(depth: 4, article_children: self.root.child_links)
  @children ||= get_children.call(depth, self.root.child_links)
  return @children
end

You pass self.root_child_links to get_children. You should be passing article_children.

Some style notes:

def children(depth: 4, article_children: self.root.child_links)
  ...
  @children ||= get_children.call(depth, self.root.child_links)
  return @children
end

The return is generally considered bad style. It is enough to specify just the return value on the last line. i.e. just @children. In this case even that is unnecessary as the assignment above returns the value of @children. iow I would just write:

def children(depth: 4, article_children: self.root.child_links)
  ...
  @children ||= get_children.call(depth, self.root.child_links)
end

Also (simplifying this piece of code to show my point)

article_children.map do |uri|
  article = Article.new(uri: uri)
  { article => get_children.call(depth - 1, article.child_links) }
end

This returns an array of hashes which is an odd way to structure data, wouldn't it make sense to return a single hash.

Lastly instead of passing article_links into the method I would pass the article.

My take on this code would be something like:

def children(depth: 4, root: self.root)
  @children ||= recurse_children(depth, root)
end

private

def recurse_children(depth, article)
  article.child_links.reduce do |hash, uri|
    article = Article.new(uri: uri)
    hash[article] = depth > 0 ? recurse_children(article) : nil
    hash
  end
end


Safely Initialising a static variable to a file

I would avoid doing this kind of thing in a static constructor or static initializer. Error handling in this situation can get tricky: errors thrown will result in a TypeInitializationException and the static constructor will not get executed again even if this is handled. You also don't have much control about where this will get thrown in your code: it would be very easy to refactor your code and end up with the first reference to the type appearing in a completely different place.

Loading from a file is also going to cause issues when you write tests: a reference to the type will trigger the static initialization and therefore depend on the presence of the file, which you will need to ensure is present in all the relevant test assemblies (and this kind of thing becomes a headache if you are using things like ReSharper's shadow copying behavior).

I would consider avoiding the use of static methods: define an interface and pass the relevant data in through the class constructor, e.g.

public interface IDataSetToPdf
{
    void Process();
}

public class DataSetToPdf : IDataSetToPdf
{
    private readonly byte[] fontData;

    public DataSetToPdf(byte[] fontData)
    {
        this.fontData = fontData ?? throw new ArgumentNullException(nameof(fontData));
    }

    public void Process()
    {
        // do stuff with fontData
    }
}

There are several advantages of doing this: firstly, if the data is in a static field, it it will last as long as the application does, whereas using an instance field allows the memory to be reclaimed by the garbage collector when no further references to it remains.

Another advantage is that it makes it easier to unit test: provided you write your code against the interface IDataSetToPdf rather than the concrete class DataSetToPdf, you would be able to provide a mock implementation of the interface for your tests, which would allow you to focus your tests on the calling code rather than the combination of the calling code with DataSetToPdf.


Your code seems to me to be as efficient as reasonable for the application you are writing...

... but what you want/intend to do with it is unreasonable.... but first:

The method resetting the time is not very practical

private void textBox1_TextChanged(object sender, EventArgs e)
{
    bestTime = long.MaxValue;
    tbBestTime.Text = bestTime.ToString();
}

This method is setting the text to a value that the typical user will have no frame of reference for.... why is that 'big' number meaningful. Why not just set the tbBestTime.Text to be 'None yet' or something? This is especially significant since all other times the tbBestTime is set, you set it to a floating-point time/1000.0 value.
In your messageBox you do a simple /1000.0 for your time display. This is not going to always be 'pretty' since not all floating point values have a neat representation in binary. You should be using a Number formatter to ensure that the presentation of the value is consistent.... consider Custom Numeric Format Strings.

Finally, lets talk about accuracy and precision....

precision is reporting values to a large number of significant figures. In your case, reporting the time to (an intended) millisecond precision seems like a good idea, but, is that accurate?

Your intention with this question is to improve the accuracy of the results by reducing the overhead of the code when compared to the typing.

Unfortunately there is so much happening between your code and the keyboard that any attempt to increase the code performance will be outweighed by the simple operations happening on the system.... The following are things that may/will affect the accuracy of your timing:

Key debouncing
Interrupt handling
OS event notification
OS Thread scheduling
Clock granularity
TextBox listener notification

I would wager that each of these will be significantly more time than the per-cycle cost of your code.

Optimizing your code will make no difference to the accuracy of your timing, and, as it is, your reported precision is probably far more than the actual accuracy. In fact, I would suggest that anything within 1/10th of a second (instead of 1/1000th) is a 'tie'.


You are basically calculating the modulo manually by doing

if (inh >= 24) { inh = inh - 24; }

but JavaScript can do it for you, so the inXh() function could be written like this:

var inXh = function(toAdd) {
    return (h + toAdd * 6) % 24;
}

With that, after having declared

var h = new Date().getHours();

you have (at least) two options, choose the one you feel more elegant.

OPTION 1: using for:

var hours = [];
for (var i = 0; i < 4; i++) hours.push(inXh(i));

OPTION 2 (nicer in my opinion): using Array.map():

var hours = [0, 1, 2, 3].map(inXh);

which all together in one line would be

var hours = [0, 1, 2, 3].map(function(toAdd) { return (h + toAdd * 6) % 24; });


The smallest number that can be divided by a set of numbers without any remainder is also known as the least common multiple, which can be calculated directly using the greatest common divisor (gcd).

The least common multiple of a, b:

lcm(a, b) = a * b / gcd(a, b)

The least common multiple of a, b, c:

lcm(a, b, c) = lcm(a, lcm(b, c))

You could generalize this to more numbers.


I like the idea you have here and the implementation looks good.  You are right though that it is not best practice to use !important frequently.
I'd think you could avoid using !importants simply with either of the following:

Order: having night mode CSS come later/below day mode CSS
Specificity: as in div.nightmode or .nightmode div would override just div.

Below I used specificity as the order was more to keep it organized.  Sorry I didn't revise your code but I wanted to test this out for myself and see if my simple idea would work.
Code
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Night Mode Test</title>

Some Sample Stuff

Sample Text...

    <button id="toggleNightMode" type="button" name="button">Toggle</button>

So I'd recommend doing the following:

Combine some of your CSS that uses the same color and/or background
Use specificity to override CSS instead of !importants.  I'd recommend using a class or two (dayMode, nightMode).  My small example only needed one: if it lacked the nightMode class then I knew it was day mode.

CodePen Example


ImportExcel for Dataset with Multiple tables

If the Excel sheet names should retain the original TableNames this could do:
(can't test myself)
The code contains two commented out alternatives.

# your code upto $connection.Close() ...

$DataToGather = @{}
foreach ($table in $dataset.Tables) {
    Write-Host $table.TableName
    Add-Member -InputObject $DataToGather -Name $table.TableName -Value $table
#   Add-Member -InputObject $DataToGather -Name $table.TableName -Value $dataset.Tables['$($table.TableName)']
#   $DataToGather.Add($table.TableName,$table)
}

Export-MultipleExcelSheets -Path 'C:\Temp\Test.xlsx' -InfoMap $DataToGather -Show -AutoSize
#$DataToGather

$DataToGather.Clear()


CFLAGS conventionally control the compilation. Linking options, that is

-nostartfiles -shared -ldl

are better be separated into LDFLAGS.
-Werror is always a good idea. You don't want your users to run potentially incorrect code, do you?
I recommend to make $(OUT) directory automatically.

$(OUTFILES): | $(OUT)
$(OUT):
    mkdir $(OUT)

See order-only dependencies for details.
JNI_AUTO_HEADER is a build artifact, and yes make is responsible for it. I see no reason for confusion.
As for #include "bld/com_daftdroid_droidlib_bind_ClientBind.h", consider adding

-include $(JNI_AUTO_HEADER)

to CFLAGS, or passing it via -D option (see this discussion for details)
I don't know the correct way to figure out Java include paths; maybe java.home is a good place to start? You'd need a small Java app to print it though.


You don't care what the numeric value here is, so don't test for it. You want a boolean, and I think the listFind() call is semantically boolean itself without the comparison.

So: "neither". Do this instead:

<cfif ListFind(attributes.config[3], "payout")>

Either/any option looks pretty cluttered as it is, so given yer repeating the same string except for the difference of the value, I'd put that lot in a loop over the values too, maybe?


Python has an official style-guide, PEP8, which you are encouraged to follow to improve readability (mostly by others, but also yourself). On e of its recommendations is using spaces around operators, but no spaces around = when assigning keywords. So these are good:

var = "value"
l = [2, 1, 3]
l.sort(reverse=True)

while these are bad:

var="value"
l=[ 1,2,3 ]
l.sort( reverse = True)

In general it is not best practice to use global, because it makes the state your program is in potentially undefined.

For example the function

def f():
    global c
    return c

It is not defined what this function will output at any given time, because anybody else might modify the global c.

Most of the times, global can be avoided entirely, just by making functions accept the values as parameters and returning the results where necessary.

In your case this is a bit more tricky, because many of these functions cannot take any parameter (because Tkinter just calls them as they are).

There is one work-around for it and one solution, though.

One is using lambdas, like this:

buttons = []
for i in range(10):
    buttons.append(Tkinter.Button(base, bd="0", highlightthickness="0",
                               width="7", height="5", activebackground=color,
                               bg=alt_color, command=lambda i=i: print i)

Here the i=i is evaluated whenever the function is called. A simple lambda: print i would have failed.

The actual solution to this problem, though is to use a class. This way you can pack all those global variables as attributes, can access them within the functions, and so on.

I won't go into details about how to write a class, because there are very good tutorials about this (add links).

There are a few more noteworthy changes.

I made functions to create and place a label, which is pretty straight-forward, and to create and place a button. The latter is a bit more complicated, because, as explained above, the button needs a parameter-less function. For this I used the fact that in python functions are first-class objects. This means that you can return functions from other functions. I therefore wrote a button click handler factory, that produces a custom function given its parameters (with the right color, highlightcolor, etc).

To save the data of the different buttons I created a collections.namedtuple, which is just a tuple, where you can access the members also by name (but also still by index if you need to).

Then I made the game slightly more complete by adding a variable length of the shown sequence, an actual saving and verification of the user sequence and the correct handling of checking whether it is correct.

The attribute self.sequence contains the generated (and shown) sequence, while if a user clicks a button it is added to self.user_sequence if the two are identical the user wins, score is updated (and best if needed). A new sequence can be generated, with a length one longer than before.

If the user clicks and the sequence is right so far, nothing happens. But if the user clicks a button which is not the next in the sequence, the game resets (keeping only best).

I also placed the actual execution of the game in a if __name__ == "__main__": guard to allow importing parts of the code from other scripts (So you can e.g. do from simon_game import Button, if this code is saved as simon_game.py).

Final code:

import Tkinter
import random
from collections import namedtuple

Button = namedtuple("Button", "color alt_color x y")
BUTTONS_DATA = [Button("yellow", "yellow3", 30, 50),
                Button("blue", "medium blue", 125, 50),
                Button("red", "red3", 30, 145),
                Button("green", "dark green", 125, 145)]

class SimonGame:
    def __init__(self, buttons_data=BUTTONS_DATA):
        self.base = Tkinter.Tk()
        self.frame = Tkinter.Frame(self.base, bg="black", width="238", height="250")

        self.score = 0
        self.score_label = self.place_label(30, 15, "Score:")
        self.score_val = self.place_label(70, 15, self.score)

        self.best = 0
        self.best_label = self.place_label(155, 15, "Best:")
        self.best_val = self.place_label(188, 15, self.best)

        self.start = Tkinter.Button(self.base, bd="0", text="start", command=self.show_sequence)
        self.start.place(x=90, y=12)

        self.sequence = []
        self.user_sequence = []

        self.buttons_data = buttons_data
        self.buttons = [self.create_button(*button) for button in self.buttons_data]

        self.frame.pack()
        self.base.resizable(False, False)
        self.base.mainloop()

    def place_label(self, x, y, text, fg="white", bg="black"):
        label = Tkinter.Label(self.base, bg=bg, fg=fg, text=text)
        label.place(x=x, y=y)
        return label

    def click_factory(self, button, color, alt_color):
        def click():
            button.configure(activebackground=alt_color)
            button.after(500, lambda: button.configure(activebackground=color))
            self.user_sequence.append(color)
            self.check_sequence()
        return click

    def create_button(self, color, alt_color, x, y):
        button = Tkinter.Button(self.base, bd="0", highlightthickness="0",
                           width="7", height="5", activebackground=color,
                           bg=alt_color)
        button['command'] = self.click_factory(button, color, alt_color)
        button.place(x=x, y=y)
        return button

    def show_sequence(self):
        self.reset_gui()
        for _ in range(self.score + 1):
            i = random.randrange(len(self.buttons))
            button = self.buttons[i]
            button_data = self.buttons_data[i]
            button.configure(bg=button_data.color)
            button.after(750, lambda: button.configure(bg=button_data.alt_color))
            self.sequence.append(button_data.color)
        print self.sequence

    def check_sequence(self):
        if self.sequence == self.user_sequence:
            self.score += 1
            self.best = max(self.best, self.score)
            self.reset_gui()
        elif not self.sequence[:len(self.user_sequence)] == self.user_sequence:
            self.score = 0
            self.reset_gui()

    def reset_gui(self):
        self.sequence = []
        self.user_sequence = []
        for button, data in zip(self.buttons, self.buttons_data):
            button.configure(bg=data.alt_color, activebackground=data.color)
        self.best_val.configure(text=self.best)
        self.score_val.configure(text=self.score)

if __name__ == "__main__":
    game = SimonGame()

What is left to do:
The graphical part is not very clean. Some buttons get stuck on on (in sequences where a button appears an even number of times) and the sequence plays out too fast. Also more visual feedback when getting a whole sequence right or messing it up would help.


Style

The Style Guide for Python Code called PEP 8 recommends a 4-space indent.

More functions

You could split your logic into smaller logical pieces which are easier to understand, to test and to optimise (I'll come back to this later).

For instance:

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def get_primes(lower, upper):
    for num in range(lower, upper):
        if is_prime(num):
            primes.append(num)

Avoid global

Your function get_primes would be much easier to use if instead of appending to a global variable, it was using a proper return value.

def get_primes(lower, upper):
    primes = []
    for num in range(lower, upper):
        if is_prime(num):
            primes.append(num)
    return primes

primes = get_primes(5, 56)  # get_primes(500000, 560000)
print primes

More functions (again)

You could add a function get_twin_primes to return ... the twin primes.

if __name__ == "__main__":

It is practical (and conventional) in Python to use the if __name__ == "__main__": to separate your functions/classes definitions from the code actually using it. This makes code reuse possible via import : the functions/classes can be used by other modules without triggering all your computations.

Now, the whole code looks like:

import math

def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def get_primes(lower, upper):
    primes = []
    for num in range(lower, upper):
        if is_prime(num):
            primes.append(num)
    return primes

def get_twin_primes(primes):
    twins = []
    for i in range(0, len(primes) - 1):
        if primes[i+1] - primes[i] == 2:
            twins.append((primes[i], primes[i+1]))
    return twins

if __name__ == "__main__":
    primes = get_primes(5, 56)  # get_primes(500000, 560000)
    print primes
    for a, b in get_twin_primes(primes):
        print a, b

More beautiful loop

I highly recommend Ned Batchelder's excellent talk called "Loop Like A Native" (and any other talk he's done). You'll learn a lot about iterations in Python and that basically, anytime you write "range(len(list))", there is a better way.

In your case, you'll find various ways to iterate over consecutive items in a list like this:

def get_twin_primes(primes):
    twins = []
    for p1, p2 in zip(primes, primes[1:]):
        if p2 - p1 == 2:
            twins.append((p1, p2))
    return twins

(In Python 2, you could use itertools.izip instead of zip but if you're learning Python, you should try to use Python 3 directly).

Then, this can easily be rewritten using a list comprehension:

def get_twin_primes(primes):
    return [(p1, p2) for p1, p2 in zip(primes, primes[1:]) if p2 - p1 == 2]

More list comprehensions

You can also use list comprehensions in get_primes:

def get_primes(lower, upper):
    return [num for num in range(lower, upper) if is_prime(num)]

Using builtins (and generator expressions)

Your function could be writen in a more concise way using the builtin all.

def is_prime(n):
    return all(n % i != 0 for i in range(2, n))

You can easily read this as "a number is prime is all divisions have a non-zero remainder".

It's exactly like the logic you had before but you are reusing already existing builtins and it teaches you new things :)

Now, the whole code looks like:

import math

def is_prime(n):
    return all(n % i != 0 for i in range(2, n))

def get_primes(lower, upper):
    return [num for num in range(lower, upper) if is_prime(num)]

def get_twin_primes(primes):
    return [(p1, p2) for p1, p2 in zip(primes, primes[1:]) if p2 - p1 == 2]

if __name__ == "__main__":
    primes = get_primes(5, 56)  # get_primes(500000, 560000)
    print primes
    for a, b in get_twin_primes(primes):
        print a, b

Optimisation

A simple yet very efficient optimisation when checking for prime is to use the fact that if a number is composite, for any pair of factors, one is less than or equal to the square root, and the other is greater than or equal to the square root, so you don't need to check the values larger than the square root of the number you are considering. There you can write something like:

def is_prime(n):
    """Checks if a number is prime."""
    if n < 2:
        return False
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1))

Another optimisation you could do is to use the step argument of range in get_primes to iterate over odd numbers only (and add "2" at the beginning if needed).


Executing an operator in an RPN evaluator

As @DavidHarkness points out, you didn't provide enough context for this question to make sense.  However, I see that this code comes from a doTypeCheck() method, which is at the heart of your RPN calculator implementation.  I'll reproduce that method here, along with its call site:

private void doTypeCheck(Fraction op1, Fraction op2)
{
    Fraction answer = null;
    String readIn = "";
    boolean valid = true;
    readIn = stdin.next();

    while(!readIn.equals("#") && valid == true)
    {
       if(!isOperator(readIn) && isOperand(readIn))
       {
          processOperand(readIn);
          readIn = stdin.next();
       }
       else if(isOperator(readIn))
       {
          System.out.print(readIn);
          if(myStack.isEmpty())
             valid = false;
          else
             op2 = (Fraction)myStack.pop();

          if(myStack.isEmpty())
          {
             valid = false;
             throwLine(readIn);
          }
          else
          {
             runTheOperator(op2, op1, readIn);
             readIn = stdin.next();
          }
       }
       else
       {
          System.out.print(readIn);
          valid = false;
          throwLine(readIn);
       }
    }
    System.out.println();
    if(myStack.isEmpty())
       valid = false;
    else
       answer = (Fraction)myStack.pop();
    if(!myStack.isEmpty())
       valid = false;
    checkMessageValid(valid, answer);
}

private void runOnce(int count)
{
    Fraction op1 = null;
    Fraction op2 = null;
    clear(myStack, myQueue);

    System.out.print("Expression " + count++ + " is: ");
    doTypeCheck(op1, op2);
 }

The root problem is that your method has no clear purpose, and tries to do many things:

Read tokens from the input stream, and decide whether they are operands or operators
If it sees invalid input, discard the rest of the input and display an error
Pop an operand from the stack, with error handling
Feed two operands to the calculating function
Check that the stack is empty afterwards
Display the answer

As I mentioned in my other answer, that's not a good way to write an RPN calculator.

The main loop of an RPN evaluator should probably look something like this:

try {
    while (in.hasNext()) {
        String token = in.next();
        RpnOperator op = RpnOperator.forSymbol(token);
        if (op != null) {
            op.operate(calcStack);
        } else {
            calcStack.push(new Fraction(token));
        }
    }
    System.out.println(calcStack.peek());
} catch (EmptyStackException emptyStack) {
    System.out.println("Error: empty stack");
}

That's all!  To summarize:

Let the operators manipulate the stack.  The main loop just needs to dispatch to the appropriate operators.
Use exceptions for error handling.


“Real world” JSON transformation using Node.js

Maintenance by design
There are many times when I see this type of question regarding maintainability of the code. The line between code maintenance and user friendly becomes blurred. This is most evident when the coder is also the end user, the interface UI is misunderstood by familiarity of use, it is of course the IDE. This may sound somewhat pedantic, but the mind set it helps introduce can go a long way into how you design your code.
Encapsulate the interface
In this example if we look at the task of maintenance as an end user task, we design the code with all the possible changes encapsulated in a simple structure that isolates the code from the user. (Users can't code so don't let them near it, especially those users than think they can code (I am my most difficult client))
If done well the maintenance is trivial and the meat of the logic safe from the corruption inevitable when the logic must be reacquired in some maybe distant future.
So we can create am object called rules. It is the interface (abstract representation of codes functionality), and as with all good UI it will require some help information in the form of comments (remember the interface is the IDE)
As I have little to no clue what the possible alterations may be I have had to guess, this interface may not be adaptable to your needs. It is an example only
const rules = {
    name: "Outputs",     // name of transformed object
    typesName: "types",  // name of type ids array eg {Outputs: types: [1,4,23] }
    itemsName: "locs",   // name of items object in and out  eg {Outputs: locs: {} }
    keep: ["contents", "last_update", "plan_id", "type_id"],  // List of properties
                                                              // to keep per item
    itemName: "loc_id",  // name of property to use as named item
    ids: ["type_id"],    // list of property names containing ids for the array of types
};

The code can then use this encapsulated information as input, doing its thing and spitting out the result. Many changes can be made by just changing some text and never going near the logic.
function transform(data, rules) {
    const items = {}, types = new Set();
    const addTypes = from => rules.ids.forEach(key =>
         from[key] !== undefined && (types.add(from[key]));
    const addProps = from => rules.keep.reduce((obj, key) =>
         from[key] !== undefined ? (obj[key] = from[key], obj) : obj, {});
    const transformLoc = loc => {
        const lName = loc[rules.itemName];
        if (lName !== undefined) {
            items[lName] = addProps(loc);
            if (loc.contents) { loc.contents.forEach(addTypes) }
            addTypes(loc);
        }
    }
    data[rules.itemsName].forEach(transformLoc);
    return {
        [rules.name]: {
            [rules.typesName]: [...types],
            [rules.itemsName]: items
        }
    };
}

const transformed = transform(data.Input, rules);

Even if we ignore this UI/code abstraction, the resulting code is more maintainable as you have moved many of the magic constants out of the code, and have been forced to think of what you are doing in a higher level abstract, that helps any future coders wrap their thinking nog around the logic.


PowerShell script to automate the search of DLL files

You can replace all this:

function likeAnyOf($obj,$array)
{
    foreach($item in $array)
    {
        if($obj -like $item)
        {
            return $item
        }
    }
    return $null
}

# ...

$excluded = likeAnyOf $moduleParent (Resolve-Path $Exclude)

With this:

$excluded = Resolve-Path $Exclude | ? { $moduleParent -like $_ }

The question mark (?) is an alias for Where-Object, so read up on that for an explanation.

Instead of this:

if ($excluded -ne $null)
{
    # ...
}

you can do this:

if ($excluded)
{
    # ...
}

It's just a little bit easier to read.


You've posted some code, which shows what you told the computer to do.
And it even has some comments.
Honestly, that's a lot better than the average question.

Then you realize that we aren't going to understand this blob of code, so you use phrases like "I made" and "It uses Euler's Sieve" and "I need the primes up to about two billion".
Look, that's super-useful information, and I'm glad you told me that, but I'm going to suggest that in the future you put information about who wrote the program, the name of the algorithm you use, etc.
into comments embedded in the program:

// pes30.cxx
// prime number generator for Project Euler
// Print all the primes up to 2x10^9.
// 2014-05-08: started by hacatu
// implementation of Euler's sieve (a modified Sieve of Eratosthenes)
// http://en.wikipedia.org/wiki/Euler%27s_sieve
// using wheel factorization with a wheel of size 30 to reduce memory requirements
// http://en.wikipedia.org/wiki/wheel_factorization

So is there some reason not to use http://primesieve.org/ ?
Have you gotten it working without the wheel factorization optimization?
Have you tried looking at only odd prime candidates (wheel of size 2) or a small wheel of size 6 or 12 ?

I am mystified by the 3 lines

bool n[max];//array of whether or not each number is prime (30/8 too big!)
for(big i=0; i<max; ++i)//initialize the array
    n[i]=true;

The "max" is the largest number you want to check for possibly being prime during this run of the program, right?
So that line eats a bunch of memory -- one bool per each number from 0 to max, perhaps 2 million bool values.

I thought you were going to use wheel factorization to reduce memory requirements?

I think you want to replace those 3 lines with something more like the following 2 lines of code:

big blocks_of_30_values = (max/30)+1;
// For example, when max is 38, max/30 gives 1, but we need 2 blocks: 0..29 and 30..59.
// In each block of 30 values under consideration
// (i.e, the block 30..59, the block 60..89, the block 90..119, etc.),
// after using the wheel factorization to eliminate multiples of 2 and 3 and 5,
// there are only 8 potential candidates left in each block.
// So store each block in a single unsigned char:
// and initialize the array to all 1 bits (1=candidate prime, 0=definitely composite)
std::vector<unsigned char> candidatePrime( blocks_of_30_values, 0xFF );

So when max is 2 billion, we only allocate (max/30) = under 70 million chars, or roughly 533 million bits.

It might make your program easier to read if you have named functions for converting a bit in the array to the integer value it represents and vice versa:

// the bit at the n'th bit of the m'th byte of the candidatePrime array
// represents what value?
big the_value( big block_number, int bit_number ){
    const int offset[] = { 1, 7, 11, 13, 17, 19, 23, 29 };
    int this_offset = offset[bit_number];
    return( (30*block_number) + this_offset );
}
// the given integer value n corresponds to
// what (block_number, bit_number) of the candidatePrime array?
// assumes that n is *not* a multiple of 2, 3, or 5.
big block_number( big integer_value ){
    return (integer_value/30);
}
int bit_number( big integer_value ){
    // as long as the integer_value is not a multiple of 2, 3, or 5,
    // this function should never return '9'.
    // translate a value 0..29 into the corresponding bit number 0..7
    const int bit_offset[] = {
        9, 0, 9,  9, 9, 9,
        9, 1, 9,  9, 9, 2,
        9, 3, 9,  9, 9, 4,
        9, 5, 9,  9, 9, 6
        9, 7, 9,  9, 9, 7
    };
    return bit_offset[ integer_value % 30 ];
}


if time_slices[current_time_slice] == nil
  time_slices[current_time_slice] = Hash.new
end

It's more idomatic to write

time_slices[current_time_slice] ||= {}

In general don't use Hash.new if you can just write {}. You can rid of that statement alltogether though if you declare the time_slices variable with

time_slices = Hash.new { |h, k| h[k] = {} }

instead of time_slices = Hash.new.

if time_slices[current_time_slice][row['label']]
  time_slices[current_time_slice][row['label']].put_line(row)
else
  new_slice = Slice.new(current_time_slice, row['label'])
  new_slice.put_line(row)
  time_slices[current_time_slice][row['label']] = new_slice
end

Also

time_slices[current_time_slice][row['label']] ||= Slice.new ...

is more idiomatic here. But there is more to say here:

Don't forget that Ruby is an interpreted language in principle (although the byte compiler of Ruby 1.9 relativizes that), so don't repeat complex references like time_slices[current_time_slice][row['label']]. But that's not only an performance but even more so an readability issue.
Why does a Slice instance has to know the current_time_slice and label? That's completely redundant, since that information is already in the Hash. Get rid of that.

Considering this I would write the loop like this:

time_slices = Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = Slice.new } }

CSV.foreach(input_file, col_sep: '|', headers: :first_line) do |row|
  current_time_slice = row['timeStamp'][0, precision]
  time_slices[current_time_slice][row['label']].put_line(row)
end

Of course you then have to modify your output loop a little

time_slices.each do |slice_timestamp, time_slice|
  time_slice.each do |label, slice|
    out.puts [slice_timestamp, label, slice.average].join('|')
  end
end

So you don't need the Slice#aggregated_row method anymore. But that's a good idea anyway: e.g. why does Slice has to know about your pipe separator? That's not a good separation of concerns.

Note that I avoid the + operator here. That would create a new String instance with every + call. Alternatively you can also try <<, but be aware that this modifies the leftmost string (but oftentimes that doesn't matter).

In contrast there is no penalty in using + in groovy normally, because modern JVMs are using StringBuilder under the hood for it when they see fit. But in Ruby you still should be aware of its implications.

attr_accessor :slice_timestamp, :slice_label, :lines, :sum, :count

Why are you declaring these accessors? They are never used.


Getting hexagonal arrays of dots arranged in this spiral pattern

return early

For the special case, n_max == -1, you can return early

def hexit_60(n_max):
    if n_max == -1:
        return None

This allows you to simplify the loop a lot

special case

the part before the for-loop can be included in the main loop by taking one of the other answers to your int question, and use casting.

reverse

The reverse of seq is also the negative. If you extract the (n-1)*[-n] to another variable, you can make this a lot clearer.

np.roll

np.hstack((p0[N-2*n:], p0[:N-2*n])) is equivalent to np.roll(p0, 2 * n)

generator

You can make the hexit_60 into a generator, even further simplifying it

def hexit_60_gen(n_max):
    if n_max == -1:
        return
    yield np.zeros(2, dtype=int)[:, None]
    for n in range(1, n_max + 1):
        seq = np.arange(-n, n + 1, dtype=int)
        middle = np.array((n - 1) * [-n], dtype=int)
        p0 = np.hstack((-seq, middle, seq, -middle,))
        p1 = np.roll(p0, 2 * n)
        yield np.vstack((p0, p1))

This code is a lot clearer to read to me.

It generates the same points:

all(
    np.array_equal(
        hexit_60(n_max), np.hstack(list(hexit_60_gen(n_max)))
    )
    for n_max in range(10)
)

get_points

You need to adapt this slightly:

def get_points_gen(a, n_max):
    vecs = a * np.array([[1.0, 0.0], [0.5, 0.5 * np.sqrt(3)]])
    pairs = list(hexit_60_gen(n_max=n_max))
    if pairs:
        return (np.hstack(pairs)[:, None] * vecs[..., None]).sum(axis=0)

if pairs is empty, this returns None implicitly.

The one thing I would is replace [0.5, 0.5 * np.sqrt(3)] by

angle = np.pi / 3 # diagonal
[np.cos(angle), np.sin(angle)]

So you don't have as many magic numbers in the code

draw_hexagon

can be simplified with a slight reordering and a continue

def draw_hexagon():
    fig = plt.figure()
    for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
        ax = fig.add_subplot(2, 3, i+1)
        # plt.subplot(2, 3, i+1)
        ax.set_title('n_max: ' + str(n_max))
        points = get_points_gen(a=1.0, n_max=n_max)
        ax.set_xlim(-4.2, 4.2)
        ax.set_ylim(-4.2, 4.2)
        if points is None:
            continue
        x, y = points
        ax.scatter(x, y)
        ax.plot(x, y, '-k', linewidth=0.5)
        ax.set_aspect('equal')
    plt.show()

This latest part can be made a bit cleaner, using the principles of clean architecture, but this is good enough, or a bit more parametrized, but this is good enough.

--

alternative approach

Instead of the approach of the hexit_60, you can have a function to assemble the first side of the hexagon, and then apply rotations to this:

ANGLE = np.pi / 3
COS_ANGLE = np.cos(ANGLE)
SIN_ANGLE = np.sin(ANGLE)
ROTATION_MATRIX = [[COS_ANGLE, -SIN_ANGLE], [SIN_ANGLE, COS_ANGLE]]

Then to get one side, using np.linspace to do the interpolation:

def side_points(n):
    if n == 0:
        return np.array([[0], [0]])
    p0 = np.array([n, 0])
    p1 = n * np.array([COS_ANGLE, SIN_ANGLE])
    return np.linspace(p0, p1, n, endpoint=False).T

And then the rotations is a simple generator

def rotations(side):
    yield side
    if np.array_equal(side, np.array([[0], [0]])):
        return
    for _ in range(5):
        side = np.dot(ROTATION_MATRIX, side)
        yield side

Note that this can be easily adjusted to any regular polygon, by adjusting the angle, and passing in the appropriate cosinus, sinus and or rotation_matrix as function parameter instead of using the global

from functools import lru_cache

@lru_cache(None)
def cos_angle(sides):
    return np.cos(2 * np.pi / sides)

@lru_cache(None)
def sin_angle(sides):
    return np.sin(2 * np.pi / sides)

@lru_cache(None)
def rotation_matrix(sides):
    return np.array(
        [
            [cos_angle(sides), -sin_angle(sides)],
            [sin_angle(sides), cos_angle(sides)],
        ]
    )

def side_points(n, sides=6):
    if n == 0:
        return np.array([[0], [0]])
    p0 = np.array([n, 0])
    p1 = n * np.array([cos_angle(sides), sin_angle(sides)])
    return np.linspace(p0, p1, n, endpoint=False).T

def rotations(side, sides=6):
    yield side
    if np.array_equal(side, np.array([[0], [0]])):
        return
    rot = rotation_matrix(sides)
    for _ in range(sides - 1):
        side = np.dot(rot, side)
        yield side

def points(n_max, sides=6):
    return np.hstack(
        list(
            itertools.chain.from_iterable(
                rotations(side_points(n, sides), sides)
                for n in range(n_max + 1)
            )
        )
    )

Then drawing the polygon is simply:

def draw_polygon(sides=6):
    fig = plt.figure()
    for i, n_max in enumerate([-1, 0, 1, 2, 3, 4]):
        ax = fig.add_subplot(2, 3, i + 1)
        # plt.subplot(2, 3, i+1)
        ax.set_title("n_max: " + str(n_max))
        ax.set_xlim(-4.2, 4.2)
        ax.set_ylim(-4.2, 4.2)
        if n_max < 0:
            continue
        all_points = points(n_max, sides=sides)
        ax.scatter(*all_points)
        ax.plot(*all_points, "-k", linewidth=0.5)
        ax.set_aspect("equal")
    return fig

draw_polygon(7)


Is this powershell code to install the linux sl command to PowerShell good?

Use the script template for documentation
Use a cmdlet binding for parameter
validation and help text
Personally, I run with $ErrorActionPreference = "Stop"


Calculating reverse dependencies of a Debian package

#!/usr/bin/env python3

import argparse
import apt

def getdeps(deptype, pkg, otherpkg):

I recommend not using abbrivates like dep or pkg.

    deps = list()

We usually create lists with [] not list()

    name = otherpkg.shortname
    otherpkg = otherpkg.candidate

I wouldn't do this. You only use it once, so its actually best to just otherpkg.candidate.get_dependencies Generally, I recommend against replacing one variable with another because often it increases confusion.

    for deplist in otherpkg.get_dependencies(deptype):
        for dep in deplist.or_dependencies:
            if dep.name == pkg.shortname:
                deps.append(name)

    return deps

Why does this function return a list? It seems to me that you are checking whether otherpkg depends on pkg. If so, this function really ought to return True or False.

def reverse_dependencies(pkg):
    """Which packages have some kind of dependency on the given package"""

    cache = apt.cache.Cache()
    try:
        pkg = cache[pkg]
    except KeyError as e:
        print(str(e).strip('"'))
        return 1

You don't do anything with this return value. you should pass it to sys.exit()

    dependents = dict()

We usually create dicts with {}

    recommends = list()
    suggests = list()
    replaces = list()
    enhances = list()
    depends = list()

These are all basically the same thing which means they shouldn't be seperate variables.

    for key in cache.keys():
        otherpkg = cache[key]
        depends.append(getdeps("Depends", pkg, otherpkg))
        recommends.append(getdeps("Recommends", pkg, otherpkg))
        suggests.append(getdeps("Suggests", pkg, otherpkg))
        replaces.append(getdeps("Replaces", pkg, otherpkg))
        enhances.append(getdeps("Enhances", pkg, otherpkg))

This would be better as iteration over a list of the dependency types. Also you are putting lists into lists. It'd be cleaner if you just had lists.

    dependents["Depends"] = depends
    dependents["Recommends"] = recommends
    dependents["Suggests"] = suggests
    dependents["Replaces"] = replaces
    dependents["Enhances"] = enhances

    for deptype, deps in dependents.items():
        deps_output = list()
        for match in deps:
            if match:

There's no point in doing this, because the loop will be executed 0 times if match is empty

                for item in match:
                    deps_output.append(item)

Use dep_output.extend(match) it has the same effect as this loop

        if deps_output:
            print(deptype.upper(), end=": ")
            print(" ".join(deps_output))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("pkg", help="pkg to describe")
    args = parser.parse_args()
    reverse_dependencies(args.pkg)

My reworking of your code:

#!/usr/bin/env python3

import argparse
import apt
import sys

DEPENDENCY_TYPES = [
    "Depends",
    "Recommends",
    "Suggests",
    "Replaces",
    "Enhances",
]

def extract_dependencies(package, dependency_type):
    """
    Generator that produce all the dependencies of a particular type
    """
    for dependency_list in package.candidate.get_dependencies(dependency_type):
        for dependency in dependency_list.or_dependencies:
            yield dependency.name

def reverse_dependencies(pkg):
    """Which packages have some kind of dependency on the given package"""

    cache = apt.cache.Cache()
    try:
        pkg = cache[pkg]
    except KeyError as error:
        print(error.args[0])
        sys.exit(1)

    dependents = { name : [] for name in DEPENDENCY_TYPES }

    for key in cache.keys():
        other_package = cache[key]
        for dependency_type, specific_dependents in dependents.items():
            if pkg.shortname in extract_dependencies(other_package, dependency_type):
                specific_dependents.append(other_package.shortname)

    for dependency_type, specific_dependents in dependents.items():
        if specific_dependents:
            print(dependency_type.upper(), ": ", " ".join(specific_dependents))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("pkg", help="pkg to describe")
    args = parser.parse_args()
    reverse_dependencies(args.pkg)


Instead of that while-loop, I'd use a for-loop and use the common loop/index variable i.
Instead of a separate status variable, I'd simply use i % 2.
I'd deduplicate the two cases.
Putting the current two array elements into variables avoids duplicating the longer array[i] and array[i + 1] and simplifies the swap.
As Joop Eggen points out, it's probably better to not modify the array in-place and return it. (Unless you have a good reason to, which it seems you don't, as your own calling code ignores the returned value.)

Code:
    private static void zigZag(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            int a = array[i], b = array[i + 1];
            if (i % 2 == 0 ? a > b : a < b) {
                array[i] = b;
                array[i + 1] = a;
            }
        }
    }


Convert String to Integer with default value

here is a solution :

int tryParseInt(String value) {
 try {
     return Integer.parseInt(value);
  } catch(NumberFormatException nfe) {
      // Log exception.
      return 0;
  }
}

you should catch NumberFormatException instead of exception.


Stopping a long-running asynchronous computation

Task-based Asynchronous Pattern (MSDN)

public async Task<IProblemSolution> Search(CancellationTokenSource cts)

As I explain in this answer, one would rightfully expect the signature of that method to read like this:
public async Task<IProblemSolution> SearchAsync(CancellationTokenSource cts)

The pattern for async methods is quite simple: use the async keyword, return Task or Task<T>, and put an "Async" suffix to the method's name.

I haven't written much async code (read: never wrote a line of C# that leverages features of .net 4.5), but from previous reviews of such code I think this:
    Task<IProblemSolution> t = Engine.Search(CancelTokenSrc);
    await t;

    ResultLabel.Content = t.Result.ObjectiveValue().ToString();

Could be written like this:
    var searchResult =  await Engine.SearchAsync(CancelTokenSrc);
    ResultLabel.Content = searchResult.ObjectiveValue().ToString();
    //...

My understanding is that await somehow deals with Task.Result and so the type of searchResult would be IProblemSolution - I might be wrong here though.
Other than that, I find you could give var some lovin', and change this:
IProblemSolution s = Problem.RandomSolution();

To this:
var s = Problem.RandomSolution();

Lastly, I might be biased because I use ReSharper and with that tool IntelliSense/auto-complete is much "smarter", but I don't like names like cts - I'd rather call it cancelTokenSource and then I can type ctsTab and poof I'm referring to a readable identifier with a pronounceable name.


Segregate even and odd numbers in a given array

I strongly doubt that your program does exactly this:

Example:
  Input = {12, 34, 45, 9, 8, 90, 3}
  Output = {12, 34, 8, 90, 45, 9, 3}

AFAIK the output will be

  Output = {12, 34, 90, 8, ...}

i.e., the elements get reordered because of the swapping. But that's alright according to what's required.

 private static void evenOddFunction(int []data) {

It's not a function, it's a method. And calling something evenOddMethod wouldn't be any better as there's no information therein. something like evenOddSegregator sounds better, but method names should be verbs. So maybe segregateEvenOdd?

    if(data[leftSide] % 2 != 0 && data[rightSide] % 2 == 0) {
        ...
    } else {
        if(data[leftSide] % 2 == 0) {
            ...
        }
        if(data[rightSide] % 2 == 1) {
            ...
        }

I hate repeated conditions. What about

    if(data[leftSide] % 2 == 0) {
        ...
    } else if(data[rightSide] % 2 == 1) {
        ...
    } else {
        ...
    }

It's not exactly the same, but this doesn't matter.

private static void swappEvenOdd(int []data , int left, int right) {

This is misnomer (and a type, too). There's nothing even nor odd in this method.

  Any chances of improvement/optimizations in this code?

I guess your code is optimal, apart from this low-level optimization: Instead of (x % 2) use x & 1; it's much faster, works better for negative numbers, etc. But the JIT knows this trick too and there's not so much to gain.

An untested, stupid, but funny solution:

Comparator<Integer> comparator = new Comparator<>() {
    public int compare(Integer a, Integer b) {
        return (a & 1) - (b & 1);
    }
}
Collections.sort(Ints.asList(data), comparator);

The comparator claims that an even number is smaller than an odd number and sort does all the work. It's even stable, i.e., it doesn't reorder what it doesn't have to and produces the output from your example. Guava's Ints adapts the array as a List<Integer>.


Extracting queries from controller to model

This is a good place to use scopes. http://edgeguides.rubyonrails.org/active_record_querying.html#scopes Scopes are just syntactic sugar for class methods that return relations. In this way they can always be chain-able.

scope :ordered -> { order(deadline: 'DESC') }
scope :paginated -> (page: 1) { paginate(page: page, per_page: pagination_per_page) }
scope :assigned_default -> (page: 1) { uncompleted.includes(executor: :profile).ordered.paginated(page: page) }


This is excellent code for a Python novice.

To address your questions:

Rather than x and y, try naming your variables row and col.  Then it wouldn't feel unnatural to write self.state.board[row][col].
In my opinion, the .neighbour() function would be better in the State class, since you're counting neighbours of a cell within that state.
Your code is easy to understand, partly because the rules of the game are well known.  However, you should still write docstrings for your functions.  It's not obvious, for example, what to pass for the state parameter to the Game constructor unless you read the code.  (Should I pass a 2D array of booleans?)
You could use list comprehensions, but the current code is not bad either.
I would rename both of your display(self) functions to __str__(self).  In Game, that function would become

def __str__(self):
    return str(self.state)

Then you can just print my_game.


1. Checking your claim

You claim that "these both outperform scipy's gmean implementation", but I can't substantiate this. For example:

>>> import numpy
>>> data = numpy.random.exponential(size=5000)
>>> from timeit import timeit
>>> timeit(lambda:fast_gmean(data), number=10000)
5.540040018968284
>>> timeit(lambda:actually_fast_gmean(data), number=10000)
1.4999530320055783
>>> from scipy.stats import gmean
>>> timeit(lambda:gmean(data), number=10000)
1.4939542019274086

So as far as I can tell, there's no significant difference in runtime between your actually_fast_gmean and scipy.stats.gmean, and your fast_gmean is more than 3 times slower.

So I think you need to give us more information. What's the basis for your claim about performance? What kind of test data are you using?

(Update: in comments it turned out that you were using scipy.stats.mstats.gmean, which is a version of gmean specialized for masked arrays.)

2. Read the source!

If you look at the source code for scipy.stats.gmean, you'll see that it's almost exactly the same as your actually_fast_gmean, except that it's more general (it takes dtype and axis arguments):

def gmean(a, axis=0, dtype=None):
    if not isinstance(a, np.ndarray):  # if not an ndarray object attempt to convert it
        log_a = np.log(np.array(a, dtype=dtype))
    elif dtype:  # Must change the default dtype allowing array type
        if isinstance(a,np.ma.MaskedArray):
            log_a = np.log(np.ma.asarray(a, dtype=dtype))
        else:
            log_a = np.log(np.asarray(a, dtype=dtype))
    else:
        log_a = np.log(a)
    return np.exp(log_a.mean(axis=axis))

So it's not surprising that these two functions have almost identical runtimes.

3. Why fast_gmean is slow

Your strategy is to avoid calls to log by performing arithmetic on the exponent and mantissa parts of the floating-point numbers.

Very roughly speaking, for each element of the input, you avoid one call to each of log and mean, and gain one call to each of frexp, sum, array_split and prod.

>>> from numpy import log, mean, frexp, sum, array_split, prod
>>> for f in log, mean, frexp, sum, prod:
...     print(f.__name__, timeit(lambda:f(data), number=10000))
log 1.0724926821421832
mean 0.3662677980028093
frexp 0.34479621006175876
sum 0.21649421006441116
prod 0.280590218026191
>>> timeit(lambda:array_split(data, 5), number=10000)
2.1635821380186826

So it's the call to numpy.array_split that's costly. You could avoid this call and split the array yourself, like this:

def fast_gmean2(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = np.sum(exponent)
    while base.size > 1:
        intermediates = []
        for i in range(0, base.size, chunk_size):
            intermediates.append(np.prod(base[i:i + chunk_size]))
        base, current_exponent = np.frexp(np.array(intermediates))
        exponent_sum += np.sum(current_exponent)
    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)

and this is roughly twice as fast as your version:

>>> timeit(lambda:fast_gmean2(data), number=10000)
2.585187505930662

but still about twice as slow as scipy.stats.gmean, and that's because of the Python interpreter overhead. Numpy has a speed advantage whenever you can vectorize your operations so that they run on fixed-size datatypes in the Numpy core (which is implemented in C for speed). If you can't vectorize your operations, but have to loop over them in Python, then you pay a penalty.

So let's vectorize that:

def fast_gmean3(vector, chunk_size=1000):
    base, exponent = np.frexp(vector)
    exponent_sum = np.sum(exponent)
    while len(base) > chunk_size:
        base = np.r_[base, np.ones(-len(base) % chunk_size)]
        intermediates = base.reshape(chunk_size, -1).prod(axis=0)
        base, current_exponent = np.frexp(intermediates)
        exponent_sum += np.sum(current_exponent)
    if len(base) > 1:
        base, current_exponent = np.frexp([base.prod()])
        exponent_sum += np.sum(current_exponent)
    return base[0] ** (1.0/vector.size) * 2 ** (exponent_sum/vector.size)

For arrays of the size we've been testing (about 5000), this is a little slower than fast_gmean2:

>>> timeit(lambda:fast_gmean3(data), number=10000)
2.8020136120030656

But for larger arrays it beats gmean:

>>> bigdata = np.random.exponential(size=1234567)
>>> timeit(lambda:gmean(bigdata), number=100)
3.192410137009574
>>> timeit(lambda:fast_gmean3(bigdata), number=100)
2.3945167789934203

So the fastest implementation depends on the length of the array.

4. Other comments on fast_gmean

There's no docstring. What does this function do and how do I call it? What value should I pass in for the chunk_size argument?
It's critical that chunk_size is not too large, otherwise the call to prod could underflow and the result will be incorrect. So there needs to be a check that the value is safe, and a comment explaining how you computed the safe range of values.


Small nitpicks

The for loop can be started from 1, as the iteration with 0 doesn't actually do anything.
Prefer to reduce the scope of variables if possible. This allows better reasoning for the compiler/optimizer, and makes the code more readable because the variable declaration is nearer to the actual usage.
The check arr[index_sorted] >= 0 in the while loop should probably be index_sorted >= 0u (after all, Element might not be comparable to integers), but this is true in all cases (-1 for an unsigned integer type is equal to that type's maximum value). However, even checking this becomes unnecessary if the first iteration starts at 1.
The array elements could possibly be moved to their new locations (this might improve performance in some cases).

template<typename Element>
void insertion_sort(Element arr[], size_t size) {
    for (auto index = 1u; index < size; ++index) {
        auto temp = std::move(arr[index]);
        auto index_sorted = index - 1;
        while (arr[index_sorted] > temp) {
            arr[index_sorted + 1] = std::move(arr[index_sorted--]);
        }
        arr[index_sorted + 1] = std::move(temp);
    }
}

Technically, the size of the array could be deduced automatically by taking a reference (though it has an ugly syntax). However, by taking an explicit size parameter one can sort a partial array, so I'd prefer the flexibility of this approach.


A more functional try...catch construct in Java

Thank you for sharing your code and this idea with us! :)

I have just some personal preferences and ideas to some of you "major problems" witch should be additional to the answers of @Mateusz Stefek and @TorbenPutkonen

Not Functional

  public Try<T> catching(Class ex, Function<Exception, T> handler) {
  if(/* ... */) {
    throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
  } else {
    /* ... */
  }
}

In functional programming attempt not to throw any error instead you would return an Either.

  new Try<>(()-> Integer.parseInt("1"))
                      .catching(NumberFormatException.class, (e) -> 2)
                      .execute();

On each method call on Try you modify it, but fp is all about immutability.

Some Refactoring

Naming

  public Try<T> catching(Class ex, Function<Exception, T> handler)

I would write out ex to exception. Than we can change the name of

  private final Map<Class, Function<Exception, T>> handlers

to exceptionByHandler, which makes it easier to read, because it suggests a Map more intuitively, than handler which could be a List.

Null check

We have currently two null checks

  // in execute
if(finallyExpr != null)

// in andFinally
if (finallyExpr == null)

The utility class Objects offers the static methods isNull and nonNull and with an static import it could look like

// in execute
if(nonNull(finallyExpr))

// in andFinally
if (isNull(finallyExpr))

But if we use an Optional in andFinally it could look like

public T andFinally(Runnable newFinallyExpr) {
    finallyExpr = Optional.ofNullable(finallyExpr)
                          .orElseThrow(() -> new IllegalStateException("Cannot have multiple finally expressions"));

    return execute();
}

Non Intuitiv API

  The check in andFinally seems like it's unnecessary. [...]

You already mention this as a flaw.. but from an other perspective. For me as a client it is not intuitive to have the method andFinally and execute to fire up the Try.

More natural would be to let the client call the execute itself and override all finally with the next occurring finally.

new Try<>(()-> Integer.parseInt("f"))
                  .catching(NumberFormatException.class, (e)-> 2)
                  .catching(IllegalStateException.class, (e) -> 3)
                  .andFinally(()-> System.out.println("Finally!"))
                  .andFinally(()-> System.out.println("Finally #2!")) // overrides all previous finally
                  .execute();

Improvement

Make Try immutable

As in functional programming objects are immutable we can do it in Java too. We can let the client modify a Try with methods we provide him and return each time a new Try.

But to build up a Try we can create a TryBuilder witch is mutable. This is a common way which you can find in the Java-World to or example with String and StringBuilder.

State Pattern

  The need for execute when andFinally isn't used. I can't see how the class would know that all catches have been added though.

This is a scenario for the State Pattern. We have our base-state, which allows the client to add multiple catch-cases. After the last catch-case we need to let the client allow only one finally-case. After this our object is in the execution-state.

Builder Pattern

We can mix the State-Pattern with the Builder-Pattern and on each state we can use a builder, which only let use the methods the client currently needs to make the api more intuitive.

Replace the Constructor

  The need for new is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something like Try.tryMethod to reference it, which isn't a whole lot better.

With a static method as constructor we are allowed to return a different reference type.

new Try(/* ... */) // can only return an instance of Try

Try.of(/* ... */)  // can return everything you can imagine

For the use case I have in mind we need to make the constructor private and return a builder that we need to implement.

private Try(/* ... */) { /* ... */ }

public  static <T> CatchBuilder of(Supplier<T> tryExpr) {
    return new CatchBuilder<T>(new TryBuilder<T>().withTryExpr(tryExpr));
}

Example Implementation

Try

The Try is a public class with builds the API to the client. It provides the client outside of the package only a of(Supplier<T> tryExpr) to build up a Try. The constructor is package private therewith TryBuilder can access it. With of(Supplier<T> tryExpr) the clients gets a CatchBuilder (this is the modified State-Pattern mentioned above)

public class Try<T> {

  private Supplier<T> tryExpr;

  private Map<Class, Function<Exception, T>> handlers;

  private Runnable finallyExpr;

  Try(Supplier<T> tryExpr,
      Map<Class, Function<Exception, T>> handlers,
      Runnable finallyExpr) {
    this.tryExpr = tryExpr;
    this.handlers = handlers;
    this.finallyExpr = finallyExpr;
  }

  public static <T> CatchBuilder of(Supplier<T> tryExpr) {
    return new CatchBuilder<T>(new TryBuilder<T>().withTryExpr(tryExpr));
  }

  public T execute() {
    try {
      return tryExpr.get();
    } catch (Exception e) {
      if (handlers.containsKey(e.getClass())) {
        Function<Exception, T> handler = handlers.get(e.getClass());
        return handler.apply(e);
      } else {
        throw e;
      }
    } finally {
      if (finallyExpr != null) {
        finallyExpr.run();
      }
    }
  }
}

TryBuilder

This is the mutable way to build up a Try.

class TryBuilder<T> {

  private Supplier<T> tryExpr;

  private Map<Class, Function<Exception, T>> handlers;

  private Runnable finallyExpr;

  public TryBuilder<T> withTryExpr(Supplier<T> tryExpr) {
    this.tryExpr = tryExpr;
    return this;
  }

  public TryBuilder<T> withHandlers(Map<Class, Function<Exception, T>> handlers) {
    this.handlers = handlers;
    return this;
  }

  public TryBuilder<T> withFinallyExpr(Runnable finallyExpr) {
    this.finallyExpr = finallyExpr;
    return this;
  }

  public Try<T> build() {
    return new Try<>(tryExpr, handlers, finallyExpr);
  }

}

CatchBuilder and FinallyBuilder

class CatchBuilder<T> {

  private final Map<Class, Function<Exception, T>> handlers = new HashMap<>();

  private final TryBuilder<T> tryBuilder;

  CatchBuilder(TryBuilder<T> tryBuilder) {
    this.tryBuilder = tryBuilder;
  }

  public CatchBuilder<T> withCatch(Class ex, Function<Exception, T> handler) {
    if (handlers.containsKey(ex)) {
      throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
    }

    handlers.put(ex, handler);
    return this;
  }

  public FinallyBuilder<T> and(Class ex, Function<Exception, T> handler) {
    withCatch(ex, handler);
    return new FinallyBuilder<>(tryBuilder.withHandlers(handlers));
  }

  public FinallyBuilder<T> onlyCatch(Class ex, Function<Exception, T> handler) {
    return and(ex, handler);
  }

}

class FinallyBuilder<T> {
  private final TryBuilder<T> tryBuilder;

  public FinallyBuilder(TryBuilder<T> tryBuilder) {
    this.tryBuilder = tryBuilder;
  }

  public Try<T> finallyDo(Runnable newFinallyExpr) {
    return tryBuilder.withFinallyExpr(newFinallyExpr)
                     .build();
  }

  public Try<T> withoutFinally() {
    return tryBuilder.build();
  }

}

Exmaple

public static void main(String[] args) {

  Try<Integer> firstTry = Try.of(() -> Integer.parseInt("f"))
                             .withCatch(NumberFormatException.class, (e) -> 2)
                             .and(IllegalStateException.class, (e) -> 3)
                             .finallyDo(() -> System.out.println("Finally!"));

  Try<Integer> secondTry = Try.of(() -> Integer.parseInt("f"))
                              .onlyCatch(NumberFormatException.class, (e) -> 2)
                              .withoutFinally();
}


There's no docstring for the class. What kind of thing does an object belonging to this class represent? The text from your post would make a good start.
There's no docstring for the __init__ method. What do I pass for substream? What does tailcutoff mean? Again, the text from your post would make a good start.
There are no docstrings for the cachedfrom and cachedto methods. What do these return?
The cachedfrom and cachedto methods do not take any arguments. Would it make sense for these to be properties instead of methods?
Attributes like substream and rwbuffer do not appear to be intended to be used outside of the class implementation. It is conventional to give these names starting with _. See PEP8:

  Use one leading underscore only for non-public methods and instance variables.

The idea seems to be to create an object that acts like Python's built-in buffered I/O objects. But it doesn't implement the whole interface — for example, there's no close method, no closed property, and so on.

It would make sense to inherit from the abstract base class io.BufferedIOBase so that you get implementations of all the methods (even if some of them are only stubs).
The number 128*1024 appears in two places without explanation. It should have a name, something like _chunk_size, and it might make sense for it to be a keyword argument to the constructor.
In the seek method I would use the constants io.SEEK_SET and io.SEEK_CUR instead of the numbers 0 and 1. That's because the named constants make the intention clear.
BufferedIOBase.read has this behaviour:

  If the argument is omitted, None, or negative, data is read and returned until EOF is reached.

This behaviour is not implemented by RebufferedBytesIO.read. This kind of incompatibility might prevent someone from being able to pass a RebufferedBytesIO object to a function that was expecting an io.BufferedIOBase object.
RebufferedBytesIO.read raises an exception on a short read:

if len(data) < count:
    raise IOError("could not read enough bytes, something went wrong")

But for BufferedIOBase streams, short reads are possible.
The code for reading more chunks from the substream until the target position is reached is duplicated between the read and write methods. This should be refactored into its own method.
The code for doing the tail cut-off is duplicated between the read and write methods. This should be refactored into its own method.
Cutting off the tail using:

 self.rwbuffer = self.rwbuffer[removed:]

is inefficient. In the worst case this code ends up copying the whole of rwbuffer on each read or write, which would be disastrous for performance.
The logic for reading a single chunk from the underlying stream looks like this:

newdata = self.substream.read(128*1024)
self.rwbuffer += newdata

but the documentation for RawIOBase.read says:

  If the object is in non-blocking mode and no bytes are available, None is returned.

If this happens, the += will fail with TypeError: can't concat bytes to NoneType.
The logic for reading chunks from the underlying stream looks like this:

while self.moved + len(self.rwbuffer) < endsat:
    newdata = self.substream.read(128*1024)
    self.rwbuffer += newdata
    if not newdata:
        sleep(0)

If the underlying stream is blocking, the sleep(0) is not necessary (because the read blocks if there is nothing to return. But if the underlying stream is non-blocking, then:

  A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.

So in neither the blocking case nor the non-blocking case is there any obvious reason to have a sleep here.


Use of Factory pattern — how to implement it

There's no need to pass a string to makeShip. You should instead create 2 methods: makeAlienShip and makeZombieShip. This way as someone working on your code I can let my editor autocomplete and you won't have to write as much documentation.
As per above, having an AbstractShipFactory is an overuse of abstraction. What you could do is instead just make a ShipFactory that makes different types of ships: allied, enemy, neutral, zombie, pirate, alien etc.
Try to use template strings instead. It makes it much more readable especially if you're spitting out long messages. Like so:

return `---->You are being attacked by ${this.name} spaceship and got a damage of ${this.damage}`

Why is attack() responding with the string "You are being attacked by..."? This is extremely awkward and hard to understand: can a ship attack another ship? Or can a ship only attack the player? Maybe you could change the method name to takeDamageFromShip(). Even better would be to make a method attack(ship: Ship)

Think more about the relationships between objects in your program. You defined what a Ship is, but how does it interact with other objects in your program?

If zombie, alien, etc. are meant to be types of a Ship, add a string to your Ship interface instead.
Why are you not using a constructor to instantiate the properties of AlienShip? What if certain ships do more damage than others?


Summing integers in stream using Fenwick tree

Incorrect creation of fenwick tree

Your function create() is both incorrect and slow.  You had the correct function update() but you never used it.  Instead you tried to create the fenwick tree yourself but used an \$O(n^2)\$ algorithm to do so.  The correct way would have been just:

public static void create() {
    for (int i = 1; i <= N; i++) {
        update(i, array[i]);
    }
}

This would have created the fenwick tree in \$O(n \log n)\$ time.

Bug

Another problem you have is when you update the array.  You do correctly update the fenwick tree, but you forgot to update the actual array.  In other words, after this line:

               update(x, y - array[x]);

you need this line:

                array[x] = y;


JavaScript reducer that updates a deep value in a hash

Since you are already using lodash, don't reinvent the wheel! Nearly all of your code can be replaced by a single _.set call.

const Issues = {
  verified_documents: {
    drivers_licence: {
      front_image: ['Image is too blurry', 'Image is too dark']
    }
  }
}

console.log(Issues)
_.set(Issues, 'verified_documents.drivers_licence.front_image', [])
console.log(Issues)
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

With that said, I believe there is merit to reviewing your approach.

Not mutating an object doesn't mean a function is pure. Sure, updateIssue doesn't mutate the Issues object, but it does overwrite it, making this function inherently impure.
Don't use merge to clone an object. Use clone or cloneDeep.
A class with nothing but static functions shouldn't be a class. Just use a plain object, or if you are using a proper module system, don't even bother wrapping functions in an object!
setIssues worries me. When I call a method called setSomething, I expect it to either set, or throw an error. Silently ignoring the call if Issues is already instantiated will probably lead to painful debugging later.
getNestedValue can be replaced with at.
Multiple returns is not necessarily a bad thing. The "single exit" rule is far more important when writing assembly than JavaScript. There's plenty of discussion on this. See this blog, another post, this software engineering question... plenty more to be found with a simple search.
getNestedValue looks like it has a bug, obj[key] !== "undefined" should probably have a typeof in front of it.
Your rewritten function, while cleaner, does not exactly replicate the behavior of your original implementation. If a key that does not exist in the object is specified, the original implementation will set it. The refactored function will throw.


Applying a dataframe function to a pandas groupby object

You can directly use apply on the grouped dataframe and it will be passed the whole group:

def clean_df(df, v_col='value', other_col='other_value'):
    '''This function is just a made up example and might
       get more complex in real life. ;)
    '''
    prev_points = df[v_col].shift(1)
    next_points = df[v_col].shift(-1)
    return df[(prev_points > 50) | (next_points < 20)]

df.groupby('id').apply(clean_df).reset_index(level=0, drop=True)
#    id  other_value  value
# 0   1          2.3     70
# 1   1          3.3     10
# 4   2          5.0     50

Note that I had to give the other arguments default values, since the function that is applied needs to have only one argument. Another way around this is to make a function that returns the function:

def clean_df(v_col, other_col):
    '''This function is just a made up example and might
       get more complex in real life. ;)
    '''
    def wrapper(df):
        prev_points = df[v_col].shift(1)
        next_points = df[v_col].shift(-1)
        return df[(prev_points > 50) | (next_points < 20)]
    return wrapper

Which you can use like this:

df.groupby('id').apply(clean_df('value', 'other_value')).reset_index(level=0, drop=True)

Or you can use functools.partial with your clean_df:

from functools import partial

df.groupby('id') \
  .apply(partial(clean_df, v_col='value', other_col='other_value')) \
  .reset_index(level=0, drop=True)


Welcome to the Haskell community :)
Haskellers like composition. Your logic is composed of 2 parts:
splitWhen :: (a -> Bool) -> [a] -> [[a]]

toTuple :: [[a]] -> ([a], [a])

Let's address splitWhen first.
E.g. splitWhen (== '2') "132342245" should be ["13", "33", "", "45"].
To illustrate how it works:
initial state: (unconsumed input: "132332245", aggregator: [""])
step 1: (current input: '1', unconsumed input: "32342245", aggregator: ["1"])
step 2: (current input: '3', unconsumed input:  "2332245", aggregator: ["13"])
step 3: (current input: '2', unconsumed input:   "332245", aggregator: ["13",""])
step 4: (current input: '3', unconsumed input:    "32245", aggregator: ["13","3"])
step 5: (current input: '3', unconsumed input:     "2245", aggregator: ["13","33"])
step 5: (current input: '2', unconsumed input:      "245", aggregator: ["13","33", ""])
step 6: (current input: '2', unconsumed input:       "45", aggregator: ["13","33", "", ""])
step 7: (current input: '4', unconsumed input:        "5", aggregator: ["13","33", "", "4"])
step 8: (current input: '5', unconsumed input:         "", aggregator: ["13","33", "", "45"])

There are many ways to write this in Haskell, for example if we call the above logic f:
splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p xs = f xs [] -- the initial aggregator
    where f [] agg = [agg]
          f (y : ys) agg = if p y
                           then agg : f ys [] -- we are ignoring the element here
                           else f ys (agg ++ [y]) -- put y into the aggregator

Notice the pattern match (y : ys), they are the current input and unconsumed input.

Notice the recursive function call of f.

toTuple is trivial:
toTuple :: [[a]] -> ([a], [a])
toTuple [] = ([], [])
toTuple [xs] = (xs, [])
toTuple (xs:ys:_) = (xs, ys)

Finally the exiting part - function composition:
splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])
splitAtPredicate p = toTuple . splitWhen p

or if you are not yet comfortable with the pointfree style
splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])
splitAtPredicate p xs = toTuple . splitWhen p xs

Because Haskell's lazy nature, splitAtPredicate will stop when it finds the second element that satisfies the predicate, as we have enough data to construct the pair.
To put everything together:
splitWhen :: (a -> Bool) -> [a] -> [[a]]
splitWhen p xs = f xs [] -- the initial aggregator
    where f [] agg = [agg]
          f (y : ys) agg = if p y
                           then agg : f ys [] -- we are ignoring the element here
                           else f ys (agg ++ [y]) -- put y into the aggregator

toTuple :: [[a]] -> ([a], [a])
toTuple [] = ([], [])
toTuple [xs] = (xs, [])
toTuple (xs:ys:_) = (xs, ys)

splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])
splitAtPredicate p = toTuple . splitWhen p

Hope that helps :) And again welcome to the Haskell world.
If you haven't done it already, checkout https://hoogle.haskell.org , you'll love it :)


I'm not a big algorithms/data structures guy, but the only thing that caught my attention was the delete function. Is there a reason that delete uses data to identify the node, as opposed to just taking in the Node object you want to delete? It seems like that could get hairy if two nodes have the same data (which happens in main).

Besides that, there are a few comments I have in general about the code. Most of the following is fairly standard code format type stuff, but I think it's worth saying it as many times as possible.

Formatting

It's fairly minor, it helps to make sure there's an empty line between methods.

Also, I know some feel differently, but my preference about operators is that they have spaces on either side. data=datanew vs data = datanew.

Naming

In Java, the convention is that class names start with a capital letter, so circularLL should be CircularLL. Even better, it should really be something more descriptive like CircularLinkedList.

Besides that, names of methods, members, variables, etc should follow lowerCamelCase. So, datanew becomes dataNew, but I would personally call it newData.

In delete, avoid variable names like temp1 and previous1. With the number of variables and how they're named, you're starting to enter mental-juggling territory. What I mean by that is that as I read through the code, I have to keep reading back through the code to remember what a variable does because its name isn't descriptive enough.

Etc

I don't have too much else to say, but I would consider breaking this code out into two or three files. I would make a new class with main to separate the linked list from what's using it, and I might put Node in its own class.

Sorry I couldn't help out more with the efficiency/number of variables issue, but you don't seem to be doing anything too crazy, and like I said before, data structures and algorithms aren't my strong suit. Just thought I'd throw in my two cents.


Parallel Task Queue that runs in sequence

This is an interesting approach. I would have used a queue by default since it seems to express the semantics a bit clearer (the queuing is slightly more obvious). Also ContinueWith creates a Task wrapping the original task which I'm not sure if that has any form of performance downsides (it probably shouldn't). I hacked a quick benchmark together with the alternative being implemented using the BlockingCollection:

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

public interface IAppendable
{
    void Append(Action action);
}

public class TaskGroup : IAppendable
{
    public int CurrentlyQueuedTasks { get { return _currentlyQueued; } }

    private readonly object _previousTaskMonitor;
    private Task _previousTask;
    private int _currentlyQueued;

    public TaskGroup()
    {
        _previousTaskMonitor = new object();
        _previousTask = Task.FromResult(false);
    }

    public void Append(Action action)
    {
        lock(_previousTaskMonitor)
        {
            Interlocked.Increment(ref _currentlyQueued);
            _previousTask = _previousTask.ContinueWith(task =>
            {
                try
                {
                    action();
                }catch(Exception)
                {
                    //TODO
                }
                finally
                {
                    Interlocked.Decrement(ref _currentlyQueued);
                }
            });
        }
    }
}

public class QueueAppendable : IAppendable, IDisposable
{
    public int CurrentlyQueuedTasks { get { return _Queue.Count; } }

    BlockingCollection<Action> _Queue = new BlockingCollection<Action>();

    public QueueAppendable()
    {
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                try
                {
                    var action = _Queue.Take();
                    action();
                }
                catch (InvalidOperationException)
                {
                    break;
                }
                catch
                {
                    // TODO log me
                }
            }
        });
    }

    public void Append(Action action)
    {
        _Queue.Add(action);
    }

    public void Dispose()
    {
        _Queue.CompleteAdding();
    }
}

public class Test
{
    public static void TimeIt(string name, IAppendable appendable)
    {
        var finishEvent = new ManualResetEvent(false);
        var sw = new Stopwatch();
        sw.Start();
        for (int i = 0; i < 2000; ++i)
        {
            appendable.Append(() => { Thread.Sleep(1); });
        }
        appendable.Append(() => { finishEvent.Set(); });
        finishEvent.WaitOne();
        sw.Stop();
        Console.WriteLine("{0} elapsed time: {1}ms", name, sw.ElapsedMilliseconds);
        (appendable as IDisposable)?.Dispose();
    }

    public static void Main()
    {
        TimeIt("TaskGroup", new TaskGroup());
        TimeIt("Queue", new QueueAppendable());
    }
}

Output:

TaskGroup elapsed time: 2135ms
Queue elapsed time: 2121ms

So there is pretty much no performance difference between the two however I think the BlockingCollection approach has a few advantages:

Easier to debug. You can simply set a break point and peek the queue. This is quite difficult to do with the wrapped task approach.
No use use of lower level synchronization primitives. The first time I read your code I instinctively thought "Hang he's got a lock why the Interlocked calls" until I realized that the decrement happen in the async task outside of the lock. With the BlockingQueue you program against a slightly higher level of abstraction which is often a good thing.
Fewer class members which reduce the state complexity of the object (the queue is the only member).

Apart from that I think your approach should be fine. You may want to consider adding support for cancellation via CancellationToken


Entity Framework Lazy loading performance comparison

1) Not sure if it impacts performance, but your first code fragment has one redunant order by:

.OrderByDescending(t => t.RunID).ThenByDescending(t => t.RunID)

2) You could improve performance of your seconds code with "client side indexing" (using a dictionary):

var tasksMap = tasks.ToDictionary(t => t.TaskID);
var jobsMap = jobs.ToDictionary(t => t.JobID);

foreach (var r in result)
{
    var task = tasksMap[r.TaskID];
    r.TaskDescription = task.TaskDescription;
    r.TaskType = (TaskType)task.TaskTypeID;
    r.JobName = jobsMap[r.JobID].JobName;
}


Retrying a request using 'request' library without extra modules

It's not "excessive" (your term) to use a pre-made module that does what you want. In fact, if it's solid code, then it's smart to use something that's already written and tested and maintained by someone else. There's little cost on a server to using a small module that does what you want.

I didn't do an exhaustive search, but I came across requestretry on NPM that seems to be pretty much what you might want (there are several other similar options on NPM too).  Using it, reduces your code to this:

const requestRetry = require('requestretry');

function checkUrl(url = 'http://localhost', retriesLeft = 0, timeoutMS = 3000) {
    return requestRetry({url: url, maxAttempts: retriesLeft + 1, retryDelay: timeoutMS});
}

checkUrl('http://www.example.com/', 3, 5000).then(data => {
    console.log(data);
}).catch(err => {
    console.log(err);
});

This particular library even has ways for you to plug in your own retry strategy or delay strategy (if, for example, you wanted to implement a back-off strategy to the retries so the retry interval gets longer after more failures which is sometimes desirable).


Removing punctuation and lowercasing a string

Instead of just import string you could get the punctuation list directly:

from string import punctuation

words = "Dave, Laura, Maddy, Dave, Laura, Maddy, Dave, Laura, Dave"
translation = str.maketrans("", "", punctuation)

I'd also remove the semicolons. Python doesn't need them to know when a line of code ends since it uses newlines instead (there are exceptions, but none here) so you can remove them.


You can use try except IOError on with the same way you did for open.

def getLinesFromFile(filename):
    content = []

    try:
        with open(filename, "r+") as file:
            for line in file:
                line = line.rstrip()
                if line:
                    content.append(line)
    except IOError:
        print "[ERR] File does not exist"

    return content

Using with is a good idea, but I'm not sure if you understood what it does. with automatically ensures that a file is always closed safely. So even if the script encounters an error then you'll close it. This means that you only need to catch an error if the file doesn't exist, which is why we use except IOError like this.

There are other notes too. In Python it's recommended that you use snake_case, not camelCase like in java. So you should call your function get_lines_from_file.

There's no need to use "r+", that's for reading and writing a file, but you only read it. Instead you could use 'r' but since that's the default you can just leave out the mode argument and do open(filename).

Don't use the name file, as that's shadowing Python's built in file constucting function. Python allows you to use a lot of the built in method's names in case you want to overwrite them, but it's best not to unless it's necessary. Using f is fine in such a small function.

You can also build your list easier with something called a list comprehension. List comprehensions are like for loops collapsed into a single expression that results in a list. In your case, you first need to get every line from the list and rstrip it, so that'd look like this:

content = [line.rstrip() for line in f]

However you also want to ignore empty lines, so you'll want to add an if condition at the end:

content = [line.rstrip() for line in f if line.rstrip()]

Now, you don't even need to actually store this as content. You can return it directly instead. Though, doing this means that you should manually return an empty list when the IOError is raised, otherwise Python will default to returning None. (It might be better to return None in the case of an error, but that depends on how you're using this)

Lastly, add a docstring to explain what the function does. They're a similar idea to javadocs but less structured and formal. Here's how I'd write the function:

def get_lines_from_file(filename):
    """Return a list of rstripped lines from filename

    Returns an empty list if the file doesn't exist."""

    try:
        with open(filename) as f:
            return [line.rstrip() for line in f if line.rstrip()]
    except IOError:
        print "[ERR] File does not exist"
        return []


Check whether an array can be the result of merging two smaller arrays, maintaining order

I placed the if condition for checking lengths at the top even before the index definitions because I figured that if they aren't even the same size, why bother with doing anything else. Is that weird?

No I don't think that is weird. I would consider it a good optimization.

Personally I think the code is mostly fine, a good starting point would be to Google some examples on how to merge sub-arrays since that is fairly similar.

My one question would be why you started at the end of the array and merged them in descending order. That is kind of strange to me. I would do it in ascending order. I would also use a for loop instead of a while loop.