Adding multiple events in gcalcli using a bash script

Your main questions

  Is there a way I could do this in one loop?

Yes.
The two loops do essentially the same thing,
but use different values.
The loop should be inside a function,
the range of values and the event details should be parameters of the function.

  Or should I be using another method?

As it is, the dates of the event are very hard to read.
It would be better to have a function that takes start date, end date, and other event details, and use a loop from start date stepping forward one week until the end date is reached.

Furthermore, a "recurring event" is usually not the same event registered n times, but a single event with some parameters. I don't know the API of Google Calendar, but I suggest to check on that, as there might be a much easier method, natural and intuitive method to register a proper recurring event.

Code review

Avoid pointless comments like this one that only state the obvious:

#assigning variables
start="14:00"
duration="150"
title="Exper. Lab"
year="2016"
start2="17:30"
duration2="230"
title2="Calc1"

And there's really no need to define start2, duration2 and title2 at the top of the file.
It's unnecessary information at that point.
You could define these right before the second loop.
You could even reuse the start, duration, title variables.
If you did that, the two loop bodies would look identical,
and converting to a function would be a trivial step.

Be extremely cautious with long lines like this:

for monthday in {09/{1..29..7},09/{6..27..7},10/{4..25..7},10/{6..27..7},11/{1..29..7},11{3..24..7},12/{6..20..7},12/{1..15..7}}

Can you spot the bug?

   Should have been 11/{3..24..7} instead of 11{3..24..7}

A long relative path like this is awful:

... | ../../../../usr/bin/gcalcli add --calendar 'Class'

What if you later need to change the directory of this script or gcalcli?
You will have to recalculate the correct depth,
and update the script at multiple places (the two loops).

It's better to add ../../../../usr/bin to PATH, and use simply gcalcli. Alternatively, you could define a function like this:

gcalcli() {
    ../../../../usr/bin/gcalcli "$@"
}

Actually, since I don't have gcalcli on my PC,
I used this function as a dummy in my tests:

gcalcli() {
    cat
}

Code is easiest to read from top to bottom,
with minimal distractions sideways.
This line is too long,
and I'm forced to scroll to the right to see it:

(echo $title ; echo "'$monthday/$year $start'"; echo $duration) | ../../../../usr/bin/gcalcli add --calendar 'Class'

Avoid multiple statements on one line, break it up like this:

(
echo $title
echo "'$monthday/$year $start'"
echo $duration
) | gcalcli add --calendar 'Class'

Alternative implementation

Consider the alternative implementation below, using some of the suggestions above.

#!/bin/bash

PATH="path_to_gcalcli:$PATH"

add_to_calendar() {
    title=$1
    datetime=$2
    minutes=$3

    (
    echo $title
    echo "'$datetime'"
    echo $minutes
    ) | gcalcli add --calendar 'Class'
}

add_weekly_event() {
    title=$1
    start_time=$2
    minutes=$3
    start_date=$4
    end_date=$5

    event_date=$start_date
    while [[ "$event_date" < "$end_date" ]]; do
        datetime="$(date +%m/%d/%Y -d $event_date) $start_time"
        add_to_calendar "$title" "$datetime" $minutes
        event_date=$(date +%Y/%m/%d -d "$event_date + 1 week")
    done
}

add_weekly_event "Exper. Lab" 14:00 150 2016/09/01 2016/12/21
add_weekly_event "Exper. Lab" 14:00 150 2016/09/06 2016/12/21
add_weekly_event "Calc1" 17:30 230 2016/09/12 2016/12/20

This script is much slower than yours, due to the many calls to date.
But it's a lot easier to understand what dates will be added,
and it's trivially easy to reuse it for other events.

Note that the add_weekly_event function takes the date parameters in %Y/%m/%d format, where month and day are 0-padded. This is to make the loop condition possible, as the alphabetic ordering of dates in this format coincides with the correct chronological ordering.

Also note that before passing the date to add_to_calendar,
it is formatted to (roughly the same) format in your script.
I don't know the Google Calendar API,
but I suspect this is unnecessary,
the %Y/%m/%d format probably works just fine.

For the date parsing and + 1 week calculation,
this script depends on GNU date.
This is the default on Linux,
on other OS you can usually find it in a coreutils package,
named gdate.
To use gdate instead of date,
you can create a function:

date() {
    gdate "$@"
}

But this technique is not my first recommendation.
My first recommendation is to check the Google Calendar API to create proper recurring events, instead of manually looping over dates and adding the same event multiple times.


Function that normalizes a vector of double

It looks pretty good as it is but I can offer the following:

template <typename InputIterator, typename OutputIterator>
void normalizeProbability(InputIterator begin, InputIterator end, OutputIterator out) {
    typedef typename std::iterator_traits<InputIterator>::reference ref_t;
    double norm = std::accumulate(begin, end, 0.0);
    std::transform(begin, end, out, [norm](const ref_t t){ return t/norm; });
}

I have removed the cast to double, which isn't necessary. The double return type is deduced by the 0.0 argument. I also changed to use std::iterator_traits instead of decltype which I think is a bit cleaner.

The biggest source of error you have is in the summation of norm. Adding a small floating point (FP) number (the dereferenced value) to a large floating point number (the current sum) will cause a truncation error. For example 1.0 + 1E-18 == 1.0 will return true due to the limited precision of FP-numbers. What you want to do is to add the numbers from the smallest to the biggest. But simply sorting isn't good enough, consider 10^20 entries (yeah I know fat chance but it's just for illustration) each with value 1E-18 you expect the norm to be 10^2, but in fact it will be close to 1.0 or less. Because after about 1E18 iterations the running sum will be so big that any remaining elements will truncate. So you need to have a heap, take the two smallest numbers, add them and put the result back into the heap. Then repeat until only one number is left, which will be the sum. This guarantees that you will always minimize the truncation error.

However I have no idea if this level of accuracy is necessary for you, but you stated precision as a question so I went for it. :)


First Impressions
I haven't gone through the functionality in detail but a few things strike me immediately.

Why explicitly include StringSplitOptions.None. They default value is none.

IsNullEmptyOrWhiteSpace() seems to be a (not included) extension method for string that performs the same function as String.IsNullOrWhiteSpace.  Does it do something else as well?

The check for an empty 'line' inside the loop

if (line.IsNullEmptyOrWhiteSpace())
        continue;

should be redundant as we have previously filtered the lines

var filterLines = lines.Where(line => !line.IsNullEmptyOrWhiteSpace());

I would need to do up some performance checks to be sure but I reckon that the use of the StringBuilder (presumably for performance reasons) will be negated by the calls to line.SubString().

I can't tell for certain what the requirements are  - I would guess

Max line Length of n
Do not split words
Do not end on a space
Do not start on a space

but it look like a linear progression through the string, with some back tracking to deal with split words/spaces, might work and appending the individual chars might give you better performance.

The final return should be

return multiLine.ToString();

there is no need to create another string and place the result of multiLine.ToString() inside it and then return the anonymous string.


How to create a simple stateless cache class in PHP

I would say that there isn't a correct or incorrect way of achieving this. Everyones requirements differ.

You probably want to expand this out, there's a lot going on in the one static method you have in that class. Whilst I don't have anything against mediator patterns, I would probably combine a number of patterns to build a powerful caching class, as well as utilising magic methods (I know some people are averse to this).

I need to note the below is a lot more complicated and would benefit from some refactoring to be stored against the actual method rather than a key.

class Cache {

    /**
     * Cached objects
     * @static array
     */
    private static $cache = array();

    /**
     * Per instance class name
     * @var string
     */
    private $call;

    /**
     * Per instance method name
     * @static array
     */
    private $method;

