First off, great that you have a separate prompt function. Too often people don't do this and it's much better separated into it's own function. However, you keep it very light on purpose right now. Much better would be to perform input validation here, ensure that the user has provided something you can actually work with. Even at a basic level, you could test for an empty string:

def prompt():
    while True:
        userInput = input("> ")
        if len(userInput) > 0:
            return userInput
        print("Please enter a command.")

You can see I used a while loop to keep asking for input until the user enters something valid, and then the function returns whatever their command is. This is only a small amount of validation, but it should give you an idea about how to expand on the idea.

You should have more small functions like prompt. For example, your number extracting process is the same in each arithmetic function but you copy and paste it anyway. Instead, have one function to handle that in all cases.

def parse_numbers(user_input):
    numbers = re.findall(r'\d+', user_input)
    nums = ''.join(numbers)
    return nums.replace(" ", "")

One thing that's odd about this function is that it only allows for single digit numbers. You should use the actual operator to split up separate numbers and that way you can have multiple digits.

>>> "12+251".split('+')
["12", "251"]

With this, I'd modify parse_numbers to instead split(+):

def parse_numbers(user_input, operator):
    numbers = user_input.split(operator)

Note that we nowhave to pass the operator parameter, this way we can call parse numbers on any arithmetic command, whether it has a +, -, * or \.

We could simply return numbers now, but then we'd have no input validation. So instead lets try turning all the string into numbers before we return them. A good way to do this is using map, which will apply a function to every item in a list. So we can apply int to each number and then return it. We can also use try except to make sure that if anything can't be converted to a number we tell the user what happened.

def parse_numbers(user_input, operator):
    numbers = user_input.split(operator)
    try:
        return map(int, numbers)
    except ValueError as error:
        print (error.message)

except ValueError means that if an invalid value is passed to int (like "hello") Python will catch the error. This prevents the whole program from ending and gives you an opportunity to instead inform the user why their input is invalid. That's what print (error.message) does, as that will tell the user something useful like:

invalid literal for int() with base 10: 'hello'

To continue with all these functions, I think you should have a function for each command. They can be quite short now that you defined parse_numbers but they still help organisation:

def add(command):
    numbers = parse_numbers(command)
    return numbers[0] + numbers[1]

Easy, right? And you could do this with all of them. Note that I'm using return instead of print because it's best to have functions actually return values in case you ever need them for more than just displaying the result. Also, it's not much harder to account for more than two numbers, ie. "23+3+1". It's very easy for add, you can use a built in function called sum that gets the total sum of all elements in a list.

def add(command):
    numbers = parse_numbers(command, '+')
    return sum(numbers)

For other functions it's not so easy, but you can use something called reduce. reduce basically takes each element of the list and combines them through some function until all the elements have been combined. This does exactly what you need for the other cases. For reduce you need to pass a list as well as a function, in this case we can use a special function called a lambda, they're basically small one line functions. They're useful in cases like this where you don't need to bother defining a whole function to do the job. They're quite compact but still look like functions just without names. Here's how subtract would look:

def subtract(command):
    numbers = parse_numbers(command, '-')
    return reduce(lambda x, y: x - y, numbers)

The same principle can operate on * and / to give you a set of four arithmetic functions. In Python 3 this function was moved to the functools module, so you'll need add an import for it.

from functools import reduce

Of course your other two are even simpler, they're just basic print calls.

def quine(command):
    print(command)

def print_command(command):
    print(command.strip("p "))

Two points on these though. First, I have no idea what a quine is. I had to google it and I still don't see why it's implemented here? You could explain it with a comment, but now that it's a function you could put on a docstring to explain what it does. Docstrings are programmatically accessible comments that explain a function or class. Good practice to put them on your functions. Even if add is quite clear in its use and function, it's good to note that it operates on a list of any length of integers and returns a single integer.

Second, your print command will accidentally remove any 'p's from the end of a string. strip actually removes all the characters that it's passed, not just a specific string. So see what happens here:

>>> "p ppp p p p ppppp pp p ".strip("p ")
""

Instead, just using slicing. Slicing allows you to use indices to get a certain range from a string or list. In your case, you just want to get from the 3rd element on. Indexing starts at 0, so the third element is index 2. You can slice command with [2:]. The lack of a second parameter after : means that it will go to the end of the string.

Now, since we have a bunch of handy functions, this will make the parse function even neater. Here's how it could look:

def prompt():
    while True:
        userInput = input("> ")
        if len(userInput) > 0:
            return userInput
        print("Please enter a command.")

def parse_numbers(user_input, operator):
    numbers = user_input.split(operator)
    try:
        return map(int, numbers)
    except ValueError as error:
        print (error.message)

def add(command):
    numbers = parse_numbers(command, '+')
    return sum(numbers)

def subtract(command):
    numbers = parse_numbers(command, '-')
    return reduce(lambda x, y: x - y, numbers)

def multiply(command):
    numbers = parse_numbers(command, '*')
    return reduce(lambda x, y: x * y, numbers)

def divide(command):
    numbers = parse_numbers(command, '/')
    return reduce(lambda x, y: x / y, numbers)

def parse(command):
    if command.startswith("q"):
        quine(command)
    elif command.startswith("p "):
        print_command(command)
    elif '+' in command:
        print (add(command))
    elif '-' in command:
        print (subtract(command))
    elif '*' in command:
        print (multiply(command))
    elif '/' in command:
        print (divide(command))
    else:
        print("Invalid command")

You'll note I added a print to inform the user when they've passed a totally invalid command too. I'm also not keen on the long chain of elifs, you could remove them partially with dictionaries since they're all basically calling a function with the same parameter. The difficulty is figuring out how to extract the command from your string without clashes. This is more of a design than programming problem, because if you're going to extend this you need to find a safe way to define your syntax that's both computer and human readable.


How to do these extraction/computations efficiently?

In general if you have relational data in a list-like data structure, you want to convert it into a more appropriate data structure before you do anything tricky with it.  I'm not sure what the type of recipes_df so I'm just going to copy your code that iterates over it and go from there.

from collections import defaultdict
from typing import Dict, List, Set, Tuple

# For each product, return where it can be produced.
product_lines: Dict[str, Set[str]] = defaultdict(set)

# For each line, what are the products that it can produce.
line_products: Dict[str, Set[str]] = defaultdict(set)

# For each (p,l) couple store the set of all need raw materials
# to produce product p on l, the property of each raw material
# (coded as 1 if it's S and 0 otherwise), and the total price
class Recipe:
    def __init__(self):
        self.raw_materials: List[Tuple[str, int]] = []
        self.total_price = 0.0
recipes: Dict[Tuple[str, str], Recipe] = defaultdict(Recipe)

# Loop over recipes_df and populate all these structures.
for product, line, rm, rm_type, rm_price in \
        recipes_df[['product','line', 'rm','rm_type','rm_price']].values:
    product_lines[product].add(line)
    line_products[line].add(product)
    recipes[(product, line)].raw_materials.append((rm, 1 if rm_type == 'S' else 0))
    recipes[(product, line)].total_price += rm_price

At this point you've done a single pass through the entirety of recipes_df and you've completely populated the dictionaries that will let you find all the information you're looking for in constant time.  From here you can convert those dictionaries into whatever other output format you need.


I find [interpreted] pure python is pretty slow.

Yes, that's true. And numpy operations can offer speed advantages, since its loops are coded in compiled C. But that's only significant when manipulating large arrays, and 5 seems like a pretty small number, too small to realize gains. (I think eval_() only evaluates a single hand at a time, it's not like you're passing in thousands of hands in a single call.)

Yes, you could return count[1] instead of count[1][2], but that's quite a different thing, presenting callers with a different API. Would you please state your concern in terms of what values the caller should receive, similar to a unit test?

The list comprehension you use seems pretty reasonable to me.

You have lots and lots of magic numbers that you might define identifiers for.

It wouldn't hurt to mention https://en.wikipedia.org/wiki/List_of_poker_hands in a comment, if that matches the rankings you're returning.


It's not "unoptimized". it's just bad.

your JS code shouldn't contain CSS manipulation (unless you are actually making complex animations)
even when your if and for statements have a single line following it, that code should be wrapped in { .. }
use === when comparing values, unless you explicitly require behaviour, that is provided by == loose comparison
you should use meaningful variable names, instead of el1, el2, etc.
none of this required jQuery
don't define variables in the middle of a function


Some thoughts:

Divide function has been implemented recursively. In general, recursive implementations provide clarity of thought despite being inefficient. But in this case, it just makes the code cumbersome.

while m % factor == 0:
    m /= factor
return m

should do the job.

A lot of computational work is done by isPrime which is unnecessary. Eg: when factor 15 is being considered, the original n would've been already Divided by 3 and 5. So, if factor is not a prime then n%factor will not be 0.

So, the following should do:

import math
def largestPF(n):
    limit = int(math.sqrt(n)) + 1
    for factor in xrange(2, limit+1):
        while n % factor == 0:
            n /= factor
        if n == 1:
            return factor
    return n

You can of course, include the 'run through factors in steps of 2' heuristic if you want.

PS: Be careful with the is statement for verifying equality. It might lead to unexpected behaviour. Check out https://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why


Project Euler 1 (sum of multiples of 3 or 5 under 1000)

So, any time you want to write a "helper" recursive function, the standard way to write that is to use a named let. So here's how I might restructure your program (but keeping the same algorithm):

(define (sum-multiples start end)
  (let loop ((sum 0)
             (i start))
    (cond ((>= i end) sum)
          ((or (zero? (modulo i 3))
               (zero? (modulo i 5)))
           (loop (+ sum i) (add1 i)))
          (else (loop sum (add1 i))))))

Named let is a macro, which in this case expands to the same expression as:

(define (sum-multiples start end)
  ((letrec ((loop (lambda (sum i)
              (cond ((>= i end) sum)
                    ((or (zero? (modulo i 3))
                         (zero? (modulo i 5)))
                     (loop (+ sum i) (add1 i)))
                    (else (loop sum (add1 i)))))))
     loop)
   0 start))

(I've taken the liberty of using (add1 i) instead of (+ i 1) since you're using Racket.)

Here's a version that's even more Rackety, using for/sum to accumulate the sum rather than using a manual loop:

(define (sum-multiples start end)
  (for/sum ((i (range start end)))
    (if (or (zero? (modulo i 3))
            (zero? (modulo i 5)))
        i 0)))


The solution is generally good.

