the most simple algorithm would be to calculate the start and end indices

    // set start index relative to selected
    int start = selectedPage - (offset / 2);
    // adjust for first pages
    start = Math.max(start, 1);
    // set end index relative to start
    int end = start + offset - 1;
    // adjust start and end for last pages
    if (end > totalPages) {
        end = totalPages;
        start = end - offset + 1;
    }

    return IntStream.rangeClosed(start, end).boxed()
        .collect(Collectors.toList());

as for code review:

method signatures correctly return interface List. however, there are two places where you initialize the list with a concrete implementation. now imagine you would decide that ArrayList is better suited. you need to remember to modify two places.
while on the subject: don't use LinkedList. it has an extremely narrow use case where it is preferable over ArrayList. this is not one of them. Especially if you initialize the ArrayList with initial size.
use Java 8 collection stream (if you've learned it) it is more efficient and concise than for loop
The code does not use java standard indentation. code inside if block should be indented inward.


jQuery autocomplete for all place names in the UK

You can improve performance by using autocomplete function with this options:

$( "#location" ).autocomplete({
      source: availableTags,
      delay: 0,
      minLength: 2,
});

This library has  a 300 ms delay by default. So setting delay to 0 disables it.
minLength is for loading the matches after the users typed at least 2 chars, I don't think there is a point to load them when you have only 1 character.

Good luck


Validator and Sanitizer for HTML 5 attribute regex according to current HTML living standard

The \x{0020} (SPACE) character is already included in \s, you can omit that part.
I prefer to use  \p{Cc} over [:cntrl:] for consistency and because I don't like to have nested square braces in a character class.
I expect isAttributeNameValid() to be checking that the whole string contains NO blacklisted characters.  If you want to match the entire string then you will need "start of string" and "end of string" anchors and a negated character class in your pattern.  But wait, you have a regular character class and you are returning true if one or more blacklisted characters are in the string -- this seems precisely the opposite of what the method name suggests.  Unless I am confused, you should replace (bool) with ! so that you return false when a match is made and true when there are no blacklisted characters found.
I don't know if I agree with the wording of Failed to sanitize attribute name; it seems more truthful to say that the Attribute name had no salvagable characters.


Am I wrapping synchronous code in ktor/Kotlin coroutine correctly?

To start, I don't know Ktor, so what I'm going to tell is when Ktor doesn't do additional stuff, which is highly probably not the case.

Coroutines are managers for threads: they tell threads what to do and when to do it.
When you write a coroutine, everytime you come across a suspend-keyword, the thread that executes the task asks the coroutine what to do next. The coroutine can tell to continue with the task he was working on, but it can also tell the thread to do something else.

This is great if you have to work with triggers:

A database-call
A with triggers the threads
Another thread that returns something.

Instead of waiting, the coroutine can tell the thread to do something else and once it comes across the suspend-keyword to continue with the task if the trigger is fulfilled.

In your code, you introduce a side-task by adding the async-keyword.
The next thing you do is telling to wait on this side-task.
This means that apart from adding a suspend-keyword, it does nothing.

So, a coroutine is not for computation, but for waiting. However, coroutines can manage more than one thread. Giving the side-task to a side-thread and waiting for that side-thread to finish is something that coroutines are great for.

Therefor, your code could be better written as:

/**
 * A dedicated context for sample "compute-intensive" tasks.
 */
val compute = newFixedThreadPoolContext(4, "compute")

get("/"){
    val key = withContext(compute){
       //heavy computation
    }
    call.respond(key.toString())
}

The expanded example can be found here: https://ktor.io/samples/feature/async.html


This type of functionality is what .hover() was designed for. I wouldn't recommend using anything else. As far as avoiding building up a queue of events when hovering, jQuery has the .stop() method for that very reason.

$(".project-mask").hover(
    function() {
        $(".thumbnail").stop(true, true).fadeOut(300);
        $(".description").stop(true, true).fadeIn(300);
    },
    function() {
        $(".thumbnail").stop(true, true).fadeIn(300);
        $(".description").stop(true, true).fadeOut(300);
    }
);

Here is a fiddle


SICP exercise 1.28 - miller-rabin primality test part II

Stylistically, I'd write it this way:

;; expmode b e m = b^e modulo m
(define (expmod b e m)
  (define (expmod-iter acc b e)      ; iterative accumulation
    (define bsq (remainder (* b b) m))
    (cond ((= e 0) acc)
          ((and (not (= b (- m 1)))
                (not (= b 1))
                (= bsq 1))
           0)
          ((even? exp)
           (expmod-iter acc bsq (/ e 2)))
          (else
           (expmod-iter (remainder (* acc b) m)
                        b
                        (- e 1)))))
  (expmod-iter 1 b e))               ; initial accumulator = 1

(define (miller-rabin-test n)
  (define (try-it b)
    (if (and (= b 1)
             (> n 2))
        (miller-rabin-test n)
        (= (expmod b (- n 1) n)
           1)))
  (try-it (random 1 n)))

(define (fast-prime? n times)
  (or (= times 0)
      (and (> times 0)
           (miller-rabin-test n)
           (fast-prime? n (- times 1)))))

You've corrected the error of not taking the remainder of the square.

There's no need to define a function square just to save one call to *.

You've converted your recursive expmod into iterative code; although I wouldn't call the former "horrible" since its complexity is only logarithmic, so recursion depth is kept in check.

Assuming you're using Racket, (+ 1 (random (- n 1))) can be written simply (random 1 n).

You've kept the awkward encoding for fast-prime? which is more naturally coded directly with the logical connectives.

Will think over some more with regards to its correctness, that you ask about.


Creating enchantment objects based on configuration

Assuming you already have a class called Enchant (should be a superclass of your enchantments), you could use an enum to organize all of your enchantments:

public enum Enchantments {
    MULTI_FIRE(1, "multifirearrow") {
        Enchant getEnchant() { return new MultiFireArrow(); }
    }, BOLT(2, "bolt") {
        Enchant getEnchant() { return new Bolt(); }
    }, RANDOM_SPEED(3, "randomspeed") {
        Enchant getEnchant() { return new SpeedRandom(); }
    };
    //Add more enchantments here!
    abstract Enchant getEnchant();
    public void enchant() {
        Enchant enchant = getEnchant();
        DashEnchant.getEnchants().put(this.index, enchant);
        DashEnchant.getStringEnchants().put(this.name, enchant);
        if(debug()) getLogger().info(this.toString() + " enchant registered");
    }
    public boolean isEnabled() {
        return getDashConfig().getBoolean("enchantments." + this.name + ".enabled");
    }
    private String name;
    private int index;
    private Enchantment(int index, String name) {
        this.index = index;
        this.name = name;
    }
}

and then do something like:

for(Enchantment e : Enchantment.values())
    if(e.isEnabled()) e.enchant();

You could make the code even shorter using reflection and enum ordinals but there is a point where shortening the code doesn't really help anymore (plus the added speed penalty.) Nonetheless: (replace MY_PACKAGE_NAME with your package)

public enum Enchantment {
    MULTI_FIRE, BOLT, SPEED_RANDOM;
    //Add more enchantments here!
    public void enchant() {
        Enchant enchant = Class.forName(MY_PACKAGE_NAME +
                toUpperCamel(this.toString(), "_")).newInstance();
        DashEnchant.getEnchants().put(this.ordinal() + 1, enchant); //ordinal starts at 0
        DashEnchant.getStringEnchants().put(this.replaceAll("_", "").toLowerCase(), enchant);
        if(debug()) getLogger().info(this.toString() + " enchant registered");
    }
    public boolean isEnabled() {
        return getDashConfig().getBoolean("enchantments." +
                this.toString().replaceAll("_", "").toLowerCase() + ".enabled");
    }
    private static String toUpperCamel(String a, String spl) {
        StringBuilder b = new StringBuilder(a.length());
        for(String s : a.split(spl)) {
            b.append(Character.toUpperCase(s.charAt(0)));
            b.append(s.substring(1).toLowerCase());
        } return b.toString();
    }
}


Encrypt texts, with saved password using pycrypto

Be careful naming your functions
You declare a lambda function named EncodeAES, but this function itself doesn't know anything about AES. It accepts an object with an encrypt() member function which it calls, but that object could be anything.
The name should reflect what the function does. This one does two things: it base64-encodes, and it calls encrypt(). I think any descriptive name would be really awkward, maybe it is best not to use these lambda's at all, especially since they are only used once.
Don't modify the message before/after encryption
Your DecodeAES lambda calls rstrip() on the decrypted message. But what if the original text has whitespace of its own at the end of the message that is significant? Or what if the message is not a piece of text but a binary file? Then the output after decryption will be different from the message before encryption. It also allows for length extension attacks.
Don't use ECB mode
You should never use ECB mode to encrypt things, it has many issues such as revealing patterns in the plaintext, and allowing an attacker to flip bits in the plaintext at will.
Almost any other mode would be suitable to use, if you add a unique initialization vector (IV) to the ciphertext. Note that this IV should be different each time you write an encrypted file, otherwise it might make it easy for someone to decrypt parts of the message by comparing two ciphertexts.
Even better would be to use an authenticated encryption mode to ensure that if an attacker has tampered with the ciphertext, this is detected when trying to decrypt the message. If you don't provide any form of authentication of the ciphertext, it allows an attacker to modify it, and then the output after decryption will be modified as well, sometimes in ways that are not easy to spot.
Don't use home-grown crypto in production code
While it is perfectly fine to try to implement your own encryption protocols (it's a good way to start learning about it), it is very easy to make mistakes, and mistakes will be costly (since there probably is a good reason why you want to keep the data private).
Go to  https://crypto.stackexchange.com/ and search there for how to safely encrypt files. You'll likely find many answers like this one that tell you to not try it yourself and rather use existing, well-established software to do encryption for you. If you don't want to become a crypto expert, then follow that advice. If you really do want to become better at crypto, then have a look at the well-established software and protocols out there, and try to learn how they work.
Use a higher-level cryptography library
The Crypto package is quite low-level. It provides you the basics of encryption, but already for properly encrypting a file you need to combine several techniques. It is better to use a library that provides higher level functions that take care of all the details for you. There are many of them out there. A popular one is PyNacl.


One option is to not perform any regular expression check at all. You can perform a quick match by checking if the line ends with SRGB and the try the split and convert and simply continue if it fails. Something along these lines:

private static void GetOrigionalRGBColours(string txtFile)
{
    using (StreamReader inputReader = new StreamReader(txtFile))
    {
        while (!inputReader.EndOfStream)
        {
            var line = inputReader.ReadLine();

            if (line.EndsWith(" SRGB")
                && line != "1 1 1 SRGB"
                && line != "0 0 0 SRGB")
            {
                try
                {
                    string[] rgbArray = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (rgbArray.Length == 4)
                    {
                        RGBColour rgbColour = new RGBColour() { Red = Convert.ToDecimal(rgbArray[0]), Green = Convert.ToDecimal(rgbArray[1]), Blue = Convert.ToDecimal(rgbArray[2]) };
                        originalColourList.Add(rgbColour);
                    }
                }
                catch (FormatException) {}
                catch (OverflowException) {}
            }
        }
    }
}

Alternatively to the try-catch you can use decimal.TryParse() and ignore the line if it returns false for any of the 3 entries.

Update: Version with decimal.TryParse.

private static void GetOrigionalRGBColours(string txtFile)
{
    using (StreamReader inputReader = new StreamReader(txtFile))
    {
        while (!inputReader.EndOfStream)
        {
            var line = inputReader.ReadLine();

            if (line.EndsWith(" SRGB")
                && line != "1 1 1 SRGB"
                && line != "0 0 0 SRGB")
            {
                string[] rgbArray = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (rgbArray.Length != 4) { continue; }

                decimal red;
                var hasRed = decimal.TryParse(rgbArray[0], out red);
                decimal green;
                var hasGreen = decimal.TryParse(rgbArray[1], out green);
                decimal blue;
                var hasBlue = decimal.TryParse(rgbArray[2], out blue);

                if (hasRed && hasGreen && hasBlue)
                {
                    RGBColour rgbColour = new RGBColour() { Red = red, Green = green, Blue = blue };
                    originalColourList.Add(rgbColour);
                }
            }
        }
    }
}

I like that one better because I find try {} catch {} block always a bit ugly . It also conveys the intend of the code better.


Implementation of a new algorithm for sklearn

Thank you for posting this.

You didn't include any result timings. CPU performance and error performance on an available dataset would be of interest, for evaluating against sklearn's baseline code. Highly correlated inputs would be more interesting than uniform random numbers.

Noticing the import just above it makes the class name perfectly clear, but nonetheless please give it a docstring explaining:

"""Iterative Sparse PCA (principal component analysis)."""

Please fix a comment so it reads:

    self.Npc = Npc  # number of principal components

or, better, put it in a docstring. Consider deleting the redundant max_iter comment, or perhaps rephrase it to describe max number of principal components if that is its function.

Typo: tolerance

def spca_iterate(self, u_old, v_old):

The public API should probably talk about u_init & v_init.

Typo: no more (but consider deleting this redundant comment)

    v_new = np.zeros(shape=v_old.shape)
    u_new = np.zeros(shape=u_old.shape)

This pair of assignments appears to have no effect.

        if norm_v == 0:  # if norm v is 0 it means that no components have been selected. So you should reduce the penalty lambda
            break

This seems to be speaking about this author's alpha in terms of another author's lambda. Your docstring should definitely mention the effect of alpha on the solution's sparsity.

        if np.linalg.norm(v_new)==0:#check again if the norm is 0
            break
        if np.linalg.norm(v_new - v_old)<self.tol or np.linalg.norm(-v_new - v_old) < self.tol:#check if there is convergence
            break

The first test is pointless (redundant). Please delete it. The 2nd test is phrased oddly. Please express it as:

        if abs(np.linalg.norm(v_new - v_old)) < self.tol:  # check for convergence
            break

This assignment:

        x_times_v.shape = (self.m, 1)

and the v_new .squeeze(), make me concerned that we didn't take an opportunity to fix up shapes before the loop began. The squeeze returns either a view or the underlying object. A single view would be just fine, but a chain of max_iter views would be a problem. Can we maybe banish the shape concerns to the init code at top of function, outside the loop?

        print("No Convergence. Error!!!")

A raise might be more appropriate here.

    norm_v = np.linalg.norm(v_new)

We were squaring before. This statement might be fine, but it warrants a comment, as one norm_v is not like the other. Or, put another way, the whole method really really needs a specific literature reference describing the method.

It's not actually clear what the squaring was about. If FP negative zero was a concern, then abs() should suffice.

fit() would like a docstring, please.

    self.components_ = np.zeros(shape=(self.n,self.Npc))
    ...
    self.components_[:, i] = v_final.squeeze()

This made no sense to me. It is conventional to use underscore suffix to avoid conflict with pre-existing symbols (e.g. min_) and prefix for private variables. But here it appears you just wanted a local variable (not an attribute) named components. For that matter, it's not clear what's going on with m, n, sT, & X. It appears they should be locals.

X = np.random.random((100, 20)) #generate a random matrix
X = sk.preprocessing.scale(X)   # scale the data

Please delete both remarks.

alpha = 1  # set the penalty

Good. Very clear, consistent with the literature.

nPCs = 2  # set the number of components

You felt a need to write a comment. This suggests nPCs was misnamed, and would be clearer as num_components. Similarly for Npc in the ctor.

Consider using a private _spca_iterate name.

The a name helps nobody. Consider turning

a = IterativeSPCA(Npc=nPCs, alpha=alpha)
sP, sT = a.fit(X)

into

sP, sT = IterativeSPCA(Npc=nPCs, alpha=alpha).fit(X)

Maybe a single fit() function, with no class, would suffice.

The sP and sT names could be more helpful. I understand that P denotes principle components, but you didn't offer a literature reference so T is a bit obscure, it doesn't seem to relate to "feature".

df['it_spc1'] = a.components_[:,0]

What is going on here? Didn't you just put that in sP, but now you're unwilling to use it?

df['spc1'] = spca.components_.T[:,0]

Oh, I see. You were going for API compatibility. I guess you know already how I feel about SPCA fit() being void. I cannot fathom why you return transpose of what SPCA offers.

Ok, maybe .components_ is an important part of your public API, at least for backward compatibility. But it seems like you could be friendlier to callers, so it is easier to consume your API and correctly interpret results.


Comparing columns from two CSV files - follow-up

There is some duplication of code because you are handling two files.
When you need some data converted to int it would be best to do soon as you've read it to avoid sprinkling other logic with int() calls.
The two columns SIREN and NIC combined seem to form a sorting key to the file. You could simplify the if elif... part by performing the comparisons on (SIREN, NIC) tuples.

To address the above, I propose to organize the code like this:

def parse_file(file, variable):
    reader = csv.reader(file, delimiter=';')
    sir_s, nic_s, comp_s = set_up_file(reader, variable)
    for line in reader:
        key = int(line[sir_s]), int(line[nic_s])
        yield key, line[comp_s]

def test_variable(variable):
    with open('source.csv', 'r') as source, open('tested.csv', 'r') as tested:
        source_r = parse_file(source, variable)
        tested_r = parse_file(tested, variable)

        correct = 0
        try:
            line_s = next(source_r)
            line_t = next(tested_r)
            while True:
                key_s, comp_s = line_s
                key_t, comp_t = line_t
                if line_s == line_t:
                    correct += 1
                if key_s >= key_t:
                    line_t = next(tested_r)
                if key_s <= key_t:
                    line_s = next(source_r)

        except StopIteration:
            return correct

Note however that I've omitted the computation of size. This could be done by incrementing a variable after reading each line, but since lines are read at multiple places, and some may be left in the end if the other file ends first, it may be best to count the lines separately like you have done.


Current approach

You can determine the exact count of days in the mask beforehand -> you can use a better initial size than 7 for the array list (or directly an array as the size is fixed).
You don't have to sort the list (and thus don't need the comparator), rotating based on the firstDayOfTheWeek is sufficient as the order of the days does not change.
While this is very ugly: You could replace the new ArrayList<>(dayList.size()) with (List<String>)(List<?>)dayList.

Regarding your edit: This seems like a very bad idea if you ever want to make your app multithreaded.

Alternative implementation

You can avoid rotating the resulting list if you start interpreting the mask at the provided firstDayOfWeek instead of Monday.

public static final int MONDAY    = 0x01;
public static final int TUESDAY   = 0x02;
public static final int WEDNESDAY = 0x04;
public static final int THURSDAY  = 0x08;
public static final int FRIDAY    = 0x10;
public static final int SATURDAY  = 0x20;
public static final int SUNDAY    = 0x40;

public static String maskToString(int mask, int firstDayOfWeek) {
    assert (mask & ~127 | firstDayOfWeek & ~127
            | firstDayOfWeek & firstDayOfWeek - 1) == 0;
    String[] values = new String[bitCount(mask)];
    int i = 0, d = firstDayOfWeek;
    do {
        if ((mask & d) != 0)
            values[i++] = dayToString(d);
    } while ((d = d << 1 & 127 | d >> 6) != firstDayOfWeek);
    return Strings.join(" ", values, true);
}

Which gives the following result:

maskToString(MONDAY, MONDAY);                              // Mon
maskToString(TUESDAY | THURSDAY | SATURDAY, MONDAY);       // Tue Thu Sat
maskToString(TUESDAY | THURSDAY | SATURDAY, SUNDAY);       // Tue Thu Sat
maskToString(TUESDAY | THURSDAY | SUNDAY, MONDAY);         // Tue Thu Sun
maskToString(TUESDAY | THURSDAY | SUNDAY, SUNDAY);         // Sun Tue Thu
maskToString(127, MONDAY);      // Mon Tue Wed Thu Fri Sat Sun
maskToString(127, SUNDAY);      // Sun Mon Tue Wed Thu Fri Sat
maskToString(127, WEDNESDAY);   // Wed Thu Fri Sat Sun Mon Tue


I made basketball program using Java that runs on console

Descriptive variable names
You have this:
player = scanner.nextLine();

Does the input reflect a player?
I think a more descriptive name would be playerInput. That makes the switch more readable as well.
Make methods do one thing (single responsibility principle)
Your shootBall method does three things: asking for input, calculating the result, and printing the result. Ideally this would be split up:

private String getInput()
private String shootBall(String input)
private String printResult(String result)

This makes it easier to change the implementation of a responsibility and easier to read the logic of your program.
The main while loop would become
while(true) {
    String input = getInput();
    String result = shootBall(input);
    printResult(result);
}

This makes it easier for coding some exit value as well;
while (true) {
    String input = getInput();
    if (input.equals("QUIT"))
      break;
    String result = shootBall(input);
    printResult(result);
}

Or, if you don't like the while-true-break
String input;
while (!(input = getInput()).equals("QUIT")) {
    printResult(shootBall(input));
}


Project Euler #12 - highly divisible triangular number

Project Euler problems typically don't benefit from micro-optimizations such as inlining functions or flushing standard output. The biggest speed gains often come from algorithmic improvements. Here there are two key mathematical facts that can make this computation tractable:

A number with prime factorisation n = Product_i p_i ^ e_i (where p_i are primes and e_i their exponents) has a number of divisors equal to d = Product_i (e_i + 1).
A triangle number is equal to n * (n + 1) / 2. These factors have no prime factors in common and only one of them has a factor of two. This means that the number of divisors of  a triangle number can be factored in the number of the divisors of n and n+1.

In order to code this algorithm, a few more guidelines to writing better code:

write functions that take an int and return an int. Don't use Pascal like procedures by modifying a reference argument. This makes your code harder to reason about.
separate computation from I/O: an algorithm should ideally have no side effects, and be silent. If you want to query the result, just print that.

Below some working code:

#include <chrono>
#include <ctime>
#include <iostream>

int triangle(int n)
{
    return ((n + 1) * n) / 2;
}

// Math fact: a prime decomposition n = Prod_i p_i^e_i yields
// Prod_i (e_i + 1) different divisors
int num_divisors(int n)
{
    auto divisors = 1;  // 1 has one divisor
    {
        auto f = 2;
        auto count = 0;
        while (n % f == 0) {
            ++count;
            n /= f;     // divide by factor of 2
        }
        divisors *= (count + 1);
    }

    // <= n guarantees that a prime has 2 divisors
    for (auto f = 3; f <= n; f += 2) {
        auto count = 0;
        while (n % f == 0) {
            ++count;
            n /= f;     // divide by odd factor
        }
        divisors *= (count + 1);
    }
    return divisors;
}

int unique_divisors(int n)
{
    if (n % 2 == 0)
        n /= 2;
    return num_divisors(n);
}

// triangle(n) = (n + 1) * n / 2
// only one of them has a factor of two, and they have no prime factors in common
// we can cache one of the divisor counts while iterating over triangle numbers
int first_triangle_with_more_than_n_divisors(int n)
{
    auto i = 1;
    for (auto f1 = unique_divisors(i), f2 = unique_divisors(i + 1); f1 * f2 <= n; ++i)   {
        f1 = f2;                        // re-use result from previous iteration
        f2 = unique_divisors(i + 2);    // only one new computation
    }
    return i;
}

int main()
{
    auto start = std::chrono::steady_clock::now();

    auto const n = 500;
    auto res = first_triangle_with_more_than_n_divisors(n);

    std::cout << "the first Triangle number to have over " << n << " divisors : " << triangle(res) << "\n";

    auto stop = std::chrono::steady_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);

    std::cout << "\nIt took me " << elapsed.count() << " milliseconds." << "\n";
}