    /**
     * Construct the class and build cache array if not set
     * @param string $method
     * @param string $class
     * @param string $key
     */
    public function __construct($method, $class, $key)
    {
        if ( ! isset(static::$cache[$class] )
            static::$cache[$class] = array();

        if ( ! isset(static::$cache[$class][$method] )
            static::$cache[$class][$method] = array();

        // Set the class for this instance
        $this->call = $class;

        // Set the method for this instance
        $this->method= $method;

        // Set the key for the cache
        $this->key = $key;
    }

    /**
     * Get the cached value
     * @return mixed Cached value
     */
    public function get()
    {
        return $this->{$this->key};
    }

    /**
     * Get magic method to return the key
     * @param string $key
     */
    public function __get($key)
    {
        if (isset(static::$cache[$this->call][$this->method][$key]))
            return static::$cache[$this->call][$this->method][$key];

        return static::$cache[$this->call][$this->method][$key] = call_user_func(array($this->call, $this->method));
    }

    /**
     * Call static magic method, catches all statically called methods
     * and builds an instance of the cache class using a reflector
     * @param $method
     * @param $args
     */
    public static function __callStatic($method, $args)
    {
        $method = str_replace(__CLASS__ . '::', '', $method);

        $ref = new ReflectionClass(__CLASS__);

        $inst = $ref->newInstanceArgs($args);

        return $inst->get();
    }

}

Usage

$result = Cache::{method}({class}, {key};

To retrieve say a user object from the User class with method get_user;

$user = Cache::get_user('User', 'user_object');

The main advantage to this is that the class can be extended easily using other design patterns such as a Facade that further simplifies the class API. It can also be added to easily with further methods within the class body itself rather than by a pure static call. The class can also be instantiated with the new keyword providing the ability to create separate cache instances that utilise the same static properties and methods.

I need to add this class is very much a prototype that I thought of when I saw your class above. I love cacheing stuff in general and providing standardised interfaces for it is always a great thing to do across all applications you write.


Getting the neighbors of a Point in a 2D grid

Improvements

Use x and y names to avoid confusion about what is i and what is j
I personally find it preferrable to put the x parameter first
rows and cols should not be static variables, so neither should this method
Use a double for-loop to loop over the neighbors
Declare by interface and not implementation (use List<Point> when possible)
Use some maths to check if you're at a corner or not

Code
private List<Point> getNeighborsOfPoint(int x, int y) {
    List<Point> neighbors = new ArrayList<Point>();
    for (int xx = -1; xx <= 1; xx++) {
        for (int yy = -1; yy <= 1; yy++) {
            if (xx == 0 && yy == 0) {
                continue; // You are not neighbor to yourself
            }
            if (!CONSIDER_CORNERS && Math.abs(xx) + Math.abs(yy) > 1) {
                continue;
            }
            if (isOnMap(x + xx, y + yy)) {
                neighbors.add(new Point(x + xx, y + yy));
            }
        }
    }
    return neighbors;
}

public boolean isOnMap(int x, int y) {
    return x >= 0 && y >= 0 && x < cols && y < rows;
}

In this code, I have not added your array[i][j] != 0 check, but that can easily be added into isOnMap, although you could then rename it to isValidNeighbor or something.
Going the extra mile
Having this method, it is very easy to add support for some very crazy neighbor styles. This might not fit your game, but using crazy neighbor styles can transform a concept into an entirely different game.
For example, take Minesweeper Flags (where the objective is to find the mines and not avoid them).

We all know what an 8 means, right? 8 mines around the number, plain and simple.

Now, what if we transform the way we look for neighbors? To what I call "Chess style" (based on how a Knight moves in Chess).

This "simple" change leads to a much greater challenge when playing, leading to all kinds of fun.
The change required for this is really simple, extract a NEIGHBOR_SET array:
private static final Point[] NEIGHBOR_SET = new Point[]{ new Point(-2, -1), new Point(-2, 1),
   new Point(-1, -2), new Point(-1, 2), new Point(1, -2), new Point(1, 2), new Point(2, -1), new Point(2, 1) };

private List<Point> getNeighborsOfPoint(int x, int y) {
    List<Point> neighbors = new ArrayList<Point>();
    for (Point neighbor : NEIGHBOR_SET) {
        if (isOnMap(x + neighbor.x, y + neighbor.y)) {
            neighbors.add(new Point(x + neighbor.x, y + neighbor.y));
        }
    }
    return neighbors;
}

Using this method, the special case logic for handling corners and the self neighbor is no longer necessary.
Of course, using the ordinary neighbor set is also possible with this method:
private static final Point[] NEIGHBOR_SET = new Point[]{ new Point(-1, -1), new Point(-1, 0),
   new Point(-1, 1), new Point(0, -1), new Point(0, 1), new Point(1, -1), new Point(1, 0), new Point(1, 1) };


When writing programs it is often important to do some mental math before you start. In Math class at school they would often suggest that you estimate what the answer will be to a problem before you calculate it "for real".

Here, what you have, is a recursive function. Each time the function is called, it loops over the current-list's members creates a new LinkedList, adds the member and then recurses.

The algorithm is actually quite clean, and readable.... but, do the math:

For a list of 10 members, you create 10 "sub" lists. For each of those sub lists, you recurse, and create 10 more..... so, taking your example of 10 lists of 5 members, how big will your results be (how many lists....)?

5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5

9765625, but let's call that 10 million

Now, each list is a LinkedList which creates a Node instance for each member, so, each LinkedList has 6 instances created to store references to the members (and the list itself), so, let's just say that each instance is 32 bytes (which is about right - by the way).... that's

10Meg * 6 * 32

That's 1.92 Gig

Now, you take in to account various other things, like the fact that you are storing each list in another list, which will need 10 million members of 32-bytes.... or 320 meg, you are past the 2Gig mark.

So, your solution will use "more than" 2 Gig for your 10-lists of 5-members.

How can you support 10-by-10 solutions? (10 billion permutations - 1000 times more than 10-by-5)..... I don't believe you can....

What you can do though, is be more memory efficient with your data structures....

Using an ArrayList instead of a Linked List will reduce your per-node memory from 32bytes-per-node to just 8 or so.....

Using an iterator/push mechanism will remove the need for the list entirely, and will not need to store anything at all.....

Otherwise, frankly, you're out of luck.... there's just no way that you can create a scalable system that has a size-complexity of \$O(m^n)\$ where m is the number of elements in each list, and n is the number of lists....

For example, in your code, you can remove the results list entirely, and then simply replace the lines:

if (d == inputList.size()) {
    outputList.add(tempList);
    return;
}

with:

if (d == inputList.size()) {
    System.out.println(tempList);
    return;
}

And suddenly you will no longer be constrained by memory (though it will be pretty damn slow still).


Eratosthenes' and Sundaram's prime sieves in Python

There are some curious inconsistencies between the Eratosthenes and Sundaram code.

    for i in range(2, limit):
        if i * i > limit:
            break

is IMO more Pythonic than

    i = 1
    j = i
    while (i + j + 2 * i * j <= new_limit):
        ...
        i += 1
        j = i

We can refactor the second into something similar to the first: firstly, observe that there's no need to repeat the assignment j = i:

    i = 1
    while (i + i + 2 * i * i <= new_limit):
        j = i
        ...
        i += 1

Then simplify algebraically:

    i = 1
    while (2 * i * (i + 1) <= new_limit):
        j = i
        ...
        i += 1

And finally replace with range:

    for i in range(1, new_limit + 1):
        if 2 * i * (i + 1) > new_limit:
            break
        j = i
        ...

As noted by Janne, you can then refactor the inner loop to also use range...

The indexing of the arrays in both is a bit tricky. Are the maintenance costs worth saving four bytes of memory? If so, would it at least be worth leaving a comment to explain why (for example) the primes recovered by the Sundaram sieve are 2 * i + 3 instead of the 2 * i + 1 which someone who just read the Wikipedia page would expect?

    primes = [2]
    for i in range(0, new_limit):
        if boolean_list[i]:
            primes.append(i * 2 + 3)

can be written as a one-liner using something called list comprehensions. This is something that's worth learning because it's very common style for Python.

    primes = [2] + [i * 2 + 3 for i in range(0, new_limit) if boolean_list[i]]

        if boolean_list[i]:

...

        if boolean_list[i] == True:

What's the difference?

Answer: the first one is better style. x == True should be rewritten as x ; and y == False or y != True should be rewritten as not y. With good variable names this usually gives a very natural reading.

On the subject of names: boolean_list tells me the type, but what I care about is the meaning. For Eratosthenes that's easy: a True means that the index is a prime, and a False means that it's a composite number, so is_prime is a good name. For Sundaram the exact interpretation is a bit trickier, but is_prime would still work.


Algorithm to replace this duplicated code

So, a linear mapping from 50-200 onto 40-20 is (40-20)/(200-50) = 0.1333 font size points per length. So we can can compute this as

$('.fc-cards').css('font-size', 20 + 0.1333 * (200 - maxLen));

for a sliding linear falloff in font size. If you want to clamp the sizes to change in exactly the same way, you could index them into an array of sizes, computed by the modulus of the length, i.e. something like...

 $('.fc-cards').css('font-size', [40, 25, 22, 20][Math.floor(maxLen / 50)]);

But you'll need suitable checks on the length to ensure you remain in bounds.

These solutions are debatably more elegant though. They take less code, but they're not as easy to read as definitely solving the same problem your original if tests did. I'd probably prefer a loop over a dictionary of range/size possibilities as the best solution:

sizes = [50, 100, 150, 200];
fonts = [40, 25, 22, 20];

for (var i = 0; i < sizes.length; i++)
{
  if (maxLen < sizes[i])
  {
    $('.fc-cards').css('font-size', fonts[i]);
    break;
  }
}

Edit: Changed based on comment that for/in doesn't ensure enumeration order.

I wouldn't rage against the original solution in a code review, either. Elegance is found in the clearest expression of the goal, in tension with the solution efficiency and maintainability (where, in my view, clear expression wins 99/100 times). Efficiency is not a worry here, and adding/removing sizes from the range in the original code is trivial. Hence, pick whatever your team finds easiest to read a solving the "Change the font size based on length in these windows" problem is.


Your Script

Handlers

Unless your handlers are called somewhere else, you can just embed them

window.addEventListener('load', function () {
    canvasApp();
});

requestAnimationFrame

There's this timer function called requestAnimationFrame that is better than setTimeout and setInterval. It's more optimized for animations, aiming 60fps when possible. But it's prefixed in other browsers, check for compatibility first.

(function gameLoop() {
    window.requestAnimationFrame(gameLoop);
    drawScreen();
    // All other loop functions here
}());

Common gotchas in JS

Never forget semi-colons, even when JS allows you to forget them.
Remember using var when declaring variables. Unless you have them in some upper scope, if you forget them, they automatically become globals - and that's bad practice.

Conclusion

There was little to go by, but here's what I got

function canvasApp() {
    var radius = 100;
    var circle = {
        centerX: 250,
        centerY: 250,
        radius: 30,
        angle: 0
    }
    var ball = {
        x: 0,
        y: 0,
        speed: .1
    };

    var theCanvas = document.getElementById('canvasOne');
    var context = theCanvas.getContext('2d');

    function drawScreen() {

        context.fillStyle = '#EEEEEE';
        context.fillRect(0, 0, theCanvas.width, theCanvas.height);

        //Box
        context.strokeStyle = '#000000';
        context.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height - 2);

        ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
        ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;

        circle.angle += ball.speed;

        context.fillStyle = "#000000";
        context.beginPath();
        context.arc(ball.x, ball.y, 15, 0, Math.PI * 2, true);
        context.closePath();
        context.fill();
    }

    (function gameLoop() {
        window.requestAnimationFrame(gameLoop);
        drawScreen();
        // All other loop functions here
    }());
}

window.addEventListener('load', function () {
    canvasApp();
});


What struck me most are these lines:

p.Name.ToUpper() != name.ToUpper()

I find it's always better to use the Equals overload that accepts a StringComparer and set it as a readonly field for the entire class rather then hoping you don't forget ToUpper everywhere.

This is a minor thing but I find that Excerpt should be called Without because it does not actually create an excerpt where you can say what you want to have but rather the other way around. The parameter says what should be excluded from the string. I also think it should take a params string[] argument.

new Regex(regex ?? throw new ArgumentNullException(nameof(regex)))

I find newing a Regex should be reserved for initializing a field. In a situation like here the static Regex.Matches would be more suitable - unless there is a reason why you chose new over the static method.

public string ToString(string format) =>

This one I don't like. It's not a standard .net practice. If you want to use a formattable ToString then the class should implement the IFormattable interface correctly... or you should make this one private.

Besides having this helper method to just do

ToString("{0}={1};")

is a little bit overengineered. How many of such formats do you have? A single ToString() would do too.

ConnectionParameter should be ConnectionStringField (or Property) to clearly communicate it belongs to a connection string.

I'm not sure if you know that there is already a SqlConnectionStringBuider and most providers have their own implementations.

I prefer to write extensions against this type rather than parsing everything myself. It also validates the keys you use so you cannot use anything that isn't supported... well, unless it was your intention and a reason for the custom builder.


Ideally, you'd profile it on a line-based manner, seeing where the cost is.

But, I might have some suggestions.

The following if-statement gets run every time the function is called:

    if tree == None:
        tree = self.tree #tree is the Ast

In most cases, it would miss, so maybe separate the rest of the code out to another function? (Also, try tree is None instead of tree == None first).

Now, the following line can also be optimised:

        g = not type(i) is Tree.FuncStart and not type(i) is Tree.FuncBraceOpen and not type(i) is Tree.FuncBody and isGlobal
        #for code that is not inside a function, it must be put somewhere else, g is a boolean for checking if outside a function

I think it might as well be written

        g = isGlobal and type(i) not in (Tree.FuncStart, Tree.FuncBraceOpen, Tree.FuncBody)

The reason for this re-arrangement is the following: checking isGlobal is a simple boolean check: really fast. Also, computing type(i) is a function call. Not that expensive, but not cheap either. Better to do that just once. On the other hand, looking up Tree.* is also expensive. There are tricks to make that cheaper as well. I'll get back to that.

        if g:
            if i.isEnd(): #is the end node
                self.main += i.compile(self)
            else:
                self.toLLVMHelp(i, g) #recurse for further nodes
                self.main += i.compile(self) #compile turns the node into 'llvm-ir'
        else:
            if i.isEnd():
                self.out += i.compile(self)
            else:
                self.toLLVMHelp(i, g)
                self.out += i.compile(self)

Not sure if the following will be faster, but I'd like to hope so. That is: profile! I see that in the nested if/else, they share code.

if g:
    if not i.isEnd():
        self.main += self.toLLVMHelp(i, g)
    self.main += i.compile(self)
else:
    if not i.isEnd():
        self.out += self.toLLVMHelp(i, g)
    self.out += i.compile(self)

Again: profile! But I think it will either make it faster, or not be slower, so you should be good. Adding to self.main or self.out is done, but I don't see any nice way to make that better without losing performance.

After thinking about it some more, I see you doing string-appends. Depending on the situation, this can be very expensive, as it must do a full copy.

Maybe replace that logic with

self.main_parts.append(self.toLLVMHelp(i, g))
self.main_parts.append(i.compile(self))

and in the end, replace

self.main

with

''.join(self.main_parts)


Will this code get cleaned up by the garbage collector?

This code looks mostly fine to me, when the .move method gets called, .once gets moved to .old and then when .clean happens, .old gets deleted (and eventually garbage collected unless a reference to it continues to exist somewhere else).

However I think you could do better by encapsulating each route in a function that takes care of .move and .clean for you.

Something like:

route(function () {
    App.once.users = new Users();

    App.once.users.fetch({
        success: function () {
            App.once.userView = new UserView({
                collection: App.once.users
            });
            $('body').append(App.once.userView.el);
        }
    });
});

where route is:

function route(fn) {
    App.move();
    fn();
    App.clean();
}

(but you probably already have a method like this in your code where these things would belong)

A better question: Why do you need this .once property anyway? It looks like it is just holding private data for the route. Why not make it private to the route then?

route(function () {
    var users = new Users();

    users.fetch({
        success: function () {
            $('body').append(new UserView({ collection: users }).el);
        }
    });
});

Garbage collection in JavaScript

(very simplified basic design ignoring tricks/special cases)

Every variable in javascript can be thought of as a reference to an underlying system object.

That is, in JS you have:

var a, b;

to the system there is:

var all = [ {data: a, declaredScope: function()}, {data: b, declaredScope: function()}];
var scope = function();

When the garbage collector runs, it does something like this:

function markDescend(variable) {
    for (var child in variable) { //the system has the child as seen in the "all" array
        if (child !== undefined && child !== null && !child.marked) {
            child.marked = true;
            markDescend(child);
        }
    }
}
var tempscope = scope;
var tempall = all;
do {
    for (var variable in tempall) {
        if(tempscope === variable.declaredScope) {
            variable.marked = true;
            markDescend(variable);
        }
    }
    tempscope = tempscope.outer;
} while (tempscope);

all = [];
for (var variable in tempall) {
    if(variable.marked) {
        variable.marked = false;
        all.push(variable);
    } else {
        __free(variable);
    }
}

That is to say, when the garbage collector runs, all variables reachable from the current scope (and closure scopes) are marked; then a second loop runs and all variables not marked are freed from memory.

Thus, if there is no way for the system to reach an object via scope then it is going to be collected. From a user perspective, there are a few ways to create objects that the user can not reach, but are still in scope. Some examples:

window.setTimeout(function () {}, x) - this function is reachable from global scope until it finishes running; and it has access to any variables from any of its closure scopes (even though you may not be able to reach it)
$.ajax('asdg', function () {}) - same as setTimeout
Any attached DOM node is reachable from the global scope. You may attach events to these nodes and if you don't maintain the reference, you would lose access to it.

In these cases, you would need to do more than what you are currently doing in your .move method to take care of unregistering these functions (In IE7 and below).  My perspective would be just to let it leak (tell the users to get a better browser). IE6 would leak until the browser is closed, IE7 would leak until the page is out of the navigation cache. In every other browser, once the DOM is detached (or the timeout occurs, or the ajax post happens, etc.) these functions are not reachable from the global scope anymore (and so they are removed in the next garbage collection cycle).

Cleanup in IE

Essentially what you are doing in .move is move the stuff you want to delete in the previous route to .old and then in .clean you take care of deleting the old references.

Really the only things you should care about are those properties that you cannot actually get at via variable properties once set. Whenever you do a window.setTimeout() (or similar) you would want to do something like this:

function setTimeout(fn, msec, App) {
    var id = window.setTimeout(function () {
            fn();
            destructor.removeReference = null;
        }, msec),
        destructor = {
            removeReference: function () { window.clearTimeout(id); }
        };
    App.once.push(destructor);
}

function setInterval(fn, msec, App) {
    var id = window.setInterval(fn, msec);
    App.once.push({
        removeReference: function () { window.clearInterval(id); }
    });
}

and so on for attaching events, setting DOM properties, making ajax requests, etc. Then in .clean you would check if the object in .old has a removeReference function; if so run it then delete it and the object.


Getting the lengths of each word in its String parameter

//only allowed to use length and charAt from string class
public static ArrayList<Integer> getWordLengths( String s )
{
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            list.add(count);
            count = 0;
        }
        else
        {
            count++;
        }
    }
    return list;
}

