Bugs

>>> gen = batch(range(50), lambda x:x%10==9, 7)
>>> for i in gen:
    print(list(i))

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    for i in gen:
  File "<pyshell#142>", line 13, in batch
    n = next(iterable)
TypeError: 'range' object is not an iterator

Damn, I expected to be able to use iterables as the iterable parameter, not iterators.

Let's fix it:

def batch(iterable, condition_func=(lambda x:True), max_in_batch=None):
    iterator = iter(iterable)
    def Generator():
        nonlocal n, iterator, condition_func, max_in_batch
        num_in_batch = 1
        yield n
        while True:
            n = next(iterator)
            if num_in_batch == max_in_batch or condition_func(n):
                return
            num_in_batch += 1
            yield n

    n = next(iterator)
    while True:
        yield Generator()

and try again:

>>> gen = batch(range(50), lambda x:x%10==9, 7)
>>> for i in gen:
    print(list(i))

[0, 1, 2, 3, 4, 5, 6]
[7, 8]
[9, 10, 11, 12, 13, 14, 15]
[16, 17, 18]
[19, 20, 21, 22, 23, 24, 25]
[26, 27, 28]
[29, 30, 31, 32, 33, 34, 35]
[36, 37, 38]
[39, 40, 41, 42, 43, 44, 45]
[46, 47, 48]
[49]
[49]
[49]
[49]
[49]
[49]
[49]
[49]
[49]
Traceback (most recent call last):
  File "<pyshell#157>", line 2, in <module>
    print(list(i))
  File "C:\Python33\lib\idlelib\PyShell.py", line 1336, in write
    return self.shell.write(s, self.tags)
KeyboardInterrupt

Dang… Let's try to limit that:

def batch(iterable, condition_func=(lambda x:True), max_in_batch=None):
    iterator = iter(iterable)
    def Generator():
        nonlocal n, on_going, iterator, condition_func, max_in_batch
        num_in_batch = 1
        yield n
        on_going = False
        while True:
            n = next(iterator)
            on_going = True
            if num_in_batch == max_in_batch or condition_func(n):
                return
            num_in_batch += 1
            yield n

    n = next(iterator)
    on_going = True
    while on_going:
        yield Generator()

Way better!

Use a for loop to iterate over an iterator

Iterating over elements and maintaining a counter of how much elements were iterated over is usually done using a for loop combined with enumerate:

def Generator():
    nonlocal n, on_going, iterator, condition_func, max_in_batch
    yield n
    on_going = False
    # Start enumerate at 1 because we already yielded n
    for num_in_batch, item in enumerate(iterator, 1):
        on_going = True
        n = item
        if num_in_batch == max_in_batch or condition_func(n):
            break
        yield item

Using this construct also help handling the on_going flag (I don't like the way we have to change it twice to continue iterating): when the break is not reached, we know we have exhausted the iterator.

def Generator():
    nonlocal n, on_going, iterator, condition_func, max_in_batch
    yield n
    # Start enumerate at 1 because we already yielded n
    for num_in_batch, item in enumerate(iterator, 1):
        n = item
        if num_in_batch == max_in_batch or condition_func(n):
            break
        yield item
    else:
        on_going = False

Use closures instead of nonlocals

Specifying iterator, condition_func, and max_in_batch in the nonlocal clause is not necessary as they are not modified within Generator. Instead you should use standard scope resolution to do the job.

In fact, your use of nonlocal to get non-trivial side effects on n had me wondered if an inner function is really the way to go. Let's try OOP instead:

class Batch:
    def __init__(self, iterable, condition=(lambda x:True), limit=None):
        self.iterator = iter(iterable)
        self.condition = condition
        self.limit = limit
        try:
            self.current = next(self.iterator)
        except StopIteration:
            self.on_going = False
        else:
            self.on_going = True

    def group(self):
        yield self.current
        # start enumerate at 1 because we already yielded the last saved item
        for num, item in enumerate(self.iterator, 1):
            self.current = item
            if num == self.limit or self.condition(item):
                break
            yield item
        else:
            self.on_going = False

    def __iter__(self):
        while self.on_going:
            yield self.group()

A bit more verbose but it seems to be a bit more explicit too. You use it as you would for your batch function:

>>> gen = Batch(range(50), lambda x:x%10==9, 7)
>>> for i in gen:
    print(list(i))

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


Extract unique words from given text and group by letter count

If code is not correct it is not useful and it may be harmful.

I reviewed the specification for your program,

  The idea is to extract unique words sorted and grouped by length.

the sample input,

echo "The unary notation can be abbreviated by introducing different symbols for certain new values. " | go run extract_words.go

and the sample output.

2(2):   be by
3(3):   can for new
5(1):   unary
7(2):   certain symbols
8(1):   notation
9(1):   different
11(2):  abbreviated introducing

I then ran your program

2(2):   be by
3(4):   can for new the
5(1):   unary
7(2):   certain symbols
8(1):   notation
9(1):   different
11(2):  abbreviated introducing

felix posted an answer, so I ran his program

2(2):   be by
3(4):   can for new the
5(1):   unary

Three different outputs! All wrong!

None of the earlier outputs is correct. I wrote a program to find the correct output.

Output:

2(2):   be by
3(4):   can for new the
5(1):   unary
6(1):   values
7(2):   certain symbols
8(1):   notation
9(1):   different
11(2):  abbreviated introducing

wordsbylen.go:

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "os"
    "sort"
    "strings"
    "unicode"
)

func wordsByLen(r io.Reader) ([][]string, error) {
    unique := make(map[string]bool)
    scan := bufio.NewScanner(r)
    for scan.Scan() {
        fields := bytes.FieldsFunc(
            scan.Bytes(),
            func(r rune) bool {
                return !unicode.IsLetter(r)
            },
        )
        for _, field := range fields {
            unique[string(bytes.ToLower(field))] = true
        }
    }
    if err := scan.Err(); err != nil {
        return nil, err
    }

    words := make([]string, 0, len(unique))
    for word := range unique {
        words = append(words, word)
    }

    sort.Slice(words,
        func(i, j int) bool {
            if len(words[i]) < len(words[j]) {
                return true
            }
            if len(words[i]) == len(words[j]) {
                return words[i] < words[j]
            }
            return false
        },
    )

    var byLen [][]string
    for i, j := 0, 1; j <= len(words); j++ {
        if j == len(words) || len(words[j]) != len(words[i]) {
            byLen = append(byLen, words[i:j])
            i = j
        }
    }
    return byLen, nil
}

func main() {
    f := os.Stdin
    if len(os.Args) == 2 {
        var err error
        f, err = os.Open(os.Args[1])
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            return
        }
        defer f.Close()
    }

    byLen, err := wordsByLen(f)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    for _, words := range byLen {
        if len(words) > 0 {
            list := strings.Join(words, " ")
            fmt.Printf("%d(%d): \t%s\n", len(words[0]), len(words), list)
        }
    }
}

Go programmers usually like to write efficient code. I ran the code on Shakespeare:

The Complete Works of William Shakespeare by William Shakespeare
http://www.gutenberg.org/files/100/100-0.txt

For my program (correct results)

real    0m0.369s
user    0m0.356s
sys     0m0.012s

For your program (incorrect results)

real    0m0.675s
user    0m0.630s
sys     0m0.040s

For felix's program (incorrect results)

real    1m58.704s
user    1m58.600s
sys     0m0.140s

Since felix's program takes hundreds of times longer than other programs, it is unlikely to be useful.

You and felix have a narrow view of words, limiting them to ASCII letters

regexp.Compile("[^a-zA-Z]")

There is a larger world out there: The Unicode Consortium. For example, unicode.IsLetter()

The Go garbage collector manages memory, it does not manage operating system resources like files. To avoid crashing with too many open files, get into the habit of releasing OS file resources by closing files when no longer needed. See my use of defer f.Close().

Two key goals of the Go programming language are simplicity and readability.

Your text algorithms favor regular expressions, which can be complicated and error prone. See Mastering Regular Expressions, 3rd Edition, Jeffrey Friedl, ISBN-13: 978-0596528126.

Your data structures are complicated, favoring maps (dictionaries). For example, map[int]map[string]struct{}. I used simple structures: map[string]bool, []string, and, at the end, [][]string.

Your control structures look complicated. I used a simple, sequential control structure: unique words -> word list -> sort word list -> group word list -> print grouped word list.


What if you would operate with character code ranges and use the ord() and chr() built-in functions instead:

def char_range(mini, maxi, step=1):
    for code in range(ord(mini), ord(maxi) + 1, step):
        yield chr(code)

Or, with the yield from (Python 3.3+):

def char_range(mini, maxi, step=1):
    yield from range(ord(mini), ord(maxi) + 1, step)

Demo:

$ ipython3 -i test.py
In [1]: for char in char_range('a', 'h'):
   ...:     print(char, end=' ')
   ...:
a b c d e f g h

Couple notes about the code style of your solution:

according to PEP8, there should be two blank lines after the imports
use the "lower_case_with_underscores" style to name the function - charRange() vs char_range() (PEP8 reference)


1

From looking on the script, seems there is nothing that can be slow except of the mail(). The problem is, it needs to connect with the target mail server and thats often very slow.

mail() got many problems so it is best avoid using it. You can read about it here and here

The best alternative is probably Swiftmailer http://swiftmailer.org/. With that  you can solve also your "in background sending" using spool. Your mails will be send after the script finished running.

For the next two questions I would advise to handle your script like an HTTP API.

2

With Spool

you cannot know in real time if sending of your email was an success, as this will happen after your script will terminate.

Without Spool

it could still be faster (or not), but you will know if it was ok right away

What to return depend now on the above

You can use standard response codes, almost for all your scenarios. http_status_codes
You don't need to return anything in the body most of the time.

Fail:

400 - Bad Request - when the request is missing $msg, or body json is malformed
401 - Unauthorized - when missing http_origin or not in the list of allowed
405 - Method not allowed - if it is not POST or OPTIONS
409 - Conflict - email sending failed (if not usign spool)

Success:

200 - OK - email send successfully (if not using spool)
202 - Accepted - when everything is ok, but using spool so you don't know if the sending of email was successfull

In an API approach you would be able to call some url to check if your Accepted request was done processing or not, but this is another topic.

3

As I said before, this is basically an API, so all methods how to secure an API apply here. You can study those.
If you want to go simple and quick the easier ones are:

