Random game code id generator in typescript

One important consideration: should those who do not have the code for a room be able to guess it (or guess a random code) and enter a room they were never told the code for? If not, then 4 characters probably isn't quite enough:

If guesses and codes were random, the chance of guessing a lobby is on the order of magnitude of 100/450_000. Chances are low, but they're not astronomically low. To make it better, increase the number of characters in a code.
But long random character strings are difficult to remember. If you think that might be a problem for the UI, consider using random words instead - for example, have a dictionary of a large number of English words, and then to generate a code, put two or three of them together.

Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found

If you really expect there to be less than 100 codes in use at a given time, then the chances of a collision are extremely low, so simply re-picking a random number in such rare cases sounds perfectly fine to me. If the app became more popular and collisions started happening on a regular basis, then it might be time to consider a different approach (such as hashing incremental numbers, or increasing the number of characters, or using a different algorithm entirely).

Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)

When turning a number into a string, I'd prefer to use toString if possible. For example, if you're able to use numbers 0-9 in addition to letters, you could make encodeAlphabet much simpler and use:
  encodeAlphabet(num) {
    return num.toString(36);
  }

(though, for such an approach to be user-friendly, you might also want to remove all characters that might get confused with each other, like O and 0)
Another approach to consider - rather than generating a number and then turning it into a string, how about generating random characters and putting those into a string instead? No need to work with modulo and radix:
generateCode() {
  let code;
  do {
    code = this.getRandomCode();
  } while (this.usedCodes.has(code));
  this.usedCodes.add(code);
  return code;
}
getRandomCode() {
  return Array.from(
    { length: this.codeLength },
    () => String.fromCharCode(Math.floor(Math.random() * 26) + 65)
  ).join('');
}

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

class RoomCodeManager {
  // Generate 4-letter codes by default
  constructor(codeLength = 4) {
    this.codeLength = codeLength;
    this.usedCodes = new Set();
  }
  generateCode() {
    let code;
    do {
      code = this.getRandomCode();
    } while (this.usedCodes.has(code));
    this.usedCodes.add(code);
    return code;
  }
  getRandomCode() {
    return Array.from(
      { length: this.codeLength },
      () => String.fromCharCode(Math.floor(Math.random() * 26) + 65)
    ).join('');
  }
  releaseCode(code) {
    this.usedCodes.delete(code);
  }
}

const roomCodeManager = new RoomCodeManager();
console.log(roomCodeManager.generateCode());

Regarding
// If every code is already in use, just return a random code
if (this.usedCodes.size >= max) {
  return this.encodeAlphabet(code);
}