Output:

[4, 2, 6, 4]

As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine.  Just because you need to count more than one thing doesn't mean you need more than one loop.


String converting and parsing a few rows of a .csv file

for i := 0; i < len(record[i]); i++ {

... I don't think that does what you intended. It seems like just luck from how the data is that it works, or did I miss something? :-) I think you can just take the for {} loop out altogether.

I'd move the ParseFloat() calls up to where you assign the record[] values to named variables. Be sure to check the err return from both calls.

Your idea of using a struct is also good.

type SomeRecord struct {
    Num  int
    Name string
    Eia  float
    // etc
}

The for moving some of the code to a function: Have the function take a SomeRecord as a parameter and do the output.

I don't know if using a template is necessary for such a short string, but if you want to then outside of the loop read the template file with text/template, specifically template.ParseFiles and then execute the template when appropriate with the record data or a new data structure if it needs data not in the record. If this is all the program does it might make most sense to have the SomeRecord struct have the data that the template needs (so include IncDiff).


Calculate the total items used, if for every x items used, you get one additional item to use

I managed to create another algorithm that produces the same results, this algorithm iteration seems to be more efficient so it will perform better.

Consider startingTotalItems as x and newItemInterval as y.

Using while loop:

public static int TotalItems(int x, int y)
{
    int sum = 0;
    while (x >= y)
    {
        int remainder = x % y;
        int quotient = x / y;
        sum += (x - remainder);
        x = remainder +  quotient;
    }
    return sum + x;
}

Using recursive method:

public static int TotalItems(int x, int y)
{
    if(x < y)
    {
        return x;
    }
    int remainder = x % y;
    int quotient = x / y;
    return x - remainder + TotalItems(remainder +  quotient, y);
}

How does it work?
Let's assume that x is the amount of items we are holding now.
For every x bigger than or equal to y we will add to the sum x without the remainder of x divided by y, let's consider that these are the items we've used during this turn.
Now we still have the remainder that we haven't used yet but we need to remember the we've got more items while using the previous items, the amount of items we've got is the quotient of x divided by y, so now x should be the quotient plus the remainder.
We will repeat this procedure until x is less than y in this case we know that we will not get any more items so all we have left to do is to add x to the sum, break the procedure and return the result.


Finding an equilibrium index in an int array

I think my whole solution is \$O(N)\$ because both my methods are O(N). Is that right?

Correct. Both of your methods are \$O(N)\$: they are linear in terms of the number of elements in the input array. More specifically, both generateSums and getEquilibrium loop over the array once.

  I believe I used some space to generate the sums and it Is still \$O(N)\$. Is it right?

Also correct. The intermediate array containing the sum contains as many elements as there was in the input array; doubling the input array in size would double the size of the intermediate array. This makes in linear in terms of space complexity.

The method generateSums doesn't have a good name. Its purpose is to calculate the cumulative sum of the input array, going from the right to the left. Consider naming it cumulativeSums instead. The rest of the algorithm is correct. You won't be able to make this faster than \$O(N)\$, in terms of time complexity.

A small comment: instead of using a break explicitly inside the for loop, consider returning directly the found index. You currenly have:

int res = -1;
for (int i = 0; i < A.length; i++) {
    if (lowSum == sums[i+1]) {
        res = i;
        break;
    }
    lowSum += A[i];
}
return res;

but it would be shorter to have:

for (int i = 0; i < A.length; i++) {
    if (lowSum == sums[i+1]) {
        return i;
    }
    lowSum += A[i];
}
return -1;

It avoids the use of a temporary local variable holding the result, and makes it clearer that -1 is the default value returned.

In terms of space complexity however, you can do better: this is possible in \$O(1)\$. Instead of generating an array containing the cumulative sums of the array, just calculate the total sum, let's call it right sum. Then, you keep a running sum of the array by traversing it from left to right, decreasing this right sum as you go: if the running sum is equal to the right sum, you found an equilibrium.

public int getEquilibrium(int[] array) {
    long totalSum = sum(array);
    long lowSum = 0L;
    for (int i = 0; i < array.length; i++) {
        totalSum -= array[i];
        if (lowSum == totalSum) {
            return i;
        }
        lowSum += array[i];
    }
    return -1;
}

public long sum(int[] array) {
    return Arrays.stream(array).asLongStream().sum();
}


Monkeypatching __builtin__ in tests for mocking

I'm assuming you're fine with assert, generally I'd recommend using
the unittest
library.

Now for the monkey patching the other choice you have is to restructure
how the credentials are loaded.  At the moment the credentials are
loaded every time a request is performed - instead of that the
credentials could be loaded once, for the whole module as globals,
before invoking any other functionality.  Yes, globals are bad, but
unless you have another layer of indirection it'd be okay for this
purpose.

Done that way, you'd call e.g. ghdwn.load_credentials(), then issue
the call, then ghdwn.drop_credentials() and repeat.

If you stay with the current approach, I'd only move the patch method
out of the test into a proper function, as it's quite reusable, and give
it a better name maybe.

I'm not quite sure if there are other ways to open a file in Python,
regarding your concern whether you're actually testing the right thing;
it might also make sense to test two separate things: the function to
load credentials (from a custom path, so you can load from "/tmp/...")
and calling that function.  Then you wouldn't mock Python standard
functions, but instead only the credential loader, while you'd test the
loading of credentials with an actual test file.


There are many things to discuss about your code and I have two options to do do that:

Redesign your program by applying a suitable design pattern.
Obey to my legendary laziness and point out only the minimum things you should care about.

For some considerations, I chose the second option. So here are some random notes you should ponder about:

Do not confuse me

Before diving in any details, I see a bunch of functions and a class. That was the first thing that attracts my attention. This is confusing  because it does not let the maintainer of your code to understand the ideology of your program and whether you belong to the OOP or procedural sects.

Opting only for one of those programming types will help to understand the flow logic of your program. This will also reflect you are not versatile but self-confident and a good decision maker.

As developers, we need to take a set of decision before coding anything. This is a big chance for us to train ourselves to take the right decisions. And the decision regarding which programming type to adopt for your program is not that difficult. Your program needs to comply to an OOP approach because:

You are designing a GUI, so do not forget that the leaves of history inform us that object-oriented concept is the legitimate child of the simulation and graphical design.
Python is FCF programming language. So be pythonic by adopting OOP since even functions are objects in this language.

We do not need to be more gossip because this is already convincing on why
you should write those functions in a proper class instead.

You can be monadic

Let me pick this function, for instance:

button(source,text,command=None,row=0,column=0,rowspan=None,columnspan=None)

Parameters are heretics that must be used parsimoniously because they are a different level of abstraction. The ideal is, when possible, to use monadic functions; and in your situation this is possible because row, column, columnspan and rowspan are already options of the grid() geometry manager, so it is useless1 to inject them as parameters to the enclosing functions. For the command and bg parameters,you also can inject them directly as an option to the widgets you need to use it for (tkinter.Button() in this function)

Container's type as a name: bad!

You used function names such as button() and label() while you already have widget types which names are Button() and Label(). Do not use the container's type as a name for your functions. This is a source of confusion as stated by Robert C. Martin in his book Clean code.

Function names must divulge the function's purpose:

What about this function name you used: iQuiz()? You should rename this function to be informative in that if Donald Trump reads the name of that function he can instantly understand its purpose.

Choose the right names for variables

Your program is small, so maybe I can be enough smart and patient to guess, but also remember, why these variables are useful for: opt1, opt2, opt3, opt4. As your program grows, these variables will make your source code unclear and thus difficult to maintain. Also, if I am a mathematician, I may tend to understand that opt stands for optimum or anything else you do not think.

Code a lighter initializer

You are doing too much things in the initializer __init__(). Initialize only the necessary things and delegate everything else to other functions.

init() takes a useless argument

The string argument you provide to init() is a bad decision. A good practice is to use as less parameters as possible. Plus, you can simply set the title of your GUI in a separate configuration function like this one:

def configure_gui(self):
    self.window_height = 500
    self.window_width = 1000
    self.background_color = 'powder blue'
    self.master.title('Quiz')
    self.master.option_add('*Font','aerial 12')
    self.master.config(width=self.window_width, height=self.window_height)

and use this configuration function within __init__():

def __init(self, master):
   self.master = master
   self.configure_gui()

Improve readability

Put spaces between the the coma and the option in all similar situations to this one:

storeObj.grid(row=row,column=column,rowspan=rowspan,columnspan=columnspan)

Put space also for your variables. I mean you have many situation like this one: pre=button(frame_pre,'Previous') which should be written: pre = button(frame_pre,'Previous')

Remove unpractical graphical choices

You set the font weight to bold and font seize to 20: that is too much. This will lead to an ugly text, and you punish yourself if one of the answers or questions contains a half dozen or more of words.

1. But also may be harmful for the scalability of your program.


Algorithmic complexity of this algorithm to find all ordered permutations of length X

def generate_permutations(symbols, permutations_length):

These are not permutations. They are Cartesian products. In addition, calling the function generate_something suggests that what's returned might be a generator, which is probably what you want for a function which returns a stupendously large data structure, but is not what you get from this function.

    for symbol in symbols:
        for tail in tails:
            permutation = [symbol] + tail

            permutations.append(permutation)

If you use extend instead of append then you give better hints as to how much underlying buffers might need to be increased:

    for tail in tails:
        result.extend([symbol] + tail for symbol in symbols)

Performance: with an alphabet of size \$L\$ let \$T_L(X)\$ be the cost of calling this function for products of length \$X\$. Then \$T_L(1) = L\$ and \$T_L(X+1) = T_L(X) + L L^X (X+2)\$ assuming that constructing the list [symbol] + tail takes time proportional to its length and extending the list of results take amortised constant time per element added. This gives \$\Theta(L^{X}X)\$ complexity.

The same complexity but much better memory efficiency can be achieved with a true generator approach which is based on the fact that all you really need to do is count to \$L^X\$ and convert into base \$L\$.


K-nearest neighbours in C# for large number of dimensions

var distances = new double[trainNumber][];
for (var i = 0; i < trainNumber; i++)
{
   distances[i] = new double[2]; // Will store both distance and index in here
}

This is a code smell. You shouldn't use a jagged double array to store an array of distances and indexes. Despite the comment, what you're doing is unclear, and it's very confusing to have a variable named distances that stores both distances and indexes. The only justification for this would be if you actually had hard profiling evidence that it caused a significant speedup.

Make a separate class (or struct, if you're worried about overhead) with members double distance; int index; and then trainInfo (the former distances) should just be a trainNumber-sized array of that type.

Also, since you only need the top K elements, you don't need to sort the whole list (n log n time). You ought to be able to do it with a partial sort (actual code sample) which is almost linear-speed. There are also parallel algorithms for this; you could probably get a speedup using PLINQ with a custom aggregate.

On to the next refactoring.

foreach (var voter in votingDistances)
{
    if (trainClasses[(int)voter[1]] == 1)
       yea++;
    else
       nay++;
}

This code is also crying out for LINQ. How about

yea = votingDistances.AsParallel().Count(voter=>trainClasses[voter.index] == 1);
nay = votingDistances.Count - yea;

And I'd refactor this:

for (var i = 0; i < sample1.Count; i++)
{
    var temp = sample1[i] - sample2[i];
    distance += temp * temp;
}

to this:

var differences = sample1.AsParallel().Zip(sample2,(s1,s2)=>s1-s2);
distance = differences.Sum(x=>x*x);

though you could get improved performance from a custom aggregate.


Simple read/write lock implementation without starvation

You'd need _shared_mutex and _is_blocked to flip together 'atomically' in order for this code to work, no?
Imaging one thread in lock() just flipped _unique_mutex and before it flips _is_blocked, another thread in lock_shared() is testing _is_blocked.


Scanning directories and caching paths to an array

I have to ask why you would want to find a file anywhere on the filesystem. That seems like a pretty odd requirement. Most apps (take node module loading for example) check a limited number of folders which can be done very quickly.

To answer your questions:

the OS does not do this kind of caching.
No, I wouldn't consider this safe. For two reasons. There are many other names that could match. For example video_file_1.txt, file_1.txt.old or some_path/file_1.txt/cat.jpg.  I would check against the basename something like

function basename(path) {
   return path.match(/[^\\\/]+$/)[0];
}
const matches = cache.filter(element => basename(element) == filename)

Someone already answered this in the comments. It is really just an artifact of attempting to handle windows and unix paths consistently.

Also if retrieval efficiency is important then I would store the data as a hash not an array, i.e:

let cache = {};

let paths = walkdir(searchDir, options, (path) => {
  const name = basename(path);
  if (!cache[basename])
    cache[basename] = [];
  cache[basename].push(path)
});

Then finding an element is a simple matter of:

findItem (cache) {
  let filename = 'file_1.txt';
  const matches = cache[filename];
  console.log(matches);
}

Note that, since you are on Windows, you should also consider case-insensitivity of filenames.


Miller-Rabin Prime test (Speed is the main goal)

You could use the Sieve of Eratosthenes for numbers less than 10 million (you are only going up to 100 million).

I think that  checking the low bit (num & 1) == 0 is quicker than checking the remainder num % 2 == 0.  Similarly, bit shifting is quicker for division or multiplication by 2: d /= 2 could be d >> 1.

You might experiment with doing an initial check for division by a few low primes (3, 5, 7, 11) in your IsPrime method and see if that makes a difference.

Finally, for your "random" numbers, you might want to choose products of primes, e.g. 3*5*7*11*13..., or maybe that plus 1.  Maybe that's crazy.  But some "random" numbers might provide richer test cases than others, and cause a faster elimination of non-primes.


Calling different class objects using python

I think you've over-engineered the code a bit. If I were to write this code I wouldn't have used a class at all. Looking at what your code does I understand that:

you have multiple proxies files
you randomly choose one of them and perform whatever actions based on that

Why not just doing something along the following lines:
import random
import time

from proxymanager import ProxyManager

PROXY_FILES = (
    './test.txt',
    './test2.txt',
    './test3.txt',
    './test4.txt',
)
DELAY = 10

def get_random_proxy():
    """
    Return a random proxy dict from a random file.
    """
    random_file = random.choice(PROXY_FILES)
    return ProxyManager(random_file).random_proxy().get_dict()

def main():
    while True:
        proxy = get_random_proxy()
        print(f'Do something with {proxy["http"]}\n')
        time.sleep(DELAY)

if __name__ == '__main__':
    main()

This approach will save you a lot of development time since you:

won't have to add a new method to your ProxyServer each time you have a new proxy file.
won't have to keep track of random_list (which is not quite random since it has to match the attributes of the class)
you won't need a Testing() class anymore

Notice that with this version is really easy to figure out what you're doing.
Recommendations (PEP8):

use appropriate naming for your variables (snake_case naming convention for methods/functions, UPPER_CASE naming convention for constants);
use docstrings to help your readers understand the code;

If you're really tied to use classes, I'd mix your solution with mine and do something along these lines:
import random
import time

import requests

from proxymanager import ProxyManager

PROXY_FILES = (
    './test.txt',
    './test2.txt',
    './test3.txt',
    './test4.txt',
)
DELAY = 10

class ProxyServer:
    def __init__(self, random_proxy_file):
        self.proxy_manager = ProxyManager(random_proxy_file)

    def get_proxy(self):
        """
        Return a random proxy dict.
        """
        return self.proxy_manager.random_proxy().get_dict()

class Scrapper:
    def __init__(self, base_url):
        self.base_url = base_url

    @staticmethod
    def _get_random_proxy():
        random_proxy_file = random.choice(PROXY_FILES)
        return ProxyServer(random_proxy_file).get_proxy()

    def get_url_data(self):
        proxy = self._get_random_proxy()
        data = requests.get(self.base_url, proxies={'http': proxy['http']})
        return data

    def do_something_with_data(self, data):
        return data

def main():
    scrapper = Scrapper('http://scrapeme.not/')

    while True:
        data = scrapper.get_url_data()
        scrapper.do_something_with_data(data)
        time.sleep(DELAY)

if __name__ == '__main__':
    main()

But notice how this has become a lot more complex than it should've been. Some advantages that this has over your solution:

it uses better naming;
it avoids creating multiple ProxyManager() instances;
it avoids mapping the getattr() to a value from a list you'd have to maintain all the time as complexity of the scrapper increases;

And to answer your question: no, it's not wrong to use getattr() like that but in this specific case I don't think it's necessary due to the above listed reasons.


First of all, lets clean up your code to really leverage the power of .on():

$(function() {
    var touched = false,
        previous_touched;

    function updatePreviousTouched(e){
        if(typeof previous_touched !== 'undefined' && previous_touched !== null && !previous_touched.is($(e.target))){
            previous_touched.data('clicked_once', false);
        }

        previous_touched = $(e.target);
    }

    $(".nav").on({
        touchstart:function(e) {
            touched=true;
        },
        click:function(e);
            var $this = $(this);

            updatePreviousTouched(e);

            if(touched) {
                if ($this.data('clicked_once')) {
                    $this.data('clicked_once', false);
                    return true;
                } else {
                    e.preventDefault();
                    $this.trigger("mouseenter").data('clicked_once', true);
                }
            }

            touched = false;
        }
    },'li .has_children');

    $("html").on({
        mousemove:function(e){
            touched=false;
        },
        click:updatePreviousTouched
    });
});

Notice the following:

Object use of .on() rather than mere string use (only one binding instead of multiple)
caching where appropriate
variables and functions declared at top

Now that we've got your original code all pretty and efficient, I'll offer a different alternative that should be much more lightweight.

Based on your currently use CSS to do the :hover piece. Instead, you may consider making that CSS a class, and then dynamically add / remove the class in the code. This maintains the speedy leveraging of CSS while avoiding dealing with the CSS and JS events fighting each other over what wins out. I have done something like this on a number of projects and it seems to work pretty well. The key is the custom event; by separating this out, you can control when it is fired rather than rely on some crazy if logic to determine whether it should be fired or not.

Here is a working example:

This CSS that was this...

.header-nav-menu ul li:hover > ul { display: inline-block; }

Becomes this...

.header-nav-menu ul li > ul.MenuActive { display: inline-block; }

And here is your working jQuery...

$(function(){
    var menuActive = false,
        touched = false,
        $nav = $('.nav');

    function removeActive(callback){
        $nav.find('.MenuActive').removeClass('MenuActive');
        callback();
    }

    function newActive($this,menu){
        removeActive(function(){
            $this.next().addClass('MenuActive').queue(function(){
                if(menu){
                    menuActive = true;
                    touched = false;
                } else {
                    touched = true;
                }
            }).dequeue();
        });
    }

    $nav.on({
        touchstart:function(e){
            e.stopPropagation();
            newActive($(this),touched);
        },
        mouseenter:function(){
            newActive($(this),true);
        },
        click:function(e){
            e.preventDefault();

            if(menuActive){
                $(this).trigger('trueClick',e.target);
            }
        },
        trueClick:function(e,$target){
            $(this).parents('.nav').trigger('mouseleave');
            window.location.href = $target;
        }
    },'li .has_children').on('mouseleave',function(){
        removeActive(function(){
            menuActive = false;
            touched = false;
        });
    });

    $('html').on('touchstart',function(e){
        if(menuActive){
            $nav.trigger('mouseleave');
        }
    });
});

This should manage what you want in a much cleaner way:

menuActive variable defaults to false, and is only set to true when submenu is open (by either touchstart or mouseenter)
actual click action is prevented, and verification is done to determine if menu is appropriately active
if menu is active, custom event is triggered to go to the link's target
touch event is not bubble up to html by use of e.stopPropagation();
if user touches somewhere on the screen that is not the submenu, it will close the submenu and set menuActive to false

I separated out a couple of actions into reusable functions, and separated events to avoid if checking. This code executes much faster than the original, and more importantly it is bulletproof. There is true separation of touch vs hover events, the show / hide of the menu still leverages CSS, and it accounts for browser inconsistencies (example:  the reason for the use of the callback is because Safari 5.1 has a 300ms delay between adding a class and it displaying onscreen).

I know this code is longer than the original, but guaranteed it will run faster and be easier to maintain. Hope it helps.


Efficient way to sort Matrix elements into separate bins in Python

Here are some alternative clustering (binning) methods.

I assumed that the line mini = min(float(s) for s in diff) and the following code was indented incorrectly. If the indent was correct then that is your problem.  If not, here are three implementations that might speed up the work:

Method #1:

Here is an implementation of the original code with redundancies removed and a comprehension for the inner loop:

def method1():
    K = [[A[0, 0]]]
    for element in A.flatten():
        min_diff = min((abs(element - l[0]), i) for i, l in enumerate(K))
        if min_diff[0] < Theta:
            K[min_diff[1]].append(element)
        else:
            K.append([element])

Method #2:

This is bit more complex, in that it keeps a sorted list of the first elements, and for each element first does an efficient lookup to find the two closest first elements, and then performs the distance/Theta calc against only the two closest.

import bisect
def method2():
    global A
    A = np.random.random(A.shape)
    data_iter = iter(A.flatten())
    K = [[next(data_iter)]]
    first_elements = [K[0][0]]
    for element in data_iter:
        x = bisect.bisect_left(first_elements, element)
        if x == 0:
            # below lowest value
            min_diff = abs(element - first_elements[0]), x
        elif x == len(first_elements):
            # above highest value
            min_diff = abs(element - first_elements[-1]), x-1
        else:
            min_diff = min((abs(element - l[0]), i)
                           for i, l in enumerate(K[x-1:x+1]))
        if min_diff[0] < Theta:
            K[min_diff[1]].append(element)
        else:
            first_elements.insert(x, element)
            K.insert(x, [element])

Method #3:

I was not quite sure why you are using the first element found outside of the range of theta to define the grouping center, so I tried a small experiment.  This sorts the data, and then builds clusters that are built around 90% of theta above the minimum value in each cluster.  So the results will not match the other methods, but it is quite a bit faster.

def method3():
    global A
    A = np.random.random(A.shape)
    K = []
    target = -1E39
    for element in np.sort(A.flatten()):
        if element - target > Theta:
            target = element + Theta * 0.9
            K.append([])
        K[-1].append(element)

Timing Test Code:

import numpy as np
A = np.random.random((100, 100))

# Threshold value
Theta = 0.03

from timeit import timeit

def runit(stmt):
    print("%s: %.3f" % (
        stmt, timeit(stmt + '()', number=10,
                     setup='from __main__ import ' + stmt)))

runit('method0')
runit('method1')
runit('method2')
runit('method3')

Run Times

4 Methods:

0. Original
1. Original recast to more Pythonic
2. Use a search to minimize the number of comparisons
3. Sort the values, and then cluster

For the run times, I had to decrease Theta.  With the original theta there are only very small number of clusters with the data given.  If the number of clusters is small method #2 is not a lot faster.  But as the number of clusters goes up method #2 will get much faster than methods #0 and #1.  Method #3 (the sort) is fastest by far.

method0: 5.641
method1: 4.430
method2: 0.836
method3: 0.057

(Seconds, small numbers are better)


Basic ul li elements in JavaScript listeners

Don't Modify Array.prototype

Writing custom functions to built in prototypes is generally a bad idea. The basic reasoning behind this is that it is a bad practice to modify something you don't own, but check out this Stack Overflow Question for more info.

Instead of changing the prototype you could just write a global function:

function pushIfDoesntExist(array, item) {
  if (array.indexOf(item) === -1) {
    array.push(item);
    return true;
  }
  return false;
}

Weigh Out Pros and Cons before Abstracting

The function pushIfDoesNotExist is well named, so it can act as a comment for what the code is doing. Also, I can think of several of cases where it could be useful. BUT is it really worth writing a function for it? After all, you wouldn't write a function add1:

function add1(number) {
  return number + 1;
}

And that's a well named function with even more applications than pushIfDoesNotExist. What I'm trying to get at here is that abstracting a part of code is not always a good idea. There are some downsides to making a function for something:

The function delocalizes code. Someone who is reading through your code to better understand it needs to hunt down where pushIfDoesNotExist is defined to see how it works. (good documentation can help with this)
It adds a dependency. Functions that call pushIfDoesNotExist rely on pushIfDoesNotExist being defined properly. (unit tests can help with this)
It takes time to write/debug/unit-test/document/maintain/think-about pushIfDoesnNotExist.

Is the value added by the function pushIfDoesntExist really worth the cost? (especially since you only call it once)

Inline Module Constructor

If you want private member variables, or you don't like using this or self you can use an inline function to construct your Testing object.

var Testing = (function () {
  var clickedList = []; //hidden inside inline function scope

  function applyListeners() {
    document.getElementsByTagName("li").forEach(function (node) {
      if (clickedList.indexOf(elem.textContent) === -1) {
        clickecList.push(node.textContent);
        displayData();
      }
    });
  }

  function displayData() {
    document.getElementById("clickedElements").textContent = clickedList.join(", ");
  }

  return {
    applyListeners: applyListeners // public
  };
})();


@Deduplicator said almost everything, I will only add that it's really important that you know algorithms and data structures from the STL and using the proper in each case.
Here, you do so much work for nothing:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <map>

int main() {
    auto in = std::istream_iterator<std::string>{std::cin};
    auto out = std::map<std::string, int>{};

    std::for_each(in, {}, [&out](const std::string& w) { out[w]++; });
    for (auto& w : out) { std::cout << w.first << ' ' << w.second << '\n'; }
}


Bitmask type to perform binary operations

It looks like you are misusing an enum as just a more cumbersome way to write a ulong.

If the days of the week are meant to be treated as a set rather than a single value (i.e., more like checkboxes than radio buttons), then you should be using the [Flags] attribute.  In fact, this is almost exactly the example given in the MSDN documentation:

[Flags]
enum Days2
{
    None = 0x0,
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40
}

class MyClass
{
    Days2 meetingDays = Days2.Tuesday | Days2.Thursday;
}

Personally, I'd write the constants using left-shift operators:

[Flags]
enum Days2
{
    None = 0,
    Sunday = 1 << 0,
    Monday = 1 << 1,
    Tuesday = 1 << 2,
    Wednesday = 1 << 3,
    Thursday = 1 << 4,
    Friday = 1 << 5,
    Saturday = 1 << 6
}


Game of Rock paper and scissors against a random bot

Welcome to Code review. I want to start out by highlighting a few things that I like about this code.

One thing that I quite liked is handling the tie case first. It is often good to simplify logic as much as possible, and the tie case is a good spot of somewhere that you can simplify, rather than have three more elif lines.

It is also good to see handling of erroneous input from the user. This includes making minor corrections when it is clear what was intended: using the .lower() function to ensure that "Rock" and "rock" work the same. It also includes making clear to the user if they entered something from which you can't guess what they meant. In many ways the mark of a good programmer is how well they handle the unexpected.

There is a minor bug in that though: because the '-1' is after the else it will first complain that the input is invalid, and only then realise that it's the exit signal. (There is another minor bug in that it won't actually call exit() because it needs indenting in to the if, but I think that is probably just a copy paste error to codereview.)