The docstring is OK, but could be better if it more clearly stated the purpose of the function.  Follow the PEP 257 conventions for formatting.  Use the imperative rather than the indicative mood.

The comment blocks throughout the function are useful, but could be less verbose.  For example, you can cut out filler words like "First, we need to …".

Instead of assert type(grid) == list, I would assert isinstance(grid, list) to state what you really require without being too strict about the type, since duck-typing is the norm in Python.

You used this to validate the row lengths:

row_len = map(lambda x: len(x) == 9, grid)
if False in row_len:
    return None

Here, as in many places throughout the function, you used x as dummy variable.  x is vague, and has a connotation of being a floating-point number.  Try to pick more helpful names, as in lambda row: len(row) == 9.

Throughout this exercise, the all() built-in function and generator expressions are your friend.  These are ways to write compact Pythonic code that is in the spirit of functional programming without actually using map and lambda explicitly.

I don't think that this block is necessary:

# next we need to make sure that the numbers are between 0 and 9
max_len = map(max, grid)
min_len = map(min, grid)
more_than_ten  = filter(lambda x: x > 9, max_len)
less_than_zero = filter(lambda x: x < 0, min_len)
if len(more_than_ten) or len(less_than_zero):
    return False

Your strategy is to first ensure that the entire grid contains nothing but digits 1 to 9, then ensure that each set contains nine distinct members.  It would be simpler and clearer to eliminate this block, then check whether each set is equal to set(range(1, 10)).

For example, to check each row…

    DIGITS = set(range(1, 10))
    if not all(set(row) == DIGITS for row in grid):
        return False

Checking rows is easy; checking columns is slightly more challenging.  Transposing the grid can easily be accomplished with a list comprehension.

Checking each 3×3 square is more challenging.  You used one loop to build a bunch of lists of lists, then cleaned up the "ickiness" by flattening it.  You could avoid the flattening step by using .extend() instead of .append().

But really, what you should be using is itertools.product().

>>> from pprint import pprint as pp
>>> from itertools import product
>>> THREES = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> pp(list(product(THREES, THREES)))
[((0, 1, 2), (0, 1, 2)),
 ((0, 1, 2), (3, 4, 5)),
 ((0, 1, 2), (6, 7, 8)),
 ((3, 4, 5), (0, 1, 2)),
 ((3, 4, 5), (3, 4, 5)),
 ((3, 4, 5), (6, 7, 8)),
 ((6, 7, 8), (0, 1, 2)),
 ((6, 7, 8), (3, 4, 5)),
 ((6, 7, 8), (6, 7, 8))]
>>> pp([
...     [(r, c) for r, c in product(row_block, col_block)]
...     for row_block, col_block in product(THREES, THREES)
... ])
[[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)],
 [(0, 3), (0, 4), (0, 5), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)],
 [(0, 6), (0, 7), (0, 8), (1, 6), (1, 7), (1, 8), (2, 6), (2, 7), (2, 8)],
 [(3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (5, 0), (5, 1), (5, 2)],
 [(3, 3), (3, 4), (3, 5), (4, 3), (4, 4), (4, 5), (5, 3), (5, 4), (5, 5)],
 [(3, 6), (3, 7), (3, 8), (4, 6), (4, 7), (4, 8), (5, 6), (5, 7), (5, 8)],
 [(6, 0), (6, 1), (6, 2), (7, 0), (7, 1), (7, 2), (8, 0), (8, 1), (8, 2)],
 [(6, 3), (6, 4), (6, 5), (7, 3), (7, 4), (7, 5), (8, 3), (8, 4), (8, 5)],
 [(6, 6), (6, 7), (6, 8), (7, 6), (7, 7), (7, 8), (8, 6), (8, 7), (8, 8)]]

I could go further and validate all nine 3×3 blocks using just one statement, but that could be a bit too overwhelming.

Suggested solution

from itertools import product

def check_sudoku(grid):
    """Validate a sudoku solution.

    Given a grid as a list of lists, return None if it is ill-formed,
    False if it is invalid, or True if it is a valid solution.
    """
    assert isinstance(grid, list)

    # Check that the grid is 9x9.
    if len(grid) != 9 or not all(len(row) == 9 for row in grid):
        return None

    DIGITS = set(range(1, 10))

    # Check that each number appears exactly once per row
    if not all(set(row) == DIGITS for row in grid):
        return False

    # Check that each number appears exactly once per column
    columns = [[row[c] for row in grid] for c in range(9)]
    if not all(set(col) == DIGITS for col in columns):
        return False

    # Check that each number appears exactly once per 3x3 grid
    THREES = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
    for row_block, col_block in product(THREES, THREES):
        block = [grid[r][c] for r, c in product(row_block, col_block)]
        if set(block) != DIGITS:
            return False

    return True

Functional solution

Since you mentioned an interest in functional programming, I thought I should also present a more functional variant for your consideration.

from itertools import product

def check_sudoku(grid):
    """Validate a sudoku solution.

    Given a grid as a list of lists, return None if it is ill-formed,
    False if it is invalid, or True if it is a valid solution.
    """
    assert isinstance(grid, list)

    # Check that the grid is 9x9.
    if len(grid) != 9 or not all(len(row) == 9 for row in grid):
        return None

    DIGITS = set(range(1, 10))
    THREES = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]

    def correct(groups):
        return all(set(group) == DIGITS for group in groups)

    rows = grid
    columns = zip(*grid)
    squares3x3 = [
        [grid[r][c] for r, c in product(row_block, col_block)]
        for row_block, col_block in product(THREES, THREES)
    ]

    return correct(rows) and correct(columns) and correct(squares3x3)


A pointer vector sorted by its member function

There's probably much that can be done here, but I'll point out some things I've noticed:

As @David Harkness has mentioned in the comments, the method-naming looks like C# naming (uppercase, or PascalCase).  While this isn't necessarily a bad thing as C++ is more flexible with naming, one problem here is that your types (particularly the class) and functions use the same naming convention, which may cause confusion for others.

I would use separate naming for both of them, such as by changing the functions to camelCase or snake_case, while keeping the types as is.
Since you're not overloading the default constructor, you don't have to include it.  The compiler will make a default one for you.

However, with C++11, you can now use default constructors:

SortedPtrVector() = default;

It looks like Add() is doing too many things:

the actual adding
updating a reference
returning a bool

Based on the name, it should just attempt to add something.  But if it's still necessary to update the index, then it should just return that.  You could instead return an std::pair<iterator, bool> as done with std::map::insert, but that may not be what you want here.
Find() shouldn't set index to 0 if the vector is empty.  An index of 0 is a valid position for a non-empty container (the first position).  Instead, it could return -1, which is an out-of-bounds value commonly used with not found (this is also the same value as the constant std::string::npos).

It may also be better to have Find() return an index instead of a bool.  Assuming this is to somewhat resemble std::map::find, it can return a past-the-end value (an iterator) if the key isn't found.
DeleteAt() may do something problematic if the argument isn't checked prior to calling erase() (an invalid index can cause erase() to attempt access to some other location, leading to undefined behavior).
Size() should be const as it's not modifying any data members.  You could also make it noexcept (also C++11) since it's guaranteed not to throw.

Also, unsigned is not quite the specific return type of std::size().  It should either return an std::size_t (usually assumed), std::vector<std::unique_ptr<T>>::size_type (very lengthy), or even better and shorter with C++14 (if your compiler also supports it): the type deduced by auto.

auto Size() const noexcept { return m_vector.size(); }


Checking whether a bullet has hit a Space Invader

Welcome to CodeReview!

I'm not really working with javascript, but I noticed some things I'd like to mention:

You can safely move the first two initialisations of invaderX an invaderY one condition deeper into the Invaders[i].isVisible() block - if the invader isn't visible there is no need to know the invaders position.
Same with the score variable. Initialise the variable immediately before using it (game.updateScore(score)).
Don't use magic numbers like 15 for the radius of an invader. Use a static class constant or instance property of an Invader instance. This would even allow you to create invaders of different size.
I would also put the isInInvadersRadius condition into a separate function. This function could look something like this:

function areInRadius(location1, location2, radius) {
    var x1 = location1[0],
        y1 = location1[1],
        x2 = location2[0],
        y2 = location2[1];

    return x1 >= x2 - radius && x1 <= x2 + radius &&
           y1 >= y2 - radius && y1 <= y2 + radius;
}

Using this function you wouldn't even need the temporaries bulletX and bulletY, just calling areInRadius(bullet.location(), Invaders[i].location(), Invader[i].radius).

Your function would look like this:

