You've gone from two easy-to-understand lines to six methods across three classes; hardly an efficient use of OOP. There is really no need to have the three classes Attr, Generator and MainGen, and they're so heavily interconnected as to suggest single class.

If you do want to use classes, I think you should have a World class, in which generate (covering Generator and MainGen) is a class method for creating a new world and the attributes (covering Attr) are a mix of class attributes and parameters to the class method. This would look like:

import random

class World(object):
    """The world in which the game takes place.

    Args:
      map (list of list of string): a representation
        of the world, a 2-D structure of single-
        character tiles.

    Attributes:
      map (list of list of string): the map supplied
        in the argument to __init__
      TILES (string): the characters to use for tiles.

    """

    TILES = '#*~o'

    def __init__(self, map):
        self.map = map

    def __str__(self):
        """Display whole map as 2-D grid."""
        return "\n".join("".join(row) for row in self.map)

    def render(self):
        """Generator to provide one tile at a time."""
        for row in self.map:
            for tile in row:
                yield tile

    @classmethod
    def generate(cls, shape):
        """Generate a new, random map.

        Args:
          shape (int or tuple of int): Either a two-tuple
            (x, y) or a single integer to use for both x
            and y defining the shape of the map to create.

        """
        try:
            x, y = shape
        except TypeError:
            x = y = shape
        return cls([[random.choice(cls.TILES)
                     for _ in range(x)]
                    for _ in range(y)])

Then when you play the game:

world = World.generate(100)
for tile in world.render():
    ...

This separates the world itself out from how the game needs it displayed. As a simple example:

>>> world = World.generate(5)
>>> print(str(world))
oo#~#
*oo~#
#o#o~
*o*#o
**#*o


Checking if a multi dimensional array's given property is empty or not for the whole collection

Style

Some points on your style