Mast suggested in the comments that you really want to be using functions to help make the code less redundant. In general when you find yourself repeating things it is a good opportunity to think about using a function. For example before your while loop, have this function:

def print_win(bot, user_choice):
    print("You win! I chose",bot," and you chose", user_choice , ", ", user_choice, " beats ", bot, "!")

Then when you win, you can just use

print_win(bot, user_choice)

That way if you ever had to change the message (perhaps, say, to translate the program into another language) you could change all the win messages in one place.

You could also structure the program so that you separate out user input from the actual game, which also makes it easier to improve the game bit. If, for example, you had a function that tells you who won, then it would be easy to track a score over multiple rounds. With your set up, you'd have to update the score separately with every one of those ifs or elifs.


How can I store the fibonacci sequence in a vector during each recursive call?

Its normal to put parameter names even in the declarations:

void getUserNum(int &);

We use this to help us identify what the function is doing.

In C++ the '*' and the '&' are part of the type information. So it is usual to push these left towards the type rather than the name. Note this is basically the opposite of C conventions. But C++ is much more rigorous on types and safety than C.

void dispSeq(std::vector<int> &vRef);

// Normally in C++ code I would expect this:
void dispSeq(std::vector<int>& vRef);

Be careful with your use of out parameters.

void getUserNum(int &refVal)