SSL + Http Basic Auth - simple basic auth when going over https is quite secure
SSL + ApiKey in header + Token Auth - basic thing for all API

I would not recommend going without SSL as you can always catch the request and read the keys.


Pointless try ... catch:

 try {
   if (item == null) {
     throw new IllegalArgumentException("item cannot be null");
   }
 }
 catch (NullPointerException ex) {
   throw new IllegalArgumentException("item cannot be null");
 }

Nothing in the protected code can generate a NullPointerException.  Perhaps something did at one point, but that code was removed, and the try ... catch was not removed?

Missing argument check:

addFirst() protects against adding null, but addLast() does not.

Resizing:

private void resize (int currentSize) {

This is not a static member function, so it has access to the current size of your deque.  Why require the caller to pass in currentSize?

private void resize() {
  int currentSize = size;

... would be sufficient, and more friendly to the caller.

Resizing:

  int newSize = currentSize * currentSize;

You are squaring the current size???  Ok, going from 2 to 4 is fine, and 4 to 16 is within reason, and 16 to 256 could be justified, but 256 to 65536?  I won't even contemplate the next step!

Doubling is a perfectly reasonable, and quite sane, resizing strategy.

Resizing:

  for (int j = itemCount; j > 0; j--) {
    newA[newStart++] = a[head++];
  }

Copying element by element is entirely correct, but you could let the JVM do the heavy lifting.  There is a good chance it will be faster.

  System.arraycopy(a, head, newA, newStart, itemCount);

DequeIterator

You aren't protecting against any external modification to the deque while you are iterating over it.  Consider a deque containing one item, and call the iter = iterator() method.  Then, call removeLast().  At this point, iter.hasNext() will return true, and iter.next() will return a null!

A simple fix is to maintain a modification counter in the deque class, and on every modification, increase it by one.  When you create an iterator, the iterator gets a copy of the modification counter's value.  On any iterator operation, compare the deque's current modification counter with the copy; if they are different, throw a ConcurrentModificationException.

Wasted space:

If your deque has space for 256 items, but only contains 100 items, if the items are all stored at the start or end of the storage array, then a call to addFirst() or addLast() might resize the array, growing it to 65536 entires, 65436 which will be empty.

Two options:

1) If there is still plenty of available space in the storage array, just move the current contents back to the "centre" of the storage array.  System.arraycopy() will do the heavy lifting here, avoiding any copy issue that may arise if the source and destination blocks overlap.

2) Use a circular array.  When you increment past the end of the storage array, you reset the index back to 0; when you decrement past the start of the storage array, you reset the index to the last element. itemCount == size() becomes the trigger condition to resize the storage array.  Take care to ensure you copy data from the src array to the destination array properly; you'll need to do it in two arraycopy() calls.

(Optional, Advanced) Type safety:

Your Item[] a array is not actually an Item[] array.  It is a Object[] array masquerading as an Item[] array, because it was cast to the desired type to force it into the desired member:

a = (Item[]) new Object[size];

This is fine, as long as the array never, ever leaks out of your Deque class.  For instance, don't ever add a toArray() method.

You can make a correctly typed storage array, as long as you are willing to pass the real item's class to the constructor.

public Deque(Class<Item> item_class) {
  size = 2;
  a = (Item[]) Array.newInstance(item_class, size);
  ...

You'd need this item_class in your resize() code as well, so store it as a member.


Calculating profit and score, if coordinates fall in a certain region of a field

I think we can all agree that that code is hard to read.  Rather than treating the dark shaded zone as the union of four rectangles, you would be better off treating it as a square with the centre excluded.

I've used a macro to reduce the verbosity.

In your code, when (x, y) falls in either of the white zones, you return an uninitialized value for innerbadge.  In those cases, the behaviour is undefined.

#define XY_IN_SQUARE(min, max) (((min) <= x && x <= (max)) && \
                                ((min) <= y && y <= (max)))

int badgeInnerCircle(int x, int y) {
    if (XY_IN_SQUARE(9, 12)) {          /* In innermost white zone */
        return /* what? */;
    } else if (XY_IN_SQUARE(7, 14)) {   /* In dark grey zone */
        double fprofit = fieldProfit(x, y);
        double fscore = fieldScore(x, y);

        /* The following value will be either 1 or 0 */
        return fprofit >= 10 && fscore >= 10;
    } else if (XY_IN_SQUARE(2, 19)) {   /* In outer white zone */
        return /* what? */;
    } else if (XY_IN_SQUARE(1, 20)) {   /* On yellow border */
        return /* what? */;
    } else {                            /* Outside yellow border */
        return -1;
    }
}


Python Bingo game that stores card in a dictionary

Style

Python comes with an "official" Style Guide for Python Code (aka PEP 8) which is a widely accepted standard for naming conventions and the like. Since you say your professor is keen on using best practices, I'd recommend to have a look at those guidelines. There is also a variety of tools that can help you to check for those best practices automatically. A non-exhaustive list (including Pylint) can be found in this meta-post here on Code Review.

From what I have seen, your code looks quite good in that regard. I especially like your docstrings. The most prevalent issue in your code would be that there are usually two blank lines between different function definitions in order to make their separation more clear.

Code

Idiomatic Python

As @nz_21 already mentioned, if sth == True: and also if sth == False: can be expressed in a more idiomatic way as if sth: and if not sth: (Note: Pylint would also catch this particular "mistake".)

Redefining built-ins

Some of the variable names you have chosen (min, max, list) redefine built-in functions from the Python core. You should avoid that. The simplest way is to append a single trailing underscore, e.g. list_, in order to avoid that issue. Also the parameter list seems to be unused in draw(...).

Random number generation

card[letter] = random.sample(range(min_, max_), 5) could also be rewritten as card[letter] = [random.randrange(min_, max_) for _ in range(5)]. Although I don't think that it will make a big difference in your case. The documentation explicitly list them as alternatives:

  random.randrange(start, stop[, step])

  Return a randomly selected element from range(start, stop, step). This
  is equivalent to choice(range(start, stop, step)), but doesn’t
  actually build a range object.

From that it seems that the later approach would make more sense for a large range of values to choose from.

Edit: removed after hint in the comments with regard to sampling with and without replacement. Thanks to @Wombatz.

Global variables

random_draw_list is used as a global variable, but unfortunately not as a constant as one might expect, but as a mutable global variable. That makes it harder to reuse code. Since draw(...) is the only function using this variable, it makes no sense to have it as a global variable. Instead, it should defined in main() after you have changed draw(...) to accept it as parameter (maybe that's what list was supposed to do in the first place?) and passed when calling draw(...) from main().

Top-level script environment

In order to show what part of the file is actually supposed to be run as a script, Python defines the concept of a top-level script environment. Although the name sounds daunting at first, it's quite likely that you have seen it in someone else's Python code: if __name__ == "__main__": This tells the Python interpreter to only run that part of code if the file is used as a script. In your case all there is to do is to do add the above right before calling the main-function:

if __name__ == "__main__":
    main()

That also helps you to avoid the issue that Python always starts a new bingo game whenever you try to import a function from your file ;-)


Merge entities which have the same children