Live Example that runs in less than 0.2 seconds.


Convert a boxed integer to an nullable integer with potentially different type

You should probably add IConvertible restriction on T, since it is used by Convert.ChangeType method.

Also this check: typeof(T) == x.GetType() looks like an overhead. Convert.ChangeType does nothing if types match. For example, check out Int32 sources:

int IConvertible.ToInt32(IFormatProvider provider) {
    return m_value;
}

So you might as well just check for null instead:

static T? Unbox<T>(object x) where T : struct, IConvertible
{
    if (x == null) return null;
    return (T)Convert.ChangeType(x, typeof(T));
}

Edit: as mentioned by sir t3chb0t, there are cases, where Convert.ChangeType can throw. So it might be a good idea to swallow exceptions inside your method and return null in those cases. But it also can be a very bad idea. It depends on use case, which you should carefully evaluate.


Pythonic way to find duplicate objects in a set

hash

Since tuples are hashable if their elements are hashable, you can just do

def __hash__(self):
    return hash((self.latitude, self.longitude, self.year, self.month))

If you want to have locations that are near each other be set as the same, you might have to round the coordinates

repr

for debugging, adding a repr can be handy:

def __repr__(self):
    return (
        "Position("
        f"lat: {self.latitude}, "
        f"lon: {self.longitude}, "
        f"year: {self.year}, "
        f"month: {self.month}, "
        ")"
    )

