Replacing accented letters with regular letters in a spreadsheet

In addition to @Raystafarian's observations, there are a couple of other issues that I see.

I would personally put your AccChars and RegChars variables into
Consts, because you never change their values.
Your code also requires that AccChars and RegChars are the same
length, and will fail if they aren't.  I'd add an assert that tests
that before you do anything that writes to the Worksheet.
You generally want to avoid using the Integer type unless you
absolutely need to (for example in an API call). VBA stores them as a
Long regardless of how they are declared.
Declaring A and B as fixed-length strings is a bit of premature
optimization that is backfiring. When you pass them to .Replace as
parameters, they are actually being implicitly cast back to
variable length ones.
Minor thing, but I prefer the term "stripped" to "regular" - all
characters are "regular" in their native context.
Using string functions is not ideal when what you really care about
are individual characters as opposed to a sub-string.  VBA allows a
direct assignment of a String to a Byte array, and indexing into
the array is much faster than calling Mid. The performance hit is a
lot higher when you're doing it inside a loop. As a side note, you
should always use the String returning functions that end with '$'
to avoid superfluous casting unless you explicitly require a
Variant type. Mid$ (returns a String) as opposed to Mid
(returns a Variant).
Your call to .Replace method is acting on every single cell in your
Range. This is a huge performance hit, because I'm guessing that
not every cell in the entire Worksheet is going to have an accented
character in it. You should really only be concerned with cells that
do. By performing the replacement on every cell, your performance is scaling directly with the number of cells, not the number of
replacements. So, if only 5% of the cells have accented characters
you are still doing 100% of the work. This is where the regular
expression would be useful, but you can't easily pawn that off on
Excel (except maybe with using .Find, which has issues of its own).
A loop would be better - a loop over an array pulled from the Range
would be best.
Your "TODO: highlight changed cells yellow" is going to be much more
difficult using the .Replace function, because it would require
storing the state of the entire sheet, then doing a cell-by-cell
comparison. It will be a lot easier to track this concurrently while
you are making changes.

With all of that in mind, I'd do something more like this:

Private Sub RemoveAccentsFromForeignLetters()
    Dim Target As Range
    Set Target = ActiveSheet.UsedRange

    StartNewTask ("Removing accents from foreign letters")

    Dim Values() As Variant
    Values = Target.Value

    Debug.Assert Len(AccentedChars) = Len(StrippedChars)

    Dim FindChars() As Byte
    Dim ReplaceChars() As Byte
    FindChars = AccentedChars
    ReplaceChars = StrippedChars

    Dim AccentedTest As RegExp
    Set AccentedTest = New RegExp
    AccentedTest.Pattern = "[" & AccentedChars & "]"

    Dim index As Long
    Dim character As Long

    Dim col As Long
    Dim row As Long
    For row = 1 To UBound(Values, 1)
        For col = 1 To UBound(Values, 2)
            'Ignore strings that don't require character replacements.
            If AccentedTest.Test(Values(row, col)) Then
                Dim buffer() As Byte
                buffer = StrConv(Values(row, col), vbUnicode)
                'Skip every other character - VBA "Unicode" expansion
                'inserts nulls there.
                For character = 0 To UBound(buffer) Step 2
                    For index = 0 To UBound(FindChars)
                        If buffer(character) = FindChars(index) Then
                            buffer(character) = ReplaceChars(index)
                        End If
                    Next index
                Next character
                'Highlight changed cells yellow left as an exercise for
                'the reader.
                Values(row, col) = StrConv(buffer, vbFromUnicode)
            End If
        Next col
    Next row

    ActiveSheet.UsedRange = Values
End Sub

Some quick and dirty benchmarks, all done with 2000 rows and 10 columns.  In the "worse case" benchmarks, all cells have the value "ŸÀÁÂÃÄÅÇÈÉÊËÌÍÎ".  In the "average case" benchmarks, 5% of the cells have the "ŸÀÁÂÃÄÅÇÈÉÊËÌÍÎ" and the rest of them contain "XXXXXXXXXXXXXXX".

Replace method, worst case: 3.51 seconds.
Array method, worst case: 1.15 seconds.
Replace method, average case: .40 seconds (supports disabling ScreenUpdating).
Array method, average case: .08 seconds.


def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)

Why store the neighbor in the list? Instead of putting it in a list, just combine your two loops.

for i in nodes:

i typically stands for index. I suggest using neighbor to make your code easier to follow

    if depth+1 > maxdepth:
        return False

This doesn't relate to this individual node.  What is it doing inside this loop?

        if search(graph, i, maxdepth, depth+1):
            return i
   return False

Failure to find is better reported using None rather than False.


I haven't done much work in C#, but from a general coding perspective...

class Main
{
    static void Main(string[] args)
    {
        // lotsa stuff....
    }
}

These (the class and method both) really ought to be public, as I believe that most application runners/executables will be looking for public methods.  Additionally, a Main() method should be mostly empty, containing just enough code to launch the rest of the application (whether this submits an additional process or not).

 Console.WriteLine()  // Many times

Ideally, never call out to the console specifically.  What you should be doing is injecting some sort of output/input stream.  It's fine if these actually come from the console, but explicitly tying it to the console itself is frowned upon.

Console.WriteLine("1. New Game\n" +
                  "2. Load Game\n" +
                  "3. Exit Game\n");

So... you're using WriteLine() to write multiple lines at a time?  Seems a little counter-intuitive.  I'm slightly torn between recommending using individual calls (and potentially having output re-ordered because of some threading issue), or just using Write()...

while (correctChoice == false)
{
    // stuff
}

Using booleans like this is frowned upon; don't compare the boolean with a value, use the boolean itself (that's what it's for) - so, it should be while (!correctChoice) { ... }.  Additionally, the name is somewhat ambiguous: possibly availableOptionChosen?

switch (choice)
{
    // lotsa stuff
}

Look into something called the Strategy Pattern.  While the use of a switch works out for simple things, software patterns are something to always keep in mind.

case "2":
    Console.WriteLine("This feature is not yet implemented.");
    correctChoice = false;
    break;

Strictly speaking, correctChoice = false; shouldn't be necessary.

case "3":
    Environment.Exit(0);
    break;

Using Environment.Exic(0); should end the running thread.  However (if this is anything like Java's System.Exit()) this may have unintended consequences.  It would be much better to simply return to the next level.

default:
    Console.WriteLine("Please enter a correct value.");
    break;

You check the 'remaining' cases.  Good; generally speaking, you should always do so, even if it's impossible (some of those should maybe only be 'asserts', used for verification-time checks).

        Console.ReadLine();
    }
}

You read a line immediately before the program exits.  Why?

class CharacterCreation
{

     // Lotsa stuff
}

This is semantically a Builder-pattern, so the class name is a little odd - perhaps CharacterCreator?

public static void createChar(Hero newHero)
{
    // Stuff
}

Why the abbreviation of 'Character' (and why all the abbreviations, generally)?  Also, if it's named 'create...', you shouldn't be passing it in - it should be the return type (alternatively, call it setupCharacter(), and pass in the Hero). Additionally, newHero is an awkward name here - just use hero (you don't have an `oldHero you're using, do you?).

while (correctChoice == false)
{
    switch (classChoice)
    {

The stuff I mentioned about your main loop applies here as well.  This is especially prevalent with the class, if you're eventually going for something like DnD (which can have hundreds of classes).

class Character
{
    public int charHealth, charMaxHealth, charStr, charInt, charAgi;
}

Always put member definitions on their own lines.  Always make them private, and provide equivalent public properties.  Don't abbreviate unnecessarily, seek to be understandable.  Don't prefix variable names with their enclosing class' name (especially abbreviated) - it's noise.

class Hero : Character
{
     // Acceptable
}

This works, although it may become awkward in the future.

public static void ClassSelect(Hero newHero)
{
    newHero.charAgi = 10;
    newHero.charInt = 10;
    newHero.charMaxHealth = 100;
    newHero.experience = 0;
    newHero.gold = 0;
    newHero.level = 1;

    switch (newHero.heroClass)
    {
        case "Warrior":
            newHero.charMaxHealth = newHero.charMaxHealth * 115 / 100;
            newHero.charStr = newHero.charStr * 12 / 100;
            break;
        case "Mage":
            newHero.charInt = newHero.charInt * 12 / 100;
            break;
        case "Rogue":
            newHero.charAgi = newHero.charAgi * 12 / 100;
            break;
    }
    newHero.charHealth = newHero.charMaxHealth;
}

This, though, belongs in CharacterCreation (that's what it's there for).  Additionally, instead of

newHero.charXxx = newHero.charXxx * 12 / 100;

you should probably just be setting it to the desired value.  Especially because that's probably a bug, since a warrior will start out with a higher Int (10) than a mage

((10 * 12) / 100) = 120 / 100 = 1.2 -> 1

which I doubt is what you want.


Improve the for loop

The loadMap method is really hard to read, and is not verry efficient:

Currently, if a file doesn't exists, here are the steps followed by the method:

try to read the content of a file to see if it exists
send a request to google map, and write the response to a file
read the content of the new file

but we could merge just return the response instead of reading the file twice !
Also, it would be better to have a map for keeping records of saved map.
To do this, we create a server that implement the ServerHTTP method:

  type server struct {
    mux        *http.ServeMux
    fetchedMap map[string]string
  }

  func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
      s.mux.ServeHTTP(w, r)
  }

Now, let's rewritte the loadMap method:

  func (s *server) loadMap(address string, title string) ([]byte, error) {

    if filename, ok := s.fetchedMap[title]; ok {
        return ioutil.ReadFile(filename)
    }
    mapHost := "http://maps.googleapis.com/maps/api/staticmap"

    v := url.Values{}
    v.Add("center", address)
    v.Add("zoom", "15")
    v.Add("scale", "2")
    v.Add("size", "400x350")
    v.Add("markers", address)
    v.Add("sensor", "false")
    v.Add("key", apiKey)
    mapURL := mapHost + "?" + v.Encode()

    fmt.Println("Getting map for " + address + " and saving it to " + filename)
    fmt.Println("Map URL: " + mapURL)
    httpClientGetMap, _ := http.Get(mapURL)
    body, _ := ioutil.ReadAll(httpClientGetMap.Body)
    ioutil.WriteFile(filename, []byte(body), 0600)
    return body, nil
  }

The steps are now:

check if requested address has already been fetched, and if yes, return file content
if no fetch map from google map and write it to a file
return the map

General advices

use constant for mapHost and other constant parameters
use fmt.Printf("%v", str) instead of fmt.Println(" " + str) because it's easier to read
Always check the error ! Silently discarding errors is really dangerous
avoid useless conversion: body is already a slice of byte

Here is the new version of the code:

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "os"
)

