Converting date format in range of cells

In solving the overall problem of date conversion, your code makes a few assumptions that have tripped me up in the past.

Always use Option Explicit
Set references to the workbook and your worksheets
Make a habit of trying to use arrays instead of cells directly from the worksheet

Using these habits along will greatly improve your code. In particular, notice in the example below how all the variables end up being fully referenced back to the parent sheet and workbook so that you (and the VBA) never gets confused.

I found it less useful to have a single function that determined the last row or column or cell, since that generated more code than I usually use to find it. Instead, I arrived at a different decomposition of the problem into functions.

While you created a function to find the last row/cell/column, you also have a repeated need to convert the dates within an area. So the "main" routine breaks down into an easily understandable set of repeatable steps (functions):

Option Explicit

Public Sub main()
    Dim wb As Workbook
    Dim targetDateSheet As Worksheet
    Dim myDateArea As Range
    Set wb = ThisWorkbook

    Set targetDateSheet = wb.Sheets("MySheet1")
    Set myDateArea = GetDataArea(targetDateSheet, "Start")
    ConvertDates myDateArea

    Set targetDateSheet = wb.Sheets("MySheet2")
    Set myDateArea = GetDataArea(targetDateSheet, "Keyfield")
    ConvertDates myDateArea
End Sub

The GetDataArea function quickly determines where the dates are based on a search for the key field:

Private Function GetDataArea(ByRef targetSheet As Worksheet, _
                             ByRef keyField As String) As Range
    Dim theArea As Range
    Dim lastRow As Long
    Dim lastCol As Long
    Dim numRows As Long
    Dim numCols As Long
    With targetSheet
        Set theArea = .Cells.Find(keyField)
        If Not theArea Is Nothing Then
            lastRow = .Cells(.Cells.Rows.Count, theArea.Cells(1, 1).Column).End(xlUp).Row
            lastCol = .Cells(theArea.Cells(1, 1).Row, .Cells.Columns.Count).End(xlToLeft).Column
            numRows = lastRow - theArea.Cells(1, 1).Row
            numCols = lastCol - theArea.Cells(1, 1).Column + 1
            '--- assume the first row contains headers for each column, so offset
            Set GetDataArea = theArea.Offset(1, 0).Resize(numRows, numCols)
        Else
            theArea = Nothing
        End If
    End With
End Function

I've found it much quicker and simpler to find the last row and column using the above method, rather than the Find method.

Converting the dates in the given range then breaks down into these pseudo-steps:

copy the cell range into a memory array (for speed and ease of referencing)
loop through the entire array and detect the date data and convert it to the Excel serial date (numerical) value
copy the converted array back to the worksheet range and set the desired date format

It's very important NOT to assume that the text string you find is read by excel as a date string. It may or may not be recognized that way. In order to guarantee you're converting the string to an Excel date value, you should use the DateSerial function as shown and then format the worksheet cells as you need.

This becomes:

Private Sub ConvertDates(ByRef theArea As Range)
    Dim area As Variant
    area = theArea                               'copied to memory array

    '--- look for a string pattern with two "/"s and assume that value
    '    is a European-format date string
    Dim i As Long
    Dim j As Long
    For i = LBound(area, 1) To UBound(area, 1)
        For j = LBound(area, 2) To UBound(area, 2)
            Dim pos1 As Long
            Dim pos2 As Long
            pos1 = 0
            pos2 = 0
            pos1 = InStr(1, area(i, j), "/", vbTextCompare)
            If pos1 > 0 Then
                pos2 = InStr(pos1 + 1, area(i, j), "/", vbTextCompare)
            End If
            If (pos1 > 0) And (pos2 > 0) Then
                Dim dd As Long
                Dim mm As Long
                Dim yy As Long
                dd = CLng(Left(area(i, j), pos1 - 1))
                mm = CLng(Mid(area(i, j), pos1 + 1, pos2 - pos1 - 1))
                yy = CLng(Right(area(i, j), Len(area(i, j)) - pos2))
                area(i, j) = DateSerial(yy, mm, dd)
            End If
        Next j
    Next i

    '--- now put the array back onto the worksheet and set the
    '    number format for those cells to the desired
    theArea = area
    theArea.Cells.NumberFormat = "dd-mmm-yyyy"
End Sub

Note that I'm testing each value to make certain it's a date with two "/" appearing before I attempt to convert it.

For convenience, here's the whole module in a single area:

Option Explicit

Public Sub main()
    Dim wb As Workbook
    Dim targetDateSheet As Worksheet
    Dim myDateArea As Range
    Set wb = ThisWorkbook

    Set targetDateSheet = wb.Sheets("MySheet1")
    Set myDateArea = GetDataArea(targetDateSheet, "Start")
    ConvertDates myDateArea

    Set targetDateSheet = wb.Sheets("MySheet2")
    Set myDateArea = GetDataArea(targetDateSheet, "Keyfield")
    ConvertDates myDateArea
End Sub

Private Function GetDataArea(ByRef targetSheet As Worksheet, _
                             ByRef keyField As String) As Range
    Dim theArea As Range
    Dim lastRow As Long
    Dim lastCol As Long
    Dim numRows As Long
    Dim numCols As Long
    With targetSheet
        Set theArea = .Cells.Find(keyField)
        If Not theArea Is Nothing Then
            lastRow = .Cells(.Cells.Rows.Count, theArea.Cells(1, 1).Column).End(xlUp).Row
            lastCol = .Cells(theArea.Cells(1, 1).Row, .Cells.Columns.Count).End(xlToLeft).Column
            numRows = lastRow - theArea.Cells(1, 1).Row
            numCols = lastCol - theArea.Cells(1, 1).Column + 1
            '--- assume the first row contains headers for each column, so offset
            Set GetDataArea = theArea.Offset(1, 0).Resize(numRows, numCols)
        Else
            theArea = Nothing
        End If
    End With
End Function

Private Sub ConvertDates(ByRef theArea As Range)
    Dim area As Variant
    area = theArea                               'copied to memory array

    '--- look for a string pattern with two "/"s and assume that value
    '    is a European-format date string
    Dim i As Long
    Dim j As Long
    For i = LBound(area, 1) To UBound(area, 1)
        For j = LBound(area, 2) To UBound(area, 2)
            Dim pos1 As Long
            Dim pos2 As Long
            pos1 = 0
            pos2 = 0
            pos1 = InStr(1, area(i, j), "/", vbTextCompare)
            If pos1 > 0 Then
                pos2 = InStr(pos1 + 1, area(i, j), "/", vbTextCompare)
            End If
            If (pos1 > 0) And (pos2 > 0) Then
                Dim dd As Long
                Dim mm As Long
                Dim yy As Long
                dd = CLng(Left(area(i, j), pos1 - 1))
                mm = CLng(Mid(area(i, j), pos1 + 1, pos2 - pos1 - 1))
                yy = CLng(Right(area(i, j), Len(area(i, j)) - pos2))
                area(i, j) = DateSerial(yy, mm, dd)
            End If
        Next j
    Next i

    '--- now put the array back onto the worksheet and set the
    '    number format for those cells to the desired
    theArea = area
    theArea.Cells.NumberFormat = "dd-mmm-yyyy"
End Sub


Shortest path in a grid between two points

I think BFS is your algorithm, but I do have some cleanups for you. The reason A* won't work is because your estimation of how much farther you have to go (you could do a simple grid distance from where you are to the end point, also considering the jump value where you are sitting) could be wrong based on future jumps, and in your case, estimations are not acceptable. (Note: in some cases, for example if this was an AI in a game, estimation can be acceptable if performance is greatly improved)

Use a queue instead of a vector for openList. Every erase on the first item in a vector means you have to copy all the items to new memory positions!!! BFS algorithm and  std::queue are a married pair because your push and pop are constant time, and you won't accidentally push or pop at the wrong end.
You are keeping a list of visited points, but you aren't using this list, and you aren't using it because you don't need it. You can't go backwards in your path toward the end, so you don't have to keep track of where you have been.


Count the number of occurrences of a word

First of all, these interview questions are often a trick. It doesn't really matter if your code works for all cases (everybody makes mistakes). What does matter is how you write the code.

Even if they ask specifically for 'a' or 'A', you are not supposed to hardcode these values. They are a parameter. Understanding what is the input to your program is always the first task. If they ask you "Make a program that counts the number of times the letter 'a' occurs in 'Example'", the correct answer won't be return 1;. They also ask for words, you shouldn't assume that the program should search only for words withs 1 letter.

Second - words are not usually delimited only by a space. You should consider all whitespace and punctuation characters. Or just declare a function isWordDelimiter(char) and don't implement it.

Third - your code is not easily readable. An if inside another if in a for? Use functions. Example (pseudocode - I am not C++ programmer and I forgot STL):

while ((word = getNextWord(input)) != NULL) {
    if (word is in set of searched words) {  //replace this with STL set
        count++
    }
}

Summary:
Even on a very simple program, they can see how much experienced you are. Good developer won't just write something that works. He has to think how the problem will evolve in the future (different parameters), how the program will be maintained (write readable code). Good developers also write programs from top to bottom - first define the structure using high level functions, then write the implementation of the functions.


How to improve this algorithm for building a graphs closures

Since your nodes are double-linked (i.e. each has a list of all parents and children), creating the list of closures for all children of a certain node (especially the root node) seems like an overkill, especially if you're doing that whenever you start to filter. If you have a doubly linked graph, descendant and ancestor lists seem pretty cheap to get for each node, and for a large graph you will have to waste an awful lot of memory to keep them around.

If I am not mistaken, for each "chosen" node, you need to mark that node as safe, mark its children as safe, then traverse back to the root and mark all nodes you encounter as safe, and finally remove all non marked nodes. That should be much less work than you're doing now, if I didn't misunderstand the problem completely.

Some minor issues:

To merge two HashSets, it's much cheaper to use HashSet.UnionWith, than to create a new HastSet each time (like you're doing in your Filter method).
Btw, by looking at your code, it seems that Node.AnyDescendant should iterate through Children, not Parents.

I.e. wouldn't this work:

public static Node Filter(Node startNode, IEnumerable<int> includedNodes)
{
    var explicitlyIncludedNodes = startNode
        .Descendants()
        .Where(n => includedNodes.Contains(n.Id));

    var nodesToKeep = new HashSet<int>();
    foreach (var node in explicitlyIncludedNodes)
    {
        nodesToKeep.UnionWith(node.Ancestors().Select(n => n.Id));
        nodesToKeep.UnionWith(node.Descendants().Select(n => n.Id));
    }

    return BreadthFirstDeletion(startNode, nodesToKeep, includedNodes.ToArray());
}

Ancestors() should simply return all ancestors all the way to the root:

public IEnumerable<Node> Ancestors()
{
    var stack = new Stack<Node>();
    stack.Push(this);
    while (stack.Count != 0)
    {
        var current = stack.Pop();
        yield return current;

        foreach (var child in current.Parents)
            stack.Push(child);
    }
}