Counting

To count, you can use a collections.Counter, and just feed it an iterable of Positions.

counter = Counter(locations)
most_visited = counter.most_common(<n>)

You will need one Counter per year/month, but this can be done with a defaultdict(Counter)


Your code looks good and is well documented. I have a few suggestions anyway.

Naming

calc_fibonacci_num is a long name for such a function. The calc_ prefix is probably not useful and neither is the _num.

The expression fibonacci(5) is probably explicit enough without additional information.

The same kind of comment applies to the other function names.

Domain definition (and default value)

It seems a bit "un-natural" to handle d=0 as a special case for calc_fibonacci_sum.
It may be clearer to explain that d is expected to be a strictly positive integer.

Then you'd just need to give d the default value 1 and everything would work just fine.

Function called twice

In return [calc_fibonacci_num(x) for x in itertools.takewhile(lambda x: calc_fibonacci_num(x) <= n, itertools.count())], you call the same function with the same argument twice. You can easily check this by adding a print(n) at the beginning of calc_fibonacci_num.

A solution to this issue is to rewrite the function:

def calc_fibonacci_seq(n):
    return itertools.takewhile(lambda x: x <= n, (calc_fibonacci_num(x) for x in itertools.count()))

This fixes another issue you had which is the fact you were building an actual list in memory when you just need a generator to go through the different lists.

An easier way to generate successive fibonacci numbers

The formula you've used is fairly efficient to generate the n-th fibonacci number without generating all the numbers before. However, in our case, we do need to compute them anyway. Thus, a naive solution would probably be faster. I'd suggest the following generator:

def fibo(f=1, g=1):
    """Yields Fibonacci numbers."""
    while True:
        yield f
        f, g = g, f + g


Please stop using using namespace std. Read
this
Consider using a std::vector to hold the digits of a number. Here
it seems as though you can assume the user is inputting a number
with four digits. But that might not always be the case. A vector is
dynamic.
 This is...uh, well:

first = base / 1000;
second = base / 100 % 10;
third =  base / 10 % 10;
fourth = base % 10;

Consider using a while loop to get all digits of the number.

while(number)
{
    digits.push_back(number%10);
    number /= 10;
}

Note the digits will be in reverse. You can use std::reverse() to
reverse the digits such that the first element in the vector is the
first digit of the number.
Use std::accumulate() to obtain the sum of all digits. You don't
have to do this in the while loop.

Here is everything together. Ideally, you would want to put the while loop and summing operation in another function.

#include <iostream>
#include <vector>
#include <algorithm>

using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main()
{
    int number, sum;
    vector<int> digits;

    cout << "Enter a whole number: ";
    cin >> number;

    while(number)
    {
        digits.push_back(number%10);
        number /= 10;
    }

    std::reverse(digits.begin(),digits.end());
    sum = std::accumulate(digits.begin(),digits.end(),0);

    //C++11 range-based for loop
    for(auto i : digits)
        cout << i << " ";

    cout << "\nSum of the digits: ";
    cout << sum << endl;

}


Comparing strings with different newlines

The code looks quite complicated at first glance, but when reading it, it is straightforward. If you want to make the code shorter, you can just do this:

public static boolean equalsIgnoreNewlineStyle(String s1, String s2) {
    return s1 != null && s2 != null && normalizeLineEnds(s1).equals(normalizeLineEnds(s2));
}

private static String normalizeLineEnds(String s) {
    return s.replace("\r\n", "\n").replace('\r', '\n');
}

Concerning running time and GC stress, your code is probably better. Use a benchmark to see how much better it is.