var apiKey = os.Getenv("API_KEY")

const (
    baseURL = "http://maps.googleapis.com/maps/api/staticmap"
    zoom    = "15"
    scale   = "2"
    size    = "400x350"
)

func (s *server) loadMap(address string, title string) ([]byte, error) {

    if filename, ok := s.fetchedMap[title]; ok {
        return ioutil.ReadFile(filename)
    }
    v := url.Values{
        "center":  {address},
        "zoom":    {zoom},
        "scale":   {scale},
        "size":    {size},
        "markers": {address},
        "sensor":  {"false"},
        "key":     {apiKey},
    }
    mapURL := baseURL + "?" + v.Encode()
    filename := title + ".png"

    fmt.Printf("Getting map for adress %s and saving it to %s\nMap URL: %s\n", address, filename, mapURL)

    httpClientGetMap, err := http.Get(mapURL)
    if err != nil {
        return nil, err
    }
    body, err := ioutil.ReadAll(httpClientGetMap.Body)
    if err != nil {
        return nil, err
    }
    err = ioutil.WriteFile(filename, body, 0600)
    if err != nil {
        return nil, err
    }
    s.fetchedMap[title] = filename
    return body, nil
}

func (s *server) viewHandler(w http.ResponseWriter, r *http.Request) {

    address := r.URL.Query().Get("address")

    checksum := md5.Sum([]byte(address))
    title := hex.EncodeToString(checksum[:])
    mapByte, err := s.loadMap(address, title)
    if err != nil {
        fmt.Println(err)
        w.WriteHeader(http.StatusGatewayTimeout)
        return
    }
    w.Header().Set("content-type", "image/png")
    w.Write(mapByte)
}

type server struct {
    mux        *http.ServeMux
    fetchedMap map[string]string
}

func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    s.mux.ServeHTTP(w, r)
}

func main() {

    s := &server{
        mux:        http.DefaultServeMux,
        fetchedMap: map[string]string{},
    }
    s.mux.HandleFunc("/getmap", s.viewHandler)
    http.ListenAndServe(":8080", s)
}


You can see your implementation is wrong by examining the simplest case, a pattern P consisted of a repeated single character: "AAAAA". At every point of the failure function, the length of the largest proper prefix of P which is also a proper suffix of P is ever-increasing: [-1, 0, 1, 2, 3] - however your implementation computes [-1, -1, -1, -1, -1].

Translating the pseudocode in the Wikipedia entry into Python gives us:

def kmp_table(pattern):
    if len(pattern) == 0:
        return None

    ff = [0] * len(pattern) # FF for failure function
    ff[0] = -1
    pos = 2
    cnd = 0

    while pos < len(pattern):
        if pattern[pos - 1] == pattern[cnd]:
            cnd += 1
            ff[pos] = cnd
            pos += 1
        elif cnd > 0:
            cnd = ff[cnd]
        else:
            ff[pos] = 0
            pos += 1

    return ff


Wiki Link Mapper — A webcrawler which crawls links recursively and prints them into a graph

Wikipedia contains circular references. Currently you follow them around until your max depth is reached. Instead, keep a set of all sites visited so far.

You also don't need this function to be recursive, you can make it iterative like this:

from collections import deque

def build_link_graph(start, max_pages=10):
    queue = deque([start])
    visited = set()
    i = 0
    while queue and i < max_pages:
        next_url = queue.popleft()
        urls = get_links(next_url)
        i += 1
        # make sure not to visit any page twice
        queue.extend(url for url in urls if url not in visited)
        visited.update(urls)
        yield next_url, urls

The actual parsing can also be simplified using the CSS selector p > a, meaning all a tags which are contained in a p tag. I would also use a requests.Session to keep the connection alive and use the lxml parser, both of which slightly speed up the scraping.

def filter_links(links):
    blacklist = ['#cite', '/wiki/Help', '/wiki///en:', '/wiki/Wikipedia']
    return [link for link in links
            if not any(link.startswith(prefix) for prefix in blacklist)]

def get_links(url):
    page = SESSION.get(url)
    soup = BeautifulSoup(page.text, "lxml")
    links = [a["href"]
             for a in soup.select("p > a")
             if "selflink" not in a.get("class", [])]
    return [BASE_URL + link for link in filter_links(links)]

With these functions, building the graph is rather easy. Note that you might want to choose a directed graph, since links are usually unidirectional. Also, networkx automatically adds missing nodes when adding edges, so no need to do that.

import sys

if __name__ == "__main__":
    BASE_URL = "'https://en.wikipedia.org'"
    if len(sys.argv) == 2:
        start = sys.argv[1]
    else:
        start = BASE_URL + '/wiki/Earthquake_engineering'
    SESSION = requests.Session()
    g = nx.DiGraph()
    for url, urls in build_link_graph(start):
        graph.add_edges_from((url, link) for link in urls)

I added a if __name__ == "__main__": guard to allow importing from this script from another script without running the scraping

Note that if you increase max_pages too much, you will run into a too many requests.response. Currently there is no code to handle that, but you might add some. The easiest way is to just time.sleep some time and try again afterwards. There are also other ways, some of which may not be in compliance with Wikipedia's ToS:

# robots.txt for Wikipedia and friends
# Please note: There are a lot of pages on this site, and there are
# some misbehaved spiders out there that go _way_ too fast. If you're
# irresponsible, your access to the site may be blocked.

There may be other ways to build this graph than scraping. Wikipedia supplies databases to download which should contain everything you need: https://en.wikipedia.org/wiki/Wikipedia:Database_download Note that it is 58 GB when uncompressed, though.


Using a Function to emulate F# Match in C#