Maybe, in such a case, increment this.codeLength instead of returning a duplicate? (Though, this'll probably never happen)


Adding time offsets to create future dates

You can add seconds directly to a Time object, so you could do:

now = Time.now.utc
starts = now + 3600 # Add 1 hour's worth of seconds (60 * 60)
ends   = now + 7200 # Add 2 hours

and then do the strftime-formatting.

Of course, since you need to do this twice, I'd suggest adding a method to avoid the repetition, i.e.:

def offset_utc_timestamp(offset, format = "%Y-%m-%dT%H:%M:%S.%3NZ")
  time = Time.now.utc + offset
  time.strftime(format)
end

You may want to split it up differently (i.e. have the method just return a Time object, which you make into a string elsewhere; or have the method also do the URL escaping).

I'd also recommend using the URI.escape method instead, if this is intended for URLs

With all that your code becomes:

starts = URI.escape(offset_utc_timestamp(3600))
ends   = URI.escape(offset_utc_timestamp(7200))

Alternatively, the ActiveSupport gem has a ton of helpful time stuff, letting you do things like 2.hours.from_now.utc


Hints to make Sudoku solver more Pythonic

I noticed a few suspicious problems with your coding style.  There's plenty to talk about even without analyzing the sudoku solver portion of your program.

Your functions are actually more like procedures that act on global variables.  For example, your read() doesn't return anything, and your write() doesn't take a parameter for the matrix to be written.  Although set() takes several parameters, the object it mutates is not one of the parameters — it operates on the global pos instead.  Similarly, check(), only_pos_left(), and only_pos_for_it() take no parameters at all, which is a bad sign.

Even when read() and write() take a parameter called name (you probably meant "filename"), they ignore the parameter altogether!  The filenames 'in' and 'out' are hard-coded.

Your read() and write() each has a file descriptor leak.  fid.closed does not close the file handle.  You probably meant fid.close().  But really, you should almost always prefer to open files using a with block instead, so you would never need to worry about having to close them again.

Your read() and write() counterintuitively transpose rows ↔ columns.  I suppose those transpositions cancel each other out, and therefore have no effect.  However, it makes it hard for others to think about or discuss your code.

read() tries to do more than just reading the file.  The function should do one thing only: return a 2-dimensional matrix.  Converting characters to numbers could also be acceptable.  However, constructing the data structure you want to use to represent the sudoku puzzle should be a separate function.  The fact that read() also subtracts one from each value makes it more disconcerting.  Perhaps you do want to have constraints in the 0 to 8 range, but such a transformation definitely doesn't fall under "reading".

To summarize some of the suggestions above…

def read(filename):
    """ Return the contents of the file as a 2-D array. """
    with open(filename) as f:
        return [map(int, row.rstrip()) for row in f.readlines()]


Export class instances to a string (for sharing, backup) and importing them

I don't see a question here, but I think I understand your concerns...

Regarding performance - I don't think you need to worry. Note that JSON and XML exist, in part, as formats for transmitting objects between apps in a platform independent way and there isn't a whole lot of worries about performance with either of them.

That said, I suggest you use one of these standard data interchange formats rather than trying to invent your own. Both JSON and XML already have very efficient and OS provided functions for doing the conversion...

extension Patient {
    init(dictionary dict: [String: AnyObject]) {
        id = dict["id"] as! String
        name = dict["name"] as! String
        age = dict["age"] as! Int
        // etc...
    }

    var dictionary: [String: AnyObject] {
        var dict: [String: AnyObject] = [:]
        dict["id"] = id
        dict["name"] = name
        dict["age"] = age
        // etc...
        return dict
    }
}

Once you have the above, you can easily convert a Patient to and from a Dictionary object and once you have that, you can use Apple's methods to convert the dictionary to/from either JSON or XML depending on what you like best.

You might also want to consider using SwiftyJSON instead of [String: AnyObject] dictionaries.


From the end of the chapter 1.8:

  "When the name of an array is used as an argument, the value passed to
  the function is the location or address of the beginning of the array
  - there is no copying of array elements. By subscripting this value, the function can access and alter any element of the array".

So, when you pass array as an argument to a function, you don't create a local copy of array. Instead, you create a pointer (Chapter 5) and work with it as with an array.


Raspberry PI switching from Soft Access Point to WIFI client

There are a few compiler errors that may not have show up for you, the first major compiler problem is that read is a basic function in C input and output so the variable declaration ssize_t read; should be changed to something like size_t readsize. It might be good if you compiled with the -w flags to add warnings to the compiler error messages.

The second problem I see is that you might have compiled this with a C++ compiler rather than a C compiler, a strict C compiler will not recognize the function readline() in a strict C compiler fgets() should be used instead. You will have to make the variable line an array of characters.

char line[BUFSIZ];

The symbolic constant BUFSIZ is defined in the include file stdio.h.

    fgets(line, BUFSIZ, fp);

Overall it would be better if main() was a short function that called other functions, it is currently too complex (does too much).


In your code you're calling GetImageData for each pixel adding a lot of call that are not necessary, you can do this by calling it once for the entire canvas and getting the data from the array.

GetImageData returns a 1 dim array with RGBA for each pixel like :

[R(pixel1),G(Pixel1),B(Pixel1),A(Pixel1),R(pixel2),G(Pixel2),...etc]

this means that you can get the pixel value by using (y * canvasWidth+ x)*4+RGBA
(RBGA is a 0-3 value representing the 4 values)

Another thing you can improve on is the order of your for loops. The way you're looping now you need to loop through the whole image before you can know the edge, however if you turn the loops around you can lessen the amount of pixels you need to check.

For example when going for the left edge you can start the double loop with x then y. This means that whenever the condition first becomes true you can be sure that it is the outer most left edge.

If you implement these relative easy changes the code would look more like this:

function getEdges(tempcanv, colour, which, condition) {
    let ledge = -1, redge = -1, tedge = -1, bedge = -1;
    const canvwidth = tempcanv.width, canvheight = tempcanv.height;
    const imageData = tempcanv.getContext('2d').getImageData(0, 0, canvwidth, canvheight).data; //gets all image data
    for (let x = 0; x < canvwidth; x++) {//left edge
        if (ledge >= 0) {
            break;
        }
        for (let y = 0; y < canvheight; y++) {
            //(y * canvwidth + x) * 4 is for getting the current location
            if (condition(imageData[(y * canvwidth + x) * 4 + which], colour)) {
                ledge = x;
                break;
            }
        }
    }
    for (let x = canvwidth - 1; x >= ledge; x--) {//right edge
        if (redge >= 0) {
            break;
        }
        for (let y = 0; y < canvheight; y++) {
            //(y * canvwidth + x) * 4 is for getting the current location
            if (condition(imageData[(y * canvwidth + x) * 4 + which], colour)) {
                redge = x;
                break;
            }
        }
    }
    for (let y = 0; y < canvheight; y++) {//top edge
        if (tedge >= 0) {
            break;
        }
        for (let x = ledge; x <= redge; x++) {
            //(y * canvwidth + x) * 4 is for getting the current location
            if (condition(imageData[(y * canvwidth + x) * 4 + which], colour)) {
                tedge = y;
                break;
            }
        }
    }
    for (let y = canvheight-1; y >= tedge; y--) {//bottom edge
        if (bedge >= 0) {
            break;
        }
        for (let x = ledge; x <= redge; x++) {
            //(y * canvwidth + x) * 4 is for getting the current location
            if (condition(imageData[(y * canvwidth + x) * 4 + which], colour)) {
                bedge = y;
                break;
            }
        }
    }
    console.log('edges', [ledge, tedge, redge + 1, bedge + 1]);
    return [ledge, tedge, redge + 1, bedge + 1]
}


#3 Normalization

What will you do if a place belongs to more than one category?  For example, I might categorize Boston as New England as well as The Northeast.  But you only have one place category ID per place.

If the category is always a region, you might call the table Regions instead.  That's more specific than category or even place category.

I would expect something called place categories to know to what place it belonged.  But in this case, one place category has many places.  This is part of why I don't like the name.  It feels wrong to me.

#2 Object vs. ID

Hibernate is an Object-relational Mapping tool (ORM).  It always includes related tables as objects, but it doesn't necessarily bother loading them unless needed.  I.e. it has a lazy loading option.  It's application specific which way you do it.  If you normally need it, perhaps load it aggressively.  If you normally don't need it, perhaps you only load it lazily.

Note that place categories are rather light weight.  It would be easy enough to load all of them and assign them as you load places.  That's a good pattern if you have to load all the categories in order to make your drop down.


Marking projects as done when all tasks' progress are 100%

16 and 15 are pretty artificial values, you should aim for a better code quality rather than a higher/smaller metric in particular.

Let's see what can be improved...

Your boolean comparison if all_done == True: could (and should) be written in a more concise way: if all_done:.
Python has an optional else on for loops which can be understood as "this loop exited the usual way, not via a break". This removes the need for the all_done variable altogether:

if len(record.task_line_ids) != 0 and record.state in ('open', 'done'):
    for line in record.task_line_ids or record.task_line_rider_ids:
        if line.progress != 100:
            record.state = 'open'
            break
    else:
        record.state = 'done'

You could use the all or any builtin to rewrite this without the for... else logic:

if len(record.task_line_ids) != 0 and record.state in ('open', 'done'):
    if all(line.progress == 100 for line in record.task_line_ids or record.task_line_rider_ids):
        record.state = 'done'
    else:
        record.state = 'open'

You could re-introduce the temporary variable and use ternary operator:

if len(record.task_line_ids) != 0 and record.state in ('open', 'done'):
    all_done =  all(line.progress == 100 for line in record.task_line_ids or record.task_line_rider_ids)
    record.state = 'done' if all_done else 'open'


Optimize program to test for divisibility of numbers 3.0

Table generator

Your table generator has a bug, which caused it to crash on my machine.  This line:

  if(*len > buflen) {

should be:

  if(*len >= buflen) {

Second, your table generator is outputting entries for permutations that aren't required.  For example, since 12 and 21 are permutations of each other, you only need to output "-12 21", and later on, there shouldn't be a "-21" entry because you've already checked for 21.  But currently, your table includes both, so your program will check entries that it doesn't need to check.

Incorrect table searching

There are a couple of things wrong with your program.  The biggest problem is that you are starting over at index 1 every time through the loop.  You really don't have to do that because to get to the next number, you just need to skip all the negative numbers.  In other words:

   for(x=1;x<MAX;x++) {
     j=x-1;
     i=-x;

should be:

    j = 0;
    for(x=1;x<MAX;x++) {
      i=-x;

Just making that change with your current table reduces the program time back down to "normal" levels, although it still isn't correct.

A second problem is that you are skipping lookup[j] when doing the dividing loop.  This is because your loop uses a preincrement, most likely because you are trying to avoid the first number of the sequence, which is negative.

  m = j;
  while((k = lookup[++m]) > 0) {

What you can do is change the table's negative entry to positive.  Then you can use a postincrement:

lookup[j] = -lookup[j];
for(l=0;l<N;l++) {
  m = j;
  while((k = lookup[m++]) > 0) {
    if(k%n[l]==0)break;
  }
  if(k<0) goto outer;
}

Searching the optimized table

Once you start using a table that doesn't include redundant entries, your search will need to change.  Your current search looks for the next number.  But since not every number will exist, all you need to do is search for a non-negative number.  Also, I appended a -1000000 entry at the end of my table to make sure I didn't run past the end of the table.

Your current search:

 while((unsigned int)(j) < LENGTH(lookup) && lookup[j] != i) ++j;

would turn into:

while (lookup[j] >= 0)
    ++j;

Putting it all together

This is what your code would look like with all the changes.  This code assumes that the table you generate has a -1000000 entry at the end and contains no redundant entries:

#include <stdio.h>

int lookup[] = {
#include "table.h"
};

#define MAX 1000000

int main(void) {
  int n[100];
  int i, j, k, m, N;

  scanf("%d", &N);
  for(i=0;i<N;i++) scanf("%d", &n[i]);
  for(i=0;i<MAX;i++) {
    while(lookup[i] >= 0)
        ++i;
    lookup[i] = -lookup[i];
    for(j=0;j<N;j++) {
      m = i;
      while((k = lookup[m++]) > 0) {
        if(k%n[j]==0)break;
      }
      if(k<0) goto outer;
    }
    break;
    outer:
    continue;
  }
  fprintf(stdout, "%d\n", lookup[i]);
}

You can find my own version of the table generator and solver program here on Github.


"MathChallenge" game for sums with 4 operators

Some notes:

You took a OOP approach. I won't say that's wrong (maybe it was even encouraged by that guide), but when learning a language like Python, where OOP is not compulsory, I'd say it preferable to take a non-OOP approach first.
return ('addition', '+', a+b). Those 4 operations are pretty uniform, why don't you use a data structure instead? (a list, a dictionary). Use module operator.
You code is for version 2.x. Unless you have some good reason, it's better to use Python 3.x, you won't lose a second re-learning things later on.
op[0], op[1], op[2]. If I had to highlight one single aspect of good programming practices, this would be: be declarative! If your code does not look as if you are writing pseudocode (specially if you are using a high-level language), then you're doing something wrong. What's op[1]? No idea, we'd have to look at the function. So destructure the result giving meaningful names to the variables: op_name, op_symbol, op_function = choice(self.operator)(a, b).
I'd take a more functional approach, try to organize code so there are as few in-place updates of variables as possible (not always feasible or idiomatic in an imperative language like Python).

I'd write:

import operator
import random

operations = {
    "addition": ("+", operator.add),
    "substraction": ("-", operator.sub),
    "multiplication": ("*", operator.mul),
    "division": ("/", operator.floordiv),
}

def ask_operation(difficulty, maxtries=3):
    maxvalue = 5 * difficulty
    x = random.randint(1, maxvalue)
    y = random.randint(1, maxvalue)
    op_name, (op_symbol, op_fun) = random.choice(list(operations.items()))
    result = op_fun(x, y)

    print("Difficulty level %d" % difficulty)
    print("Now lets do a %s calculation and see how clever you are." % op_name)
    print("So what is %d %s %d?" % (x, op_symbol, y))

    for ntry in range(1, 1+maxtries):
        answer = int(input(">"))
        if answer == result:
            print("Correct!")
            return True
        elif ntry == maxtries:
            print("That's %s incorrect answers.  The end." % maxtries)
        else:
            print("That's not right.  Try again.")
    return False

def play(difficulty):
    while ask_operation(difficulty):
        difficulty += 1
    print("Difficulty level achieved: %d" % difficulty)

play(1)


I would not implement method UnmarshalJSON as it is not really necessary. Instead, I would create Audio and Photo types and put them as fields into Attachment type. It would be easier to reference data as field than get it as a value from map.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

type Response struct {
    Id          int `json:"id"`
    FromId      int `json:"from_id"`
    Attachments []Attachment
}

type Audio struct {
    Artist string `json:"artist"`
    Title  string `json:"title"`
}

type Photo struct {
    Id  int    `json:"id"`
    Url string `json:"url"`
}

type Attachment struct {
    Type  string
    Audio `json:"audio"`
    Photo `json:"photo"`
}

func main() {
    encoded := `
    {
        "id": 123,
        "from_id": 234,
        "attachments": [
            {
                "type": "audio",
                "audio": {
                    "artist": "Van Halen",
                    "title": "Eruption"
                }
            },
            {
                "type": "photo",
                "photo": {
                    "id": 123,
                    "url": "http://someurl.com"
                }
            }
        ]
    }
    `

    response := &Response{}
    reader := strings.NewReader(encoded)
    err := json.NewDecoder(reader).Decode(&response)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(response)
}


Your concepts look completely misguided.

A ring is a mathematical concept, an algebraic structure. It does have a size, but it doesn't have a value.

The value would be part of a ring element. Such a ring element is a tuple (ring, value).

The pitch of a note is indeed a ring element. A ring element can only be used to store the pitch of a note, but not its octave. If it did, it would not match the mathematical concept of a ring anymore.

To represent a musical note in Western notation, my first idea is:

data class Note(
    val octave: Int,
    val name: NoteName,
    val mod: NoteModifier,
    val duration: NoteDuration
)

enum class NoteName {
    C, D, E, F, G, A, B
}

enum class NoteModifier {
    Natural, Sharp, Flat, TwoSharp, TwoFlat
}

enum class NoteDuration {
    Full, Half, Quarter, Eighth, Sixteenth
}

The above definitions are very rough and limited. To get a grasp of the actual complexity of typesetting music, have a look at LilyPond, it should have a definition of a note somewhere in the code.

If you just want to replay the music, there's no need to distinguish between c# and d\$\flat\$, which would make the above definitions much simpler.

In Kotlin you don't need setters since the copy function is more powerful than in Java. You can just say:

val note = other.copy(octave = 3, pitch = 5)

This is easier to grasp and less code to write. If you write a setter method in Kotlin, lean back and think twice. Probably you are doing something unusual.

By the way, property names in Kotlin are written in lowercase. Kotlin is based on Java, not C#.


RungeKutta method in C, pointers and arrays

Generally, it is preferrable to put the \ns at the end of the corresponding printf instead of relying on them being present on the next one.

printf("\n"); // <-- you don't need to complicate your whole logic just because of this guy!
              //     put him on a line of his own.
printf("\y'(t) - y(t) = e^(t/2) * (sin(5t) - 10cos(5t))\n");
printf("\y(0) = 0\n");
printf("0 <= t <= 10\n");

for(i=0; i<1001; i+=100){
    printf("i = %lf => y = %lf\n", 0.01*i, res[i]);
}

Also, as a general principle I don't like returning malloc-ed values from functions since doing so

forces you to remember to free the data even though the corresponding malloc is hidden away inside the other function and
couples your algorithm (the numeric calculations) with the memory management. It would be preferable if you were free to use any sort of memory instead of being forced into using malloc-free (as you currently are)

One possibility is passing the result array as an argument to your function:

//so you can malloc...
double *result = malloc(/**/);
runge_kutta( /*...*/, result);
free(result);

//...or not
double results[MAX_SIZE];
runge_kutta( /*...*/, result);

Do note that in the previous example you now need to be able to know the length of the result array beforehand. Most of the times this is trivial but in some cases you might need to package this in a subroutine.

Finally, since this is a numerically intensive problem and the list of results is not really needed (since I guess you only need to look at them one at a time and in sequential order) you might want to consider reorganizing things so that you can get away without any allocation for the results array.

For, example, we could have the Runge Kutta function call a callback on each result it gets instead of storing it to an array.

void runge_kutta_2nd_order(
   /*the original arguments and...*/,
   void (*onPoint)(int index, double x_i) /*the callback*/
)
{
   //...
       onPoint(index, ystar2);
   //...
}


This is actually a stab in the dark but could you use the .NET 4 System.Threading.Task object for this.  Something like:

var task = Task.Factory.StartNew(() => _wrapped.Run(code) });

// Wait returns true if the task finished within the allocated timeframe
// http://msdn.microsoft.com/en-us/library/dd270644.aspx
if(task.Wait(_timeoutInSeconds * 1000))
{
   return executionResult;
}
else
{
   throw new ApplicationException(string.Format("Code took longer than {0} seconds to run, so it was aborted.", _timeoutInSeconds));
}


Here's my starting point for computing the performance improvement due to the various revisions below: how long does it take to sieve for the prime numbers below \$ 10^8 \$?

>>> from timeit import timeit
>>> test = lambda f: timeit(lambda:f(10**8), number=1)
>>> t1 = test(sieve)

The exact number is going to depend on how fast your computer is, so I'm going to compute performance ratios, but for the record, here it is:

>>> t1
78.9875438772142

Your initialization of the list l takes more than half the time, so let's try a cheaper approach. Let's also give this array a better name, and make it a Boolean array while we're about it.

def sieve2(n):
    """Return a list of the primes below n."""
    prime = [True] * n
    for p in range(3, n, 2):
        if p ** 2 > n:
            break
        if prime[p]:
            for i in range(p * p, n, 2 * p):
                prime[i] = False
    return [2] + [p for p in range(3, n, 2) if prime[p]]

When optimizing a function like this, it's always worth keeping the un-optimized version around to check the correctness of the optimized version:

>>> sieve(10**6) == sieve2(10**6)
True

This already runs in less than a third of the time:

>>> test(sieve2) / t1
0.30390444573149544

We could avoid the test for p ** 2 > n by computing a tighter limit for the loop. Note that I've used n ** .5 here as this is slightly faster than math.sqrt(n).

def sieve3(n):
    """Return a list of the primes below n."""
    prime = [False, False, True] + [True, False] * (n // 2)
    for p in range(3, int(n ** .5) + 1, 2):
        if prime[p]:
            for i in range(p * p, n, 2 * p):
                prime[i] = False
    return [p for p in range(2, n) if prime[p]]

This makes little difference to the overall runtime:

>>> test(sieve3) / t1
0.2971086436068156

We can accumulate the result as we go, instead of in a separate iteration at the end. Note that I've cached result.append in a local variable to avoid looking it up each time round the loop.

def sieve4(n):
    """Return a list of the primes below n."""
    prime = [False, False, True] + [True, False] * (n // 2)
    result = [2]
    append = result.append
    sqrt_n = (int(n ** .5) + 1) | 1    # ensure it's odd
    for p in range(3, sqrt_n, 2):
        if prime[p]:
            append(p)
            for i in range(p * p, n, 2 * p):
                prime[i] = False
    for p in range(sqrt_n, n, 2):
        if prime[p]:
            append(p)
    return result

Again, this makes very little difference:

>>> test(sieve4) / t1
0.286016401170129

We can use Python's slice assignment instead of a loop when setting the sieve entries to False. This looks wasteful since we create a large list and then throw it away, but this avoids an expensive for loop and the associated Python interpreter overhead.

def sieve5(n):
    """Return a list of the primes below n."""
    prime = [True] * n
    result = [2]
    append = result.append
    sqrt_n = (int(n ** .5) + 1) | 1    # ensure it's odd
    for p in range(3, sqrt_n, 2):
        if prime[p]:
            append(p)
            prime[p*p::2*p] = [False] * ((n - p*p - 1) // (2*p) + 1)
    for p in range(sqrt_n, n, 2):
        if prime[p]:
            append(p)
    return result

This gives a small but noticeable improvement:

>>> test(sieve5) / t1
0.2617646381557855

For big improvements to the performance of numerical code, we can use NumPy.

import numpy

def sieve6(n):
    """Return an array of the primes below n."""
    prime = numpy.ones(n, dtype=numpy.bool)
    prime[:2] = False
    prime[4::2] = False
    sqrt_n = int(n ** .5) + 1
    for p in range(3, sqrt_n, 2):
        if prime[p]:
            prime[p*p::2*p] = False
    return prime.nonzero()[0]

This is more than 6 times as fast as sieve5, and more than 25 times as fast as your original code:

>>> test(sieve6) / t1
0.03726392181902129

We could avoid allocating space for the even numbers, improving memory locality:

def sieve7(n):
    """Return an array of the primes below n."""
    prime = numpy.ones(n // 2, dtype=numpy.bool)
    sqrt_n = int(n ** .5) + 1
    for p in range(3, sqrt_n, 2):
        if prime[p // 2]:
            prime[p*p // 2::p] = False
    result = 2 * prime.nonzero()[0] + 1
    result[0] = 2
    return result

>>> test(sieve7) / t1
0.029220096670965198

And finally, an implementation that sieves separately for primes of the form \$ 6i − 1 \$ and \$ 6i + 1 \$, due to Robert William Hanks:

def sieve8(n):
    """Return an array of the primes below n."""
    prime = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
    for i in range(3, int(n**.5) + 1, 3):
        if prime[i // 3]:
            p = (i + 1) | 1
            prime[       p*p//3     ::2*p] = False
            prime[p*(p-2*(i&1)+4)//3::2*p] = False
    result = (3 * prime.nonzero()[0] + 1) | 1
    result[0] = 3
    return numpy.r_[2,result]

This is about 40 times as fast as the original sieve:

>>> test(sieve8) / t1
0.023447068662434022


Calculate work progress in percentage of batches that contain tasks and task contain sub tasks

System.out.println("\t\tSub Task " + k + " from " + Math.floor(fromSubTaskWeight) + "% to "
    + Math.floor(toSubTaskWeight) + "%");

I'd use System.out.format here, it's easier to read than string concatenation:

System.out.format("\t\tSub Task %d from %f%% to %f%%%n",
    k, Math.floor(fromSubTaskWeight), Math.floor(toSubTaskWeight));

With that you can easily format floating numbers.

Weight of each task: 33,333333%
Weight of each sub task: 16,666667%

Could be a readable

Weight of each task: 33,33%
Weight of each sub task: 16,67%

With

System.out.format("Weight of each task: %.2f%%%n", weightOfEachTask);
System.out.format("Weight of each sub task: %.2f%%%n", weightOfEachSubTask);

Having three nested for loops is hard to read. I'd try to extract out a printSubtaskWeights and a printTaskWeights method.
I've seen earlier the numOfSubTasksInEachTask style variables but I've found subTasksInEachTaskNumber more easier to work with. Maybe because if more than one variable starts with numOf it's hard to differentiate them.
i, j, k variables could be more descriptive and could express their purpose. For example,
batchNumber, taskNumber and subtaskNumber.
Batches, tasks and subtasks looks very similar. I'd try to create a common abstraction for them and use that three times instead of duplication.

public class Item {

    private int subItemCount;
    private double weight;

    public Item(final int subItemCount, double weight) {
        super();
        this.subItemCount = subItemCount;
        this.weight = weight;
    }

    public int getSubItemCount() {
        return subItemCount;
    }

    public double getOneSubItemWeight() {
        final double subItemWeight = (1 * weight) / subItemCount;
        return subItemWeight;
    }

    public String getWeightInfo() {
        return String.format("Weight of each %s: %.2f%%",
            name, getOneSubItemWeight());
    }
}

(I'd call it Task but it hasn't already been used.)

I started refactoring the code but I guess I won't finish it. The beginning of the code looked like this:

final Item batches = new Item(3, 100);
final Item tasks = new Item(1, batches.getOneSubItemWeight());
final Item subtasks = new Item(2, tasks.getOneSubItemWeight());

100 is the batches' weight, tasks and subtasks inherit the weight of their parents.

Note that the duplicated Weight of each print statement was also moved to the Item class.

I'd also try to move a loop into the Item class and call subitem printing from that method. I'd reduce the number of loops to one. Something like this:

public class Item {

    private final Item subitems;
    ...

    public void print(double fromWeight) {
        for (int item = 1; item <= itemCount; item++) {

            double toWeight = getItemWeight() * item;
            System.out.format("%s %d from %f%% to %f%%%n",
                name, item, Math.floor(fromBatchWeight),
                Math.floor(toBatchWeight));

            if (subitems != null) {
                subitems.print(fromWeight);
            }
            fromWeight = Math.nextUp(toWeight);
    }
}


Writing a generic performance efficient isEmpty method which can check for null or emptiness

Method overloading can make your implementations more efficient and cleaner:

public static boolean isEmpty(Collection obj) {
    return obj == null || obj.isEmpty();
}

public static boolean isEmpty(String string) {
    return string == null || string.trim().isEmpty();
}

public static boolean isEmpty(Object obj) {
    return obj == null || obj.toString().trim().isEmpty();
}

The Collection version is as efficient as possible.

The String version would be more efficient without the trimming. It would be best to trim your strings as soon you see them, long before they reach this call. If you can review the callers and make sure that the strings are always trimmed at their origins, then you can remove .trim() for best performance.

The Object version can be inefficient, depending on the toString implementation of the objects that will be passed to it, and because of the trimming.

I removed the comparison with null from there, because it seems pointless to me. I mean, a class whose toString method says "null" would seem very very odd.

In any case, you don't really want the Object version to be called, at all. Most importantly because it probably won't even work. Take for example an empty Map. Its toString method returns the string {}, which won't match your conditions of emptiness. (For this type you should definitely add isEmpty(Map<?, ?> map) to benefit from its isEmpty method.)

If performance is so critical, then add more overloaded implementations for all other types that you care about, for example:

public static boolean isEmpty(Something obj) {
    return obj == null || obj.isEmpty();
}

Finally, especially when something is so important, you definitely want to unit test it, for example:

@Test
public void testEmptyObject() {
    assertTrue(isEmpty((Object) null));
    assertFalse(isEmpty(new Object()));
}

@Test
public void testEmptyString() {
    assertFalse(isEmpty("hello"));
    assertTrue(isEmpty(""));
    assertTrue(isEmpty(" "));
    assertTrue(isEmpty((Object) null));
}

@Test
public void testEmptySet() {
    assertFalse(isEmpty(new HashSet<String>(Arrays.asList("hello"))));
    assertTrue(isEmpty(new HashSet<String>()));
}

@Test
public void testEmptyMap() {
    Map<String, String> map = new HashMap<String, String>();
    assertTrue(isEmpty(map));
    map.put("hello", "hi");
    assertFalse(isEmpty(map));
}


Return a minimum number of ranges from a collection of ranges

I’ll try to go over your five points. Keep in mind that I’m not your interviewer and my interpretation might not be what they really meant.

While loops are not bad per se, but they are not the preferred way to iterate over a datastructure. I started solving the exercise also using a while loop to reduce a partially reduced list until reaching a fixed point. But I realized that, once the original list is sorted, you only need a single pass (more on that later). This is why solving this problem with a while loop is a weird thing to do.
Compare these toy examples:

counts = []
running_total = 0
for amount, should_separate in some_input:
    running_total += amount
    if should_separate:
        counts.append(running_total)
        count = 0

and

counts = [0]
for amount, should_separate in some_input:
    counts[-1] = counts[-1] + amount
    if should_separate:
        counts.append(0)

even though the second one is shorter, the core of the computation (counts[-1] = counts[-1] + amount) loose its readability due to the indexing. Plus, using one less variable, you lose the opportunity to document the code using an expressive name.
I’m assuming Python 2 here, as in Python 3 range produces a range object, pretty much the same as xrange in Python 2. So yes, use xrange instead, you’ll save both on memory and time as checking if an element is in a list is \$\mathcal{O}(n)\$. But for such simple checks where you already have the bounds up-front, you can use the shorthand comparisons: if low - 1 <= value <= high + 1:. Especially given the fact that:
Once the list is sorted, only two consecutive ranges can be part of the same "mega"range. If they are not, then you know your output contains another "mega"range that starts at this moment because no other element will start before this new range. This also simplifies the check for range inclusion as you only need to check for the lower bound of the current element to be in the current range; and since items are sorted, you know that that lower bound won't be lower than the lower bound of the current range either.
The ….pop(0) will make the for loop a no-op when initial length is 1, so the loop will stop itself on the next iteration, so the len(…) == 1 check is really redundant with the rest of your code. Drop code that serve no purpose as it is error-prone.

Others remarks I can make:

Why generate an exception on empty input? Simply return an empty list as output: no range in, no range out, I don't see any problem. You won't even enter the while so return an empty list anyway, again, this code is somewhat redundant with the rest.
Why modify the original list by .sort()ing in place? Since you return a different result, you should not modify the input.

Proposed improvements:

def zip_range_reducer(ranges):
    if not ranges:
        return []

    ranges = sorted(ranges)
    reduced = []

    lowest, highest = ranges[0]
    for low, high in ranges:
        # Since we sorted ranges, we know of overlapping
        # ranges by this only check.
        if low <= highest + 1:
            lowest = min(lowest, low)
            highest = max(highest, high)
        else:
            reduced.append([lowest, highest])
            lowest = low
            highest = high
    reduced.append([lowest, highest])

    return reduced

Another interesting way to put this code and remove the boilerplate (empty check, first item extraction) is to use an helper generator function that will trigger interesting behaviours of how iteration works in Python:

def zip_range_reducer(ranges):
    ranges = iter(sorted(ranges))
    return list(_zip_range_helper(ranges))

def _zip_range_helper(sorted_ranges_iterator):
    lowest, highest = next(sorted_ranges_iterator)

    for low, high in sorted_ranges_iterator:
        # Since we have sorted ranges, we know
        # of overlaping ranges by this only check.
        if low <= highest + 1:
            lowest = min(lowest, low)
            highest = max(highest, high)
        else:
            yield [lowest, highest]
            lowest = low
            highest = high

    yield [lowest, highest]

Here the empty check is implicit by the fact that next will raise StopIteration when ranges is empty. But this StopIteration will be interpreted by list() as "there is no more elements to put in here" and an empty list will be returned. Otherwise the first element will be consumed to populate lowest and highest; and each element of the resulting list will be yielded one by one.


Bugs:

Here, instead of promt it should be prompt:

password: str = getpass(promt="Enter password: ")

If PDF file is not in the current folder, this will throw an error:

if decrypt(os.path.join(folder_name, filename), password):
    os.remove(filename)

it should be os.remove(os.path.join(folder_name, filename)) instead.

Docstring:

"""
Decrypts all files in a folder and sub folder with provided password
"""

I think it would be better to specify that only PDF files will be decrypted. Also, it should mention that original copy will be removed. How about:

"""
Decrypts all pdf files in a specified folder
and all its sub-folders with provided password,
saves decrypted copy and removes original encrypted files.
"""

PEP 8:

  Imports should be grouped in the following order:

  Standard library imports.
  Related third party imports.
  Local application/library specific imports.

  You should put a blank line between each group of imports.

Also, it is advised to sort imports alphabetically.

So, instead of:

import os
import argparse
from typing import Tuple
from getpass import getpass
from pathlib import Path
import PyPDF2

You will have:

import argparse
import os
from getpass import getpass
from pathlib import Path
from typing import Tuple

import PyPDF2

Also, before the first function there should be two blank lines. Apart from that, well done! You follow the style guide pretty well!

Click:

Instead of using argparse, I'd suggest to take a look at third-party library Click. Why Click?

Example of usage:
For example, here is how you could wrap main function pdf_decrypter:

import click

...

@click.command()
@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')
@click.password_option(confirmation_prompt=False)
def pdf_decrypter(path: str,
                  password: str):
...

Running python3 pdf_decrypter.py --help from command line will print:

Usage: pdf_decrypter.py [OPTIONS]

  Main routine: Giving a password and path all PDFs which are encrypted get
  decrypted in the supplied path. If the password is wrong a message is
  displayed.

Options:
  -p, --path PATH  Folder path to look for PDFs to decrypt (absolute or
                   relative). [default: .]
  --password TEXT
  --help           Show this message and exit.

Confirmation messages:
Further in the body of the function you can add confirmation message as well, like:

...
if not click.confirm(f'All PDF files will be encrypted in {path}\n'
                     'Do you want to continue?'):
    return
...

This will look like:

python3 pdf_decrypter.py
Password:
All PDF files will be encrypted in /path/to/pdf_files
Do you want to continue? [y/N]:

Putting encryption and decryption together:
And, probably, you would want to put both encryption from your previous post and decryption in the same module later, as they share a lot in common. In this case you would want to use Nesting Commands, for example, like this:

@click.group()
def cli():
    pass

@cli.command()
@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')
@click.password_option(confirmation_prompt=False)
def decrypt(path: str,
            password: str):
...

@cli.command()
@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')
@click.password_option(confirmation_prompt=False)
def encrypt(path: str,
            password: str) -> None:
...

And you would call your functions like python pdf_utils.py encrypt or python pdf_utils.py decrypt, etc.

click.Path:
You can specify additional checks, like checking if path exists, path is not a file, and also make Click to resolve path automatically by setting resolve_path as True. So you wouldn't have to use os.path.join later in the code:

@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(exists=True,
                              file_okay=False,
                              resolve_path=True),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')

Iterating over files:

Right now you have two nested loops and two checks of extension and if file is encrypted:

for folder_name, _, filenames in os.walk(path):
    for filename in filenames:
        if not filename.endswith('.pdf'):
            continue

        if not is_encrypted(os.path.join(folder_name, filename)):
            continue

        # decryption logic

This looks pretty cumbersome. And I personally don't like it when the code is nested on two or more levels. We can use pathlib module to simplify this logic:

pdf_paths = Path(path).rglob('*.pdf')
encrypted_pdfs = filter(is_encrypted, pdf_paths)
for pdf in encrypted_pdfs:
    # decryption logic

Errors catching:

Now you catch PyPDF2.utils.PdfReadError on the deepest level, in decrypt function. I suggest you to take it out to main function, and not return True or False to indicate success/failure. See, for example, When and how should I use exceptions?
So, in the pdf_decrypter, you will have:

for pdf in encrypted_pdfs:
    try:
        decrypt(pdf, password)
        pdf.unlink()
    except PyPDF2.utils.PdfReadError:
        print(f'{pdf} could not be decrypted (wrong password)')

pathlib over os:

You almost don't use advantages of the pathlib. I already included some things in previous code examples. But here I will sum up everything.

Opening file:
This:

with open(filename, 'rb') as pdf_file:

will become:

with filepath.open('rb') as pdf_file:

Note that filepath would be a better name here.

Changing filename:

filename_decrypted = filename.strip('.pdf') + "_decrypted.pdf"

could be rewritten as:

decrypted_filename = f'{filepath.stem}_decrypted{filepath.suffix}'  # new name
decrypted_filepath = filepath.parent / decrypted_filename  # complete path

Removing file:
os.remove(path) can be replaced by path.unlink().
By this moment we removed all os module usages. So, we can remove that import.

Putting it all together:

"""
Decrypts or encrypts all pdf files in a specified folder
and all its sub-folders with provided password,
saves processed copies and removes original files.
"""
from itertools import filterfalse
from pathlib import Path

import click
import PyPDF2

def is_encrypted(filepath: Path) -> bool:
    """Checks if file is encrypted"""
    with filepath.open('rb') as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        return pdf_reader.isEncrypted

def write_copy(filepath: Path,
               password: str,
               *,
               mode: str) -> None:
    """
    Writes encrypted or decrypted copy of the file based on the mode
    :param filepath: path of the PDF file to be processed
    :param password: password to decrypt/encrypt PDF with
    :param mode: one of 'encrypt' or 'decrypt'
    """
    with filepath.open('rb') as pdf_file:
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        pdf_writer = PyPDF2.PdfFileWriter()

        if mode == 'decrypt':
            pdf_reader.decrypt(password)
        for page_number in range(pdf_reader.numPages):
            pdf_writer.addPage(pdf_reader.getPage(page_number))
        if mode == 'encrypt':
            pdf_writer.encrypt(password)

        suffix = {'decrypt': '_decrypted',
                  'encrypt': '_encrypted'}
        processed_filename = f'{filepath.stem}{suffix[mode]}{filepath.suffix}'
        processed_filepath = filepath.parent / processed_filename

        with processed_filepath.open('wb') as pdf_file_processed:
            pdf_writer.write(pdf_file_processed)

@click.group()
def cli():
    pass

@cli.command()
@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(exists=True,
                              file_okay=False,
                              resolve_path=True),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')
@click.password_option(confirmation_prompt=False)
def decrypt(path: str,
            password: str) -> None:
    """
    Decrypts all encrypted PDFs in the supplied path.
    If the password is wrong a message is displayed.
    Saves processed copies and removes original files.
    :param path: folder path to look for PDFs to decrypt
    :param password: password to decrypt PDFs with
    """
    pdf_paths = Path(path).rglob('*.pdf')
    encrypted_pdfs = filter(is_encrypted, pdf_paths)
    for pdf in encrypted_pdfs:
        try:
            write_copy(pdf, password, mode='decrypt')
            pdf.unlink()
            click.echo(f'Decrypted successfully: {pdf}')
        except PyPDF2.utils.PdfReadError:
            click.echo(f'{pdf} could not be decrypted (wrong password)')

@cli.command()
@click.option('--path', '-p',
              default='.',
              show_default=True,
              type=click.Path(exists=True,
                              file_okay=False,
                              resolve_path=True),
              help='Folder path to look for PDFs to decrypt '
                   '(absolute or relative).')
@click.password_option(confirmation_prompt=False)
def encrypt(path: str,
            password: str) -> None:
    """
    Encrypts all non-encrypted PDFs in the supplied path.
    Saves processed copies and removes original files.
    :param path: folder path to look for PDFs to encrypt
    :param password: password to encrypt PDFs with
    """
    if not click.confirm(f'All PDF files will be encrypted in {path}\n'
                         'Do you want to continue?'):
        return

    pdf_paths = Path(path).rglob('*.pdf')
    not_encrypted_pdfs = filterfalse(is_encrypted, pdf_paths)

    for pdf in not_encrypted_pdfs:
        write_copy(pdf, password, mode='encrypt')
        pdf.unlink()
        click.echo(f'Encrypted successfully: {pdf}')

if __name__ == '__main__':
    cli()

Probably, encrypt and decrypt could be put in one function with a mode parameter, like what I did in a write_copy function; but see for yourself if it will make the code more clear.


Prefer returning a result instead of passing it via a reference

The result of your function is a std::ifstream object, so make that explicit:

std::ifstream OpenFile() {
  while(true) {
    // read filename

    std::ifstream file(fileName);

    if (file.is_open())
      return file;
    else
      // handle error
  }
}

The advantage is that instead of having to write:

std::ifstream file;
OpenFile(file);

You can write:

std::ifstream file = OpenFile();

Or even:

auto file = OpenFile();

Avoid using std::stringstream if it's not necessary

It might seem convenient, but it's rather inefficient, and often there are other ways to accomplish what you want. It seems from your code that you want to forbid filenames with whitespace characters in them. Consider using std::find_first_of() to check if there are certain characters in a string.

Apart from that, many filesystems, including those on mainstream operating systems such as Linux, Windows and macOS, allow spaces in their filenames. And surely, when you call open(), the operating system will return an error if you pass it an invalid filename, so you don't have to do this error checking yourself.

Avoid casting std::string to C-strings

Since C++11 you can pass a std::string directly to a std::ifstream's constructor or to its open() function.

Use '\n' instead of std::endl

Avoid using std::endl. It is equivalent to '\n' plus a call to flush(). The flush is usually unnecessary and might hurt performance. So for example, instead of:

std::cout << "File could not be opened. Please try again.";
std::cout << std::endl;

Write:

std::cout << "File could not be opened. Please try again.\n";

Pass along the error message from the operating system

There are many reasons why opening a file might fail. It will benefit the user to learn the exact reason why it failed. For example, it could be that the file doesn't exist, or that it's permissions don't allow it being opened by the user. To do this, call strerror(errno), like so:

std::cout << "File could not be opened: " << strerror(errno) << "\nPlease try again.\n";

Add a way for the user to cancel opening a file

The function loops forever until a file has succesfully been opened. What if the user decides that it doesn't want any file to be opened at this time, but wants the application to cancel this operation but do something else? If you don't allow a way out of this function, the only option available to the user is closing the application and restarting it.

Consider making the function more generic

While you shouldn't add bells and whistles to a function like this if you are not going to use them, you might want to consider whether you want to make this function a bit more widely applicable. For example, you could have it open a file either for reading, writing or both, or have a way to give a custom prompt. For example:

std::fstream OpenFile(ios_base::openmode mode = ios_base::in, const std::string &prompt = "Enter a file name: ") {
  while(true) {
    std::cout << prompt;
    // read filename

    std::fstream file(filename, mode);

    if (file.is_open())
      return file;
    else
      // handle error
  }
}


Awesome code,

Well named variables, commented and easy tor read
JsHint.com has nothing on this code
Use 'use strict'


In general, I think the program is well readable, and demonstrates the idea correctly. I have some suggestions for further improving it.

Constants

Consider the following statement:

drawDigit(hour/10, 20, 100);
drawDigit(hour%10, 110, 100);

Since the values are reused more than once, I would suggest introducing constants for them:

final int HOUR_TO_DIGIT_QUOTIENT = 10;
final int  HOURS_FIRST_X = 20;
final int  HOURS_SECOND_X = 110;
final int  HOURS_Y = 100;

Of course, this holds also for all the other numeric constant, and the strings "AM" and "PM", which are repeated more than once as well.

(Btw., I would suggest introducing these constants even if each value was used only once, because this makes the code easier to understand.)

Organising code

There are some blocks of code, which could be separated into subroutines, in order to make the main code shorter, and thus more readable. E.g.:

fill(75);
rect(40, 230, 10, 10);
text("AM", 55, 240);
fill(255, 0, 0);
rect(40, 245, 10, 10);
text("PM", 55, 255);

This part could be extracted to methods, e.g. like this:

void showAmIndicactor(boolean enabled) {
    if (enabled) {
        fill(255, 0, 0);
    }
    else {
        fill(75);
    }
    rect(40, 230, 10, 10);
    text("AM", 55, 240);
}

void showPmIndicactor(boolean enabled) {
    if (enabled) {
        fill(255, 0, 0);
    }
    else {
        fill(75);
    }
    rect(40, 245, 10, 10);
    text("PM", 55, 255);
}

// in the main block:
if (hour >= 12) {
   showAmIndicactor(false);
   showPmIndicactor(true);
 } else {
   showAmIndicactor(true);
   showPmIndicactor(false);
 }

N.B.: I am not familiar with Processing in detail, but since from the question I understand that 'drawDigit' is an own method (i.e. not built in to Processing), I assume, that it is possible to introduce other own methods in a similar way as in Java.

Functionality

I do not understand, how the seconds will be rendered correctly. As far as I see, this is the only part that depends on the seconds:

if (second % 2 == 0) fill(240, 0, 0);
else fill(75);

But as I understand, this code does not show any digits, just fills a space with a colour. Is this the intended behaviour? If so, then I suggest documenting why is it like that (in a comment), otherwise, I propose to extend the functionality so that seconds are rendered as well.

On a side note, I recommend to use always the block-form of if-else statement (and any other statements), even if it has just one instruction per branch. In other words, I suggest rewriting it as follows:

if (second % 2 == 0) {
     fill(240, 0, 0);
}
else {
     fill(75);
}

This prevents that you add more statements (accidentally indented at the level of if-else block), and think they will be executed within if-else.

Validation

Although not part of the original problem statement, I would recommend to extend your code with validation. I.e., make sure that hours are between 0-23 (or 1-12 in case of 12-hour format), minutes and seconds are between 0-59, and throw an exception otherwise (or print an error and exit, whichever is available in Processing).

Before adding validation, it would be also interesting to experiment how your program behaves with invalid input (e.g. negative numbers, hours consisting of three digits or four, etc.)


It's probably best to use a function that uses SI units - you can then convert lbs to kgs and in to cm. Additionally, since the majority of the world either uses Imperial or metric, we can use a Boolean to indicate which one to use:

def BMI(height,weight,is_metric):
    if (is_metric):
        # Height in meters, weight in kg
        return weight / height**2
    else:
        # Height in inches, weight in lbs
        height = height * 0.0254
        weight = weight * 0.453
        return BMI(height,weight,True)


Am I writing good Go here? Python functions converted to Go

Early return is better than nesting. For example:

var adsPat1 = regexp.MustCompile(`\.txt$`)
var adsPat2 = regexp.MustCompile(`_[0-9]{8}\.txt$`)
func addDateSuffix(target string, suffix string) error {
    fis, e := ioutil.ReadDir(target)
    if e != nil {
        return e
    }
    for _, fi := range fis {
        if m1 := adsPat1.FindStringSubmatch(fi.Name()); m1 == nil {
            continue
        }
        if m2 := adsPat2.FindStringSubmatch(fi.Name()); m2 != nil {
            continue
        }
        ext := filepath.Ext(fi.Name())
        gn := fmt.Sprintf("%s_%s%s", strings.TrimSuffix(fi.Name(), ext), suffix, ext)
        fmt.Println(fi.Name(), "->", gn)
    }
    return nil
}

Also see this post for more idiomatic go discussion: https://stackoverflow.com/questions/20028579/what-is-the-idiomatic-version-of-this-function


Java Slick 2D Collision Detection Methodology

That really looks quite slow.

First of, don't use HashSet in these situations. A HashSet is a HashMap with "blind" values - like using the key as a value, too. They guarantee uniqueness and fast access (as everyone knows!), but for a set of four objects in a tight and often called loop, you are really hurting performance - the creation overhead is far too high and lookup speed isn't that great.

Next, you should probably change your usage pattern. Don't store distances in int if everything else is float. Same goes the other way around - the conversion between int and float is not free and you should avoid it in code that has to be really fast.

It looks like you never use fractional values and always integers - even in your floats - so you probaly think you can get away with them. They are used as painting positions for the tiles anyway.

Still, even for pixel-precise games, as soon as you change to float, everything starts to get smoother. Because you get sub-pixel movements, which wouldn't be possible for int. You can't display them, but they still affect percieved smoothness. I'd go for float, always keep positional data as floats and only convert to int when I need it to draw stuff.

Next, you can use a vastly better collision check method.

Vastly better in most cases as least. If every object is rectangular, you'd be ok with your way - but there's a lot of conditionals involved and you end up with code like this:

if (!(a.maxY < b.minY || a.minY > b.maxY)) blocked = true; ....

The other (better) way:

Use bounding circles. For each object, you store float x, y, boundsRadius; - the center and the distance to the entities point with the largest distance from the center.

Then... pythagoras (a*a + b*b = c*c)! For entities e1 and e2:

public static boolean maybeCollision(Entity e1, Entity e2) {
    float xDistance = e1.x - e2.x,
          yDistance = e1.y - e2.y,
          rSum      = e1.boundsRadius + e2.boundsRadius
    ;
    return xDistance * xDistance + yDistance * yDistance < rSum * rSum;
}

It's like calculating the distance - Math.sqrt(dx * dx + dy * dy) - but we don't use square root (which is on the slow side) and square the sum of the radius instead. You can use float or int - it doesn't matter as long as there is no overflow. Just change the local variables.

I really love how it's totally independend of the orientation of the objects towards each other - you don't need any ifs, the square of the distance automatically makes the result positive and it just works.

Here, I call the method maybeCollision (and that's a bad name, as it's not a verb. Still fits!) because you still have to check per pixel - it sees anything inside of the circle as a collision. But it's lightning fast and you have to check with bounding boxes, too (as long as you don't write Tetris or a round-based Minecraft)...


Your code looks ok to me, but here are a couple of points to improve:

You used the flag package to obtain the arguments to your program. The original intention of the flag package is to process optional, named arguments to your program and store their parsed values into variables (designated by pointers). Using it just to obtain a list of arguments is somewhat "overkill", better would be just to use a simple variable in the os package: os.Args. os.Args holds the command-line arguments, starting with the program name. Since you don't need the program name, skip that by re-slicing this slice. Your new main() function:

func main() {
    ch := make(chan string)
    go WatchFolders(os.Args[1:], ch)
    for seenat := range ch {
        log.Println(seenat)
    }
}

By doing this we also got rid of the flag package dependency (so it won't have to be added to your compiled executable; and os was already used, so that's not a plus).

Next on to your map utilized as a Set. This is how you check if something is in your map:

if _, ok := set[minifi]; !ok {
    // fi doesn't exist in the set, add it
}

This works, but can be written simpler. Note that if a key is not in the map, indexing a map yields the zero value of the value type of the map (Spec: Index expressions). Zero value for the bool type is false. So the expression set[minifi] will be true if minifi is in the map (because when you put it into the map, you stored true as the value for this key), and it will be false if minifi is not in the map (the zero value of bool). So this can be rewritten as follows:

if !set[minifi] {
    // fi doesn't exist in the set, add it
}

Now an explanation why your original os.FileInfo didn't work as the key. When you want to find an element in a map by key, Go uses the == comparison operator to test for equality of keys (hash code is generated and used under the hood to speed up the lookups, but that is irrelevant now).

This is how the spec defines the terms and the result of the comparision. Quoting the relevant part from Spec: Comparision operators:

  Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
  Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
  Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

Your miniFileInfo type is a struct, and 2 values of the same struct type are equal if all their fields are comparable and are equal. So you will find a value in the map if they match by name and size.

os.FileInfo is an interface, so a different comparison rule applies here. At runtime interface values can hold values of different dynamic type. Both the dynamic type and the value must match in order to claim 2 interface values equal. (You can read more about the representation of interface values in blog post The Laws of Reflection: The representation of an interface.)

The dynamic type of the values stored os.FileInfo interface is a pointer, a pointer to the unexported type os.fileStat. So now we need to apply the comparison rule for Pointers. 2 pointers are equal if they point to the same variable.

So 2 values of os.FileInfo will match only if the pointers stored in them match. You used ioutil.ReadDir() to obtain the slice of FileInfos, and whenever you call it, it creates new os.fileStat pointers and hence they will never be equal, meaning the wrapper os.FileInfo interface values will never be equal, meaning indexing the map with these FileInfo values will never yield any results.


Preamble: I don't know scala. All code you see here is improvised from the question and a few bits of scala that I've seen somewhen. Improvements and comments are welcome
Naming:
I am going to be blunt here... Your names are bad. Not horrible, but seriously bad.

var i = ids.split(",");

first thing jumping me here is, that you have a single thing (the id-string) named with a plural. next thing that jumps me, is that you have a collection with multiple elements and it's name is a single letter.
Rename that stuff:

ids -> idString
i -> idCollection (or even ids, anything is better...)

on we go:

for(pos<-0 to i.size){

usually the iterator in a for loop has your single letter identifier, extremely often, that is our friend i. Also you don't really have to cramop that all together. Give your variables and statements some fresh air:
for (i <- 0 to idCollection.size) {

looks much more readable IMO ;)

val result = SQL([...]

result is a dumb name. result of what? yes, I know it's the SQL statment, but if you just skim it, you could think it's what you want to return in the end.
instead I'd use dbRecord or similar.
Alright, so much for the names, now we get to the real wtf
Storing numbers:
WHY DO YOU STORE NUMBERS AS STRINGS?
AND WHY DO YOU STORE POINTS IN A SEPARATE ENTRY? pardon caps
Don't shoehorn everything into Strings:
var pointMap:scala.collection.immutable.Map[String,Double]=null
[...]
val point:Double = if (result[Boolean]("privacy")) {
    result[Double]("point")
} else {
    0.0
}
pointMap+=("id" + idCollection(i) -> point)


String manipulations: transform "a-b-c" into "a(b(c))"

Having split the string you can join it with brackets instead of replacing them.  You could optionally choose to remove the repeatString function and your +/- 1, but it does make a lot of sense the way you have it.

function dashesToParentheses(str) {
    var list = str.split('-');
    return list.join('(') + Array(list.length).join(')');
}


I'm very confused by your naming - or perhaps you are. When pushing something onto a non-empty deque, you create a new Element and set its next element to be the preceding one. I.e. when examining the appended element, I'd see that its next is in fact the one before it. And vice-versa for unshift. It seems to work out (or I think it does) because you're at least consistent about the next-means-previous, and previous-means-next.
Or you've simply got push and unshift (and pop and shift backwards. Which is think is the case.
You could make good use of Struct for your Element class. And I'd make it a private inner class, since it's not meant for external use

class Deque
  # ...

  private

  Element = Struct.new(:datum, :prev, :next)
end

Saves you having to type the whole class declaration.
While pop and shift return the actual data, your first and last accessors return Element instances. I'd suggest that pop/push/shift/unshift/first/last all return data, while you use different methods/variables internally to get the Element-wrapped data. Say head and tail.
You don't need to check for nil as often as you do. Forgetting for at moment the prev/next confusion, your push method could be just

def push(datum)
  if @last.nil?
    @last = @first = Element.new(datum)
  else
    @last = Element.new(datum, @last)
  end
end

As an alternative to your current approach, you could put some more logic into Element to clean up the code in Deque. I.e. give Element methods like append and prepend which create a new Element instance that's properly linked to the receiver. It avoids you having to set things from the outside.

class Deque
  def initialize
    @head = nil
    @tail = nil
  end

  def push(datum)
    if @tail
      @tail = @tail.append(datum)
    else
      @head = @tail = Element.new(datum)
    end
  end

  def pop
    return nil unless @tail
    datum, @tail = @tail.datum, @tail.prev
    datum
  end

  def unshift(datum)
    if @head
      @head = @head.prepend(datum)
    else
      @head = @tail = Element.new(datum)
    end
  end

  def shift
    return nil unless @head
    datum, @head = @head.datum, @head.next
    datum
  end

  def first
    @head ? @head.datum : nil
  end

  def last
    @tail ? @tail.datum : nil
  end

  private

  Element = Struct.new(:datum, :prev, :next) do
    def prepend(datum)
      raise "Can't prepend here" if self.prev
      self.prev = self.class.new(datum, nil, self)
    end

    def append(datum)
      raise "Can't append here" if self.next
      self.next = self.class.new(datum, self, nil)
    end
  end
end

The exceptions being raised in prepend/append are there to catch cases where you try to append/prepend something "in the middle" if the deque. Doing so would only modify one side of the linkage, causing the list to branch and things to go weird.

Of course, the simplest deque in Ruby is the built-in Array.

deque_instance = []

And done.


Creating a new item or updating an existing item on page load

The only real issue I can see (it's been a while since I worked in VB, so there may be other things) is using a global value to store the ID of the created record. Make your Create() sub a function and return the ID instead of storing it in the property; that will remove a potential source of errors.

Other than that, naming is always important. Create doesn't say much, maybe name it CreateNewBook. Also, what do navmod or modID mean? Generally be more explicit in your naming, it will help others (and you as well a bit later on) understand your code.

This may not exactly compile, as my VB days are a bit in the past as mentioned, but I think you'll get the idea:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim bookID = Request.QueryString("bookID")

    If Not String.IsNullOrWhiteSpace(bookID) Then
        newBook = False
    Else
        newBook = True
        bookID = CreateNewBook()   'create a new book
    End If

    If Not newBook Then
        commitData()   'saves data on form
    End If

    If Not IsPostBack And Not newBook Then
        Page.DataBind()
        populateControls()    'populate my dropdown lists and radio/checkbox controls
        populateDatasets()    'load datasets to be used later
    End If
End Sub

Public Function CreateNewBook() As String
    'create a new book
    Using dbcon As New SqlConnection(DBUtilities.ConnectionStringDefault)
        dbcon.Open()
        Dim cmd As New SqlCommand(CreateSQL, dbcon)
        cmd.Parameters.Add(New SqlParameter("@authorID", currentUser))
        modID = DirectCast(cmd.ExecuteScalar(), Int32)
    End Using
    navmod = NavbookFactory.Getbook(CInt(modID))
    populateNewBook()

    CreateNewBook = modID.ToString()
End Function

Now that I think of it, the modID property I just eradicated may have been used by other methods of yours. If at all possible, try to always pass those values around to any methods that need them. You want to have as little "global" state as possible, because that increases the risk of side effects - and such bugs are often pretty hard to track down and fix.

Also, if you need to work in VB (if you don't, my advice would be to consider switching to C#, as it's a much clearer and stricter language, you can often get much better help because many advanced programmers shun VB, and most example code nowadays will also be in C#), always call parameterless methods (such as ToString()) with parentheses anyway - method calls that don't look like method calls are always a pain, and it gets worse if that code should ever have to transition to another language.


Few improvements which can be seen right away are in this part

let splitStr = [];
for (let i = 0; i < str.split(' ').length; i++) {
  if (str.split(' ')[i].length) {
    splitStr.push(str.split(' ')[i])
  }
}

Can be re-written as:

const tempArray = str.split(' ')
let splitStr = tempArray.filter(data => data.length)

You can use Array.filter directly here.
Str.split(' ') is getting repeated at lot. So better save it in some variable and then re-use
Comparison inside if (length === 0) in other portions can be written as if(!length) since 0 is falsy


Improving efficiency of Project Euler 185 (16-place Mastermind)

Expressiveness

What does prob(a,n) mean?  How about apply_constraint(guess, n_correct) instead?
Why do you reinvent xrange() (Python 2) or range() (Python 3)?
number is a global variable, which makes the code hard to follow.
number is an iterable of numbers, but your constraints are given as characters, which makes comparisons awkward.
temp is an uninformative name for a variable.  It's especially bad when you return temp — that implies that it's not very temporary at all.
Parsing the input is better done using a regular expression.

Strategy

Let \$p\$ be the number of positions (16 in the real problem, 5 in the test case).
Let \$g\$ be the number of guesses (22 in the real problem, 6 in the test case).

The outline of prob() is:

for j in number:
    for i in newCombos:
        …
        [… for l in range(len(newCombos.values()))]

number is \$O(10^p)\$ (the number of candidate solutions you initially generate).

newCombos has \$\left(\begin{array}{c}p\\c\end{array}\right) = \dfrac{p!}{c!\ (p - c)!}\$ combinations, each of which has \$c\$ values, where \$c\$ is the number of correct guesses within that constraint.

If we estimate that \$c = 3\$, then the complexity of your solution is \$O(10^p p^3g)\$ in time.  The maximum space needed is the number candidates remaining after processing the first constraint, or \$O(\left(\begin{array}{c}p\\c\end{array}\right))\$.

I'm not sure that I analyzed the complexity completely correctly, but in any case those bounds are crazy.  Your strategy of enumerating all the possibilities just doesn't scale.  It's as if you were trying to solve a sudoku puzzle by generating all possible solutions first.


I don't see the need to find a specific row number.  Simply work your way down until you reach the current week.
The key to reducing repeat code is to extract it to it's own method.
Refactored Code
Sub UpdateWeeklyReports()
    Application.ScreenUpdating = False
    Const WorksheetName As String = "Sheet1"
    Const FirstWeekNumberRow As Long = 3
    Dim LastWeek As Range
    Dim What As String, Replacement As String
    With Worksheets(WorksheetName)
        Dim Row As Long
        For Row = FirstWeekNumberRow + 1 To  Format(Now, "WW") - 1
            If Not .Cells(Row, 3).HasFormula Then
                ' What = "sem " & .Cells(Row - 1, 2).Value
                ' Replacement = "sem " & .Cells(Row, 2).Value
                AddNewRow SourceRange:=.Rows(Row - 1).Range("C1:J1"), What:=What, Replacement:=Replacement
                AddNewRow SourceRange:=.Rows(Row - 1).Range("M1:T1"), What:=What, Replacement:=Replacement
                AddNewRow SourceRange:=.Rows(Row - 1).Range("W1:AD1"), What:=What, Replacement:=Replacement
            End If
        Next
    End With
End Sub

Private Sub AddNewRow(ByVal SourceRange As Range, ByVal What As String, ByVal Replacement As String)
    With SourceRange
        .Offset(1).Formula = .Formula
        .Offset(1).Replace What:=What, Replacement:=Replacement, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    End With
End Sub


pos+ (value added to position) - ex 3.5 in “ANSI Common Lisp” (p57)

For loop you can see the excellent book by P. Seibel “Practical Common Lisp”, available on-line, in particular chapter 7 and chapter 22.

Let’s start from the last function: the idea is ok, we can just simplify the function noting that (lambda (x y) (+ x y)) is nothing more than the original +:

(defun pos+3 (lst)
  (mapcar #'+ lst (range (length lst))))

For the first function, since an helper function is introduced, it could as well be used for tail-recursion, instead of normal recursion:

(defun pos-helper (lis n acc)
  (if (null lis)
      (reverse acc)
      (pos-helper (rest lis) (1+ n) (cons (+ (first lis) n) acc))))

(defun pos+ (lis)
  (pos-helper lis 0 nil))

where acc accumulates the result, which at the end must be reversed. Note that certain Common Lisp compilers transform the function in an iterative loop, so I do not know if this would be considered recursive. In that case, your version is ok (but note the idiomatic use of (1+ expression) instead of (+ expression 1)).

Then, for the second function, of course a loop version is much more readable (even if it is not so lispy :) :

(defun pos+2 (lis)
  (loop for i from 0
        for x in lis
        collect (+ x i)))

If you prefer more parentheses, here is a variant (without modifying the original list):

(defun pos+2 (lis)
  (let ((result nil))
    (do ((i 0 (1+ i))
         (y lis (cdr y)))
        ((null y) (reverse result))
      (push (+ (car y) i) result))))

A final note about efficiency: the function pos3 is the less efficient one since it must generate a new list with the same length as the original one (and so the list must be scanned twice, in addition to doubling the memory footprint of the program). With a simple trick we could use mapcar and avoid creating a new list:

(defun pos+3 (lis)
  (let ((index -1))
    (mapcar (lambda (x) (+ x (incf index))) lis)))


There's more elegant ways, although not necessarily more efficient. The common idiom for fiddling with this kind of linked list in C is to add one more layer of indirection and fiddle with pointers-to-node-pointers, like this:

void insert(node_t **head, int val)
{
    node_t *new_node = malloc(sizeof(node_t));
    new_node->val = val;
    new_node->next = NULL;

    node_t **ptmp = head;
    while (*ptmp != NULL) {
        ptmp = &(*ptmp)->next;
    }
    *ptmp = new_node;
}

Given that example, I think you can figure out how to rewrite movetoend in just a few additional lines: much shorter than the page of code you have now.

However, whether this will be equally fast depends on your compiler and optimization levels. When in doubt, check the assembly code! If you see a lot of additional memory loads in the inner loop, that's a bad sign.

In C++, but I think not in C yet, you could eliminate even the appearance of extra memory loads by doing

void insert(node_t **head, int val)
{
    node_t *new_node = malloc(sizeof(node_t));
    new_node->val = val;
    new_node->next = NULL;

    node_t **ptmp = head;
    while (node_t tmp = *ptmp) {
        ptmp = &tmp->next;
    }
    *ptmp = new_node;
}


There's not a lot of code here to be reviewed, but I'll have a go.

A small efficiency gain is possible, by moving the db_ argument in the initializer list, rather than copying it:

SqlTransaction(std::shared_ptr<sqlite::database> db_)
  : db{std::move(db_)}
{ *db << "begin;"; };

It's not necessary to delete the move constructor, as explicitly deleting the copy constructor prevents the move constructor being implicitly provided.  However, if you feel that doing so improves clarity, you should probably delete move assignment, too.
We should document that the class isn't thread-safe.  It's quite reasonable that we should use it from only one thread, but we need to be clear to our users about that.  Alternatively, we could make it thread-safe by making finished an std::atomic<bool> and using its test-and-set method, exchange().
Since rollback() tests finished, there's no need to duplicate that in the destructor - just call rollback() unconditionally.  It may be worth taking steps to avoid it throwing when called there - destructors that throw need to be handled with extreme care.

~SqlTransaction() { try { rollback(); } catch (...) { /* ignore */ } };

I have nothing specific to SQLite, as I've not used that library myself (I'm surprised it has to parse string commands, rather than having methods for those operations, though).


Executing asynchronous functions in sequence

Quick review.

It is not bullet proof. So much so that it is a bug dressed in javascript.

You must protect against improper use, inadvertent error, or failure to complete.

The next bit of code shows a variety of ways it will fail.

series([cb => {
    if (Math.random() < 0.01) { throw "Spanner" }
    const handle = setTimeout(() => {
        cb('done');
        console.log("Not really done");
        cb('Done again');
    }, 1000);
    // Indeterminate completing clause
    setTimeout(() => clearTimeout(handle), Math.random() * 2000);
}, "Iron filings"], undefined); // undefined for a free throw if it got to the end

Why not use promises and async functions???

The following is immune to any of the above spannering.

async function series(tasks, tasksComplete) {
    if (Array.isArray(tasks)) {
        const timeoutPeriod = 5000; // 5 seconds and your out. Task can still complete
        const results = [];
        while (tasks.length) {
            const task = tasks.shift();
            if (typeof task === "function") {
                await new Promise(done => {
                        setTimeout(() => done("Too slow!") , timeoutPeriod);
                        task(done);
                    })
                    .then(result => results.push(result))
                    .catch(error => results.push(error))  // assuming good to continue
            }
        }
        if (typeof taskComplete === "function") { tasksComplete(results) }
    }
}

Update

In lieu of the above answer and comment you made the following might suit your needs a little better.

Rather than pass a callback to the series function, that function returns a promise which will resolve when all tasked have completed successfully, if there is a problem along the way the function will terminate returning the error.

Also the results stack is passed to each task. Rather than the last results the entire results stack is passed. It is up to the task which results it needs to use.

Also added are some options. Stop on error if true will stop on the first error, and timeout is greater then 0 will have a timeout error on tasks.

// Returns promise to do tasks in series
// stopOnError is false then continues tasks if there is an error placing
//             the error on the results stack
// timeout if > 0 will throw error if task takes too long.
// Promise resolves with the results stack for both completed and error
function series(tasks, stopOnError = true, timeout = 0) {
    const results = [];
    async function doEachTask(completed, failed) {
        while (tasks.length) {
            const task = tasks.shift();
            if (typeof task === "function") {
                await new Promise((done,error) => {
                        if (timeout) {
                            setTimeout(()=> error(new Error("Too slow!")) , timeout);
                        }
                        task(done, results);
                    })
                    .then(result => results.push(result))
                    .catch(error => {
                        results.push(error);
                        if (stopOnError) { failed(results) }
                    });

            }
        }
        completed(results);
    }
    return new Promise(doEachTask);
}

Used as follows

series([
    (complete, data) => {
         setTimeout(()=> {
             complete("Task1 complete");
         },1000)
    },
    (complete, data) => {
         console.log("Task 2 has data : "+data[0]);
         setTimeout(()=> {
             complete("Task2 complete");
         },1000)
    }])
    .then(results => console.log(results))
    .catch(results => console.log("Error and available results : " + results));


looks great!

(filter #(not (nil? %1)) ...)

Prefer % instead of %1 for single arguments

Simpler to write as (remove nil? ...)

(map #(cond
       (= %1 i1) i2
       (= %1 i2) i1
       :else %1) input))

When you have map + function definition in one statement, consider creating a named function with a defn, or using a for expression:

(for [i input]
  (cond ...))

Never ever def inside a loop:

(do
  (def i (first to-swap))

def creates a global var http://clojure.org/vars

You want:

(let [i (first to-swap)]
  ...)

Consider using destructuring:

(loop [[i & more] i3
  ...
 (if i
   (recur more (swap o1 i) (swap o2 i))
   [o1 o2]))


Vanilla ES6 Todo/Task List with LocalStorage

I would prefer a better extensibility (for example, easy to add new actions) and to get the taskId only if I’m going to use it.

initializeEventListeners() {
    const actions = {
        button: 'removeTask',
        input: 'toggleCompleted'
    };

    this.tasksElem.addEventListener('click', (event) => {
        const action = actions[event.target.localName];
        if (action) {
            const taskId = event.target.parentNode.getAttribute('data-id');
            this[action](taskId);
        }
    })

    this.addButton.addEventListener('click', this.addNewTask.bind(this))
}


Don't use using namespace std;

It's bad practice that can cause a lot of problems that are easy to avoid, most people are used to the prefix, and three letters aren't that hard to type.

Don't use system("pause")

It's not portable and there are better ways to hold the console open.

Prefer nullptr to NULL

NULL is a macro that will be silently converted to 0 whenever possible. nullptr is a language extension and will only work contextually with pointers.

Use proper encapsulation

A linked list should be a class that acts as a container of Nodes. Your Node class should not know how to sort all Nodes. This is the job of the container. Furthermore Nodes are an implementation detail that should not be exposed to the user.

class LinkedList
{
public:
    // user functions should go here
private:
    struct Node
    {
        int value;
        Node* next{ nullptr };
    }
}

A few things to note.

I put the public section first. This way anyone reading the code
will know what functions and variables are available to them.
I used struct for the Node since it represents plain data. It is
also easier to use because struct is default public so the
LinkedList will be able to access it easily (But since it is
properly encapsulated inside the container nothing else can.)
I initialized new nodes to nullptr.

Printing and Sorting aren't typically done as member functions. They should be standalone functions that accept a container, or a range of a container to perform their tasks.

Use RAII whenever possible

You shouldn't be manually allocating memory. Especially since you aren't freeing it. Every instance of new should come with an instance of delete but you shouldn't be using them at all.

Prefer '\n' to std::endl

std::endl does more than just move to the next line. It is generally preferred not to use it casually.

Keep working on it. Try to implement the container with some of the member functions found at std::list. Browse The Core Guidelines from time to time. And bring us more code to review.


Divide and conquer approach in search for max element

First of all I'm not sure why you use a divide and conquer approach here, given that just walking over the entire list once and getting the maximum element is both shorter and more efficient.

Secondly I would use the more general &[T] instead of &Vec<T>.

Your implementation will recurse forever and crash with a stack overflow when the input is empty.

Because you demand PartialOrd rather than Ord, the result you get from max_elem will depend on the order of the list. For instance, a list with floating point numbers may get inconsistent results when NaN is present: if the list ends with NaN then than will be the maximum element. If it begins with NaN but also contains other numbers, then a different number will be the maximum element. It is even possible for NaN to hide the maximum number, and make the method return a number that is not the largest. A demonstration:

fn show(v: Vec<f64>) {
    println!("Max element of {:?} is {}", v, v.max_elem());
}
show(vec![1.0, std::f64::NAN]); // the max is NaN
show(vec![std::f64::NAN, 1.0]); // the max is 1
show(vec![10000.0, std::f64::NAN, 1.0, 1.0]); // the max is 1

Basically you should just use .iter().max() when you want the maximum element of some iterable structure, which avoids all of these problems.


355 - The Bases Are Loaded (math numbers conversion)

No, you don't need to convert to base 10. Base 10 is in fact quite slow to operate with, as it is in no way a "native" base for computers, which store integers in binary format.

Let's do the math. Assume you need to convert four digit number from base a to base b. Let x_i denote the digit of the number in base a and y_i the digit in base b:

In base a the number is:

x1*a^3 + x2*a^2 + x3*a^1 + x4*a^0 = ((x1*a + x2)*a + x3)*a + x4

In base b it becomes:

y1*b^3 + y2*b^2 + y3*b^1 + y4*b^0 = ((y1*b + y2)*b + y3)*b + y4

The right side of these equations suggests an algorithm idea: to convert a number to binary format from a string s in base a, start with zero, and in each step multiply the number so-far with a and add the next digit. This requires only one multiplication per loop, not two, like in your approach (although that's not likely the reason why your code is too slow.)

int len = strlen(s);
int i;
unsigned long long number = 0;

for (i = 0; i < len; ++i) {
        unsigned digit;
        if (s[i] >= '0' && s[i] <= '9') {
                digit = s[i] - '0';
        } else {
                digit = s[i] - 'A' + 10;
        }
        number = number * a + digit;
}

You had the rest of it already: adding for completeness. For conversion to base b, in each step divide by b.

const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

char result[50];
/* Note the end condition here: stop when the number becomes zero */
for(i = 0; number != 0; ++i) {
        unsigned digit = number % b;
        number /= b;
        result[i] = digits[digit];
}

Now result contains the digits backwards. To print them in order:

for (; i >= 0; --i) {
        putchar(result[i]);
}

Other minor performance notes

Don't call strlen() twice - there's no need to do it more than once anyway, but if there was, you could cache the result and pass as a parameter.
The code in main that determines whether the input string is acceptable is too complex: no need to do the conversion here, just check if each digit is in the acceptable range.

Unrelated notes about readability:

instead of this:

base = (base > a[i]-'0') ? base : a[i]-'0';

suggest using this:

base = max(base, a[i] - '0');

Avoid variable names like l - easy to confuse with 1.
Use const before read-only variabes (such as the array of digits).


5 lines ought to be enough for everyone

The following has no meaning. Why 5?

line1 = input()
line2 = input()
line3 = input()
line4 = input()
line5 = input()

Instead let the user end:

def get_lines():
    print("Enter 'END' to end.")
    lines = []
    line = input()
    while line != 'END':
         lines.append(line)
         line = input()
    return lines

Now you can write:

lines = get_lines()
file.write('\n'.join(lines))

Programming with with

with is an extremely useful idiom because it handles closing files automagically.

with open(filename,'r') as f:
    f.read()
# The file is closed automatically :)

If considered harmful (if overused)

So you just started programming and think "Oh the if statements are so good they feel so CS" (I felt that way too when I started programming when I was 15 so I understand you).

BUT so many if and elif are repetitive and you should not repeat yourself.

I would suggest the high level dictionary to accomplish the task more shortly.

command_actions = {
    'textviewer' : textviewer,
    'edit' : edit,
    'dir' : print_dir,
    'cls' : clear_screen,
    'shutdown' : shutdown,
    'help' : give_help
    }
if shell in command_actions:
    action = command_actions[shell]
    action()
else:
    error_message()

Be helpful

It is common and good practice to show some help/info if the user types in help.

Who sleeps too much does not catch fish annoys the user

Why do you sleep up to 4 seconds?

time.sleep(4)

Ok, this emulates an ancient terminal but really, you don't want to make the user wait so much without reason. I suggest  time.sleep(0.5)


Find index where left sum equals to right sum

Two minor improvments are possible:
1- splitting an array by the sum of the elements only makes sense if the elements are integers. Two equal sums of elements require the total sum over all elements to be even. Check this to shortcut the search.
2- if all elements are positive we can further shortcut the search (see comment).
On my notebook this cuts the runtime to ~ 1/3 for short arrays (len=200) and ~2/3 for long arrays (len=20k).

def find_index2(nums):
    total = sum(nums)
    if total%2 != 0:    # this shortcut only if integer array
        return False, -1
    total /= 2
    L = 0
    for i, v in enumerate(nums):
        L += v
        if L == total:
            return True, i
        if L > total:  # this shortcut only if only positive values in array
            break
    return False, i

edit:
Observing that sum() is faster than elementwise summation I changed the algorithm a bit. Now the majority (here: 50%) of the elements are summed up in one call to sum() and then the exact target value is searched for step by step. Also, I have incorporated @kyrill's comments to remove the restriction for integer values. Still, the assumed property of only positive values is used (see code comments).
Execution time is down to approximately 20% vs. OP's code:

def find_index8(nums):
    total = sum(nums) / 2.
    n = int(len(nums) * .5)  # arbitrary, well-guessed testing index
    S = sum(nums[:n])
    if S == total:
        return True, n-1
    elif S < total:                 # add elementwise
        for i, v in enumerate(nums[n:], n):
            S += v
            if S >= total:    # '>' shortcut only if only positive values in array
                return S==total, i
        return False, -1
    else:                 # subtract elementwise
        for i, v in enumerate(nums[:n][::-1], 2):
            S -= v
            if S <= total:    # '<' shortcut only if only positive values in array
                return S==total, n-i
        return False, -1


Although this passes the pep8 tool as of version 1.5.5,
this is not PEP8 compliant:

  Function names should be lowercase, with words separated by underscores as necessary to improve readability.
  Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

If you convert the lambda expressions to def statements, the result will be longer, but better.

Also, these statements are a bit tightly packed for my taste:

calcAverage = lambda *args: sum(args)/len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99)/10)-5)]

Would have been better this way, but PEP8 does not require it:

calcAverage = lambda *args: sum(args) / len(args)
determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, (min(s, 99) / 10) - 5)]

In this last statement, there are some redundant parentheses, this is equivalent:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A'][max(0, min(s, 99) / 10 - 5)]

Instead of the min hack for the value of 100, how about this way:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s / 10 - 5)]

Last but not least, beware that in Python 3, 27 / 10 will give you 2.7 instead of 2 as in Python 2. As such, the determinGrade will try to use a float as the list index, and your script will break. Adopting Python 3 is probably only a matter of time, so it's good to be prepare for that, and use // to ensure that you will get an integer index:

determinGrade = lambda s: ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s // 10 - 5)]

Suggested implementation

Putting the above suggestions together:

def is_valid_score(n):
    return 0 <= n <= 100

def calc_average(*args):
    return sum(args) / len(args)

def determine_grade(s):
    return ['F', 'D', 'C', 'B', 'A', 'A'][max(0, s // 10 - 5)]

def get_valid_score():
    while True:
        try:
            s = int(raw_input('Input score: '))
            if is_valid_score(s):
                return s
        except ValueError:
            pass
        print('Score has to be an integer in the range 0 to 100')

if __name__ == "__main__":
    scores = [get_valid_score() for _ in range(5)]
    print('The scores are: ' + str(scores))
    print('The average is: ' + str(calc_average(*scores)))
    print('The grade is: ' + determine_grade(calc_average(*scores)))