The word twirks sounded negative to me, therefore I replaced it with style.

Since the two strings have equal rights and are treated the same, none of them should be called the "other one".

You should not make the constants public, since there is no need to do that.


Is there a nice way to avoid this repetition/boilerplate?

Yes, there is a cleaner way.

Since you are using Spring, please check the annotation @ControllerAdvice and the class ResponseEntityExceptionHandler.

To handle exceptions, you'll need to extend ResponseEntityExceptionHandler and manage the returned ResponseEntity in a method annotated with @ExceptionHandler, for example:

@ControllerAdvice(basePackageClasses = MyControllerClass.class)
public class ErrorResponseHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(MyExceptionType.class)
  @ResponseBody
  ResponseEntity<Object> handleControllerException(HttpServletRequest request, Throwable ex) {
    // process the exception and wrap the response to return in ResponseEntity
  }

}

Using this approach, you service methods will remain one-liners, returning non-wrapped ArrowsGraph instances.


Do you think there will be security issues if I put this code I made onto the client side?

Yes. You should not expose your Google API key to other users - it should be hidden away on your server. You should expose an end point on an API server that will run the Google OAuth actions. This is known as the three-legged or server-side OAuth flow.

The security reasons mainly come down to the fact that if someone knows your API key then they can masquerade as you. This is usually solved by a shared secret (or just a private key), but the Google OAuth flow doesn't appear to provide this.

You can see here for Google's own resource on best practises for API keys.


Find The Triangular Number With More Than N Divisors

Your naming of variables is hard to reason about. When I think about what your program is doing you, I come up with the following sequence of steps:

Take in a target divisor count.
Index through each triangular number n and check if it satisfies the condition.
If it doesn't increment n and repeat.
Once it does print out the results.

Here is how I would restructure your main loop:

std::cout << "You want to find the first triangular number with less than or more than how many divisors? " << std::endl;
int target;
std::cin >> target;
// Indexes the triangle numbers.
int n = 0;
// Keeps track of how many divisors.
int divisors = 0;
do {
    n++;
    divisors = enumerate_divisors(generate_triangular(n));
} while (divisors < target);
std::cout << "The " << n <<" th triangular number" << std::endl;
std::cout << generate_triangular(n) << std::endl;