It seems more natural to return a value from a function then get sombody inside to set an external value via a reference (not unheard of and it will depend a lot on the context). But in this situation I would return a value. It will then make using the code eaiser.

 int userNum   = getUserNum();

Error Checking (especially input from a human) needs to be more rigorous.

void getUserNum(int &refVal)
{
    std::cout << "Enter a positive integer:\n";
    std::cin >> refVal;
}

If a user enters a non positive value things will go bad. If the user inputs a string the value of refVal I believe is left unaltered (which leaves your code with an uninitialized variable).

int getUserNum()
{
    int result;

    // user input is done by the line.
    // so read a line at a time and validate it.
    std::string  line;
    std::getline(std::cin, line);

    std::stringstream  linestream(line);

    int result;
    if (linestream >> result)
    {
         // The read worked.
         // Lets check the user did not type ofther crap on the line.
         //
         char x;
         if (!(linestream >> x))
         {
               // Reading more data worked. This means the input was good.
               // As the user typed a number followed by some other stuff
               // like  56.4   (the .4 is illegal)
               //       5Plop  (the Plop is illegal)
               //
               // The the above would have successfully read a value into
               // `x` this with the ! it would have failded and this
               // this condition would not have been entered.

               // We only return if:
               //    1. We read an integer.
               //    2. There is no other data on the line except white space.
               return result;
         }
    }
    // invalid input
    std::cout << "Stupid user input aborting\n";
    exit(1); // Reading failed.
             // Leave as an exercise on how to repeat the question.
             // You can also compress that very verbose if statement into a single
             // line without it looking too bad.
}