function testForInvaders(bullet) {
    for(var i = 0; i < Invaders.length; i++) {
        if(Invaders[i].isVisible() && areInRadius(bullet.location(), Invaders[i].location, Invaders[i].radius) {
            Invaders[i].removeVisibility();

            var score = document.getElementById('score');
            game.incrementScore();
            game.updateScore(score);
            return false;
        }
    }

    return true;
}

testForInvaders gets called quite often as you already mentioned and I'm honestly not sure if the overhead of the function call above will screw with the performance. You should consider to measure the impact.

Since I'm not into javascript I can't say anything special about hit detection (maybe there is a builtin or an standard way of doing so), but I'm sure other users will remind you of those (if existent).

Nice piece of code you delivered here for your first review. Keep it up!


Automatically run doctest every time program is run

Make it a habit to run pyflakes and the pep8 tools on Python projects. pep8 finds some style violations in this code:

There should be two blank lines before global method declarations (main and _doctests_pass in your case)
There shouldn't be trailing whitespace at the end of line 3 and 4.

You can install pyflakes and pep8 using pip. See also the PEP8 documentation for more details on Python style.

By the way, I think running unit tests is a job for a Continuous Integration system, not something to do every time you run the code. The point of testing is to run after every code change. You're going way further, but it's completely pointless. If the code hasn't changed, then the repeated tests are just wasting CPU cycles. I think it would be better to abandon this approach and leave this up to a Continuous Integration tool, where you could include other goodies easily like pep8, pyflakes, and others.

If this is not a team project, then setting up a Continuous Integration system could be overkill. A good middle ground can be setting up a pre-commit hook with your version control system. That should be relatively easy to do, and ensure that all your committed code pass your tests.


Insert a number in a sorted list and return the list with the number at the correct index

Recursion is usually a poor choice in Python.  Non-tail recursion is usually a poor choice in any language (and this is non-tail because we apply + to the result before returning it).

It's better to use the standard bisect module to find (once) the correct index at which to insert.  This module provides the bisect() function to locate the correct index, and also the insort() function that calls bisect and then inserts, exactly as we want:

insert = bisect.insort

This will insert in place, rather than creating a new list, so not exactly equivalent to the existing code.

As you say "using only simple functions", let's suppose you can't use the Standard Library (that's a bad assumption in general - Python philosophy is that it "includes batteries" to make your code simpler).  Then we can use a similar method to write our own non-recursive version.

def insert(lst, to_insert):
    """
    parameters : lst: sorted list (smallest to largest)
                 to_insert: value to add
    returns : copy of lst with the to_insert value added in sorted position
    """

    # binary search
    left = 0
    right = len(lst)

    while left != right:
        mid = left + (right-left) // 2
        if lst[mid] == to_insert:
            left = right = mid
        elif lst[mid] < to_insert:
            left = mid + 1
        else:
            right = mid

    # now copy the list, inserting new element
    return lst[:left] + [to_insert] + lst[left:]

Since the question states (without justification) that "recursion is mandatory", I recommend making the search recursive, but performing the insertion just once:

#! untested
def insert(lst, to_insert, left=0, right=None):
    if right is None:
        right = len(lst)

    if left == right:
        return lst[:left] + [to_insert] + lst[left:]

    else:
        mid = left + (right-left) // 2
        if lst[mid] == to_insert:
            left = right = mid
        elif lst[mid] < to_insert:
            left = mid + 1
        else:
            right = mid
        # move left or right, then
        return insert(lst, to_insert, left, right)

This is now tail-recursive, at least, and only reallocates the list elements once, rather than every level of recursion.


Creating strings of desired length from a list of substrings

The trouble is that you are generating an array with all possible combinations of all possible strings and then whittling it down from there.  You end up doing a lot of work you don't have to do.  However, it makes for conceptually easy-to-understand code, so I certainly wouldn't call this solution "wrong" (unless it is simply too slow for your actual application).  There is often a trade off between "does the job very well" and "easy to understand", and sometimes the latter is the real winner.

In terms of alternate approaches, I just have a general outline of one I can suggest (if it is helpful).  Instead of doing this in "string" space you could imagine doing this in "length" space.  I.e. instead of thinking of the problem in terms of allowed substrings, think of it in terms of allowed lengths of substrings:

available_strings = ['AB', 'CDE', 'FGHIJK', 'LMN', 'OP', 'QR', 'ST', 'U']

becomes:

strings_by_length = { 1: [ 'U' ], 2: [ 'AB', 'OP', 'QR', 'ST' ], 3: [ 'CDE', 'LMN' ], 6: [ 'FGHIJK' ] }
substring_lengths = strings_by_length.keys()

You now know that you have substrings of length 1, 2, 3, and 6.  Then break down the length combinations that are actually applicable.  For instance, for a desired length of 5 you can combine substrings of length:

[ 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 2 ],
[ 1, 1, 3 ],
[ 1, 4 ],
[ 1, 2, 2 ],
[ 3, 2 ],
[ 5 ]

You can automatically rule out [1, 4] and [ 5 ] because you have no substrings that match those lengths.  You also rule out substring FGHIJK because it is too long for any of your allowed lengths.  Of course, generating this list of possibilities is a bit tricky, and then the next part is also tricky:

Take your list of allowed combinations and combine them with the substrings separated by length to get all allowed combinations.  I'm not familiar with the itertools library but it might help with that.  For instance you could imagine taking combination [ 1, 2, 2 ] and basically doing an iterative combination of:

build_all_combinations( strings_by_length[1], strings_by_length[2], strings_by_length[2] )

Overall, this makes sure you are only calculating combinations for values that you know are allowed, rather than calculating all combinations and then filtering.  It has the potential to be more efficient, but the devil is always in the details.  Not sure how it will work out in practice, or how easy it will be to write.

Edit to add notes about performance

In case you are new to it, welcome to the world of np-complete problem sets!  I think your problem is effectively a variation on the knapsack problem.  Reading up on that may give you some ideas of different (and more efficient) approaches to this problem.  The short of it is that this can be slow.  I'm pretty sure you are running on O(n^2) time, which is not terrible, all things considered.  Anyway, onto the steps to optimize:

1. Make your algorithm smarter!

This is basically what I was trying to do.  How much my particular algorithm will help will vary depending on the precise problem.  If you have a lot of sub strings that are not applicable (i.e. the 'FGHIJK' in your example), then a little intelligence can save you a lot of computation.  In the example you gave some the general algorithm I had suggested would have ruled out that one branch before doing any computations, which would have theoretically brought the minimum number of computations down from 8^2 = 64 to 7^2 = 49, a ~25% improvement.  However, If all of your substrings had been shorter than the max length, there would have been no improvement.

In practice though I'm comparing to the best-case scenario, and your current algorithm may not be anywhere near that.  Your current algorithm may be running in a time substantially slower than the best-case scenario.  That is what I meant by "the devil is in the details".  Do you know how itertools works?  External libraries can make things convenient, but depending on how they run they may actually make your algorithm slower.  To really speed things up, it can help to really think through your algorithm and make sure it is running as close to ideal as possible.

2. Run in compiled code

Regardless of how smart your algorithm is, you are still facing at least O(n^2) time.  For large n the answer isn't going to be smartness but rather raw computing power.  As an interpreted language python is relatively slow, so in cases like this that can be a big source of your problem.  This doesn't mean you have to rewrite in C or another language, as python has many built in tools that may delegate parts of your tasks to compiled code.  As a general example (which may or may not be helpful for you), in a lot of my computations I used numpy extensively and relied upon its built-in array operations, in particular seeking to avoid for loops.  Looping tends to be one of the slowest parts of interpreted languages, while all of numpy's array operations are actually running as compiled code.  Taking parts of algorithms and switching from for loops to array operations that execute as compiled code on the server frequently saw performance gains by a factor of 5-40.

3. Parallel processing!

Some problems are very amenable to parallel processing.  This can either mean taking advantage of multi-core CPUs, working in a distributed computing environment (aka hadoop) or even GPU processing.  Off the top of my head, I'm not sure how helpful any of those options will be to your program.  I'm going to guess that this isn't important enough to be worth the time it takes to re-write this algorithm for some advance parallel processing but hey, you never know.

Summary

These are the steps I would go through if I had code that I needed to run quickly that was simply too slow.  How much time you spend actually optimizing things always depends on how important the code is, of course.  But ultimately you have those three options: make the code faster, figure out how to get it to run compiled, or throw lots of computing power at the problem.  In your particular case your problem will likely allow for only some optimization via smarter algorithms, so if you really need this to go fast you may have to start looking at options 2 & 3.


.slice() does not actually do a deep copy, the easiest way to do a deep copy with simple objects is

array = JSON.parse( JSON.stringify( array ) )

Also, you can sort on a boolean in a simpler way:

function sortWordsByIncorrectAnswers(array)
{
  array =  JSON.parse( JSON.stringify( array || [] ) );
  return array.sort( function(a, b)
  {
    return a.fields.false - b.fields.false;
  });
}


JSON-ification and processing of data with Python

It's slow because of this line:

for line in lines:
    records = [item['hash'] for item in lines]

Notice that records will be overwritten for each line.
And in fact it's overwritten with the exact same value for each line.
In fact you could replace this loop with just this line:

records = [item['hash'] for item in lines]

That should already solve the problem with the slowness.
But I would go one step further and get records in one step,
by getting hash directly during the first pass over the input lines:

with open('toy.json', 'rb') as input:
    records = [json.loads(line)['hash'] for line in input]

    for item in records:
        print item


Timed series of events. Logic for organizing events based on time?

My simplified answer (without interpolation or looping):

        int numEvents = events.Count;

        // Check if there are any events to execute
        if (eventIndex == numEvents)
        {
            return;
        }

        // Check if the current event has yet to occur
        if (events[eventIndex].Time > currentTime)
        {
            return;
        }
        else
        {
            // Update the property based on the current event
            UpdateProperty(events[eventIndex].Value);

            // Current event has been executed so increase the event index
            eventIndex++;
        }


Switch-Case pattern for non-constant types

The co-occurrence of Value and value in the same methods is irritating and likely to lead to bugs: I would rename value to query or something like that (and shall call value by query for the rest of this answer in the interests of not making any mistakes myself).

I was initially dubious of Flater's suggestion that creating the SwitchCase objects would be a problem given all the predicates flying around, so I looked at the memory characteristics of his example loop (only with a few more zeros on the end), and saw that I was completely wrong:

Note all the predicates and boxed ints (always a bad sign). All those predicates are not the ones the caller wrote: those are predicates created by the Case(T, ...) methods, and all the Int32s are integers being boxed so they can be cast as IEquatable<int>. If you change Flater's code to one which only uses the Case(Predicate<T>, ...) overload, everything disappears with the exception of the SwitchCases (the caller's predicates are reused), and as Flater says, you can remove those too by caching and improve the method memory characteristics dramatically.

Now to diverge from the code itself... there may be little point in your if (Value is IEquatable<T>) condition, since the EqualityComparer will do that for you. The only thing it gives you, is that it will use T's implementation of IEquatable<T> by default rather than query's: this sort of thing needs to carefully documented, because it could cause someone down the line no-end of confusion when they try to 'override' the comparison by implementing IEquatable<T> in a super-class of T, only to have it ignored. This feels the wrong way round to me; however, personally I wouldn't do the check for either, and would solely depend on the EqualityComparer (and maybe a comparer passed to the constructor). If I did want to use query's implementation, then I probably ought to know either that it has an implementation to use (and when it will be used), in which case the caller can decide if they want to use it or not. I'd rather provide a performant version with statically determinable behaviour:

public ISwitchCase<T> Case<S>(S query, Action action) where S : IEquatable<T>
{
    if (query.Equals(Value))
    {
        action();
        return EmptySwitchCase<T>.Instance;
    }

    return this;
}

Such a method also has the advantage of being efficient when handling structs, as it doesn't involve any boxing. I've also in-lined the conditional logic, because it avoids the allocation of the Predicate<T> and its body (which can't be reused).

This doesn't solve the boxing int problem in Flater's example, because the Case(T, etc.) overloads are better, but if you replace those with these, you can prevent any repetitive allocations occurring when these methods are called.

/// <summary>
/// Compares the query and internal value using the DefaultEqualityComparer, and invokes the given action if they match
/// </summary>
public ISwitchCase<T> Case(T query, Action action)
{
    return Case(query, EqualityComparer<T>.Default, action);
}

/// <summary>
/// Compares the query and internal value using the given comparer, and invokes the given action if they match
/// </summary>
public ISwitchCase<T> Case(T query, IEqualityComparer<T> comparer, Action action)
{
    if (comparer.Equals(Value, query))
    {
        action();
        return EmptySwitchCase<T>.Instance;
    }

    return this;
}

Obviously it's your decision what your API does, and it is important to stress that the behaviour is different like this, but that the behaviour was unclear before. With the added inline documentation, the new behaviour is clear and completely transparent at compile time. The difference is that that a value which provides an alternative implementation of IEquatable<T> will only be compared using this implementation if it is not a T and it can be determined at compile time that it is IEquatable<T>. I'd make a case for this behaviour being more 'intuitive', because it become equivalent to using a predicate of the form v => query.Equals(v) when query is not of type T. Without a : T constraint, this means that stuff which is comparable to T without necessarily being a T can also be used, which may or may nor be desirable.

Naturally, it is not nice having many methods implementing the if (predicate(Value)) logic, so I'd be inclined to put this login in a simple private ISwitchCase<T> Case(bool condition, Action action), essentially replacing your current Case(Predicate<T>, etc.) in this role. If you want to keep the dynamic IEquatable<T> behaviour, then you can still rid yourself of all the anonymous methods by using such a method instead of deferring everything to Case(Predicate<T>, etc.). For example:

/// <summary>
/// Compares the query with the internal value, first trying to use implementation of `IEquatable&lt;t&gt;` provided by the internal value, then that provided by the query, falling back to the DefaultComparer otherwise
/// </summary>
public ISwitchCase<T> Case(T query, Action action)
{
    if (Value is IEquatable<T>)
        return Case(((IEquatable<T>)Value).Equals(query), action);

    if (query is IEquatable<T>)
        return Case(((IEquatable<T>)query).Equals(Value), action);

    return Case(query, EqualityComparer<T>.Default, action);
}

/// <summary>
/// Compares the query and internal value using the given comparer, and calls the given action if they match
/// </summary>
public ISwitchCase<T> Case(T query, IEqualityComparer<T> comparer, Action action)
{
        return Case(comparer.Equals(Value, query), action);
}

/// <summary>
/// Invokes the given action if the condition is true
/// </summary>
private ISwitchCase<T> Case(bool condition, Action action)
{
    if (condition)
    {
        action();
        return EmptySwitchCase<T>.Instance;
    }

    return this;
}

Or, more tidily (using pattern matching):

/// <summary>
/// Compares the query with the internal value, first trying to use implementation of `IEquatable&lt;t&gt;` provided by the internal value, then that provided by the query, falling back to the DefaultComparer otherwise
/// </summary>
public ISwitchCase<T> Case(T query, Action action)
{
    if (Value is IEquatable<T> v)
        return Case(v.Equals(query), action);

    if (query is IEquatable<T> q)
        return Case(q.Equals(Value), action);

    return Case(query, EqualityComparer<T>.Default, action);
}

Note the inline documentation, which should appear on the interface.


Iterative depth first search using adjacency matrix

It's nearly impossible to tell what your code does because:

The variable names are meaningless
There are no prompts for the user to tell them what the inputs mean
The output appears to just be a string of numbers with no apparent meaning

I can't tell you if it's correct or not (which is beyond the scope of Code Review anyway) because I can't tell what it's trying to do. In terms of trying to improve your code, I recommend changing the variable names from single letters or cryptic acronyms to full words, such as adjacencyMatrix and traversalList, or whatever they actually represent.

I recommend outputting some strings to tell the user what to input. Alternately, if this code is supposed to read its input from a file, then you should write code to read from a file instead of assuming it will come from standard in.

Finally, your output should say what it's outputting and have some sort of separators between the values, such as commas, spaces, or line endings. Again, if it's meant to be outputting to a file, then you should write code to write to a file rather than standard out.


Your code is reviewable, even if it does not work, from a once over:

Indent your code (!!), this is bad:

function Caesar(order){
this.order = order;
this.encode = encode;
function encode(input){
this.output = '';
for (var i = 0; i < input.length; i++) {
var this.c = input.charCodeAt(i);
if      (this.c >= 65 && this.c <=  90) this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65);  // Uppercase
else if (this.c >= 97 && this.c <= 122) this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97);  // Lowercase
else   this.output += input.charAt(i);
}
return answer.innerHTML= output;
 }

This is better:

function Caesar(order){
    this.order = order;
    this.encode = encode;
    function encode(input){
        this.output = '';
        for (var i = 0; i < input.length; i++) {
            var this.c = input.charCodeAt(i);
            if (this.c >= 65 && this.c <=  90)
                // Uppercase
                this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65);
            else if (this.c >= 97 && this.c <= 122)
                // Lowercase
                this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97);
            else
                this.output += input.charAt(i);
        }
    return answer.innerHTML= output;
}

