I haven't used shopify so I don't know if you can accomplish your task with fewer shopify calls, but I do find it a little odd that the URL in the second call requires redundant theme identification.  I mean, the theme id is in the path and the querystring.

Outside of that, I spy some basic refinements.

As a general rule, avoid declaring single-use variables. Reasonable exceptions to this rule include when:

the merging of multiple processes/declarations results in a code line which exceeds a sensible length (horizontal scrolling is a drag and I generally obey PHPStorm's visual guide line when deciding when a line is too long) or
the data being processed/produced/declared is clarified by the variable name

Within a given project, determine if variables will be written in camelCase or snake_case.  Use one style consistently throughout.
There is no JSON_PRETTY_PRINT for json_decode() -- you are looking for the true parameter to make an array.  The outcome is the same, but it is a typo worth fixing to avoid future confusion.
Write a space between all comma-separated parameters in functions.

Application:

$themeList = shopify_call($token, $shop, "/admin/api/2019-07/themes.json", array(), 'GET');
$themeList = json_decode($themeList['response'], true);
$themeId = $themeList['themes'][0]['id'];
$themePath = "/admin/api/2019-07/themes/{$themeId}/assets.json?asset[key]=layout/theme.liquid&theme_id={$themeId}";

$customTheme = shopify_call($token, $shop, $themePath, array(), 'GET');
$customTheme = json_decode($customTheme['response'], true);
$currentTheme = $customTheme['asset']['value'];
$pos = strpos($currentTheme, "</body>");
$str = "{% include 'back-to-the-top' %}\n";
$currentTheme = substr_replace($currentTheme, $str, $pos, 0);

In conclusion, I reckon only the PRETTY_PRINTing, variable formatting, and the spacing should be changed.  The choice of how/when to declare data is mostly about personal taste.


As poined out in the comments, your current approach might be too slow for your goal of "about 4-5 seconds". Depending on what's your actual use case, using an index might indeed be a good idea. This is similar to how internet search engines do it.

To create the index:

create a map Map<String, List<File>> for holding the association of search terms to files
go through all your files, and for each word in each file, add that file to the list corresponding to that word in your index map
you might want to skip common words, such as "a", "and", "the", etc., or you could even apply a stemmer to drastically reduce the variability in words

Once you've created the index (which could take quite some time), you just have to look up the search word in that index to get the list of files that contain the word (or a linguistic variant of it, if you used a stemmer).

As said before, the applicability of this approach depends heavily on your actual use case. If the files contain genetic sequences and you are searching a certain pattern, this probably won't help much. Even if you are searching for some complex phrase this might not work, as you'd have to add each possible (sub) phrase to the index. But if you are looking for individual words in ordinary text files (or HTML or the like) this might work.

Update: Since you seem to indeed search for complex phrases, you could try the following:

create the index, as desribed above, optionally using a stemmer
search for each word in your phrase (or the stemmed version thereof) in your index
for each file that, according to your index, contains all the words, do a full-text search for the original phrase

Finally, if this still does not cut it, you could also create indexes for word bigrams or even trigrams.


Don't Repeat Yourself (DRY)

    public void enqueue(int valueToAdd){
        if(amountInQueue == queue.length){
            throw new FullQueueException();
        }
        else if(rearIndex == queue.length -1){
            rearIndex = 0;
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
        else if(amountInQueue == 0){
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
        else{
            rearIndex++;
            queue[rearIndex] = valueToAdd;
            amountInQueue++;
        }
    }

There's some duplicate code here.  Consider

    public void enqueue(int valueToAdd) {
        if(amountInQueue == queue.length) {
            throw new FullQueueException();
        }

        if (rearIndex == queue.length -1) {
            rearIndex = 0;
        }
        else if (amountInQueue == 0) {
            frontIndex = 0;
            rearIndex = 0;
        }
        else{
            rearIndex++;
        }

        queue[rearIndex] = valueToAdd;
        amountInQueue++;
    }

You don't need to use an else after you throw an exception, as it will leave the function immediately.

More importantly, other than the exceptional case, all the cases have the same two lines.  So take them out of the if/else construct.  In the empty queue case, there's nothing left.  You can clear the front and rear indexes if you want.  Or you can remove that case entirely.

    public int dequeue(){
        int frontValue = frontIndex;
        if(amountInQueue == 0){
            throw new EmptyQueueException();
        }
        if(frontIndex == queue.length -1){
            frontValue = queue[frontIndex];
            frontIndex = 0;
            amountInQueue--;
        }
        else{
            frontValue = queue[frontIndex];
            frontIndex++;
            amountInQueue--;
        }
        return frontValue;
    }

Similarly, this could just be

    public int dequeue(){
        if (amountInQueue == 0) {
            throw new EmptyQueueException();
        }

        frontValue = queue[frontIndex];
        amountInQueue--;
        frontIndex++;
        if (frontIndex == queue.length) {
            frontIndex = 0;
        }

        return frontValue;
    }

You don't have to set the return value before the exceptional case, as it won't be used if the exception is thrown.

Only the modifications of frontIndex need to be in the if/else.

If you always increment, then you don't have to subtract in the comparison.  Saving one math operation in the common case and using the same number in the uncommon case.

Interfaces

There is a Queue interface.  You might consider having this code implement that interface.  That will force you to name the operations as expected.

public class Queue2 implements Queue {

As is, someone used to the other queue might have trouble finding the equivalents of add, remove, and peek.

Bug?

In your valueAtFront and valueAtRear methods, you don't verify that there are elements in the queue.  So these may return garbage.  They should either throw an exception or return something like null when the queue is empty.

Resize

It's pretty common to allow queues to resize.  Something to consider for future development.


"command preprocessing" with bash - string parsing and handling pipes

The infinite loop with break, counter, and multiple invocations of cut looks clumsy at best. Consider instead

IFS=";"
for segment in $data; do
    # your logic here
done

Similarly, cutting the segment is unnecessary:

    IFS=":"
    set $segment
    export $1=$2
    IFS=";"

does the same job.
I don't understand the goal not achieved yet. The script has no knowledge where its input coming from. Whoever calls your script is in the position to redirect it at will. Perhaps, close stdin before invoking it?


We should be using auto-layout.  Not being as comfortable with auto-layout is not an excuse to not use it.  Manually setting rects is not very good at all.  Manually set rects don't play well with rotation.  Manually set rects mean we probably need a special set of code for iPad versus iPhone.  Manually set rects mean we probably need a special set of code for iPhone 4 vs iPhone 5 vs iPhone 6 vs iPhone 6+.

I'm not really going to touch the createSubviews method, which has some issues that should be address, but I do want to point out the problems with createViewRects: and how we can more easily write this code with auto-layout and using the Visual Format Language quite simply.

The method sets up the position for four views.  The spacing follows two rules:

Each view has an X of 16 pixels from the left edge.
Each view has a Y that leaves a gap of 8 pixels between the other views (plus 8 pixels between the top of the super view and the top of the top view and 8 pixels between the bottom of the super view and the bottom of the bottom view).

For this, I'm going to assume that bgView is a scroll view.  Scroll view's content doesn't really work particularly well with multiple top-level subviews.  Instead, we give the bgView a single subview and add all of the subviews to that subview.  This will allow auto-layout to work well.

Let's define a couple dictionaries to use with VFL.

For starters, so we can put them in a dictionary, let's use NSNumber objects rather than CGFloat for our metrics:

NSNumber *padding = @16.0;
NSNumber *rowPadding = @8.0;

We don't need a total height.  Auto-layout will resolve this for us.  Anyway, creating a dictionary is as simple as this:

NSDictionary *metrics = NSDictionaryOfVariableBindings(padding, rowPadding);

Now, using a mutable string, a mutable dictionary, let's set up these constraints:

int viewIndex = 0;
NSMutableString *vertConstraintsStr = [@"V:|-[rowPadding]-" mutableCopy];
NSMutableDictionary *views = [NSMutableDictionary dictionary];

UIView *backgroundView = [[UIView alloc] init];

for (UIView *view in views) {
    NSString *viewKey = [NSString stringWithFormat:@"view%i", viewIndex];
    ++viewIndex;

    [backgroundView addSubview:view];

    views[viewKey] = view;

    view.translatesAutoresizingMaskIntoConstraints = NO;

    [vertConstraintsStr addFormat:@"[%@]-[rowPadding]-", viewKey];

    NSString *horizConstraintStr =
        [NSString stringWithFormat:@"H:|-[padding]-[%@]", viewKey];

    NSArray *horizontalConstraints =
        [NSLayoutConstraint constraintsWithVisualFormat:horizConstraintStr
                                                options:0
                                                metrics:metrics
                                                  views:views];

    [backgroundView addConstraints:horizontalConstraints];
}

[vertConstraintsStr addString:@"[rowPadding]-|"];

NSArray *verticalConstraints =
    [NSLayoutConstraint constraintsWithVisualFormat:vertConstraintStr
                                            options:0
                                            metrics:metrics
                                              views:views];

[backgroundView addConstraints:verticalConstraints];

[self.bgView addSubview:backgroundView];

Ultimately, this is more lines of code, but this is much more flexible.

Consider what happens if we were to change the size of one of our subviews.  With your code, we must be sure to call createViewsRect: each time any view changes sizes in order to ensure everything still looks right.  With auto layout, the view will automatically adjust to the new size of one of the subviews.  Plus, now you've got some experience working with auto layout so you'll be less intimidated and more comfortable with it in the future, particularly when you want to start doing more complicated layouts.


Implementation of FastICA in multithreading approach

The code is a mess, but I can tell you that it will spin forever right here:

std::thread process_thread(&MainProcess::controller,&p3);

This starts controller running immediately.

void controller()
{
    while(true)
    {
        while(IsPrepare==numberOfThreads)
        {
            std::lock_guard<std::mutex> lk(lock);
            std::cerr<<"Now controller is checking fastICA is converged or not "<<std::endl;
            std::fill(checkedEvent.begin(), checkedEvent.end(), 0);
            IsPrepare=0;
            data_prepare.notify_all();
        }
    }
}

IsPrepare is 0, and numberOfThreads is 10, and there's no synchronization to worry about here (no locks, no atomics), so we can definitely say that 0 == 10 is invariably false. Thus controller reduces to

void controller()
{
    while(true)
    {
        while(false) {}
    }
}

Okay, so that thread won't be doing anything anytime soon.
And with that code out of the way, the rest is pretty much irrelevant; it looks to me as if it will end up blocking forever, since there's nobody left to notify the condition variable.

Your problem might be suited to a TBB flowgraph; consider using TBB instead of hand-rolling your own stuff.


LINQ query using StartsWith and Contains to limit the results for an autocomplete field

Naming
Instead of term maybe searchTerm would be better. As in your second example you name the IEnumerable<> variable suppliers, your method would be better named as AutocompleteSuppliers.

Review

A Boolean variable can be evaluated just by using the variable, so && l.IsSupplier == true can be replaced by && l.IsSupplier. As an evaluation of an boolean is faster as the comparing of an int (assuming AdministrationId  is an int) we change the order of the where condition like

List<Relation> relations =
    db.Relation
        .Where(l => l.IsSupplier &&
               l.AdministrationId == Helpers.Session.AdministrationId)

Inside the foreach loop you are first checking if the Relation.Name is starting with term and if not, you are checking if term is contained inside Relation.Name. This will be faster if term is often the starting of the name, but will be slower if it is contained as of the double check.
So let us just remove the StartsWith().

Your combination of the Linq statement and the loop does look ok, but will produce different results than in the Autocomplete() method, as you are selecting Relation.Name instead of Relation.Name.ToLowerInvariant().

Refactoring

As this refactoring is based on the original method we use the Select() with ToLowerInvariant() first and are checking afterwards if it contains the searchTerm

public ActionResult AutocompleteSuppliers(string searchTerm)
{
    searchTerm = searchTerm.ToLowerInvariant();

    IEnumerable<string> suppliers = db.Relations
        .Where(l => l.IsSupplier && l.AdministrationId == Helpers.Session.AdministrationId)
        .Select(l => l.Name.ToLowerInvariant())
        .Where(s => s.Contains(searchTerm))
        .OrderBy(s => s)
        .Take(5);

    return Json(suppliers, JsonRequestBehavior.AllowGet);

}


TypeScript definitions for Server-Sent Events

According to your definition file, I'm assuming there's a global class called EventSource

If that's the case, I have the following improvements:

Avoid Function (or Object or Array), describe the signature accurately (like you did with onmessage). If you don't know the return type or the argument, apply any liberally. At least you're explicit about not knowing.
TypeScript has literal string, number and enum types, so you could do something like CONNECTING: ReadyState.CONNECTING

All in all, it's a fine definition file.


Use a table driven menu

The menu to select from /bin, /sbin and other is very repetitive.
A table-based approach would be more compact, easier to write and maintain.
Try to use an array, as you did in other places of the script.

First, put the directories in an array, for example:

dirs=('' /bin /sbin /usr/bin)  # fill the rest

Note that I added a dummy empty first element.
This is to make the 1-based indexes of your menu work with the 0-based array indexes.

Build the menu from this array using a counting loop from 1, the first non-empty element:

for ((index = 1; index < ${#dirs[@]}; index++)); do
    echo "$index) ${dirs[$index]}"
done

To validate the user input, simply check if ${dirs[$index]} is empty.
If yes, the input is invalid.

Security

  Maybe it is normal to have plain text files in this directory or maybe this is something I did unintentionally when experimenting writing this script. (An earlier version of this script wrote all the man pages to plain text files.)

No, it is not normal to have .txt files in any of those directories.
So I guess your earlier script put them there.
But a normal user should not have write access to these directories.
Which seems to suggest that you're playing with a privileged account,
possibly root.
That's a bad idea, avoid using root casually.

Simplify

You can simplify [[ $n = 'b' || $n = 'B' ]] using pattern matching: [[ $n == [bB] ]].

Strangeness

You don't need the -1 here.

menu=( $(ls -1 ${dir}) )

When inside $(...), ls does not columnize its output.

In this code, I don't see why you need basename:

echo "$(( i++ ))) $(basename $m)"

It seems the value of $m will always be a simple filename without a path part.


Logic

Consider the if condition, which I have reproduced below with different alignment for ease of viewing…

if (year%4==0 and year%100==0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400!=0):
    …

It's clear that the first two lines can be collapsed due to redundancy.  As for the third line, any number that is not divisible by 100 is automatically not divisible by 400 as well.

if (year%4==0 and year%400==0)or \
   (year%4==0 and year%100!=0):
    …

That can be further simplified to:

if (year%4==0 and (year%100!=0 or year%400==0)):
    …

Formatting

Please take care to follow Python formatting conventions, especially the consistent indentation by four spaces, especially since whitespace is significant in Python.

year = int(raw_input("Input year: "))

if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print str(year) + " is a leap year"
else:
    print str(year) + " is NOT a leap year"


Facility to run code explicitly implemented in a base class that does not follow CA1033

This is a pretty tidy implementation, not much to say here. A couple very minors:

This is a bit hard to read:

return new ReturnMessage(.Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);

I'd split it up:

var targetMethod = map.TargetMethods[Array.IndexOf(map.InterfaceMethods, (MethodInfo)methodCall.MethodBase)];
return new ReturnMessage(targetMethod.Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);

Clone the argument array instead of explicitly copying it:

var args = (object[])methodCall.Args.Clone();

Expresses the semantics on a more compact way.
For me this seems to be some sort of method forwarding so I'd possibly consider renaming it and maybe turning it into an extension method (I like the syntactic sugar of it). Something along these lines:

public static TInterface ForwardToBase<TBase, TInterface>(this TBase @this)
    where TBase : TInterface
    where TInterface : class
{
    return (TInterface)new ExplicitImplementationProxy(typeof(TBase), @this).GetTransparentProxy();
}

In which case the call would then read as:

this.ForwardToBase<BaseClass, IExampleInterface>().InterfaceMethod()


Counting different kinds of line terminator characters in files

Your program works fine and you are correctly using goroutines, but the code isn't very idiomatic.

Producer/Consumer architecture

What we have here is a typical producer/consumer scenario. The producer is filepath.Walk() wich returns a list of files, and the consumers are goroutines executing regex on file content.

So instead of the splitIntoChunks() method, we could just have a chan string: the producer sends file names to the channel, and the consumers loop over it and parse the file content.

This have two main advantages:

code is easier to read
producer and consumer can work in parallel

So the code would looks like

results := make(chan Endings, 2) // chan to get the results of each worker
var wg sync.WaitGroup
wg.Add(2)
files := make(chan string, 1000) // channel containing file list
for i := 0; i < 2; i++ {
    go run(files, results, &wg) // start the producers
}
filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
    if !f.IsDir() {
        files <- path // feed the channel
    }
    return nil
})
close(files)
wg.Wait()
close(results)

Work on []byte rather than on string

This is a general advice regarding performances: always prefer working on []byte instead of working on string to avoid extra allocations.
The regex package has methods to work on string or on byte slice, so instead of

fileContent, err := ioutil.ReadFile(filename)
c <- countEndings(string(fileContent))
...
x := len(crlf.FindAllStringIndex(s, -1))

we can just use

fileContent, err := ioutil.ReadFile(fileName)
...
x := len(crlf.FindAllIndex(fileContent, -1))

Don't panic

The code shouldn't panic on every error. For example, if the user running the program don't have the permission to read a file in searchDir, the program should not crash but rather log the error

so avoid method like this:

func check(e error) {
    if e != nil {
        panic(e)
    }
}

instead handle the error localy:

fileContent, err := ioutil.ReadFile(fileName)
if err != nil {
    fmt.Printf("fail to read file %s: %v\n", fileName, err)
}

Other consideration

It's better to define regex as global var:

var (
    crlf = regexp.MustCompile("\r\n")
    lf   = regexp.MustCompile("\n")
)

It's also better to use the flag package to parse arguments instead of relying on os.Args

Here is the final version of the code:

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "regexp"
    "sync"
)

var (
    crlf = regexp.MustCompile("\r\n")
    lf   = regexp.MustCompile("\n")
)

type Endings struct {
    crlf, lf uint
}

func (e *Endings) countEndings(fileName string) {
    c, err := ioutil.ReadFile(fileName)
    if err != nil {
        fmt.Printf("fail to read file %s: %v\n", fileName, err)
    }
    x := len(crlf.FindAllIndex(c, -1))
    y := len(lf.FindAllIndex(c, -1))

    e.crlf += uint(x)
    e.lf += uint(y - x)
}

func run(files <-chan string, results chan<- Endings, wg *sync.WaitGroup) {
    e := &Endings{}
    for f := range files {
        e.countEndings(f)
    }
    results <- *e
    wg.Done()
}

func main() {

    searchDir := flag.String("dir", "dir", "directory to search")
    nWorker := flag.Int("n", 2, "number of worker")
    flag.Parse()

    results := make(chan Endings, *nWorker)

    var wg sync.WaitGroup
    wg.Add(*nWorker)
    files := make(chan string, 1000)
    for i := 0; i < *nWorker; i++ {
        go run(files, results, &wg)
    }
    filepath.Walk(*searchDir, func(path string, f os.FileInfo, err error) error {
        if !f.IsDir() {
            files <- path
        }
        return nil
    })
    close(files)
    wg.Wait()
    close(results)

    count := &Endings{}
    for e := range results {
        count.crlf += e.crlf
        count.lf += e.lf
    }
    fmt.Printf("crlf: %d, lf: %d\n", count.crlf, count.lf)
}

Performance

The new code is slightly faster:

old:

$ time ./test ~/go/src/golang.org
crlf: 6231, lf: 1589462
./test ~/go/src/golang.org  1,78s user 0,23s system 167% cpu 1,201 total

new:

$ time ./test -dir ~/go/src/golang.org -n 6
crlf: 6231, lf: 1589462
./test -dir ~/go/src/golang.org -n 6  1,48s user 0,18s system 181% cpu 0,911 total


Mutex Protected Object (scoped object wrapper)

Access

I don't like the fact that Access gives you a reference to the object directly. This leads to issues with somebody accidentally keeping a reference to the object after the Accesses object is destroyed or accidentally making a copy of the object.

T&  myRef = wrapped.access().obj_;   // Now I have a reference to the object
                                     // But the Accesses object is gone.

myRef.doStuffWithNoLock();

// or

T   myCopy = wrapped.access().obj_;  // I made a copy of the object.

How about Access delegating all accesses via operator ->? That way you don't leak the object to external code.

class Access
{
    public:
        T* operator->() {return &obj_;}
    private:
        T&  obj_;
};

Now you can use Access like it was a T*:

auto foo = wrapper.access();
foo->fun1(args);
foo->fun2(args);

Initializer list

The order of initialization of members is the order of declaration. If you define the order deferently in the initializer list this can be confusing (most compilers will warn you about it).

class Access {
    public:
    Access(std::mutex& m, T& obj)
        : sl_(m)             // This is not the order they are
        , obj_(obj)          // initialized in. The obj_ will be done first
    {}

    T& obj_;

    private:
    std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
};

Best practice is to keep the initializer list in the same order as the declaration order in the class.


A function determining intervals of values greater than threshold

(You can skip right to TL;DR for a simpler approach)

Your function actually determines the indices of list elements that are above a threshold. In Haskell, when you have a list, an index is not the idiomatic way to represent its items. What do you want with those indices?

Agreed, your version is hard to read. For another approach, I start with

intervalsT :: [Bool] -> [(Int, Int]

and notice that the group function might come in handy to collect subsequent equal elements.

*Main> group [True,True,False,False,True]
[[True,True],[False,False],[True]]

mapping length will result in [2,2,1], which is a step closer to the indices. To turn [a,b,c] into [0,a ,a+b, a+b+c], the function scanl' is perfect:

*Main> scanl' (+) 0 [2,2,1]
[0,2,4,5]

which we can zip with its own tail. But wait! We lost information whether something is above or below threshold.
zip it again with the grouped Bools, filter based on the bools, throw away the bools. This yields:

TL;DR

intervals p = intervalsT . map (>p)
intervalsT :: [Bool] -> [(Int,Int)]
intervalsT xs = let grouped = group xs
                    idx = scanl' (+) 0 . map length $ grouped
                    ivs = zip idx (map (subtract 1) $ tail idx)
                 in map snd $ filter fst $ zip (map head grouped) ivs


1) I would not expose IQueryable via IRepository. IQueryable is still a virtual set of objects that hasn't been retrieved from a database yet. If you have (for example) some problem with database performance, you would have to go through all your application to find out what queries you construct and send to DB.

Instead I would expose methods for specific purposes on specific repositories. These methods would return IList<T> (or ICollection<T>, depends on your preference). Then you have all the code for accessing a database on a single place. For example, your IBookRepository would look like:

public interface IBookRepository : IRepository<Book>
{
    Book FindByIsbn(string isbn);
    IList<Book> FindByAuthor(int authorId);
    IList<Book> FindByTitle(string title);
    ...
}

And your generic repository would be:

public interface IRepository<T>
{
    T FindById(int id);
    void AddOrUpdate(T entity);
    void Remove(T entity);
}

2) It is not necessary to make your repositories disposable. So far you have nothing to dispose there. Your repositories get IDbContext (which is IDisposable) from outside, thus it should not be disposed inside a repository. If your repositories get created via an IoC container, the container will also handle disposing of all dependencies.

3) UnitOfWork: You can implement UnitOfWork pattern if you want to (e.g.) wrap all your database work inside transactions. I would recommend such IUnitOfWork interface:

public interface IUnitOfWork
{
    void SaveChanges();
    void BeginTransaction();
    void CommitTransaction();
    void RollbackTransaction();
}

Implemetation of IUnitOfWork would have dependency on IDbContext. Then the only places where you work with a database (via IDbContext) are UnitOfWork and Repository classes. At places where you want to save your work to a DB, use IUnitOfWork, not IDbContext.


write an algorithm for: x / 2 + 100 * (a + b) - 3 / (c + d) + e * e

a, c - word,
b, d - byte,
e - doubleword,
x - qword

Because your biggest number is 64 bits (x is a qword), your final result will have to be 64 bits too!
Your first operation was to divide the qword in x by 2. You seem to expect that this result will fit in just a single dword because you've moved the quotient in the EBX register. You cannot make this assumption and worse the division could easily produce a divide exception if the quotient doesn't fit in 32 bits.
For the solution you should be aware that dividing by 2 is actually simply a shift to the right.
mov   ebx, [x]
mov   ebp, [x + 4] ; EBP:EBX is x
sar   ebp, 1
rcr   ebx, 1       ; EBP:EBX is x / 2

This means that you'll have to scale up the other calculations too in order to add them to EBP:EBX using:
add   ebx, ...
adc   ebp, ...

Because addition is associative, you can start by calculating the e * e part. You did not rearrange the expression and had to move around some more the registers in the end. Not a big deal, but nicer my way:
mov   eax, [e]
imul  eax
add   ebx, eax
adc   ebp, edx

Then comes 100 * (a + b):
movsx eax, word [a]
movsx edx, byte [b]
add   eax, edx       ; eax = a + b
mov   edx, 100
imul  edx            ; edx:eax = 100 * (a + b)
add   ebx, eax
adc   ebp, edx

I'll leave 3 / (c + d) to you...
... and finally the end will be:
sub   ebx, eax
sbb   ebp, edx
mov   [result + 0], ebx
mov   [result + 4], ebp

did I make it unnecessarily complicated?

It was a bit hard to read your program because you didn't insert some blank lines between the different operations.

You don't need to write a size tag (byte, word, dword) if the register involved already implies the size. In mov dword [result + 0], eax the dword tag is redundant.

Best have the comments in the program aligned above each other.

Reread carefully to avoid typos like in:
  mov ecx, edx ; ecx:edx = x / 2 + 100 * (a + b) - 3 / (c + d)

Should be ECX:EBX.

To compute a square: once you've loaded the number in the register, you can multiply by that same register and not turn to the memory a second time like you did:
  mov   eax, [e]
  imul  eax        ; Don't write "imul dword [e]"


Computing the number of permutations of n consecutive numbers

In addition to Jamal's good points:

1: Consider sorting your #includes alphabetically. It's not a big issue, but I think it looks more tidy, and it's easier to see if something is already included or not.

2: Consider typedef vector<string> StringCollection (or some other meaningful name). This makes it easier to change the underlying data structure later, and makes the code look cleaner.

3: If you are using C++11, I'd write the for loop like this:

for (auto const& number : permutations) {
    myfile << number << endl;
}

Since you are learning, I see no reason not to get into C++11 right away.

4: Tutorials and the like often use mySomething as identifiers. my is a bad identifier prefix. Instead, write what role it has or what it represents. outputFile is much better than myFile.

5: Initialize variables right away. The std::ofstream constructor takes a filename, so there is no need to first initialize and then call open().

6: Instantiate variables as late as possible. In your rotateRt() (which should be called rotateRight(), by the way), you don't have to create your strings unless the last else triggers. Change it to this:

else {
    string a = input.substr(0, len - 2);
    string b = input.substr(len - 1) + " ";
    return b + a;
}

The same applies to for example ostringstream convert.

When you instantiate a variable as late as possible, you avoid constructing it unless you really have to. "As late as possible" implies as close as possible to the relevant context, which makes the code easier to read.

7: Consider rewriting permute() to reduce nesting.

8: Your code would normally be better suited as a class. You don't have to think too much about this yet, since you just started with C++. It's a good exercise to refactor this to use classes later.

9: In the case of int len = input.length();, you should use std::size_t instead of int.

10: Prefer C++-style comments: // (Effective C++ explains why, so I won't repeat it here.)

11: Use more whitespace. Especially more vertical whitespace. Insert an empty line in logical places to make your code much more readable.

12: You don't modify or copy the string you pass to rotateRt, so it should be reference-to-const instead: rotateRt(string const& input). (If you prefer, you can write const string&, it's the same thing.)

13: Consider rewriting permute() so that it's not recursive. Recursive functions that create a couple of objects can quickly chew up a lot of memory, and are often not very efficient. In short, your permute() function can be improved a great deal.

14: Consider refactoring the file name out into a constant:

const string filename = "rosalind_perm.txt";

This way it's easier to find if you have to change it, and by using the constant you are guaranteed you will only have to change it in one location.


NodeJS executing multiple database queries using async library

A couple of helper functions will aid in flattening your callback chain:
function getConnection() {
  return new Promise((res, rej) => {
    pool.getConnection(function (err, connection) {
      if (err) {
        rej(err);
      } else {
        res(connection);
      }
    });
  });
}

function query(connection, sql, params) {
  return new Promise((res, rej) => {
    connection.query(sql, params, function (err, rows) {
      if (err) {
        rej(err);
      } else {
        res(rows);
      }
    });
  });
}

Then you can do something like:
async function step_1(connection) {
  const rows = await query(connection, 'step 1 query');
  return rows.insertId;
}

function step_2(connection, id) {
  return query(connection, 'step 2 query', id);
}

function step_3(connection, id, result) {
  return query(connection, 'step 3 query', id, result);
}

exports.handler = async (event) => {
  const connection = await getConnection();
  try {
    const id = await step_1(connection);
    const rows = await step_2(connection, id);
    const result = await step_3(connection, id, rows);
    return JSON.stringify(result);
  } finally {
    connection.release();
  }
};


Grouping objects that have the same attributes

public class People

The class is named People, but it should probably be called Person. Every instance of the class is another Person, not another People.

private String name;
private String age;
private String address;

It might be worth to consider splitting up the name attribute into a firstName and lastName, because otherwise it could be difficult to compare two peoples' last names, for example.

Representing age as a String is not the best fit. Age is usually a whole number, i.e. an integer, so it would be better to use int instead. Then you could also more easily compare ages by e.g. calculating the age difference between two people. Strings should be used for things that are actual text or at least sequences of characters.

Even better than having an age attribute at all could be to have a dateOfBirth instead, represented by the Java type Date. Age is just an implicit attribute of a person that could change any day, and so instead of saving it in a variable you can calculate it from the date of birth and the current date whenever you need.

I'd say that representing address as a String is fine, but could be worth getting its own class with street, zipCode etc., then saving a reference to an Address inside the Person.

public boolean isAttributeEqual(final People dupPeop)

isAttributeEqual does not tell you which attribute it checks. The singular name implies that one attribute is being checked, but what the method actually does is compare all attributes. There is a convention for that in Java, which is to override the equals method which the class inherits from Object.

List<People> asList = Arrays.asList(new People("Sri", "28", "TN"), new People("Sri", "28", "TN"), new People("Sri", "28", "TN"),
    new People("Pri", "28", "TN"));

List<People> groupSimilar = groupSimilar(asList);

It can be more readable if a variable name states what it contains, independently from how it came to be. asList is the operation that creates the list, but that will not be relevant anymore if you use the variable later on in the code. So, assuming the rename of the class that I recommended earlier, you could have something like this:

List<Person> persons

or

List<Person> people

Similarly, groupSimilar groups similar people, but the result is a list of similar people:

List<Person> similarPeople = groupSimilar(people);

or

List<Person> similarlyGroupedPeople = groupSimilar(people);

Also, it seems to me that what groupSimilar does is to find the people that are duplicated in the same list, rather than actually grouping similar people, so I would rename the variable and the method to this:

List<Person> duplicates = findDuplicates(people);

  public static List<People> groupSimilar(final List<People> people)
  {
    List<People> duplicatePeople = new ArrayList<>(people);
    for (Iterator<People> iterator = duplicatePeople.iterator(); iterator.hasNext();)
    {
      People people2 = iterator.next();
      for (People orignalPeople : people)
      {
        if (!orignalPeople.equals(people2) && orignalPeople.isAttributeEqual(people2))
        {
          iterator.remove();
          people2 = iterator.next();
        }
      }
    }
    return duplicatePeople;
  }

Rather than manually controlling the iterator, i.e. checking hasNext() and advancing it with next(), I would use a simple for-each loop for the outer loop, just like your inner loop already is.

Since you are using the default implementation for equals which is inherited from Object, it is equivalent to a reference equality check, which can be done on reference types using the == operator (!= for reference inequality).

So, assuming that you replaced your isAttributeEqual with an overriding implementation of equals, and use ==/!= instead of the default equals, I would rewrite the method like this:

public static List<People> findDuplicates(final List<People> people) {
    List<People> duplicates = new ArrayList<>();

    for (Person person : people) {
        for (Person person2 : people) {
            if (person != person2 && person.equals(person2) {
                duplicates.add(person);
            }
        }
    }

    return duplicates;
}

The code also becomes, in my view, more easily understandable by only adding the people that are verified as duplicates, rather than declaring all as duplicates and removing those that are not.


Removing extra spaces without using a regular expression

Your code is buggy: it fails to copy the last character.

As @Mat'sMug says, defining a function would be a good idea.

The task can be done with one array and one loop.

public static String compressConsecutiveSpaces(String str) {
    if (str.isEmpty()) return str;
    char[] chars = str.toCharArray();
    int dest = 1;
    for (int src = 1; src < chars.length; src++) {
        if (!(chars[src - 1] == ' ' && chars[src] == ' ')) {
            chars[dest++] = chars[src];
        }
    }
    return new String(chars, 0, dest);
}


Dropdown menu that opens on click using plain Javascript

Overall the code looks fine. I just have a couple suggestions about the JavaScript and CSS.

JS

querySelectorAll vs getElementsByClassName

Generally document.getElementsByClassName will be quicker than document.querySelectorAll (see this post for more information) and the former also returns a live HTMLCollection so it wouldn't need to be queried each time. Bearing in mind that deactivateAllDropdownTriggers() looks for elements with both class names dropdown-trigger and active, only the latter is really needed. If active applies to other elements, then perhaps a name like active-dropdown would help narrow down elements. In order to iterate over the items in that collection, they would need to be put into an array - that can be done with the spread operator ...

const activeElements = document.getElementsByClassName('active');
function deactivateAllDropdownTriggers() {
  [...activeElements].forEach(elem => elem.classList.remove('active'));
}

CSS

Useless class on-click

It appears that the on-click class is only utilized in the last selector (i.e. .dropdown .dropdown-trigger.on-click.active + .dropdown-menu) but that class name could be removed since it doesn't appear to be used anywhere else

default values

Some rules set values to what should be the default values - e.g. margin: 0 for the unordered list and list items, and cursor: pointer for the anchors. Those shouldn't be needed unless there are other styles matching the selectors that would add different values - e.g. for other page contents or a browser/plugin stylesheet


You're first building a list of all permutations of the input word, and then using that to filter the dictionary. The problem with this approach is that the number of permutations is huge — for 10 distinct letters, there are 10! = 3628800 permutations. In comparison, /usr/share/dict/american-english is only about 100k words, and /usr/share/dict/american-english-huge is about 340k — less than 10 times the number of permutations. This kind of pretreatment can be useful, but only if the variable data to be processed afterwards is large or if the amount of computation per data pair is very large, neither of which are the case here.

There's cheap way to check if two words are a permutation of each other: sort their letters. Two words are permutations of one another if and only if sorting their letters returns identical results.

def is_a_permutation(word1, word2):
    return sorted(word1) == sorted(word2)

Here, you only want to see if each dictionary word consists of number_input elements of split_letters. This is the case if the length of the word is number_input and the word is a subsequence (not necessarily consecutive) of split_letters — after sorting both the word and split_letters.

I don't think the Python standard library has a subsequence test (only a substring test, i.e. where the elements must be consecutive). A cheap way to implement it for lists of characters is to build a regular expression and let the regular expression engine build an optimized automaton internally.

def subsequence_re(word):
    return re.compile('.*'.join([re.escape(letter) for letter in sorted(word)]))

That's a tiny precomputation, after which you get cheap processing on each dictionary word. You can then process the dictionary as a stream, so your program will use constant memory with respect to the dictionary size (and linear memory in the size of the target permutation, instead of factorial).

Here's a demo program where I don't copy the whole input logic, I just take the letters from the command line and the dictionary from standard input.

#! /usr/bin/env python
import re
import sys

def subsequence_re(word):
    return re.compile('.*'.join([re.escape(letter) for letter in sorted(word)]))

def filter_file(target_length, target_re, data_file):
    for line in data_file:
        word = line[:-1]
        if len(word) == target_length and \
           re.search(target_re, ''.join(sorted(word))):
            yield word

if __name__ == '__main__':
    target = sys.argv[1]
    for word in filter_file(len(target), subsequence_re(target), sys.stdin):
        print word

There are other ways to test if a word is a permutation of the number_input letters among split_letters. One way is to build a dictionary (in the sense of a Python dict) where the keys are the distinct letters in split_letters and the values are the number of occurrences of each letter. To see if a word matches, build a similar dictionary and check if the number is smaller (entries not in the reference dict count as an immediate failure); note that the word must also have the target length. As a follow-up exercise, implement and benchmark this method.


Return "support count" for a given itemset after searching a large list of transactions

One simple improvement will be to realize that sum can take a generator expression. It does not need an intermediate list which will take up a lot of memory if the number of transactions becomes large. Same goes for any, which will even use short-circuit evaluation in that case. So you can write:

count = sum(1 for row in spec_rows if items in row)

and

count = sum(1 for row in spec_rows if any(item in row for item in items))

Secondly, your specs rows_indiv seem to be used exactly once (and have the length of the number of entries). You could make it a generator to save a lot of space (and time for memory allocation).

rows_indiv = (set(a) for a in rows)

On the other hand, this is not true for rows_all_type_combos, because some of the list's members are being re-assigned in the for loop after its construction.


NIO2 and ByteBuffer use for reading variable length messages

Write some JavaDoc!

As stated above, I was very confused by your code. However, if your methods included JavaDoc, then I wouldn't be so confused by the names.

Here is an example of JavaDoc on a simple method:

/**
    Returns the sum of both of the parameters.
*/
public int add(int a, int b) {
    return a + b;
}

Note the /**? This is required for it to be valid JavaDoc.

In more complicated functions where the parameters aren't clear or the return value isn't clear, you can include something like this in your JavaDoc:

@param nameOfParameter -- description/purpose of parameter
@return -- description of return
        -- description of return
        -- description of return

You would have multiple -- description of returns if there were multiple potential return values.

There is no point in having a do/while loop where the condition being checked is true; if it were just a normal while loop, it would run atleast once anyway.

I recommend that you change your do/while to just a while as while loops are much more common.

I can not go into the way you tried to solve the problem because I am having trouble understanding your code. I believe this is just on me, but I think that having more documentation would help anyway.


Project Euler #2 (classic) - Sum of even fibonacci numbers below 4 million

Notation

It is a common convention in Lisp to avoid uppercase (or mixed lowercase and uppercase) letters in identifiers (symbols), so for instance use l instead of L, or fibo-nums instead of fiboNums, etc.

Variables

If you type your function in a Common Lisp interpreter/compiler, you will receive warnings undefined variable for A B and next. This is because you should introduce local variables before using them with the let or let* special operators (let* is needed if you need to initialize variables with the value other variables introduced). Then, you can assign these variables, as well as all the other type of variables, with setf, that can assign several variables in sequence.  So, for instance:

(defun fibo-nums (max-num)
  "list of fibonacci numbers that are below max-num"
  (let* ((a 1)
         (b 2)
         (next (+ a b)))
  (loop while (< b max-num)
    do (setf next (+ a b)
             a b
             b next)
    collecting a)))

Primitive operators

The definition of filter is not necessary, your definition is equivalent to the primitive function remove-if-not.

Algorithm

In this case there is no need of generate a list of Fibonacci numbers and then visiting it, it is sufficient to sum the numbers while generating them:

(defun sum-of-even-fibo (max-num)
  (loop for a = 1 then b
     for b = 1 then next
     for next = (+ a b)
     while (< a max-num)
     when (evenp a)
     sum a))

Finally, since loop is a powerful macro with a complex syntax, here is an alternative version with the more simple macro do*, which has also a syntax more “lisp-style”:

(defun sum-of-even-fibo (max-num)
  (do* ((sum 0)
        (a 1 b)
        (b 1 next)
        (next (+ a b) (+ a b)))
       ((> a max-num) sum)
    (when (evenp a)
      (incf sum a))))


Optionals do not improve your code. You're using if statements and null checks just like they are intended to be used. There is no need to improve anything there.

Edit: If-statements and null-checks are not evil. There is no need to try to get rid of either one and Optionals were not intended to replace them. The evil is having an API made by someone else and not knowing if it returns a null or not. Optionals were intended to give the person reading the code and the compiler compiling it a strongly typed fact about the possibility of a method return value not existing.

If I have to try to find something worth mentioning from your code it's the use of heavy String.format to create a trivial exception message. Just use concatenation like in the logging statements. :)


Breadth-First Search heuristics to find solution to Water Jug Challenge

I think that the function that computes new states could be simplified in this way:

vector <pair<int,int> > newStatesSet(pair<int,int> state){
  //generating all possible states from a given initial state
  vector<pair<int,int> > newStates;

  if (state.first < 3) {
    newStates.push_back(make_pair(3, state.second));
  }
  if (state.second < 4) {
    newStates.push_back(make_pair(state.first, 4));
  }
  if (state.first > 0) {
    newStates.push_back(make_pair(0, state.second));
  }
  if (state.second > 0) {
    newStates.push_back(make_pair(state.first, 0));
  }
  if (state.second > 0 && state.first < 3) {
    newStates.push_back(make_pair(std::min(3, state.first + state.second),
                        std::max(state.second - (3 - state.first), 0)));
  }
  if (state.first > 0 && state.second < 4) {
    newStates.push_back(make_pair(std::max(state.first - (4 - state.second), 0),
                        std::min(4, state.second + state.first)));
  }

  return newStates;
}

Note that with this function a new state is generated from the previous state by considering a single operation. So, for instance, from the state (0, 0) it produces (3, 0) and (0, 4), but not (3, 4) (which will be generated later) as in your function. I think that this reflect more correctly the idea that each state is derived from the previous one with a single step.


My yld NPM - callbacks/promises alternative

Interesting question;

I honestly can't follow the code, and I tried a while. I like to think of myself as above average in JavaScript, which means that from a readability/maintainability perspective you have a problem. It might be related to the fact that you have no comments in there ;)

Some minor style tips

For easier reading you can merge your var declarations with initial assignments, this

var parent;

parent = this;

becomes then

var parent = this;

You make a shortcut for Array.prototype.slice, but you use it only once, I would throw away the shortcut and simply go for value = Array.prototype.slice.call(arguments);.
There is no need to keep creating a function in your loop, just create the function outside of your loop.

while (true) {
   response = yield defer(function () {
      fnGenerator.next(response);
   });
}


The problem

There is a massive hole in your logic here. You are relying on the fact that there exists a property whose type is equal to the name of the property.

public MyEnumProperty MyEnumProperty { get; set; }

Your class would become unusable if I changed this line to:

public MyEnumProperty MyProperty { get; set; }

To explain the issue in detail, the rest of my answer will assume that you're using this second case where the type and name do not match.

The problem is here:

t => t.GetType()
      .GetProperty(index.GetType().Name)  // <== HERE
      .GetValue(t)
      .Equals(index)

GetProperty retrieves a property based on its name (MyProperty). So, what name are you using?

index.GetType().Name

The name of the type (MyEnumProperty). Which is not the same as the MyProperty name that you're looking for.

Let's look at another implementation of your class, where we will use MyIntProperty as the index:

var myCollection = new IndexableCollection<MyClass, int>();

var element = myCollection[5];

Going by the intention of your code, this should be possible. After all, you have made no specific requirements for the given TIndex, which means that your class needs to work for all possible types.

But it doesn't, because when you try to access myCollection[5], you get:

t => t.GetType()
      .GetProperty("Int32")
      .GetValue(t)
      .Equals(index)

There is no property by the name of Int32, so it does not work.

The solution

In essence, you are trying to define the indexed property by its type alone, which is a dangerous thing to do.

We could rewrite the code to search MyClass for the first property of the given type TIndex. However, what will you do if MyClass has multiple properties of that same type?

You'd be stuck guessing at the intended index, and that's not a good solution either.

What we're missing is the definition of the exact property you want to use as an index. You're trying to find it by its type alone, and that is not enough. Instead, you need a way to select the correct property.

My solution: the lambda.

You need a mapping between the element (TElement) and its intended index (TIndex). This is the perfect situation to use a lambda method of type Func<TElement, TIndex>.

I updated your code to a working example with lambdas. I slightly tweaked your code for the sake of example:

public enum MyEnum { One, Two, Three }

public class MyClass
{
    public int MyIntProperty { get; set; }
    public string MyStringProperty { get; set; }
    public MyEnum MyEnumProperty { get; set; }
}

The collection class:

public class MyCollection<TElement, TIndex> : List<TElement>
{
    private Func<TElement, TIndex> _indexMapping { get; set; }

    public MyCollection(Func<TElement, TIndex> indexMapping)
    {
        _indexMapping = indexMapping;
    }

    public TElement this[TIndex index]
    {
        get
        {
            return base.Find(t => _indexMapping.Invoke(t).Equals(index));
        }
    }
}

The only real difference is that we now store a Func<TElement, TIndex> _indexMapping. This gives us the mapping between the element and its index.
This has the interesting side effect that you can't use a TIndex that doesn't exist as a property in TElement (unless you supply a constant value unrelated to the element, but then you're being silly).

base.Find(t => _indexMapping.Invoke(t).Equals(index));

When iterating over the list, we simply invoke the mapping (on the element t), which returns the value of its intended index. All we have to do then is check whether the value matches the index that was currently given as a parameter, which is easily done by calling .Equals().

Example usages:

//Enum as index

var myCollection = new MyCollection<MyClass, MyEnum>(o => o.MyEnumProperty);
var element = myCollection[MyEnum.One];

//Int as index

var myCollection = new MyCollection<MyClass, int>(o => o.MyIntProperty);
var element = myCollection[12345];

//String as index

var myCollection = new MyCollection<MyClass, String>(o => o.MyStringProperty);
var element = myCollection["Hello"];

Tangential comments

If your index is a custom class, make sure to implement the correct equality comparison! The default behavior (checking if it's the same object in memory) may or may not be what you want.
There's still an issue when your collection contains multiple items with the same index. You'll always receive the first matching item, the others will essentially be invisible (until you remove the first item). Again, depending on your requirements, that might be intentional behavior, or it might not be.

If you want to ensure that you only have unique items in the list, and no duplicate indexes exist, you will need additional logic to validate new entries to the list.

As an aside, I would use TElement instead of TCollection, as the generic type refers to the elements of the collection (MyClass), not the collection itself (which is a List). Generic type names, e.g. TFoo, should be read as "type of the Foo". This applies to your TIndex (type of the index), and TElement would be similarly correct.


Working directory

os.path.dirname(os.path.realpath(__file__))

is not the current working directory. The current working directory is available via os.getcwd. Either you should call that instead, or maybe rename your variable.

Semicolons

are usually discouraged in Python, so you can drop one here:

working_directory: str = os.path.dirname(os.path.realpath(__file__));

pathlib

f"{working_directory}/{file}"

is better represented by making a Path and then using the / operator.

Overall

This approach is fragile. You're better off tapping into something like the LLVM/Clang AST, which actually understands how to parse all of the edge cases of C++.

Here is a suggestion that takes care of everything except the AST:

from pathlib import Path

NAMESPACE = 'using namespace'

log_file_name = Path('logs/log.txt')

if __name__ == '__main__':
    working_dir = Path.cwd()
    with log_file_name.open('w') as log_file:
        for prefix in ('h', 'c'):
            for file_name in working_dir.glob(f'*.{prefix}*'):
                with file_name.open() as source_file:
                    for line_number, line in enumerate(source_file):
                        if NAMESPACE in line:
                            log_file.write(f'NAMESPACE FOUND: LINE [{line_number + 1}] IN FILE {file_name}\n')

This also takes into account @AJNeufeld's feedback which is good.


Directed graph similarity calculation -- optimizing Mathematica code

Minor improvements, but consider using:

pList = ArrayFlatten[{{am\[Transpose], am}}];

and

dropDiagonal = MapThread[Delete, {#, Range@Length@#}] &;

I also tried dropDiagonal = MapIndexed[Drop, #] & but this is slower, at least in v7.

Replace:

Total[#1 #2]/Total[Sign[#1 + #2]] &

With:

#.#2 / Tr@Unitize[#1 + #2] &

I believe this is an improvement to your compiled function:

Compile[{{p, _Real, 2}},
  With[{b = p\[Transpose]},
    #.b / Total@Sign[# + b] & /@ p
  ]
]


At very least, DO NOT copy-paste your macros directly into .pch file

  A PCH file is, by definition, a project specific precompiled header.
  It really shouldn't be used beyond the context of the project and it
  really shouldn't contain anything but #includes/#imports.

As suggested by an Apple engineer, you should make a separate file with your macros e.g. Defines.h, and just put #import Defines.h into .pch file.
I would suggest re-thinking you logging strategy. If it is not absolutely necessary (e.g. you do not have access to production instance of your app), you should log only the critical errors. Abundance of logging code decreases its readability/maintainability and can even CAUSE bugs. I recommend an excellent blog post on this matter from co-founder of Stack Overflow.


Not without having to reinvent a lot of other things and make it more complex, no. This solution looks to be the best to me. You even use using correctly, which is one of my frequent nitpicks. However, if you want to simplify that bit of code, you might be able to help it with an extension method like so:

        List<string> list;

        using (var s = new MemoryStream(myFile))
        {
            list = s.ReadLines().ToList();
        }

...

    public static IEnumerable<string> ReadLines(this Stream s)
    {
        using (var sr = new StreamReader(s))
        {
            while (!sr.EndOfStream)
            {
                yield return sr.ReadLine();
            }
        }
    }


If you can, I would encrypt the password entered before it is passed back to the service.  This will eliminate any chance it could be intercepted.  As for the rest of your first question, I think the how you process is up to you.  I don't think there is a right or wrong answer.

Now onto improvements:

First off, I think you code is doing too much.  This is very evident by then number of if/else and return statements.

I think a better approach would be to pull out all of the logic into a number of separate methods, or even better classes that all work together to process the login, and decide what the appropriate course of action is.  I'm going to tackle the multiple method approach.  If you want to see how multiple classes can be implemented let me know, and I'll update the post then.

There are two important pieces of data that you require, the LoginStatus and the ActionResult  Keeping this in mind, I would first create a class call LoginResult, which contains the two pieces of information in it

internal class LoginResult
{
    public ActionResult ActionResult { get; private set; }
    public LoginStatus LoginStatus { get; private set; }

    public LoginResult(ActionResult actionResult, LoginStatus loginStatus)
    {
        ActionResult = actionResult;
        LoginStatus = loginStatus;
    }
}

This will allow for each method to return the important data.

Now that you have the first building block, I would start by pulling out every if/else statement in your original code into its own method, returning a LoginResult.  There is another important piece of data returned from one of the checks, and that is user, so add a UserLoginResult class:

internal class LoginResult
{
    public ActionResult ActionResult { get; private set; }
    public LoginStatus LoginStatus { get; private set; }

    public LoginResult(ActionResult actionResult, LoginStatus loginStatus)
    {
        ActionResult = actionResult;
        LoginStatus = loginStatus;
    }
}

internal class RetrieveUserResult
{
    public LoginResult Result { get; private set; }
    public User User { get; private set; }

    public RetrieveUserResult(LoginResult loginResult, User user)
    {
        Result = loginResult;
        User = user;
    }
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel logModel, string returnUrl)
{
    _returnUrl = returnUrl;
    _logModel = logModel;

    var result = EnsureModalStateIsValid();
    if (result.LoginStatus == LoginStatus.InvalidCredentials)
    {
        TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;

        return result.ActionResult;
    }

    var retrieveResult = TryToRetrieveUserFromRepository();

    if (retrieveResult.User == null)
    {
        TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;
        return result.ActionResult;
    }

    var lockedResult = CheckIfUserIsLockedOut(retrieveResult.User);

    if (lockedResult.LoginStatus == LoginStatus.AccountBlocked)
    {
        TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = lockedResult.LoginStatus;
        return lockedResult.ActionResult;
    }

    var passwordResult = ConfirmUserPasswordMatches(retrieveResult.User);
    if (passwordResult.LoginStatus == LoginStatus.InvalidCredentials)
    {
        TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = passwordResult.LoginStatus;
        return passwordResult.ActionResult;
    }

    //is the account activated?
    var activatedResult = ConfirmUserIsActivated(retrieveResult.User);
    if (activatedResult.LoginStatus == LoginStatus.AccountNotActivated)
    {
        TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = activatedResult.LoginStatus;
        return activatedResult.ActionResult;
    }

    return activatedResult.ActionResult;

}

private LoginResult EnsureModalStateIsValid()
{
    if (!ModelState.IsValid)
    {
        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.InvalidCredentials);
    }

    // Should come up with a dummy Action for this case
    return DetermineSuccessResult();
}

private RetrieveUserResult TryToRetrieveUserFromRepository()
{
    try
    {
        var user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));
        return new RetrieveUserResult(new LoginResult(RedirectToAction("Index", "Home"), LoginStatus.LoginOK), user);
    }
    catch (Exception ex)
    {

        return new RetrieveUserResult(DetermineSuccessResult(), null);
    }
}

private LoginResult CheckIfUserIsLockedOut(User user)
{
    if (user.IsLockedOut)
    {
        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.AccountBlocked);
    }

    return DetermineSuccessResult();
}

private LoginResult ConfirmUserPasswordMatches(User user)
{
    string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);
    if (!String.Equals(passHash, user.Password))
    {
        user.FailedPasswordAttemptCount++;
        try
        {
            _usersRepository.Update(user);
        }
        catch (Exception ex)
        {
            //just log it, not a big deal the FailedPasswordAttemptCount could not be updated
            user.FailedPasswordAttemptCount--;
        }

        TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;

        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.InvalidCredentials);
    }

    return DetermineSuccessResult();
}

private LoginResult ConfirmUserIsActivated(User user)
{
    if (!user.IsApproved)
    {
        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.AccountNotActivated);
    }

    return DetermineSuccessResult();
}

private LoginResult DetermineSuccessResult()
{
    FormsAuthentication.SetAuthCookie(_logModel.LoginUsername, false);
    return new LoginResult(ReturnUrlIsValid() ? Redirect(_returnUrl) : RedirectToAction("Index", "Home"), LoginStatus.LoginOK);
}

private bool ReturnUrlIsValid()
{
    return (Url.IsLocalUrl(_returnUrl) && _returnUrl.Length > 1 && _returnUrl.StartsWith("/") &&
        !_returnUrl.StartsWith("//") && !_returnUrl.StartsWith("/\\"));
}

The Login method still is doing too much, but at least it has moved the checking logic out into sub routines.  You should now start to see a pattern emerging in the Login method: DoCheck -> CheckResult -> return if failed -> repeat.  This can be moved into a chain event where if the first one fails, it returns, if it passes, it calls the next event:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel logModel, string returnUrl)
{
    _returnUrl = returnUrl;
    _logModel = logModel;

    var result = Process();

    TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;

    return result.ActionResult;
}

private LoginResult Process()
{
    LoginResult result = EnsureModalStateIsValid();
    return result.LoginStatus == LoginStatus.InvalidCredentials ? result : TryToRetrieveUserFromRepository();
}

private LoginResult EnsureModalStateIsValid()
{
    return !ModelState.IsValid
                ? new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.InvalidCredentials)
                : DetermineSuccessResult();

    // Should come up with a dummy Action for this case
}

private LoginResult TryToRetrieveUserFromRepository()
{
    try
    {
        var user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));

        return retrieveUserResult.User == null ? result : CheckIfUserIsLockedOut(retrieveUserResult.User);
    }
    catch (Exception ex)
    {
        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.DatabaseException);
    }
}

private LoginResult CheckIfUserIsLockedOut(User user)
{
    return user.IsLockedOut
                ? new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.AccountBlocked)
                : ConfirmUserPasswordMatches(user);
}

private LoginResult ConfirmUserPasswordMatches(User user)
{
    //is the password correct?
    string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);
    if (!String.Equals(passHash, user.Password))
    {
        user.FailedPasswordAttemptCount++;
        try
        {
            _usersRepository.Update(user);
        }
        catch (Exception ex)
        {
            //just log it, not a big deal the FailedPasswordAttemptCount could not be updated
            user.FailedPasswordAttemptCount--;
        }

        TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;

        return new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.InvalidCredentials);
    }

    return ConfirmUserIsActivated(user);
}

private LoginResult ConfirmUserIsActivated(User user)
{
    return !user.IsApproved
                ? new LoginResult(RedirectToAction("LoginFailed"), LoginStatus.AccountNotActivated)
                : DetermineSuccessResult();
}

private LoginResult DetermineSuccessResult()
{
    FormsAuthentication.SetAuthCookie(_logModel.LoginUsername, false);
    return new LoginResult(ReturnUrlIsValid() ? Redirect(_returnUrl) : RedirectToAction("Index", "Home"),
                            LoginStatus.LoginOK);
}

private bool ReturnUrlIsValid()
{
    return (Url.IsLocalUrl(_returnUrl) && _returnUrl.Length > 1 && _returnUrl.StartsWith("/") &&
            !_returnUrl.StartsWith("//") && !_returnUrl.StartsWith("/\\"));
}

With this interation, you get rid of the RetrieveUserResult class.

There are a few more things I'd suggest, but I don't like giving too much information in these all at once.

Hope this helps.


Since a digital root is obtained by adding all the digits in a number, and while the resulting number is more than 9, repeating the process, an alternative and equally effective approach could simply be dividing by 9. In most cases, the digital root is simply the remainder of this operation.

Here's an example to see this in action. Take any number; for simplicity's sake, I choose a relatively low number: 625.

625 ->
6 + 2 + 5 = 13 ->
1 + 3 = 4

Thus the digital root is 4.

If you divided 625 by 9 you would get 69 with a remainder of 4. In other words, using modulo, and factoring in our edge cases (When n is 0, or 9 divides n with no remainder), we can write a digital root computing method as straight-forward as:

public static int computeDigitalRoot(int n) {
    return n == 0 ? 0 :
           n % 9 == 0 ? 9 : n % 9;
}

If the ternary operator is not to your liking, this is the equivalent using if statements:

public static int computeDigitalRoot(int n) {
    if (n == 0) {
        return 0;
    }
    if (n % 9 == 0) {
        return 9;
    }
    return n % 9;
}


filtering element of one List from another in Scala with different tuple structure

Apart from my comment, I'd suggest using Set for, well sets, since operations will likely be quicker, but more importantly, they're more correct wrt. what operations can be done on them.
val setB: Set[(String, String)] = ListB.toSet

val filtered: List[((String, String), Int)] =
  ListA.filterNot(x => setB.contains(x._1))

val result: List[Int] =
  filtered.map(_._2)

This returns a different result.  As I wrote in my comment I don't quite understand the reasoning behind the algorithm and if it's a real requirement that it's going to be iterative like this, you'll likely have to use the implementation you have right now, i.e. via for.
Also splitting the computation into multiple steps might help with understanding what's going on (especially in a debugger), that's also why I copied over the type signatures as you did.

*If the exact same output is desired*, that'd be this then:
val result = ((for {
  m <- ListA.filter(x => setB.contains(x._1)).map(_._2)
} yield m):::List(0)).slice(0,1)

Nevermind, the same result requires to walk through the list as in the original post.

Also variables shouldn't start with an upper case, c.f. setB instead of SetB.


There is a very simple way to handle this but that is all dependant on the fact you have only one implementation of each ISprite impelementation per interface type. If thats the case (and they all have parameterless constructors) you can simply use reflection to get your type and then construct it.

class SpriteFactory : ISpriteFactory
{
    public T Create<T>() where T : ISprite
    {
        var type = typeof(T);
        var spriteType = AppDomain.CurrentDomain.GetAssemblies()
                                                .SelectMany(s => s.GetTypes())
                                                .Where(p => type.IsAssignableFrom(p) && p.IsClass)
                                                .FirstOrDefault();

        if (spriteType == null)
            return default(T);

        return (T)Activator.CreateInstance(spriteType);
    }
}

Now there is alot wrong with this implementation as it assumes alot.

That there is only one implenetation of the ISprite type passed in.
It does an assembly scan everytime you need to create a new instance of this object.
Requires all implementations to have a default parameterless constructor on the implementation.

We could approach this by only scanning for the object once. But again we are stuck with the issues in point 1 and 3. This implementation is even uglier and (not tested) doesn't appear to be too thread safe.

class SpriteFactory : ISpriteFactory
{
    static object _locker = new object();

    Dictionary<Type, Type> registrations = new Dictionary<Type, Type>();

    public T Create<T>() where T : ISprite
    {
        var type = typeof(T);
        if (!registrations.ContainsKey(type))
        {
            lock (_locker)
            {
                var spriteType = AppDomain.CurrentDomain.GetAssemblies()
                                                        .SelectMany(s => s.GetTypes())
                                                        .Where(p => type.IsAssignableFrom(p) && p.IsClass)
                                                        .FirstOrDefault();
                registrations[type] = spriteType;
            }
        }
        var regType = registrations[type];
        return regType != null ? (T)Activator.CreateInstance(regType) : default(T);
    }
}

What you are really after is some sort of dependency injection and do away with the SpriteFactory all together. Dependency injection was made for this type of work and although the initial code is usually a bit more its typically more elegant. Especially when it comes to managing constructor injection, object disposal etc. The real power comes in when you need to start extending your application and adding more types.

Now without depenency injection you could define your registrations some where else. Where although it is similar to your first approach does abstract the implementation. Something like.

interface ISpriteFactory
{
    T Create<T>() where T : ISprite;
}

class SpriteFactory : ISpriteFactory
{
    static Dictionary<Type, Func<object>> registrations = new Dictionary<Type, Func<object>>();

    public static void AddRegistration<T>(Func<T> aquire)
    {
        registrations[typeof(T)] = aquire as Func<object>;
    }

    public T Create<T>() where T : ISprite
    {
        if (registrations.ContainsKey(typeof(T)))
            return (T)registrations[typeof(T)]();
        return default(T);
    }
}

Now what I have done is basically created static method to create registrations of your ISprite implementations.  This can be used as such.

class Program
{
    static void Main(string[] args)
    {
        SpriteFactory.AddRegistration<IPieceSprite>(() => new PieceSprite());
        SpriteFactory.AddRegistration<ITileSprite>(() => new TileSprite());

        var factory = new SpriteFactory();

        var piece = factory.Create<IPieceSprite>();
    }
}

All in all without a proper framework in place to take care of your dependency resolution and life-time scopes you are stuck with either having our initial 3 problems or writing out your object creation methods manually.


WIP library that will encrypt some text for the purpose of obfuscating my code

Preamble

What you're looking for is a way to obfuscate your code, not a way to encrypt it. The issue lies in the fact that the interpreter needs to have access to the unencrypted source code. This means that you have to store the key somewhere and decrypt the file before runtime, which defeats the purpose of encrypting the source code in the first place. It's almost impossible to properly protect Python code and there's lots of decompilers out there.

There's several better ways to go about doing this:

Use a restrictive (proprietary) license. Be sure to do some research on what license is best, so you know exactly what restrictions and rights people have when using your software.
If you need to interact with a (web)server, try to make as much as possible happen server-side, which, provided you secure your server, prevents people from viewing the source code.
Push frequent, backward-incompatible updates.
Think again and decide you may as well just release it under an open-source license like the MIT license or the GNU GPL.

Your code

Ram Chandra Giri covered most issues with style conventions. I'd like to point out something:

After calling open, one should call close to properly clean up. We may be tempted to do something like this:

f = open(FILENAME, MODE)
# Do stuff with `f`
f.close()

But what if an exception occurs before the close call? So, we have to wrap it in a try: | finally: statement instead:

try:
    f = open(FILENAME, MODE)
    # Do stuff with `f`
finally:
    f.close()

Python provides a cleaner way to do this, using context managers:

with EXPR as VAR:
    BLOCK

In the case of file descriptors, we can use:

with open(FILENAME, MODE) as f:
    # Do something with `f`

Specifically:

with open("save.txt", "r") as f:
    contents = f.read()
    contents = int(contents, 2)
    return contents.to_bytes(
        (contents.bit_length() + 7) // 8,
        'big'
    ).decode()

You can use sys.byteorder to find the system's native byte order. Alternatively if you want to use 'big' as byteorder, I'd make it a constant:

BYTE_ORDER = "big"

If the file is sufficiently large, the system may run out of memory trying to read it all at once. We can avoid this problem by reading 'chunks' into memory.

Here's the same code, but rewritten to implement all changes:

import sys

def write_binary_string(string, filename):
    """Convert `string` to binary and write it to `filename`.

    :param str string: The string to be obfuscated.
    :param str filename: The filename to write to.
    :raises FileNotFoundError: If `filename` is not a file.
    :return: None
    """
    with open(filename, "w") as f:
        binary_representation = bin(int.from_bytes(
            string.encode("utf-8"),
            sys.byteorder
            )
        )
        f.write(binary_representation)

def read_binary_string(filename):
    """Open `filename` and return the deobfuscated contents.

    :param str filename: The file to read from.
    :raises FileNotFoundError: If `filename` is not a file.
    :return: None
    """
    CHUNK_SIZE = 65536
    binary_representation = []
    with open(filename, "r") as f:
        while True:
            chunk = f.read()
            if not chunk:
                break
            binary_representation.append(chunk)
    binary_representation = "".join(binary_representation)
    return int(binary_representation, 2).to_bytes(
        (binary_representation.bit_length()+7) // 8,
        sys.byteorder
    ).decode("utf-8")


Well, for starters, it is a proven mathematical fact that if a number is prime, it is not divisible by any prime number that is less than its square root. In your inner loop you go up to i/2 and you can change this to Math.floor(Math.sqrt(i)).

Because you are checking for a range of numbers, you would probably benefit from a cache of primes, rather than testing every odd number less than the square root.

Something like this:

package mypackage;

import java.util.ArrayList;

/**
 * Checks for primeness using a cache.
 */
public class PrimeCache {

    private static ArrayList<Integer> cache = null;

    static {
        cache = new ArrayList<Integer>();
        cache.add(2);
    }

    public static boolean isPrime(int i) {
        if (i == 1) return false; // by definition

        int limit = (int) Math.floor(Math.sqrt(i));
        populateCache(limit);

        return doTest(i, limit);
    }

    private static void populateCache(int limit) {
        int start = cache.get(cache.size() - 1) + 1;
        for (int i = start; i <= limit; i++) {
            if (simpleTest(i)) cache.add(i);
        }
    }

    private static boolean simpleTest(int i) {
        int limit = (int) Math.floor(Math.sqrt(i));

        return doTest(i, limit);
    }

    private static boolean doTest(int i, int limit) {
        int counter = 0;
        while (counter < cache.size() && cache.get(counter) <= limit) {
            if (i % cache.get(counter) == 0) return false;
            counter++;
        }

        return true;
    }
}


Combine neighboring parts of an array based on a condition

Some general remarks about your code:

combineBy use PascalCase for method names
f it's not a good parameter name, if it's a condition function they are usualy named predicate
predicate.Invoke(...) - you can call it directly with predicate(...)
values.TakeWhile(n => !predicate(n)) - do not enumerate it twice, call ToArray and use it in the subsequent lines
if you like it the LINQ way you can write values.Any() instead of values.Length != 0 and values.First() instead of values[0] also this new string[] { inp[0] } could be turned into values.Take(1).ToArray()
don't use abbreviations for variables like inp or f, use full names like values and predicate

x

public static string[][] CombineBy(this string[] values, Func<string, bool> predicate)
{
    var result = new List<string[]>();
    while (values.Any())
    {
        if (predicate(values.First()))
        {
            result.Add(values.Take(1).ToArray());
            values = values.Skip(1).ToArray();
        }
        else
        {
            var toAdd = values.TakeWhile(n => !predicate(n)).ToArray();
            result .Add(toAdd);
            values = values.Skip(toAdd.Length).ToArray();
        }
    }
    return result.ToArray();
}

Unfortuantely your code doesn't seem to work and returns invalid results. This should do:

public static List<List<string>> CombineBy(this string[] values, Func<string, bool> predicate)
{
    var result = new List<List<string>>();

    foreach (var value in values)
    {
        if (predicate(value))
        {
            if (!result.Any() || !predicate(result.Last().Last()))
            {
                result.Add(new List<string>());
            }
            result.Last().Add(value);
        }
        else
        {
            result.Add(new List<string> { value });
        }
    }

    return result;
}

or even without loops:

public static List<List<string>> CombineBy3(this string[] values, Func<string, bool> predicate)
{
    var result = values.Aggregate(new List<List<string>>(), (current, next) =>
    {
        if (predicate(next))
        {
            if (!current.Any() || !predicate(current.Last().Last()))
            {
                current.Add(new List<string>());
            }
            current.Last().Add(next);
        }
        else
        {
            current.Add(new List<string> { next });
        }
        return current;
    });
    return result;
}


It's ok, but there's room for improvement.

Don't use BOM. Use BillOfMaterials.
It won't matter to you, but the next guy will thank me.
You're missing indexes on the items you defined foreign keys for. They're not free, you have to create them yourself.
I find it really odd that the BOM.Quantity can be null. If a part is on the BoM, shouldn't there be at least one of them required as part of the "kit"? I may even consider using a default value of one.


for (int i=0; i < Grade.values().length;i++){
            if(value > Grade.OBS4.getLim()){
                return Grade.OBS4.getTitle();
            } else if(value < Grade.INS.getLim()){
                return Grade.INS.getTitle();
            } else if(value > Grade.values()[i].getLim() && value < Grade.values()[i+1].getLim()){
                return Grade.values()[i+1].getTitle();
            }
        }

You don't need the first two conditions in the for loop.  You can instead say

        if (value > Grade.OBS4.getLim()) {
            return Grade.OBS4.getTitle();
        }

        if (value < Grade.INS.getLim()) {
            return Grade.INS.getTitle();
        }

        for (int i = 1; i < Grade.values().length; i++) {
            if (value > Grade.values()[i - 1].getLim() && value < Grade.values()[i].getLim()) {
                return Grade.values()[i].getTitle();
            }
        }

This is because those two conditions are invariant relative to the loop.  They'll either be true the first time or they will never be true.  Since you are returning, an else is unnecessary (although harmless if you prefer it).

We don't need to check i equal to 0, as there is no -1 grade.  We instead just check the insufficient grade before the loop.

If the BMI grade is exactly equal to the border marker, you'll fall through to the null case.  You should make one of those inequalities "or equal to", i.e. >= or <=.  Which one depends on the exact rules, which you don't include in your question.  I'm going to choose >=.

        for (Grade grade : Grade.values()) {
            if (value < grade.getLim()) {
                return grade.getTitle();
            }
        }

        return Grade.OBS4.getTitle();

You may need to change your limits to match.

Now we don't do any checks outside the loop.  And we don't need to compare across grades.  We know it's greater than or equal to previous grades, as if it were less than, we would already have returned.

If we fall through the loop, we know that the value represents extreme obesity.

I've added some additional whitespace for readability.

I would prefer to replace Lim with Limit for readability.

You can also use a NavigableMap here.  See here for an example on a similar problem.


The problem with the first two is that you are assuming separators are spaces but they could potentially be tabs, new lines or punctuation. Although it is easy to split on a non-word character joining them back in is tricky (even multiple spaces will fool the algorithm). Your regex solution has the added problem that it will convert words like kiss to kXXs.

I would stick to the regex, it is shorter and, imo, more readable. You can fix the issue by using a word boundary regex match:

const filter = new RegExp(`\\b(${BANNED.join('|')})\\b`, 'gi')

That said, I would also measure the performance of the three solutions as that is likely to be the biggest concern, especially with longer strings.

Edit 1

An alternative solution using split would be something like:

const censor = (sentence) =>
  sentence.split(/\b/).map(
    (word) => BANNED.includes(word.toLowerCase()) ? CHAR.repeat(word.length) : word
  ).join('')


O(lg n) algorithm for a fibonacci number with c++ template

As always, using namespace std; is dangerous. In fact, there is a tuple class in  C++11, std::tuple. You could very easily have a naming collision here thanks to that.

Why bother using a template for the size if you compare it to an int anyway? It's overkill here. If you do decide to keep it, you should give your template parameters more descriptive names here. T is used when there really is no information about what the possible type could be, as in container classes. However, the value here is going to have to be some kind of integral constant - so call it as such.

template <class IntegralValue, class IntegralValue2>
void fastFibo(IntegralValue n, IntegralValue *tuple)

Why does n have to be >= 4? What happens if the user wants the value at 1? This shouldn't throw up an error (or in this case, call abort). This violates the principle of least surprise.

Finally, passing a size and a pointer as parameters is the C way of doing things. In C++, prefer to use the concept of Iterators:

template <typename Iterator>
void fastFibo(Iterator begin, Iterator end)

This makes the code below a little bit messier, but doesn't force the user to utilize an array. They could use a std::vector (preferable), or even a list, set, or their own custom data structure to store the results. You can get the distance between two iterators using std::distance.

Edit: There are a couple of solutions to your problem. Using another function which forwards to fastFibo is a reasonable solution here, as it hides the user from some of the implementation details. With templates, it's a bit trickier to hide things (since they need to be in header files). One way is using a namespace like detail (which generally indicates that the things inside it are internal and shouldn't be used directly). Another possibility is to use a class or struct with static member functions: the call then looks very much like using a namespace, but you can utilize access protection modifiers. For example:

struct fib
{
private:
    const static int initFibo[5] = {5,3,2,1,1};

    template <class U, class V>
    static void fastFibo_impl(U n, V *tuple) {
        assert(n >= 4);
        if(n <= 5) {
            for(int i = 0; i < 4; i++)
                tuple[i] = initFibo[i + (5 - n)];
            return;
        }
        V tmp[4];
        fastFibo_impl<U, V>(n / 2 + 1, tmp);
        if(n % 2 == 0) { // even
            tuple[0] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
            tuple[1] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
            tuple[2] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
            tuple[3] = tmp[2] * tmp[2] + tmp[3] * tmp[3];
        } else {
            tuple[0] = tmp[0] * tmp[0] + tmp[1] * tmp[1];
            tuple[1] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
            tuple[2] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
            tuple[3] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
        }
    }

public:

    template <typename U, typename V>
    static V fastFibo(U n){
        if( n < 4 )
            return initFibo[5 - n];
        else {
            V buf[4];
            fastFibo_impl<U, V>(n, buf)
            return buf[0];
        }
    }
};

which is then called by fib::fastFibo<...>(...).

I also noticed I didn't answer one of your questions. If someone wishes to use this with their own BigNumber class, then their class would need to support operator*, operator+, and operator= (and have those functions perform integer multiplication, integer addition, and integer assignment). This falls under the idea of Concepts, which were slated for inclusion into C++11, but were dropped due to not being ready. Suffice to say, as long as the user has a BigNumber class that "acts like" an integer with respect to *, + and =, is DefaultConstructable (since you call the default constructor for V in V buf[4]), and has an overload of operator+ taking a BigNumber and an int, they could use it in your template without having to touch anything.


Picking the desired one between two links

You're right that the two for-loops are possibly overkill... though, it's not all that bad.. how big are the documents really?. The alternative is to track a default about link, and if a contact link appears, to override it. I'll explain that later, but first I should mention that the function should really return a value, not just print it inside the loops.

Having said that, consider the loop:

link = None
for item in soup.select("a[href]"):
    if "contact" in item.text.lower():
        link = urljoin(site,item['href'])
        # terminate the loop, no need to look further.
        break;
    if link is None and "about" in item.text.lower():
        link = urljoin(site,item['href'])
return link


Calculate Mersenne prime numbers in MATLAB

I can comment on multiple things here. But you ask about making the code look cleaner, so I'll start with that

Indenting

Be consistent with indenting. Indents show the structure of your code. Inconsistent indenting makes it hard to follow the structure.

Consistent spacing around operators also helps readability.

Variable names

It's common in MATLAB code to use single-letter variable names. I do this too. Try to use variable names that make the purpose of the variable clear. For example, p could be called candidates, since they are the possible Mersenne prime candidates.

Variable usage

psize = size(p);
x = psize(2);
% <snip>
for m = 1:x

You define a variable x here, but then use it only once. The name x is meaningless, so it takes a bit of time to find out what you are looping over. Consider instead:

for m = 1:length(p)

That one statement is immediately clear.

But since you are only using m to index into p (a = p(m)), you can also do this:

for a = p

Now m will have one of the values of p in each loop iteration (you don't need to do the indexing). Note that this form of for iterates over the columns of p, so if p were a column vector instead of a row vector, then the loop would only run once, with a containing all values in p.

You actually index p(m) three times within this loop. Two of those you can replace with a, which you have assigned the value of p(m).

Finally, k is initialized, and incremented each loop iteration, but not used at all. Unnecessary assignments and operations add confusion to your code, try to avoid these.

Vectorize

There are several places where you can simplify your code.

for k = 1:50000 %calculates mersenne primes using mersenne formula
   p(k) = 2^k -1;
end

This is identical to

p = 2.^(1:50000) - 1;

(note the .^ element-wise operator). Here you generate 50 thousand powers of two, but next you keep only 12:

p = p(p<10000 & p>1);

Why not directly generate the values you intend to keep? For the condition 2.^k-1 < 10000, you need k < log2(10000-1), and for 2.^k-1 > 1 you need k > 1:

p = 2.^(2:log2(10000-1))-1;

Testing for primeness

Next, you loop over each of the candidates to see if it's a prime:

a = p(m);
b = p(m)-1;
if all((rem(a,2:b)) ~= 0)

Note that to test for primeness, you need to test division only up to sqrt(a), any larger value is guaranteed not to divide the value evenly. And you don't need to test with any power of 2 except 2 itself:

if all(rem(a,[2,3:2:sqrt(a)]) ~= 0)

You could consider making this test into a function, which will improve readability (then you don't need to add the comment):

isprime = @(a)all(rem(a,[2,3:2:sqrt(a)]) ~= 0);
% ...
if isprime(a)

(now you're using the isprime function, but not the built-in one!)

Simplify logic

Within this test you set flag = 1 or flag = 0. Considering true has a value of 1, and false a value of 0, you might as well do:

flag = isprime(a);

But next you test flag and add the number to the list of Mersenne primes. So you don't need the flag at all:

if isprime(a)
   f = f+1;
   mersenneprime(f) = a;
end

Appending to an array

Adding a value to the mersenneprime list can be simplified too, using the end keyword in indexing, do you don't need f:

mersenneprime(end+1) = a;

This is actually fairly efficient. They have tried to make people preallocate arrays like these that grow within a loop for decades, and finally decided to optimize their allocation strategy for this use case. Also, since your list will always be very small, no matter how large your upper limit is, you don't need to worry about efficiency here at all. You do need to initialize the mersenneprime to an empty array.

Putting it all together

So putting this all together I get to the following bit of code:

isprime = @(a)all(rem(a,[2,3:2:sqrt(a)]) ~= 0);
limit = 10000;
candidates = 2.^(2:log2(limit-1))-1;
mersenneprime = [];
for c = candidates
   if isprime(c)
      mersenneprime(end+1) = c;
   end
end
disp(mersenneprime)


Consider the following potential row in your data:

'abbbbbbbbbbbbbbb'

The bare minimum amount of work necessary would be to add 15 to both results - but with your loop as written, you'd add 15 to result['a']['b'], but then add 1 to result['b']['a'] 15 times. That's less than ideal.

So let's first condense the row into a counter - and then add the counter itself:

result = collections.defaultdict(lambda: collections.defaultdict(int))

for row in data:
    counts = collections.Counter(row)
    for key_from, key_to in itertools.permutations(counts, 2):
        result[key_from][key_to] += counts[key_from] * counts[key_to]

permutations() gives us all the pairs of keys that we will need to update - without repeat to ensure that a letter does not co-occur with itself. Of course, if the row is 'abcdefgh', this won't do us any good - we still make \$N^2\$ passes. But if the row is the first one I suggested, it's a big improvement.

Regardless, this:

result[e].update([el for el in l if el is not e])

Can be improved by removing the []s:

result[e].update(el for el in l if el is not e)

update() can take an iterable, so no need to create a full list.