// Single line if
if ((linestream >> result) && !(linestream >> x))
{   return result;
}

In Fib() you should probably not use recursion. Prefer a while loop. Loop from 0 upto the point you want to reach. This makes using a vector easy. You can also start from where you left off last time rather than 0.

int fib(int n)
{
     static std::vector<int>   values = {1,1};
     if (n < values.size()-1) }return values[n];

     int start = values.size();
     for(int loop = start; loop < n; ++loop)
     {
          values[loop] = values[loop-2] + values[loop-1];
     }
     return values[n];
}


I think this is a very clean looking code base, so congrats getting that down. I also think that the the way you implemented the pattern worked out very well.

I don't have much to say, it's mostly just formatting.

Throughout, you insist on keeping block sections condensed to one line. It's perfectly okay to add the brackets and break apart the code into multiple lines.
In attach(), you return the current object. I don't see why you're doing so as in the example you didn't utilize this feature. Don't write code that's not in use yet!
You might consider moving strtolower(trim($event)) to a function with the appropriate parameters. Don't repeat yourself.
Why is !isset($this->events[$event]) returning false. I would expect an exception to be throw, that way if the code needs to watch for other errors later on, false could mean many things.
attachEventMediator I think needs a new name. You're not just attaching a mediator, you're setting it. If you had support for multiple mediators, then attach would be appropriate. Similarly, detach should be remove or delete.
Perhaps in replace of echo "{$message}\n";, you could use the sprintf function. I personally think this would clear up the line.
To improve your dependency injection  in Eventful, pass the Log as a parameter.
Will the message always be "log message"? Maybe pass that as an argument.

Overall I think the code is well-written. A couple more comments and better example code could have improved it even more!


Advice 1

while(mid != leftPos)

Above, mid is not defined, so my compiler does not compile that.

Advice 2

#include<stdio.h>

I don't see your code using anything in stdio.h; why not remove it?

Advice 3

It seems that you forgot to seed the random number generator. Did you mean to

srand(time(NULL));

before creating the integer array?

Advice 4

int mid = (rightPos + leftPos)/2;

If rightPos + leftPos overflow, mid will end up negative. You can "extend the range" by writing

mid = leftPos + (rightPos - leftPos) / 2;

instead.

Putting pieces together

After a minor rewrite, your implementation may look like this:

int binSearch(int *arr, int arrSize, int num)
{
    int leftPos = 0, rightPos = arrSize - 1;

    // 'mid' not yet declared:
    int mid;

    while(leftPos < rightPos)
    {
        // Avoids overflowing '(leftPos + rightPos) / 2':
        mid = leftPos + (rightPos - leftPos) / 2;

        if(arr[mid] == num)
            return mid;
        else if(arr[mid] > num)
            rightPos = mid - 1;
        else
            leftPos = mid + 1;
    }

    return -1;
}

Alternative implementation

It is not hard to write the binary search as a template:

template<typename RandomIt, typename T>
RandomIt binarySearch(RandomIt begin, RandomIt end, const T& value)
{
    RandomIt save_end = end;

    while (begin != end)
    {
        auto range_length = std::distance(begin, end);
        RandomIt middle = begin;
        std::advance(middle, range_length / 2);

        if (*middle == value)
        {
            return middle;
        }

        if (value < *middle)
        {
            end = middle;
            std::advance(end, - 1);
        }
        else
        {
            begin = middle;
            std::advance(begin, +1);
        }
    }

    return save_end;
}