Caesar is an unfortunate name

It does not really say what it does ( one can guess )
it should not start with a capital C, it is not a constructor

The Caesar is completely wrong

it puts encode in this.encode and then never uses this.encode
if encode were called, it set this.output but then in the end you put output in answer.innerHTML
you try to access answer, but you never declared it with var, much less pointed it to the answer element with getElementById

You hardcode magical numbers

Some developers know 65 is A, you should put a comment about that
Same for 97 , 26 and 122

order -> what does order do ? Should be commented, it is not obvious
onclick ="encode()" <- This is very old skool ( bad ), the correct way is using an addEventListener for load and in there use an addEventListener for click


The code in maximums is doing what it is supposed to do, based on that SO question. I have several remarks about the other parts though.

Do not use single letter variables. Use names that say something.
So no v, vv, vvv.

Another naming issue, your two maximums functions do the same thing but with a different approach, you can make this clear in the name. They both use T=period, so this is not distinguishing. Maybe use the fact that a deque is used or that one is the simple variant.

You create double vectors in the test and then pass them to maximums for example. There is absolutely no reason for test to create them. Let maximums create the vector, since it needs it and then return it. Some for maximumsT.

Your maximumsT is not intuitive. There is no need to do a double loop.
Why did you change your implementation as in your question on SO? It was better there.
Namely

for (size_t i = period; i <= v.size(); ++i) {
        vv[i - 1] = *std::max_element(v.begin() + i - period, v.begin() + i);
    }

The code will not be faster or save space, but its shorter and clearer.

Initializing random vectors to test against, could be done in a dedicated function. I would make the test also parameterized on the source vector.

My suggestion:

#include <vector>
#include <deque>
#include <algorithm>

std::vector<double> maximumsT(const std::vector<double> &src, size_t period)
{
    std::vector<double> dst(src.size());

    for (size_t i = period; i <= v.size(); ++i) {
       vv[i - 1] = *std::max_element(v.begin() + i - period, v.begin() + i);
    }
    return dst;
}

std::vector<double> maximums(const std::vector<double> &src, size_t period)
{
    std::vector<double> dst(src.size());
    std::deque<std::pair<size_t, double>> deq;

    for (size_t i = 0; i < src.size(); ++i) {
        if (!deq.empty() && i >= period && deq.front().first <= i - period) {
            deq.pop_front();
        }

        while (!deq.empty() && deq.back().second < src[i]) {
            deq.pop_back();
        }

        deq.push_back(std::make_pair(i, src[i]));
        dst[i] = deq.front().second;
    }
    return dst;
}

std::vector<double> randomVect()
{
    std::vector<double> v(1 + rand() % 1000);
    for (double &e : v) {
        e = (double)rand() / RAND_MAX;
    }
    return v
}
bool compareMaximums(std::vector<double> v, size_t period)
{
    return maximumsT(v, period) == maximums(v, period);
}

bool test(size_t iterations)
{
    for (size_t i = 0; i < iterations; ++i) {
        std::vector<double> srcVec = randomVect();
        size_t period = 1 + (rand() % srcVec.size());
        if (!compareMaximums(srcVec, period)) {
            return false;
        }
    }

    return true;
}

int main(int argc, char *argv[])
{
    return test(10000);
}


Your base cases are both invalid and unnecessary:

union' [] _ = []
union' _ [] = []

There isn't anything bad about using where, especially when you consider that union' needs no base cases.  Your question is, really, whether union' should be implemented using some kind of nub or not.  If you're reinventing-the-wheel as an exercise, why wouldn't you want to reimplement nub as well?

The real question you should be asking is how to avoid ++.


Project Euler problem 19 - How many Sundays fell on the first

The loops could be clearer:

The outermost loop is actually spread across three lines: int year=1901, while(year<=2000), and year++.  It should be written as a for loop.
i should be renamed to month or m.
The exceptional case for leap years is awkward: you sometimes clobber the February entry at the top of the loop, then reset it at the end.  I'd consider such mutations to be a hack that makes the code harder to understand.  It also makes the code harder to maintain, since you have hard-coded 29 and 28 in scattered places.

As for the algorithm itself… you should be able to do better than advancing a day at a time through an entire century.  Why not advance a month at a time?

#include <stdio.h>

static const int *month_lengths(int year) {
    static const int NON_LEAP_YEAR[] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    static const int LEAP_YEAR[] = {
        31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };
    return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ?
        LEAP_YEAR : NON_LEAP_YEAR;
}

int main(void) {
    int first_sundays = 0;
    int day_of_the_week = 2;    // 0 = Sun, 6 = Sat.  1 Jan 1901 was a Tuesday.
    for (int year = 1901; year <= 2000; ++year) {
        const int *lengths = month_lengths(year);
        for (int month = 0; month < 12; month++) {
            if (day_of_the_week == 0) {
                first_sundays++;
            }
            day_of_the_week = (day_of_the_week + lengths[month]) % 7;
        }
    }
    printf("There are %d Sundays that fell on the first of the month\n",
           first_sundays);
}


Generate a CSV file from a multidimensional array in php

Encapsulate the csv line generation in another function.

function GenerateCSVlineFromArray($array){
    $line = "";
    foreach ($array as $value){
        $line .= $value .",";
    }
    //cut last comma
    $line = substr($line, 0, strlen($line) -1);
    return $line;
}

Assuming you have already the right order of values.


Perm-Missing-Elem: 100% functional score, but only 60% performance