(Descendants the same way but for Children instead of Parents)


Ranking players in a league by sorting the contents of an OrderedDict

First of all, your entire def player_rank: is way over-engineered.. and with the correct standard modules this practically becomes a one-liner

Review

Use better variable names (naming is hard), but to me names like c, x makes no sense. I don't know what they do at all.
Use built in methods, like sort() this greatly reduces complexity.
With the full powers of sorted() you can sort multiple items at once.
With a - before the item we are sorting you can reverse the order, that makes it easier to sort multiple items on different orders.

With my changes I get the following code.

from collections import OrderedDict, Counter

class LeagueTable:
    def __init__(self, players):
        self.standings = OrderedDict([(player, Counter()) for player in players])

    def record_result(self, player, score):
        self.standings[player]['games_played'] += 1
        self.standings[player]['score'] += score

    def player_rank(self, rank):
        return sorted(self.standings, key=lambda p: (-self.standings[p]['score'],
                                                     self.standings[p]['games_played']))[rank-1]


Omit the extra == true in conditions:

if(randomBool())

Use the ternary if operator to compact your code:

left_side.push(randomChoice(randomBool() ? chars : double_chars))

If this seems to dense for you, you can also extract the inner expression like this:

var options = randomBool() ? chars : double_chars;
left_side.push(randomChoice(options))


Adding labels and fields to a nested JSON

The rgp loop can be made more compact, and a bit faster, with:

def foo2(rgp):
    alist = []
    for n, g in rgp:
        temp2 = {"name": n}
        values = g.T.to_dict().values()
        n = len(values)
        def size(t):
            return (t['Rating'] * t['Count'] * 10000) / n
        temp3 = [{'name': t['Name'], 'size': size(t)} for t in values]
        temp2['children'] = temp3
        alist.append(temp2)
    return alist

I don't have enough experience with Pandas to know whether it is possible to improve on the groupby.  For example, it would be possible to perform a 2 level grouping with one call - ie. group on 'Count' and within that 'Rating'?

Considering that json is a string version of a dict, and you have a specific dictionary layout in mind, I don't see how you can organize the code in any other way.  With the exception of update, all dictionary additions are key by key.  So you have to have these 2 loops over groups.


Display characters remaining next to input/textarea

You're misusing what jQuery.noConflict does.

var jq = jQuery.noConflict();

You're using it like it creates another instance of jQuery, or something similar.

What it actually does is relinquish control of the $ variable.

Due to other libraries using $, jQuery needs to be able to return and reset what $ originally was.

Imagine this:

var $ = function(){ console.log(arguments) }; //A debugging function.

//Induction of jQuery here.

$('body'); //Returns a node containing the DOM body element.
$.noConflict();
$('body'); //Returns ['body'].

You're using it wrong.

Using jQuery

jQuery is a framework used by many to simplify processes, but do you really need it?

An important question to ask yourself when designing / architecting a new system is whether you need a library or not.

If you're building a slick, lightning-fast mobile site, you may not have room for massive libraries like jQuery.

Luckily, people realise this and write helpful companion sites you can use like YouMightNotNeedjQuery.com

Consider carefully whether it's better to write a little more code and not use jQuery, or whether it's better to lose a little performance.

Bracket spacing

You shouldn't be adding spaces inside your brackets like the following example:

jQuery( document ).ready( function() {

It should look like:

jQuery(document).ready(function(){


Delete K nodes in a linked list having their data less than the next node's

Do you know Shlemiel The Painter?
He never moves his paint can, and so repeatedly walks all over the town.

What you need to do is take the algorithm for removing one friend, look at how it works when applied k times, and then cut out all the redundant Setup work.

Aside from that, you aren't using any C++ containers or algorithms, nor smart-pointers (std::unique_ptr), new or the like.

Don't assume nothing will go wrong. While it is unlikely with malloc() as long as you stay reasonable, scanf() parses user-input, and users will do everything possible, even if you think it's impossible.

There's more, but that should be a good start.


Retrieving doubles from string - simple problem

Don't know if using regex is overkill, but it does open up for a fairly concise and (in my opinion) readable solution.

public class ArgumentParser {
    public static final Pattern KEY_VALUE_PATTERN = Pattern.compile("\\[([a-zA-Z]+)=(-?\\d+\\.?\\d*)\\]");

    public Map<String, Double> parse(String str) {
        Map<String, Double> values = new HashMap<>();

        Matcher matcher = KEY_VALUE_PATTERN.matcher(str);
        while (matcher.find()) {
            String key = matcher.group(1);
            Double value = Double.parseDouble(matcher.group(2));
            values.put(key, value);
        }

        return values;
    }
}

Edit: The question did ask for an array of doubles to be returned, but that should be trivial to obtain once the parsing is done. Alternatively the parse-method could be modified to only extract the values.


IsDatabaseUp returns true or throws exception

The naming convention Is… implies that the function is a predicate, returning either true or false.

If you wanted to throw an exception when the database is down, then you might name the function RequireDatabaseUp(), returning void, instead.  But that seems silly: why not just try performing a real SQL operation instead?

In summary, if you want to provide a function whose sole purpose is to determine whether the database is available, make it return true or false.  If you prefer to have an exception thrown on failure, don't bother providing such a function at all.


Readability

Your code is visually unappealing. You have multiple PEP 8 violations, and your variable names really don't speak volumes. You have 2 spaces of indentation which is pretty much un-heard of in Python. If we move your code into a function and perform a little clean up we can get something like:

import numpy as np

def get_indexes(tokens, word):
    return [
        index
        for index, token in enumerate(tokens)
        if token == word
    ]

def co_occurrence_matrix(corpus, vocabulary, window_size=5):
    matrix = np.zeros((len(vocabulary), len(vocabulary)), np.float64)
    for word_1 in vocabulary:
        for word_2 in vocabulary:
            for sent in corpus:
                tokens = sent.split()
                tokens_1 = get_indexes(tokens, word_1)
                tokens_2 = get_indexes(tokens, word_2)
                for k in tokens_1:
                    for l in tokens_2:
                        if abs(l - k) > window_size:
                            continue
                        if word_1 == word_2:
                            continue
                        matrix[
                            vocabulary.index(word_1),
                            vocabulary.index(word_2),
                        ] += 1
    return matrix

print(co_occurrence_matrix(corpu1, voca))

Performance

Now It doesn't look too bad, but it doesn't really look nice. From here we can see clearly that word_1 and word_2 are defined in the first two loops, however the check word_1 == word_2 is on the inner-most level of the loops. This means you're needlessly looping over sent, tokens_1 and tokens_2. These loops, totalling around 12000000, are useless and a waste of time.

It can be hard to see, but vocabulary.index(word_1) has a for loop in it. How else is it getting the index? This means you're looping 2000 times, this is a waste as you can define a variable to store the index when looping through vocabulary.

You don't need to iterate over vocabulary, you can just iterate over corpus. This is because if word_1 or word_2 is not in tokens then the for loop will iterate over an empty list and so will do nothing. And so we can derive word_1 and word_2 from corpus.

Since vocabulary only contains the top 2000 words in the corpus. Then a naïve flip of the loops is still going to waste some cycles. And so we can just filter sent to ones in the vocabulary. To achieve this I opted to use a closure as I think it makes the code cleaner and easier to read. This is because I don't have the walrus on Python 3.7 and wanted to use dict.get rather than perform two dictionary lookups per filter of each token.

import numpy as np
import itertools

def by_indexes(iterable):
    output = {}
    for index, key in enumerate(iterable):
        output.setdefault(key, []).append(index)
    return output

def co_occurrence_matrix(corpus, vocabulary, window_size=5):
    def split_tokens(tokens):
        for token in tokens:
            indexs = vocabulary_indexes.get(token)
            if indexs is not None:
                yield token, indexs[0]

    matrix = np.zeros((len(vocabulary), len(vocabulary)), np.float64)
    vocabulary_indexes = by_indexes(vocabulary)

    for sent in corpus:
        tokens = by_indexes(split_tokens(sent.split())).items()
        for ((word_1, x), indexes_1), ((word_2, y), indexes_2) in itertools.permutations(tokens, 2):
            for k in indexes_1:
                for l in indexes_2:
                    if abs(l - k) <= window_size:
                        matrix[x, y] += 1
    return matrix

print(co_occurrence_matrix(corpu1, voca))

This currently isn't fully optimized, as you can use combinations rather than permutations but that would require mirroring the non-empty values of the matrix. That would likely half the time it takes to run, but would require additional code.

This is answer is entirely hypothetical. This means using dict[] twice rather than dict.get may be faster. It also means that many of the assumptions I made may not translate into performance benefits due to the way Python is.


Java method to check if a binary tree is a valid BST

What comes to the actual algorithm, you could traverse the tree in-order and check that node keys are strictly growing. This takes \$\Theta(n)\$ time.

public class Main {

    private static final class TreeNode {
        int key;
        TreeNode left;
        TreeNode right;
        TreeNode parent;

        TreeNode(int key) {
            this.key = key;
        }
    }

    private static TreeNode minimum(TreeNode node) {
        if (node == null) {
            return null;
        }

        while (node.left != null) {
            node = node.left;
        }

        return node;
    }

    private static TreeNode successor(TreeNode node) {
        if (node == null) {
            return null;
        }

        if (node.right != null) {
            return minimum(node.right);
        }

        TreeNode parent = node.parent;

        while (parent != null && parent.right == node) {
            node = parent;
            parent = parent.parent;
        }

        return parent;
    }

    public static boolean isBinarySearchTree(TreeNode root) {
        if (root == null) {
            return true;
        }

        TreeNode node = minimum(root);
        int previousKey = node.key;

        while (true) {
            node = successor(node);

            if (node == null) {
                return true;
            }

            if (previousKey >= node.key) {
                return false;
            }

            previousKey = node.key;
        }
    }

    public static void main(final String... args) {
        // Build a valid BST.
        TreeNode root = new TreeNode(0);
        TreeNode node1 = new TreeNode(-2);
        TreeNode node2 = new TreeNode(2);
        TreeNode nodeBad = new TreeNode(-2);

        root.left = node1;
        node1.parent = root;

        root.right = node2;
        node2.parent = root;

        node1.right = nodeBad;
        nodeBad.parent = node1;

        System.out.println(isBinarySearchTree(root));

        nodeBad.key = -3;

        System.out.println(isBinarySearchTree(root));

        nodeBad.key = -1;

        // Now should print 'true'.
        System.out.println(isBinarySearchTree(root));
    }
}

Naming

Please fix check_if_valid_binary_search_tree to camel case: checkIfValidBinarySearchTree.

Also, not curr_node, but rather currentNode would more appropriate for Java.

Coding conventions

Fix

if (curr_node.val < lower_bound || curr_node.val > upper_bound) return false;

to

if (curr_node.val < lower_bound || curr_node.val > upper_bound) {
    return false;
}

Use the diamond inference:

Deque<Bounds> stack = new ArrayDeque<>();

instead of

Deque<Bounds> stack = new ArrayDeque<Bounds>();


A Map would have a roughly constant time lookup on keys but if there only going to be 4 entries then checking each item in an array will probably be quicker anyway.

I think a much bigger issue is the repetition in the code and use of a ResizeArray to write in an imperative style when that can be easily avoided. Both of those issues are covered in this refactor (note that the names I used are quite arbitrary and you can probably come up with better ones):

member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array =
    let makeStatePair state stateType =
        let networkState = (this.CabinetNetworkState >>> state) &&& 2uy
        if Enum.IsDefined(typeof<CabinetNetworkState>, networkState)
        then stateType, networkState
        else stateType, 0uy
    [|
        makeStatePair 0 CabinetNetworkStateHosts.EXT
        makeStatePair 3 CabinetNetworkStateHosts.CAN
        makeStatePair 5 CabinetNetworkStateHosts.NET1
        makeStatePair 7 CabinetNetworkStateHosts.CAN
    |]


Improving a filter array function with Set and objects, to match elements and conditions

The Array methods filter() and every() come in very handy here. First you could define a function to check wheter a given element matches all conditions:
function meetsAll(element, conditions) {
    return conditions.every(c => element.condition_matrix.includes(c));
}

Now it's almost trivial to filter out the matching elements using Array.filter():
const meetConditions = this.arrayWithAllElements.filter(
    element => meetsAll(element, userSelectedConditions)
);

I recommend you also have a look at the other functional methods defined on Array.


You still have a floating point problem
If you change your line to this input:
auto change = getChange(0.04, 0.03);

you will get the following output:
2, 0, 0, 0, 0, 0,

As you can see, it answers with 2 pennies instead of one.  The problem is with the line that you "fixed":

// I had a floating-point problem here by computing cents = (M-P)*100;
// it took me a few minutes to figure it out
int cents = (int)(M*100) - (int)(P*100);

You did notice a problem with your floating point conversion but you came to the conclusion that it was the subtraction that was the problem.  The actual problem is that a floating point value of something like 0.03 can sometimes be slightly above or slightly below the actual value of 0.03.  In this case, it is slightly below.  When you convert this value to cents by using (int)(P*100), you end up converting something like 2.999999 to 2 instead of 3.
One way to avoid this problem is to round instead of truncate.  So you can change your line to this to fix the problem:
int cents = (int) (100*(M-P) + 0.5);


Template heap/priority-queue data structure with update-key operation

peak() should be returning a const reference. same goes for getItem().
Extract() should not return anything. Having two functions to read the head just begs for someone to accidentally call Extract() when they meant peak().
Why is key forced to be an int? It could easily be a separate template parameter.
heap.push_back(IzHeapItem(keys[i], items[i])); should be heap.emplace_back(keys[i], items[i]); instead.
you should do a heap.reserve() at the top of heapify()
Heapifying a vector<> containing the same item twice would break this pretty badly. You should guard against this.
Unless you intend to call heapify() multiple times in a row, that should just be a constructor. Otherwise, I would rename that function addToHeap()
I prefer to avoid using the [] operator on maps in general unless I specifically want a "insert-or-replace" logic. There's a bunch of logic to handle creating a new instance, which assumes the value type of the map has a default constructor.

so:

itemToHeapIndex[items[i]] = i;

becomes

itemToHeapIndex.emplace(items[i], i);

and

assert(itemToHeapIndex.count(item) > 0);
int index = itemToHeapIndex[item];

becomes

auto found = itemToHeapIndex.find(item);
assert(found != itemToHeapIndex.end()); // Bonus! no additional lookup in debug
int index = found->second;

Super minor detail:

The peak() function name made me squint. Traditionally, peek() means "see the next value that will come out of the datastructure", which is what happens here. This is not really a problem you have to fix, more of an observation. I would personally have used top() and pop() to match established standards.


The first problem that jumps out at me is that many of your variables are "stringly typed".  This class is a calculator, right?  Why are you storing your numbers as strings rather than as doubles?

Why does the constructor take a num parameter, and what does it mean?

There is no need to redefine π.  Just use Math.PI.

Why is there a getPoolCost() method?  Your code would be more flexible if you offered a method to calculate the volume, and a separate method to calculate the cost based on the volume.

I don't think that there is much of a reason to define a bunch of setters and getters.  Just define one function that accepts all of the dimensions as parameters, and be done with it.


Looping

You want to perform an action 10 times. The loop counter never matters for your code, you just need to ask 10 questions. The way you wrote the code, you have:

count = count + 1

in 6 places, all of which are necessary, otherwise you would loop too many times. That is very error prone. If you added support for division, you would have to write it two more times. Good rule of thumb is never repeat yourself!

The best way to loop 10 times in Python, when you don't care about the loop count, is:

for _ in range(10):
    # stuff

No need to worry about incrementing count. Let range() do it for you.

Don't Repeat Yourself

The code for adding, subtracting, and multiplying is the same. The only difference is what operation you do and what operation you print. You mostly already have that refactored. You do use op() to perform the operation. So let's just go one step further:

ops = (('+', add), ('-', sub), ('*',mul))
op_name, op = random.choice(ops)

And then, I'm pretty much copying your logic for add with just one real change (and renaming some variables):

print("What is", x, op_name ,y, "? ")  # op_name, not +
actual = int(input())
expected = op(x,y)
if actual == expected:
    print("Well done, this is correct!")
    score += 1
else:
    print("Sorry, but this is incorrect.")

I also renamed your variables to actual and expected, instead of question and answer - since question didn't really refer to a question. Also += 1 is a more concise way of expressing incrementing by one.

Tell the user the answer?

If the user gets it wrong, do you want to tell them the correct answer?

Finishing up

You don't need to check count (or, now, _) to know when you're done. Just wait for the loop to end, at which point you can print the score. So the flow looks like:

score = 0
for _ in range(10):
    # prompt a problem and potentially increment score

print("Well done "+name+"! You have completed the quiz. Your final score out of 10 is "+str(score)+".")

Though typically you'd express the score as X/10, not out of 10 is X. That just reads funny.


Method to return a string of max length (in bytes vs. characters)

It depends what you mean by correct. Consider this program:

const string Input = "a\u0304\u0308bc\u0327";
var bytes = Encoding.UTF8.GetByteCount(Input);
Console.WriteLine("{0} ({1} bytes in UTF-8)", Input, bytes);
for (var i = 0; i <= bytes; i++)
{
    var result = Input.OfMaxBytes(i);
    Console.WriteLine("{0} \"{1}\" {2}", i, result, Input.StartsWith(result, StringComparison.Ordinal));
}

Here is what your solution gives:

ā̈bç (9 bytes in UTF-8)
0 "" True
1 "a" True
2 "ab" False
3 "ā" True
4 "āb" False
5 "ā̈" True
6 "ā̈b" True
7 "ā̈bc" True
8 "ā̈bc" True
9 "ā̈bç" True

Granted, you might not come across such an input very often, but I don't think that's the result you want.

Two other points:

You are building up a lot of intermediate strings. When you catch yourself doing that, see if you can use a StringBuilder instead.
You are iterating through the entire string, regardless of the value of maxBytes.

Here is what I would suggest:

public static string OfMaxBytes(this string input, int maxBytes)
{
    if (maxBytes == 0 || string.IsNullOrEmpty(input))
    {
        return string.Empty;
    }

    var encoding = Encoding.UTF8;
    if (encoding.GetByteCount(input) <= maxBytes)
    {
        return input;
    }

    var sb = new StringBuilder();
    var bytes = 0;
    var enumerator = StringInfo.GetTextElementEnumerator(input);
    while (enumerator.MoveNext())
    {
        var textElement = enumerator.GetTextElement();
        bytes += encoding.GetByteCount(textElement);
        if (bytes <= maxBytes)
        {
            sb.Append(textElement);
        }
        else
        {
            break;
        }
    }

    return sb.ToString();
}

Which gives this output:

ā̈bç (9 bytes in UTF-8)
0 "" True
1 "" True
2 "" True
3 "" True
4 "" True
5 "ā̈" True
6 "ā̈b" True
7 "ā̈b" True
8 "ā̈b" True
9 "ā̈bç" True


ScheduledExecutorService running a couple of scheduleAtFixedRate

Your code is not thread-safe.
The Handler.run() method creates two services which will end up being deparate threads.  These threads are accessing and updating the neededDataList shared variable without any synchronization.  This could lead to unpredictable behavior, including the service that is reading the list seeing stale values.
Also, this code won't compile because the executeTask method is not defined.


Comments are inline.

public static class Console

Where's your using directives? They're needed for the code to compile; you should post them.
It's a little bit unusual to give your class the same name as one in System but I see why you did it -- so you can just switch to using your new module with a using.

{
    private static Regex _writeRegex = new Regex("<[fb]=\\w+>");

Don't forget to make it readonly. The pattern for that Regex should be specified as a verbatim string literal so you don't have to double the backslashes (only you can prevent Leaning Toothpick Syndrome) -- @"<[FB]\w+>". You don't save length but it's easier to understand.
I had initially thought that it might make sense to construct this Regex using RegexOptions.Compiled, but it turns out that has no benefit since it's only used in a static method, so it will automatically be cached. But if you ever use nonstatic methods, it's worth trying it and see if it gives a speed increase.

    public static void WriteLine(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        Write(value + Environment.NewLine, cursorPosition, clearRestOfLine);
    }

It's inefficient to use + here to append onto the string. Since .NET System.String is immutable, it has to build a whole new string and copy. It would be better to just call Write with the parameters as you got them, followed by System.Console.Write(Environment.NewLine);.

    public static void Write(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        if (cursorPosition.HasValue)
            System.Console.CursorLeft = cursorPosition.Value;

        ConsoleColor defaultForegroundColor = System.Console.ForegroundColor;
        ConsoleColor defaultBackgroundColor = System.Console.BackgroundColor;

        var segments = _writeRegex.Split(value);
        var colors = _writeRegex.Matches(value);

This seems a bit inefficient since you're doing the same matching twice. I strongly suspect that it would be better to skip the .Split call and use a foreach loop on the Matches.

        for (int i = 0; i < segments.Length; i++)
        {
            if (i > 0)

As another reviewer suggested, this is suboptimal. If i==0 is a special case, move it outside the loop so you don't need to test i each time through the loop. (The compiler will probably do this for you, so you won't gain any speed -- it's just for code legibility)

            {
                ConsoleColor consoleColor;
                // Now that we have the color tag, split it int two parts,
                // the target(foreground/background) and the color.
                var splits = colors[i - 1].Value
                    .Trim(new char[] { '<', '>' })
                    .Split('=')
                    .Select(str => str.ToLower().Trim())
                    .ToArray();

This is clever, but it really would be easier and clearer to just use capturing groups in your Regex so you can access the two parts directly from the Match.

                // if the color is set to d (default), then depending on our target,
                // set the color to be the default for that target.
                if (splits[1] == "d")
                    if (splits[0][0] == 'b')

This code would be a lot clearer if you used meaningful variable names instead of splits[1] and splits[0].

                        consoleColor = defaultBackgroundColor;
                    else
                        consoleColor = defaultForegroundColor;

You like terseness -- how about the ternary operator here?

                else
                    // Grab the console color that matches the name passed.
                    // If none match, then return default (black).
                    consoleColor = Enum.GetValues(typeof(ConsoleColor))
                        .Cast<ConsoleColor>()
                        .FirstOrDefault(en => en.ToString().ToLower() == splits[1]);

Again, very clever, but I think it would be more efficient to just build a Dictionary<string,ConsoleColor> one time at the start, rather than searching the whole list each time. LINQ is extremely useful; that doesn't mean it's best used everywhere.

                // Set the now chosen color to the specified target.
                if (splits[0][0] == 'b')
                    System.Console.BackgroundColor = consoleColor;
                else
                    System.Console.ForegroundColor = consoleColor;
            }

            // Only bother writing out, if we have something to write.
            if (segments[i].Length > 0)
                System.Console.Write(segments[i]);
        }

Like the other reviewer said, this if should be at the start so you don't bother unpacking the string at all.

        System.Console.ForegroundColor = defaultForegroundColor;
        System.Console.BackgroundColor = defaultBackgroundColor;

How about System.Console.ResetColor()? It would make these two variables unnecessary.

        if (clearRestOfLine)
            ClearRestOfLine();
    }

    public static void ClearRestOfLine()
    {
        int winTop = System.Console.WindowTop;
        int left = System.Console.CursorLeft;
        System.Console.Write(new string(' ', System.Console.WindowWidth - left));
        System.Console.CursorLeft = left;
        System.Console.CursorTop--;
        System.Console.WindowTop = winTop;
    }
}

Does this do what you want after a WriteLine? It looks to me like it clears the next line not the current one.


Making toString function more readable In Java

This answer to a question on multi line strings contains a lot of good examples of trouble with building multi line string output this way but in particular I think the String.format approach works best with a template string.

Your setup would be something like

String template = “ Name: %s %n ID: ...”

And you would place it with

String formatted = String.format(template, nameString, idString,...);

Don’t like their sorting algorithm? I’d recommend extending your own! You can provide your own comparator for the sort stream function. This gives you complete control over how it sorts, at the expense of providing the desired sorting logic.
This article contains several examples of ways to extend your own comparators to this function


in Jackson, you have the mixin feature. This allows to add or override annotations at run time.

so we have one target POJO

public class Person
{
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

and the mixin classes can be interfaces (they never get initialized) with matching setter method signatures and different annotations

public interface NameModel
{
    @JsonProperty("name")
    void setName(String name);
    @JsonProperty("age")
    void setAge(int age);
}

public interface TitleModel
{
    @JsonProperty("title")
    void setName(String name);
    @JsonProperty("years")
    void setAge(int age);
}

at run-time you can associate one mixin to the target class.  Jackson matches properties and methods by name and takes the annotations from the mixin. overriding any from the target:

public static void main(String[] args) {
    String nameModelJson = "{\"name\":\"title1\",\"age\":31}";
    try (InputStream is = new ByteArrayInputStream(nameModelJson.getBytes())) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(Person.class, NameModel.class);
        Person p = mapper.readValue(is, Person.class);
        System.out.println(p.name + " " + p.age);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String titleModelJson = "{\"title\":\"title1\",\"years\":\"31\"}";
    try (InputStream is = new ByteArrayInputStream(titleModelJson.getBytes())) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(Person.class, TitleModel.class);
        Person p = mapper.readValue(is, Person.class);
        System.out.println(p.name + " " + p.age);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


It is not idiomatic and it is not okay usage. It should be:

  SliceTricks

  Delete (pointers)

copy(a[i:], a[i+1:])
a[len(a)-1] = nil // or the zero value of T
a = a[:len(a)-1]

For example,

package main

import (
    "fmt"
    "strconv"
)

const ARBITRARY = 5

type myData struct {
    det detailSlicePtr
}

type detail struct {
    id   int
    name string
}

// Slice of pointers to details
type detailSlicePtr []*detail

// Returns true if item removed succesfully,
// false all other cases
func (s *myData) remove(d *detail) bool {
    for i := range s.det {
        if s.det[i].name == d.name && s.det[i].id == d.id {
            copy(s.det[i:], s.det[i+1:])
            s.det[len(s.det)-1] = nil
            s.det = s.det[:len(s.det)-1]
            return true
        }
    }
    return false
}

// Find and remove a struct element from a slice of struct pointers within a     struct
func main() {

    var d myData
    details := make(detailSlicePtr, ARBITRARY)

    for j := 0; j < ARBITRARY; j++ {
        details[j] = &detail{
            id:   j,
            name: strconv.Itoa(j),
        }
    }

    d.det = details

    // Print out what we have so far
    for index := range d.det {
        fmt.Printf("Item %d is %s\n", index, d.det[index].name)
    }
    // Print what is hidden
    for i := range d.det[len(d.det):cap(d.det)] {
        j := len(d.det) + i
        det := d.det[:cap(d.det)]
        fmt.Printf("Hidden item %d is %v\n", j, det[j])
    }

    findMe := ARBITRARY / 2
    middle := &detail{id: findMe, name: strconv.Itoa(findMe)}

    if ok := d.remove(middle); !ok {

        fmt.Printf("Unable to find element: %v\n", middle)

    } else {

        fmt.Printf("Found and removed element: %v\n", middle)

        // Print what is left
        for index := range d.det {
            fmt.Printf("Item %d is %s\n", index, d.det[index].name)
        }
        // Print what is hidden
        for i := range d.det[len(d.det):cap(d.det)] {
            j := len(d.det) + i
            det := d.det[:cap(d.det)]
            fmt.Printf("Hidden item %d is %v\n", j, det[j])
        }
    }
}

Output:

Item 0 is 0
Item 1 is 1
Item 2 is 2
Item 3 is 3
Item 4 is 4
Found and removed element: &{2 2}
Item 0 is 0
Item 1 is 1
Item 2 is 3
Item 3 is 4
Hidden item 4 is <nil>

NOTE: There is a bug in the Slice Tricks that you linked to. It will be corrected soon. Until then use the link in my answer.


Since you use it in a subquery, I don't see the problem. If you used both in the same query, that would be redundant. But the subquery needs to use it to obtain the required data.

Did the person give a reason as to why he/she thinks this, or was it simply a general statement?

The only thing I can think of is that DISTINCT is rather slow compared to GROUP BY: stackoverflow.com/questions/1887953/


^v([0-9]+)([.])([0-9]+)(b)?([0-9]+)?$

Not much to say but:

seems a bit strange to capture the . since that's the only value that could be there. Also [.] could be written mode simply as \..
also seems a bit strange to capture the b, unless v1.1b is specifically allowed. And you're trying to find that last digit group even if b isn't present - not a bug, but could be made clearer.

To address the second point, make the whole beta part optional:

^v([0-9]+)\.([0-9]+)(?:(b)([0-9]+)?)?$

If beta with no number isn't allowed, this can be simplified (and drop capturing b also in this case):

^v([0-9]+)\.([0-9]+)(?:b([0-9]+))?$

(The (?:...) construct is a non-capturing group.)


Calculating Euclidean distance and performing unit-testing

Since the tests are testing the same thing (calculate the distance between two nodes) and the only difference is the test data, I say refactor it so that you have one test that tests the same logic with different data. When you have tests that are there for different purposes (like validation checking, distance calculation, not calling createLink, etc) you will have code duplication.

There should be separate tests for addNode and separate tests for validation checks (what happens when you try to create a link when there are no nodes added). Also there should be different variations of the amount of nodes.

Setup is called before every testmethod, so if you always create the same SpatialGraph you can do that there.


The way that the random graph is generated seems suspicious:

class Network(object):
    def __init__(self, num_nodes):
        self.nodes = [0]*num_nodes
        for i in range(num_nodes):
            self.nodes[i] = Node(randint(1, 10))
        self.set_connections()

    def set_connections(self):
        for f, g in product(self.nodes, self.nodes):
            p = uniform()
            if p < 0.8:
                f.friends.append(g)
                g.friends.append(f)

First of all, self.nodes should just be defined as

self.nodes = [Node(randint(1, 10)) for _ in range(num_nodes)]

The way that nodes changes type from a list of integers to a list of Node objects makes it feel slightly more dirty.

It looks like set_connections() is only meant to be called from the constructor, so it should be renamed _set_connections() to suggest that it is private.  However, considering that __init__() would just consist of two lines (self.nodes = … and self._set_connections()), I would just lump everything into __init__().

product(self.nodes, self.nodes) seems wrong.  It's possible to cause a Node to befriend itself.  It's also possible to have two nodes list each other as friends twice.  I suspect that what you want is combinations(self.nodes, 2).

def __init__(self, num_nodes):
    self.nodes = [Node(randint(1, 10)) for _ in range(num_nodes)]
    for f, g in combinations(self.nodes, 2):
        if uniform() < 0.8:
            f.friends.append(g)
            g.friends.append(f)


Apart from what @RubberDuck said, you can also do a bit less work by not
converting from/to String, but iterating over the digits one by one
directly.  I've also moved the value to where it is initialised, that
way its scope is better visible.

After making those changes I arrive at the following snippet.  isHappy
or (isHappyNumber) can be reused and the main function only does
interface stuff.

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class HappyNumber
{
    public static boolean isHappy(int number)
    {
        Set<Integer> unique = new HashSet<Integer>();

        while (unique.add(number))
        {
            int value = 0;
            while (number > 0)
            {
                value += Math.pow(number % 10, 2);
                number /= 10;
            }
            number = value;
        }

        return number == 1;
    }

    public static void main(String[] args)
    {
        System.out.print("Please enter a number: ");
        int number = new Scanner(System.in).nextInt();
        System.out.println(isHappy(number) ? "Happy" : "Not Happy");
    }
}


A consistent tidyverse solution would use readr::read_csv I guess.

You don't need map2 if you don't use .y, map is enough.

You can use read.csv as your .f argument, and leave the rest to the ... in your map call, might be a matter of taste but I prefer it that way as with the formula notation you have to read through to make sure read.csv is the only function called.

as.is doesn't seem necessary if you give column classes already.

Your mutate call is not necessary, tibble will evaluate lazily the definition of filename given at the previous step.

It seems you really want a "one liner" but in my opinion it would be much clearer in a few steps, I propose the following:

files <- list.files(
  "./",
  full.names = TRUE,
  pattern = "^(accounts|symbols)_201[7-9][0-9]{4}\\.csv$")

data_lst <- map(
  files,
  read_csv,
  header = FALSE,
  sep = "=",
  coltypes = "ic",
  col_names = c("count", "names"))

tibble(
  file_name = files,
  date = str_extract(filename, "201[7-9][0-9]{4}"),
  type = str_extract(filename, "(accounts|symbols)"),
  data = data_lst)

In fact as you're working with a lot of data files I'd tend to write a for loop instead of a map call, so I could more easily debug and proceed without restarting all if an issue arises.


AppTaskWorker - Running class methods at sporadic intervals

Start() is spawning an infinite number of new tasks without waiting for them to complete. It's also a bit weird that Start() is blocking the calling thread.

Make Start() async and await the Task returned by Task.Run.

Start(), a blocking method, being called at the end of the constructor is an absolute no-go. The constructor is not done, the object initialization is never completed.

Unless you're living on UTC (DateTime.Now - lastProcessed).TotalSeconds is going to be inconsistent around daylight saving transitions.


Inline conversion/cast from Expression> to LambdaExpression

You can do this by creating a custom class that supports collection initializers. Its Add() method would be generic, so that it fits any allowed expression:

class ExpressionDictionary<T> : IEnumerable<KeyValuePair<string, LambdaExpression>>
{
    private readonly Dictionary<string, LambdaExpression> m_dictionary
        = new Dictionary<string, LambdaExpression>();

    public void Add<TResult>(string key, Expression<Func<T, TResult>> expression)
    {
        m_dictionary.Add(key, expression);
    }

    public IEnumerator<KeyValuePair<string, LambdaExpression>> GetEnumerator()
    {
        return m_dictionary.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Usage:

new ExpressionDictionary<T>
{
    { ContentItem.ORDER_BY_ID, i => i.Id },
    { ContentItem.ORDER_BY_ENABLED, i => i.IsEnabled },
    //the cast is necessary if the result has to be Func<T, IComparable>
    // and not Func<T, string>
    { ContentItem.ORDER_BY_AUTHOR, i => (IComparable)i.Creator.UserName },
    //...
};

You will need to add other methods to ExpressionDictionary. Either implement the whole IDictionary<TKey, TValue> interface and make GetOrderDelegates() return that. Or just add a getter for the private Dictionary and return that.

But even better option might be not to use Dictionary at all. Instead create OrderByDeletegates class (though that's probably not the best name, since it would contain expressions, not delegates) that would have properties for all expressions:

class OrderByDeletegates<T> where T : ContentItem
{
    public Expression<Func<T, int>> OrderById { get; set; }
    public Expression<Func<T, bool>> OrderByEnabled { get; set; }
    public Expression<Func<T, IComparable>> OrderByAuthor { get; set; }
    // …
}

Usage:

new OrderByDeletegates<T>
{
    OrderById = i => i.Id,
    OrderByEnabled = i => i.IsEnabled,
    OrderByAuthor = i => i.Creator.UserName,
    // …
};

The advantage of this is that it's type-safe. You can't for example accidentally do something like OrderByEnabled = i => i.Id.


Here's a scheme that appears to be about 7 times faster that yours when run in node.js:

function getData2(content, lastNumberOfYears) {
    // organize data by year into a Map object
    const map = new Map()
    for (let item of content) {
        const year = new Date(item.date).getFullYear();
        let yearData = map.get(year);
        if (yearData) {
            yearData.push(item);
        } else {
            map.set(year, [item]);
        }
    }

    /* map object data looks like this:
        Map {
          2020 => [
            { document: '/content/path/document1.pdf', date: '2020-02-20' },
            { document: '/document/order/order.pdf', date: '2020-06-20' }
          ],
          2019 => [ { document: '/content/path/file.docx', date: '2019-02-20' } ],
          2018 => [
            { document: '/content/abc/document2.docx', date: '2018-06-20' },
            { document: '/content/order/update.pdf', date: '2018-03-21' }
          ],
          2017 => [ { document: '/content/author/author.pdf', date: '2017-03-21' } ],
          2016 => [ { document: '/content/path/dummy.pdf', date: '2016-02-15' } ],
          2015 => [ { document: '/content/dummy/dummy.docx', date: '2015-12-15' } ]
        }
    */

    // get lastNumberOfYears by getting all the years, sorting them
    // and getting most recent ones
    let sortedYears = Array.from(map.keys()).sort();
    if (sortedYears.length > lastNumberOfYears) {
        sortedYears = sortedYears.slice(-lastNumberOfYears);
    }
    let result = [];
    for (let year of sortedYears) {
        result.push(map.get(year));
    }
    return result.flat();

}

function time(fn) {
    const start = process.hrtime.bigint();
    let result = fn();
    const end = process.hrtime.bigint();
    console.log(result);
    console.log(`Benchmark took ${end - start} nanoseconds`);
}

It uses the following steps:

Parse years and put each year's into a Map object with the year as the key and the value as an array of values for that year
Get the years from the Map object, sort them and get the desired lastNumberOfYears
Collect the results from the Map object for each of the chosen years and flatten them into a single array

If you want to run both yours and mine in node.js, here's the entire program I used to compare:

const inputData = [{
    "document": "/content/path/document1.pdf",
    "date": "2020-02-20"
  }, {
    "document": "/content/path/file.docx",
    "date": "2019-02-20"
  }, {
    "document": "/content/abc/document2.docx",
    "date": "2018-06-20"
  }, {
    "document": "/document/order/order.pdf",
    "date": "2020-06-20"
  }, {
    "document": "/content/order/update.pdf",
    "date": "2018-03-21"
  }, {
    "document": "/content/author/author.pdf",
    "date": "2017-03-21"
  }, {
    "document": "/content/path/dummy.pdf",
    "date": "2016-02-15"
  }, {
    "document": "/content/dummy/dummy.docx",
    "date": "2015-12-15"
}];

function getData1(content, lastNumberOfYears) {

    let selectedYearArray = [];

    const result = content.reduce((current, value) => {
      const dateYear = new Date(value.date).getFullYear();
      current[dateYear] = current[dateYear] || [];
      current[dateYear].push(value);
      return current;
    }, {});

    /*
    output is like
    {
       "2015":[{...}],"2016":[{}],..."2020":[{}, {}]
    }
    */

    Object.values(result).forEach(value => value.reverse());

    const yearsArray = Object.keys(result).sort((first, second) => (first > second ? -1 : 1));

    if (yearsArray.length !== 0 && lastNumberOfYears <= yearsArray.length) {
      for (let i = 0; i < lastNumberOfYears; i++) {
        selectedYearArray.push(yearsArray[i]);
      }

      /*
        Step 5: console.log(selectedYearArray);
      */

      const filteredResult = Object.keys(result)
        .filter(key => selectedYearArray.includes(key))
        .reduce((obj, key) => {
          obj[key] = result[key];
          return obj;
        }, {});

      /*
        Step 6: console.log(filteredResult);
      */

      contentObj = [].concat.apply([],Object.values(filteredResult));

      /*
        Step 7:
      */
      return contentObj.reverse();
    }
}

function getData2(content, lastNumberOfYears) {
    // organize data by year into a Map object
    const map = new Map()
    for (let item of content) {
        const year = new Date(item.date).getFullYear();
        let yearData = map.get(year);
        if (yearData) {
            yearData.push(item);
        } else {
            map.set(year, [item]);
        }
    }

    // get lastNumberOfYears by getting all the years, sorting them
    // and getting most recent ones
    let sortedYears = Array.from(map.keys()).sort();
    if (sortedYears.length > lastNumberOfYears) {
        sortedYears = sortedYears.slice(-lastNumberOfYears);
    }
    let result = [];
    for (let year of sortedYears) {
        result.push(map.get(year));
    }
    return result.flat();

}

function time(fn) {
    const start = process.hrtime.bigint();
    let result = fn();
    const end = process.hrtime.bigint();
    console.log(result);
    console.log(`Benchmark took ${end - start} nanoseconds`);
}

time(() => getData1(inputData, 2));

time(() => getData2(inputData, 2));

And, the output on my desktop computer was this:

[
  { document: '/content/path/document1.pdf', date: '2020-02-20' },
  { document: '/document/order/order.pdf', date: '2020-06-20' },
  { document: '/content/path/file.docx', date: '2019-02-20' }
]
Benchmark took 602501 nanoseconds
[
  { document: '/content/path/file.docx', date: '2019-02-20' },
  { document: '/content/path/document1.pdf', date: '2020-02-20' },
  { document: '/document/order/order.pdf', date: '2020-06-20' }
]
Benchmark took 89100 nanoseconds

Note a slightly different sort order of the results.  I didn't see in your description if a specific sort order of results was required or not.


Use using keyword to define your type instead of typedef

C++11 introduced type alias which can be used to define your own type and it's compatible with templates, so instead of:

typedef typename std::multiset < Tree * , typename Tree::compare > NodeSet;

you'll get this:

using NodeSet = std::multiset < Tree * , Tree::compare >;

Consider using range-based for loop instead of while loop with iterator

I think that it will result in simplier and more readable code, for example Visit function will look like this:

void Visit(std::deque <T>& exp) const {
  exp.push_back(content);
  for (const auto& child : children)
        child->Visit(exp);
}

Unnecessary erase call in Clear function

The following call:

children.erase( *it);

is unnecessary - multiset childern will be erased automatically.

Reconsider memory management

Currently it's possible to add new child to existing Tree by calling function

void AttachTree(Tree* t)

which expects pointer to existing Tree object as argument. It means that Tree is not repsonsible for creation of children. By the other hand, in destructor the Clear function is called which deletes all the children, which means that Tree takes responsibility for deletion of children. This might lead to undefined behaviour. Consider the following code:

Tree<int>* t1 = new Tree<int>(1);
{
    Tree<int> t2(2);
    t2.AttachTree(t1);
    {
        Tree<int> t3(3);
        t3.AttachTree(t1);
        std::cout << "1. t1 content: " << t1->GetContent() << "\n";
    } // t3 desctructor is called, which means that t1 has been deleted
    std::cout << "2. t1 content: " << t1->GetContent() << "\n"; // t1 doesn't exist anymore - what's the result of t1->GetContent() ?
} // t2 desctructor is called and t1 will be deleted again
std::cout << "3. t1 content: " << t1->GetContent() << "\n"; // t1 doesn't exist anymore - what's the result of t1->GetContent() ?


Computation of concordant and discordant pairs

These sorts of operations are tough to vectorize because you need to compare every element to all later elements. If the counting operation is a performance bottleneck in your code, then one possibility would be to implement it in C++ using the Rcpp package:

library(Rcpp)
cppFunction(
  "IntegerVector CDcount(NumericVector x, NumericVector y) {
    IntegerVector counts(2, 0);
    int n = x.size();
    for (int i=0; i < n; ++i) {
      for (int j=i+1; j < n; ++j) {
        counts[0] += (x[i] < x[j]) && (y[i] < y[j]);
        counts[1] += (x[i] < x[j]) && (y[i] > y[j]);
      }
    }
    return counts;
  }")

pairs2 <- function(x, y) {
  n <- length(x)
  ix <- order(x)
  x <- x[ix]
  y <- y[ix]
  counts <- CDcount(x, y)
  return(list(Nc=counts[1], Nd=counts[2]))
}

For your test data, this results in a 50 times speedup on my system.

x <- runif(10000)
y <- runif(10000)
system.time(pairs(x,y))
#    user  system elapsed
#   4.892   1.447   6.584
system.time(pairs2(x, y))
#    user  system elapsed
#   0.119   0.001   0.120
identical(pairs(x, y), pairs2(x, y))
# [1] TRUE

The Rcpp package takes some time to compile the CDcount function, so this option is probably only helpful if you are operating on very large vectors or if you are repeating the operation many times.


From java 7 on you can use the try-with-resources syntax :

try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
    workbook.write(out);
    return out.toByteArray();
} catch (Exception e) {
    e.printStackTrace();
}

return null;

Which handles the closing of the Stream, and any excptions that may throw, for you.

In earlier versions of Java, you're pretty much stuck with what you have.

Edit:

It is worth noting that in case you get an exception on the close() method, it is still the original exception that is being thrown. The exception on the close() method is then added to that exception as a suppressed exception. You can get at the suppressed exceptions by calling java.lang.Throwable#getSuppressed


Module for providing users easy access to all social networking websites

You are inconsistent in naming. Some of your methods are in camelCase and some are in under_score format. Pick one.

Where is the consistent API for the various social networks?? From your write up I expect to be able to write something like the following:

my_friends = []
for soc in my_social_networks:
    my_friends.append(soc.get_friends())
show(my_friends)

or:

my_messages = []
for soc in my_social_networks:
    my_messages.append(soc.get_current_messages())
show(my_messages)

Instead I see get_tweets or get_wall. That means I have to pay attention to whether I have a Twitter object or a Facebook object. So all of my code needs to have a long if/else for each new type of social network I want to support in my program.

Double underscores are not meant for code outside of Python. Use a single underscore.


Interface design to have multiple implementations of network call libraries (Retrofit or Volley)

Let me point out an other aspect, you might miss at the moment. I know that this is a learner question/example, but keep in mind that your approach is designing an application where you can switch the network library (in extreme) at runtime. This is not the most common scenario.

Actually it is more likely that you want to switch Retrofit against a mock or Volley against a mock in your tests. So you have done everything right, if you can write tests for related parts of your system (e.g. the StatusFragment)  without doing real network calls and there is no test switch in your production code. (The network stuff will get it's own test.)

On the other hand, although I'm not familiar with the libraries, Google told me that both seems to have some own mocking concepts. So there might not even be a need to switch your implementation in unit tests. In case you finally end up with only one implementation now and optional a total replacement in the future, this approach might add an unnecessary (mental and technical) overhead.

Implementing against an interface don't necessary mean a Java interface. If you only have one implementation at a time, it is totally fine to drop NetworkCallsApi and move NetworkCallsRetrofitImpl into ServiceCalls. Afterwards you are implementing against the interface of ServiceCalls and you don't care about is implementation. It is also pretty straight forward to change the implementation in ServiceCalls later without changing other parts of the application.


Frequency distribution of words and phrases

Use consistent naming

removeNonAscii(s) -> remove_non_ascii(n)

Use with

def read_textfile(filename):
    # Reads the entire content of FILENAME and returns a non Ascii letters cleaned string
    with open(filename) as f:
        return removeNonAscii(f.read())

Merge similar functions

def remove_punctuation1(text):
    # Removes all punctuation and conotation from the string and returns a 'plain' string
    punctuation = '®©™€â´‚³©¥ã¼•ž®è±äüöž!@#Â“§$%^*()î_+€$=¿{”}[]:«;"»\â¢|<>,.?/~`0123456789'
    for sign in punctuation:
        text = text.replace(sign, "")
    return text

    def remove_punctuation(text):
    # Removes all punctuation and conotation from the string and returns a 'plain' string
    punctuation2 = '-&'
    for sign in punctuation2:
        text = text.replace(sign, " ")
    return text

Should become

def remove_punctuation(text):
    # Removes all punctuation and conotation from the string and returns a 'plain' string
    punctuation2 = '-&'+'®©™€â´‚³©¥ã¼•ž®è±äüöž!@#Â“§$%^*()î_+€$=¿{”}[]:«;"»\â¢|<>,.?/~`0123456789'
    for sign in punctuation2:
        text = text.replace(sign, " ")
    return text

Use docstrings

def read_textfile(filename):
    """
    Reads the entire content of FILENAME and
    returns a non Ascii letters cleaned string.
    """
    with open(filename) as f:
        return removeNonAscii(f.read())

Avoid one-two letter variable names, prefer longer ones

l1 -> words_to_check


Storing words from an input stream into a vector

Minor inconsistency here:

#include<string>

Add a space in between them, like all the others:

#include <string>

Just get rid of this:

using std::cout; using std::cin; using std::vector; using std::sort; using std::string; using std::endl; using std::domain_error; using std::cerr;

Even if you put them onto separate lines, it'll still be lengthy.  Just put std:: where necessary and try to keep it consistent.
Exception objects usually should not be passed by value:

catch (domain_error e)

They should be passed by const&:

catch (domain_error const& e)

Consider separating this into additional lines:

if (v.size() == 0) throw domain_error("Nothing to count");

While it's okay to put short statements on a single line, it may be a little harder to read and maintain longer lines, also with the lack of curly braces.

In addition, just call empty() instead of comparing size() to 0.

if (v.empty())
{
    throw domain_error("Nothing to count");
}

Instead of getting the first element via []:

string unique = v[0];

use front():

string unique = v.front();

I'd also like to add a compliment:

Thank you for using std::size_type instead of int.  I hardly see that done by others.  It's good to see that you're paying attention to return types and compiler mismatch warnings.


Tail Recursion
Erlang (and hence Elixir) pride in the tail recursion idioms they use. You've got one recursion in your code but it is not a tail recursion!

This means that the recursive part is not the last thing in the function, and the tail recursion optimization cannot be used. Although your code's recursion is limited to up to 11 hits, it still misses the point of the Elixir idiom.

A more idiomatic pattern is using an accumulator, and recursing on that:

def create_fives_minutes(m) when m >= 0, do: _create_fives_minutes(m, "")

def _create_fives_minutes(0, acc), do: acc

def _create_fives_minutes(m, acc) when rem(m,3) == 0 do
  _create_fives_minutes(m-1, "R" <> acc)
end

def _create_fives_minutes(m, acc), do: _create_fives_minutes(m-1, "Y" <> acc)

if code smell
In Elixir if and cond are seldom used, and are even considered a code smell - if you can solve the problem using pattern matching - it is considered more idiomatic. Consider get_seconds - the following is more idiomatic in Elixir than using cond:

def get_seconds(s) when even?(s), do: "Y"
def get_seconds(_), do: "O"

Also see above how I've avoided the if in the create_fives_minutes above using a guard condition (when rem(m,3))

Code Duplication
You've got several methods, which do essentially the same thing. Making a method which takes the duplicate code will remove the need for them entirely - something like:

def build_field(pattern, repeat \\ 1, field_length) do
    String.ljust(String.duplicate(pattern, repeat), field_length, ?O)
end

Now - your main code can look something like this:

    seconds = get_seconds(s)
    single_minutes = build_field("Y", rem(m, 5), 4)
    fives_minutes = build_field(create_fives_minutes(div(m, 5)), 11)
    single_hours = build_field("R", rem(h, 5), 4)
    fives_hours = build_field("R", div(h, 5), 4)

and all the helper methods are no longer needed.

Indentation and readability
When parsing the time string you've got a piping block which looks like this:

    [h, m, s] = String.split(time, ":")
        |> Enum.map fn n -> Integer.parse(n)
        |> elem(0) end

This is a very misleading indentation, since you indent elem(0) at the same level as the Enum.map.

A more readable way to put it should be:

    [h, m, s] = String.split(time, ":")
        |> Enum.map fn n ->
            Integer.parse(n)
            |> elem(0)
        end

Showing that |> elem(0) is inside the Enum.map function, and not after it.

Playing with the idioms
You can parse the time string using the recursive method idioms, which would look like this:

def _parse_time("", acc), do: acc

def _parse_time(":" <> s, acc), do: _parse_time(s, acc)

def _parse_time(s, acc) do
    {num, s} = Integer.parse(s)
    _parse_time(s, [num | acc])
end

and used like this:

    [s, m, h] = _parse_time(time, [])

It is not worse or better than your solution, but it uses a different Elixir idiom.


Assuming you're using the current c++ standard, since you don't specify in your question.

Prefer stoi to atoi. atoi has issues.
Prefer standard int types: std::uint128_t instead of unsigned long long int
Create a type alias for your map type since you use it a lot.
Don't include unnecessary headers in the fibbonacci.h file. Include them in the implementation.
It would make more sense to implement your memoizing map statically in the function.
You should use the map count method rather than relying on [] returning zero for a missing key

Putting these together

using fibmap = std::map<int, std::uint128_t>;

std::uint128_t fibonacci(int seq) {

    static fibmap m = {{0,0}, {0,1}};
    if (!m.count(seq)){
        m[seq] = fibonacci(seq - 2) + fibonacci(seq - 1);
    }
    return m[seq];
}


FIrst time trying tree classifier in python

First of all, pandas, scikit-learn, numpy, keras and tf come with a lot of data loading utilities.

Your data_processor(input_file) can be replaced with pandas.read_csv().
Alternatively, IRIS dataset is avaiable at sklearn.datasets.load_iris()

I would advise to have a look at Scikit-learn's example of analyzing IRIS


Find offset that minimizes squared difference between two vectors of different size

Without changing the algorithm, the only things I can see by having a look at the assembly of sqDiffSum:

read x[i] only once in the outer loop (i.e const double x_i = x[i] and then use x_i instead). You'll get a small win by not having to fetch it whenever you enter the if.
compute once i * scale - offset in the outer loop because this invariant. But latest gcc and clang seem smart enough to figure this out themselves.

Also, you might want to test std::unordered_map.

edit: whenever bin >= ref.size(), you know that it will be for all the next j. Maybe you even replace j by bin running (before morning coffee) when \$offset >= i \cdot scale\$ and \$\frac{i \cdot ref\_size}{x\_size} + offset < ref\_size\$


Find given number by summing up integers from 2 sorted arrays

Your code reads easily: it loops over the two arrays to find the corresponding pairs.

However, it doesn't take advantage of the fact that both arrays are sorted. You can refer to this Stack Overflow answer by Mark Byers to see how it is possible to do it in linear time and constant storage when both arrays are sorted. Quoting for reference:

  Start with two pointers, one pointing at the smallest element of A, the other pointing to the largest element of B.
  Calculate the sum of the pointed to elements.
  If it is smaller than k increment the pointer into A so that it points to the next largest element.
  If it is larger than k decrement the pointer into B so that it points to the next smallest element.
  If it is exactly k you've found a pair. Move one of the pointers and keep going to find the next pair.

In this version, each pointer will always go forward (for the first array) or backward (for the second array), so there will be at most A.length + B.length moves.

Putting this into code, you would have:

private static void findPairs(int[] array1, int[] array2, int sum) {
    int l = 0, r = array2.length - 1;
    while (l < array1.length && r >= 0) {
        int s = array1[l] + array2[r];
        if (s < sum) {
            l++;
        } else if (s > sum) {
            r--;
        } else {
            System.out.println("Pair found at index : " + l + " " + r);
            l++;
        }
    }
}


Here's a few suggestions in addition to what Keith mentions.

I would try to avoid the memory copy and move operations. You mention a circular buffer, which is one way of doing it, another would be to have the fifo hold discrete buffers and pop each buffer from the front in it's entirety. Avoiding the copy and move operations should speed up the code significantly, which I assume is of concern when processing audio data :)

Also, I would drop the typedef, just use struct fifo instead. This makes it easier to convert this into a full ADT (Abstract Data Type) later, and just forward declare the struct to users while keeping the actual struct private.

As a final note, are you absolutely sure that the restrict keyword is the proper thing to use here?

Edit:
Here's one naive way of getting rid of the memove operation:

typedef struct {
    float *buffer;
    float *start;
    float *end;
    size_t max_length;
} FIFO;

bool FIFO_pop(FIFO *restrict fifo, float *restrict data, size_t count) {
    if (!fifo || !data) return false;
    if (count == 0 || FIFO_available(fifo) < count) return false;

    // move count items from the buffer
    memcpy(data, fifo->start, count*sizeof(float));
    fifo->start += count;

    return true;
}

This will only work if you know the max sized buffer that you need, but it should give you an idea.


Work out if a string is "fieldname" or "tablename.fieldname", and assign variables

Assuming that field always gets the value of the last part of dbFieldEntries you could do:

field = dbEntryEntries[ dbFieldEntries.length - 1 ];
if ( dbFieldEntries.length > 1 ) {
  table = dbEntryEntries[ 0 ];
}

Besides this, s is a bad variable name.


Reversing each word of a string while keeping the case index

If you aim for fewer lines of code, you could of course put everything into a single line, but that would not helpful at all.

However, you could shorten your code a bit by using a simple regular expression and some linq-fu, something like:

var s = yourInputString;

// split string into words
var splitted = Regex.Split(s, @"(\W)").Select(r => r.AsEnumerable()).ToArray();

// reverse each word
var reversed = splitted.Select(sp => sp.Reverse().ToArray());

// adjust case
var zipped = splitted.Zip(reversed, (a, b) => string.Join("", a.Select((c, i) => char.IsUpper(c) ?
                                                                                char.ToUpper(b[i]) :
                                                                                char.ToLower(b[i]))));

// join back to string
var result = string.Join("", zipped);

I would not care about performance in this case, because it would be pointless.

Also, reversing a string with Reverse().ToArray() will corrupt your string if it contains surrogate characters, but this is probably out of scope of your task.


Sessions class With assoc-array - practicing

return isset($_SESSION[$name]) ? true : false; is more succintly written as:

return isset($_SESSION[$name]);

The boolean evaluation of isset() is all you need.
You can use the null coalescing operator to tight up:

if(isset($_SESSION[$name])){
    return $_SESSION[$name];
}else {
    return false;
}

Into:

return $_SESSION[$name] ?? false;

You never need to check if a variable exists before calling unset(). If the variable doesn't exist, the script smoothly, silently continues processing as usual.
The tabbing of your code is needing a fair amount of tender loving care.  Use 4 spaces to indent where necessary. PSR standards are available for everyone's benefit.
I don't think I support the technique of pushing an error message into an array pre-emptively, then removing the element if everything passes.  Add a descriptive error to the error array ONLY if an error is detected.
If you are not going to use a variable (e.g. $key in your loop), then don't bother declaring it.
I realize this is just practice, but try to store only id values in session data if your project permits it.  There is such a thing as Session Hijacking -- it may be an extreme scenario, but it is best to avoid storing any "real world" identifying data in session arrays.
I generally avoid using AND and OR in my if expressions so that I am never tripped up by a fringe "precedence" gotcha.
If you want to display boolean values for diagnostics, I recommend var_export().
Finally, read about how to destroy a session on logout: PHP Session Destroy on Log Out Button


Deleting a section of a website using Ajax

This is very weird. If I read the code without this line, I wouldn't have a clue what that might be:

var that = $(this); // this is very weird
// I suggest the following name, (or thisElement, or something like that)
var $elem = $(this); // I use the $ in the name to indicate 'jQuery Object'

Saving the object is a good thing, saving multiple DOM look-ups, just be obvious about the name.

Instead of getting the data-id, you could use this to get the id of your element, which you can access it directly via JS, which is a lot faster:

var catid = that.data("id"); // instead of this:
var catid = this.id; // Just use id:

You chain your css methods, you can use them more effectively by using the multiple input variant:

that
    .css({backgroundColor: "#27AE60", color: "#FFF"}) // multiple in one go

Even better, do this via classes. You should not style with javascript, apart from tiny exceptions.

if(data == 1) {
    that.addClass("HighlightGood").html('Success');
} else {
    that.addClass("HighlightBad").html('Failure');
};

window.setTimeout(function() {
    that.removeClass("HighlightGood HighlightBad").html('Finished');
}, 5000);

This way you can style via css, as you should. This also allows simple css animation.

Instead of calling the timeout, use a function. DRY (=don't repeat yourself) programming is often more maintainable (IMO):

function setAsFinished( $elem, timeout ){
    timeoutLength = timeout || 5000; // Take the given input (if set), else default value 5sec
    window.setTimeout(function() {
        $elem.removeClass("HighlightGood HighlightBad").html('Finished');
    }, timeoutLength);
}

All suggestions combined:

function setAsFinished( $elem, timeout ){
    timeoutLength = timeout || 5000; // Take the given input (if set), else default value 5sec
    window.setTimeout(function() {
        $elem.removeClass("HighlightGood HighlightBad").html('Finished');
    }, timeoutLength);
}

$('.trg-finished').on('click', function() {
    if( confirm('Are you sure?') ){
        var $thisElem = $(this);
        var catid = this.id;

        $.ajax({
            type: "POST",
            url: "./close-cat.php",
            data: { catID: catid }
        })
        .done(function(data) {
            if(data == 1) {
                $thisElem.addClass("HighlightGood").html('Success');
            } else {
                $thisElem.addClass("HighlightBad").html('Failure').html('Failure');
            };
            setAsFinished( $thisElem );
        })
        .fail(function(data) {
            $thisElem.addClass("HighlightBad").html('Failure');
            setAsFinished( $thisElem );
        });
    };
});


At the moment, your implementation allows

auto& p = nullptr;

This is forbidden in C++11 as nullptr is an rvalue.  You also do not allow the following:

auto p = nullptr;
auto pp = &p;

While C++11 does allow it.  You are also missing overloads for comparison operators.

A simple workaround would be to remove the operator& overload and add a macro:

#define nullptr (nullptr_t())

Also, I'd generally use struct X { ... } const x; instead of const struct X { ... } x;.


Things should be fine if you perform strength reduction on n / num**exp. That not only makes things faster, it also gets rid of the messiness inherent in Python's exponentiation operator (so that you don't have to find out how it actually works under the hood).

In the kth iteration of the inner loop you have a quotient q_k that is equal to n / p**k (i.e. n / num**exp in your code).

To obtain n / p**(k+1) in the next iteration, all you have to do is q_k / p because that makes it (n / p**k) / p, which is equal to n / p**(k+1) as desired. In other words, instead of computing the power of the prime anew and then performing a division, simply divide the old quotient by the prime again.

Here's the complete loop, coded in a more pedestrian language:

static ushort[] primes_up_to_LIMIT = U16.SmallPrimesUpTo(50000).ToArray();

...

long divisor_count = 1;

foreach (int prime in primes)
{
    if (prime > n)
        break;

    int e = 0;

    for (int q = n; q >= prime; )
        e += q /= prime;

    divisor_count = (divisor_count * (e + 1)) % 1000000007;
}

return (int)divisor_count;

It isn't very fast - it clocked 0.12 s on SPOJ - but it should show the principle well enough and it can serve as the basis of a more performant solution.

Note: detailed investigation shows that for once, the lackluster performance of my C# submission on SPOJ is not due to usual problems inherent in .Net (e.g. poor input/output performance) but rather to some strange problem with Mono. On my laptop a worst-case input file clocks 13.7 ms under .Net and 136.4 ms under Mono.

Here is an attempt at rending the loop in Python (renaming some things for clarity):

divisor_count = 1

for current_prime in primes:

    if current_prime > n:
        break

    q = n
    e = 0
    while q >= current_prime:
        q /= current_prime
        e += q

    divisor_count *= e + 1

print divisor_count % 1000000007

One thing worth looking into is the underlying data type of the divisor count (pr in the original code). This can grow quickly, far beyond anything representable in a plain integer, and hence it will go big integer internally. This makes the multiplication pr *= s + 1 more expensive, and the statement has a cost multiplier of max(T) * pi(max(N)) = 500 * 5133.

Reducing the division count modulo 1000000007 after every update by changing

divisor_count *= e + 1

to

divisor_count = (divisor_count * (e + 1)) % 1000000007

improved the time for a worst-case input file from 1.92 s to 1.39 s on my box, so it's something worth keeping in mind. For comparison: the original code clocked 2.64 s for this file.

Belated addition: a few days after the fact an idea hit me out of the blue while I was having a smoke, and I'm reporting it here because it can speed up things by a factor of 20 for the SPOJ limit of 50000 (much more for higher inputs). This idea is based on the observation that half of the primes p satisfy

(n / 2) < p <= n

and hence

1 <= (n / p) < 2

which is just a coy way of saying

n / p = 1

Knowing that there are k primes that satisfy this condition (bisect_right() to the rescue) I can compute the contribution for all these primes in one fell swoop as

(1 + 1)**k

This readily extends to other small quotients in the remaining range of primes, and the fun only stops when the primes get so small that their squares appear as divisors (i.e. p <= sqrt(n)).

Here's how you explain this to your computer in the pythonic manner:

def v6b (n):
    """number of divisors of n! (SPOJ DIVFACT)"""
    divisor_count = 1
    hi = bisect.bisect_right(primes, n)
    for m in range(2, int(math.sqrt(n))):
        lo = bisect.bisect_right(primes, n / m, 0, hi)
        k  = hi - lo
        hi = lo
        divisor_count = (divisor_count * m**k) % 1000000007
        if k < 2:
            break
    # the rest is algorithm v5b but without regular modulo trimming since growth is contained
    for current_prime in primes[0:hi]:
        q = n
        e = 0
        while q >= current_prime:
            q /= current_prime
            e += q
        divisor_count *= e + 1
    return divisor_count % 1000000007

Here are the timings for the usual 500 worst-case inputs, first for the earlier version (here called 'v5b') and then for this new version. I went beyond the SPOJ limit of 50000 to give some idea of the growth behaviour.

# timing v5b ...
500 @    500:    0.016  // cksum 230711749546
500 @   1000:    0.016  // cksum 256088767231
500 @   5000:    0.078  // cksum 248659270107
500 @  10000:    0.156  // cksum 255839576411
500 @  50000:    1.281  // cksum 252317442043
500 @ 100000:    3.313  // cksum 246710058695
500 @ 500000:   44.376  // cksum 244700225412

# timing v6b ...
500 @    500:    0.000  // cksum 230711749546
500 @   1000:    0.015  // cksum 256088767231
500 @   5000:    0.016  // cksum 248659270107
500 @  10000:    0.031  // cksum 255839576411
500 @  50000:    0.063  // cksum 252317442043
500 @ 100000:    0.078  // cksum 246710058695
500 @ 500000:    0.266  // cksum 244700225412

Beyond 100000 or thereabouts the code gets faster with a hand-coded powering function (via repeated squaring) but the builtin exponentiation operator is faster for lower limits, and hence on SPOJ. In C++ and C# things were faster when bailing out of the first loop for k < 12 but in Python it worked best with k < 2.

Note: the time for 500 test cases at the SPOJ limit of 50000 is virtually the same as for the C# version running under Mono on my box, which is no mean feat for an interpreted language...


Google Code jam puzzle - Welcome to Code Jam

w_s, short for "welcome_solve", is, frankly, a poor name.  You're writing a function that counts the number of subsequences.  It's not even restricted to operating on strings.  Why not call it countSubsequences?

countSubsequences :: Eq a => [a] -> [a] -> Int

Your base cases should be simpler.

countSubsequences [] _ = 1
countSubsequences _ [] = 0

The recursive case is correct, but could be written more clearly with a more idiomatic convention for parameter names, and using guard clauses.

countSubsequences needle@(n:ns) haystack@(h:hs)
  | n == h    = countSubsequences needle hs + countSubsequences ns hs
  | otherwise = countSubsequences needle hs


Python Pandas - finding duplicate names and telling them apart

First I will comment on the coding, then I will suggest an alternative solution

Variable naming

Ideally you want your variable names to express what the purpose of a variable is. nameid and df2 are partly understandable, namead is not.

Exception

Never just do try-except. Always try to be as specific as possible on the exception. In the creation of nameid you except a KeyError, and in the other case a IndexError. Then use it like that

collections.defaultdict or dict.setdefault

Instead of trying and getting the KeyError, it is easier to use

nameid = defaultdict(list)
for i in df2.index:
    nameid[df2.loc[i, 'Name']].append(df2.loc[i, 'People ID'])

would work

iteration

apart from the fact that you want to prevent iteration as much as possible when using pandas (or numpy), in Python in general, there is almost always a better way than to iterator over the index. In this particular case, you can use DataFrame.iterrows. If the column labels had been valid python identifiers, DataFrame.itertuples would have been even better

nameid = defaultdict(list)
for _, row in df2.iterrows():
    nameid[row['Name']].append(row['People ID'])

with _ being the convention for the name of a variable you don't need

set

later you do

for i in nameid.keys():
    nameid[i] = list(set(nameid[i]))

Why not use set from the start, and why the conversion to list afterwards?

nameid = defaultdict(set)
for _, row in df2.iterrows():
    nameid[row['Name']].add(row['People ID'])

does all you need

len

the next part

namead = {}

for i in nameid.keys():
    paceholder = ['Nothing']
    try:
        paceholder.append(nameid[i][1])
        namead[i] = nameid[i]
    except:
        pass

uses list indexing [1] and expects lists with only 1 element to throw an Exception. This can be expressed a lot simpler with a dict expression. Later it seems the actual ids are not even needed since you only use the keys, so a set expression does the trick.

namead = {
    name
    for name, ids in nameid.items()
    if len(ids) > 1
}

pandas indexing

dupes = [i for i in df2.index if df2.loc[i, 'Name'] in namead.keys()]
for i in duperevs:
    df2.loc[i, 'Name'] += ' ' + str(df2.loc[i, 'People ID'])

pandas.Series as an isin function, so there is no need to make an intermediate list of keys whose name has more id's

dupes = df2["Name"].isin(namead)
df2.loc[dupes, "Name"] += " " + df2["People ID"].astype(str)

works too

Alternative approach

You can also use groupby.nunique

dupes = df2.groupby(['Name'])["People ID"].nunique()

This is a Series with the Name as index, and the number of unique People IDs as value. Then you can filter those with a value > 1, and check against the name

Name
Jane Doe    1
John Doe    2
Name: People ID, dtype: int64

dupes_idx = df2["Name"].isin(dupes[dupes>1].index)

Now you just need to append the People ID  to the Name

df2.loc[dupes_idx, "Name"] += " " + df2["People ID"].astype(str)

This was tested on

data = [
    ["John", "Doe", 1],
    ["John", "Doe", 1],
    ["John", "Doe", 2],
    ["Jane", "Doe", 1],
    ["John", "Doe", 2],
    ["Jane", "Doe", 1],
    ["John", "Doe", 1],
]

df2 = pd.DataFrame(data, columns=['First Name', 'Last Name', 'People ID'])

First Name    Last Name   People ID   Name
0     John    Doe     1   John Doe 1
1     John    Doe     1   John Doe 1
2     John    Doe     2   John Doe 2
3     Jane    Doe     1   Jane Doe
4     John    Doe     2   John Doe 2
5     Jane    Doe     1   Jane Doe
6     John    Doe     1   John Doe 1


Efficient way of reading in list of string csvs' into lists

Fastest way would be to use a list-comprehension here. This would avoid the repetitive lookups to list.append and will use the LIST_APPEND byte code.

s_lists = [[int(x) for x in row.split(',')] for row in data]

Note that for function names underscores are preferred over camel-case.


Implementation of Sieve of Eratosthenes in Python

Code review
Advice 1
primeslist is not used. Remove it from your code.
Advice 2
x=2: PEP 8 requires to put two spaces around the operator =.
Advice 3
Also PEP 8 complains about while (j < primeseries):. Those parentheses (()) are not required; remove them in order to reduce the visual clutter.
Advice 4
The identifier primeserieslist is misspelled: it should be prime_series_list. Actually, the role of that very list is to hold the actual prime sieve, so why not rename it simply to sieve?
Advice 5
if (z <= primeseries):
    if (z in primeserieslist):
        primeserieslist.remove(z)

could be written as
if z <= prime_series and z in prime_series_list:
    prime_series_list.remove(z)

Advice 6
SieveofEratosthenes: in Python, CamelCase identifiers are suggested to be used for naming classes. What comes to function naming, your name should be sieve_of_eratosthenes.
Advice 7
x = x + 1: you can write more succinctly x += 1.
Advice 8
Both operations prime_series_list.remove() and z in prime_series_list run in average linear time, and, thus, are inefficient. See below for more efficient implementation.
Alternative implementation
Your implementation works and seems correct, yet there is room for improvement code style -wise and efficiency-wise:
def sieve_of_eratosthenes(max_integer):
    sieve = [True for _ in range(max_integer + 1)]
    sieve[0:1] = [False, False]
    for start in range(2, max_integer + 1):
        if sieve[start]:
            for i in range(2 * start, max_integer + 1, start):
                sieve[i] = False
    primes = []
    for i in range(2, max_integer + 1):
        if sieve[i]:
            primes.append(i)
    return primes

I have set up this benchmark. From it, I get the output:

SieveofEratosthenes in 17560 milliseconds.
sieve_of_eratosthenes in 31 milliseconds.
Algorithms agree: True

Any question? Give me a message.


Representing a recursive data structure as HTML DIVs

I think what you've got here is looking pretty fine. You could move the comment explaining that it's recursive to the function header if you want it to be more explicit. The recursive function isn't doing anything strange, though.

Usually, with recursion, one can unroll the recursion to be iteration instead.

I wouldn't recommend that in this case. Right now, you have about 10-12 lines, depending on how you count. It's just two forloops. The whole function can be summarized as "make a div that contains, for each wpi zone, another div containing it's sub wpi's, similar to the div we make now."

If you were to unroll this recursion then it would get messy.

You did well.

Possible improvements are assigning the strings to separate constants, and perhaps storing wpi.zones[zone] in a local store to reduce a double double array access for each for-loop iteration to a double single array access (the for loop accesses [zone][0] and [zone][wpiInner], by storing [zone] locally, you reduce the accesses to [0] and [wpiInner] instead).


Finding remainder of stepping by multiple beyond a limit

Math.ceil(scrollOffset/n)*n - scrollOffset

gives you the difference between scrollOffset and the next multiple of n larger or equal to scrollOffset. This is equivalent to:

var firstTickX = (scrollOffset % n) ? n - (scrollOffset % n) : 0;


Well, there's already a good review by Barry, but I'll take a different tack:

In general, it's a good idea to use existing types (like smart-pointers) as building-blocks.
Still, you should not deform your code, causing loss of efficiency or clarity, just so you can use one, especially not in library-code (and such a basic container is that).

So, no smart-pointers for you, sometimes one really should get down to it.
As an aside, your clear has a bug: It tries to assign the deleter after already having deleted the source. See std::unique_ptr::operator=(std::unique_ptr&&).
There's a reason a node is generally a wholly-owned passive and dumb aggregate without any behavior: It would just get in the way of the List defining it properly.
You should use the same names for members all the containers in the standard-library use, so you can use standard algorithms.
For that same reason, and so you can efficiently iterate over all elements, you should provide iterators.
Sacrificing some space in the class itself for a size can be a reaonable idea. Similar arguments can be made for including a pointer (node**) to the end, so you can speed up push_back/emplace_back.
Consider putting the next-pointer first, that might allow the compiler to merge code for different template-arguments more often.

This is how you clear a list:

void List::clear() {
    for(node *head = this->head, *temp; head; head = temp) {
        temp = head->next;
        delete head;
    }
    this->head = nullptr;
}


Setting output parameter inside LINQ select

No, you can't do that, you can't use out parameters in a lambda.

But even if you could, I don't think it would be a good idea to do so, because it would make the code less readable.

There are also some suspicious practices in your code:

You're using SingleOrDefault(), but you don't check the result for null. If you don't want to check for null, use Single() which will throw an exception if the query returns an empty collection.
You're catching all exceptions. You should catch only the exceptions you know about. And you certainly shouldn't use something like return -1, it's much better to just let the exception bubble up and catch it somewhere up the call stack. Another option might be catching the exception, wrapping it in some more specific exception and throwing that.
Why are you setting the output parameters to 0 by default? They are nullable, so setting them to null makes more sense to me.