Also, add some spaces in between your function declarations, it's hard to read when everything is clumped together. But don't over do it (in particular, don't double space everything).


Quicksort implementation in TASM assembly

It feels like the first comment I make for every assembler code review is the same: Add comments.

This may seem silly to you, after all, you know exactly what the code does.  It's obvious, isn't it?  But 6 weeks from now or 6 months from now, even 6 years from now, will it still be obvious to you what this code does?  And that's just you, the person who wrote it.  Reading someone else's assembler is always a challenge.

You are asking for a code review, and I would never sign off on code (assembler or otherwise) that didn't have decent comments describing what it does.  If nothing else, performing that last pass thru the code describing what everything does sometimes turns up bugs or inefficiencies.

I realize this may just be a class project, or even just written for your own interest/education.  But it's a habit you should acquire.  Your future self (and the people you ask to read your code) will thank you.

So, let's start at the top with some file-scope comments.  Perhaps something like this:

; qs.asm - Routine to perform a quicksort on a hard-coded
;          list of numbers.
;
; Written for 16bit on i386.
;
; The list of numbers to sort is stored in the variable arr.

And looking at your first procedure, perhaps something like this:

; Swap - swap 2 variables in a list
;
; On input:
; sp + 4 - Pointer to first entry to swap
; sp + 2 - Pointer to second entry to swap
;
; On output:
; nothing
;
; Registers clobbered
; none

proc Swap

push bp     ; Create stack frame
mov bp, sp

push di     ; Preserve all used registers
push bx
push ax
push cx

xor ax, ax   ; Zero register (not sure why you do this?)
xor cx, cx

mov bx, [bp+6]   ; Get pointer to first entry
mov di, [bp+4]   ; Get pointer to second entry

mov ah, [bx]     ; Read first value
mov ch, [di]     ; Read second value

mov [bx], ch     ; Write second value to first location
mov [di], ah     ; Write first value to second location

pop cx     ; Restore used registers
pop ax
pop bx
pop di

pop bp     ; Restore stack
ret

endp Swap

This is the same code as you posted above, just with comments and spacing.  It makes the code drastically easier to understand and follow.  And it's not like it makes the .exe file any bigger.  It also highlights one of those inefficiencies I mentioned (why are you zeroing ax and cx?).

There are several other changes I would make to this routine.

You do standard stack-frame code (push bp mov bp, sp), but why?  There is no benefit to doing this here, and it will make (what is likely to be) the busiest part of your code that much slower.
Using xchg, you can use 1 fewer register.
Your routine uses pascal (or cdecl) calling convention (who pops the registers that are passed to Swap?).  There is nothing 'wrong' with calling functions this way, but there are alternatives.  If you wanted to, you could follow the 'fastcall' convention, which passes parameters in registers instead of on the stack.  Not having to read/write memory is typically faster, and requires fewer instructions (which is also faster).  The fastcall rules also allow you to use ax without having to preserve it (since it's intended to be the return value).  The downside is that if you call a routine that uses this convention, you need to make sure you don't mind having it stomp on the values of any of these registers.

I don't have a 16bit environment to test this, but given the comments, I expect you'll understand the intent, even if I muck up the syntax somewhere.

Implementing 1 & 2:

proc Swap

push ax     ; Preserve all used registers
push bx
push cx

mov bx, [sp+4]   ; Get pointer to first entry
mov cx, [sp+2]   ; Get pointer to second entry

mov al, [bx]     ; Read first value
xchg [cx], al    ; xchg first value and second value
mov [bx], al     ; Write second value back to first location

pop cx     ; Restore used registers
pop bx
pop ax

ret

endp Swap

Note that xchg doesn't allow you to use 2 memory addresses, so you still need ax.  But this still uses fewer registers, so needs fewer push/pops.

How about implementing #3?  Instead of pushing the two pointers to be swapped onto the stack, what if we pass them in cx and dx?  This is the normal 'fastcall' method on 32bit (IIRC, the standard for 16bit was a bit different).  Likewise, ax is used to return the 'result.'  In our case, there is no result, so we can use the register however we want.

Is changing the way functions are called kosher?  Well... kinda.  Assembler allows you to pass parameters however you want (as long as both the 'caller' and the 'callee' agree upon the rules), and the CPU certainly isn't going to care.  On the other hand, if every routine you write uses a different method, it's going to make reading your code a nightmare (even with comments).

Generally what you want to do is pick 1 standard and use it for most or all of your code.  Picking one of the industry standards makes sense.  Obviously if your code needs to be callable from C, you must pick a standard that C supports.  But since your entire program is asm, that doesn't apply here.

In this example, I'm using the Microsoft Fastcall standard for 32bit code.  It's one I'm familiar with (although most of my recent code is 64bit).  Obviously before you can use this, you'd need to change the code that calls Swap.

So, that gives us:

; Swap - swap 2 variables in a list
;
; On input:
; cx - Pointer to first entry to swap
; dx - Pointer to second entry to swap
;
; On output:
; nothing
;
; Registers clobbered
; ax

proc Swap

mov al, [cx]     ; Read first value
xchg [dx], al    ; xchg first value and second value
mov [cx], al     ; Write second value back to first location

ret

endp Swap

You know what?  The code is getting pretty small here.  In fact, does it still make sense to have a routine for this?  Or should you just put this code in Split?  Putting this code 'inline' would make Split a bit bigger (since you call it 3 times), but avoiding the call/ret instructions can make things even faster.  That's a judgement call.

I realize I've only covered the first routine, but this answer is already 5 pages long.  That seems like enough to get you started.

Main takeaways should be:

Comments.
Either remove stack frames, or document why they are needed.
Decide what calling convention to use.  They each have benefits (preserve all registers, faster, callable from C, etc), so decide what is important to your program.
Consider inlining smaller routines.

While Cody never responded to my request for clarification, he does tend to be right about these things.

Still, I'm not going to remove the xchg from this answer.  Why?  Because making this routine small makes you start thinking about inlining it.  And once you think about inlining it, you look again at this code:

mov dh,[byte ptr bx]
cmp dh,[byte ptr di]
jae greater
push ax;offset to be swapped
push bx;offset to be swapped
call Swap

So before calling Swap, we not only had the pointers, we also had the values and knew they needed to be swapped.  Instead of pushing the pointers, preserving registers, re-loading the pointers re-reading the values, and restoring the registers, we could simply have written the swapped values:

mov dh,[byte ptr bx]   ; Read the first value
mov dl,[byte ptr di]   ; Read the second value
cmp dh, dl
jae greater            ; Are they correctly ordered?
mov [byte ptr bx], dl  ; Nope.  Swap them.
mov [byte ptr di], dh

So the question of how expensive xchg is drops out of the question.  It was useful as a step along the way, even if ultimately it doesn't get used.

BTW, using a Swap routine in a higher-level language like C still makes sense.  The C compiler can optimize this code and does the inlining for you.  That way you get the benefit of clearer code (breaking out the Swap function makes the intent clear) while still getting the best performance.

Since assemblers aren't going "optimize" or "inline" for us, we as assembler programmers have to decide for ourselves where to make the trade-off between discrete functions and performance.


As a general naming convention, go methods are either named LikeThis (for public methods) or likeThis (for package private methods). For a small, single file project like this it doesn't really matter too much, but it is a good habit to get into regardless.

Your openfile method should probably be named readFile, as it doesn't just open the file, it also reads every line in it. Further, you're forgetting to close the file when you are done with it. Go has a fairly clean way to ensure this will always happen: the defer keyword:

func readFile(filename string) (lines []string) {
    source, err := os.Open(filename)
    defer source.Close()  // Make sure we close the file

    ...
}

Your operate function can be written more cleanly; firstly, by recognising that the case if o == 0 is exactly the same in each branch, secondly by using a switch statement (which is more idiomatic in go):

func operate(operands []string, op string) float32 {
    result := getvalue(operands[0])
    for o := range operands[1:] {
        switch op {
        case "+": result += getvalue(o)
        case "-": result -= getvalue(o)
        case "*": result *= getvalue(o)
        case "/": result /= getvalue(o)
        default: return 0.0
        }
    }
    return result
}

Here, we get initialise result to the first value in operands. Then, we range over the rest of the elements in operands. This uses range, which should be preferred to manual for loops when you can use them, and also slicing off the first element of the slice.

Note that go does not need break statements in a switch, rather, it requires an explicit fallthrough (which stops probably the largest class of bugs when using switch statements).


Welcome!

You may be interested in viewing the Go API implementation of a linked list. Their implementation is not restricted to just integer node data.

Use go fmt

A few of your lines have trailing whitespace. Likewise, some of your formatting isn't standard for Go.

If you run go fmt on the source code, it cleans all that up for you.

Don't unnecessarily export things

Your type LinkedList is exported. If this is for a library, you should add a comment explaining it's usage (used to generate documentation: see Godoc). If it's not for a library, it shouldn't be exported.

Going forward, I'll assume it's not meant for a library. Otherwise the fields of LinkedList also need to be exported, and the node type as well.

Avoid extra typing when initializing a struct

When initializing a struct, you don't have to initialize the fields to values that would already be the default.

See §Composite Literals in the language specification for more details.

n := node{
    item: val,
    next: nil,
}

Can be written as:

n := node{
    item: val,
}

And

l := linkedList{
    first: nil,
    last:  nil,
}

Becomes

l := linkedList{}

Combine variable declarations:

We can combine multiple variable declarations under one var keyword.

var ptr2 *node
var ptr3 *node
var prev *node

Becomes either

var ptr2, ptr3, prev *node

Or

var (
    ptr2 *node
    ptr3 *node
    prev *node
)

I prefer the shorter notation most times when the variables are of the same type, but either is better.

Use the specific Printf verb

You use the %v verb, but here we know at compile time that we're printing integers. You can safely use %d instead.

Return an error instead of panic()ing

Unless you expect to always recover() from the panic(), you should return an error value instead. This is more common.

func (l *linkedList) swapLL() {
    if l.first == nil {
        panic("First element cannot be null")
    }

    if l.first.next == nil {
        return
    }

    //...
}

Becomes

func (l *linkedList) swapLL() error {
    if l.first == nil {
        return fmt.Errorf("List cannot be empty")
    }

    if l.first.next == nil {
        return nil
    }

    //...

    return nil
}

This now makes it easy to check for the error:

if err := l.swapLL(); err != nil {
    log.Fatal(err)
}

Conclusion

Here is the final source I ended up with.

package main

import (
    "fmt"
    "log"
)

type linkedList struct {
    first, last *node
}

type node struct {
    item int
    next *node
}

func (l *linkedList) add(val int) {
    n := node{
        item: val,
    }

    if l.first == nil {
        l.last = &n
        l.first = &n
    } else {
        l.last.next = &n
        l.last = &n
    }
}

func (l *linkedList) traverse() {
    for n := l.first; n != nil; n = n.next {
        fmt.Printf("%d ", n.item)
    }

    fmt.Println()
}

func (l *linkedList) swapLL() error {
    if l.first == nil {
        return fmt.Errorf("List cannot be empty")
    }

    if l.first.next == nil {
        return nil
    }

    ptr1 := l.first

    var ptr2, ptr3, prev *node

    for ptr1 != nil && ptr1.next != nil {
        //Allocate resources
        ptr2 = ptr1.next
        ptr3 = ptr2.next

        //swap
        ptr2.next = ptr1
        ptr1.next = ptr3

        //hook to the previous pair
        if prev == nil {
            l.first = ptr2
        } else {
            prev.next = ptr2
        }

        //advance
        prev = ptr1
        ptr1 = ptr3
    }

    return nil
}

func main() {
    l := linkedList{}

    l.add(10)
    l.add(20)
    l.add(30)
    l.add(40)

    l.traverse()

    if err := l.swapLL(); err != nil {
        log.Fatal(err)
    }

    l.traverse()
}

Hope this helps!


Reading a gzipped file with JSON data for thousands of users

It looks like your code is somewhat non-optimal.

In the case get_new_user is True, you call json.loads(line) once for the "UpdatedAt" test, and if that passes, you call it again, returning effectively the same value, to append the users list.
In the case of get_new_user is True, you call (datetime.today()-timedelta(1)).date() once for each user, yet it is effectively constant.  You should move this out of the loop.

You could refactor your code like this:

threshold = (datetime.today()-timedelta(1)).date()
for line in fin:
    user = json.loads(line)
    if get_new_user is True:
        if datetime.strptime(user.get('UpdatedAt'), '%Y-%m-%dT%H:%M:%S.%fZ').date() == threshold:
            users.append(user)
    else:
        users.append(user)

You are doing the get_new_user is True test for each user/line in the file.  That too is constant, and only needs to be done once.  It is a tiny gain, but you could put the for loop inside the if and else clauses.

if get_new_user is True:
    threshold = (datetime.today()-timedelta(1)).date()
    for line in fin:
        user = json.loads(line)
        if datetime.strptime(user.get('UpdatedAt'), '%Y-%m-%dT%H:%M:%S.%fZ').date() == threshold:
            users.append(user)
else:
    for line in fin:
        users.append(json.loads(line))

And maybe using some list comprehensions and a generator expression for fun ...

if get_new_user is True:
    threshold = (datetime.today()-timedelta(1)).date()
    users = [ user for user in (json.loads(line) for line in fin)
              if datetime.strptime(user.get('UpdatedAt'),
                                   '%Y-%m-%dT%H:%M:%S.%fZ'
                                  ).date() == threshold ]
else:
    users = [ json.loads(line) for line in fin ]

Or if you are truly brave ... almost a 1-liner:

threshold = (datetime.today()-timedelta(1)).date()
users = [ user for user in (json.loads(line) for line in fin)
          if get_new_user is not True or
             datetime.strptime(user.get('UpdatedAt'),
                               '%Y-%m-%dT%H:%M:%S.%fZ'
                              ).date() == threshold ]

I've left your if get_new_user is True: statement alone, but it is a little non-Pythonic.  Usually, you'd just use if get_new_user:, but those two statements are very different.  The first is true if and only if get_new_user is True whereas the second would be true when get_new_user contains any non-falsey value, such as: True, or "True" or 1, or 17 or "False", or [0], ... etc.


Single Responsibility

As written, parse parses data and sorts them. This is plain wrong. Same goes for bubbleSort which sorts and prints. I recommend to change parse to

long int parse(string line, vector<int>& numbers);

and use it as in

vector<int> data;
while (getline(file, line)) {
    long int iterations = parse(line, data);
    bubbleSort(data, iterations);
    printVector(data);
}

Kudos for not using namespace std!
The code seems to implement interrupted bubble sort correctly. I don't really understand the expected outcome of the assignment so no comments on the speed.


Grabs 10 bytes and converts it into a hex formatted string

It looks like you overcomplicate things. I don't see why do you need to build the string. You only use it for comparison (and immediately kill it after). Comparing integers is much simpler, especially that your bytes follow nice structure. Inspect bytes one by one, along the lines of (I might be getting even/odd bytes wrong, follow their wire order):

    if ((bytes[1] != 0) && (bytes[1] != 1)) {
        return "Error";
    }

    for (int i = 0; i < 10; i += 2) {
        if (bytes[i] != i) {
            return "Error";
        }
        if (bytes[i + 1] != bytes[1]) {
            return "Error";
        }
    }

    return bytes[1] == 0? "Off": "On";

If the message structure is coincidental, and you don't have such an algorithmic approach handy, I recommend to format expected messages as byte arrays, e.g.

    char off_msg[] = {0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00, 0x05, 0x00};

and memcmp them against bytes. Again, follow the wire byte order.


Ensure that a directory reflects a specified Git commit

The two calls to checkout look well to me.  They are simple method calls to self with no arguments, and I can easily see that both calls are the same.  You avoid making two identical calls to run_command(['git', 'clone', ...]).

The "something really obvious" might be a return:

def ensure_correctness
  if exist?
    return if correct_version?
    delete!
  end
  checkout
end


Have you considered using BackgroundWorker? It might save you some trouble.

However, it does use ThreadPool and you are better to create your own threads if you have any of the following requirements:

You require a foreground thread.
You require a thread to have a particular priority.
You have tasks that cause the thread to block for long periods of time. The thread pool has a maximum number of threads, so a large number of blocked thread pool threads might prevent tasks from starting.
You need to place threads into a single-threaded apartment. All ThreadPool threads are in the multithreaded apartment.
You need to have a stable identity associated with the thread, or to dedicate a thread to a task.

I add my comment to the answer of "Peter K." here as it seemed to please you.

  Mutex is a bit overkill as it works
  across multiple processes. One should
  use locks (i.e. Monitor) when there is
  no need to synchronize across
  processes. Anyway, I don't see here
  any need for the locks assuming that
  the bDoWork_Click() is always called
  from the UI thread. It only creates a
  new thread if the existing thread is
  not alive. However, the resources used
  by DoWork() must be protected with
  locks if they are shared with other
  threads.


Some suggestions

If you ignore the q your questions object is a list of sequential integers so might as well be an array. This will simplify the logic later on.

answers: [
    'd',
    'd',
    'a',
    'c',
    'a'
]

If you use an array as suggested above, then we can simplify this block quite a lot (also, use strict comparators!):

var resultArr = [];
        for (var p in ans) {
            var x = parseInt(p) + 1;
            var key = 'q' + x;
            var flag = false;
            if (ans[p] == 'q' + x + '-' + arr[key]) {
                flag = true;
            } else {
                flag = false;
            }
            resultArr.push(flag);
        }

    var results = [];
    for ( var i = 0; = < ans.length; i++ ) {
        var flag = (ans[p] === arr[i]);
        result.push(flag);
    }

This is daft unless you want to make certain it's not something other than a boolean;

if (results[i] === true) {}

if (results[i]) {}

It's much nicer to build HTML using jQuery than with Strings. And your for loop seems to have an unnecessary variable.

 var resultSet = $('<div>');
 var trueCount = 0;
 for (var i = 0; i < results.length; i++) {
    if (results[i] === true) trueCount++;
    resultSet.text('Question ' + (i + 1) + ' is ' + results[i] + ');
 }

If you're declaring multiple variables you can separate them with a comma.

var results = jQuiz.checkAnswers(),
  resultSet = $('<div>'),
  trueCount = 0;


1. Review

No docstring. What does this function do? What parameters does it take? What shape must the depth_image parameter be? What does it return?
In Python, there is no need for a semi-colon at the end of a statement (unless another statement follows on the same line) and it is best to omit it.
It seems that depth_image is required to have three dimensions, but only the coordinate 0 is used on the third dimension. It would be simpler if the function took a two-dimensional depth image. A caller with a three-dimensional image could pass depth_image[...,0].
The result is returned as a linear array rather than in the natural shape as a cols × rows × 3 array. This loses information about the shape of the image that might be needed by some callers. There's a comment that says this is "for convenience" but if so, the caller can easily call numpy.reshape.

2. Vectorize

As always with Numpy performance problems, an important step is to scrutinize all the loops that run in the Python interpreter (the for and while loops) to see if they can be vectorized. A loop running inside Numpy is usually hundreds of times faster than the same loop running in native Python.

In this case it should be straightforward: instead of looping over pixels and doing some operations on each pixel, apply those operations to the whole image and let Numpy worry about looping over the pixels.

We only need the 0 plane on the third axis, as discussed in §1.3 above:

depth = depth_image[..., 0]

Let's make a mask array of valid pixels:

valid = (depth > 0) & (depth < 255)

The z-coordinates of the result can be computed by using numpy.where to distinguish between valid and invalid pixels:

z = np.where(valid, depth / 256.0, np.nan)

For the other coordinates of the result, we need row and column coordinates for each pixel, which can be generated using numpy.meshgrid:

rows, cols = depth_image.shape
c, r = np.meshgrid(np.arange(cols), np.arange(rows), sparse=True)

Then we have:

x = np.where(valid, z * (c - self.cx) / self.fx, 0)
y = np.where(valid, z * (r - self.cy) / self.fy, 0)

The coordinate arrays can be stacked using numpy.dstack to produce the result:

return np.dstack((x, y, z))

If the caller really needs a linear array, they can flatten it using numpy.reshape.

3. Revised code

Putting this together:

def point_cloud(self, depth):
    """Transform a depth image into a point cloud with one point for each
    pixel in the image, using the camera transform for a camera
    centred at cx, cy with field of view fx, fy.

    depth is a 2-D ndarray with shape (rows, cols) containing
    depths from 1 to 254 inclusive. The result is a 3-D array with
    shape (rows, cols, 3). Pixels with invalid depth in the input have
    NaN for the z-coordinate in the result.

    """
    rows, cols = depth.shape
    c, r = np.meshgrid(np.arange(cols), np.arange(rows), sparse=True)
    valid = (depth > 0) & (depth < 255)
    z = np.where(valid, depth / 256.0, np.nan)
    x = np.where(valid, z * (c - self.cx) / self.fx, 0)
    y = np.where(valid, z * (r - self.cy) / self.fy, 0)
    return np.dstack((x, y, z))

I find that this is about fifty times as fast as the original code.


Add/Remove class on scroll depending on scroll length

The code can made very short.

$(window).scroll(function () {
    var scrollTop = $(document.body).hasClass('home') ? 510 : 293;
    $('#navigation-wrapper').toggleClass('navbar-fixed-top', $(this).scrollTop() > scrollTop);
});

There is no need of wrapping the code in $(document).ready() for binding events on window.
Use ternary operator
Use toggleClass() with second parameter to add/remove class based on a condition.


is my add method in binary search tree correct

It looks to be correct.

However this code can result in unbalanced trees (like if you add all numbers in increasing order).

To keep it balanced you can use the techniques described for self-balancing trees


Memoization of Fibonacci using generic Int => Int helper

For generic memoization I pretty much always use scalaz Memo but when I compute sequences, I personally prefer using the standard Scala Stream.

Stream naturally memoize every computed value. Your solution could be refactored as:

lazy val fib = {
  def f(a: Int, b: Int): Stream[Int] = a #:: f(b, a + b)
  f(0, 1)
}

scala> fib.take(10) foreach println
0
1
1
2
3
5
8
13
21
34

scala> fib(45)
res1: Int = 1134903170


If you crack argv using argparse you'll enjoy a couple of benefits, including you get --help for free.

Defining read & WRITE_MODE is maybe a little over the top, as open(f, 'w') is a standard idiom. Anyway, you have an opportunity to let with close files for you, if you like. For example:

    with open(filepath + ".enc", "wb") as write_stream:
        write_stream.write(encrypted_content)

You probably want binary mode: "wb" rather than "w".

Consider throwing an exception in place of calling exit(1).

For the filepath[-4:0] == ".enc" enforcement test you might write: filepath.endswith(".enc").

Here is a magic number, corresponding to len(".enc"): filepath[:-4]. Consider changing the enforcement test so it uses a regex, re.compile(r'^(.+)\.enc$'). Then you can use group(1) of the match object when specifying a file path.

The ioError identifier (or io_error according to PEP8) is accurate, but perhaps a bit long -- err would suffice. Better to use the "as" keyword:

except IOError as err:


I think it looks pretty good. One possible way to make it faster is in this part:

for ( int i = 0; i< k ; i++ ) {
    for ( int j = i; j< k ; j++ ) {
        int w = just_primes[i]+just_primes[j];
        if ( w >= 1000000 && w <= 2000000 ) {
            p = w - 1000000;
            conjunct[p]++;
        }
    }
}

Notice that for each value of justprimes[i] you are currently testing all values of justprimes[j] and after this you are testing if the sum is in the desired interval.

One way to work around this is by using a two pointer method that tells us the biggest possible value j can take for any value of i, and also by breaking out of the loop as soon as j becomes to small.

int high = k-1;
    for ( int i = 0; i< k ; i++ ) {
        for ( int j = high; j>=i ; j-- ) {
            int w = just_primes[i]+just_primes[j];
            if(w< 1000000) break;
            if ( w <= 2000000 ) {
                p = w - 1000000;
                conjunct[p]++;
            }
            else{
                while( just_primes[i]+ just_primes[high] > 2000000 && high > 0){
                    high --;
                }
            }
        }
    }

This seems to give a 15% speed boost in my computer.


In the third line, there's a let self = this;. I did that because I needed to access the Cat instance inside the img.click callback function.

Use an arrow function, which won't rebind this. The self alias can then be removed.

this.img.click = () => {
  this.count++;
  ...
}

Your examples don't save the Cats anywhere, access any properties on them, pet them, or otherwise interact with them -- if adding a cat to the DOM is all you need, the constructor doesn't need to attach anything to this (which is equivalent to exposing things as public properties).

  The Cat constructor adds a new cat in the HTML (it appends the cats div), using div, h1, img and p.

Putting that behaviour in the constructor is not ideal. People reading your code probably expect new Cat(...) to return a cat, but not necessarily for it to put that cat somewhere. Besides being unexpected, this isn't very flexible: what if I want to put a cat somewhere else on the page?

It's probably better to separate creating the cat (and its click handler) from actually attaching it anywhere. You could add another method in the Cat class, like this:

  attach(element) {
    element.append(this.catDiv);
  }

but I think all you need in this example is a function:

function createCat(name, picture) {
  let clickCount = 0;

  const $cat = $('<div/>');    // $var is just a naming convention for jQuery variables
  const $img = $('<img/>', { src: picture }).appendTo($cat);
  const $counter = $('<p/>').appendTo($cat);

  $img.click(() => {
    clickCount++;
    $counter
      .text(`You clicked ${name} ${clickCount} times.`)
      .css("font-size", "+=0.5");    // Most jQuery methods can be chained
  });

  return $cat;    // return the cat div, not yet attached to the DOM
}

$(function() {    // equivalent to $(document).ready(function() {
  const $main = $('#cats');

  $main.append(createCat('Kimmy', 'http://newmediarockstars.com/wp-content/uploads/2014/07/femcat.png'));
  $main.append(createCat('Logan', 'http://svoctopussy.com/wp-content/uploads/2013/02/Grumpy-Cat.jpg'));
});


Since all your patterns have similar structure, we only need to focus on one, e.g.

refresh_pattern -i (.+\.)?avg\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$

This pattern starts with (.+\.)?. This pattern says 'match any characters that end in a '.', but, the ? means that if nothing matches, then that's OK..... so, what the (.+\.)? really means is "Match something with a dot at the end, or match nothing".

This is apparently sensible, but, because the entire URL is not anchored to the start of the line (there is no ^) it really means "match anything".

For example, all of these URL's will successfully match:

http://www.avg.com/file.gz // we would expect this
http://avg.com/file.gz // we would maybe expect this
http://cravg.com/file.gz // we would not expect this
https://downloads.avg.com/file.gz // we would expect this
mailto:me@www.avg.com/file.gz // we would expect this
ftp://ftp.avg.com/file.gz // we would expect this

This is all beside the point, though, because whether we use (.+\.)? or not it makes no difference whatsoever (functionality wise).

It is possible that the squid regex engine is smart enough to identify that the (.+\.)? is useless, and it may optimize it out.... but, I doubt it.

So, you can remove all the (.+\.)? structures.

I believe that you should replace them with a \b which is a 'word break'. This will match things like http://avg.com/... and http://www.avg.com/... but it will not match http://cravg.com/.... I believe this is what you want.

It would likely be better to also anchor the regex to the beginning of the URL. If you can assume that it is an http or https URL then I would absolutely recommend that you include it as part of the regex. It will anchor the query well.

I will assume that the protocol could be https as well as http, in which case the match would be:

refresh_pattern -i ^https?//.*\bavg\.com/.*?\.(cab|exe|dll|ms[i|u|f]|asf|wm[v|a]|dat|zip|ctf|bin|gz)$

This change can be applied to all the refresh_patterns.   (replace (.+\.)? with ^https?//.*\b)


It is extremely difficult to understand what's going on in your code. Try to think of things the following perspective: the goal of programming is to tell other people what you want the computer to do. And what you want to do is match the template to the base as some location. So how can we make that clearer?

Rather than character-wise matching for the appropriate inversion, we can just invert the template and then we just have to match for equality. Suppose we have a function:

std::string invertDNA(std::string const& );

which flips A/T and C/G. Once we have that inversion, we're just searching for the inverted match_template in base:

std::size_t index = base_template.find(invertDNA(match_template));
if (index == std::string::npos) {
    std::cout << "None\n";
}
else {
    std::cout << index << '\n';
}

We've now reduced dozens of lines of loops and variables, which are error prone, into a one line standard algorithm which is very easy to both reason about and for other users to understand. I don't know anything about chemistry, but I get this!

For minor comments, avoid using namespace std; and keep your indentation consistent. You do not need variables for the string length, since you can always call .size(). Avoid comparing against true and false. That part can be if (!check) { ... } else { ... }


Adjacency List Graph representation on python

Here are two ways you could represent a graph with weighted edges in Python:

Represent a graph as a mapping from a node \$n\$ to a mapping from neighbouring node \$m\$ to the weight \$w\$ of the edge from \$n\$ to \$m\$:

graph = {
    0: {2: 4, 4: 60, 3: 23},
    1: {},
    2: {3: 4},
    3: {1: 10},
    4: {2: 15},
}

Represent a graph as a pair of mappings: one from a node \$n\$ to a list of its neighbouring nodes, and the other from pairs of nodes \$n, m\$ to the weight \$w\$ of the edge from \$n\$ to \$m\$:

graph = {
    0: [2, 4, 3],
    1: [],
    2: [3],
    3: [1],
    4: [2],
}
weights = {
    (0, 2): 4,
    (0, 4): 60,
    (0, 3): 23,
    (2, 3): 4,
    (3, 1): 10,
    (4, 2): 15,
}

Either of these representations should work fine. Representation (2) would be good if you need to iterate over all the edges at some point in your algorithm. Representation (1) is the simplest and probably best if you have no special requirements.

Answers to comments

You don't even need .keys() — in Python, iterating over a dictionary yields its keys, so you can write:

for m in graph[n]:
    # m is a neighbour of n

Yes, defaultdict is a useful technique for building graphs. In representation (1) you'd start with:

graph = defaultdict(dict)

and then add an edge from \$n\$ to \$m\$ with weight \$w\$ by writing:

graph[n][m] = w

In representation (2) you'd start with:

graph = defaultdict(list)
edges = {}

and then add an edge from \$n\$ to \$m\$ with weight \$w\$ by writing:

graph[n].append(m)
edges[n, m] = w


Is usage of friend class appropriate in this case?

Personally, I don't have major objections with that design. It gets the job done in a fairly straightforward way. But it does creates coupling, which might become a nuisance to you as the project grows. So another option with less coupling, as mentioned in comments, would be defining a default parameterized constructor:

class Object {
public:
    Object(<several params>);
private:
    <the data>
};

class Loader {
public:
    Object LoadObject()
    {
        // many fields of data...
        int a    = ...
        double b = ...
        std::vector<int> c = ...

        return Object(a, b, std::move(c), ...);
    }
};

In C++11, you also don't have to worry about unnecessary copies of complex objects such as a std::vector. You can make the constructor take a move ref, e.g.: std::vector<int> && vec and apply std::move in the call site.


Data Access Layer method with transaction handling

First and foremost, I would strongly suggest using an ORM (e.g., Entity Framework or nHibernate) rather than doing all this manual work to update the database.  ORMs take most of the drudge work away and generally make things much easier.

That aside, there are a few things I would change:

As much as possible, utilize the ADO.NET interface methods instead of creating concrete classes directly
While a commit must be performed before leaving scope, rollback happens automatically, so the catch block is unnecessary
The method should not take in BindingList, both because it only requires IEnumerable and because DAL code shouldn't have ties to view concerns
The SQL statement variable should be const
There is no need to prefix variables with sql - this smells like a form of Hungarian Notation

With that in mind, I would modify it to be more like the following:

public void InsertAttendance(IEnumerable<IAttendance> attendanceList)
{
    const string selectStatement = @"IF NOT EXISTS (SELECT Attendance.Atten_ID FROM Attendance WHERE Atten_ID = @aid) BEGIN INSERT INTO attendance (EID,PID,in_time,out_time,shift) VALUES(@eid,@pid,@inT,@outT,@shift) END ";
    using (var connection = new SqlConnection(db.ConnectionString))
    {
        connection.Open();
        using (var trans = connection.BeginTransaction())
        using (var command = connection.CreateCommand())
        {
            command.CommandText = selectStatement;
            var parameters = command.Parameters;

            parameters.Add("@aid", SqlDbType.Int);
            parameters.Add("@pid", SqlDbType.Char);
            parameters.Add("@eid", SqlDbType.Int);
            parameters.Add("@inT", SqlDbType.DateTime);
            parameters.Add("@outT", SqlDbType.DateTime);
            parameters.Add("@shift", SqlDbType.Char);

            foreach (var attendanceItem in attendanceList)
            {
                parameters["@aid"].Value = attendanceItem.AttendanceID;
                parameters["@pid"].Value = attendanceItem.PointID;
                parameters["@eid"].Value = attendanceItem.EmployeeID;
                parameters["@inT"].Value = attendanceItem.InTime;
                parameters["@outT"].Value = attendanceItem.OutTime;
                parameters["@shift"].Value = attendanceItem.ShiftType;

                command.ExecuteNonQuery();
            }
            trans.Commit();
        }
    }
}

Sadly, creating parameters is particularly painful using just IDbCommand, so I continued using the SqlParameterCollection members.

Additional questions/considerations:

Should PointID be char?  An ID suggests a numeric type.
Should ShiftType be char?  This name suggests an enum type, which I suppose you could choose to represent as a character in the database, but it could also be a numeric type.
The SQL statement no-ops if a record already exists, but the method gives no indication when this occurs.  This should probably be re-considered, since it fails to provide any feedback to the caller that the insert did not occur.
What is db?  It seems to be providing the connection string, but we only see the property reference.


Processor that would process an Object (say a message you received)

Not the answer you're looking for, but this bit of code casts msg twice: if(msg is T) { inner.Process((T)msg); }. You can cast it once by using as, e.g. var m = msg as T; if (m != null) inner.Process(m); Also if you're actually writing the if bit on one line (as I love to do for one-liners) then I don't see the point of using curly braces on that line, though I guess that's just a style issue. You didn't use it for the else part after all.

And I'm sure in "real life" you won't have a test called "Test1", so I won't say anything about that...


Use the Gateway or Unicast IP Address

For the case of checking if the VPN Connection is online or not, you could consider a solution that just returns a boolean value.

Secondly, I wouldn't do it by connection name, instead how about using either the gateway IP address or the unicast IP address?

public class OpenVpnConnection
{
    private IPAddress _gatewayIpAddress;
    private IPAddress _unicastIpAddress;

    public OpenVpnConnection()
    {
        _gatewayIpAddress = IPAddress.Parse("10.0.0.1");
        _unicastIpAddress = IPAddress.Parse("10.0.0.101");
    }

    public bool IsNetworkAvailable()
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if (ni.OperationalStatus != OperationalStatus.Up) continue;
            if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
            //if (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel) continue;

            // discard if the interface is not "virtual"
            //if (ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) <= 0) continue;
            //if (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) <= 0) continue;

            if (GetIpFromGatewayAddresses(ni).Contains(_gatewayIpAddress)) return true;
            if (GetIpFromUnicastAddresses(ni).Contains(_unicastIpAddress)) return true;
        }
        return false;
    }

    private static IEnumerable<IPAddress> GetIpFromGatewayAddresses(NetworkInterface nic)
    {
        return nic.GetIPProperties().GatewayAddresses
            .Where(ip => ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            .Select(ip => ip.Address);
    }

    private static IEnumerable<IPAddress> GetIpFromUnicastAddresses(NetworkInterface nic)
    {
        return nic.GetIPProperties().UnicastAddresses
            .Where(ip => ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            .Select(ip => ip.Address);
    }
}

You can take out sections of the code that you don't need, but I included both unicast and gateway options above.

You would then simply check if the connection is online by

var vpn = new OpenVpnConnection();
bool online = vpn.IsNetworkAvailable();

of course, you'll want to pass parameters and what-not, but this is simply to illustrate the idea of moving away from the connection name and using an IP address instead.

Putting it together

A quick and dirty way of piecing it together with you current code would look something like this

private static async void StartOpenVPN(string configFile)
{
    // Start OpenVPN on the config file...
    Process.Start("openvpn-gui", $"--connect {configFile}");

    var vpn = new OpenVpnConnection(); //of course, send parameters in your actual code
    while (!vpn.IsNetworkAvailable)
    {
        await Task.Delay(100);
    }

    Console.WriteLine("Connected!");
}

Rather than using a loop, you could consider using the NetworkChange.NetworkAvailabilityChanged Event instead.


By reviewing your code, the first thing that comes to my mind is a lot of if statements. You should try and keep those minimal by writing solutions to be as general as they can be.

Another thing that I don't like in your code is that you are doing manipulation of array passed to the function, instead of going out with a fresh one. It looks like this manipulation is what leads to a lot of ifs in the first place.

So main point on how you can refactor your code is that you initialize an empty array which will act as a result and then manipulate that code:

function stutter(arr) {
    const result = []

    for (let word of arr) { // for..of loop is a bit clearer to read
        result.push(word, word) // push can accept N arguments
    }

    return result
}

So by initalizing resulting array with an empty one, you cleared of a case that the argument array passed in is empty, because for..of loop won't do the looping at all.
I've used for..of loop here since it's less code, but you could also use the C-like for like you've written in your question. Note that that loop also wouldn't loop if the argument array was empty, therefor no need for the if(arr.length == 0).

By the way, I'm a bit puzzled with what exactly is the point of the last if you have in the code, but I think that with the refactoring I've provided, then there is no need for it at all.

Since you've asked for more JS way of doing this, here are two ways:

Using map and flat (this one won't run in Edge):

function stutter(arr) {
    return arr.map(x => [x, x]).flat()
}

Using just reduce:

function stutter(arr) {
    return arr.reduce((result, current) => [...result, current, current], [])
}

EDIT

As @AndrewSavinykh pointed out, the assignment is worded in such way that the original array should be mutated. If that truly is the case, and both Andrew and me are not misreading it, then the solution would be to  just reassign the result to arr and return arr (@JollyJoker pointed that previous answer was not correct) use splice (the code is updated for the first example, but same thing can be done for the other two):

function stutter(arr) {
    const result = []

    for (let word of arr) { // for..of loop is a bit clearer to read
        result.push(word, word) // push can accept N arguments
    }

    arr.splice(0, arr.length, result)
    return arr
}

On the other hand, I'd advise against input arguments mutation, because you can easily forget which function mutates the arguments and which not, so it can create some additional cognitive load while reading the code. Also, it goes against the principles of functional programming where you want your functions to be as pure as they can.


PHP: Overuse of date manipulation leading to convoluted code

I'll provide a snippet with some sample data to demonstrate a few of my suggested techniques.

Code: (Demo)

$incs=[
    ['order_date'=>'20171128','order_dispatch_date'=>'20171129','order_address'=>'Paris'],
    ['order_date'=>'20171128','order_dispatch_date'=>'20171129','order_address'=>'Munich'],
    ['order_date'=>'20171129','order_dispatch_date'=>'20171130','order_address'=>'London'],
    ['order_date'=>'20171129','order_dispatch_date'=>'20171130','order_address'=>'Cardiff'],
    ['order_date'=>'20171130','order_dispatch_date'=>'20171201','order_address'=>'New York'],
    ['order_date'=>'20171130','order_dispatch_date'=>'20171201','order_address'=>'Sydney']
];

$wednesday = array("Paris","London","New York");

foreach($incs as $inc){
    $order_date = DateTime::createFromFormat('Ymdhis', $inc['order_date'].'000000');
    $day_name = in_array($inc['order_address'], $wednesday) ? 'Thursday' : 'Saturday';
    $order_collection = new DateTime($adj_date=date('Y-m-d 00:00:00', strtotime("next $day_name {$inc['order_dispatch_date']}")));

    $interval = $order_date->diff($order_collection)->d;
    echo "\n{$inc['order_date']} - $adj_date = $interval";
}

Output:

20171128 - 2017-11-30 00:00:00 = 2
20171128 - 2017-12-02 00:00:00 = 4
20171129 - 2017-12-07 00:00:00 = 8
20171129 - 2017-12-02 00:00:00 = 3
20171130 - 2017-12-07 00:00:00 = 7
20171130 - 2017-12-02 00:00:00 = 2

Now for the fine points:

Because you state that every order_address is in the $wednesday or $friday array, then you should only be checking one of them for best efficiency.  This check will determine the day name that will be fed to strtotime() later.
When generating your DateTime objects, assign them zero-ed times.  This way php will not default them to the "current time" for the given date.  Performing this declaration will avoid getting deviations in the diff() value later.
strtotime() will correctly interpret your Ymd format, so no additional string preparation is necessary.
The syntax for your strtotime() call is a single parameter with next $day_nameand$inc['order_dispatch_date']` all in a single string.
You can sensibly save a line of code by chaining ->d to your $interval declaration.

Here is how I think your new code should look:

$wednesday = array("Paris","London","New York");

$res = RNCPHP\ROQL::query( "SQL QUERY HERE")->next();
while($inc = $res->next()) {

    $order_date = DateTime::createFromFormat('Ymdhis', $inc['order_date'].'000000');
    $day_name = in_array($inc['order_address'], $wednesday) ? 'Thursday' : 'Saturday';
    $order_collection = new DateTime(date('Y-m-d 00:00:00', strtotime("next $day_name {$inc['order_dispatch_date']}")));

    $interval = $order_date->diff($order_collection)->d;
}


Less efficient? It consumes more stack space, which shouldn’t be a problem for any dataset where a bubble sort would be appropriate.
With the latest version of the c# compiler, tuple deconstruction will allow you to swap the values with a single line of code (although it will probably be slower).
On a side note, I’m not clear on why you have a separate continue instead of having a lower conditional check. It’s the same thing.
Not sure if you know this, but you are examining already sorted elements with your recursive call. An “efficient” bubble sort moves the end position back one cell after each cycle.
Update: I did some rough testing your implementation, and get a stack overflow a bit after 8k items. Sorting 8k random numbers without reducing the end point took ~.75 seconds, sorting with reducing the end point took ~.70 seconds. Much better than I expected.  Using Moch Yusup modification to use a more traditional structure the time for 8k items was approximately the same, but it took 116.8 seconds for 80k items.
So, performance wise, within the usable range, recursion was functionally identical, but due to stack overflow the usable range is limited.  OTOH, the usable range and "not enough time to go get a cup of coffee" range are fairly close.
Just for comparison, I tried using the standard List.Sort method, which took .0003681 seconds for 8k items, and .006 seconds for 80k items...


As @e-sushi remarked in his answer: you're still vulnerable to header injections. Though his approach is rather complex, and (when applied to $email, not required if you validate the email address the way I do (explained further down), but for the subject, and message body, you could use these simpler, and (IMO, therefore) better ways to tackle the header-injection issue:

$mail->Body = str_ireplace(
    array("%0a", "%0d", '0x0A'), '',//PHPMailer replaces \r\n already for you
   'your string here...'
);
//a Core-function alternative:
$body = 'your string here';
filter_var($body, FILTER_SANITIZE_EMAIL);//will alter $body
$mail->Body = $body;

More details on the caveats/benefits of each approach can be found here. Because you're setting the $name along side the email address, too as the from of the email, you should pass the $name value to either one of these filters, too.

Your code is attempting to validate an email address using a regular expression that is, at best, slightly off. There is a built-in function that can validate email addresses, without an inaccurate, too restrictive and slow regular expression, called filter_var.

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
    exit('Invalid email');
}

The result is that, while your regex doesn't allow for: some.name@site.info to be used as an email address (even though it's valid), filter_Var will accept it.
Unlike your regex, which, because it uses the s modifier allows for line-breaks in your email (for some reason), this won't... not blindly.
If, however, you wish to keep on using a regular expression, here's a PCRE expression that is (almost) fully RFC822 compliant:

/(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)/

Source: ex-parrot

I think it's clear which one of the validations is the more elegant one...

The name ($name) is a trimmed version of the POST var. That's good, because you know that, if the strlen($name) > 2, you're not just counting whitespace. However, you still are counting possible whitespace-only input when validating the $comment variable.

I'd suggest additional processing on both of these values:

$name = trim(html_entity_decode($_POST['name']));
if (strlen($name) < 2 || !preg_match('/^[^\d]+\s*[^\d]*/',$name))
{//nobody is called R2D2 in real-life!
    exit('name is too short ( < 2 chars) or contains numeric chars');
}
$comment = trim(strip_tags(html_entity_decode($_POST['comment'])));
if (!strlen($comment))
{//empty comment
   exit('No comment supplied');
}

As you can see, I've also used html_entity_decode and, for the comments at least strip_tags to remove any markup that might have been passed. This is often overlooked, so if I were to post a comment saying:

&nbsp;<br/>&nbsp;

Even trim would see this as a valid comment, whereas it actually is little more than whitespace