@chillworld is correct in his observation that the issue is related to the int overflow causing the problems in the performance tests.
The more accurate solution to this is to use a long to set the score, instead of an int.
public class Solution {

    public int solution(int[] A) {

        long N = A.length + 1;
        long total = N * (N + 1) / 2;

        for (int i : A) {

            total -= i;
        }

        return (int)total;
    }
}

As for your code, I understand why you have variables with names like N and A, because those are the variable names used in the problem.
Those variable names do not conform to standard Java naming conventions though. They should be meaningful names, and start with a lower-case letter, like sum, and data.
the fact that my code below still uses N is not an indication that it is OK .... Do what I say, not what I do...

Update
Sometimes, the performance tricks in Java can be a PITA.

Whenever you can, declare your variables as final
declare your methods as final
declare variables and for-loop variables as final (if you use the enhanced-for semantics).
addition may, or may not be faster than subtraction.

Using this code:
class Solution {

    public final int solution(final int[] data) {

        final long N = data.length + 1;
        final long total = (N * (N + 1)) / 2;

        long sum = 0L;

        for (final int i : data) {

            sum += i;
        }

        return (int)(total - sum);
    }
}

Scores 100%

Update 2 final is not the issue:
public int solution(int[] data) {

    long N = data.length + 1;
    long total = (N * (N + 1)) / 2;

    long sum = 0L;

    for (int i : data) {

        sum += i;
    }

    return (int)(total - sum);
}

Also scores 100%


Generating a password to save to a .txt file

By making it more Pythonic for one:

string.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()'
let1 = random.choice(string.letters)
let2 = random.choice(string.letters)
let3 = random.choice(string.letters)
let4 = random.choice(string.letters)
let5 = random.choice(string.letters)
let6 = random.choice(string.letters)
let7 = random.choice(string.letters)
let8 = random.choice(string.letters)
letters_section = let1 + let2 + let3 + let4 + let5 + let6 + let7 + let8

should be:

''.join(random.choice(string.letters) for _ in range(length))

Now instead of a hard coded length you can ask the user for a length or easily change it by changing one variable instead of adding or deleting lines.

Instead of this:

file1 = open(completeName, "w")
toFile = your_pass
file1.write(toFile)
file1.close()

You want:

with open(completeName, "w") as file1:
    file1.write(your_pass)  # no need to assign a new variable

The with context manager will automatically handle closing the file for you.

This seems to be a pattern in your code but its wholly unnecessary:

num1 = random.randrange(100,999)
number_section =  num1

Just use num1 or save the output of randrange() to number_section directly there is no need for an intermediate variable.

So in the end you can simplify to:

import random
import string
import os.path

num1 = random.randrange(100,999)
string.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()'

letters_section = ''.join(random.choice(string.letters) for _ in range(8))  # change 8 to a variable if you want to ask the user for a length or have it passed as an argument
password = str(number_section) + letters_section

password_for = raw_input('This password is for: ')
your_pass =  'Your password for {} is: {}'.format(password_for, password)
print(your_pass)

save_path = 'C:\Users\Charles\Desktop\Passes'
name_of_file = raw_input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "w") as file1:
    file1.write(your_pass)

Or even more simply:

def gen_password(length):
    choices = string.digits + string.punctuation + string.ascii_letters
    return ''.join(random.choice(choices) for _ in range(length))

>>> gen_password(13)
'7P~R6dSy<T)+Z'
>>> gen_password(20)
"Q{qHs6ahwj^EaT_'t,.7"
>>> gen_password(11)
'XDi49z+;^?='


Flatten dictionary in Python (functional style)

Your solution really isn't at all functional. You should return a flattened dict and then merge that into your current dictionary. You should also not modify the dictionary, instead create it with all the values it should have. Here is my approach:

def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
                for subkey, subvalue in flatten_dict(value).items():
                    yield key + "." + subkey, subvalue
            else:
                yield key, value

    return dict(items())

Alternative which avoids yield

def flatten_dict(d):
    def expand(key, value):
        if isinstance(value, dict):
            return [ (key + '.' + k, v) for k, v in flatten_dict(value).items() ]
        else:
            return [ (key, value) ]

    items = [ item for k, v in d.items() for item in expand(k, v) ]

    return dict(items)


This code has basically the same performance issue as your last question, and the performance solution is pretty much the same.  Other things to note:

This is more of a nag than anything, but you should really remove
dead code that is commented out.
The variable Cell is never declared. You should put Option Explicit at the top of all of your code modules. See Why should I
dimension my variables in VBA
really? over on SO.
You don't return a value, so this should really be a Sub, not a
Function.  If you don't want it to appear in the macro list,
declare it as Private. I'd get into the habit of always
explicitly declaring your scope.
You have a bug.  You explain pretty clearly in your question that
the .Value of a cell can differ dramatically from the .Text of a
cell depending on the formatting. However, when you test the length
of the cell values, you're checking against the Value that you
already point out is not dependant on the formatting.  You need to
test the Text against your width.
You have another possible bug (not addressed in the code below) -
for proportional width fonts, the value referred to by ColumnWidth
is based on the width of the character '0' (see the
documentation).
If you happen to be using a font where any character is wider than
'0' (for example 'X' in my browser's default font), you can't reliably use the ColumnWidth as a proxy for the
length of a string that it can display.
255 is the magic number, yes it is. Since you're testing the maximum
width of a text rendered cell to this value, and using it in
multiple places in your code to provide formatting information, make
it a constant and give it an appropriate name.
I'm assuming that the call to RefreshScreen is to provide some
sort of indication to the user that something is actually happening
instead of a hung script.  I'd remove it completely.  If you call
DoEvents Excel will have a chance to update the screen buffer.
This is not only more performant (it avoids a function call), but it
will also be clearer to the reader what is going on. Even better
would be to simply omit it, as redrawing the screen is what is
killing your in performance in the first place (see below).
Personally, I would cache the column widths and reset them when you
are done instead of using the arbitrary value '20'.  This upholds
the principle of least astonishment.
You set the NumberFormat to text for the entire Worksheet at the
end of the Function.  Setting it for individual cells inside your
loop is not only redundant, but forces a ScreenUpdate. This is
killing your performance. Basically, what is happening is that you are updating the display once for every cell in the UsedRange.
This is incredibly expensive.  Turn ScreenUpdating off instead.
As I mentioned in comments to your previous question, updating cells
is more expensive in terms of performance than you might guess.
When you are working with large ranges of cells, you should pull
them into an array if at all possible, then write the entire array
back at once. This lowers your "Excel overhead" almost
quadratically.
You should avoid using the Cells collection (it is entirely
dependant on what object is active) and the Selection object
(almost every operation can be performed with the Range you
already have a reference to).
Use With blocks to your advantage, especially in loops.  Every
 '.' operator that you see in your code causes an object deference
 call.  Wrapping sections where the same object is used repeatedly
 in a With block essentially caches the result of the deference
 instead of repeatedly performing it.
Similar note with pulling cell values from a Range.  Accessing
 the object is much more expensive than storing it.  If you have to
 reference the same value twice (looking at you, If Cell.Text <> Cell.Value And Len(Cell.Value) <= 255 Then), cache it.

The above notes basically boil down to something more like this:

Const MaxTextLength = 255

Private Sub ConvertAllCellsToText()
    StartNewTask "Converting all cells to text"
    Application.ScreenUpdating = False

    Dim MyRange As Range
    Set MyRange = ActiveSheet.UsedRange
    Dim cache() As Long
    cache = GetColumnWidths(MyRange)

    With MyRange
        .ColumnWidth = MaxTextLength
        Dim Values() As Variant
        ReDim Values(.Rows.Count, .Columns.Count)

        Dim col As Long
        Dim row As Long

        For row = 0 To UBound(Values, 1)
            For col = 0 To UBound(Values, 2)
                Dim temp As String
                temp = .Cells(row + 1, col + 1).Text
                If Len(temp) <= MaxTextLength Then
                    Values(row, col) = temp
                End If
            Next col
        Next row
        .NumberFormat = "@"
    End With

    MyRange = Values
    SetColumnWidths MyRange, cache
    Application.ScreenUpdating = True
End Sub

Private Function GetColumnWidths(Target As Range) As Long()
    Dim output() As Long
    ReDim output(1 To Target.Columns.Count)
    Dim index As Long
    For index = 1 To Target.Columns.Count
        output(index) = Target.Columns(index).ColumnWidth
    Next index
    GetColumnWidths = output
End Function

Private Sub SetColumnWidths(Target As Range, widths() As Long)
    Dim index As Long
    For index = LBound(widths) To UBound(widths)
        Target.Columns(index).ColumnWidth = widths(index)
    Next index
End Sub

NOTE: I didn't benchmark this, but I'd ballpark about 100 times faster.

EDIT: Almost forgot.  If you have a bunch of numbers in your sheet, you'll want to ignore the numbers stored as text errors to get another nominal performance gain.  Call it before you turn ScreenUpdating back on.


UIGraphicsImageContext Memory Spike - Reducing Footprint

your image might have 111 KB compressed as an jpg or a png. But for image processing it needs to be decompressed. It will be loaded into memory with 8 or 16 bit for each color channel. With RGB it would be up to 48 bit per pixel and 8 bit for the alpha cannel in case of png. So 5MB would represent roughly 1.25 million pixel, or something like 1000*1250 pixel.


You could turn this into a general purpose plugin, but I'm not gonna go into that. There are also many good plugins that provide this functionality.

I'd ditch the IDs and just use the index of the current element as the reference.

You'll obviously still need a parent element with an ID, for nav and slides, so your code knows where they are.

Create class for active slide/nav, when a nav item is clicked, you get the index, multiply it by slide width/height, and animate. You get the corresponding slide with the index, so no need for IDs. Give the clicked element an active class. First step as soon as click happens would be to remove the active class so you can reassign it.

Then just put together some css using your parent elements class/ID.

Your code will be more generic, and your html will be cleaner.


Does this I/O operation caused a memory leak

Absolutely, the 2nd example is the way to ensure disposable objects/resources are released for the GC. The using clause does this by enforcing the rule that the object being created must inherit from IDisposable. At the closing '}' of each using block, the object is disposed.

In the first example, you will have memory leaks occur if you don't close and dispose the MemoryStream.


HTML Templates with Substitutable Areas - PHP

According your comment you don't want to use a template engine, but are actually creating a new one. At some point you will need loops or ifs and it starts becoming ugly.

PHP is already a template engine. Actually it was designed for exactly this purpose. There is a braceless/echoless syntax for all control structures.

Your template/view:

<!DOCTYPE HTML>

    <title><?=$page_title?></title>
    ...

<?=$page_title?>

            <?=$content?>

     ...

Your controller:

private function generatePageSource($page_title)
{
    $page_title=pdisplay($page_title));
    $content = $this->pagecontent_content;

    ob_start();
    $template=REGISTRY_CODE_PATH . "views/templates/" .
        $this->template_dir . "/main.html";
    include $template;
    $this->page_content=ob_get_clean();
}