Hope that helps.


You're wasting a bit of time instantiating an empty list to instantly append to it with sublist. You'd be better off creating sublist as a list containing the array.pop() element.

    sublist = [array.pop()]

You could also save time in merge by just calling len once at the start. Since these lists aren't modified in the loop there's no need to call it on each iteration.

Stylewise, you could have better names. I know you can't call it a list, but array isn't quite accurate. Maybe sortable or collection? More importantly, you don't need to use num when your algorithm actually works on characters lexicography.

>>> strand_sort("See this can actually still be sorted".split())
['See', 'actually', 'be', 'can', 'sorted', 'still', 'this']

This obviously causes a little oddness with capitals being sorted before other letters. But since you're just using the > symbol, then this algorithm works on any object that has a function for the operator. I think it's worth noting in a docstring that this can be done, and you can highlight its limitation for sorting strings or explicitly say not to use it for strings even though it's possible.


How to speed up window leveling (brightness, contrast)?

I think we need more code,

Where are imagewc, imageww, and lutArr defined ? Those are all 3 unfortunate variable names by the way

Regardless, I think a large speed up should be gained from calling Recalculate once before the loop on pixelArr since imagewc and imageww never change in that loop.

Furthermore, since value is cut of between 0 and 255, you should pre-calculate the array of values.

var lookup= [] , i;
for( var i = _minimumOutputValue  ; i < _maximumOutputValue+1; i++ )
    lookup[i] = Math.round((((i- _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);

then your function would be:

function ApplyWL(value, _valwindowCenter, _valwindowWidth)
{
   if (value <= _windowStart)
     return lookup[_minimumOutputValue  ];
   if (value > _windowEnd)
      return lookup[_maximumOutputValue];
   return lookup[value]
}

I might be wrong about the ranges of lookup, your table might have to be larger, but I am sure you realize the value of a lookup table at this point.

EDIT:

I wrote some code to look at it, some notes:
* I moved the variables to the top, please make sure that all variables are declared with var
* Only constructors should start with an uppercase letter

var imagewc = document.getElementById("text1").value,
    imageww = document.getElementById("text2").value,
    _minimumOutputValue = 0,
    _maximumOutputValue = 255,
    _valid,
    cacheWL = [],
    pixelArr = [11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11];

if (pixelArr != null)
{
  //Move this out of the for loop
  recalculate(_valwindowCenter, _valwindowWidth);
  //Then set the cache which needs the results of `recalculate`
  cacheWL();
  for (var i = 0, n = pixelArr.length,v = 0,i < n; i++)
  {
    pix = pixelArr[i];
    pix = ApplyWL(pix, imagewc, imageww);
    pix = lutArr[pix];

    imagedata[v] = pix & 0xff;
    imagedata[v + 1] = (pix >>> 8) & 0xff;
    imagedata[v + 2] = (pix >>> 16) & 0xff;
    imagedata[v + 3] = 255;
    //Instead of doing a multiplication, you can keep adding 4
    v += 4;
  }
  offscreenCtx.putImageData(g, 0, 0);
}

function setCacheWL()
{
  for( var i = _minimumOutputValue ; i <= _maximumOutputValue ; i++ )
    cacheWL[i] = Math.round((((i - _windowCenterMin05) / _windowWidthMin1) + 0.5) * 255.0);
}

function ApplyWL(value, _valwindowCenter, _valwindowWidth)
{
   if (value <= _windowStart)
     return cacheWL[_minimumOutputValue];
   if (value > _windowEnd)
      return cacheWL[_maximumOutputValue];
   return cacheWL[value]
}

function recalculate(_valwindowCenter, _valwindowWidth)
{
  if (!_valid)
  {
    _windowCenterMin05 = _valwindowCenter - 0.5;
    _windowWidthMin1 = _valwindowWidth - 1;
    _windowWidthDiv2 = _windowWidthMin1 / 2;
    _windowStart = (_windowCenterMin05 - _windowWidthDiv2);
    _windowEnd = (_windowCenterMin05 + _windowWidthDiv2);
    _valid = true;
  }
}


At a glance, OnScreen looks like a method that would raise some Screen event, as On[EventName] is, by convention, the name we use for methods that raise an event. Now, those would obviously return void, and yours is returning a bool - I think I would have it like this:

public bool IsOnScreen(Vector2 point)

The return statement is pretty intense in terms of parentheses. Are they meant to improve readability?

return ((((rect.X <= point.X) && (point.X < (rect.X + rect.Width))) && (rect.Y <= point.Y)) && (point.Y < (rect.Y + rect.Height)));

Let's try something:

return rect.X <= point.X
    && point.X < (rect.X + rect.Width)
    && rect.Y <= point.Y
    && point.Y < (rect.Y + rect.Height);

Much better isn't it?


Find all the positive divisors of a positive integer

Why is the implementation of the algorithm a static method outside of the class IntWithDivisors? Is it in class Program? It shouldn't be there.

It is unusual to do complex work in the constructor. A constructor should only perform initialization. See answer of Telastyn in how complex a constructor should be. There are different possibilities to solve this

E.g. lazy evaluation:

private List<int> _divisors;
public List<int> Divisors
{
    get {
        if (_divisors == null) {
            _divisors = IntDivisors(Number);
        }
        return _divisors;
    }
}

Another option is to simply call a method to get the result.

This leads us to the next question: what is the task of the class IntWithDivisors? Do we really need to store the input number together with the output? Do we really need to override Equals and GetHashCode?

I would rather opt for a minimalist but reusable and flexible approach in the LINQ style as extension method implemented as iterator.

I observed that the starting i is one bigger than incr. We can use this fact to simplify the initialization.

Testing if a number is even is usually done with the modulo operator which yields the remainder of the division num % 2 == 0.

numOveri is a strange name. I renamed it to quotient and i to divisor.

The divisors are tested in ascending order; however, the quotients accumulate in descending order. Therefore, we can return the divisors immediately with yield return and store the quotients in a list. We then need to reverse this list before we return its items.

public static class IntExtensions
{
    public static IEnumerable<int> SelectDivisors(this int num)
    {
        yield return 1;

        int incr = num % 2 == 0 ? 1 : 2;
        var largeDivisors = new List<int>();
        for (int divisor = incr + 1; divisor * divisor <= num; divisor += incr) {
            int quotient = num / divisor;
            if (quotient * divisor == num) {
                yield return divisor;
                if (quotient != divisor) {
                    largeDivisors.Add(quotient);
                }
            }
        }

        largeDivisors.Reverse();
        for (int k = 0; k < largeDivisors.Count; k++) {
            yield return largeDivisors[k];
        }

        yield return num;
    }
}

We can use this extension method like this (shown in a little test routine):

int[] numbers = new[] { 9, 12, 15, 16, 17, 27, 54 };
foreach (int num in numbers) {
    Console.Write($"Number {num} has divisors ");
    foreach (int n in num.SelectDivisors()) {
        Console.Write(n + " ");
    }
    Console.WriteLine();
}


For efficiency, you can take take some things out of the inner loop:

The computations that depend only on x should be in the outer loop.
The computation of combined should be under the if where it is used.
Using enumerate and direct iteration instead of range is simpler and a little faster.
l_sub_one = sorted(items[x]) does the same as these two lines:

    l_sub_one = list(items[x])
    l_sub_one.sort()

Revised code:

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    table = []
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    for x, item_x in enumerate(items):
        l_sub_one = sorted(item_x)
        first = l_sub_one[:new_k] # getting the first k-2 items of the set
        for item_y in items[x+1:]:
            l_sub_two = sorted(item_y)
            second = l_sub_two[:new_k]
            if first == second:
                combined = item_x.union(item_y) # merge
                table.append(combined)
    return table

A further improvement is possible.
One way to describe what you are doing is that you are generating all different pairs of items that share the same value of sorted(item)[:new_k]. Your code does this by considering all possible pairs. A more efficient approach would begin by grouping the items by that value. With the help of a dictionary this only requires one pass over the items. Then you only need to generate pairs withing each group.

Here's again revised code. I'm using collections.defaultdict for grouping, and itertools.combinations for pairing.

from collections import defaultdict
from itertools import combinations

def apriori_creator(items, k):
    """Function that creates apriori table using supported candidates"""
    new_k = k-2 # first k-2 items as described in algorithm in book for 'apriori gen'
    groups = defaultdict(list)  # group by the first k-2 items of the set
    for item in items:
        l_sub_one = sorted(item)
        key = tuple(l_sub_one[:new_k])
        groups[key].append(item)

    table = []
    for group in groups.values():
        if len(group) > 1:
            for item_x, item_y in combinations(group, 2): # all pairs
                combined = item_x.union(item_y) # merge
                table.append(combined)
    return table


For small matrix multiplications, I think it is typically fastest (surprisingly) to implement the basic matrix multiplication you learn in elementary/middle school, which gives us an asymptotic runtime complexity of n^3, where n is the length and width of the arrays (assuming both arrays have the same dimensions and aspect ratios).

In Pseudo code, this algorithm goes as follows:

for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            resultingArray[i][j] = 0;
            for (k = 0; k < n; k++) {
                resultingArray[i][j] += firstArray[i][k] * secondArray[k][j];
            }
        }
    }
    return resultArray;

For larger matrices, typically 30 and up (subjective), there is an algorithm called Strassen's Algorithm that multiplies matrices with an approximate asymptotic runtime complexity of 2^n, again, where n is the length and width of the matrices. This problem is a recursive algorithm that breaks the problem into a lot of sub-problems by breaking down and working on web-matrices. This algorithm typically has a numeric "cross-over" point variable that is defined by the developer and represents the size bound of the matrices where it would be more efficient to simply multiply using the standard matrix multiplication algorithm. The algorithm would roughly go as follows:

if (n <= crossOverPoint) {
        resultArray = basicMatrixMult (n, firstArray, secondArray, resultArray);
    } else {
        double[][] firstArraySubArray1 = partitionSubArray (firstArray, 0, (n / 2), 0, (n / 2));
        double[][] firstArraySubArray2 = partitionSubArray (firstArray, (n / 2), n, (n / 2), n);

        double[][] secondArraySubArray1 = partitionSubArray (secondArray, 0, (n / 2), 0, (n / 2));
        double[][] secondArraySubArray2 = partitionSubArray (secondArray, 0, (n / 2), (n / 2), n);

        resultArray = strassenMatrixMult ((n / 2), addMatrices (firstArraySubArray1, firstArraySubArray2),
                                                 addMatrices (firstArraySubArray1, firstArraySubArray1),
                                                 resultArray);
    }
    return resultArray;

Here's some more info in case you wanted to read up on Strassen's Algorithm:
https://en.wikipedia.org/wiki/Strassen_algorithm


Writing huge 2D vectors to text file too slow

The output-writing code should reside in a function that takes two parameters: the flowDirGrid and a filename.

Don't omit braces on multi-line conditionals.  It's a filthy habit, and someday you will contribute to a coding accident like this.

A performance problem is outputting std::endl at the end of every line, which causes a flush.  Output '\n' instead.


Moving to other game states with ScreenManager

You could use generics

public static void MoveToScreen<T>() where T : Screen, new()
{
    if (currentscreen != null) currentscreen.Remove();

    currentscreen = new T();
    currentscreen.Init();
}

In this case, you'd have to call the method as

ScreenManager.MoveToScreen<ScreenClassHere>();


jQuery

Your code uses jQuery, but you don't seem to be using any features of jQuery that offer any advantages over the DOM - unless you need to target older browsers you can remove your jQuery dependency and thus make your code better: faster (less abstraction, fewer dependencies to download), more portable, more future-proof, etc).

Simply replace $("#id") with document.getElementById and $(selector) with document.querySelectorAll (you can alias it for brevity if necessary: var q = document.querySelectorAll;).

Time-safety

The moment() function, when called, returns the current time value the moment the function is called - your code keeps on calling the moment() function which could return different values each time it's called (if there's a long-enough delay in the interpreter, or if your code executes on a time-unit boundary) - issues like these can cause bugs if midnight at the end of a month happens while your function is executing.