To be honest, it's pretty much impossible to do elegant pattern matching in a language that doesn't support it (e.g., C#).  The problem with what you've written there is it's more complicated than the equivalent if-then-else chain:

if (IsCloudy(skyImage)) {
    ChangeWeatherIcon(Icons.Clouds);
    return 13;
}
if (a < b) {
    throw new Exception();
}

Now, I would dearly love to see some later version of C# adopt algebraic data types (a la F#) with pattern matching, but until then I very much doubt you'll be able to do better than if-then-else chains.


A straightforward method for computing the Binomial probability mass function

High powers of small-magnitude numbers tend toward zero.  When you get subnormal floating-point numbers, then there's a heavy speed penalty; this point is reached sooner with double than with long double (and reached even sooner still using float).

A simple way to improve the speed may be to disable subnormals for this function - e.g. compile with g++ -ffast-math to push subnormal numbers to zero.


You should have HashMap<K, Set<V>>, not ConcurrentHashMap<K, ConcurrentHashMap<V, Object>>.


The stocks problem - find the biggest profit that can be made

This implementation is very inefficient due to creating a lot of arrays. Even worse is that the arrays are of type Integer[] instead of int[] which would be lighter.

A much simpler algorithm is possible:

iterate over the prices
keep track of the max difference seen so far, and the local minimum and maximum
if the current price is bigger than the local max

update the local max
if the difference from the local minimum is bigger than the max difference seen so far, then update the max difference = the best time to sell so far

if the current price is less than the local minimum then reset the local min and max
the maximum profit is the maximum difference at the end of the iteration

It's nice that you added some test cases, but it would be a lot better to turn those into proper junit test cases.

You missed some interesting corner cases:

decreasing sequence, for example: 5, 1
degenerate input: empty array or single element

Negative values as stock prices in the test cases seem strange and a bit confusing.

"stocks" is a poor name for a function that returns an integer. Plural names imply some sort of collection. The number returned is the maximum profit you can make. So for example calculateMaxProfits would be more appropriate.

Suggested implementation

Applying the suggestions above,
here's a solution that's \$O(n)\$ time and \$O(1)\$ space.

public int maxProfit(int[] prices) {
    if (prices.length < 1) {
        return 0;
    }

    int maxDiff = 0;
    int localMin = prices[0];
    int localMax = localMin;

    for (int price : prices) {
        if (price > localMax) {
            localMax = price;
            int localDiff = localMax - localMin;
            if (localDiff > maxDiff) {
                maxDiff = localDiff;
            }
        } else if (price < localMin) {
            localMin = localMax = price;
        }
    }

    return maxDiff;
}


Take a look at html/template package from standard library. It will help you a lot in separating parsing code and HTML generation. Also it will escape all input by default.

Some other notes:

It is handy to use ` instead of " when writing regular expressions with lots of escapes.
GPRegex variable will be exported. Should it be?
Kudos for using bytes.Buffer and not concating strings by hand (:


The maximum sum of squares-of-digits of an \$n\$-digit number is \$n\cdot9\cdot9 = n\cdot81\$.  The number of digits in a number \$B\$ is \$\lceil\log_{10}(B)\rceil\$.

Since you only need to sieve to the square root of the number you're testing for primality, you only need to run your sieve from \$3\$ to \$\sqrt{\lceil \log_{10}(B)\rceil\cdot81}\$.  Even for \$B\$ = 1 billion, this means the max you need to sieve to is \$28\$.

So, run the sieve once, and simply cache the results.

Also, if you wanted to be really cool, you could probably get some minor speed-ups by not calculating the sums-of-digits, and looping over them instead.

What I mean by that is this:  notice that the sum of digits of \$32x\$ (where \$x\$ is any digit - read that as "three hundred and twenty-\$x\$") is always going to be \$3 + 2 + x\$, and the sum-of-squares will always be \$9 + 4 + x^2\$.  Thus, instead of looping from \$320\$ to \$329\$ and calculating the sum-of-digits and sum-of-square-of-digits every time, you could just loop from \$x = 0\$ to \$x = 9\$, and check \$3+2+x\$ and \$9+4+x^2\$ for primality.

Using a bit of recursion, you could loop over all values of all digits.


Variadic Functions in NASM Win64 Assembly

mov     qword [rsp+8H], rdx

Why would you store this value at all? You never use the stored value afterwards!

You can easily dismiss all of the local storage for the sum routine. No need for sub rsp, 24 nor add rsp, 24 instructions. Also, why 24 bytes when all you use are the middle 8 bytes? The same happens in main where you reserve 40 bytes when all you use are the middle 24 bytes! The alternative main evens wastes 24 bytes this way.

You can avoid the separate .end code by clearing the accumulator very early and jumping to the one RET you really need.

lea     eax, [rcx-1H]
lea     rcx, [rsp+rax*8+30H]

You can calculate this upper limit in just one instruction. Absorb the decrement by 1 operation into the displacement of the LEA:

lea     rcx, [rsp + rcx*8 + 28h]

And since by the time of this calculation the RDX register already points at [rsp + 28h] you could simply write:

lea     rcx, [rdx + rcx*8]

Applying these changes:

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
    mov     [rsp + 10h], rdx    ; 1st arg for sure (ECX=1+)
    mov     [rsp + 18h], r8     ; maybe 2nd arg
    mov     [rsp + 20h], r9     ; maybe 3rd arg
    lea     rdx, [rsp + 10h]    ; lower limit
    lea     rcx, [rdx + rcx*8]  ; upper limit
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    cmp     rdx, rcx
    jb      .more
.end:
    ret

When comparing memory addresses like in your code cmp rdx, rcx, it would be best to not check for equality but rather for excess. Provided the step is non-zero, checking for the 'below' condition will happen eventually while checking for the 'equal' condition might never happen at all (if there's an error in the program of course...).

An even simpler solution uses the ECX register as a counter (like it was on input):

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
    mov     [rsp + 10h], rdx    ; 1st arg for sure (ECX=1+)
    mov     [rsp + 18h], r8     ; maybe 2nd arg
    mov     [rsp + 20h], r9     ; maybe 3rd arg
    lea     rdx, [rsp + 10h]    ; lower limit
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    sub     ecx, 1
    jnz     .more
.end:
    ret

  We can change how many variables are being given to the function without having to change the amount of memory being allocated to the function itself.

True, but the caller still has to reserve - somewhat mysteriously - those 24 bytes that correspond to the 3 arguments passed via registers EDX, R8D, and R9D.
I think it would be simpler to either pass all values on the stack or pass a pointer (in RDX) to a buffer holding all of those values. In both cases the count remains in ECX.
Next code combines it all:

    sub     rsp, 48
    mov     rdx, rsp
    mov     dword [rdx + 40], 6
    mov     dword [rdx + 32], 5
    mov     dword [rdx + 24], 4
    mov     dword [rdx + 16], 3
    mov     dword [rdx + 8], 2
    mov     dword [rdx], 1
    mov     ecx, 6
    call    sum
    ...

sum:
    xor     eax, eax
    test    ecx, ecx
    jle     .end
.more:
    add     eax, dword [rdx]
    add     rdx, 8
    sub     ecx, 1
    jnz     .more
.end:
    ret


I recently heard about Laravel 8 changing the way routing was declared, as this video explains that developers upgrading from Laravel 7 or earlier will need to either switch to using the PHP callable syntax or fully namespace the controller in the string syntax (as your first code snippet does) (see the section Routing under Upgrading To 8.0 From 7.x).
Yes adding that use statement at the top then you should be able to reference the class without the namespace before it.
You can use the ::class keyword for name resolution instead of using a string literal:
'uses' =>  [CrewAPIController::class, 'Update'],

Many populate IDEs will index the class names and allow you to then easily jump to the class definition -e.g. ctrl/command + click on name).

I also wasn't familiar with the 'as' syntax, then I found this comment on this accepted SO answer to What does “as” keyword mean in Laravel routing?

As keyword is in older version, if you change the documentation to 5.2 you can see the as keyword. In newer version it's ->name

So you could use the name() method to make the Named route instead:
Route::post('/update-crew', [CrewAPIController::class, 'Update'])
    ->name('apiUpdateCrew');


Printing all the prime numbers between two bounds

When using trial division to test a number n for primality, the highest potential divisor that needs to be checked is floor(sqrt(n)). The first number that must not be checked is n itself, because that would result in a false verdict of non-primality (seeing that every number is divisible by itself). But that is precisely what happens for the code posted by user5486241 in the case n == 2:

for (int i = 2; i < std::sqrt(n)+1; ++i)
   if (n % i == 0)
      return false;

Recomputing the square root during each iteration carries a heavy runtime cost, though, unless the compiler is able to quietly correct this programming mistake. This requires the compiler to prove that the expression std::sqrt(n) is loop-invariant, which in turn requires it to prove or know that std::sqrt() is idempotent (free of observable side-effects).

The point about only scanning up to the square root is valid and important, though. Scanning up to n instead of sqrt(n) leads to an exponential increase in runtime, which is why the OP's original code is not included in the benchmarks. These benchmarks show the performance of user5486241's code (shown as 'v0') vs. the following cleaned-up version 'v1':

typedef std::uint32_t num_t;

bool v1::is_prime (num_t n)
{
   if (n < 2)
      return false;

   for (num_t i = 2, sqrt_n = num_t(std::sqrt(n)); i <= sqrt_n; ++i)
      if (n % i == 0)
         return false;

   return true;
}

The num_t typedef has no deeper purpose here, I introduced it only to facilitate experimentation without turning everything into a template (and making it thus unreadable).

The benchmarks show the time in milliseconds for scanning a maximum-width range according to the tasks SPOJ PRIME1 (n - m <= 100,000, n <= 1,000,000,000, timeout 6 s) and SPOJ PRINT (n - m <= 1,000,000, n <= INT32_MAX, timeout 1.223 s) respectively.

The first column shows the value for n, which is the upper end of the range and in the first row it is also equal to the constant n - m. The variants v2 through v6 are explained later.

*** BC++ 5.5.1 (free) 32 ***

PRIME1 10^5    v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
    100000     75     11      5      4      4      3      1      9592
   1000000    253     33     16     11     11      7      1      7224
  10000000    667     84     40     27     27     13      1      6134
 100000000   1813    228    107     73     71     30      1      5454
1000000000   4964    624    291    196    191     69      1      4832

PRINT 10^6     v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
   1000000   1834    236    114     80     79     55      6     78498
  10000000   6519    798    386    267    264    134      7     62090
 100000000  17948   2237   1083    719    709    291      6     54332
1000000000  49234   6093   2863   1955   1890    693      6     47957
2147483647  69528   8749   4078   2741   2624    939      7     46603

With bcc64 the overhead of v0 is less pronounced than with bcc32, because the 64-bit compiler can inline the square root computation with three XMM instructions instead of having to call a library function. The timings for variants v1 through v6 are noticeably worse, though (showing only the last line):

*** BC++ 7.10 (RX/Seattle) 64 *** CLANG 3.3.1 (35465.f352ad3.17344af)

2147483647  20007   9512   4781   3373   3195   1710     22     46603

Now, gcc and VC++ as examples for highly optimising compilers that can quietly correct programming mistakes. Their timings - regardless of bitness - are exactly the same, within the limits of jitter.

*** g++ 4.8.1 32 *** on MAGNUM (3.0 GHz Haswell)

PRIME1 10^5    v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
    100000     10     10      5      4      3      3      0      9592
   1000000     31     31     16     11      9      7      0      7224
  10000000     82     82     41     27     24     14      0      6134
 100000000    216    219    110     73     64     31      1      5454
1000000000    580    580    293    195    170     71      1      4832

PRINT 10^6     v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
   1000000    226    222    113     77     68     52      5     78498
  10000000    781    780    391    263    228    133      5     62090
 100000000   2104   2128   1065    706    608    294      5     54332
1000000000   5761   5824   2935   1942   1685    706      6     47957
2147483647   8221   8162   4108   2743   2379    952      6     46603

v0 ... user5486241's code
v1 ... sqrt computation hoisted out of the loop
v2 ... skipping multiples of 2
v3 ... skipping multiples of 2 and 3
v4 ... skipping multiples of 2, 3 and 5
v5 ... trial-dividing only by primes (SoE for the factors)
v6 ... simple windowed Sieve of Eratosthenes

Comparing the timings for v0 and v1 shows clearly that these two compilers managed to hoist the square root computation out of the loop all by themselves.

All these timings were taken on a 3 GHz Haswell laptop. The gcc32 timings are for a P4 build - no advanced instructions - so that I could run the same executable on a 2.8 GHz Northwood (P4), which is the kind of iron that SPOJ ran on when the limits for PRIME1 and PRINT were set:

*** g++ 4.8.1 32 *** on HELIOS (2.8 GHz Northwood)

PRIME1 10^5    v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
1000000000   2378   2324   1165    778    625    266      2      4832

PRINT 10^6     v0     v1     v2     v3     v4     v5     v6   #primes
---------------------------------------------------------------------
2147483647  32806  32679  16344  10933   8800   3549    107     46603

It can be clearly seen that division instructions are about four times as fast on current machines compared to back when the tests limits were set, since v0 through v5 are essentially limited by division performance. The sieve code (v6) profits even more from the many improvements in current processors, across the board from memory system performance to superscalar out-of-order execution.

The performance of simple, division-based primality tests is interesting because they are a perfectly adequate solution for many applications where the superior bulk performance of sieves is not necessary. Euler problem #35 (circular primes) comes to mind, where only 5460 candidates need to be checked for covering the range up to 1,000,000. The advantage of the division-based code - besides its simplicity - is that it does not need auxiliary structures like factor sieves.

One simple improvement is to skip the number 2 and its multiples, which immediately doubles performance:

bool v2::is_prime (num_t n)
{
   if (n <= 2)
      return n == 2;

   if ((n & 1) == 0)
      return false;

   num_t sqrt_n = num_t(std::sqrt(n));

   for (num_t i = 3; i <= sqrt_n; i += 2)
      if (n % i == 0)
         return false;

   return true;
}

The performance is actually slightly more than doubled because multiples of 2 get rejected faster now: before the call to sqrt() and before the loop is set up, and without requiring a division. This code already shows the complications necessary for wheel-based operations:
o special handling of the wheel primes before operations commence
o special handling for the multiples of the wheel primes
o special rules for striding through the search space, so that wheel prime multiples are skipped

Skipping the remaining multiples of 3 cuts the workload by another third. I'm showing it here because it makes the approach behind v4 easier to understand:

bool v3::is_prime (num_t n)
{
   if (n < 4)
      return n == 2 || n == 3;

   if ((n & 1) == 0 || n % 3 == 0)
      return false;

   num_t sqrt_n = num_t(std::sqrt(n));

   for (num_t i = 5, d = 2; i <= sqrt_n; i += d, d ^= 6)
      if (n % i == 0)
         return false;

   return true;
}

The step sequence for avoiding multiples of 3 as well as multiples of 2 is 2, 4, 2, 4... (when starting at 5) which I produce here with a simple xor cheat.

The step sequence gets longer when 5 is added to the wheel; it has 8 steps which are 4, 2, 4, 2, 4, 6, 2, 6 (when starting at 7). In other words, the mod 30 wheel has 8 prime-bearing spokes and numbers above are the distances between non-dud spokes when the wheel is currently positioned at 7. I couldn't find an elegant way of creating the sequence with a few arithmetic operations, so I simply stuffed it into the nibbles of a 32-bit word that gets rotated as the algorithm chugs along. For compatibility I did the rotation with a workaround instead of a non-standard compiler intrinsic or library function. This hurts performance a bit (increasing the instruction count from one to three, with attendant increase in register pressure), which is why the performance increase is slightly less than the expected 20%.

I'm also showing a different way of dealing with the wheel primes: instead of testing for equality with each of them, I use a constant as a bitmap. This allows me to deal with 32 numbers in one go. The performance of this branch is insignificant because it is taken very rarely, but the tighter code means less pressure on the instruction cache.

A similar approach could be used for discarding all multiples of 2, 3 and 5 after a single division by 30 (if (EMPTY_SPOKES & (1 << (n % 30))) return false) but this does not result in an improvement because it rejects multiples of 2 slightly more slowly than the code shown in v4, which is why performance-wise it is pretty much a wash. Hence the simpler, more pedestrian code.

template<unsigned SHIFT>  // replace with _lrotl() or similar
inline
num_t rotate_right (num_t n)
{
   return num_t( (n >> SHIFT) | (n << (sizeof(num_t) * CHAR_BIT - SHIFT)) );
}

enum
{
   PRIMES_7_TO_29 = (1<<7) | (1<<11) | (1<<13) | (1<<17) | (1<<19) | (1<<23) | (1<<29),
   PRIMES_2_TO_31 = (1<<2) | (1<< 3) | (1<< 5) | PRIMES_7_TO_29 | (1<<31)
};

bool v4::is_prime (num_t n)
{
   if (n < 32)
      return (PRIMES_2_TO_31 >> n) & 1;  // normalised to 0/1; good compilers recognise this

   if ((n & 1) == 0 || n % 3 == 0 || n % 5 == 0)
      return false;

   num_t sqrt_n = num_t(std::sqrt(n));

   for (num_t i = 7, w = 0x62642424; i <= sqrt_n; i += (w & 15), w = rotate_right<4>(w))
      if (n % i == 0)
         return false;

   return true;
}

v5 needs a vector of potential prime factors up to the square root of the upper limit. For a limit of INT32_MAX the maximum factor not exceeding the square root is 46340, and even the simplest, most-straightforward code can sieve this in less than a millisecond:

// intended to go no higher than sqrt(2^31) == 46340, hence no need for segmentation or wheeling
// (despite exceeding the L1 cache not slower than vector<bool> for gcc and lots faster for bcc)
void sieve_small_primes_up_to (unsigned limit, std::vector<num_t> &result)
{
   result.resize(0);

   unsigned max_factor = unsigned(std::sqrt(limit));   // = 215

   std::vector<char> is_composite(limit + 1);          // +1 because we're indexing with numbers

   for (unsigned i = 2; i <= max_factor; ++i)          // * 214
      if (!is_composite[i])                            // * 47
         for (unsigned j = i * i; j <= limit; j += i)
            is_composite[j] = true;

   for (unsigned i = 2; i <= limit; ++i)               // * 46339
      if (!is_composite[i])                            // * 4792
         result.push_back(num_t(i));
}

Obviously, this initialisation must be arranged to happen before the primality test function is called. In order to make v5 directly comparable to v4 I decided to handle the primes 2 to 5 in exactly the same way as v4 does. This gives v5 the same advantage as v4 has, which is fast rejection of the multiples of 2, 3 and 5 (73.3% of all numbers). Hence the wheel primes need to be removed from the vector:

sieve_small_primes_up_to(num_t(std::sqrt(INT32_MAX)), small_factors_gt_5);
// erase the wheel primes
small_factors_gt_5.erase(small_factors_gt_5.begin(), small_factors_gt_5.begin() + 3);

Normally this would all be encapsulated in a class that houses the function and its auxiliary data, guarding its invariants. Here I'm showing only the raw primality test code:

bool v5::is_prime (num_t n)
{
   if (n < 32)
      return (PRIMES_2_TO_31 >> n) & 1;  // normalised to 0/1; good compilers recognise this

   if ((n & 1) == 0 || n % 3 == 0 || n % 5 == 0)
      return false;

   num_t sqrt_n = num_t(std::sqrt(n));

   for (auto prime: small_factors_gt_5)
   {
      if (prime > sqrt_n)
         return true;

      if (n % prime == 0)
         return false;
   }

   assert("too few small_factors_gt_5[] (not initialised properly)");

   return false;
}

Older compilers and the classic (non-clang) versions of the Emborlandero compiler need some #ifdefery for replacing the range-based for loop with a normal iterator-based for loop, but I've edited that out here in order to improve readability.

And finally, some code that can beat even PRINT without breaking a sweat, with several orders of magnitude reserve regarding time and memory limits. Most of the bits and pieces are already in place; all that remains is replacing iterated calls to is_prime() with a small Eratosthenean sieve. The only tricky bit here is computing exactly where in the sieve window the sequence of hops for a given prime starts. Here I formulated this in a way that anchors the computation at the slot before the start of the sieve window (hence the apparently unmotivated -1); this has the advantage that it avoids additional branching or a double mod.

Since the code is orders of magnitude faster than the SPOJ requirements, it can simply sieve its factor primes on every call.

void v6::get_primes (num_t m, num_t n, std::vector<num_t> &result)
{
   std::vector<num_t> small_factors;

   sieve_small_primes_up_to(unsigned(std::sqrt(n)), small_factors);

   num_t window_size = n - m + 1;
   std::vector<char> is_composite(window_size);

   for (num_t prime: small_factors)
   {
      num_t first_multiple = prime * prime;  // absolute, may lie outside the window

      if (first_multiple > n)
         break;

      num_t stride = prime;                  // no need to get cute with wheely things and whatnot
      num_t i;

      if (first_multiple >= m)
         i = first_multiple - m;
      else
         i = stride - (m - 1 - first_multiple) % stride - 1;

      for ( ; i < window_size; i += stride)
         is_composite[i] = true;
   }

  result.resize(0);

   // 0 and 1 aren't composites, but they aren't primes either -> skip them if they're there
   for (num_t i = num_t((m < 1) + (m < 2)); i < window_size; ++i)
      if (!is_composite[i])
         result.push_back(m + i);
}


You could read the cell texts before sorting, so that it doesn't have to happen repeatedly in the order function:

    var rowsWithText = $tbody.find('tr').map(function() {
      return {
        row: this,
        text: $(this).children('td').eq(column).text()
      };
    });
    rowsWithText.sort(function(rowA, rowB) {
        return OrderBy(rowA.text, rowB.text);
    });
    $.each(rowsWithText, function(index,row) {
        $tbody.append(row.row);
    });


Reading lines of integers into a list of lists

A simple possibility could be to enclose each row between parentheses and use read-from-string (assuming that the file does not contain incorrect data):

(defun read-data (&optional (file "data.txt"))
  "Returns the numerical data in FILE as a list of lists."
  (with-open-file (data file)
    (let (*read-eval*)   ; set *read-eval* to NIL to avoid malicious code in the input file
      (loop :for line = (read-line data nil nil)
            :while line
            :collect (read-from-string (concatenate 'string "(" line ")"))))))


Buttons that expand or collapse all the  within the document

Performance-wise the code is fine. There is not really anything to improve. I have a few other comments about the code.

You are accessing DOM elements at the start, without checking if they are loaded. Usually they are not, which would cause an error here.

You are naming your handler function, but never refer to them. You can just use an anonymous function here. You also don't use the x parameter.

Don't use var, use let and const instead.

x is not a very descriptive name. It also overwrites the exiting parameter.

There is no need to save the length in a variable. You also don't need to declare i before the loop, since it's not used outside.

There is no need to check if they are already opened or closed. Opening one which is already open doesn't do anything, so just open them all.

Don't use "true" here .setAttribute("open", "true");. According to this.

  Boolean attributes are considered to be true if they're present on the
  element at all, regardless of their actual value; as a rule, you
  should specify the empty string ("") in value

The outcome is the same, but it might lead people to believe that setting the value to "false" will remove it, which is not the case.

With all these changes, the opening look like this

expandDetBtn.addEventListener("click", function() {
  const elements = document.getElementsByTagName("details");
  for (let i = 0; i < elements.length; i++) {
    elements[i].setAttribute("open", "");
  }
});

If you want to get more advanced you could use a single function, since they are very similar.

function toggleDetails(open) {
  for(element of document.getElementsByTagName("details")) {
    element.open = open;
  }
}

expandDetBtn.addEventListener("click", toggleDetails.bind(null, true));
collapseDetBtn.addEventListener("click", toggleDetails.bind(null, false));


What you have here is not MVC. It's DataVC, this results in some minor and major design problems.
Unwrapping data in the Controller
That's the first really bad idea here. You're trying to hide the way Data is structured from the View, based on the assumption that the Model is the Data.
That's not the case. Just pass your Customer-instance to the View for display. The view knows what it needs from the Customer to display it properly.
The Controller doesn't.
Model != POJO
The Model in an MVC application is not the "Domain Model". It's instead the Layer to provide instances of classes modelling that Domain Model (in your case Customers).
Instead of having the Controller receiving a Customer from the calling code (which is unsustainable in larger applications), you should make the Controller ask the Model for customers depending on user-input.
More nitpicks

Your package-declaration should hint at a domain you own.
Making the Customer's field accessible through getters on the Controller is a dumb idea. The Controller doesn't actually have to know about the internals of Customers and shouldn't be asked about them


First off, I don't understand why you so much time dealing with off-by-one indices that you created in the first place:

for node in xrange(1,dim+1):
    for node2 in xrange(1,dim+1):
        for s in samples:
            v1 = s[node-1]
            v2 = s[node2-1]
            if v1 == 1 and v2 == 1:

You could simply write xrange(dim) and s[node] and s[node2]. If you want a 1-based indexing when storing the results, you can still use node + 1 and node2 + 1 when appending the results.

You can also take advantage of the fact that node being a neighbour of node2 will imply that node2 will be a neighbour of node and cut down half of your computations (and a test as well):

for node in xrange(dim):
    for node2 in xrange(node + 1, dim):
        test_failed = False
        for s in samples:
            v1 = s[node]
            v2 = s[node2]
            if v1 == 1 and v2 == 1:
                test_failed = True
                break
        if not test_failed:
            node_neighbours[node + 1].append(node2 + 1)
            node_neighbours[node2 + 1].append(node + 1)

Other tiny improvements includes removing the test_failed flag by using the for ... else construct and testing equality with the extended comparisons:

for node in xrange(dim):
    for node2 in xrange(node + 1, dim):
        for s in samples:
            v1 = s[node]
            v2 = s[node2]
            if v1 == v2 == 1:
                break
        else:
            node_neighbours[node + 1].append(node2 + 1)
            node_neighbours[node2 + 1].append(node + 1)

But a bigger improvement can be achieved using the C core of Python instead of these 2 for loops. Because they perform exactly what itertools.combinations does:

for node1, node2 in itertools.combinations(xrange(dim), 2):
    for s in samples:
        if s[node1] == s[node2] == 1:
            break
    else:
        node_neighbours[node1 + 1].append(node2 + 1)
        node_neighbours[node2 + 1].append(node1 + 1)

Also note that all the provided snippets seems to take for granted that lists for each nodes has already been populated in node_neighbours. This is easily achieved using collections.defaultdict as such:

node_neighbours = defaultdict(list)

You should also wrap this code into a function to better separate the "initialization" or generation of test data from the actual computation. And testing this function should be done in an if __name__ == '__main__': clause:

import itertools
from collections import defaultdict

def pairs_never_both_one(samples, dim=None):
    if dim is None:
        dim = len(samples[0])

    node_neighbours = defaultdict(list)
    for node1, node2 in itertools.combinations(xrange(dim), 2):
        for s in samples:
            if s[node1] == s[node2] == 1:
                break
        else:
            node_neighbours[node1 + 1].append(node2 + 1)
            node_neighbours[node2 + 1].append(node1 + 1)

    return node_neighbours

if __name__ == '__main__':
    from random import randint

    dim = 10000
    sample_size = 1000
    samples = [[randint(0, 1) for _ in xrange(dim)] for _ in xrange(sample_size)]
    print pairs_never_both_one(samples, dim)


While it is okay to put using namespace std in a local scope (such as a function), it's especially problematic to put it into a header file.  By doing this, anyone including it will be forced to have that namespace code exposed globally, and you shouldn't force that on anyone.  Although the std namespace is most commonly used, this applies to any of them.
You should be opening the file and doing user input in main(), not within the class.  You should be receiving data from a client (such as main()) and constructing an object with this data.

Move all of getCommand()'s functionality into main() and have that in your while(1) loop.  Here, you'll get the user's command and supply it to the class until the loop ends.

Another misleading thing here: the name getX() usually denotes a public "getter" function, which merely returns a data member to the client.  It's best to use this name for a function that only does this, which getCommand() does not.  As mentioned, have this functionality in main(), not within the class.  You should then no longer need this function.
Consider allowing the user to provide their own file name:

std::cout << "Filename: ";
std::string filename;
std::getline(std::cin, filename);

std::ifstream file;
file.open(filename.c_str());

You should have all of this in main() and no longer have the class manage the creation, opening, and closing of the file.  Let the user decide how they want to manage their file.  You'll also be able to terminate from main() right away if the file cannot be opened.
I'd recommend against having file.close(); in the destructor.  close() is generally unneeded as the file can close on its own, and might not work as intended here.  The destructor, in general, should primarily deallocate memory when needed.
I'm not sure why commandlist needs to be a std::string*.  This could be problematic as you're having to manage the pointer and its memory yourself, and there are better alternatives to holding this data.  In general, raw pointers should be used sparingly in C++.

In setCommandList(), you're allocating an array of std::strings to that member.  Why not have an std::vector of std::strings?  This will do all the memory management for you, so it's much safer.  You will also have access to its class functions, which could be useful.

std::vector<std::string> commandList;

This should be in place of the std::string* member, and then you can size it to nrOfLines via resize() when needed.  With this, you'll no longer need to new memory nor delete it in the destructor.  You won't even need to define your destructor anymore.
Error messages, such as the one outputted in getCommand(), should be put into std::cerr instead of std::cout.  The latter should just be used for general output.
The abbreviation and comment are pointless:

int cNr; //command number

Not only is it a very confusing abbreviation, but you cannot expect readers to see this first and then remember it throughout the code.  Just rename it to commandNumber (not very long of a name) and remove the comment.
A member function that does not modify any of its data members should be const.  This also protects against any accidental modifications and communicates to the reader that this function only performs read-only actions.

In addition, any function that receives an argument of a user-defined type (such as std::string) and is not supposed to modify it should be passed by const&.  This also prevents any accidental modifications and avoids a needless copy.

These two points apply to verifyCommand(), which is not making any modifications:

verifyCommand(std::string const& command) const {}

For printCommands():

It should be const as it does not modify any data members (see the above point):

printCommands() const {}

Leave out the label output and the extra newline.  The client shouldn't have to be forced to use them if they don't want them.  Just have them done around the function call.


Determine the class hierarchy of a class

The one comment I have is that I find your if statement to be really hard to read:

if (clazz.isEnum() || clazz.isAnnotation() || clazz.isInterface() || clazz.isArray() || clazz.isPrimitive())

I would at least put that into a small helper to throw that exception:

private void checkClassRefersToClassType()


In general, the code is OK, i.e. I don't think it must be changed. However, to increase clarity, I would do a couple of things differently:

It's probably better to write an is_valid() method for your objects, so that whole inner loop is a single function call. Then, you can use grep to shorten the outer loop like this:

    my @objects = load_objects();
    my @valid_objects = grep { $_->is_valid() } @objects;
    stuff_that_assumes_valid_object($_) for @valid_objects;
    store_objects(@valid_objects);

Also, depending on what stuff_that_assumes_valid_element does, you can either put that call into is_valid() or into stuff_that_assumes_valid_object. Either way, your top-level code works with objects and thus shouldn't know too much about single elements inside those objects, that's something the object itself should know and do (see Law of Demeter for reasoning).


I know it's kind of standard to do this in C land but you should spell things like this if((result = malloc(default_sizes[i]))) out as:

result = malloc(default_sizes[i]);
if (result != NULL)
{
}

Yes it's one line of code more but the intent is much more obvious at a first glance. As suggested in the comments you might want to invert the condition and continue. Reduces the level of nesting:

result = malloc(default_sizes[i]);
if (result == NULL) { continue; }

Technically it's better to write if (NULL == result) because if you accidentally write = instead of == then the compiler will throw an error instead of compiling buggy code - I just can't seem to get myself into that habit for some reason. Probably because it reads a bit clunkier that way (imho).
It's perfectly legal for a struct to contain a pointer to itself like this:

typedef struct memory_ {
    void           *mem_pool;   //starting address for this block
    struct memory_ *next;       //next node
    size_t         *position;   //current position
    size_t         *available;  //how much memory was allocated?
} memory_t;

The return type of increase_memory should be memory_t * because that's what it returns. You can also get rid of result in there and use new_block in its place.
In init_mem_pool you asked some questions on the return value. I guess you want it to indicate whether the initialization was successful or not - which is if root is NULL or not so you can just write this:

return root != NULL;


Saving a sales order - too many repositories?

I find it interesting that you want to decouple layers, but that the method you have here is tightly coupled with UnitOfWork<LogContext> (and thus with LogContext as well), OrderLineRepository and OrderDetailRepository.
To answer the question directly, yes, it's way overdone.
I'd put a method like SalesOrder FindSalesOrder(int id) in a service layer:
public class SalesOrderService
{
    private readonly IUnitOfWork _uow;

    public SalesOrderService(IUnitOfWork uow)
    {
        _uow = uow;
    }

    public SalesOrder FindSalesOrder(int id)
    {
        return _uow.Set<SalesOrder>() // get repository
                   .Where(order => order.Id == id) // filter by id
                   .Include(order => order.OrderLines) // eager-load details
                   .ToList(); // materialize
    }
}

What's IUnitOfWork, you'll ask? Just an abstraction that looks something like this:
internal interface IUnitOfWork
{
    DbSet<TEntity> Set<TEntity>();
    void Commit();
}

The EF context itself implements it:
public class MyDbContext : DbContext, IUnitOfWork
{
    public IDbSet<SalesOrder> Orders { get; set; }

    public void Commit()
    {
        SaveChanges();
    }
}

Entity Framework's DbContext is a unit-of-work implementation, and IDbSet<T> is a repository.
Constructor-injecting an IUnitOfWork in your service class effectively decouples your service class from EF, at least good enough for unit testing (you can mock what Set<T>() returns)... "swapping the ORM" will require lots of work anyway, and is highly hypothetical - the cost vs benefits ratio doesn't add up in favor of abstracting EF with repositories.

Your Code
There are a number of itchy spots with the code you've provided:

Casing is annoyingly inconsistent for local variables. Should be camelCase, always: var LineDetails becomes var lineDetails, for example.
using blocks should be stacked whenever possible, to reduce unnecessary nesting:

using (var uow = new UnitOfWork<LogContext>())
{
    using (var repository = new SalesOrderRepository(uow))
    {
        var SalesOrder = repository.Find(s => s.Id == id, s => s.Site, s => s.User);
        if (SalesOrder != null)
        {

Becomes:
using (var uow = new UnitOfWork<LogContext>())
using (var repository = new SalesOrderRepository(uow))
{
    var SalesOrder = repository.Find(s => s.Id == id, s => s.Site, s => s.User);
    if (SalesOrder != null)
    {


If you are trying to insert data in bulk to Mysql the best would be to use LOAD DATA instead of doing it in a loop on top of an interpreted language, which is inevitably slower. However there is less flexibility if you need to transform data but that shouldn't be a problem in your case. All you're doing is get rid of carriage return. This is a plain delimited file without heavy transformation.
The mydb.commit() is misplaced. It should be called after running an insert/update. On the first iteration there is nothing to be committed.
But this is not efficient. I suggest that you take full advantage of transactions. Start a transaction at the beginning, do your loop and commit at the end. In case of error, you roll back. The added benefit is data integrity. If an error occurs, the data already inserted is "undone" so you don't end up with garbage due to a partial import of data.
Schema:
try:
    conn.autocommit = False

    # insert loop..

    # Commit your changes
    conn.commit()

except mysql.connector.Error as error:
    print("Failed to update record to database rollback: {}".format(error))
    # reverting changes because of exception
    conn.rollback()

See for example: Use Commit and Rollback to Manage MySQL Transactions in Python
This alone should improve performance but you have to test it to measure the gain.
Not performance-related, but you can also use a context manager whenever possible, for instance when opening/writing to a file. So:
agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")

becomes:
with open("C:/Users/juczi/Desktop/New Folder/" + plik, "r") as agefile:
   # do something

and you don't have to bother closing the file, this is done automatically.


Remove elements compared with other elements in a Set based on a condition

In the case where you just want to find the best tuples, the code can be much simpler:

find the Tuple with the best t for each value of itv (sounds like a job for Map)
put the best bunch of Tuple into a Set, and return it

public static Set<Tuple> bestTuples(Set<Tuple> set) {

    Map<Integer, Tuple> bestTuplesByItv = new HashMap<Integer, Tuple>();
    Tuple bestTupleSoFar;
    for (Tuple t: set) {
        if ((bestTupleSoFar = bestTuplesByItv.get(t.itv)) == null || t.t > bestTupleSoFar.t) {
            bestTuplesByItv.put(t.itv, t);
        }
    }

    Set<Tuple> bestTuples = new HashSet<Tuple>();
    bestTuples.addAll(bestTuplesByItv.values());

    return bestTuples;

}

This should also be faster - your solution has some nested loops, O(n^2), but the suggestion above just iterates through the entire set once. My gut tells me that removing things from a Set is slower than just making a new set with the things we want, but I'm not sure about HashSet.

Since the values for the Map are coming from a HashSet, all the values are guaranteed to have unique hash value. Since that's the case, we don't need a LinkedHashMap - a plain HashMap will work just fine (LinkedHashMap creates linked lists to deal with hash collisions - but that's unnecessary as we won't have any).

Your code seems to be mutating the Set that is passed in as a parameter though - if that's desired behaviour, it's a trivial modification from the code above - just clear the values in set and add the values we want before returning:

public static Set<Tuple> compareAndRemove(Set<Tuple> set) {

    Map<Integer, Tuple> bestTuplesByItv = new HashMap<Integer, Tuple>();
    Tuple bestTupleSoFar;
    for (Tuple t: set) {
        if ((bestTupleSoFar = bestTuplesByItv.get(t.itv)) == null || t.t > bestTupleSoFar.t) {
            bestTuplesByItv.put(t.itv, t);
        }
    }

    set.clear();
    set.addAll(bestTuplesByItv.values());

    return set;

}


Just a quick thing:  int(1) probably does not mean what you think it means.

mysql> create table int_length (x int(1));
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO int_length VALUES (1234);
Query OK, 1 row affected (0.05 sec)

mysql> SHOW WARNINGS;
Empty set (0.00 sec)

mysql> SELECT x FROM int_length;
+------+
| x    |
+------+
| 1234 |
+------+
1 row in set (0.00 sec)

int(x) is basically used for zerofill and nothing else.  If you want a smaller data type, you'll need to use a small data type (tinyint, etc).  (Note that this doesn't apply to var types.  varchar(5) is <= 5 characters, and varchar(10) is <= 10 characters.


A simple program with trains and inheritance

Coal_ already made some good points. Let's just elaborate on the one about private.
A class makes everything in it private by default that is why you don't need it if you order your interface this way. However it's recommended to order your interface from public to private so people who read it can see which methods you expose without having to read through all the private data first.
If you are using a trailing underscore because you're worried about problems when assigning arguments to members then there is no need for that. This is because it's guaranteed to work even if the names are the same. Just make sure to be careful in the constructor body if you do this!
Your variable names could be better. In general you should avoid single letter names and choose a descriptive name.
Some parts are probably easier to read if you put a few more spaces inbetween operators. Indenting could also be improved for example in your ctors:

Foo()
    : bar(0)
    , baz(1)

is a lot more readable than putting everything in a single line.
Some of your parenthese in the return statements are superfluous and can be removed.
In C++ it's generally recommended to treat & as part of the type and therefore write foo& instead of foo &.
Since you included <cmath> you should probably prefix pow and sqrt with std::.
You seem to use double solely because of your math functions. Perhaps strategic casting would be better instead of using a type you don't fully make use of.
When using the ranged-for loop it's recommended to use this form:

for (auto const& value : container) {
    // ...
}

The const makes it clear you don't intent to modify things in this loop and passing by reference avoids unecessary copies.
If you run your compiler with warnings (as you should! For example to discover some potential problems you can use an online compiler like Clang with -Weverything. For production code you want to pick your warning levels more carefully though) you will notice that there are some issues.
You have a wrong initialization order and are missing a virtual destructor. Order can be important when you depend on something in the base class.
The way you handle your objects in main is certainly interesting but this seems like a good place for smart[1] pointers[2] and their respective make_unique/shared functions.


Select the n most frequent items from a pandas groupby dataframe


Cython functions for generating NumPy date ranges

I'm sorry, but this code is really hard to read. I must admit I don't know Cython too well, so I won't be able to comment too much on that part. But anyways, here are a few comments, in random order.

While Cython does not fully support docstrings (they do not show up in the interactive help), this should not prevent you from adding some to explain what the different functions do and what arguments they take.
You seem to be doing np.int64(start).astype('M8[D]').astype('M8[M]').view("int64") quite a lot. As far as I can tell, this extracts the month from a date, which was given as an integer(?). There is quite possibly a better way to do that (using the functions in datetime), but they might be slower. Nevertheless, you should put this into its own function.
You do freq.decode("utf-8")[len(freq)-1] twice. Do it once and save it to a variable. Also, freq[len(freq)-1] should be the same as freq[-1] and freq[:len(freq)-1] the same as freq[:-1]. This is especially costly as len(freq) is \$\mathcal{O}(n)\$ for char *, in Cython.
You create datetime.fromtimestamp(start*24*60*60) three times, once each to get the day, month and year. Save it to a variable and reuse it.
The last two comments in loanDates seem not to be true anymore:

# If no dates generated (start date>end date)
ts = ts

# If last date generated is not end date add it
return ts.astype('int64')

The documentation seems to recommend against using C strings, unless you really need them. If I read the documentation correctly you could just make the type of freq str and get rid of all your encode("utf-8") and decode("utf-8") code.
The definition of the months array is done every time the function get_days is called. In normal Python I would recommend making it a global constant, here you would have to try and see if it makes the runtime worse.
Python has an official style-guide, PEP8. Since Cython is only an extension, it presumably also applies here. It recommends surrounding operators with whitespace (freq[len(freq) - 1]), using lower_case for all function and variable names and limiting your linelength (to 80 characters by default, but 120 is also an acceptable choice).

In the end, taking 1ms to create a date range is already quite fast. As you said this is already faster than pandas.daterange (which does a lot of parsing of the input first, which you avoid by passing in numbers directly). You might be able to push it down to microseconds, but you should ask yourself if and why you need this many dateranges per second.


benchmarking sorting algorithms: std::sort vs my naive radix

I'm not too surprised to see the radix sort being faster in this use case, 32 bits is very short for a key.
You may want to look at this comparison as well as at the last paragraph of this History section.
About the bench method, I would:

Try with values already sorted.
Try with values sorted in reverse.
Try with multiple sets of random values, each set identified by its seed (so no random seed).
Try with the same as above but with the first half filled with random values and the second half being a copy of the first half.

I would also test the end result, of course.


Verify two numbers from a list will add up to a number in the same list using Python

The thing to be concerned with when writing functions like this is the size of the data it's going to be processing. If you're only ever going to be dealing with small sets of data (less than say 100 items) then there really isn't an issue with the way this is written. At the scale of maybe tens of thousands of items this starts to be a problem.

I'm not a data scientist or anything, I'm just a web developer and I very rarely delve into trying to optimise code, so any advice I'm giving is based on my personal experience + uni, and doesn't utilize math libraries in Python like numpy which you might want to look into depending on what this code is for. Another answerer could likely help more with this specific circumstance, my answer is going to be a bit more general; assuming you're going to be dealing with large amounts of data (or otherwise prematurely optimising is sometimes considered the root of all evil):

EDIT: I just noticed that one of your examples included negative numbers, so the example code below will need to be adapted with that in mind since it affects the movement of i and j; sorry about that, but the code provided can still be run as an example with positive numbers.

Ignoring data types used for the most part & how pythonic the code is, I see probably two areas for improvement. The first I'll touch on at the end in a code example & may depend a bit on your particular data-set as to how helpful it will be, but presently, the code has no chance of finishing early (assuming random inputs that'd give you an substantial speedup especially if your data is likely to find a match in the early items of the list).

However, the primary areas for improvement can be determined through analysing your code via Big-O / Big(O) notation. I'd suggest a read of the concept if you're unfamiliar, but according to Wikipedia:

  big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows

Given the following section of your code:

for index in range(len(l)-1):  # (1)
    ...
    while counter + index < len(l): # (2)
        ...
        sum_set.add(sum) # (3)
        ...
for number in l: # (4)

If we look at, for instance, a 100,000 element array containing the numbers between 1 and 100,000, if we run your code as it's written, we will end up running the sum_set.add(sum) statement (3) about 4.99 billion times. At just 10,000 elements, on my machine, the code as written takes multiple seconds to finish.

Looking at (1), we see this statement runs through all elements in the list, therefore O(N); the time taken for the outer loop depends on a linear relationship to the input, e.g. O(N) means an input array of 200 elements, ignoring any constant time overhead, should take ~roughly~ 200x longer than an array with 1 element. Line (2) passes through N-1 elements on the first loop, then N-2, ... finally 1 item in last loop; averaging out at half as many loops as the outer index, but is still O(N) as it's linearly related to the amount of items included in the list. As you have an O(N) loop within an O(N), this gives it the overall O(N^2) performance.

(4) is tricky to estimate, as it depends on the passed in data. Iterating through the list l is O(N) again, and if we assume worst case, each element in sum_set could be unique, i.e. if the passed in array was something like [1, 11, 111, ...], which would mean there are ~N^2 terms in sum_set, actually causing this loop to degrade to O(N^3) performance. Best case, the sum_set is very small, but even assuming only 1 item, that would still be O(N) as we need to touch each element in l. Additionally, sum_set could potentially become very large, causing the loop not only to be expensive in time but also possibly memory (although as you are using a set there aren't going to be any duplicates, so it will totally depend on the input data. E.g. 100,000 elements, but the values range between 0 & 100, so sum_set ranges between 0 & 200).

I'd say your suggestion of pre-filtering to remove duplicates is a good idea, ideally something O(N) like the following (though there are likely more optimal approaches):

>>> input_list = [1,1,1,1,2,2,2,3,3,3]
>>> filtering_dict = collections.defaultdict(int)
>>> for item in input_list:
...     filtering_dict[item] += 1
...
>>> newList = []
>>> for key, value in filtering_dict.items():
...     newList.append(key)
...     if value > 1:
...         newList.append(key)
...
>>> newList
... [1, 1, 2, 2, 3, 3]

I'd then try and take advantage of sorting the array using an O(Nlog(N)) sort like Mergesort / Quicksort, or depending on your data an O(N) sort like Counting Sort. If you know your data is going to be ordered, you can skip this step. With sorted data, we don't have to use the sum_set set; we can instead pick an index in the array & determine whether it is the total of two other elements. We know that any index we suspect to be our sum will have to be made up of elements that are lower indexes than it in the list, i.e. [1, 2, 3, 4, 5] -> If we start looking at 3, we know we don't need to consider elements 4 & 5, as they will be larger than 3, so couldn't possibly sum to it. Finally, the halfway point for a number is also relevant, I.e. [1, 3, 5, 7, 9, 11, 99, 117] if we're looking at 99, we first look to add the next lowest index & the first index; however, since 11 < 99/2 we know we won't be able to find a match that adds to 99; on average this should be another speedup assuming the data isn't perfectly uniform.

Finally, since we aren't pushing results into sum_set & only checking once for each total, this will cause some repetition in our search. However, since we can return immediately upon finding a match, our best/average case just got a lot better.

def func2(l):
    # l = filter_inputs(l)
    # l.sort()
    for index in range(2, len(l)):
        i = 0
        j = index - 1
        half_val = l[index] / 2;
        while ( i < j and l[i] <= half_val and l[j] >= half_val ):
            if l[index] > l[i] + l[j]:
                i = i + 1
            elif l[index] < l[i] + l[j]:
                j = j - 1
            else:
                print(str(l[i]) + " + " + str(l[j]) + " = " + str(l[index]))
                return True
    return False

Using timeit, and comparing func & func2, using code like the following:

from timeit import timeit
timeit('func2(<TEST ARRAY>)', setup="from __main__ import func2; import random", number=20)
# Use the function that's been predefined in the python interpreter,
# pass the array, repeat the test 20 times, and output how many seconds taken

# All times listed are in seconds for 20 repeats

# list of all positive odd numbers up to 9,999 == [x for x in range(1,100000) if x % 2 is 1]
# (absolute worst-case condition for func2, behaves nearly identically to your original function)
# (this is because i, j, and half_val achieve 0% improvement & every value is checked)
# func2      # func
>>> 73.89    >>> 73.86

# all integers between 1 & 9,999 == [x for x in range(1,10000)]
# func2     # func
>>> 0.02    >>> 297.54

# 9,999 random integers between 1 & 10,000 == [random.randint(0,10000) for x in range (1,10000)]
# Re-ran this one about 5 times for func2 since it was so quick,
# with 20 loops its lowest was 0.25 & highest 0.32 seconds taken
# You'll also need to sort 'l' for this one to work with func2
# func2     # func
>>> ~0.3    >>> 312.83

Again, with a low number of entries in l, the cost of removing duplicates & sorting the array would probably cause my function to run slower than yours. None of these speedups change the fact that the overall operation is worst-case O(N^2); however, they should drastically improve the best/average-case scenarios. Additionally, getting a large average speedup with an O(N^2) operation is huge when it comes to a big dataset, as it will be the limiting factor:

I.e. 100,000 items:

Filtering     = ~2x O(N)    = ~200,000 ops
Mergesort     = O(NLog(N))  = ~1.6 million ops
Main Loop     = 1/2 O(N^2)  = ~5 billion ops

If you can come up with a better way to take advantage of the data such that you can get O(N^2) down to O(Nlog(N)) or similar, I think that'd be key here for optimizing the worst-case scenario.


////////////////Select the student marks and put it in array with subject id and exam id

$result = mysql_query("SELECT * FROM stu_marks");
while ($row= mysql_fetch_array($result)){
$arr[$row['Subj_ID']][$row['Exam_ID']]=$row['Grade'];
}

I don't fully understand why you are pulling data out of an array to put it back into an array.  You should consider writing better, more specific sql queries so that the result of the individual SQl query is as close to what you want your table to look like as possible.  From there, you can then loop through the already made (via mysql_fetch_array) result and reduce the amount of redundancy.

Also, use PDO, don't use or die (probably not ready for these two yet) and for the love of god, NAME YOUR VARIABLES DESCRIPTIVELY.  I can barely tell whats going on and it's not in any way complicated.


Is this an good OOP Design in MVC PHP for getting User Details?

There is not much OOP to review it. Actually that's just two functions, so one can review only the code, not the object structure. All in all there is a lot of repetitive or outright useless code

public function getUser($request, $response, $args)
{
    $userId= $request->getAttribute('id');
    $user = $this->User->getUserById($userId);
    return $response->withJSON([
        "error" => !$user,
        "message" => $user ? "success" : "no such user"
        "data" => $user ?: null
    ]);
}

as you can see, there could be just one return statement

public function getUserById($userId)
{
    $sql = "SELECT id, name, email FROM users WHERE id= :id";
    $stmt = $this->db->prepare($sql);
    $result = $stmt->execute(['id' => $userId]);
    return $stmt->fetch();
}

I took out all the useless code, namely

it is useless to verify $result. In case of error an exception will be thrown
it is always useless to check the rowCount()
why use fetchAll() if you need only one row?
it is useless to add any condition because fetch() will return FALSE already if no record found.
the same goes for the try-catch. There should be a site-wide error handler that will log the error and do something else like show a generic 500 error in the browser


I/O

You want to read 2 characters although you use scanf("%s", codes[i]) this can have the effect you are overwriting the end of the buffer when you read scanf("%s", codes[required_seats-1]); since there is always an \0 added to your two characters.

Either increase the buffer, change the format specifier or use an alternative method of reading from keyboard e.g. fgets() followed by sscanf() or simply read the characters one by one using fgetc(). The latter method has the advantage that you could prevent the user from entering invalid characters while he types.

You may also want to convert the characters to upper case just to be a bit more flexible towards the user (toupper())

structure

I think the code could do with some more functions to clarify the purpose.

E.g.

int isCodeValid(char* code)
{
  return code[0] >= 'A' && code[0] <= 'A' + TOTAL_ROWS - 1 &&
     code[1] >= '1' &&  code[1] <= '1' + SEATS_PER_ROW - 1;
}

int isRepeatedSelection(char* codes);
...

loop

What other suggested and as you mentioned already decrementing i in the for loop may be a bit confusing for the reader (well it was for me at least), having a do..while loop feels more natural here where the while condition is false until user enters correct code (or changes his mind and gives up).


New Year Chaos JavaScript, needs to be sped up

Reduce the inner loops iteration count.
The problem is the inner loop is looping over too many items. The result is that you spend too much time processing data you know is irrelevant.
As the function should exit if it detects a position has made over 2 bribes, you need only have the inner loop check positions down 2 from the item you are checking, and not from the start of the line.
Quicker solution
It only requires a slight modification of your code, but as you have complicated the situation by calling an inner function sort the example has just removed the inner function.
The line for (j = pos-2; j < i; j++) { is where the improvement is with pos being item[i] in your function.
function minBribe(queue) {
    var bribes = 0, i, j;
    for (i = 0; i < queue.length; i++) {
        const pos = queue[i], at = i + 1;
        if (pos - at > 2) { return "Too chaotic" }
        for (j = Math.max(0, pos - 2); j < i; j++) {
            if (queue[j] > pos) { bribes++ }
        }
    }
    return bribes;
}

This brings the solution down from \$O(n^2)\$ to near \$O(n)\$ however the number of bribes is a factor so its closer to \$O(n + (m^{0.5}/2))\$ where \$m\$ is the number of bribes. (this is only an approximation)


Using the $q service in AngularJS to handle promises

Things that could have been better;

This:

        },
        function(error) {
            deferred.reject(error);
        }
    );

could simply be

        }, deferred.reject );

reject is a function that takes error as a parameter after all..
I would have externalized the previewSessionResource.save(call, it makes the reading too hard. You only capture settings and appResponse which you would then provide as parameters.
If you control the signature of previewSessionResource.save, then I would simply request for settings as an object instead of requesting for { settings: settings } to keep it simple, it does not make sense to wrap a single data point into an object.
I am also idly wondering if previewSessionResource.save should not be responsible for calling $localForage.setItem(), would you ever call previewSessionResource.save without calling $localForage.setItem()?

On the whole, I think this is okay, it just needs some rejiggering to read better.


I don't know anything about CodeClimate or how it determines complexity, but this is the likely culprit right here:

return (
    40
    + (appearance.outfit.head ? 2 : 1)
    + (appearance.outfit.cape ? 2 : 1)
    + (appearance.outfit.amulet ? 2 : 1)
    + (appearance.outfit.weapon ? 2 : 1)
    + (appearance.outfit.shield ? 2 : 1)
    + (appearance.outfit.head ? 2 : 1)
    + (headObscured ? 2 : 4)
);

This is pretty hard to read and understand at a glance, and all of the ternary operators certainly don't help. Without knowing more about your object it is hard to review, but to me it would make more sense to have a method like this on your outfit object

function getSlotSize(slot) {
    let size = 0;
    if (this.slots.includes(slot)) {
        size = slotIsEmpty(slot) ? 2 : 1;
        if (slot === "head") {
            size += 2 * isCoveringHead(this.head);
        }
    }

    return size;
}

function slotIsEmpty(slot) {
    return this.[slot] === null || this.[slot] === undefined;
}

Now you've separated out your logic for determining the size of everything instead of having to jam it into one function.

An even better approach may be to OOP this, and create objects representing a slot (or a specific kind of slot) and then each one should have a getSize method. Without knowing more about your code it is hard to say whether or not that would be overkill.


Where will this .offsetTop() function fail?

For starters, this doesn't work in IE7 or IE8. I'm assuming you knew that, although you never mentioned compatibility if any you were aiming for.

I rewrote what you made, to work in IE7 & IE8, so you can see where it fails. It is available at http://jsfiddle.net/Akkuma/Xem3B/

You'll find the following not working correctly in IE8 compared to the latest Chrome Dev 18 static, static (static wrapped), fixed/absolute (side), absolute/relative/static (absolute/relative wrapped), relative, and fixed/absolute (bottom).

In jQuery they do several different compatibility checks for whether a browser adds the border, for relative/static/fixed positioning, whether the browser subtracts the borders for overflows that are something other than visible. It appears modern browsers should support your approach just fine.

Your code appears to work fine in IE9, so if you aren't supporting IE8 & 7 your code should be good to go. However, if you take a look at jQuery's code you'll find they do not have to recursively traverse up the tree to calculate the offset in modern browsers that support getBoundingClientRect. The trade off is obviously one of simplicity (your own code) vs performance. I haven't verified which is faster, but I would expect jQuery's approach to keep getting faster the deeper the element is in the tree compared to your documentOffsetTop.

Update: If you haven't seen it, here is an older explanation from John Resig on it and what additional things they had to do (note this is from 2008, so the links are broken and I'm sure they may have modified it more) http://ejohn.org/blog/getboundingclientrect-is-awesome/. Additionally, here is the Mozilla documentation detailing how to properly use it cross-browser.


It is very hard to read your code, since you use single letter variables (x, s, l... etc.).

Some more general concerns: x is a class member, initialized in its declaration, overriden in the Main method (without the initial value ever being used), and then passed as an argument to the Match method.

As for why the value is stuck on 2, my guess is that the line i += count - x[j]; leaves the i value the same - count - x[j] == 0 perhaps you meant to write count + x[j]?


public void LoadView()
{
    try
    {
        SQLiteCommand command = new SQLiteCommand(connection);
        command.CommandText = MyApk.Properties.Resources.user_datagrid;

        DataSet DST = new DataSet();
        DataTable DT = new DataTable();
        SQLiteDataAdapter SDA = new SQLiteDataAdapter(command);
        SDA.Fill(DT);
        this.user_view.ItemsSource = DT.AsDataView();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

DataSet DST = new DataSet(); is never used and should be deleted.
both SQLiteCommand and SQLiteDataAdapter are implementing IDisposable so you should enclose them in a using statement to automatically dispose them after their usage. In addition the constructor of the SQLiteCommand is overloaded to take a commandtext too.
variables should be named using camelCase casing and shouldn't be named using abbreviations so SDA could simply be dataAdapter and DT will be dataTable.

Implementing the mentioned points will lead to

public void LoadView()
{
    try
    {

        using (SQLiteCommand command = new SQLiteCommand(MyApk.Properties.Resources.user_datagrid, connection))
        using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            this.user_view.ItemsSource = dataTable.AsDataView();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

But now this is tightly coupled to the user_view control and the query MyApk.Properties.Resources.user_datagrid which is suboptimal.

If we pass an ItemsControl object and a string to this method it would be more flexible like so

public void LoadView(ItemsControl control, string commandText)
{
    try
    {

        using (SQLiteCommand command = new SQLiteCommand(commandText, connection))
        using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            control.ItemsSource = dataTable.AsDataView();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

and can be called like

LoadView(this.user_view, MyApk.Properties.Resources.user_datagrid);


Your code uses streams quite neatly and well. The algorithm employed is not necessarily the best, but the logic is reasonably clear.

It's common with streams to use vertical white-space to make the steps in code more readable. For example, the line:

queries.stream().forEach(query -> System.out.println(corpus.stream().filter(p -> p.equals(query)).count()));

could be re-formatted as:

queries.stream()
       .forEach(query -> System.out.println(
              corpus.stream()
                    .filter(p -> p.equals(query))
                    .count()
               ));

Now, while dealing with that stream, it's not really streaming things "right".... The System.out.println is out-of-place. You should be mapping the query in to a count in one step, and then outputting the count in a different step....

queries.stream()
       .mapToInt(query -> corpus.stream()
                    .filter(p -> p.equals(query))
                    .count()
               )
       .forEach(System.out::println);

Now, there are ways to improve that performance still, for example, lots of println statements could be grouped in to just one print...

String output = queries.stream()
       .mapToInt(query -> corpus.stream()
                    .filter(p -> p.equals(query))
                    .count()
               )
        .mapToObj(String::valueOf)
        .collect(Collectors.joining("\n"));
System.out.println(output);

Finally, note that you are doing an \$O(n)\$ operation for each query. You should consider a way of improving that time-cost by front-loading the creation of a Map when loading up the words will improve the performance of querying things.

For example, consider this:

IntStream.range(0, N).forEach(n -> corpus.add(sc.next()));

First up, that inner part n -> corpus.add(sc.next()) is doint a "side-effect" operation that can be avoided. Functional-programming purists try to avoid side-effects in streasm as much as possible. SOmetimes it is unavoidable, but you could easily re-write that line as:

List<String> corpus = IntStream.range(0, N)
      .mapToObj(n -> sc.next())
      .collect(Collectors.toList());

That adds each word to a list. How about doing it this way:

Map<String, List<String>> data = IntStream.range(0, N)
         .mapToObj(i -> sc.next())
         .collect(Collectors.groupingBy(v -> v));

That code takes each input word, and returns a Map keyed by each unique word, and each word's value is a list containing each instance of that word in the source.

Now, you can use the length (size) of the value list to return your data with:

String output = queries.stream()
        .mapToInt(query -> data.get(query).size())
        .mapToObj(String::valueOf)
        .collect(Collectors.joining("\n"));
System.out.println(output);


jQuery Toggle Between Functions Fn1 Fn2 Fn3 On Click

Your general approach seems sound. But you shouldn't hard-code the number of handlers. Take the functions as a rest-arg, and use funcs.length in the modulo expression.

You can also use the argument to .data() to look up the named data element, rather than getting the whole data object.

$.fn.clickToggle = function(...funcs) {
    this.data('toggleclicked', 0);
    this.click(function() {
        var tc = $(this).data("toggleclicked");
        $.proxy(funcs[tc], this)();
        data.toggleclicked = (tc + 1) % funcs.length;
    });
    return this;
};

You might also want to special-case a single function and just bind it the normal way, and completely ignore the call if there are no functions.

$.fn.clickToggle = function(...funcs) {
    switch (funcs.length) {
    case 0:
        break;
    case 1:
        this.click(funcs[0]);
        break;
    default:
        this.data('toggleclicked', 0);
        this.click(function() {
            var tc = $(this).data("toggleclicked");
            $.proxy(funcs[tc], this)();
            $(this).data("toggleclicked", (tc + 1) % funcs.length);
        });
    }
    return this;
};


Make Project Euler 27 solution idiomatic Ruby

Succinctness
As rubyists, we love being succinct, and we love playing with enumerations.

You will see very few literal false and true in ruby code, as well as very few explicit return calls.

For example:

Instead of writing return false if self < 1 we will prefer to compound the condition to self >= 1 && ... which will do the same thing, but we "save" return false.

The power of Enumeration
Ruby has a very powerful Enumerable, and is used widely, often more than once in a line (using method chaining).

For example:

2.upto(Math.sqrt(self)) do |i|
  return false if self % i == 0
end

Here you check if any of the numbers in the range are a divisor for self, and break if there is any. A more ruby way of doing it will be:

return false if 2.upto(Math.sqrt(self)).any? { |i| self % i == 0 }

We'll also prefer to more succinct range syntax (2..Math.sqrt(self)), which is simply shorter...

So now, our def prime? method could be reduced to a one-liner:

class Integer
  def prime?
    self > 1 && !(2..Math.sqrt(self)).any? { |i| self % i == 0 }
  end
end

Mapping
Anywhere in the code I see the following pattern:

result = []
some_loop do
  result << something
end

A red flag is raised, and I look for a way to use map to do the same thing:

result = some_loop.map { something }

Your code goes over all the non-negative integers, and takes counts how many of them result in a prime, until the first non-prime.

"All the non-negative integers" can be expressed in ruby as (0..Float::INFINITY), so we can write:

(0..Float::INFINITY).map { |n| n**2 + a*n + b }.take_while { |result| result.prime? }.count

This code takes each integer, maps it into the result of n**2 + a*n + b, takes all the results until they are no longer prime, and counts how many are there.

Cool! Right? The only problem with the code above, is that it will take infinity to complete it, as it takes all the numbers and maps them, and then checks for how many to take.

To solve this problem ruby now has...

Lazy Enumerables
As of ruby 2.0, lazy enumerables allows you to calculate values in an infinite stream only as needed.

To solve the problem above, all we need to do now is to add the lazy operator on the range:

(0..Float::INFINITY).lazy.map { |n| n**2 + a*n + b }.take_while(&:prime?).count

And we have another one-liner!

Everything is an enumerable
So you want to save on your "upto-loops"? Let's do it!

You want to enumerate over each pair of numbers from -999 to 1000, so what you actually want is to have a long matrix of those pairs:

[[-999, -999], [-999, -998],...,[1000, 1000]].do_something_smart

To do that, you can use product:

(-999..1000).to_a.product((-999..1000).to_a)

But since both a and b have the same range, we can even DRY this up, and use repeated_permutation:

(-999..1000).to_a.repeated_permutation(2)

Both of these solutions will give you the needed matrix, so we can move on the see what we should do with it...

We want to get the coeffiecients that produce the number of primes, so let's do just that:

a, b = (-999..1000).to_a.repeated_permutation(2).max_by { |a, b| get_amount_of_primes_from_quadratic_formula(a,b) }

Now all we need to do is multiply them with each other!

Method naming
Your names are very verbose, which is a good thing, but ruby idiom frowns upon get_ prefixes. Also, prefer using verbs already in the language (count) over those which are not in the language (amount_of)

So now the code will look like:

class Integer
  def prime?
    self > 1 && !(2..Math.sqrt(self)).any? { |i| self % i == 0 }
  end
end

def count_quadratic_formula_primes(a,b)
  (0..Float::INFINITY).lazy.map { |n| n**2 + a*n + b }.take_while(&:prime?).count
end

def product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values()
  a, b = (-999..1000).to_a.repeated_permutation(2).max_by { |a, b| count_quadratic_formula_primes(a,b) }
  a * b
end

start = Time.now
answer = product_of_coefficients_that_produce_maximum_number_of_primes_for_consecutive_values

puts "The answer is #{answer} and it took #{Time.now-start} seconds."

15 lines of hard-core ruby-style code!

Enjoy!

Update
It seems that lazy adds considerable overhead to the performance of the code. So it is not advisable to use it.

Fortunately this works:

(0..Float::INFINITY).take_while { |n| (n**2 + a*n + b).prime? }.count

My code still runs ~2 times slower than the original (ends in 18 seconds), but it is more reasonable than with lazy...


A ViewModel using ReactiveUI 6 that loads and sends data

Sorry to disappoint, but you did everything right! This is a quite good example of using RxUI, Akavache, and Refit together.

The only thing I would change, is to not immediately call LoadItems.ExecuteAsyncTask in the ViewModel constructor. Invoking this in the VM constructor means that your VM class becomes more difficult to test, because you always have to mock out the effects of calling LoadItems, even if the thing you are testing is unrelated.

Instead, I always call these commands in the View constructor, something like:

this.WhenAnyValue(x => x.ViewModel.LoadItems)
    .SelectMany(x => x.ExecuteAsync())
    .Subscribe();

This means that any time we get a new ViewModel, we execute LoadItems, which is what we want when the app is running, but not what we want in every unit test.