Of course you could wrap this in a View class to DRY.


Vigenere encryption assignment for CS50 C course

I'm a C++ programmer. I've never written a C program before. But most of what I say should be applicable.

Globals

int i, c;
char *key;

There's no reason for these variables to be global. These variables should be declared in the same place they are used.

These variables also have very bad names. What is i? What is c? I'll have to read the rest of the code to find out.

String typedef

int main(int argc, string argv[])

I don't think using string is a good idea. Somewhere in that cs50 header there's probably

typedef char *string;

When you apply const to this typedef, you don't get what you expect. You may expect that const string is the same as const char *, but it isn't. const string is the same as char *const. You should use a pointer to a character when you want a pointer to a character.

Declare variables as late as possible

int int_A = (int) 'A';
int int_a = (int) 'a';

When you're declaring your variables, you should leave it to the last minute. If you don't need the variables yet, don't declare them.

Conditions

if (argc != 2)
{
    // The wrong number of arguments
}
else if (argc == 2)
{
    // The right number of arguments
}

If the condition argc != 2 is false, we know that the condition argc == 2 must be true so there is no need to confirm that it is true. Also, when there is the wrong number of arguments, the function returns. Your if should become this:

if (argc != 2)
{
    // The wrong number of arguments
}
// The right number of arguments

Unhelpful error messages

When the user doesn't provide exactly 1 argument, this happens:

printf("Please use a single alphabetic command line argument\n");
return 1;

When the user provides a single argument that does not consist of only alphabetic characters, this happens:

printf("Please use a single alphabetic command line argument\n");
return 1;

You should print two different error messages for two different problems. Perhaps "Please provide a single argument" and "Please provide an alphabetic string"

Bad variable names

for (int z = 0, n = strlen(argv[1]); z < n; z++)
{
    if (isalpha(argv[1][z]) == false)
    {
        printf("Please use a single alphabetic command line argument\n");
        return 1;
    }
}

Here, you're referring to the key as argv[1]. At this point, it might make more sense to say "the key must be an alphabetic string" rather than "the first command-line argument must be an alphabetic string". You're also calculating the size of the key twice. You're doing it here in the for loop, then right after it

// foo bar mitzva
    key = argv[1];
int key_len = strlen(argv[1]);
int key_i[key_len];

We've found the place where key is used. You should put this snippet before the for loop and have the for loop refer to key rather than argv[1].

Strings are pointers, pointers can move

The part of your code that makes sure the key is an alphabetic string can be made more efficient. Your code finds the length of the key twice and then checks to see if every character is alphabetic. This is a whopping 3 iterations when only one is necessary.

char *key = argv[1];
for (const char *k = key; *k != 0; ++k)
{
    if (!isalpha(*k))
    {
        printf("The cipher key must be an alphabetic string\n");
        return 1;
    }
}

Is this a heap allocation?

// get users plaintext
printf("Plaintext: ");
char* plaintext = get_string();

I'm not sure if get_string allocates memory for the string or returns a pointer to static memory. You might want to specify that in a comment. If plaintext is heap allocated, you should call free(plaintext) to free the memory when you're done with it (at the very end of the program).

Characters are numbers

for (i = 0; i < key_len; i++)
{
    if (isupper(key[i]))
    {
        key_i[i] = (argv[1][i] - int_A);
    }
    if (islower(key[i]))
    {
        key_i[i] = (argv[1][i] - int_a);
    }

We've finally found the place where that global i is used. You should declare variables right when you need them. I'm pretty sure you're missing a } at the end of this for loop.

Here, you're copying the key into an array of ints. There is a bit of duplicate work here. If you know that a character is alphabetic, then it can only be upper case or lower case. If you know the character is upper case, then you know that it cannot be lower case. You could actually do this in the same place that you are checking you're characters are alphabetic. What I'm saying is:

char *key = argv[1];
const int key_len = strlen(key);
//If this was C++, I would definitely perform a heap allocation but
//heap allocation is a pain in C so I'll just use this C99 trick.
int key_i[key_len];
for (int idx = 0; idx != key_len; ++idx)
{
    const char character = key[idx];

    if (islower(character))
    {
        // characters are numbers, remember?
        key_i[idx] = character - 'a';
    }
    else if (isupper(character))
    }
        key_i[idx] = character - 'A';
    }
    else
    {
        //If the character is not lower case, and not upper case, then its not alphabetic
        printf("The cipher key must be an alphabetic string\n");
        return 1;
    }
}

The actual cipher part of the cipher program

Alright, now I'll find out what a Vigenere cipher is!

// set i back to 0 for the next loop
i = 0;
// iterate over characters in plaintext and shift plaintext character by key

printf("ciphertext: ");
for (int j = 0, n = strlen(plaintext); j < n; j++)

Use proper variable names. What is i? What is j? You should rename them to key_idx and plaintext_idx respectivly.

Conditionals (again)

int pt = (int) plaintext[j];
if (isalpha(plaintext[j]))
{
    if (isupper(plaintext[j]))
    {
        printf("%c", (((pt - int_A) + key_i[i % key_len]) % 26) + int_A);
    }
    if (islower(plaintext[j]))
    {
        printf("%c", (((pt - int_a) + key_i[i % key_len]) % 26) + int_a);
    }
}
else
{
    printf("%c", plaintext[j]);
}
if (isalpha(plaintext[j]))
{
    i += 1;
}

pt never changes so it should be declared const. There's no need to repeatedly index the plaintext when you already have pt just lying around, not doing much. Try not to pack a whole load of math into one line. If you know that an alphabetic character is not upper case then it must be lower case. This snippet could be simplified to this:

const int pt = plaintext[plaintext_idx];
const int key_char = key_i[key_idx % key_len];
if (isupper(pt))
{
    // most of those brackets are unnecessary.
    printf("%c", (pt - 'A' + key_char) % 26 + 'A');
    key_idx += 1;
}
else if (islower(pt))
{
    printf("%c", (pt - 'a' + key_char) % 26 + 'a');
    key_idx += 1;
}
else
{
    printf("%c", pt);
}

Characters, aren't they weird

Fun fact about C, characters literals aren't actually chars, they're ints! In a lot of places when C expects a "character", what it actually expects is an int. isupper and islower expect ints. printf("%c", integer) expects an int. Just keep that in mind when handling strings in C.

Some more optimization

This program could probably be made much smaller, faster and neater (key_i can be removed) but it's 22:00 in Australia and I have school tomorrow so that's all for now.


Is this the right way to retrieve all the fields from any Object?

In principle, your code is correct (provided you really do not want to deal with fields in superclass). But it can be optimized: inside the first loop, you already have fields so there is no need to save their names in a collection and retrieve later - just use them in place.


You don't need to enumerate twice here

var temp = _context.Users.AsEnumerable().ToList();

You can just call .ToList().
SingleOrDefault() also accepts predicates so the first .Where() call is unnecessary, you can just do it like this :

Your code :

var temp = _context.Users.Where(x => x.id == id).SingleOrDefault();

Can become :

var temp = _context.Users.SingleOrDefault(x => x.id == id);

I don't see any reason to call .ToList() here :

    var temp = _context.Users.ToList();
    if (temp.Any(x => x.name == name))
    {
        ViewBag.NotUnique = true;
        return RedirectToAction("Customers");
    }

You are not performing any List<T> specific operations, (I assume Users is  IEnumerable<T>), you are good with a pure IEnumerable<T> here. In fact, you don't even need the temp variable, you can just directly access _context.Users.
You can have just ActionResult instead of IActionResult as a return type for your methods.

Design

Usually asp.net-mvc projects work with multiple DTO's (Data Transfer Object), which are almost identical to your actual model, but you can remove some things and add others, so that you can define the way your data will be passed around your application. Often the ViewModel is mapped in a way to it's respective DTO, to ease the creation of both objects.

Even tho simple projects probably wont need any additional DTO's.
Your models should have  proper validation instead of some check against null in your controller, which should only verify that the validation is successful. For example DataAnnotations offers quite some variety of pre-written validation attributes. You can of course extend this with your own, but it already has the core things you might need. You can find examples here


Q&A

  Is the code readable?

ExactlyOne states very clearly what the method is supposed to do.
source is null seems odd to me (does that even compile?). I'd prefer source == null. (Edit from comments: a topic about is null vs == null)
IEnumerator<TSource> enumerator = source.GetEnumerator() can be written as var enumerator = source.GetEnumerator().

  Is the code maintainable?

Since you are looking for a sibling function of Any<T>(), I would also include a ExactlyOne<T>(Func<T, bool> predicate).

  Is the code performant?

It does seem so, right? But notice that LINQ is optimized for IEnumerable<T> that is also ICollection<T>, in which case Count is used. Implementations should have an eager implementation of this property. Your method could also use this optimization Count == 1.
I actually noticed (in my eyes) unexpected behavior in LINQ: Count<T>() is optimized for ICollection<T> but Any<T() is not. This means you arguably could make a slightly faster implementation than LINQ.
An in-depth comparison is required to find the most optimized approach. As discussed in the comments, testing the different implementations against a variety of input sources should yield us which method perfoms best under which conditions.

  Do the tests cover the expected cases or are there more to consider?

You cover null, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T> and custom IEnumerable<T> implementations with eager and/or lazy loading.

Reference Source: LINQ Any vs Count

// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        if (e.MoveNext()) return true;
    }
    return false;
}

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) {
        if (predicate(element)) return true;
    }
    return false;
}

// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    ICollection<TSource> collectionoft = source as ICollection<TSource>;
    if (collectionoft != null) return collectionoft.Count;
    ICollection collection = source as ICollection;
    if (collection != null) return collection.Count;
    int count = 0;
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        checked {
            while (e.MoveNext()) count++;
        }
    }
    return count;
}


Some benchmarks

I am guessing a function like this is written, apart from an exercise, to search for power numbers. Thus execution time is important.