For this reason, you should get the value of "now" only once, at the start of your function, and perform all operations on that value (you should treat it as an immutable value too, even though Date is mutable, as that's best-practice).

var now = moment();
// ...
date1.value = now.add('days').format('yada');

Culture-sensitivity

You're using the dd-MM-yyyy pattern - only a few countries use dashes between the components and it is not ISO-8601 compliant. If this is intentional then that's fine - but if your users are coming from a variety of different countries (with their own date-formatting preferences) then you have two choices:

Use ISO-8601 (yyyy-MM-dd HH:mm:ss) which is unambiguous and as a bonus: is lexicographically sortable.
Use Moment's built-in localization ("i18n") support: http://momentjs.com/docs/#/i18n/

To respect your users' settings, do this:

Get moment-with-locales.js from their website
Modify your initialization code:

// Get the ISO culture settings for the current user, e.g. "en-US" or "es-MX":
var locale = window.navigator.userLanguage || window.navigator.language;

// Configure moment:
moment.locale( locale );

When using locales, use the "locale formats" rather than specific formats. Moment uses "L" to denote a "numeric date" (e.g. "09/07/2016" in en-GB, "07/09/2016" in en-US, or "2016-07-09" in ISO-8601).

Everything

So your code would become:

var locale = window.navigator.userLanguage || window.navigator.language;
moment.locale(locale);

var selectDate = document.getElementById('publicdate');
selectDate.addEventListener('change', onSelectDateChange);

function onSelectDateChange(e) {
    var date1 = document.getElementById('date1');
    var date2 = document.getElementById('date2');
    var now = moment();
    if( selectDate.value == "today" ) {
        date1.value = now.add('days').format('L');
        date2.value = now.add('days').format('L');
        date1.setAttribute('disabled', 'disabled');
        date2.setAttribute('disabled', 'disabled');
    }
    else if( value == "yesterday" ) {
        // and so on...
    }
}


Convert an in-ordered and pre-ordered array to a BST

A few key points:

Make sure to put in semicolons!
You don't need to export properties (i.e do this.myVar) if you're not going to access them - this can lead to potentially slowing down recurrence, or in some cases, security vulnerabilities.
If you're going to use arrow functions, keep it consistent - do const Tree = () => { on the first line

Some more specific things about the actual functionality/logic:

By tracking this.level, you could simplify all required actions into an array by simply pushing their position in the tree. If this.level === 0, you know you are at the top of the tree, and you know to end recurrence.
Using a position-based tracking lets you make it asyncronous, and print the result at the end. Remember that in JS, console.logs take a lot of time, so you want to avoid it as much as possible.
This would let you essentially JSONify the tree into a bunch of function references, which, when called, would populate themselves. Giving the option to return this would make the class more integratable into other things, where a console output is not necessarily the most useful thing. Further, it would let you cut out the repetition of if (left_tree.length>1){, which is not DRY.


Your definitions of make-segment and make-point can be simply bound to cons; you may do the same for accessors.

(define make-segment cons)
(define start-segment car)
(define end-segment cdr)

(define make-point cons)
(define x-point car)
(define y-point cdr)

Your definition of sum is similar to how + works.  You may use + instead in your definition of average.

(define (average . l) (/ (apply + l) (length l)))

Notice the repetition of code in your definition of midpoint--you create a new point out of the averages of each coordinate of the two end-points that describe the line segment.  You may abstract out the calculation of averages either by writing your own helper function or by using the built-in map function, like so:

(define point->coordinate-accessors (list x-point y-point))
(define (midpoint seg)
  (apply make-point (map (lambda (point->coordinate)
                           (average (point->coordinate (start-segment seg))
                                    (point->coordinate (end-segment seg))))
                         point->coordinate-accessors)))

This definition is general enough to handle midpoint calculation in as many dimensions as handled by make-point and point->coordinate-accessors.


def checkPalindrome(self,lst):
    return lst[:] == lst[::-1]

This is an extremely expensive implementation. lst[:] is needlessly creating a copy of lst, then lst[::-1] creates a second complete copy of lst (but reversed). There are many ways of approaching this, but I would go for something like this:
def checkPalindrome(self, lst):
    return all(start == end
               for start, end in zip(lst, reversed(lst)))

It zips lst with a reversed list iterator:
>>> lst = "abcd"
>>> list(zip(lst, reversed(lst)))
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]

Then checks to see if all the pairs are equal. If they are, the list is a palindrome. This method is still inefficient though since only half of each needs to be checked. It can be further improved by introducing itertools.islice to get a "view" of the first half of the zipped lists:
from itertools import islice

def checkPalindrome(self, lst):
    half_pair_view = islice(zip(lst, reversed(lst)), len(lst) // 2 + 1)
    return all(start == end for start, end in half_pair_view)

islice is like normal list slicing except instead of creating a copy, it just allows you to iterate over a limited portion of the original iterable.
This code is more efficient because every function involved here is "lazy": they do only as much work as they need to. reversed, zip, islice, and the generator expression all return an iterator that can produce elements (but do little work up front). all also exits as soon as it gets a Falsey result, so it's comparable to a for loop that contains a break in some branches. This is key here because we only want to do as much work as is necessary to determine whether not they're palindromes. Making two full copies of the list does a large amount of work; far more than is required to check if the string is a palindrome.

checkOddChars is a textbook use-case for a list comprehension:
def checkOddChars(self, lst):
    return [i for i in lst if lst.count(i) == 1]

If you ever find yourself initializing an empty list, then iterating over another iterable and adding to the list, you likely want a comprehension.
This is quite an expensive function too. count needs to iterate the entire list each time; once for every element in lst. This also double counts any repeated elements. I'm not sure off the top of my head what a better solution is though.

 del lst[0]

This is also quite expensive. Ideally, you shouldn't delete from a list except for at the very end. Lists don't support efficient deletes, and the closer to the beginning of the list you delete from, the worse it is. I'd switch to using a dequeue instead of a list, which avoids the overhead of popping from the beginning.


Extract a number from a consecutive range in a Google Sheet

I guess the answer could be useful to someone that begin like me in coding...Anyway the tip here was to create an array first (I named it table) instead of adding objects line by line and then update the sheet in a single operation with setValues. It makes running the code way much faster !

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var feuille = ss.getActiveSheet();
  var nb_total = form.colis2 - form.colis1;
  var table = [];
  for (i = 0; i <= nb_total; i++) {
    if (i < form.gare){
      table.push([+form.colis1 + i, form.ddc, "A"]);
      }else{
      table.push([+form.colis1 + i, form.ddc, "B"]);
      }
    }
  feuille.getRange(feuille.getLastRow() + 1, 6, table.length, 3).setValues(table);
  }


Syncing Redux state with the URI in 2020

I ended up choosing the use-query-params library and writing a class which has several useEffects to sync state.  One of the useEffects fires once at load, to update the redux state with the query params in the URL, and the others each hang off one aspect of the state and update the query params when that item changes.  It works on the general rule that if the state element is not the default state, it should not add (or remove) the related query param, but if it is not default, then add the query param.

I couldn't just replace the relevant redux state with state in the query params for various reasons: 1) It's useful to keep state elements using the same pattern throughout, for modularity, and so that they benefit from redux dev tools; 2) the query params don't remember the state when the url changes; 3) the state does not care whether or not the item is default - it will always write it.

For those interested, my implementation is here: https://github.com/adybaby/taskmaster/blob/master/src/HistoryWriter.js and a demo here: https://master.d29jyoh6h48gjm.amplifyapp.com/


How to know when I need to use get/set and when not?

First of all, I'd make the texture and position fields private. They're set from the outside, and the outside doesn't need to change them.

Then I'd extend that. Anything your class needs to be given, add to the constructor. If Asteroid makes it itself, make it private. If something needs to look at it, make a get only property to access it. If it needs to be modified, make it an autoproperty.

The only thing that seems like a good candidate for a property to me is your Origin. Something may want to sort Asteroids by Origin.

If, following my advice, you reach more than 4 parameters, you should make a new class to either use as the parameter or deal with those values in the Asteroid.

If your teachers have been telling you to make everything a public field, ignore them. They're wrong. Maybe follow their advice on assignments for the sake of credits, but never in production code.