Don't forget to close the line with semicolons where appropriate.
Use const for variables that do not change.
Use let for variables that are scoped to the block.
Use for of loops when you do not need the index.
In JS the opening block delimiter { is on the same line as the associated statement. eg for(...) { // << { on same line
Even if its an example, always write code as functions, not as flat bits of code as in your example. The function name adds additional contextual semantic meaning and forces you to write in a style more akin to real world needs.
Use a space between

tokens and (, eg for (, if (foo) {.
operators and operands, eg 1 + 2, i ++
commas and expressions, eg a, b  (not that it applies in your example)

Typescript?

You have the question tagged typescript, yet the code is pure JS. If you wanted a typescript version you have not indicated, and personally apart from better IDE integration the additional complexity of typescript does not offer any benefit over well written JS.

Rewrites

With all things equal the best quality source code has the shortest line count.

Cleaning up of your code

Note that because the code is written as a function I have not needed to use an intermediate to hold the abstract "empty" state of members, removing 4 lines of code.

function populateIfMembersEmpty(members, prefix = "123 -") {
    for (const member of members) {
        if (member && member[3]) { return }
    }
    for (let i = 0; i< members.length; i++) {
        if (members[i] && members[i][2]) { members[i][3] = prefix + i }
    }
}

Alternatives

function populateIfMembersEmpty(members, prefix = "123 -") {
    if (! members.some(member => member && member[3])) {
        members.forEach((member, i) => {
            if (member && member[2]) { member[3] = prefix + i }
        });
    }
}

or

Does a member of members on the same line need to be named, or is a symbolic representation any less meaningful?

function populateIfMembersEmpty(members, prefix = "123 -") {
    if (! members.some(m => m && m[3])) {
        members.forEach((m, i) => m && m[2] && (m[3] = prefix + i));
    }
}

or

function populateIfMembersEmpty(members, prefix = "123 -") {
    if (members.some(m => m && m[3])) { return }
    members.forEach((m, i) => m && m[2] && (m[3] = prefix + i));
}

19 lines down to 4 may sound pedantic, but apply the same to a large code base and a monster source file of 10,000 lines can be a far more manageable 2,000 reducing the odds of a bug by 80%

As the only response you have so far got that has unnecessarily emphasized a confusing point, I will say your style is neither "very" hard (or hard) to read, nor is it uncommon. (Let alone "very" uncommon, meaning... unique? no! ).


Although the algorithms seems fine, there are issues with the choosen abstractions.

LeftView is a factory of lists, which are left views of an inner tree. LeftView is not a data structure itself, but a factory of it, configured by a list, that are converted to a tree -- too much responsability. Keeping in mind @abuzittin gillifirca advice, a good practise is to refactor factory methods in static, public, methods.

public final class BinaryTrees {
    public static List<T> createLeftViewList(BinaryTree<T> tree) { ... }
}

In your code, LeftView had his own tree representation. To better convey the idea of an algorithm, consider start with simple interfaces, followed by the algorithm itself. That way you get better readability and guarantee further reuse in real code.

public interface BinaryTree<T> {
    BinaryTree<T> left();
    BinaryTree<T> right();
    T element();
}

And than we fill it with runnable code.

public class BinaryTree<T> {
    public BinaryTree<T> left() { return left; }
    public BinaryTree<T> right() { return right; }
    public T element() { return element; }

    private BinaryTree<T> left, right;
    private T element;

    public BinaryTree(List<? extends T> bfsRepresentation) {
        final List<? extends T> items;
        items = new ArrayList<>( bfsRepresentation );
        create( items );
    }
    ...
}

The create method assumes that items is always random access list. Well, it is if we consider only the test methods. If it gets called with a very large LinkedList, you will get quadratic performance.

Consider copying the list in an java.util.ArrayList. An array, T[], should do the trick too, and its preferrable.

Last piece of advice, consider parameterized unit tests in JUnit. There's a good example how to use it in their github wiki.


Obtaining a target number only using the operations ×2, ×3, and +1

For each i = 0...number, your method stores a std::list containing
the complete sequence of intermediate numbers from 1 to i. Each list is created by
copying the list from the optimal predecessor and appending i.
Even for a single i, path[i] may be assigned a new list up to
three times.

That is a lot of copying which consumes a lot of time.
It can be improved by choosing a different data structure:
For each number, store only the "optimal predecessor".
This requires less memory and less copying.
 For the final number,
the sequence of intermediate numbers can then be reconstructed by traversing the predecessors from number to 1, and printing
the numbers in reverse order.

More remarks:

The use of integer types is not consistent. You use int64_t
at most places, but int i as the loop variable, and
INT_MAX as initial value. –
For n in the given range 1...10^6, int32_t is sufficiently large.
The initialization of all elements in min_steps to INT_MAX
can be avoided by testing i - 1 as predecessor first.
Coding style: There should be more space around operators
and keywords.

The function then would look like this:

void primitive_calculator(int32_t number)
{
    std::vector<int32_t> min_steps(number + 1);
    std::vector<int32_t> predecessor(number + 1);

    for (int32_t i = 2; i <= number; i++) {
        min_steps[i] = min_steps[i-1] + 1;
        predecessor[i] = i - 1;
        if (i % 3 == 0) {
            if (min_steps[i/3] < min_steps[i]) {
                min_steps[i] = min_steps[i/3] + 1;
                predecessor[i] = i/3;
            }
        }
        if (i % 2 == 0) {
            if (min_steps[i/2] < min_steps[i]) {
                min_steps[i] = min_steps[i/2] + 1;
                predecessor[i] = i/2;
            }
        }
    }

    std::cout << min_steps[number] << "\n";

    std::list<int32_t> sequence;
    for (int32_t i = number; i != 0; i = predecessor[i]) {
        sequence.push_front(i);
    }
    for (auto it = sequence.begin(); it != sequence.end(); ++it) {
        std::cout << *it  << " ";
    }
}

For number = 96234, this reduced the execution time
from 0.13 seconds with your code to about 0.001 seconds.

The measurement was done on a MacBook with this simple code:

int32_t number = 96234;
const clock_t begin_time = clock();
primitive_calculator(number);
const clock_t end_time = clock();
std::cout << "\ntime: " << float( end_time - begin_time ) /  CLOCKS_PER_SEC << "\n";


Unsubscribing Facebook admins and regular users from notifications

Verbosity of a controller is typically a signal of dubious design. As I see it, you have two sensible options:

If User and FacebookAdmin are two very different user entities: they should be treated in two separate controllers.
If User and FacebookAdmin are very similar (i.e. FacebookAdmin inherits from User): they can share the same controller but use always @user as variable. This way the code will be simplified dramatically.

What you should not have is a controller full of conditional branches, that will be an unmaintainable mess (and awful to test).


I find it annoying that you can't update both the IPv4 and IPv6 records in just one invocation of your program.

According to the usage guide at https://dns.he.net,

Hurricane Electric also provides a "what is my IP address?" service, at http://checkip.dns.he.net/ .  That way, your program wouldn't be relying on a second service provider.
Better yet, this dynamic DNS service automatically infers that you want to add a DNS record that refers to your current IP address, if you omit the myip parameter.

Autodetect my IPv4/IPv6 address:
% curl -4 "http://dyn.example.com:password@dyn.dns.he.net/nic/update?hostname=dyn.example.com"
% curl -6 "http://dyn.example.com:password@dyn.dns.he.net/nic/update?hostname=dyn.example.com"


Is my code overdesigned? Does it rely too heavily on interfaces?

Is my code overdesigned?

I think so ;)

  IChunk<T> is intended to be a grid object with a predetermined size.

public interface IChunk<T> : IGrid<T>
{
}

But a grid is already a grid object with a predetermined size:

public interface IGrid<T>
{
    Point Size { get; }
    T this[int x, int y] { get; set; }
}

I don't think you need IChunk<T>. Why not just use a IGrid<T>?

IGrid<T> is redundant here:

public class Mesh<T> : Grid<T>, IMesh<T>

Because IGrid<T> is already specified by IMesh<T>, you can't implement IMesh<T> without implementing all of IGrid<T>, because IMesh<T> : IGrid<T>.

I might be wrong, but it seems to me that "adding up" two terrains is a non-trivial operation that would be best rendered as a full-fledged method than in an operator for the terrain itself. Can you make an operator async?


Integer-to-string conversion using recursion

There are two bugs in printd():

The last character is an l instead of a semicolon.
If n is negative, it prints a negative sign before each digit.

Your itoa() also has a bug in handling negative input.  It always stringifies the absolute value of n.

Your strategy to use the return value to determine which array element to write to seems like a good idea.  I think it would be more user friendly, though, to say that you are returning the strlen() of the output.

int itoa(int n, char s[]) {
    int i = 0;

    if (n < 0) {
        s[0] = '-';
        return 1 + itoa(-n, s + 1);
    }

    if (n / 10) {
        i = itoa(n / 10, s);
    }
    s[i] = n % 10 + '0';
    s[++i] = '\0';

    return i; /* strlen(s), i.e. the next free slot in array */
}


Checking for certain values in a range of numbers

First, I would tell you to restructure the while into a do-while. This will allow you to run at least one iteration of your loop (for one-digit numbers), THEN see if you need to repeat. That will in turn allow you to avoid the additional double-checks to make sure you weren't ignoring one-digit numbers (which are currently performed unnecessarily on any number > 10 that honestly doesn't have a 1, 2, or 3 in it).

Other than that, I would suggest you break early. Use booleans instead of ints: once you know you have a 1, 2, or 3, don't keep checking digits for those values (meaning if you have all three you can exit the loop entirely; for 1000000000000000123, you're done looping through the divide/modulo loop after checking just the first three digits).

Lastly, you're making checks you already know are false. You're first checking if f1 > 0, then regardless of that result you're checking if f1 and f2 are > 0. Instead, try nesting ifs; once you know f1 > 0 you can check if f2 is also > 0, while if f1==0 you don't have to check if f1 > 0 and f2 > 0 because you already know it can't be true. Similarly, if any digit of f is 1, then the same digit cannot be 2 or 3, so as soon as you know what a digit is, continue to the next digit.

Try this (you may have to define bool; older C++ specs do not have it built-in):

unsigned long long a, b, f;

a = 1;
b = 100000000;
bool[] z = new bool[3];
int[] x = new int[7];
for(int i = a; i <= b; i++) {
        f = i;
        do{
            var c = f % 10;
            // test the most likely thing first; most digits are NOT 1-3
            if(c > 3 || c==0) { }
            //once you know the value (or know the value exists), stop testing
            else if(!z[0] && c == 1) {
                z[0] = true;
            }
            else if(!z[1] && c == 2) {
                z[1] = true;
            }
            else if(!z[2] && c == 3) {
                z[2] = true;
            }

            //this MAY be faster depending on proc architecture and compiler;
            //some CPUs have "arithmetic-in-place" instructions.
            f /= 10;
        } while(f != 0 && !(!z[0] && !z[1] && !z[2]));

        if(z[0]) {
            x[0]++;
            if(z[1]) { //1&2
               x[3]++;
               if(z[2]) //1&2&3
                  x[6]++;
            }
            else if(z[2]) x[4]++; //1&3
        }
        if(z[1]) {
            x[1]++;
            //we have already checked 1&2 and 1&2&3
            if(z[2]) x[5]++; //2&3
        }
        if(z[2] > 0) {
            x[2]++;
            //we have already checked 1&3, 2&3 & 1&2&3
        }

        //this is for conciseness and may not work depending on your C++ spec
        z[0] = z[1] = z[2] = false;
    }


I think the way to optimize it is to try an entirely different approach -- given a pattern that matches all the words in a set, and a new word to add to the set, how do you modify the pattern to match the new word as well?  Simple answer: as long as the non-wild characters in the pattern match the new word, leave them; otherwise change the pattern to have a wildcard at that position.  You could implement this either recursively or iteratively.

from typing import List

WILD = "*"

def build_common_pattern(words: List[str]) -> str:
    """Build a pattern matching all input words.
    WILD matches any single character."""
    pattern = words[0]
    for word in words:
        assert len(word) == len(pattern)
        for i in range(len(word)):
            assert word[i] != WILD
            if pattern[i] != word[i]:
                pattern = pattern[:i] + WILD + pattern[i+1:]
    return pattern

print(build_common_pattern(["aaa", "aab", "baa"]))

This is also a potential use case for functools.reduce:

def build_common_pattern(words: List[str]) -> str:
    """Build a pattern matching all input words.
    WILD matches any single character."""
    def union(a: str, b: str) -> str:
        result = ""
        assert len(a) == len(b)
        for i in range(len(a)):
            result += a[i] if a[i] == b[i] else WILD
        return result

    return reduce(union, words)


Listing all numbers that are more composite than every number less than it

The biggest thing that will gain you performance is breaking this up into two functions, one that gets the prime factor list of a number, and another that computes the total number of factors from a prime factorization (using This method). Using this, we get the following

def generate_primes(end):
    primes = []
    for i in range(2, end):
        for j in range(2, i):
            if i % j == 0:
                break
        else:
            primes.append(i)
    return primes

def prime_power_generator(x, primes):
    # Most of these steps will not be run.
    # The largest prime iterated to will be the largest prime factor of x
    # (not including x)
    for p in primes:
        if x % p == 0:
            times = 0
            while x % p == 0:
                times += 1
                x //= p
            yield times
            if x == 1:
                return

def number_of_factors_with_help(x, primes):
    answer = 1
    for power in prime_power_generator(x, primes):
        answer *= power+1
    return answer

def better_composite_count(limit):
    answer = [1]
    primes = generate_primes(int(limit**.5)+1)
    most_divisors = 0
    for x in range(2,limit+1,2):
        num_divisors = number_of_factors_with_help(x, primes)
        if num_divisors > most_divisors:
            most_divisors = num_divisors
            answer.append(x)
    return answer

By limit=10**5, this is clearly superior, taking .02 seconds, instead of 50 for the OP. However, there is a better way. These numbers have several properties that allow much more a much faster search. For any highly compoite n, the prime factorization of n:

contains consecutive primes starting with 2
with decreasing frequency
the largest prime factor has frequency 1 (except for 4 and 36)

There are very few numbers that satisfy these constraints, and computing them by their prime factorization means we don't have to factor them later. These insights leads to the following code:

def gen_primes():
    D = {}
    q = 2  # first integer to test for primality.

    while True:
        if q not in D:
              # not marked composite, must be prime
              yield q

              #first multiple of q not already marked
              D[q * q] = [q]
        else:
              for p in D[q]:
                    D.setdefault(p + q, []).append(p)
              # no longer need D[q], free memory
              del D[q]
        q += 1

def num_factors(prime_factorization):
    ans = 1
    for power in prime_factorization:
        ans *= power+1
    return ans

def composite_candidates(primes, limit, factors=(1,), num=2, candidates=None, idx=0):
    if candidates == None:
        candidates={1:1, 4:3, 36:9}
    if num < limit:
        if factors[-1] == 1:
            candidates[num] = num_factors(factors)
        # current exponent must be equal or less than previous one
        if len(factors) == 1 or factors[-2] > factors[-1]:
            # we either stay with current prime and increase exponent
            composite_candidates(primes,
                                 limit,
                                 factors[:-1] + (factors[-1] + 1,),
                                 num * primes[idx],
                                 candidates,
                                 idx)
        # or move to next prime
        idx += 1
        composite_candidates(primes,
                             limit,
                             factors + (1,),
                             num * primes[idx],
                             candidates,
                             idx)
    return candidates

def best_composite_count(limit):
    # primes up to the largest possible in a highly composite number
    primes = []
    prime_product = 1
    for prime in gen_primes():
        primes.append(prime)
        prime_product *= prime
        if prime_product > limit:
            break

    # generate numbers, and number of factors for numbers that might work
    candidates = composite_candidates(primes, limit)
    composites = []
    most_divisors = 0
    # its important that they are sorted to know current highest number of divisors
    for num in sorted(candidates.keys()):
        num_divisors = candidates[num]
        if num_divisors > most_divisors:
            composites.append(num)
            most_divisors = num_divisors
    return composites

This yields another similarly massive increase over the previous, and can sieve up to 10^30 in less than 5 seconds.


Bash script to truncate subject line of incoming email

Be sure to read the relevant RFCs that govern e-mail headers!  Specifically:

RFC 2822, Section 1.2.2: Header names are case-insensitive.
RFC 2822, Section 2.2.3: Header fields may be line-folded:

  2.2.3. Long Header Fields

  Each header field is logically a single line of characters
  comprising the field name, the colon, and the field body.  For
  convenience however, and to deal with the 998/78 character
  limitations per line, the field body portion of a header field can
  be split into a multiple line representation; this is called
  "folding".  The general rule is that wherever this standard allows
  for folding white space (not simply WSP characters), a CRLF may be
  inserted before any WSP.  For example, the header field:

Subject: This is a test

  can be represented as:

Subject: This
 is a test

Since your sed operates on the raw representation of the header, you will miss headers that are logically longer than subject_length characters long, but start with a physically short line.

What is your rationale for developing this filter?  Is the application that processes the incoming messages unable to handle long subject texts, or is it unable to handle long physical lines?  If it's the latter, maybe all you need is a filter that performs line folding, rather than truncation.
RFC 2047: Encoding mechanisms for non-ASCII headers.  A logical subject line

Subject: this is some text

… could also be represented physically as

Subject: =?iso-8859-1?q?this=20is=20some=20text?=

… or by many other representations.  Is your limit based on the number of bytes in the raw representation, the number of bytes in the UTF-8 representation, the number of Unicode characters, or something else?  You didn't specify clearly.  If you are truncating the raw representation, you might truncate a MIME-encoded header at a point that makes it syntactically invalid.


1. algo

I can see 3 areas of local improvements here:

for i in problem:
    Ncol=len(i)
    break

doing a loop to just set Ncol for the first element is really ugly. Since your list isn't empty just do:

Ncol = len(problem[0])

Now why 3 lines for this:

subproblem=[]
subproblem.append((substartR,substartc1,subnrow,subncol1))
subproblem.append((substartR,substartc2,subnrow,subncol2))

when you can create your list directly:

subproblem= [(substartR,substartc1,subnrow,subncol1),(substartR,substartc2,subnrow,subncol2)]

and last thing, learn about list comprehensions for things like this:

loc=[]
for i in range(Nrow):
    loc.append((i,mid))

that can be rewritten as

loc = [(i,mid) for i in range(Nrow)]

2. findmax / getvalue

As mentionned in comments, the indentation of return statement is off, but since the code works, I'm assuming that it's just a typo. Here:

for i in loc:
  if bestloc == None or bestval < get_value(i,matrix) :
      bestloc=i
      bestval= get_value(i,matrix)

return (bestloc,bestval)

get_value is a function created just for this method. It introduces a lot of overhead & doesn't improve readability either. Scrap it, "inline" & cache the value
set bestloc to the first value (and value is okay, but first one is the most logical choice) before the loop starts, so you don't have to test for None in the whole loop. For this we have to handle the "loc is empty" cornercase at start.

So rewrite function like:

def findmax(loc,matrix):
    if not loc:
        # get rid of the "loc is empty" case
        return (None,0)
    bestloc,bestval = loc[0]

    for i in loc:
       x,y = i  # unpack from i, no indice access
       mvalue = matrix[x][y]

       if bestval < mvalue:
          bestloc = i
          bestval = mvalue

    return (bestloc,bestval)

only one access to the matrix, no unnecessary test for None, no function calls, faster index access.

get_subproblem

Use chaining comparisons since row and col are tested twice (now you can group both conditions)
don't slice then return, return the slice

like this:

for i in sub:
    print(i)
    (start_R,start_C,num_of_row,num_of_col)=i
    if start_R <= row <start_R+num_of_row and start_C <= col <start_C+num_of_col:
        return matrix1[start_R:num_of_row,start_C:num_of_col+start_C]

if you don't care about the print you could unpack directly in loop:

for start_R,start_C,num_of_row,num_of_col in sub:


The general design of your example is correct, however there are some problems with how you have implemented the async code. Most notibly

Calling .Wait() on the Task returned by RunAsync() will block 'OnStart()'. Instead it should be done after cancellation in the OnStop() method. This would eliminate the need to use a ManualResetEvent
Task.WaitAll() should be replace with await Task.WhenAll()

More importantly you can achieve the desired behaviour much more simply by using a System.Threading.Timer. The TPL is needed only to perform parallel processing.

public partial class FtpLink : ServiceBase
{
    private Timer _timer;

    public FtpLink()
    {
        WebEnvironment.Instance.Initialise();
    }

    protected override void OnStart(string[] args)
    {
        Trace.TraceInformation("DatabaseToFtp service started.");
        _timer = new Timer(Process, null, 0, WebEnvironment.Instance.DatabasePollInterval);
    }

    protected override void OnStop()
    {
        _timer.Dispose();
        Trace.TraceInformation("DatabaseToFtp service stopped.");
    }

    private void Process(object state)
    {
        Trace.TraceInformation("Processing message files and firmware...");

        Parallel.Invoke(
            () => new Processor().ProcessMessageFiles(),
            () => new Processor().ProcessFirmware());

        Trace.TraceInformation("Processing complete.");
    }
}

If you want to ensure that the service waits for processing to complete before exiting, you can use a simple Monitor as shown in the answer to this question.


Retrieving the Currently Logged in User's Department

Overall, your code's fine. The only thing that really jumps out to me is that it clutters the global namespace with some variables; I'm not sure if that was intentional (such as if other code is then referencing those variables), but I'd try to avoid that if you can.

I understand your unease with the way the code is written, so I'm going to use the rest of this answer to (hopefully) address that concern, and then I'm going to offer some suggestions for making your code more concise and arguably more readable ...but that's admittedly a matter of personal preference.

Patterns for Asynchronous JavaScript

After working with any programming language for a while you'll start to recognize certain patterns for the "right" way to accomplish something. This is especially true of asynchronous JavaScript, which doesn't immediately mesh with the single-threaded synchronous coding mindset we programmers usually start with.

The biggest eye opener for me was to recognize that as soon as you've made your code dependent on the execution of an asynchronous function call, you should stop adding code to the current function, because when the asynchronous function actually executes, the current function will no longer be within the execution context.

// Anti-pattern: What NOT to do
function doSomething(){
    doSomethingAsync();
    doSomethingElse(); // Usually a logic error; doSomethingAsync() hasn't finished
}

Note that this also explains why you can't get a return value from an asynchronous function call.

// Another Anti-pattern
function doSomething(){
    var result = doSomethingAsync();
    doSomethingElse(result); // This is an even worse logic error!
}

The pattern for dealing with asynchronous dependencies is to move your dependent logic forward into the execution chain. This usually means passing callback functions to your asynchronous functions.

You're handing off the responsibility of executing the callback function to the new function ("Hey, you're in charge now; do this other thing once you're done.")

function doSomething(){
    doSomethingAsync(doSomethingElse);
}

Of course, to make the code more readable, you could mess with the structure of the parameters, such as by using objects with named properties...

function doSomething(){
    doSomethingAsync({whenDone: doSomethingElse});
}

function doSomethingAsync(options){
     // insert JSOM code here
     // ...
     clientContext.executeQueryAsync(
         function(){ // on success
             options.whenDone(); // if doSomethingElse wants parameters, could provide them here
         },
         function(){ // on error
         }
     );
}

Using Function Expressions

Now with all that being said, sometimes having to define multiple functions just to insert logic farther down the execution chain actually hinders readability.

A function that's only ever referenced once, and only because you need to pass it as a callback, isn't doing anything to keep your code DRY (Don't Repeat Yourself), and can make it more tedious to debug or map out the chain of execution events. For these reasons I'll often use inline function expressions instead of defined functions for callbacks.

Inline function expressions can replace your globally defined callback functions, such as onQueryUserSuccess, and onLoadPropertyFail.

I mentioned at the beginning of this answer that I dislike polluting the global namespace with variables. Using function expressions, I can refer to variables defined in the containing function without needing to attach them to the window object. (Read about closures in JavaScript to understand how this works.)

This is definitely a matter of personal preference, but I prefer the code reformatted into a single function with nested function expressions for the executeQueryAsync callbacks, like so:

function loadUserDepartment(){
    var property = "Department";
    var clientContext = new SP.ClientContext.get_current();
    var currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(currentUser);
    clientContext.executeQueryAsync(
        function(){ // successfully retrieved current user
            var currentUserName = currentUser.get_loginName().split("\\")[1];
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
            // retrieve UserProfileProperty...
            var targetUser = "DOMAIN1\\" + userName;
            var departmentProperty = peopleManager.getUserProfilePropertyFor(targetUser, property)
            clientContext.executeQueryAsync(
                function() { // successfully retrieved property
                    alert(property + " is " + departmentProperty.get_value());
                },function()(sender, args) { alert("Error: " + args.get_message()); }
            );
        },
        function(sender,args){ alert('Failed to retrieve user name.'); }
     );
}

Now I can understand why the above code might give you heartburn. It's essentially a nested decision tree instead of a sequence of straightforward (and readable) function calls. But it's much easier for me to trace the execution chain and understand what the code is doing at a glance, and there are no variables attached to the window object (...well, except for the containing loadUserDepartment function, but you could avoid even that by converting it to an immediately executing function expression (IEFE)).

Notice that within the scope of their containing functions, the calls to clientContext.executeQueryAsync are always the last lines of code to be executed, reflecting the pattern I discussed way back at the beginning of this post.


As requested by tomdemuyt. I'm posting my comments as an answeR:

You usually only use defineProperty in very specific cases. (let's say you wanted validation on age?) - in your case - I would not use it.

Op then asked:

  offhand can you think of anything outside of validation were it might be useful to use defineProperty?

Plenty of reasons:

non-enumerable properties,
frozen properties,
computed properties,
proxies (Create an object based on another object and mirror calls + observe).

There are a lot of good use cases - they're just not very common in the web because of IE8 yet. In your case (age) I would not use Object.defineProperty.


I see a couple of small ways to improve this.

DRY (Don't Repeat Yourself) the code. The code that runs on load is identical to the change event handler. So make it a function you can call from both places.
Decouple it completely from the markup by dropping the "org-*" classes. It may not be "orgs" with "categories" and "types" that you're trying to select, but, say, "cars" with "makes" and "models". The basic idea is simply that there's a primary select element, and it scopes (filters) a secondary select element.

For the second point, I'd use a custom data-* attribute on the primary select. You might call it data-secondary, and let its value be the ID of the secondary select element. E.g.

<select data-secondary="categories">...</select>
<select id="categories">...</select>

Now you can find all select elements that have an associated secondary select element, by saying $("select[data-secondary]"). From there, you can find that secondary, and use the current logic. The markup declares the relationship and behavior, while the code can stay completely generic.

I end up with code like this:

jQuery ->
  $("select[data-secondary]").each ->
    primary   = $ this
    secondary = $ "##{primary.data 'secondary'}" # find the secondary
    items     = secondary.clone()                # clone the secondary into memory

    updateSecondarySelect = ->
      scope = primary.find(":selected").text()
      secondary.html items.find("optgroup[label='#{scope}']").html()

    primary.on "change", updateSecondarySelect # set up the event listener
    updateSecondarySelect()                    # do the initial filtering

(I've changed to CamelCase, but that's not important; use whatever style you prefer)

Some extra error checking would be good (e.g. what happens if the secondary isn't found? If there's no optgroup matching the selected option in the primary, should the secondary maybe just be hidden? etc).

Here's a demo


def selection_sort(li, out=None):

I dislike the name "li," I think abbreviations are bad.

    if out is None:
        out = []
        li = li[:]

Rather then using the out parameter to do this, I suggest creating a seperate internal function which is called. Otherwise, it looks like the caller to the function might reasonable pass out = something, when its only meant to be used internally.

    if len(li) == 0:
        return out

Better to use if not li:

    small = min(li)
    li.remove(small)
    out.append(small)
    return selection_sort(li, out)

Its a little hard to gauge this code because you are doing two things you shouldn't, using recursion when its not necessary and implementing your own sort routine. But if you are doing so for learning purposes that's fine.

EDIT

Iterative solution:

def selection_sort(li):
    li = li[:]
    out = []

    while li:
        smallest = min(li)
        li.remove(smallest)
        out.append(smallest)

    return out

But why is this better than the recursive solution:

There is a limit to your stack space. If you try to sort a large list using this function you'll get a RuntimeError
Calling a function has extra overhead that iterating in a loop does not, the iterative version will be faster
A loop is usually easier to read then recursion. The while loop makes it easy to see whats doing on, whereas the recursive version requires some thought about the code to see the logic.


Calculate the number of primes in a range

Welcome to Code Review! Here are some suggestions.

Naming

Choose a better name than primes_2. I'm not clear on what this variable does.

Write some documentation

...in triple quotes at the top of your function. Describe its inputs and outputs.

Separate user input from processing

Put your calculation code in a separate function from your user input and output code.

Validation

If the user enters invalid input, consider looping until the input they provide is valid. Or, at least - return out of the function if it's invalid, instead of having a large else covering the rest of your code.

Increment-and-assign

Use x += 1 instead of x = x + 1.

Formatted output

Consider using this form instead:

print(f'Huh, fancy that! {len(primes)} is also a prime number!')


First of all one should be aware that most decimal fractions cannot
be represented exactly by a binary floating point number. For example,

let y = Double.pi.rounded(toPlaces: 3)

does not assign the number 3.142 to y but the closest number
which is representable in the IEEE 754 format for double precision
floating point numbers, which happens to be

3.141999999999999904076730672386474907398223876953125

If the purpose of rounding the number is to present a result to the
user up to a certain precision, then it is better to use a number
formatter instead, for example

print(String(format: "%.3f", Double.pi)) // 3.142

or NumberFormatter which is very versatile and can do the conversion
according to the user's locale settings.

In other cases (like working with monetary values) it may be more
appropriate to work with integers only (or DecimalNumber) to avoid all rounding issues.

Having said that, here are some remarks and possible improvements
of your method.

I have named different implementations rounded1, rounded2, ... so that all can be tested in the same
program.

I am not sure what the effect of

typealias Exponent = Int

in the protocol extension is, but the proper way to restrict an extension
is a where clause:

extension FloatingPoint where Exponent == Int {

    public func rounded1(toPlaces places: Int) -> Self {
        guard places >= 0 else { return self }
        let divisor = Self(sign: .plus, exponent: places, significand: Self(Int(pow(5, Double(places)))))
        return (self * divisor).rounded() / divisor
    }
}

Of course you don't need a restriction for your other variant:

extension FloatingPoint {

    public func rounded2(toPlaces places: Int) -> Self {
        guard places >= 0 else { return self }
        let divisor = Self(Int(pow(10.0, Double(places))))
        return (self * divisor).rounded() / divisor
    }
}

The first one looks a bit obfuscated, and relies on the representation
of the numbers as a binary mantissa with an exponent.
I would use it only if it gives a clear performance advantage.

So let's benchmark it! I used this simple
test code which rounds 10,000,000 numbers in the range 0.0 .. 10.0
to 1 .. 8 decimal digits:

let start = Date()
var sum = 0.0
for i in 1 ... 10_000_000 {
    let x = Double(i)/1_000_000.0
    for p in 1 ... 8 {
        let y = x.rounded(toPlaces: p)
        sum += y
    }
}
let end = Date()
let time = end.timeIntervalSince(start)
print(sum, time)

The results are added to prevent the compiler from removing function
calls whose result is unused, and to verify that all methods give
exactly the same results.

On a 3,5 GHz iMac, with the code compiled in Release mode, I got
the following timings:

rounded1:   2.66 sec
rounded2:   2.52 sec

so the "obfuscated" method is actually a tiny bit slower.

But we can improve the performance. As you said, there is a lot of type conversions in

let divisor = Self(Int(pow(10.0, Double(places))))

This can be improved a bit if we restrict the extension method to
the BinaryFloatingPoint protocol instead. This is not a severe
restriction, because all current floating point types (Float, Double,
CGFloat) conform to BinaryFloatingPoint. The advantage is that
a value can be initialized from a Double:

extension BinaryFloatingPoint {

    public func rounded3(toPlaces places: Int) -> Self {
        guard places >= 0 else { return self }
        let divisor = Self(pow(10.0, Double(places)))
        return (self * divisor).rounded() / divisor
    }
}

That makes it a bit faster:

rounded1:   2.34 sec

The bottleneck seems to be the pow function. Since places
will usually be a small integer, it might be worth to use
iterated multiplication instead:

extension BinaryFloatingPoint {
    public func rounded4(toPlaces places: Int) -> Self {
        guard places >= 0 else { return self }
        let divisor = Self((0..<places).reduce(1.0) { (accum, _) in 10.0 * accum })
        return (self * divisor).rounded() / divisor
    }
}

Here Double values are multiplied and the result converted to
the type of Self. This turned out to be faster than multiplying
integers or instances of Self.

This is more than 4x faster compared to rounded3 and needs only
a single type conversion:

rounded4:   0.49 sec


Overall this is good code, but there are several things that could be improved.
Encapsulation
The code should be encapsulated in an IIFE in order to isolate it from other scripts in the page, which, for example, could be using the same variable names.
Also the HTML should be surrounded by an element with a unique identifier (e.g. <div id="tip-calculator"> ... </div>) to allow selecting common elements, such as button or p, but also .tip or .total, which can appear elsewhere on the page outside the context of the calculator and adjust the selectors to represent that.
const button = document.querySelector('#tip-calculator button'),
    bill = document.querySelector('#tip-calculator #amount'),
    // ...

or
const tipCalculator = document.querySelector('#tip-calculator'),
    button = tipCalculator.querySelector('button'),
    bill = tipCalculator.querySelector('#amount'),
    // ...

Conventions
It is convention to use one const/let declaration per variable.
(Potential) bugs
The regex used to validate the bill value only forbids the letters A to Z. Any other non-digits or other errors (such as more than one decimal separator) are not caught. The service rating and number of people are not validated at all.
You should be explicitly converting the string values from the input fields into numbers. Currently you are lucky that you are only using multiplication and division on the value, so that the strings are automatically converted, but if you, for example, would addition you'd have an error ("1" + "2" === "12" not 3).
You are toggling the visibility of the paragraphs on each successful calculation, that so every second calculation does not show a result.
Other possible improvements
You are not using the variables tipAmount and totalCostPP outside the event handler (or even the final else block) and their value doesn't change in there, so it would be better to declare them as const inside that block instead of outside the function.
In order to simplify the validation and conversion of the number values you should be using <input type="number"> with appropriate min, max and step attributes. It automatically forces the user only to enter valid numbers and offers the valueAsNumber property which gives you the value already converted to a number.


I have reviewed your code and here is what I've found.

Use const references where practical

The code currently declares its addition function like so:

bigint& bigint::operator+=(bigint n)

This has two problems.  First it passes by value, so a new bigint is created on every call.  This is quite wasteful of both time and memory.  Second, it should actually be a const reference.

bigint& bigint::operator+=(const bigint &n)

Eliminate "magic values"

The values of 10000 and 9999 are sprinkled through the code, but they really ought to be a named constant instead, and specifically a named constant static member.

constexpr static int MAXVAL = 10000;

(I'm using the C++11 constexpr here, but it could be const if you're using some old compiler.)

Also use the same constant everywhere.  That is, instead of writing this:

if (*a > 9999)

write this:

if (*a >= MAXVAL)

The advantage is that the compiler can probably generate more efficient code because it only has a single constant instead of two.

Be wary of signed versus unsigned

The individual parts should probably be unsigned rather than signed.  Since the sole defined constructor only takes unsigned numbers, it's reasonable to assume that the constituent parts are also unsigned.

Avoid computationally costly operations if practical

If we have two "digits" (digits in quotation marks because they're really base 10000 rather than base 10), each with a maximum value of 9999, then the maximum sum is 19998.  This means that the carry can only be 1 or 0 and that the code can be rewritten to eliminate the computationally costly % operator:

{
    *a += *b + carry;
    if (*a >= MAXVAL)
    {
        *a -= MAXVAL;
        carry = 1;
    } else {
        carry = 0;
    }
    ++a; ++b;
}

Eliminate redundant condition checks

In the addition code, the first loop only ends if one of the iterators is at the end.  This means that the next couple of lines of code:

// If rhs has more digits than lhs
if(a == parts.end() && b != n.parts.cend())
{
    while(b != n.parts.cend())
    {

Can be simplified to just the enclosed while statement.

Extract identical code into a single place

The code for the addition of digits is repeated three places, which is a very strong hit that it should probably be made into its own member function.  One way to do it:

int bigint::digitAdd(int &a, int b, int carry)
{
    a+=b+carry;
    if(a >= MAXVAL)
    {
        a -= MAXVAL;
        carry = 1;
    } else {
        carry = 0;
    }
    return carry;
}

Use for rather than while where appropriate

With the function listed above, the first loop can be rewritten as:

for(carry = 0; a != parts.end() && b != n.parts.cend(); ++a, ++b)
{
    carry = digitAdd(*a, *b, carry);
}

It's already much simpler.

Make sure your constructor always works

If the value passed is 0 the constructor will create no members in the parts vector.  You might want to reconsider your logic for that case.

Make sure your operator<< does what you really want

Consider the case in which the value stored is 10007.  The current operator<< will print "17" which is probably not what is desired.


Contiguous elements of the list sum to K

// init
const arr = [1, 2, 3, 4, 5];
const K = 9;

// main
const getContiguousElementsSum = (arr, K) => {

It seems to me to be unnecessarily confusing to alias variable identifiers like this.

  if (arr.length === 0 || K < 0) {
    return null;
  }

I don't see this anywhere in the specification you've quoted. I would expect the function to handle K === 0 by returning [], and to give [-1,-2,-3] for getContiguousElementsSum([-1,-2,-3,-4], -6).

Also, since the specification doesn't say anything about error cases, I would assume by default that it should throw something (probably RangeError) if no matching subarray can be found.

  const found = arr.some(x => {
    sum += x;
    returnResult.push(x);
    return sum === K;
  });

It would be kinder to the garbage collector to just track indexes and use slice when you find a match.

  // recursive case
  return getContiguousElementsSum(arr.slice(1), K);

The overall complexity of this implementation is \$O(n^2)\$. It can be done quite easily in \$O(n \lg n)\$ in full generality using just arrays, and in \$O(n)\$ if you have an efficient set implementation, by using the property $$\sum_{i=a}^b A[i] = \left(\sum_{i=0}^a A[i]\right) - \left(\sum_{i=0}^{b-1} A[i]\right)$$To build an array of \$\left(\sum_{i=0}^a A[i]\right)\$ takes linear time; then either convert it into a set or sort it; and for each element in the array of partial sums you need to test for the presence of that partial sum minus the target.

And, of course, it can be done in \$O(n)\$ time with just arrays if you're guaranteed that the elements are positive, as described in janos' answer.


Converting an object to an array of objects

When defining propertyArray, you don't need to handle undefined explicitly.  (It would have been nice to use _.pluck(), but unfortunately it is designed to take arguments in the wrong order.)

_.object() is too delicious to pass up!  You basically reimplemented it as createObject().  The function that is passed to map() can be further simplified by currying.

var input = {
  key1: [ 'val1', 'val2', 'val3' ],
  key2: [ 'val4', 'val5', 'val6' ],
  key3: [ 'val7', 'val8', 'val9' ]
};

window.alert("INPUT:\n" + JSON.stringify(input, null, '  '));

function zipObj(obj) {
  var keys = _.keys(obj);
  var values = _.map(keys, function(k) { return obj[k]; });

  // Transpose the values matrix
  var valueSlices = _.zip.apply(_, values);
  return _.map(valueSlices, _.partial(_.object, keys));
}

window.alert("OUTPUT:\n" + JSON.stringify(zipObj(input), null, '  '));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

I suspect that var values = … could be simplified as _.values(obj), but I don't see anything in the Underscore.js documentation that guarantees that _.values(obj) will list the values in the same order as _.keys(obj), so I hesitate to recommend it.


Time complexity is \$O(n)\$ indeed. Since every input character must be inspected, this asymptotic is impossible to improve. However, it is possible to improve the constant. See below.
Space complexity is \$O(n)\$ indeed. However, it is possible to solve the problem is \$O(1)\$. Consider two iterators, one running left to right, and another running right to left. As long as the first iterator points a consonant, print it. As soon as it hits a vowel, scan the second iterator (right to left) until it finds a vowel, and print that vowel. Notice that this approach also doesn't need values and keys - and hence doesn't need to build them. This is how time complexity is also improved.
The line

sb.replace(num.intValue(),num.intValue() + 1,String.valueOf(values.get(count)));

is very hard to read. It is even harder to prove that it works correctly.


You're converting the matrix elements to int and then back to string without doing anything with the ints, so that's just wasteful.
Anyway, the usual way to transpose is zip. Demo including mock input:
input = iter('''3
1 2 3
4 5 6
7 8 9'''.splitlines()).__next__

matrix = [input().split() for _ in range(int(input()))]

for column in zip(*matrix):
    print(*column)

Output:
1 4 7
2 5 8
3 6 9


JavaScript function to convert decimal number to binary

Strictly speaking, the number parameter isn't decimal; it's just an abstract number.  (This is more a criticism of the terminology in your question title than of your code.)  On the other hand, it is very weird that you coerce the result into a number (101010) rather than returning it as a string ('101010').

The implementation strategy, using Math.pow(…, 2), strikes me as extravagant.  You should be able to do this more efficiently using just arithmetic:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number /= 2) {
        binaryArr.push(number % 2);
    }
    return binaryArr.reverse().join('');
}

… or the same thing using bitwise operations:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number >>= 1) {
        binaryArr.push(number & 1);
    }
    return binaryArr.reverse().join('');
}


Overloading email sender utility class methods take single or array arguments

Your code has a particular Code Smell:

  Too many parameters: a long list of parameters is hard to read, and makes calling and testing the function complicated. It may indicate that the purpose of the function is ill-conceived and that the code should be refactored so responsibility is assigned in a more clean-cut way.

One way to fix this code smell is by extracting the parameters to a EmailOptions class (or EmailDraft or something).

public class EmailOptions {
     private final List<String> recepients;
     private final List<String> cc;
     private final List<String> bcc;

     public void setHTML(boolean html) {
         this.html = html;
     }

     ...
}

Now that's only a stub but there's a lot you can add to it. You can even add a addReceipient(String email) method (also include some kind of e-mail validation if you feel like it).

In the end however, your method would just be this:

public void sendEmail(EmailOptions email) {
    ...
}

Which surely is easier to grasp than all those String parameters!


To pass a list of array arguments as individual parameters to a Python function, use the * operator:

TP1 = TensorProduct(*V)

This is equivalent to TensorProduct(V[0], V[1], V[2],...,V[n])


Algorithm

The solution is brute force. It has a time complexity of \$O(N R)\$ (where \$N\$ is a number of bulbs and \$R\$ a number of ranges) and I expect to take forever on a bonus input (I gave up after 5 minutes).

To get the correct solution you should first realize that flipping switches in [x, y] range has the same net result as flipping switches in [x, N) range followed by flipping switches in [y+1, N) range. Next, since the flippings commute, it doesn't matter in which order they are performed. Each flipping is an edge changing state of all switches to the right of it.

Which brings the correct solution, in pseudocode:

    set up a vector of integers representing edges
    for each input range (x, y)
        push min(x, y)
        push max(x, y) + 1
    sort the vector
    scan integers from 0 to N toggling state when the edge is crossed

The time complexity is down to \$O(N + R\log R)\$, including output (took less than 2 seconds on my system).


It's a short bit of code, but enough to work with, I think.  Here are some suggestions to help you improve your code.

Minimize the number of comparisons

There is not really a need to check both upper and lower bounds for each possibility if the comparisons are done in order.  That is, we could compare the incoming Freq to 60, then 140, then 180, etc.  That might look like this:

int FreqLookup(double Freq) {
    if (Freq < 60e6 || Freq > 6000e6) {
        return 0;  // or throw an error
    }
    if (Freq < 140e6) return 1;
    if (Freq < 180e6) return 4;
    if (Freq < 280e6) return 2;
    if (Freq < 460e6) return 3;
    if (Freq < 830e6) return 10;
    if (Freq < 1420e6) return 8;
    if (Freq < 2000e6) return 9;
    if (Freq < 2720e6) return 7;
    if (Freq < 4020e6) return 5;
    return 6;
}

Put constants in a structure

Having the constants in a structure allows the code to be more data driven.  Here's what I'd suggest:

struct FreqTableEntry {
    double freq;
    int divisor;
    operator double() const { return freq; }
};
static constexpr std::array<FreqTableEntry, 11> lookup {{
    { 60e6, 0 }, // error if below 60e6
    { 140e6, 1 },
    { 180e6, 4 },
    { 280e6, 2 },
    { 460e6, 3 },
    { 830e6, 10 },
    { 1420e6, 8 },
    { 2000e6, 9 },
    { 2720e6, 7 },
    { 4020e6, 5 },
    { 6000e6, 6 },
}};

Now we have a nice, neat, compile-time lookup table.  Note also that we can avoid division by simply using the full value in the table.

Use a standard algorithm

The std::upper_bound algorithm returns an iterator to the first entry that is greater than the given value.  We can use it:

auto it{std::upper_bound(lookup.cbegin(), lookup.cend(), Freq)};

It would be nice to simply return it->divisor but we have to handle a few special cases.  First, if the frequency is exactly 6000e6, we need to return 6.  Next, if the frequency is < 60e6 or > 6000e6, we need to indicate an error.  I've chosen to return 0 as an indication of error, but one could also throw if that's more appropriate.  Putting it all together we have this:

#include <array>
#include <algorithm>

int alt(double Freq) {
    struct FreqTableEntry {
        double freq;
        int divisor;
        operator double() const { return freq; }
    };
    static constexpr std::array<FreqTableEntry, 11> lookup {{
        { 60e6, 0 }, // error if below 60e6
        { 140e6, 1 },
        { 180e6, 4 },
        { 280e6, 2 },
        { 460e6, 3 },
        { 830e6, 10 },
        { 1420e6, 8 },
        { 2000e6, 9 },
        { 2720e6, 7 },
        { 4020e6, 5 },
        { 6000e6, 6 },
    }};
    // special case the last entry
    if (Freq == lookup.back().freq) {
        return lookup.back().divisor;
    }
    auto it{std::upper_bound(lookup.cbegin(), lookup.cend(), Freq)};
    if (it == lookup.cend() || it->divisor == 0) {
        return 0;  // could throw here as alternative
    }
    return it->divisor;
}

Provide a test program

It's often helpful to write a test program and to provide it to reviewers to make it clear what the program is expected to do and how it will be called.  I modified your routine slightly to return 0 as an error indication and made it a standalone function.  The test program in this case, was just to compare the original routine to the alternative (named alt) shown above:

#include <iostream>

int main() {
    for (double f{30e6}; f <= 6020e6; f += 10e6) {
        if (TunerLookUpTable(f) != alt(f)) {
            std::cout << "ERROR: TunerLookUpTable(" << f/1e6 << " MHz) = "
                << TunerLookUpTable(f) << ", but alt(f) = " << alt(f) << '\n';
        }
    }
}


Counting Divisors of a number with restrictions on the divisors

Code organisation

In order to improve the code performances, if could be a good idea to make the easier to understand and easier to change.

You could:

split your code into smaller functions
add documentation
add tests
reuse existing data structures such as collections.Counter.

We'd get something along the lines of:

from itertools import product
from collections import Counter
import time

def get_factors(n):
    """Get factor for integer n

    Return the factorisation of n as a dictionnary
    mapping prime factors to their exponents."""
    factors = Counter()
    d = 2
    while n % d == 0:
        n //= d
        factors[d] += 1
    d = 3
    while n > 1:
        while n % d == 0:
            n //= d
            factors[d] += 1
        d += 2
    return factors

def factor_m(p, q, lower, upper):
    """Return the number of unit fractions solutions to:
       p   1   1
       - = - + - with lower <= u <= upper
       q   u   v

    The equation is equivalent to ..."""
    factors = get_factors(q)
    start, end = p * lower - q, p * upper - q
    mod = -q % p
    total = 0
    for powers in product(*(range((2 * v) + 1) for v in factors.values())):
        number = 1
        for b, _power in zip(factors, powers):
            number *= b ** _power

        if start <= number <= end and number % p == mod:
            total += 1

    return total

t = time.time()
assert factor_m(2, 7, 0, 50) == 3
assert factor_m(5, 1775025265104, 355005053021, 710010106041) == 4101
assert factor_m(737, 1046035200, 1926400, 2838630) == 1
assert factor_m(105467, 1231689911361, 11678439, 23356877) == 0
print(time.time() - t)

Simple mathematical optimisation

A trivial optimisation can be added to the logic performing the prime decomposition: for all divisors d, d * d <= n. Thus we can stop the search earlier (and the remaining part is known to be a prime).

while n >= d * d:
    while n % d == 0:
        n //= d
        factors[d] += 1
    d += 2
if n >= 1:    # to avoid 1 as a factor
    factors[n] += 1

This makes the code only very slightly faster as the bottleneck is not in that part of the code.

Limit the number of operations performed/limit accesses to factors

When iterating over factors, you get the values to create range of exponents (0, 1, 2, ...) and then, in the loop, you zip this to the keys to generate the prime**exponent value.

You could feed into the product function, the values prime**exponent already computed so that you limit the number of operations (** mostly) and you access factors in a single place.

This would give something like:

def get_divisors_for_square_of(n):
    """"Generate all divisors for n^2.

    Use the factorisation of n and double the exponents."""
    factors = get_factors(q)
    powers_list = [[p**v for v in range(2 * v + 1)] for p, v in factors.items()]
    for powers in product(*powers_list):
       number = 1
       for p in powers:
           number *= p
       yield number

On my setup, this halves the computing time.

Final code

import itertools
import collections

def get_factors(n):
    """Generate factors for integer n."""
    d = 2
    while n % d == 0:
        n //= d
        yield d
    d = 3
    while n >= d * d:
        while n % d == 0:
            n //= d
            yield d
        d += 2
    if n >= 1:    # to avoid 1 as a factor
        yield n

def get_divisors_for_square_of(n):
    """"Generate all divisors for n^2.

    Use the factorisation of n and double the exponents."""
    factors = collections.Counter(get_factors(n))
    powers_list = [[p**v for v in range(2 * v + 1)] for p, v in factors.items()]
    for powers in itertools.product(*powers_list):
       number = 1
       for p in powers:
           number *= p
       yield number

def factor_m(p, q, lower, upper):
    """Return the number of unit fractions solutions to:
       p   1   1
       - = - + - with lower <= u <= upper
       q   u   v

    The equation is equivalent to:
        puv = q(u + v)
    or
        (pu-q) (pv-q) = q^2
    which boils down to finding divisors of q.
    Let a = pu - q, then u = (a + q) / p when it gives an integer
    which is when (a + q ) mod p == 0.
    Also, we want p * lower - q <= a <= p * upper - q.
    ....
    Solution for 2/7 are (u, v) = [(4, 28), (7, 7), (28, 4)].
    """
    start, end = p * lower - q, p * upper - q
    return sum(1
               for a in get_divisors_for_square_of(q)
               if start <= a <= end and (a + q) % p == 0)

if __name__ == '__main__':
    import time
    t = time.time()
    for i in range(5):
        assert factor_m(2, 7, 0, 50) == 3
        assert factor_m(2, 21, 0, 500) == 9
        assert factor_m(5, 1775025265104, 355005053021, 710010106041) == 4101
        assert factor_m(737, 1046035200, 1926400, 2838630) == 1
        assert factor_m(105467, 1231689911361, 11678439, 23356877) == 0
    print(time.time() - t)

I'll update the solution if I find other things.


Java reflection: Inject data generically and safely

Essentially you are after the answer to:

  Does this mean that anyone can just wrap another persons class, unless it is immutable, and inject data?

And you are not really interested in a review of your code... right? (By the way, your code looks neat, and covers the bases of your 'academic exercise' quite well).

Java reflection is a dangerous process. On the up-side, reflection is regulated by the Java security system, and it can be enabled or disabled depending on the site, situation, and whatever else people are worried about.

So, if someone has code in your JVM, then they have access to the internals of your program (assuming Java has a permissive setting for it's security - which is the 'default'). On the other hand, other languages (C, cough *cough*) have even more of a problem if someone has been able to 'inject' malicious code in to their program.

It is all about relative-ness. Relative to many languages, Java is quite safe, and it has ways of being even safer.

On the other hand, if you let someone untrusted run code on your JVM then you have bigger problems to worry about.... ;-)

For what it's worth, there are easier ways to produce problematic code, like deserializing 'malicious' instances of values, or simply manipulating the JVM classpath before the program launches.

It's all about perspective....


Read and display JSON results from Google Books API

Split search() up into two functions, each accepting only one method, and dispose of your if.
There's a little bit of religion around this, but HTML5 accepts both "naive HTML" and XHTML-compatible tag closure, so this:
<input type="text" name="search">

is also accepted as
<input type="text" name="search" />

and the latter is (1) more explicit on where the tag ends and (2) is more broadly compatible.
This:
request.form.get("search").upper()

does not benefit from get, because you don't provide a default. Either allow the crash on a missing parameter, i.e. request.form['search'], or provide a default to get, likely the empty string.
This:
search = lookup(search)

is ill-advised, because it swaps types on the same symbol. The input is a string and the output is a dictionary.
This:
url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=MYAPIKEY'

first should not hard-code your API key directly into the string, and second should not format any query parameters into the string. Instead, pass params={...} into get().
This:
except requests.RequestException:
    return None

is fairly catastrophic for the application's ability to tell maintainers and users what went wrong. You're going to want to log the exception, and translate it into an appropriate failure message returned to your own caller.
This:
requests.get(url)

should use the response in a with.
Your search.html template is deeply bizarre. Where I would expect to see a for, you've only shown the first and third items?
Ensure that you're telling the browser that your content is in Spanish.
This:
action='/lookup'

needs to use double quotes.


Enumerating text (ranges) vertically and horizontally

I would go with standard IEnumerator and IEnumerable, so it could be consumed as:

    static void Main(string[] args)
    {
        var template = new Template("foo", "bar", "baz", "qux");

        foreach (var row in template)
            Console.WriteLine(row.Text);

        Console.WriteLine();
        foreach (var row in template.Select(1, 3))
            Console.WriteLine(row.Text);

        Console.WriteLine();
        foreach (var row in template.Select(0))
            foreach (var column in row)
                Console.WriteLine(column.Text);

        Console.WriteLine();
        foreach (var row in template.Select(0))
            foreach (var column in row.Range(0,3))
                Console.WriteLine(column.Text);
    }

Where Select allows to subset by indecies provided, while Range is working in terms of start and count. Row and Column objects have Index (current selection) and Indecies (allowed to be selected) properties:

public class Template : IEnumerable<Row>
{
    public Template(params string[] lines)
    {
        Lines = lines;
    }

    public IEnumerable<Row> Range(int start, int count) => Select(Enumerable.Range(start, count));
    public IEnumerable<Row> Select(params int[] indecies) => Select(indecies as IEnumerable<int>);
    public IEnumerable<Row> Select(IEnumerable<int> indecies)
    {
        foreach (var index in indecies)
            yield return new Row(Lines.ElementAtOrDefault(index), index, indecies);
    }

    public IEnumerator<Row> GetEnumerator() => Range(0, Lines.Length).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    string[] Lines { get; }
}

And:

public struct Row : IEnumerable<Column>
{
    public Row(string text, int index, IEnumerable<int> indecies)
    {
        Text = text;
        Index = index;
        Indecies = indecies;
    }

    public string Text { get; }
    public int Index { get; }
    public IEnumerable<int> Indecies { get; }

    public IEnumerable<Column> Range(int start, int count) => Select(Enumerable.Range(start, count));
    public IEnumerable<Column> Select(params int[] indecies) => Select(indecies as IEnumerable<int>);
    public IEnumerable<Column> Select(IEnumerable<int> indecies)
    {
        foreach (var index in indecies)
            yield return new Column(Text.ElementAtOrDefault(index), index, indecies);
    }

    public IEnumerator<Column> GetEnumerator() => Range(0, Text.Length).GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

And:

public struct Column
{
    public Column(char text, int index, IEnumerable<int> indecies)
    {
        Text = text;
        Index = index;
        Indecies = indecies;
    }

    public char Text { get; }
    public int Index { get; }
    public IEnumerable<int> Indecies { get; }
}


I don't think you should hard-code the length of alphabet as 26 here:
for (int i = n; i < 26; i++)

Doing so will make it harder to adapt this code to languages with a different number of letters.  Instead, prefer to use alphabetL.size() and alphabetS.size() (and probably use separate loops, as some languages don't have the same number of upper-case and lower-case letters).

It's probably advisable to test that n is less than the alphabet length (or to reduce it modulo length before using), and perhaps reject a zero shift (which is what we call a "weak key" for this cipher).

decrypt() is much slower than encrypt, because it does a search for every character.  What you really want is a pair of maps, but not lowercase and uppercase - instead you want forward and reverse (with both upper and lower in the same map).  In fact, I'd go further; allow negative values for the shift, and then we can create a separate Cipher object for the decryption.

Constructor that can accept a single argument should be explicit.  I don't think a default of 0 is a good choice (see my comment about weak keys).  Also, prefer initialization to assignment in constructors (GCC will warn, with -Weffc++).

Cipher::n is never initialized or used - we can drop that member.  Also, the two constant vectors don't need to be members - they are used only in the constructor, where they can be shared between all instances.  We can simplify further by making them string literals.

encrypt() and decrypt() both take a modifiable reference to their input, but it seems they should not modify the input string.  You could pass a reference to const string, but I think it might be easier to accept a copy by value, and modify the copy.
Also, they shouldn't be modifying the Cipher object, so they can be declared const.

Modified code
Here's what I came up with:
#include <algorithm>
#include <unordered_map>

class Cipher
{
    const std::unordered_map<char, char> map;

public:
    explicit Cipher(int n);
    std::string encrypt(std::string) const;

private:
    static std::unordered_map<char, char> make_map(int n);
};

Cipher::Cipher(int n)
    : map{make_map(n)}
{}

std::unordered_map<char, char> Cipher::make_map(int n)
{
    // helper function to give a positive value for a%b
    auto mod = [](int a, int b){ a %= b; return a < 0 ? a + b : a; };

    std::unordered_map<char, char> map;
    {
        static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int const m = sizeof alphabet - 1; // subtract the final NUL
        for (int i = 0;  i < m;  ++i) {
            map.insert(std::make_pair(alphabet[i], alphabet[mod(i+n,m)]));
        }
    }
    {
        static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
        int const m = sizeof alphabet - 1; // subtract the final NUL
        for (int i = 0; i < m; i++) {
            map.insert(std::make_pair(alphabet[i], alphabet[mod(i+n,m)]));
        }
    }

    return map;
}

std::string Cipher::encrypt(std::string s) const
{
    std::transform(s.begin(), s.end(), s.begin(),
                   [=](char c){ auto it = map.find(c); return it == map.end() ? c : it->second; });
    return s;
}

I slightly modified the test program to allow it to accept command-line arguments (easier for test scripts):
#include <cstdlib>
#include <iostream>
int main(int argc, char **argv)
{
    int num;
    if (argc > 1) {
        char* pos;
        num = std::strtol(argv[1], &pos, 0);
        if (*pos || pos == argv[1]) {
            std::cerr << "Usage: " << argv[0] << " NUM WORD" << std::endl;
            return 1;
        }
    } else {
        std::cout << "Enter by how many numbers you want to shift alphabets: ";
        std::cin >> num;
        std::cin.ignore();
    }
    Cipher cipher(num);
    Cipher decipher(-num);

    std::string str;
    if (argc > 2) {
        str = argv[2];
    } else {
        std::cout << "Enter string: ";
        std::getline(std::cin, str);
    }

    std::string res = cipher.encrypt(str);
    std::string decrypted = decipher.encrypt(res);
    std::cout << "Encrypted String: "
              << res << '\n'
              << "Decrypted String: "
              << decrypted << '\n';
}


Use lowercase tag names and attributes

Quoting Quentin from "Is it bad to use uppercase letters for html tags?":

  The only relevant parts of specifications say:

  HTML tag and attribute names are case insensitive.
  XHTML tag and attribute names are case sensitive and must be lower case

  Stuff that isn't mentioned in any standard:

  Lower case is generally considered easier to read
  Lower case is most common (and what people are used to working with)
  Holding down the shift key or toggling CAPS LOCK all the time is a pain

Don't use onsubmit attribute

It's a rather bad code style to still use attributes like this one, these days. For example, that way the submit event would not be raised by form.submit() function, which you may want to use later. Use addEventListener() instead, it's supported even by IE9+.

Don't use deprecated language attribute of script tag

Not only it is deprecated and it's not used anymore, but also a standard regarding this attribute's values never existed. You should use type="text/javascript" instead or no attribute at all, since in HTML5 in case of lack of specification of language used by script tag, it is assumed to be JavaScript, anyway.

Randomness source and distribution

Your function randomInt() uses Math.random() to obtain random values in a manner that will give you non-uniform distribution of returned values. It should also be noted, that it provides non-cryptographically secure randomness, although this is not a problem in this case.

Comments

Not all comments are useful, especially this invalid one:

var encryptedText = []; // the decrypted pieces of text.

Global scope

You shouldn't declare variables in the global scope, like you did between the two functions you made. Break that code into another function or combine with already existing ones, if appropriate.

Use map()

This

var encryptedText = []; // the decrypted pieces of text.

for (var i = 0; i < text.length; i++) {
  encryptedText.push(window.btoa(text[i]));
}

could be shortened to one, very straight-forward line:

var encodedText = text.map(window.btoa);

Use .textContent instead of .innerHTML

Since you don't want nor need to have your string parsed, you should use .textContent property instead of .innerHTML.

Inconsistent quotation marks

You mix single ('') and double ("") quotation marks. Use single ones, except where it would force you to escape what's between them.

Dot notation

This

var form = document.forms['game']['text'];

would look better and be written by most as:

var form = document.forms.game.text;

Use strict equality operator

You should use strict equality operator in your code, as it doesn't performs type conversion and is generally considered a good practice.

Don't location.reload()

You don't need to location.reload(), just reset() the form.

Don't encode before necessary

Currently you are encoding all strings before they are even randomly chosen. There is no need to do that. What if there were thousands of strings? Reverse the order of operations, first choose random string and just then encode it. That way, you won't even need to store results of encoding, by the way.

Naming

What you do is encoding and decoding with Base64, but one variable is named encryptedText. Comment on the same line have exactly the same naming issue. There is no encryption involved in your code, at all.

Replace two location.reload()s with one

You could remove two instances of location.reload() that you have in your code and add just one below the chain of conditional checks.

Edit: Although remember that even this one location.reload() should be replaced with form resetting, as mentioned before.

Empty string submission check

Instead of checking if (input === '') you could add required="" attribute to your input tag.


Changing background color of HTML elements based on user input

The first thing that jumps out at me is the tight coupling it has with the current application in which it is being used.  Why hard code all those CSS selectors?  This class really cries out for configuration.

You might see a pattern like this used to achieve decoupling of class from config.

function ArticleQuiz($el, $config){

   this.config = {};
   ...
   init() {
       $.extend(this.config, this.defaultConfig, $config || {});
       ...
   }
   this.init();
}

ArticleQuiz.defaultConfig = {
    answerDataLabel = 'answer',
    answerContainerSelector = '.answer-container',
    ...
}

You should consider taking the approach of using meaningful class names to apply multiple CSS styles at once.  So, rather than using specific semantic color and font class names, define a CSS class that encapsulates the entire state of being a correct/wrong answer.  So taking this approach along with the suggestion to store configuration something might allow you to change this:

        $(this).addClass('background-' + ((THIS.answer === false) ? 'green' : 'red')).addClass('white-font');
        THIS.result.addClass('font-' + ((THIS.answer === false) ? 'green' : 'red'));
        answer =  THIS.answer ? THIS.incorrectAnswer.show() : THIS.correctAnswer.show();

Into something like:

       var classToApply = THIS.config.correctAnswerClass;
       if(THIS.answer === true) {
           classToApply = THIS.config.incorrectAnswerClass;
       }
       $(this).addClass(classToApply).show();

Your QuizLogic function would not seem to have reason to be in the static (prototype) context, as you are using it as a constructor for your class. I would think this function should be within class function scope instead on prototype and should be call something like init() or similar common name for constructors in javascript.  Note how I present the init() function in my first code example above.

Consider first populating your instance properties in the constructor rather than in the main class code.  This gives you the ability to do things such as validate that the selectors do not return empty collections and similar activities needed to put the object in the proper state for use. If these validations fail, you could throw an error to prevent the object from being used in an improper state.


Configuring a date picker with support for disabled dates

You don't need to build the options object in one go instead create what all cases need and then optionally add:

options = {
    firstDay: 1,
    dateFormat: "dd.mm.yy",
    altField: '#reservation_dates_input',
};

if (disabled_dates.length>2) {
    options.addDisabledDates = disabled_dates_array;
}
if (reservation_dates_input.length>2) {
    options.addDates = reserved_dates_array;
}

you also have some code duplication when creating the arrays, you can put that in a function and call it twice:

function createArrayFromInput(dates_input){
    if (dates_input.length) {
        var clean_dates = dates_input.replace(/\"/g, '');
        return clean_dates.split(", ");
    }
    return [];
}


Avoid iteration on complete list to find (fuzzy) matching string

Fuzzy-wuzzy is poorly optimized for that kind of use.

What you can do is use fuzzy-wuzzy functions to construct your own ratio function.

The biggest boost you will get if you will use any caching for master_category tokenization. If you are on python3 you can use functions.lru_cache and if memory allows you I would suggest making it the size of len(master_categories)+1.

This is a small change and it will increase memory usage a lot, but as a result speed of calculation will also be boosted a lot.

also since you need just 1 master_category per each category, just break your loop as soon as you find one.

for category in categories_received:
  for master_category in master_categories:
    if fuzz.ratio(category, master_category) > 95:
       response[category] = master_category
       break


PHP and MySQLi login script - is it secure / am I doing something wrong?

So after reading through your question, I noticed that you seem very concerned about the "security" of your web application. I'll do my best to share what knowledge I can muster up!

However, there are a couple key things I think need to be cleared up before we touch on the safety of your data.

  I haven't really used MySQL (especially OOP)

Cool! Good to hear that you're expanding your horizons :)

But... Don't be mistaken and call your code object oriented. There's a lot more to the pattern than simple calling an object's methods.

Don't think that we can write up an entire website procedural style, and then make one call to $object->method() and have it all of a sudden be object oriented! Object orientation means a separation of concerns in different class/interfaces.

It's too hard to give you one or two links that will magically "show you the way". I'm afraid you'll just have to read and practice until you can compare your code to other OO code, and say, "Wow, my code really looks object oriented!"

  I don't trust my knowledge of SQL

That's good! Don't ever publish something without having a second pair of eyes check your work.

When was the last time you wrote an essay without spell check turned on?

Okay, so, how secure is your code?

Well, from the comments, I'm sure you already realize there's something wrong with giving the user $stmt->error.

But, why is this bad?

Well, there are two main issues with it:

It's not user friendly. Kind of cheesy, but the guys on UX.StackExchange wouldn't be disagreeing with me. When you visit any major website, have you ever seen an error complaining the database connection failed on host 8080 on line 482? Of course not! The user doesn't need to know that information.

All the user needs to know is: how can I fix the problem. Most of the time this will just be "Try again later", sometimes it can be your browser telling you that you don't have an internet connection! Does the user need to know that the application couldn't bind the parameters to the query? What the hell does that even mean to the average user!

So now that we know all this, what should you do? Throw out all those errors that say you can bind parameters or prepare the query. All you need to tell the user is something such as: "Sorry, we couldn't execute your command" or whatever. The exact message will depend on the users, and you may need to do some A/B testing.
It in fact does assist any attack. Oh, so when I inject this SQL into the POST, it breaks on that step, that must mean the code is vulnerable there!

Here's a good read on StackExchange's information security site. There are tons of questions relating to your issue already. I'm not joking, there's a lot of relevant information for you! Did you ask for another sweet Q&A to read, because this one might help.

A Google can tell you a lot more than I can summarize here. A synopsis though: how much error message you show does depend on your site, but in general, it's best not to show the attacker a better way to attack!

Congratulations on discovering the security / user experience trade off!

OK, is there anything else that's insecure about this code? Well, unfortunately, nothing else pops out at me. Don't think that that means your code is safe though!

Any other comments from me? Yep!

Avoid die(). It's really not user friendly to kill the page when things go wrong.
Use brackets {, }! The language has them for a reason, and it was ridiculous to implement the shorthand.
It's always weird to read lot's of logic inside a switch's case. I'd see about refactoring that so you're not doing such large operations inside the statement.
When you secure passwords, which you will... I recommend using PHP's password_hash() utilities. It's probably the safest option for password storage at this point in time.
Over all, I'd look at trying to implement a database access layer into your application. I'd say the most well respected is Doctrine, but of course, do what the project calls for.

Hopefully that helps :)


Select multiple rows using multiple data attribute

The performance benefits vary depending on the browser's implementation of ECMAScript, but you can usually get a modest performance improvement by selecting the parent element first, then selecting only child elements of that parent element. This jsPerf test somewhat demonstrates the difference.

In native JavaScript, this is done by selecting the parent element with document.querySelector, document.getElementById, or document.getElementsByTagName. You can then call a similar selector method on that element instead of on document to limit your search to only child elements.

Native

var idArray = ['A123','B456'];
var table = document.querySelector("#eTable");
for(var i = 0; i < idArray.length; i++){
    table.querySelector("tr[data-empid='"+idArray[i]+"']").style.display = "none";
}

In jQuery, you can achieve the same using jQuery(parentElement).find(selector) or $(parentElement).find(selector)

jQuery

var idArray = ['A123','B456'];
var table = $("#eTable");
for(var i = 0; i < idArray.length; i++){
   $(table).find("tr[data-empid='"+idArray[i]+"']").hide();
}


Split a string into chunks of the same length

Algorithm can't be improved (or at least I see no reason to do it, ignoring a minor micro-optimization about List<string> which usage, however, helps to keep code much more readable) and code is pretty clear, however:

You're returning string[] but consumers may not need it. List.ToArray() won't simply return internal array (because its capacity != size). It implies you will make another (relatively expansive) copy. I'd simply return IEnumerable<string>: if consumer needs an array it can call ToArray() LINQ extension method (which will/may check for underlying implementation), it he doesn't need an array then you saved an Array.Copy().
You're partitioning over Char but String is UTF-16 encoded then you may produce broken strings in, at least, three cases:

One character is encoded with more than one code unit. Unicode code point for that character is encoded as two UTF-16 code units, each code unit may end up in two different slices (and both strings will be invalid).
One character is composed by more than one code point. You're dealing with a character made by two separate Unicode code points (for example Han character ).
One character has combining characters or modifiers. This is more common than you may think: for example Unicode combining character like U+0300 COMBINING GRAVE ACCENT used to build à and Unicode modifiers such as U+02BC MODIFIER LETTER APOSTROPHE.

Definition of character for a programming language and for a human being are pretty different, for example in Czech Slovak (thanks svick to correct me about this) dž is a single character however it's made by 2/3 Unicode code points which are in this case also 2/3 UTF-16 code units then "dž".Length > 1. More about this and other cultural issues on this Stack Overflow post.
Ligatures exist. Assuming one ligature is one code point (and also assuming it's encoded as one code unit) then you will treat it as a single glyph however it represents two characters. What to do in this case? In general definition of character may be pretty vague because it has a different meaning according to discipline where this word is used. You can't (probably) handle everything correctly but you should set some constraints and document code behavior.

To address all these issues (also third point if current culture is correctly set but not last one) I'd use:

string[] characters = StringInfo.GetTextElementEnumerator(value).ToArray();

And I'd perform subsequent processing over characters array instead of value. Note that this may lead to strings made of different length but with the same number of characters. For example (when performance are not an issue):

public static IEnumerable<string> Split(this string value, int desiredLength)
{
    var characters = StringInfo.GetTextElementEnumerator(value);
    while (characters.MoveNext())
        yield return String.Concat(Take(characters, desiredLength));
}

private static IEnumerable<string> Take(TextElementEnumerator enumerator, int count)
{
    for (int i = 0; i < count; ++i)
    {
        yield return (string)enumerator.Current;

        if (!enumerator.MoveNext())
            yield break;
    }
}

To do not reinvent the wheel you may just create your own AsEnumerable() extension method to walk through an existing enumerator:

public static IEnumerable<T> AsEnumerable<T>(this IEnumerator enumerator)
{
    while (enumerator.MoveNext())
        yield return (T)enumerator.Current;
}

Your code will be then simplified to:

public static IEnumerable<string> Split(this string value, int desiredLength)
{
    var characters = StringInfo.GetTextElementEnumerator(value);
    do
    {
        yield return String.Concat(characters.AsEnumerable<string>().Take(desiredLength));
    } while (characters.MoveNext());
}

If you don't need string[] return type you may live with IEnumerable<string> and use LINQ ToArray() when/if required (code is slightly simplified for demonstrative purposes, in real world you will need some error checking).

If you're processing US ASCII text and you won't need to partition horse d'œvre then you can simply ignore these issues.


Integer overflow

Since you said you cared about array sizes up to the max size, you should know that this line could cause an overflow with two large indices, meaning that pivot could become negative:

    int pivot = (start + end) / 2;

You can fix this by using the following expression instead:

    int pivot = start + (end - start) / 2;

Skip subarrays of length 1

You can do slightly better by ignoring subarrays of length 1, since they are already sorted.  In other words, this line:

    if(left - start > 0) quickSort(in, start, left);

could be:

    if(left - start > 1) quickSort(in, start, left);

The same goes for the right subarray.

In-place version should be faster

Although there is nothing incorrect with your version, it allocates a temporary array and copies elements back and forth.  If you switched to an in-place algorithm, you will reduce your array writes by 50%.  This means that the in-place version should be faster than your current version, assuming you use a proper version that swaps elements from both ends working inwards.