String manipulation and type conversion is not something that javascript likes to do, so running the two given answers in a profiler I measured the time to run the following loop.

var i;
for (i = 0; i < 1000; i += 1) {
    digPow(Math.floor(Math.random() * 10000000),i%10);
}

I ran the tests for many minutes the results were

ashraf aaref's  function ran twice as fast as Oleander's on Firefox, running on an old Win10 32Bit laptop. The times; 2ms and 4ms respectively for the above loop. Which equates to 500,000 and 250,000 calls to the function digPow (plus overhead of loop and call) per sec,

The array method reduce is the bottleneck in the slowest version. For performance always avoid any of the array iteration functions as each interaction involves a function call that needs to save the current context.

Type conversion is the bottleneck in the second function.

Avoiding both bottlenecks

But there is a much faster method that avoids the type conversion

 function digPowC(n, p){
    var digits, result, i, num;
    digits = Math.floor(Math.log10(n)) + p;  // get the number of digits
                                             // add the power p
    result = 0;
    num = n;                                 // running least significant digit
    while(digits >= p){                      // Stop at p
        result += Math.pow((num % 10),digits--);  // pow least significant digit
        num = Math.floor(num / 10);
    }
    if(result % n === 0){  // vet result
        return result / n;
    }
    return -1;
}

Which is twice as fast again at 1ms or 1,000,000 calls per second.

Which is the best, that could be debated forever as all three work except for one problem that is often forgotten when manipulating numbers.

digPow(1e100,1) is not dealt with. The two string methods fail as they try to evaluate the "e" and the pure number version fails trying to maintain the least significant digit that is way outside the 64bit Double's precision. But then we assume that arguments are vetted.

Results of a benchmark

Not runnable just hidden to avoid clutter.

// Each function is duplicated and randomly called the mean is the mean of all 4 tests
/* Raw output from tester

Test : 'Oleander'
4.155microsec 3155 samples
4.161microsec 3057 samples
4.169microsec 3128 samples
4.124microsec 3142 samples
Test : 'ashraf aaref'
2.207microsec 3186 samples
2.200microsec 3150 samples
2.203microsec 3011 samples
2.200microsec 3214 samples
Test : 'Blindman67'
1.068microsec 3158 samples
1.060microsec 3146 samples
1.058microsec 3110 samples
1.068microsec 3143 samples
----------------------------------------------------------
Test : 'Oleander'
Mean : 4.152ms 12482 samples
Min : 4.124ms Max : 4.169ms
----------------------------------------------------------
Test : 'ashraf aaref'
Mean : 2.203ms 12561 samples
Min : 2.200ms Max : 2.207ms
----------------------------------------------------------
Test : 'Blindman67'
Mean : 1.064ms 12557 samples
Min : 1.058ms Max : 1.068ms
----------------------------------------------------------
Mean : 2.469ms Totals time : 92849.685ms 37600 samples

end of output */

// the sample function. Running this function constitutes one sample.
func : function(){
    var i;
    for (i = 0; i < 1000; i += 1) {
        digPow(Math.floor(Math.random() * 10000000),i%10);
    }
},

// Functions all run in strict mode.

// Test : 'Oleander'
function digPowA(n, p){
    const digits = n.toString().split('');
    const result = digits.reduce(function(acc, value, index) {
        return acc + Math.pow(value, index + p);
    }, 0);

    if (result % n === 0){
        return result / n;
    } else {
        return -1;
    }
}
// Test : 'ashraf aaref'
function digPowB(n, p){
    var digits = n.toString(); //** without split should be faster**
    var result = 0;
    for(var i=0; i<digits.length; i++){
        result = result + Math.pow(digits[i], p);
        p++;
    }
    if(result % n === 0){
        return result/n;
    }else{
        return -1;
    }
}
// Test : 'Blindman67'
function digPowC(n, p){
    var digits, result,i;
    digits = Math.floor(Math.log10(n)) + p;
    result = 0;
    var num = n;
    while(digits >= p){
        result += Math.pow((num % 10),digits--);
        num = Math.floor(num / 10);
    }
    if(result % n === 0){
        return result/n;
    }
    return -1;
}


Find indices of first pair of numbers that sums to zero

The problem can be solved in less than quadratic time. Sort the elements by absolute value, then search for consecutive elements that sum up to zero.

def two_sum(nums)
    temp = nums.map.with_index { |x, i| [x, i] }
    temp.sort_by! { |x| x[0].abs }
    for x in temp.zip(temp.rotate)
        if x[0][0] + x[1][0] == 0
            return [x[0][1], x[1][1]]
        end
    end
    return nil
end


Object-oriented approach to sieve of Eratosthenes

Is "n" really a good idea?

I don't like arr[i].getn().  The whole algorithm relies on the fact that arr[i].getn() is exactly i+1.  If this is ever not true, then the sieve will not work.  Given that the array index is inextricably linked to the value of n, I wouldn't even bother with n at all.

Using constant expressions in loop conditions

In two places, you use constant expressions in your loop condition:

for (i = 1; i < sqrt(n); ++i) // sqrt() on every loop
for (unsigned j = 1; j < ( n / (arr[i].getn()) ); ++j) // division on every loop

What's bad about this is that you will be calling sqrt() or doing a division on every loop, even though the value of the expression will never change.  It's possible the compiler could optimize this for you, but it's not a certainty.  It's easy enough to just move the expression out of the loop yourself:

int sqrtN = sqrt(n);
for (i = 1; i < sqrtN; ++i)

Simplifying the loop

Even after getting rid of getn(), the second loop can still be simplified.  The current loop is this:

for (unsigned j = 1; j < (n / (i+1)); ++j) {
    arr[i + j * (i+1)].setflagged(true);
}

It can be simplified to this:

for (unsigned j = i+(i+1); j < n; j += (i+1)) {
    arr[j].setflagged(true);
}

In other words, instead of computing the array index using a multiplication, you can just have j be the array index.  This way avoids any multiplications and divisions and in my opinion is also simpler to read.  It would be even simpler if arr[i] stood for the number i instead of i+1.


Handler for default values in a CLI flag utility library in C

Yes, there are things to improve:

if (defaults == NULL) {
    defaults = malloc(10 * sizeof(struct pair));
}

static short pos = 0;
if(pos % 10 == 0) {
    defaults = realloc(defaults, (pos + 10) * sizeof(struct pair));
}

That allocates space for 10 elements, and then re-allocates space for ten elements. What a waste of time.

Additionally, avoid sizeof(TYPE). sizeof expr is safer, and will be obviously correct.

Next, allocating memory is known to fail sometimes. So, check for that.

And finally, rework setDefault() and clearDefaults() so the latter actually only clears the defaults.

bool setDefault(const char *flagName, const char *defaultValue) {
    static short pos = 0;
    if (!defaults) pos = 0;
    if (pos % 10 == 0) {
        struct pair* temp = realloc(defaults, (pos + 10) * sizeof *temp);
        if (!temp) return false;
        defaults = temp;
    }
    ...
}

static void clearDefaults(void) {
    free(defaults);
    defaults = NULL;
}

Are you sure you want to use strncpy()? You know that's not really a string-function, but a zero-padding function?

Another interesting question is how the other functions should know how many elements are in the list. I have no idea, design something.

Also, consider being more dynamic, and just saving two pointers to independently-allocated strings in the pair-element.

And if having defaults starts as a null-pointer-value really disturbs you, just initialize it to oint to a statically-allocated null-object.


Comparing corresponding elements of two equal-length arrays

I don't know TypeScript or lodash, but I hope the following code is at least almost correct. You should be able to use zip and map to solve the problem in a functional manner.

function changed(a, b) {
    return _.zip(a, b).map(x => { return x[0] !== x[1] });
}

Basically, the problem of what has changed can be rephrased as which elements are equal.


Speeding up Python date conversion function currently using list comprehension and datetime

You should try Numpy's datetime and timedelta support:

def days2dt(days_since_epoch):
    microseconds = np.around(np.asarray(days_since_epoch) * (24*60*60*10**6))
    return np.datetime64('1980-01-06') + microseconds.astype('timedelta64[us]')

I suggest you read the units section of the docs to make sure this is safe (both resolution and min/max dates), but it should be fine.

Note that 90% of the time taken for days2dt is converting the input list to a numpy.array; if you pass in a numpy.array it goes much faster. Nevertheless, this is significantly faster than the list comprehension already.


When creating classes in Python 2, you need to have classes explicitly inherit from object, like this:

class MyClass(object):
    ...

If you're creating a class in Python 3, you don't need to explicitly inherit from object.

As the classic Stop Writing Classes puts it, one characteristic of a class that should be a function is if the class has only two methods, __init__, and another. This means that your Thieves class would become one method, like this:

def thieves(details, items):
    ...


Optimizing large file reads with a custom line terminator in Python

1. Bug

If the file does not end with the line terminator, then the last line is lost. That's because the code says:

if not data:  # EOF
    break

but at this point there might still be an unterminated line remaining in chunk, so this needs to be:

if not data:  # EOF
    if chunk:
        yield chunk
    break

Perhaps in your case the file is required to always end with a line terminator, but if so it would be a good idea to assert this, rather than silently discarding data if the file does not meet the requirement:

if not data:  # EOF
    if chunk:
        raise ValueError("file does not end with line terminator")
    break

2. Separation of concerns

The code in the post has four concerns:

Opening and closing a file.
Generating chunks of 100 kilobytes from a file.
Generating lines from a file with arbitrary line terminator.
Filtering out blank lines.

The principle of separation of concerns suggests that these should not be combined into one function. Taking the four concerns in turn:

As a general rule, if you have a function that operates on the contents of a file, it's better if the function takes a file-like object (not a filename) and leaves the opening and closing of the file up to the caller. That's because not all file-like objects correspond to named files. The caller might have a pipe from a call to subprocess.Popen, or they might have some data in memory wrapped as a io.StringIO. If an interface takes a filename and opens the file itself, then it can't be used with these other kinds of file-like object.
Reading fixed-size chunks from a file is already implemented by the read method.
This is fine, but see below for some improvements.
Filtering out blank lines might not be needed or wanted, so it should be left to the caller to decide whether to do it. It is in any case easy to implement using an if statement, or a comprehension, or filter.

3. Other points