Your code is very difficult to read.  (To give you an idea of how difficult it is, I've been looking at this for the past 2 hours so far)

You are using traditional for loops when you instead should be using foreach loops.
Your "loop variables" are poorly named.  Look toward the end of the code.  What is a c?  What is a d?  Leave the shorter names within smaller lambdas, index varialbes and possibly single instances of "utility" objects (e.g., StringBuilder or Regex).
You are trying too hard to write everything within a single line.  for loops, if conditions, large queries... all of them should span multiple lines.  With perhaps an exception to the if (duplicates.Count == 0) continue; line.  I'd be okay with that but you should try to keep those to a minimum (it might be possible that you could code it so that line is not needed).
You have a long chain of Append()s to the string builder when you really should use a single call to AppendFormat().
There are some snippets of your code which would work better either as a separate method or a LINQ query.  Use it.
LINQ to Entities should have made associations between your objects so your joins could be replaced by using the navigation properties.  If you don't have those set up, you should.
You also have some useless comments.  // For each class...  Do we really need a comment to tell us that?  Well, maybe since we were using for loops but that should have been avoided in the first place.

You have a lot of performance issues too.

You are calling ToList() on every query when you are simply just enumerating over it most of the time.
You have a lot of repeated loops on the same collection too.  You should be able to do a lot within a single loop.
Your query for finding duplicates will be a huge hit.  I don't have much to say on it right now but it's already making this O(n^2).
I have a feeling that you don't need the calls to LoadProperty().  From what I can tell, the majority of your code is filling in data manually when you probably don't need to.  Unfortunately I don't know the entity framework enough to know better (though I am looking into it right now).

Applying what I've explained to your code, I'd start with this (hopefully I didn't break anything).

var sb = new StringBuilder();
var counter = 0;
using (var ctx = new SchoolModel())
{
    var allClasses = ctx.Classes
        .Where(o => o.SubjectId > 0)
        .OrderBy(o => o.Id)
        .ToList();

    foreach (var aClass in allClasses)
    {
        ctx.LoadProperty(aClass, o => o.Students);

        // a properly crafted query could remove this completely and not use LINQ to Objects
        var students = new HashSet<int>(aClass.Students.Select(s => s.Id));
        var dupClasses = allClasses
            .Where(o => o.SubjectId == aClass.SubjectId
                     && o.Id != aClass.Id
                     && students.SetEquals(o.Students.Select(s => s.Id)))
            .ToList();

        if (dupClasses.Count == 0) continue;

        ctx.LoadProperty(aClass, o => o.PeriodsTimetable);

        foreach (var dupClass in dupClasses)
        {
            // If the duplicate class has a timetable slot that's not also allocated to the
            // class we are keeping, then allocate it (otherwise MySql will delete it).
            ctx.LoadProperty(dupClass, o => o.PeriodsTimetable);

            foreach (var dupTimetable in dupClass.PeriodsTimetable)
            {
                var isDuplicate = aClass.PeriodsTimetable
                    .Any(ctp => dupTimetable.TeacherId == ctp.TeacherId
                             && dupTimetable.PeriodTime == ctp.PeriodTime);
                if (!isDuplicate)
                    dupTimetable.ClassId = aClass.Id;
            }

            // Now update all other entities which reference the duplicate to instead reference
            // the class we are keeping.
            foreach (var dupPeriod in dupClass.Periods)
                dupPeriod.ClassId = aClass.Id;
            foreach (var dupAssessment in dupClass.Assessments)
                dupAssessment.ClassId = aClass.Id;
            foreach (var dupSeatingPlan in dupClass.SeatingPlans)
                dupSeatingPlan.ClassId = aClass.Id;
            foreach (var dupMerit in dupClass.Merits)
                dupMerit.ClassId = aClass.Id;

            sb.AppendFormat("{0} merged with {1}.
", dupClass.LongName, aClass.LongName);

            // Finally, delete the duplicate
            ctx.Classes.DeleteObject(dupClass);

            // not sure this is really needed
            allClasses.Remove(dupClass);
            counter++;
        }
    }
    ctx.SaveChanges();
    Output = "Merged " + counter + " duplicate classes.

" + sb.ToString();
}

That's my initial analysis so far.  I'll update some more once I've gained understanding on what you are doing.  As I've said, it is very difficult to read.  I'll probably offer more improvements once I've had a chance to look at it more.


Is this a correct use of using protocols and delegate pattern in Swift?

While this code is technically fine and will work, as Flambino has pointed out, it's rather pointless and with the fact that play() is called in didStartPlaying() it's a bit confusing.  I know that's an implementation detail and doesn't have anything to do with the protocol necessarily, however, it does hint at a lack of understanding of protocols/delegates.

There's not a lot out there in the way of Swift code.  However, there is a lot out there in the way of Objective-C code.  And in Objective-C, there's heavy use of the protocol-delegate pattern as well.

The same Foundation protocol/delegate patterns exist exactly as they are in Objective-C also in Swift, it's just a different syntax.  But the method names are all basically the same, and you can definitely pick up on the very distinct naming pattern and get the idea of how protocol/delegate patterns work.

The most common protocol/delegate pattern in iOS development is that of the UITableViewDelegate and UITableViewDataSource (something similar probably exists for NSTableView in OSX).  Almost everyone who has done much of an iOS programming has at some point worked with a UITableView.

What actually makes a lot more sense in this case is for PlayableMedia to be a superclass.  BlueRayMedia and DVDMedia should be subclasses of PlayableMedia... and these objects should be delegated.

What would make a lot of sense would be something like this:

protocol PlayableMediaDelegate {
    func shouldBeginPlaying() -> Bool
    func willBeginPlaying()
    func didBeginPlaying()

    func shouldStopPlaying() -> Bool
    func willStopPlaying()
    func didStopPlaying()
}

Now the media has a delegate property, which is simply an AnyObject that conforms to the PlayableMediaDelegate protocol.

Any object can call play() on the PlayableMedia object, and then the play method would actually look something like this:

func play() {
    if delegate.shouldBeginPlaying() {
        delegate.willBeginPlaying()
        println("PlayableMedia is now playing...")
        delegate.didBeginPlaying()
    }
}

And stop() would look something like this:

func stop() {
    if delegate.shouldStopPlaying() {
        delegate.willStopPlaying()
        println("PlayableMedia has stopped playing...")
        delegate.didStopPlaying()
    }
}

Where in both cases the println() code is replaced with code that would actually start/stop the playable media from playing.

The point here is with these delegate methods, we let ANY OBJECT delegate our playable media.  The shouldBeginPlaying() and shouldStopPlaying() methods give our delegate a chance to prevent/allow that action from happening.  If the delegate returns false from this method, the action isn't taken.

The other methods just let our delegate know about the life cycle of the media starting/stopping.

Some examples of things that you might want to do in these delegate methods...

In shouldBeginPlaying(), you may check the media's age restrictions and decide not to play the media.  You may also check the device battery life, etc.  Any condition in which you might not want to play the media, your delegate can just return false from this method to prevent the action from happening.

In willStopPlaying(), the delegate may want to save the current position in the media so that it can be resumed later.  The PlayableMedia class probably shouldn't necessarily do keep track of where it left of last time.

In willBeginPlaying(), you might want to call some methods on the PlayableMedia object to finish setting it up for getting played.  Perhaps moving to the point in which was last left off.

The main idea here is that we're writing a class that we want to allow delegation by any sort of unknown object.  What you shouldn't do when designing a protocol is start by writing the class you intend to use as the delegate, then write a protocol to match that class, then write the class that needs to be delegated by the first class--that's backwards.


I could be wrong, but I think you could shorten ALOT of the code as follows:

$(function () {
    $(".social-option select").on("change", function(e) {
        $(".social-option select option:disabled").prop("disabled", false);
        $(".social-option select option:selected").each(function(i) {
            var $val = $(this).val();
            if ($val !== '0') {
                $(".social-option select option[value="+$val+"]").prop("disabled", true);
            };
        });
    }).change();
});

See fiddle with dynamic drop down added here


Trying to improve and better understand Intel SSE intrinsics

One improvement would be to restrict the number of (random) memory accesses. First notice is that for each sourceY[fixed] there's also a memory read from sourceY[fixed+1];

I believe these should be at least combined to single 64-bit memory accesses.

A more crucial improvement would be at higher level: is the interpolation really random, or could the xvalues be say localized to say 8-15 successive indices? Then I'd pursuit for a technique that reads them to 2 or 4 xmm registers and tries to shuffle the values in place an in parallel.


C++ Vector memory management in Game of Life

One rules of thumb to write idiomatic C++ is:

  Use references where you can and pointers where you have to.

It's especially true for argument passing to a variable.
In your case, you have the choice, so use references, for all the reasons cited by Ilya and also just because you won't have any * to put everywhere in your function. Your code might be clearer that way.


Firstly, there's an error in the code you've written which will prevent the calculator from working correctly:

document.getElementById('total').value = numbergrade;

You don't have an element with the ID of total so this will fail. I'm guessing you want to change this ID to percentgrade.

You also have invalid syntax here:

var percentscore =
if (numbergrade>=101) {

You need to assign a value to percentscore if you put an = sign after it. You're actually not using it in the rest of the code so you can get rid of the variable completely.

Next it can be cleaned up a bit. if (numbergrade >= 101) is a little unclear, compared to the shorter and simpler if (numbergrade > 100). The number 100 has meaning for a test because it's the maximum grade. The number 101 doesn't it's simply an invalid value. You could also extract this out into a variable to assign an even stronger meaning.

var MAX_OBTAINABLE = 100;

if (numbergrade > MAX_OBTAINABLE) {

Note the capital casing to indicate a constant. In more modern iterations of javascript you can actually create a true constant by using the const keyword rather than var or let

const MAX_OBTAINABLE = 100;

The next part which needs to be changed is your rendering of the values. Your percentgrade element is a textbox, so you should be setting it's value property. Currently you are setting the innerHTML which won't work.

document.getElementById("percentgrade").innerHTML =

Should become

document.getElementById("percentgrade").value =

The last part where you calculate the grade letter, could also do with some improvements. Whenever you find yourself using the same calculated more than once or twice, it becomes a good candidate to store in a variable. In this case, you've written document.getElementById('letter') many times. You can shorten in by extracting it into a variable before you start to determine the grade letter

var letterDisplay = document.getElementById('letter');

if (numbergrade >= 90) {
    letterDisplay.value = 'A+';
}
else if (89 >= numbergrade && numbergrade >= 85){
    letterDisplay.value = "A";
}

// ... etcetera

On this first line you've also attempted to assign the variable lettergrade to an if statement which is invalid syntax.

var lettergrade = if(numbergrade >= 90) {

You don't seem to be using this variable so you could get rid of this assignment. However, you could actually use that variable to make the above code even shorter. Starting off with the letter grade set to F we can do the following:

var letterDisplay = document.getElementById('letter');
var lettergrade = 'F';

if (numbergrade >= 90) {
    lettergrade = "A+";
}
else if (89 >= numbergrade && numbergrade >= 85) {
    lettergrade = "A";
}

// .... all the other if statements here.

else if (54 >= numbergrade && numbergrade >= 50) {
    lettergrade = 'D';
}

letterDisplay.value = lettergrade;

There are some more ways you could improve on this, but that's a few of the basic, for some slightly more advanced concepts like objects, functions and looping, take a look at this JS fiddle I created and have a play around


There's basically nothing to shorten here. Processing.js is already doing the heavy-lifting of setting up a canvas so you can draw, hooking up to the DOM, etc. etc., leaving you do focus on the task. And that task is:

draw a circle where the cursor is
make it red
with a dark border
that's 3px thick
on a white background

which is what your code does. Almost line for line (just backwards, kinda). So there's nothing to shorten.

Well, I guess you can reduce background(255, 255, 255); to background(255); since Processing will automatically assume you mean that 255 should be used for all three. But that's just a minor shortcut built into Processing.

But really, why shorten it? Short code is not a goal in itself*. Efficient code is a goal, but code length and efficiency are not the same thing. Sure, code can be inefficient and long - typically, that's how it works out (e.g. the code takes an overly complicated route to accomplish its task). But it can also be inefficient and short. Or long but very efficient.

Point is, you have to know what metric you're interested in. Maybe it's memory usage, maybe it's speed, maybe it's safety, or extensibility. Hopefully, it's also readability. Short code, in and of itself, doesn't automatically impact these.

Sidenote: Since JavaScript is almost always part of a web page, and thus sent over the internet, it is actually worth making it short, since it'll take less space, and thus download faster. But even that's only really interesting if you have thousands of lines of code. Those few lines above probably take less time to transmit than it takes to even establish the connection they're sent through.

But even if you have a ton of code, you'd use a minifier to make your JavaScript more compact after you've written it. You'd still work on the regular, readable code, and then let the minifier compress it into highly compact but humanly-unreadable gibberish.

For an example, go to google.com and view source - a lot of that nonsense is heavily optimized and minified javascript. But nobody wrote it like that. For another example, look at Processing.js itself: Here is the code pretty much as it was written (though there was probably a lot of tooling involved in piecing it together), and here's the minified version that a computer spat out.

Anyway, there's nothing in you code to shorten, but there is something that can be made more efficient. And in this case, that means more code:

strokeWeight(3);
stroke(24, 0, 0);
fill(245, 0, 0);
background(255, 255, 255);
noLoop();

mouseMoved = function() {
    ellipse(mouseX, mouseY, 30, 30);
};

You were drawing the circle in the draw function. That function runs many times a second. But if the mouse hasn't moved, why bother drawing another circle in the same place? Using draw is great for animation and stuff like that, where things are always changing. But here, nothing changes if the mouse doesn't move.

Also, if you run your code, but the mouse isn't anywhere near the canvas, it'll just endless draw circles at 0,0 - i.e. top left. It doesn't know where the mouse is, so it just defaults to zero, zero.

Hence, the code above calls noLoop() - which means that draw isn't being called constantly and pointlessly - and instead does its drawing in mouseMoved. So if you don't move the mouse, nothing happens. It only springs into action if the mouse coordinates change - that's when it has to draw a new circle.

Here it is in action.

*) Unless you're playing code golf for fun


Game where two players take turns picking numbers until a target sum (part 2)

About the algorithm

If you want to check for a force win on the first turn, you just need to check what happens when player one picks the lowest number and player two picks the remaining highest number.
If you want to check for a force win on the other turns you can repeat the check by removing numbers from the list and check the remaining highest and lowest numbers.

About the code

It took me a while to get how your code worked, I think it's overly complicated. You have flags to determine if a number has been picked, but if you really want to keep a copy of the original numbers (which you don't actually need) you can just, well, copy it.
I still don't really get the path variable. You use that to determine whose turn it is, but you don't need to know that, you only need to know if player one has a forced win.

This is how I'd go about it for a solution. Keep in mind that I didn't test every corner case, but it should give you an idea about what I mean:

def force_win(numbers, current_sum, expected_value):
    # Numbers are assumed to be positive integers
    # For simplicity I assume there are no duplicates
    # Otherwise be careful if min_value == max_value
    min_value = min(numbers)
    max_value = max(numbers)
    current_sum += min_value + max_value

    if (current_sum >= expected_value):
        return False

    numbers.remove(min_value)
    if (max_value in numbers):
        numbers.remove(max_value)
    if (len(numbers) == 0):
        return False

    if (min_value + max_value < expected_value):
        if ((current_sum + min_value) >= expected_value):
            return True
    force_win(numbers, current_sum, expected_value)

    return False

if __name__ == "__main__":
    print force_win([1,2,3,4,5], 0, 7)


How to set multiple variables at once in JavaScript?

From a very good book called JavaScript Patterns:

  Using a single var statement at the top of your functions is a useful pattern to adopt.  It has the following benefits:

  Provides a single place to look for all the local variables needed by the function
  Prevents logical errors when a variable is used before it's defined
  Helps you remember to declare variables and therefore minimize globals
  Is less code (to type and to transfer over the wire)

The author also recommends initializing the variables when you declare them when possible.


You can pass str to map rather than a lambda.
You can remove the need for map if you change your third loop to append str(number).
You can use string to remove the need for chr and int in the first three loops. By using:

string.ascii_letters:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits:
0123456789

You can combine all your loops into one string concatenation.
Don't use ; to end lines.
You can define array as a constant outside the function.
I recommend using Python 3, or changing print to be Python 3 compatible.

import random
import string

CHARACTERS = (
    string.ascii_letters
    + string.digits
    + '-._~'
)

def generate_unique_key():
    return ''.join(random.sample(CHARACTERS, 15))

print(generate_unique_key())

You can also use the secrets library (thanks @MathiasEttinger) which is a CSRNG version of random. It also contains the function secrets.token_urlsafe (thanks @Graipher) which generates a random string which is safe for use in URLs. Allowing:

def generate_unique_key(size=15):
    return secrets.token_urlsafe(size)[:size]


Generating a game board with squares in a rectangle

directions as a variable name instead of directionTuples.
Instead of having a bunch of ifs in generateBoard, use pattern matching.
Instead of passing x: Int, y: Int in generateBoard, just pass a tuple which you could call currentPos.  You could define a function to add the direction tuple with the currentPos tuple instead of typing x + directionTuples(direction)._1, y + directionTuples(direction)._2 twice.  (There might actually be a very easy way to add (Int, Int) + (Int, Int) in Scala, but I can't think of it right now.)


Excel VBA: Implementing Box Muller, Zigurrat and Ratio of Uniforms Algorithm

There are a few optimizations that can be made to the code to speed it up, mainly to do with how some mathematical operations are performed in VBA. Not sure if I have it implemented 100% accurately so please review for accuracy. Also, I'm sure there are more optimizations to be had, but this is hopefully a starting point for further conversation.

A lot of my changes may be PC specific. It may ultimately depend on your CPU and instruction set available. On my computer, this runs in about 2.5 seconds.

A list of changes:

I replaced all instances of raising something to a power of two, instead, I just multiplied the item by itself.
I pre-computed this part Sqr((2 * Exp(-1))) as it appears to always be the same, so it isn't calculated for each loop and put it into a constant.
I removed the variable v2, it wasn't really needed, you just needed to introduce Rnd in one more spot
General cleanup of the code, and renamed a few variables for clarity

Code

Sub RatioUniforms()
    Const NumberOfIterations        As Long = 10000000
    Const u2CalculationSecondHalf   As Double = 0.857763884960707 'Caching this part Sqr((2 * Exp(-1)))
    Dim Results(NumberOfIterations) As Double
    Dim PassCounter                 As Long
    Dim u1                          As Double 'Define a better name if possible
    Dim u2                          As Double 'Define a better name if possible
    Dim MyTimer                     As Double

    MyTimer = Timer
    Do While PassCounter <= NumberOfIterations
        Do: u1 = Rnd: Loop Until u1 > 0
        u2 = (2 * Rnd - 1) * u2CalculationSecondHalf

        If u1 * u1 <= Exp(-1 / 2 * (u2 * u2) / (u1 * u1)) Then
            Results(PassCounter) = u2 / u1
            PassCounter = PassCounter + 1
        End If

    Loop
    Debug.Print "Process took: " & Timer - MyTimer

 End Sub


Transactionally create something, if allowed

You don't need to use elif you can change that to just an if.
You can simplify code blocks by using guard clauses that have the following layout:

if a:
    ...
else:
    raise b

To:

if not a:
    raise b

...

You can use a in [b, c] rather than a == b or a == c.
As commented by Michel Billaud, "The code will be shorter with an auxiliary variable id = validated_data['user_institution'].id".

Employing the above would get the following which I find to be much easier to read.

def create(self, validated_data):
    user = self.context['request'].user
    if user.role == 'super_admin':  # ref PR 25.1
        return Transaction.objects.create(**validated_data)

    if user.role not in ['user', 'org_admin', 'site_admin']:  # ref PR 25.4
        raise serializers.ValidationError({'Error': 'You are not assigned a role.'})

    id_ = validated_data['user_institution'].id
    if not check_user_institution_exists(id_):
        raise serializers.ValidationError({'Error': 'This user institution does not exist.'})

    if check_user_belongs_to_institution(id_, None, user.id) <= 0:
        raise serializers.ValidationError({'Error': 'You do not belong to this institution.'})

    if not check_upload_permission(id_):
        raise serializers.ValidationError({'Error': 'You do not have upload permission for this '
                                                    'institution.'})

    return Transaction.objects.create(**validated_data)


Django controller method to list the top characters, guilds, and killers

I think you can just make a function to get the queryset and re-use it:

def queryset_from_page():
    page = request.GET.get('page')
    try:
        return paginator.page(page)
    except PageNotAnInteger:
        return paginator.page(1)
    except EmptyPage:
        return paginator.page(paginator.num_pages)

Also why is context being defined at different indentation levels?

    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

    context = {'object_list' : queryset}

vs

    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

        context = {'object_list' : queryset, 'class_type':CLASS_TYPE}

In one case you define context everytime, other times only when a particular branch in the exception handling is taken: is this a bug?


Improve Performance of Comparing two Numpy Arrays

This can be implemented concisely by using numpy.add.at:

In [2]: c = np.zeros((3, 3), dtype=int)

In [3]: np.add.at(c, (x, y), 1)

In [4]: c
Out[4]:
array([[16, 10,  0],
       [ 2, 10,  0],
       [ 2,  0, 22]])


You probably already know, but just for the record, there is of course a built-in sorted function:

>>> sorted([1, 1, 5, 3, 2, 3, 4, 3, 99, 99])
[1, 1, 2, 3, 3, 3, 4, 5, 99, 99]

I'm not sure if your algorithm has a name,
but in any case I'm afraid it's not very good,
because it's very inefficient.
First of all it's quadratic: for each element in the input, it visits all other elements.

It has other inefficiencies too, for example the way it replaces the None values is also quadratic.
This is because for each value, it uses the index function of the list to find the index, and this operation scans the content of the list.

Finally, the list is reversed twice in the process, which could be avoided by a different use of indexes.

Still preserving the essence of your algorithm, consider this alternative implementation that fixes some of the above points, along with a few other improvements:

def mysort(input):
    """
    >>> mysort([1, 1, 5, 3, 2, 3, 4, 3, 99, 99])
    [1, 1, 2, 3, 3, 3, 4, 5, 99, 99]

    """
    result = [None] * len(input)
    for num in input:
        x = 0
        for other in input:
            if num <= other:
                x += 1
        result[len(input) - x] = num

    for index, num in enumerate(result):
        if num is None:
            result[index] = result[index - 1]

    return result

But ultimately, it would be better to use an algorithm that is not quadratic.
I recommend to look into insert-sort and merge-sort for exercise.


LRU cache design using dict and doubly linked list

First off, the way you're commenting your functions is completely wrong. Proper commenting for functions uses Python docstrings. For example:

def my_func( ... ):
    """
    Write a description of your
    function and it's arguments
    here.
    """
    ...

Secondly, according to Python's official style guide, PEP8, your naming is incorrect. Variables and functions should be in snake_case, and classes should be in PascalCase. If the variable is a constant, it should be in UPPERCASE_SNAKE_CASE.

Finally, why do you have Node as a subclass of LRUCache? Why can't Node be a top-level class? I see no reason it shouldn't be.


First, I would separate loading the certificate from storing it.

They are independent concerns.
It allows multiple ways to load a certificate.
It improves testability.

As Kinjal suggests, logging the error is a good alternative when failure is recoverable. However, I would throw a custom exception (or use CertificateException) and let the caller decide to log and continue or terminate. I really don't like returning success codes when I can avoid it because it muddies the code with checks.

Finally, instead of setting a certificate or leaving the field blank consider modeling a certificate checking strategy. This would require a simple one-method interface CertificateCheck with two implementations: NullCertificateCheck and BasicCertificateCheck. Again this improves testability by providing a seam for mocking, separating concerns, etc. It also removes the need for if (this.certificate != null) checks and allows for more strategies and certificate types.

public void setupCertificate() {
    try {
        certificateCheck = loadX590Certificate(...);
    }
    catch (InvalidCertificateException e) {
        LOG.warn("Skipping certificate check", e);
        certificateCheck = new NullCertificateCheck();
    }
}

private CertificateCheck loadX509Certificate(File file) throws CertificateException {
    InputStream is = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        is = new FileInputStream(file);
        return new BasicCertificateCheck(cf.generateCertificate(is));
    }
    catch (FileNotFoundException e) {
        throw new CertificateException("Certificate file not found", e);
    }
    ... more exceptions ...
    finally {
        IOUtils.closeQuietly(is);
    }
}

Update: Since you're storing the certificate (or not) so you can check its validity, I assumed you were checking it at a later time and ideally multiple times. If this is the case, extract the logic into a CertificateCheck hierarchy using the Strategy pattern. If the certificate is checked once in isolation of any other data, this isn't necessary and I see no reason to store the certificate in an instance field.

  Note: I'm using Checkable as a stand-in for whatever contains the information that must be checked against the certificate. Your implementation would need to pass whatever is appropriate.

public interface CertificateCheck {
    boolean matches(Checkable thing);
}

// in the absence of a certificate, everything matches
public class NullCertificateCheck implements CertificateCheck {
    public boolean matches(Checkable thing) {
        return true;
    }
}

public class BasicCertificateCheck implements CertificateCheck {
    private final Certificate cert;

    public BasicCertificateCheck(Certificate cert) {
        this.cert = cert;
    }

    public boolean matches(Checkable thing) {
        // move the current checks you have here
    }
}


PHP include page index.php?page=GET safety preg_replace

You are checking if a certain key exists in an array: isset($pages[$page]) but you define the $pages array without keys, so they default to numeric ones. A much better approach is to skip the preg_replace thing (it is useless anyway) and create a router array:

$router = array(
    'url' => 'pages/foobar.php',
    'default' => 'pages/default.php'
);

This array maps urls to your internal pages. Then you check or the requested page exists:

if (isset($router[$_GET['page']]) {
    include $router[$_GET['page'];
} else {
    include $router['default'];
}


ema uses series in one place, where it references series[bar]. But bar is a global variable which is frowned upon. Let's pass series[bar] instead of series to ema.
That would be series[bar] in the for loop, but series[bar] is the same thing as close, so let's pass that instead.
ema's period is only used to calculate smoothing. Let's calculate smoothing outside and pass it in.
But now ema's a single line, so let's inline it
Let's put all of that logic inside a function
We use enumerate in the for loop, but we don't use bar

Result:

x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21]

def function(x, period):
    prevema = x[0]
    emaout =[]

    smoothing = 2.0 / (period + 1.0)
    for close in x:
        curema = prevma + smoothing * (close - prevma)
        prevema = curema
        emaout.append(curema)

    return prevema
print
print function(x, 5)

We can better by using numpy.

def function(x, period):
    smoothing = 2.0 / (period + 1.0)
    current = numpy.array(x) # take the current value as a numpy array

    previous = numpy.roll(x,1) # create a new array with all the values shifted forward
    previous[0] = x[0] # start with this exact value
    # roll will have moved the end into the beginning not what we want

    return previous + smoothing * (current - previous)


Obligatory disclaimer: My opinion.

I can see that you are a beginner - it's a little hard to explain what you should work on, because the path you're taking toward finding the highest value in an array is a little hard to understand.

Normally, you'd just need to do something like

public static double findHighestValue(double[][] doubles) {
    double currentHighestValue = Double.MIN_VALUE;
    for (int row = 0; row < doubles.length; row++) {
        for (int col = 0; col < doubles[row].length; col++) {
            double value = doubles[row][col];
            if (value > currentHighestValue) {
                currentHighestValue = value;
            }
        }
    }
    return currentHighestValue;
}

to find the maximum value of a 2D array (which is the question), but instead, you're returning an object Location.

I can understand where you got the class name idea -- locating a value -- however, it's counter-intuitive. Instead, a class name such as Case or Square would be a bit more descriptive due to the fact that the noun location has multiple meanings.

I'll show you what I would do to answer the question (finds the largest value in a 2D array), and then, to help you learn, I'll give you some tips on the code you already wrote.

As this question is extremely wide, I won't go as far as to explain everything, but I'll give you a few pointers.

What I would do

This isn't a really complex problem per se, so there's not a lot to explain.

Since you want to know the coordinates of the maximum value (column and row), we still need to create a custom class.

First, you must determine what the class represents.
In this case, it represents an element in a multidimensional array, so like I said earlier, I'll just use something a little bit more intuitive like a Case.

Why is Case a better name?

If you visualize the 2D array, it looks like this:

 _ _ _
|_|_|_|
|_|_|_|
|_|_|_|

And each square looks like a case.

Each case contains a value, and a position determined by the row number and the column number of the case, so those 3 parameters will be our fields:

public class Case {

    private int row;
    private int col;
    private double value;

    public Case(int row, int col, double value) {
        this.row = row;
        this.col = col;
        this.value = value;
    }

    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public int getCol() {
        return col;
    }

    public void setCol(int col) {
        this.col = col;
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }

}

With this new class in mind, the method we would use to find the case with the highest value would be something like this:

public static Case findHighestValue(double[][] doubles) {
    Case highestCase = new Case(-1, -1, Double.MIN_VALUE);
    for (int row = 0; row < doubles.length; row++) {
        for (int col = 0; col < doubles[row].length; col++) {
            double value = doubles[row][col];
            if (value > highestCase.getValue()) {
                highestCase = new Case(row, col, value);
            }
        }
    }
    return highestCase;
}

I would put that in an interface named something like CaseUtils (unless you have another class related to cases, e.g. CaseService, but since you initially only had a Main class and a Location class, I assume there isn't any), which would look like this:

public interface CaseUtils {

    static Case findHighestValue(double[][] doubles) {
        Case highestCase = new Case(-1, -1, Double.MIN_VALUE);
        for (int row = 0; row < doubles.length; row++) {
            for (int col = 0; col < doubles[row].length; col++) {
                double value = doubles[row][col];
                if (value > highestCase.getValue()) {
                    highestCase = new Case(row, col, value);
                }
            }
        }
        return highestCase;
    }

}

That way, if you want to add more methods of the same type (e.g. findLowestValue), you'll be able to add them there too.

As for how to implement it in your main, you just need to do something like this:

Case c = CaseUtils.findHighestValue(array);
System.out.println("The position of the case with the highest value is " + c.getValue()
        + " at (" + c.getRow() + ", " + c.getCol() + ")");

Tips on your current code

Your comments on the method locateLargest do not conform with the javadoc convention:

/*
 * Accepts a two-dimensional array as the parameter.
 * Creates a new Location object.
 * Returns a Location object with maxValue at position (0,0) unless a larger value is found.
 */

should instead be something like:

/**
 * Locates the largest double
 * @param a two-dimensional array as the parameter.
 * @return Location object with maxValue at position (0,0) unless a larger value is found.
 */

If you want to read more about Javadoc, I suggest you read this article.

The class Location should not have public fields, but private fields with public getters and setters instead. As for why, you can search online, but this is also a good explanation: Why do we need private variables?

If you have any questions, feel free to ask.

NOTE

I used the name Case to highlight that the class name should clearly explain what it is. However, I wouldn't personally use that class name and instead, I would use Cell because the keyword case is reserved (switch case).


Checking whether a table has modified rows

Is one design pattern better than another?

Every code statement is a potential defect. If you can express yourself in a shorter form without sacrificing readability, then by all means you should. The less code, the less to read and debug, the fewer suspicious elements.

  Is there a performance difference in the two?

I don't actually know VB, but this is a common pattern in many languages, and it's clear that the performance should be the same, or the second might be even faster, thanks to some optimization magic by the compiler.

  Would my version with the using syntax have any unanticipated results?

Increased understanding among readers? You changed not just the writing style, but you also gave the variables more meaningful names. It's intuitive and a lot easier to read than the first one. Both seem to accomplish exactly the same thing.

  Should I leave the old code alone?

Probably. Don't fix what ain't broken. Although the original method is not implemented pretty, from the outside it doesn't really matter: it has a good name, and it does exactly what the name says and nothing else, it works. It's nice to make it nicer, but there isn't really a need. Now that you looked at it closely and know that it works, try to treat it as a black box, and remember not to open again. Use your energy for more creative tasks.


Object array with identifier: use index to quickly access elements by id?

Your implementation is basically a Map or Object that revolves around a very specific rule. That rule being the id directly correlates to the index in the array. The advantage an Array has over other data structures, with superior search speeds, is the fact that they are ordered. If order doesn't matter and you're purely using it to leverage search, Sets and Maps do a better job


Generation of Groovy source from parent Java class

You can use Groovy to generate the Groovy source code.

The source code generator

Here's an example source code generator.

import groovy.text.SimpleTemplateEngine

def generate(Class klass, String packageName, String name, String template) {
    def engine = new SimpleTemplateEngine()
    def binding = [
        packageName: packageName,
        name: name,
        superClass: klass.name,
        methods: klass.metaClass.methods
            .findAll { !(it.toString().contains(' final ')) }
            .collect {
                def args = []
                def m = it.toString() =~ /(.*) (.*\.)(.*)(\((.*)\).*)/

                m.matches()
                if(m.group(5).size() > 0) {
                    m.group(5).split(',').eachWithIndex {arg, index ->
                        args << "$arg p$index"
                    }
                }

                return "${m.group(1).replace('native', '')} ${m.group(3)}(${args.join(', ')})"
            }
    ]

    engine.createTemplate(template).make(binding).toString()
}

How it works

It's actually quite simple. The method signatures are gathered from the class's MetaClass. Then some hefty formatting is applied to write the method signatures correctly. Also, final methods are excluded.

Example

def template = '''
package $packageName

/* Code auto generated
 * do edit what You want
 */

class $name extends $superClass {
<%
methods.each {
    println ''
    println "\t$it {"
    println ''
    println "\t}"
} %>
}
'''

generate(Object, 'my.script', 'SelfGenerator', template)

Generated source code

package my.script

/* Code auto generated
 * do edit what You want
 */

class SelfGenerator extends java.lang.Object {

    public boolean equals(java.lang.Object p0) {

    }

    public  int hashCode() {

    }

    public java.lang.String toString() {

    }

}

Templates

Ideally, you'd have two templates: one for the class and one for the methods. That would avoid the clunky JSP-style programming. You can read more about Groovy's template engines here.


Merge a new interval into given array of intervals

Avoid indexing repetitively. You know that you'll want intervals[i] frequently within the loop, so index it once... or better yet, loop on it efficiently in the first place:

for i, (low, high) in enumerate(intervals):
    if new_interval[0] < low and new_interval[1] < low:
        # ...

Along the same lines, you frequently want the know the min and max of the new interval; you already compute these values, why keep it as a tuple that has to be indexed again and again?

new_low, new_high = min(new_interval), max(new_interval)
# ...
for i, (low, high) in enumerate(intervals):
    if new_low < low and new_high < low:
        # ...

Use my_list.pop(i) instead of my_list.remove(my_list[i]). The first requires Python to iterate through the list element by element, check for equality against my_list[i], and remove the first equal element it finds; the second tells it exactly what part of the list you want gone much more efficiently, since you already know the location i.

Better yet, use an approach that doesn't modify intervals at all (no popping or inserting). It's entirely possible to solve this problem by only appending new outputs to final_interval with no other list mutations. That's particularly important if you're iterating on intervals, in which case mutating it within the for loop will break your code.

Your final loop is O(N^2), which is not necessary for this problem:

for elem in intervals:  # O(n)
    if elem not in final_interval:  # O(n)
        final_interval.append(elem)

Since you know that the values in intervals are sorted already, I would instead suggest an approach that stops the first loop after you've output new_interval and all intervals it overlaps with, then the second loop just pumps out the remaining items from where the first loop left off.

And now to actually answer your specific error: you've defined your function to work on a list of lists (or tuples, whatever), and return the same; the actual problem hosted on the site provides a list of Interval objects and expects a list of Interval objects back. This is easy to support:

def insert(self, intervals, new_interval):
    intervals = [(v.start, v.end) for v in intervals]
    new_interval = (new_interval.start, new_interval.end)
    new_low, new_high = min(*new_interval), max(*new_interval)
    # ...
    return [Interval(l, h) for l, h in final_interval]


Change implementation from getting json from file to get it from API

public interface IAsyncConfigurationService : IConfigurationService{
    Task<Configuration> GetConfigurationAsync(int agentId);
}

public class ConfigurationApiClient : IAsyncConfigurationService
{
    //...
    public Configuration GetConfiguration(int agentId)
    {
        return GetConfigurationAsync(agentId).Result;
    }

    async Task<Configuration> IAsyncConfigurationService.GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(""); // TODO add the url
            response.EnsureSuccessStatusCode();
            var Configuration = await response.Content.ReadAsAsync<Configuration>();
            return Configuration;
        }
        catch(HttpRequestException ex)
        {
            throw new ConfigurationException(string.Format("Exception when getting  settings for agent: {0}", agentId), ex);
        }
    }
}

With this, at least, you're able to try to do a cast to this interface
and call the assynchronous version.

If you are able to change the interface just a little bit and still have only the synchronous version, you could add an event, for when the configuration is ready:

public interface IConfigurationService
{
    void LoadConfiguration(int agentId);
    event EventHandler<ConfigurationArgs> ConfigurationLoad;
}

public class ConfigurationArgs{
    public Configuration Config{get;set;}
}

public class ConfigurationApiClient : IConfigurationService
{
    //...
    public event EventHandler<ConfigurationArgs> ConfigurationLoad;

    private void OnConfigurationLoaded(Configuration config){
        var handler = ConfigurationLoad;
        if(handler != null){
            handler(this, new ConfigurationArgs{
                Config = config
            });
        }
    }

    public void LoadConfiguration(int agentId)
    {
        GetConfigurationAsync(agentId).ContinueWith(e => {
            OnConfigurationLoaded(e.Result);
        });
    }

    async Task<Configuration> GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(""); // TODO add the url
            response.EnsureSuccessStatusCode();
            var Configuration = await response.Content.ReadAsAsync<Configuration>();
            return Configuration;
        }
        catch(HttpRequestException ex)
        {
            throw new ConfigurationException(string.Format("Exception when getting  settings for agent: {0}", agentId), ex);
        }
    }
}

The semantic now is that you can call LoadConfiguration any number of times (because I guess it could change),
and have the result on the event handler.


Null Object pattern with simple class hierarchy

This is a preliminary answer:

  Assume for the sake of this question that going that route isn't
  practical.

Assuming this is about some group of similar value objects.
Everything is meaningful in a context. So we need to determine what are the use cases for this object. Suppose we have the following use cases (I'm trying to guess how you could end up with the provided interfaces.):

We need to display a ZipCode on screen
We need to print ZipCode on envelopes
We also need to lookup some external service for demographic data using the 5-digit ZIP as a key.

Simplest thing that could work would then be something like:

interface ZipCode
    Zip primary() // for service lookup
    String getScreenRepresentation()
    String getPrintRepresentation()
    // you may one to use Visitor pattern
    // if you have much more different formats

Now we may try to design a Null Object that could work for all these situations.
for ZIP and ZIP+4 their implementations are straight forward.
For NullZipCode we can have getScreenRepresentation to return "No ZIP provided" and
getPrintRepresentation to return empty string. You definitely would not want "00000" or some other invalid value on the label. (Unless in the improbable case that US postal service requires people put it to designate unknown ZIP, but you get what I mean)

My criticism of the below code

interface ZipCode
    boolean isPlusFour()
    ZipPlusFour plusFour(String code)
    Zip primary()
    boolean hasSamePrimary(ZipCode other)

class Zip implements ZipCode
    String code

class ZipPlusFour implements ZipCode
    Zip primary
    String plusFourCode

isPlusFour is the back door where all the null checks sneak back in.

plusFour(code) does not belong in the interface. It is a factory method. One sign it does not belong there is Zip and ZipPlusFour should not be able to provide different versions.

hasSamePrimary is unnecessary. Value objects should provide their equality, comparison, hash, display string etc. by overriding equals, hashCode etc in Java, (or deriving Show, Eq in Haskell and so on). By value object semantics; zipCode1.hasSamePrimary(zipCode2) should be equivalent to zipCode1.primary().equals(zipCode2.primary()), it is not an overridable behavior (Closed for modification principle). If it is there for brevity, it can be placed in an abstract base class or as a static method in a Utility class (or extension method if you are using C#, etc.)

What you should do for Dealer class cannot be a simple interface, if it is to be a value object also.

class ZipOrZipPlusFour implements ZipCode
     //fields depend on what sort of persistence you use
     // factory methods:
     newNullZipCode()
     newZip(String code)
     newZipPlusFour(Zip primary, String ext)

class Dealer
    ZipOrZipPlusFour zipCode


Here are some suggestions:

Don't use global variables.
Instead of using a single big function, break it down to logical parts.
const int N = 1000000; should be constexpr instead of const.
Instead of = {0}, use {}.  The latter makes it clear that you are
value initializing all elements.
i should be declared in the loop.
Post-increment operators i++ should be changed to pre-increment
++i in a discarded-value expression.
iCpy & 1 should be iCpy % 2 == 0.  iCpy <<= 1; // Equivalent to iCpy *= 2 should be iCpy *= 2.  Optimization doesn't happen in this way — the compiler knows such things much better.
Use << '\n' instead of << std::endl when you don't need the flushing behavior.


Getting the largest element in an array using recursion

I would use a helper function, and I would avoid copying the array (using indices instead):

public static int getLargest(int ... myArray) {
    return getLargest(myArray, 0, myArray.length);
}

private static int getLargest(int[] myArray, int from, int to) {
    if(from == to) {
        throw new IllegalArgumentException("empty array");
    } else if (from + 1 == to) {
        return myArray[from];
    } else {
        int middle = (from + to)  / 2;
        return Math.max(getLargest(myArray, from, middle),
                        getLargest(myArray, middle, to));
    }
}

Using varargs int ... instead of an array int[] for the argument makes it more flexible, e.g. better testable.

In case you really want to copy the array, use System.arraycopy, which is much faster than looping through.


Assuming you want to avoid opening the file unless necessary (ie until someone requests the PageCount), I would use a nullable private field, as follows:

private int? _pageCount;

public int PageCount
{
    get
    {
        if (!_pageCount.HasValue) {
            //existing code to determine page count

            _pageCount = /* result */
        }
        return _pageCount;
    }
}

The first time the property is accessed, the private member will be null, so the code to update the value will be run.  Subsequent accesses will use the cached value.


Please take a look at itertools.product. It will simplify your code greatly.

def getCombos(digits, caps, numbers):
    # Build set of choices appropriately based on caps and numbers
    choices = list(range(33, 126))
    for vals in itertools.product(choices, repeat=digits):
        print ''.join(map(chr, vals))

getCombos(3, True, True)


Some considerations on your current code:

Don't use == True. You either want to check the truth value of the object, in which case simply drop the == True, or you want to check for identity, in which case you should use is True(even though it's really rare to see is True/False. You usually check for is None).
Instead of lti == "y" or lti == "Y" or ... you can simply convert lti to lowercase and check for y. Something like lti.lower()[:1] == "y". This will include also things like yabbadu. An other option is to use in: lti.lower() in {"y", "yes"} accepts y and yes in any case(so also yEs is accepted.
You should follow the PEP8 when writing. It's the standard coding-style for python. Using it will allow all python programmers to read your code more easily. To follow this style you should use lower_case_with_underscore for functions/variables, FullCamelCase for classes.
Regarding the full code from pastebin: it is not well organized. Things like equipping an armor should be managed by a function or by some class and they shouldn't depend on the armor kind. It's probably a good example where using classes make sense. You should have an Armor class that provides the basic implementation of an armor and the various subclasses TunicArmor etc. that provide different armor points etc. Note that inheritance is not the only way to do it.

In the end the code would look like:

leather_tunic_item = False
if leather_tunic_item and not item_slot_armor_chest:
    item_slot_armor_chest = True
    chest_armor_value = 2
    print("The leather tunic is now equipped")
elif leather_tunic_item:  #no need: and item_slot_armor_chest.
    print("Your armor value is currently: ", total_armor_value, "Equipping a Leather Tunic will make this value: ", total_armor_value - chest_armor_value + 2)
    print("Would you still like to equip this item? (Yes or No)")
    lti = input("")
    if lti.lower() in {"y", "yes"}:
        item_slot_armor_chest = True
        chest_armor_value = 2
        print("Your armor value is now ", total_armor_value)
    else:
        print("This Leather Tunic will be discarded.")
        leather_tunic_item = False

A sample implementation of what I meant in the last point might be this:

class ArmorPiece:
    def __init__(self, name, points):
        self.name = name
        self.points = points

class NullPiece:
    """An armor piece that is used to represent a missing armor piece."""
    def __init__(self):
        super(NullPiece, self).__init__("", 0)

class Armor:
    def __init__(self, head=None, chest=None, legs=None):
        self.head = head if head is not None else NullPiece()
        self.chest = chest if chest is not None else NullPiece()
        self.legs = legs if legs is not None else NullPiece()

    def defense_points(self):
        return self.head.points + self.chest.points + self.legs.points

class Tunic(ArmorPiece):
    def __init__(self):
        super(Tunic, self).__init__("tunic", 2)

After this, if you want to replace the chest piece you could do:

def change_chest(armor, new_chest):
    if isinstance(armor.chest, NullPiece):
        # The player is not wearing a chest armor piece
        armor.chest = new_chest
        print("The {.name} is now equipped.".format(new_chest))
    else:
        # The player is wearing something else.
        print("Your armor value is currently: ", armor.defense_points(), "Equipping a {.name} will make this value: ".format(new_chest), armor.defense_points() - armor.chest.points + new_chest.points)
        print("Would you still like to equip this item? (Yes or No)")
        lti = input("")
        if lti.lower() in {"y", "yes"}:
            armor.chest = new_chest
            print("Your armor value is now: ", armor.defense_points())
        else:
            print("This {.name} will be discarded".format(new_chest))

You could make this function a method of Armor if you want, even though I like to separate the logic of the program from the input/output code. Your code will be more flexible.

Note that in the formatting strings the {.name} parts are replaced with the attribute name of the object passed to format. Doing "{.name}".format(new_chest) is the same as "{}".format(new_chest.name).

You should probably read a bit of the documentation about string formatting.

If you are not comfortable with classes you can simplify the code using some dictionaries. something like:

armor = {
    "head": {"name": "", "points": 0},
    "chest": {"name": "", "points": 0},
    "legs": {"name": "", "points": 0},
}

def defense_points(armor):
    return sum(value["points"] for key, value in armor.items())

To change the head armor simply do:

armor["head"] = {"name": "tunic", "points": 2}

The code to handle this would be pretty similar to the above, but replacing attribute access with item access(e.g. new_chest.name -> new_chest["name"]).


A few minor comments:

Don't mix equality types.

You use suggestion != "" in one place, then !suggestion.Equals(""). Don't. Use the same type of equality (either using .Equals or not using .Equals) everywhere.
Only use non-braced statements in the case of guard clauses, and even then be careful.

Basically, this is OK:

if (Keywords.Length == 0)
    throw new ArgumentException(nameof(Keywords), "No Keywords set!");

This is not:

if (userInput.Length > 0)
    userInput = userInput.Substring(0, userInput.Length - 1);

Try to use built-ins (especially System.Math) when possible.

I.e. take toClear = (userInput.Length > suggestion.Length) ? userInput.Length : suggestion.Length; and convert it to toClear = Math.Max(userInput.Length, suggestion.Length). They're functionally equivalent and the Math.Max reads nicer.

The rest of it looks good, I think you did a pretty good job implementing the idea here. I might suggest building functions out, but this is a small enough program it's probably not necessary.


You need to convert your second query to a subquery and join it with the main query. To pass the learning outcome into the inner query you need to use the user-defined variable:

SELECT
    sc.studentsisid,
    sc.coursename,
    sc.learningoutcomeid,
    sc.learningoutcomename,
    count(sc.RecordID) as assessmentcount,
    count(if(sc.outcomescore >= 3,sc.outcomescore, NULL)) as over3,
    avg(sc.outcomescore) as scoreavg,
    l.recentover3,
    l.recentscoreavg
FROM studentscores sc
INNER JOIN (
    SELECT studentsisid,
        learningoutcomeid,
        count(if(outcomescore >= 3,outcomescore, NULL)) as recentover3,
        avg(outcomescore) as recentscoreavg
    FROM (
          SELECT
              (@studentsisid := studentsisid) as studentsisid,
              (@coursename := coursename) as courcename,
              (@learningoutcomeid := learningoutcomeid) as learningoutcomeid,
               @num := if(@studentsisid = studentsisid and
                          @coursename = coursename and
                          @learningoutcomeid = learningoutcomeid,
                       @num + 1, 1) as row_number,
               outcomescore
          FROM studentscores
          ORDER BY studentsisid, coursename, learningoutcomeid, recordid DESC) as r
        where row_number <= 3) AS l
ON sc.studentsisid = l.studentsisid AND sc.learningoutcomeid = l.learningoutcomeid
WHERE sc.studentsisid LIKE '$studentid' AND sc.coursename='$coursename'
GROUP BY sc.studentsisid, sc.coursename, sc.learningoutcomeid
ORDER BY sc.studentname, sc.learningoutcomename


Calculating how many Pomodori fit into a period of time

I think it would be simpler just to apply some ingenuity and partially unroll the loop.  While it's possible to fit in a long cycle (pomodoro, short break, pomodoro, short break, pomodoro, short break, pomodoro, long break) with time left over, then do that.  While it's possible to fit in a short cycle (pomodoro, short break) with time left over, do that.

I'd also define some constants for readability.

pomodori is not quite an appropriate name for the result, since it includes pomodori and breaks.

It would be a good habit to encapsulate your code in a function.

SECOND = SECONDS = 1
MINUTE = MINUTES = 60 * SECONDS
HOUR = HOURS = 60 * MINUTES

POMODORO = 25 * MINUTES
SHORT_BREAK = 5 * MINUTES
LONG_BREAK = 15 * MINUTES

def manage(time):
    """ Devise a Pomodoro schedule for a time span, given in seconds. """
    schedule = []
    while time > 4 * POMODORO + 3 * SHORT_BREAK + LONG_BREAK:
        schedule.extend(3 * ['pomodoro', 'short-break'] + ['pomodoro', 'long-break'])
        time -= 4 * POMODORO + 3 * SHORT_BREAK + LONG_BREAK
    while time > POMODORO + SHORT_BREAK:
        schedule.extend(['pomodoro', 'short-break'])
        time -= POMODORO + SHORT_BREAK
    # 0 < time < POMODORO + SHORT_BREAK
    schedule.append('pomodoro')
    return schedule

print(manage(3 * HOURS))


Group key-value pairs in chunks no longer than specified limit

def group(url,D,limit):

D is a bad parameter name because it doesn't follow the python convention: lowercase_with_underscores, and because it a pointless abbreviation.

    if len(D) == 0:
        if len(url) <= limit:
            yield url
            return
        else:
            raise ValueError("url is longer than limit")

    if len(url) > limit - 2:
        raise ValueError("url is too long to be able to hold any key-value pairs")

Is this really a useful check? Two characters is probably not enough to actually hold any of the pairs. You probably don't catch anything here you wouldn't already catch

    for i,(key,value) in enumerate(D.iteritems()):
        if i == 0:

enumerating for the sole purpose of special casing the first entry is rather gross.

            old = url
            new = '{url}?{key}={value}'.format(**locals())
            continue

I discourage the use of continue. It's almost always better to put things in an else block

        new, old = '{new}&{key}={value}'.format(**locals()), new

Use of locals() is discouraged. It encourages sloppy coding and forces python into a slower compatibility mode for that function.

        if len(new) > limit:
            if len(old) > limit:
                raise ValueError("String '{old}' is longer than GET query limit.".format(**locals()))
            yield old
            old = url
            new = '{url}?{key}={value}'.format(**locals())
    if len(new) != len(url):

In which case would this be false?

        if len(new) > limit:

Why is this check inside the other check?

            raise ValueError("String '{new}' is longer than GET query limit.".format(**locals()))
        yield new

Of course, you've already noted the duplicated code here.

Here's my take on reworking it:

def blocked(items, limit, seperator):
    """
    items is a list of strings, to be joined with seperator.
    Produces a generator of strings, each with a length <= the limit
    """
    current = []
    current_length = 0
    for item in items:
        length = len(item) + len(seperator)
        if length > limit:
            raise ValueError('{} cannot fit'.format(item))
        elif length + current_length > limit:
            yield seperator.join(current)
            current = [item]
            current_length = length
        else:
            current.append(item)
            current_length += length
    yield seperator.join(current)

def group(url,data,limit):
    if len(url) > limit:
        raise ValueError('{} is longer than the limit of {}'.format(url, limit))

    pairs = ["{}={}".format(k,v) for k, v in data.iteritems()]
    for block in blocked(pairs, limit - len(url), "&"):
        if block:
            yield '{}?{}'.format(url, block)
        else:
            yield url


Meshing algorithm for generating faces in Minecraft

First of all, the way you're formatting your code is horribly confusing.

if(Inside(neigh, ivec3(0), ivec3(SIZE) - 1))
    if(data[neigh.x][neigh.y][neigh.z])
        goto skip;

{
    ...
}

The block here looks a lot like it's in the if condition but it's not (it's just a C-like block without any condition attached to it). I really suggest using braces for your ifs to avoid confusion. Another confusing part is for(int dim = 0; dim < 3; ++dim) { int dir = -1; do {: when I see a for loop, I don't expect to see another loop at the end of it.

Now, about your question. Some languages (such as Java) support naming loop, which allows you to break to outer loops. This doesn't exist in C++, and the best option is to use a goto.


Template function specialization with code duplication

The check is better factored into a specialization on a traits class. This allows you to have one implementation of the overall logic flow, and just specialize the part that changes. I haven't fully researched the implications of this approach, but I expect that due to the always true/false nature of the check (for most given types), that it will be easily optimized away.

It would look something like this:

// traits class to determine whether to do the check
template <typename> struct ResultCanBeNull : std::false_type {};
template <> struct ResultCanBeNull<char*> : std::true_type {};

template<typename ResultType, typename v8MappingType>
v8::Handle<v8::Value> Curl::GetInfoTmpl( const Curl &obj, int infoId )
{
    v8::HandleScope scope;

    ResultType result;

    CURLINFO info = (CURLINFO) infoId;
    CURLcode code = curl_easy_getinfo( obj.curl, info, &result );

    // use the traits class to filter in or out the null pointer check
    if ( ResultCanBeNull<ResultType>::value && !result ) { //null pointer
        return v8::String::New( "" );
    }

    if ( code != CURLE_OK )
        return Curl::Raise( "curl_easy_getinfo failed!", curl_easy_strerror( code ) );

    return scope.Close( v8MappingType::New( result ) );
}

You could also implement the traits support as a method instead, in case it's not valid to call !result on instances of other types that are reasonable for ResultType.

template <typename ResultType>
struct ResultTraits {
    bool IsNull(const ResultType&) { return false; }
};
template<> bool ResultTraits<char const*&>::IsNull(char const*& pchar) {
    return !pchar;
};

: : :

    if (ResultTraits<ResultType>::IsNull(result)) {
        return v8::String::New( "" );
    }


Specifying UTC time or current time offset

In terms of conventions there is nothing to poke at there.

Where I find that approach lacking is that it tries to merge two different concepts. Namely a point in time an a time difference (or offset). Another non .NET example that I can think of is swift which has Date and TimeInterval. TimeInterval being an alias for a double which represents the offset in seconds.

Most libraries (.NET included) have distinct types to separate these two concepts.

To illustrate where it goes wrong I would expect

Utc.Now == DateTime.Now

But it is not.

I understand the convenience for have the common type and using the type system to enforce this for you but consumers of the API would have some trouble with it.

Two alternatives:

Use a built in library type. Either DateTime to specify the exact time of execution or TimeSpan.

In this case DateTime provides the utility of ToUniversalTime() but that would require the implementer of the interface IApi to ensure that this is done. As long as you clearly document what you expect it is OK.

An added benefit is that you don't have to reinvent the wheel and your code is now more portable between all .NET platforms. These types include IComparable and IEquatable already which is one less thing to worry about for the future.

Keep the type Utc but make sure you keep the underlying type consistent to either by an offset or a fixed time.

Either one works. I would lean to storing the backing data as TimeSpan. Converting a time to the time interval from when it was called.

The implicit conversions in this case are a good idea.


Finding the next higher digital permutation of a number

First of all: your code is very readable and you seem to know your way around standard library functions, which is very important is Haskell. Good job!

A couple of suggestions:

A simpler isSortedDesc:

import Data.List.Ordered (isSortedBy)

isSortedDesc :: (Ord a) => [a] -> Bool
isSortedDesc = isSortedBy (>=)

Edit: Sorry, isSortedBy is not a standard function - it belongs to data-ordlist-0.2. I'd implement it in a straightforward recursive manner:

isSortedDesc :: (Ord a) => [a] -> Bool
isSortedDesc (x:y:xs') = x>=y && isSortedDesc (y:xs')
isSortedDesc _ = True

foldFun:

In foldFun, try to make the arguments more understandable. You can add a type signature, name the arguments or add a comment. For example, what is the purpose of the boolean argument?

Another thing: nextHigherPermutation has two execution steps - find a digit we can swap, and then just copy the rest of the string. Personally I'm not a fun of the idea of passing extra information to fold (the boolean argument) and then discarding it. Instead, consider splitting it to two seperate functions - for example, one that finds the swap digit and another that performs the swap.


Longest Common Prefix in an array of Strings

Pure functions should generally be declared static.

You shouldn't need to take substrings in a loop — that's inefficient.  Think of scanning a two-dimensional ragged array of characters.  Check that all of the first characters match, then that all of the second characters match, and so on until you find a mismatch, or one of the strings is too short.

public static String longestCommonPrefix(String[] strings) {
    if (strings.length == 0) {
        return "";   // Or maybe return null?
    }

    for (int prefixLen = 0; prefixLen < strings[0].length(); prefixLen++) {
        char c = strings[0].charAt(prefixLen);
        for (int i = 1; i < strings.length; i++) {
            if ( prefixLen >= strings[i].length() ||
                 strings[i].charAt(prefixLen) != c ) {
                // Mismatch found
                return strings[i].substring(0, prefixLen);
            }
        }
    }
    return strings[0];
}

Space complexity: O(1).

Worst-case time complexity: O(n m) to scan every character in every string.


Yes.

Actually quite a lot. But it's all easily salvageable.

static. It's all static. Hard to test and impossible to use twice (imagine top-ten of two classes of products). Any mutable static field is a code smell. Just drop it everywhere. Rename main and add a new main creating an instance and calling the original main.
private static ConcurrentMap<Integer,Integer> itemsScores;

This can be initialized inline just like the lists.

public static void main(String[] args)
{

Proper Java style is
public static void main(String[] args) {

This applies to all blocks, not only to methods.

Integer boughtItem = new Integer((int)(Math.random() * 100) + 1);

Don't use Math.random() with some strange arithmetic when you can create a new Random() and write
random.nextInt(100)
Don't use new Integer when you don't need a new instance (you should never need a new instance). Use Integer.valueOf, or just leave it out (autoboxing).

    assert isSorted(topTenItems);

Asserts are fine, but not for this. Checking that the list is sorted is actually the only thing the code does, so it makes no sense to switch it off. So use
   if (!isSorted(topTenItems)) {
        throw new WhateverException("some message");
   }

or better: Write a proper test using JUnit or alike.

public static boolean isSorted(List<Integer> l)

This doesn't do what the name promises. I'd expect a sorted list not to change after I call Collections.sort. Your list is descending. Moreover, it must be strictly descending. So the method name should express it.
Checking for strictly descending is wrong, isn't it?

    Integer newScore;
    if (oldScore == null)
        newScore = 1;
    else
        newScore = oldScore + 1;

Always use braces. Or better, write
    Integer newScore = oldScore == null ? 1 : oldScore + 1;

It's much shorter and clearer.

    doTopTen(itemId,newScore);

Wouldn't updateTopTen be a better name?

private static void doTopTen(Integer itemId, Integer newScore) ...

This looks very complicated. What's worse:

You're using synchronizedList, so you're assuming concurrent access.
The method itself is not synchronized and it'' probably break.

Imagine you test topTenItems.contains(itemId) and in the meantime another thread(s) change the list. So you're doing something based on a wrong test outcome.
I'm a bit lost
Your items are Integers and you're assuming they're sorted, too. Why should they? What do you need them for?
I might go for something like
// start empty as initially there's nothing in top ten
private final List<Integer> topTenItems = new ArrayList<Integer>();
// no topTenScores

private final Object lock = new Object();

private void updateTopTen(Integer itemId, Integer newScore) {
    synchronized (lock) {
        int index = topTenItems.indexOf(itemId);
        if (index == -1) {
            index = topTenItems.size();
            topTenItems.add(itemId);
        }
        while (index > 0 && itemsScores.get(index) > itemsScores.get(index-1)) {
            swap(index, index-1);
            index--;
        }
        if (topTenItems.size() > TOP_TEN_SIZE) {
            topTenItems.remove(TOP_TEN_SIZE);
        }
    }
}


How optimize set of nested 'if' in one function?

I am not sure I understand what is supposed to happen in

    if ('main' !== session('type') && is_null($token)) {
        $instagramProfile = $this->findInstagramProfile($user);
        $token = $instagramProfile->profile->user->api_token ?? null;
    }

if by any chance $instagramProfile->profile->user happens to be null. Otherwise, refactoring is very straightforward. Just lift the common actions out of the if/else one by one:

    $instagramProfile = this->findInstagramProfile($user);

    if (!$instagramProfile) {
        $instagramProfile = create_instagram_profile($user);
    }

    user = $instagramProfile->profile->user;
    if (!user) {
        $user = $this->createUser($instagramProfile->profile);
    }

    $token = $user->api_token;

Observe that it is just a mechanical rewrite.

PS: I presume that create_instagram_profile can be safely called with null argument; you are doing it anyway.


Encapsulate common parts of Entity Framework queries

Probably more can be made to clean that code but from your snippet I'd first introduce an extension method. You're using an object just to hold some parameters.

static class MyContextExtensions
{
    public static IQueryable<Document> SelectDocumentsAccessibleToUser(this MyDbContext dc, IQueryable<Document> query, Guid userId)
    {
        var permissionsQuery = dc. ... // really big query with multiple JOIN's to determine which user has access to which documents
        IQueriable<Guid> docIdsAccessibleToUserQuery =
            from permissions in permissionsQuery.Where(_ => _.UserId == userId && _.AccessLevel == "Read")
            select permissions.DocumentId;

        return from accessibleDocId in docIdsAccessibleToUserQuery.Distinct()
                from accessibleDoc in query.Where(g => g.Id == accessibleDocId)
                select accessibleDoc;
    }
}

Simply used like this:

public void GetLatestDocsCount(Guid currentUserId)
{
    using (var dc = new MyDbContext(_environment))
    {
        var docQuery = dc.Docs.Where(d => d.CreatedDate > DateTime.Now.AddDays(-1));
        docQuery = dc.SelectDocumentsAccessibleToUser(docQuery, currentUserId);
        int latestDocsCount = docQuery.Count();
        return latestDocsCount;
    }
}

Few other things:

You named a lambda parameter as _ and you're actually using it. It's not a rule but as widely accepted convention _ is reserved for an unused parameter. Rename it to something appropriate (or...x, at least).
Do not hard-code "Read" string, you might want to introduce a private const string field for that. From your snippet it may be local to MyContextExtensions but I guess you use it also elsewhere. Is there a reason you're using a string for that? It's a good candidate to be an enum.
I feel strange when I see mixing plain LINQ calls and query syntax. If there is no other reason you may want to stick to one of them (at least within same expression).

For example:

IQueriable<Guid> docIdsAccessibleToUserQuery = permissionsQuery
    .Where(_ => _.UserId == userId && _.AccessLevel == "Read")
    .Select(x => x.DocumentId);

latestDocsCount local variable does not really help to understand better your code, you may drop it and simply return docQuery.Count();.
It's opinable but IMO if you keep functions short (good!) then docQuery might simply be query.
DateTime.Now.AddDays(-1) shouldn't be hard-coded, it's an important peace of information. I'd move that query into a separate method GetDocumentsCreatedYesterday().
You're using DateTime.Now instead of DateTime.UtcNow. It may be or not an issue in your case but consider that time is adjusted (summer time) then twice per year you may get incorrect results. Also remember that if your users are spread all over the world then you'd better to store UTC time and format to local time only for presentation.
After our first refactoring step you do not have DocumentPermissionsHelper class but in general don't forget to mark a class as sealed when it's not intended to be extended.