There are no docstrings.
When you have a class with __init__ and one other method, then there is usually no need for a class: what you want is a function. (See Jack Diederich's PyCon 2012 talk "Stop Writing Classes" for a detailed look at this issue.)
100 × 1024 bytes is one hundred kilobytes (not megabytes).
Instead of having a keyword argument with default value of None:

def read(..., chunk_size=None):

and then later setting it to a particular value if it tests false:

one_hundred_megabytes = 100 * 1024
chunk_size = chunk_size or one_hundred_megabytes

just specify the keyword argument with the default value you want:

def read(..., chunk_size=100 * 1024):

The code appends to chunk before testing for the line terminator:

chunk += data
# ...
elif self._lineterminator in chunk:

but we know that if the line terminator appears, then it must appear in the new part of the chunk (that we just read). It can't appear in the old part because then it would have been split on the previous iteration. This means that if multiple chunks need to be read before the line terminator appears, then the initial part of the line gets searched again each time. This leads to quadratic runtime complexity if lines are much longer than the chunk size.

For efficiency, we should test self._lineterminator in data instead.
The code tests for the line terminator appearing in the chunk and then splits the chunk if it is found.

elif self._lineterminator in chunk:
    lines = chunk.split(self._lineterminator)

but this has to search the chunk twice, once for the in operator, and again for the split. It would be faster to split first and then see how many pieces there are:

lines = chunk.split(self._lineterminator)
if len(lines) > 1:

Combining points 5 and 6 above, we should split data first and append to chunk afterwards:

first, *rest = data.split(self._lineterminator)
chunk += first
if rest:
    yield chunk
    yield from rest[:-1]
    chunk = rest[-1]

I think the names would be clearer if chunk were renamed part (because it is part of a line), and data were renamed chunk (because it is a chunk of text read from the file).

4. Revised code

def splitlines(file, newline, chunk_size=4096):
    """Generate lines from file (a file-like object), where a line is
    followed by the string newline (or the end of the file). Optional
    argument chunk_size is the size of the chunks read from the file.

    """
    part = ''
    while True:
        chunk = file.read(chunk_size)
        if not chunk:
            if part:
                yield part
            break
        first, *rest = chunk.split(newline)
        part += first
        if rest:
            yield part
            yield from rest[:-1]
            part = rest[-1]

The caller should write something like:

with open(longabstract_file) as f:
    for line in splitlines(f, "\tl\n"):
        if line: # ignore blank lines
            print(line)


Project Euler 22: Names scores using dictionary

Nice PEP8 compliant code, Phrancis. Good job! I only have two comments to make regarding that: you usually have to use triple-double quoted strings when it comes to docstrings. From the docs (PEP257):

For consistency, always use """triple double quotes""" around
docstrings. Use r"""raw triple double quotes""" if you use any
backslashes in your docstrings. For Unicode docstrings, use
u"""Unicode triple-quoted strings""" .

More, you missed one newline between your imports and the first function. It's not such a big deal but I thought it's worth mentioning it.
In this line:
...
return file_.read().replace("\"", "").split(",")

You can use single quotes to get rid of the escape character \:
return file_.read().replace('"', '').split(',')

You can also omit the read file mode as that's the default mode when you read a file:
with open(file_path) as file_:
    ...

There's more than one place where you wrote:
something = list(string)

Instead of the situation where you sorted the list, you don't need list(string) because you can already iterate a string just fine.
Use enumerate() more often.
The enumerate() function adds a counter to an iterable. That said, you can rewrite your get_alpha_values() function like this:
def get_alpha_values() -> Dict:
    alpha_values = {}
    for index, letter in enumerate(string.ascii_uppercase, 1):
        alpha_values[letter] = index
    return alpha_values

Enumerate takes a second argument which lets you start from whatever position you want (in our case, that would be 1).
We can also make use of the get() method of the dicts and make your get_word_alpha_value() more straightforward:
def get_word_alpha_value(word: str, alpha_values: Dict) -> int:
    return sum([alpha_values.get(letter, 0) for letter in word])

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None)


Convert object with 'long.property.name' property to object tree

If I had to take a stab at it I would write something like this:

function convertToTree(rowObjectData) {

  function isArrayKey(key) {
    return _.last(key) == ']';
  }

  function setValue(object, value, key) {
    var parts   = key.split(/[.[]/),
        last    = parts.length - 1;

    for (var i=0, current=object;
         i < parts.length;
         i++, current = current[k]) {
      var p = parts[i],
          k = isArrayKey(p) ? parseInt(p) : p;
      if (i == last)
        current[k] = value;
      else if (current[k] == undefined)
        current[k] = isArrayKey( parts[i+1] ) ? [] : {}
    }

    return object;
  }

  return _.reduce(rowObjectData, setValue, _.cloneDeep(rowObjectData) );
}

var object = {
    42: 'foo',
    'a.b.c[0].42':    'bar',
    'a.b.c[0].43':    'zet',
    'a.d.c[0].42':    'baz',
    'a.d.c[1]':       'zaphod',
    'a.d.c[2][0].49': 'beeblebrox',
};

console.log(convertToTree(object));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>

Which also allows multiple sequential arrays (c[0][1].49 = 'foo' and doesn't require the last key to be an object (c[0] = 'foo')


Indentation

Your code's indentation is wrong, the class and method declaration should not be on the same line.

Whitespace

Your code has incorrect whitespace in places, for example:

int maxValue = numofDie*6;

and here:

case 4: taco[0] += 1;
    break;

The first one is missing whitespace between the operators, and the second one should have the taco[0] statement on a new line.

switch:

Your entire switch statement could be condensed to this:

taco[oneTotalRoll - 4] += 1;

All of your cases were testing if oneTotalRoll's value was 4 more than the array position, so in that case, you could just minus four from oneTotalRoll and use that as an index position.

Naming

You have variables named like taco , gorgon, N and M.

These should be named to things that are closer to their usage and what they are, for example:

taco into rollCount
gorgon into condensedList
N into stringDieCount
M into stringRollCount

String concatenation

Instead of string concatenating everything at the end, consider using an Array join to "glue" everything together with a common join (,).


Generic extension method for NullIf() supporting nullable and non-nullable value types

Just a couple of observations:

Neither Comparer<T> nor IComparer<T> pose any type restrictions on T. So I don't see any need for imposing an IComparable restriction in the implementation.
The other option would be to keep the IComparable restriction and make actually use of that interface (i.e. return value.CompareTo(equalsThis) == 0)

IComparable is the wrong abstraction to use. IComparable is meant for objects to provide a sort order as it has the concept of smaller, equal and greater. For your purposes you simply want to test for equality - so you should use IEquatable<T> or EqualityComparer<T> instead.

Update:
Turns out that enums generally don't implement IEquatable<T>. The best option in that case would probably be to allow the user to optionally pass in an IEqualityComparer<T> defaulting to EqualityComparer<T>.Default and again not impose any additional type restrictions.


Still learning, looking for general advice about a 4-function calculator I programmed using java

It would be best to codify the various operations in a separate function. This limits the opportunity for error and eliminates the redundancy of the System.out.println("Result: " + a); statements.
   private static int applyOperation(int x, int y, int op) {
      switch(op) {
         case 1: return x*y;
         case 2: return x/y;
         case 3: return x+y;
         case 4: default: return x-y;
      }
   }
   public static void main(String[] args) {
      System.out.print("Enter the first value ");
      Scanner scan = new Scanner(System.in);
      int x = scan.nextInt();
      System.out.print("Enter the next value ");
      int y = scan.nextInt();
      System.out.println("Choose an operation: 1-multiply 2-divide 3-add 4-subtract");
      int op = scan.nextInt();
      int ans = applyOperation((x), y, op);
      System.out.println("Result: " + ans);
   }


The first consideration is that your method:

private Set<JiraTicket> getJiraTicketsAsync(JsonArray ticketsArray)

Is not asynchronous at all.

As it returns a Set of JiraTicket when you call it you wait until the collection is completed.

So the method name is not correct, and could drive to missunderanding.

On your code:

ExecutorService service = Executors.newCachedThreadPool();
List<Future<JiraTicket>> futures = service.invokeAll(tasks);
for(Future<JiraTicket> future: futures){
    try
    {
        tickets.add(future.get());
    } catch (ExecutionException e)
    {
        logger.error("There was an error getting a jira ticket", e);
    }
}
service.shutdown();

The problem here is the for loop where you consume the Future object.
Of course you parallelize the requests on multiple threads, so you will probably gain a little bit of efficiency, but your code is still blocking.

The way to write concurrent code is not trivial, you have to break up your flow and rething it starting on dependencies.

You need JiraTicket in order to get infos from Github. In that way you should think your task like so:

Get the user JiraTicket
Get the infos from Github
Go to the next JiraTicket

At the end of this concurrent tasks you could do the sequencing tasks like create a Developer object and so on.

In a comment I suggest you to use a queue instead of use any sort of collection.
The reason is that a collection need to be synchronized and for that reason will stuck you on blocking code.

If you need to speed up and use advantage of concurrency, you should avoid blocking code.

A queue decouple the producer part, where you call the Jira and Github servers, from the consumer part, where you create the Developer object and complete the report.

The advantage in your case depends on the magnitude of the number of object you're dealing with, and the time your flow is using now.

There are many libraries that could help you to achieve the asyncronous part, such JMS, Reactive Streams or design pattern like using Publisher / Subscriber pattern.


Calculate highest prime factor very slow

You want to compute the largest prime factor of a given number, but it is actually more efficient to look for the smallest prime factors first (and I am just repeating my arguments from my answer). If you test the possible factors in increasing order and divide the given number by a found factor as much as possible, then each found factor is necessarily a prime number. This means that no primality test is needed at all.

This leads to the following function (which is just a translation of the referenced
answer to Python):

def max_prime_factor(n):
    '''find the largest prime factor of integer n'''

    largest_factor = 1
    i = 2

    # i is a possible *smallest* factor of the (remaining) number n.
    # If i * i > n then n is either 1 or a prime number.
    while i * i <= n:
        if n % i == 0:
            largest_factor = i
            # Divide by the highest possible power of the found factor:
            while n % i == 0:
                n //= i
        i = 3 if i == 2 else i + 2

    if n > 1:
        # n is a prime number and therefore the largest prime factor of the
        # original number.
        largest_factor = n

    return largest_factor

Timing for the largest prime factor of 600851475143 (on a 3,5 GHz Intel Core i5 iMac):

Your method: 43 seconds
Sieve method from @wei2912: 0.2 seconds
Above method: 0.016 seconds