Play With Numbers Programming Challenge (mean value of subarrays) I'm trying to solve this  Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded.
Can someone help me improve its performance in order to pass the time limit, please?
Problem

You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.

Input

First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).

Output

print a single integer denoting the answer.

Time Limit:
1.5 sec(s) for each input file.
Result Time:
Input 1: 1.999309
Input 2: 1.998019
#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int main() {

ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);

int n = 0, q = 0;
cin >> n >> q;

vector<int> nums(n);

for (size_t i = 0; i < n; i++)
{
    cin >> nums[i];
}

for (size_t i = 0; i < q; i++)
{
    float ans = 0.0f;
    int leftIndex = 0, rightIndex = 0;

    cin >> leftIndex >> rightIndex;

    leftIndex = leftIndex - 1;
    rightIndex = rightIndex - 1;

    for (size_t i = leftIndex; i <= rightIndex; i++)
    {
        ans = ans + nums[i];
    }

    ans = ans / (rightIndex - leftIndex) + 1;
    cout << floor(ans) << "\n";
    }
    system("pause");
 }

You are running this O(R - L) loop for each query:

for (size_t i = leftIndex; i <= rightIndex; i++)
{
    ans = ans + nums[i];
}

You could obtain each sum in O(1) time if you stored the array as cumulative sums instead.

$$
\begin{align}
S_1 =&\ A_1 \\
S_2 =&\ S_1 + A_2 \\
S_3 =&\ S_2 + A_3 \\
 \vdots& \\
S_N =& S_{N-1} + A_N
\end{align}
$$

The tricky part is that \$S_N\$ could be as large as \$10^{15}\$, which requires more than 32 bits.


Command Prompt TicTacToe in C# I wrote a basic command prompt Tic Tac Toe Game. I want to know what can be improved in terms of modeling and what mistakes I've made (if any).

void Main()
{
    TicTacToeBoard board = new TicTacToeBoard();

    while(!board.GameOver())
    {
        var i = int.Parse(Console.ReadLine());
        board.MakeMove(i);
        Console.WriteLine(board.DrawBoard());
    }
}

class TicTacToeBoard
{
    SquareType[] board = new SquareType[9];

    SquareType currentType = SquareType.X;

    public void MakeMove(int i)
    {
        if(board[i] != SquareType.Empty) return;
            board[i] = currentType;
            currentType = OppositeType(currentType);
    }

    SquareType OppositeType(SquareType squareType) =>
        squareType == SquareType.X ? SquareType.O : SquareType.X;

    public bool GameOver()
    {
        return WeHaveWinner() || WeHaveDraw();
    }

    bool WeHaveWinner()
    {
        var winningIndecies = new[]
        {
            new[]{1,2,3},
            new[]{4,5,6},
            new[]{7,8,9},
            new[]{1,5,9},
            new[]{3,5,7}
        };

        foreach(var indecies in winningIndecies)
        {
            var squares = indecies.Select(i => board[i - 1]);
            if(squares.Any(x => x == SquareType.Empty)) continue;
            else if(squares.Distinct().Count() == 1) return true;
        }
        return false;
    }

    bool WeHaveDraw() => !WeHaveWinner() && board.All(x => x != SquareType.Empty);

    public string DrawBoard()
        => $@"|{board[0]},{board[1]},{board[2]}|
|{board[3]},{board[4]},{board[5]}|
|{board[6]},{board[7]},{board[8]}|".Replace("Empty","  ");
}

enum SquareType { Empty, X, O }

Overall it looks good to me.
A few points though:

int.Parse will throw if Console.ReadLine returns a non integer. Perhaps an int.TryParse and display some help (position: 0 - 8)
It's a small app but since for the whole lifetime of your application, in each iteration you'll call WeHaveWinner. I'd initialize that array as a field to that class on object construction.
On WeHaveWinner you'll (possibly) be enumerating the return of .Select() twice. Consider calling ToList() on it.
The main method, could be:

      do
        {
            var i = int.Parse(Console.ReadLine());
            board.MakeMove(i);
            Console.WriteLine(board.DrawBoard());
        } while (!board.GameOver());

This way you won't be checking for winnings before the first input

Your string replace at the end on Empty could lead to a issue if the Enum Empty was renamed. Consider replacing (SquareType.Empty, " ")
You could consider replacing the Enum with a class, that would give you ability to use polymorphism. There you could override ToString to display (X or Y or empty) which would help you get rid of that String.Replace altogether.
Something along the lines of: https://stackoverflow.com/questions/1376312/whats-the-equivalent-of-javas-enum-in-c

+1 for the verbatin + interpolation


Python Dictionary Manipulation I just finished working on a coding challenge for learning Python 2.7. Essentially, I'm a function that if it is fed a string such as:

"The man drank the drink and ate the bread and forgot the drink"

I get in return:

{'and': {'ate': 1, 'forgot': 1},
 'ate': {'the': 1},
 'bread': {'and': 1},
 'drank': {'the': 1},
 'drink': {'and': 1},
 'forgot': {'the': 1},
 'man': {'drank': 1},
 'the': {'bread': 1, 'drink': 2, 'man': 1}}

In other words, each word (that has a word following it) is a key, and the value is a dictionary of words that come right after, and the number of times that happens. (drink follows the twice in the string, hence the 2 value in its dictionary.

Here's the function I wrote to accomplish this end:

def word_counts(f):
      #Function to remove punctuation, change to lowercase, etc. from incoming string
    def string_clean(file_content):
        fc_new = "".join([i.lower() for i in file_content if i not in string.punctuation])
        fc_new = fc_new.split()
        return fc_new

    f = string_clean(f)
    unique_f = f[:]

    #For next part of function, get the unique words found in string.
    #We'll then run each through the string and find words that follow
    #Pop() the last word, since nothing follows it
    unique_f = list(set(unique_f.pop()))

    result = {}
    for word in unique_f:
        next_word_keeper = {}
        for _ in range(0, len(f)-1):
            if word == f[_]:
                if f[_+1] in next_word_keeper.keys():
                    next_word_keeper[f[_+1]] = next_word_keeper[f[_+1]] + 1
                else:
                    next_word_keeper[f[_+1]] = 1
        result[word] = next_word_keeper
    return result

Feedback appreciated, thanks.

string.punctuation == string.punctuation.lower().
You don't need string_clean to be a function as you only use it once.
Don't use _ as a variable, and definitely don't in a loop, as most use it as a 'garbage' variable.
You can use f[:-1] to get the same as u = f[:];u.pop()
Your algorithm is ok, but can be a bit odd to read.

To improve your code I'd add collections.defaultdict.
This will allow you to remove the innermost if/else.
This is as if the value isn't in the dictionary it'll default it to something for you.

>>> from collections import defaultdict
>>> next_word_keeper = defaultdict(int)
>>> next_word_keeper['test'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 1})
>>> next_word_keeper['test'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 2})
>>> next_word_keeper['test2'] += 1
>>> next_word_keeper
defaultdict(<type 'int'>, {'test': 2, 'test2': 1})

Using the above should get you:

def word_counts(f):
    f = f.lower().split()
    unique_f = list(set(f[:-1]))
    result = {}
    for word in unique_f:
        next_word_keeper = defaultdict(int)
        for i in range(len(f)-1):
            if word == f[i]:
                next_word_keeper[f[i + 1]] += 1
        result[word] = next_word_keeper
    return result

But this code is not the best when it comes to readability and performance!

Instead of going through the list multiple times, you can go though it once.
Using enumerate we get the current index, and then we can use it to get the next word.
And then using two defaultdicts we can simplify the function to six lines:

def word_counts(line):
    line = line.lower().split()
    results = defaultdict(lambda:defaultdict(int))
    for i, value in enumerate(line[:-1]):
        results[value][line[i + 1]] += 1
    return results

You can also go onto use the itertools pairwise recipe to further simplify the code.


JavaScript Sort Stack Coding Challenge A coding challenge to write a function sortStack that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.

Stack Class:

class Stack {
  constructor() {
    this.storage = [];
  }

  push(item) {
    this.storage.push(item);
  }

  pop() {
    return this.storage.pop();
  }

  peek() {
    return this.storage[this.storage.length-1];
  }

  isEmpty() {
    return this.storage.length === 0;
  }

  printContents() {
    this.storage.forEach(elem => console.log(elem));
  }
}

Stack:

const s = new Stack();
s.push(4);
s.push(10);
s.push(8);
s.push(5);
s.push(1);
s.push(6);

My solution:

const sortStack = (stack) => {
  sorted = new Stack();
  while (stack.storage.length) {
    tmp = stack.pop();
    if (tmp >= sorted.peek()) {
      sorted.push(tmp);
    } else {
      while (tmp < sorted.peek()) {
        stack.push(sorted.pop());
      }
      sorted.push(tmp);
    }
  }
  return sorted;
}

sortedStack = sortStack(s);
sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10

This iterative solution returns the correct output on multiple test cases, and there are no missing edge cases or other logical flaws that I can see, however I don't like the nested while-loop.

I want to keep the solution iterative, so how could I go about not having to use the nested while-loop?

You have access to the stack array directly so you can copy the unsorted stack it to a new stack and sort it in place using Array.sort

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    while (!stack.isEmpty()) { sorted.push(stack.pop()) }
    sorted.storage.sort((a, b) => a - b);
    return sorted;
}

or

"use strict";
function sortStack(stack) {
    const sorted = new Stack();
    sorted.storage = [...stack.storage].sort((a, b) => a - b);
    return sorted;
}

If they did not want you to access the storage array directly they would have protected it in closure. (well if that crossed their minds)

BTW your should always add "use strict" to the top of your javascript code as you have neglected to declare any of your variables, making them all global and setting your self up for some horror bugs.

The use strict directive will not let you use undeclared variable.


Maximum sum subarray efficiency -- divide and conquer w/ vectors I have successfully implemented a divide and conquer approach for find the maximum sum subarray (see code below). The code works fine and is correct, however I have an efficiency problem in that in order to recursively calculate sub-vectors, I need to do a copying operation which ordinarily wouldn't be there.

I'm using vectors because the larger program, to which this algorithm belongs, needs to read from a file and parse to the vectors. The lines vary in length, and as a result I've used vectors so that I can easily read a line, parse it to a vector, and then run it through a series of similar algorithms.

My question is: I'm trying to find a way that I can retain the use of the vectors but eliminate the copy operations so that my algorithm best reflects the \$O(nlogn)\$ runtime that the divide and conquer MSS algorithm should have.

I've tried modifying the function's header to include range values as parameters, but I can't figure out how to make that work with vectors.

int algorithm_3(vector<int> vect){

    int n = vect.size(); // size of array

    // BASE CASE
    if(n == 1){
        return vect.at(0);
    }

    // RECURSIVE CALLS
    int m = n / 2;

    // ** INEFFICIENT COPY OPERATIONS ** //
    vector<int> left_sub(vect.begin(), vect.begin() + m);
    vector<int> right_sub(vect.begin() + m, vect.end());

    int left_MSS = algorithm_3(left_sub);
    int right_MSS = algorithm_3(right_sub);

    // DETERMINE THE LEFTSUM AND RIGHTSUM FOR CASE 3: THE SUFFIX + PREFIX

    int leftsum = INT_MIN, rightsum = INT_MIN, sum = 0;
    for(int i = m; i < n; i++){
        sum += vect.at(i);
        rightsum = max(rightsum, sum);
    }

    sum = 0;
    for(int i = (m - 1); i >= 0; i--){
        sum += vect.at(i);
        leftsum = max(leftsum, sum);
    }

    int ans = max(left_MSS, right_MSS);

   return max(ans, leftsum + rightsum);
}

Most algorithms use iterators as the interface between themselves and the container. It abstracts away the actual container type and in cases likes this removes the need for a copy.

Prefer operator[] over at() when you already know that your index into the container is valid (the at() validates the index before doing the operation (useful when using unvalidated input but otherwise expensive).

template<typename I>
int sumSpecial(I loop, I end)
{
    int sum     = 0;
    int maxsum  = INT_MIN
    for(;loop != end; ++loop)
    {
        sum += *loop;
        maxsum = max(maxsum, sum);
    }
    return maxsum;
}
template<typename I>
int algorithm_3(I begin, I end){

    auto n = std::distance(begin, end);

    // BASE CASE
    if(n == 1){
        return *begin;
    }

    // RECURSIVE CALLS
    int m = n / 2;
    I mid = begin;
    std::advance(mid, m);

    int left_MSS = algorithm_3(begin, mid);
    int right_MSS = algorithm_3(mid, end);

    // DETERMINE THE LEFTSUM AND RIGHTSUM FOR CASE 3: THE SUFFIX + PREFIX

    int leftsum  = sumSpecial(std::reverse_iterator<I>(mid), std::reverse_iterator<I>(begin));
    int rightsum = sumSpecial(mid, end);

    int ans = max(left_MSS, right_MSS);

   return max(ans, leftsum + rightsum);
}

// Usage
int main()
{
    std::vector<int>   data = getData();
    std::cout << algorithm_3(std::begin(data), std::end(data));
}


Tower of Hanoi without recursion Hi I am pretty new to programming and I would like you to give me some feedback about my code, how does it look, what could be better. Thank you.

A = []
B = []
C = []
PegDict = {'A': A,'B': B,'C': C} #Would it be better to use a two dimensional array?

discs = int(input("Podaj ilość dysków: "))
for i in range(discs, 0, -1):
    A.append(i)

movesNeeded = pow(2, discs) - 1
StartingPeg = A.copy()

def move(fromm, to):
    to.append(fromm[-1])
    fromm.pop()

Moves the smallest disc one peg to the left. This part could be done better i think.

def moveLeft():
    if A and A[-1] == 1:
        move(A, C)
        return
    if B and B[-1] == 1:
        move(B, A)
        return
    if C and C[-1] == 1:
        move(C, B)
        return

Moves the smallest disc one peg to the right

def moveRight():
    if A and A[-1] == 1:
        move(A, B)
        return
    if B and B[-1] == 1:
        move(B, C)
        return
    if C and C[-1] == 1:
        move(C, A)
        return

Returns key of a peg that is the only valid move target for a cartain peg

def PossibleMove(Peg):
    if Peg:
        if Peg[-1] != 1:
            for i in PegDict:
                x = PegDict[i]
                if not x:
                    return i
                elif Peg[-1] < x[-1]:
                    return i

Main part

moves = 0
while not C == StartingPeg:
    if discs%2 == 0:
        moveRight()
        moves += 1
    else:
        moveLeft()
        moves += 1

    print(A)
    print(B)
    print(C)
    print()

    for key in PegDict:
        if PossibleMove(PegDict[key]) != None:
            fromPeg = PegDict[key]
            onePossibleMove = PossibleMove(PegDict[key])

    if fromPeg:
        moves += 1
        move(fromPeg, PegDict[onePossibleMove])
        print(A)
        print(B)
        print(C)
        print()

print()
print('Moves: '+ str(moves))
print('Minimal number of moves: '+ str(movesNeeded))

PEP-8

The Style Guide for Python Code has many stylistic guidelines that all Python programs should follow.

Naming

functions, methods, and variables should all be snake_case.  CapitalWords are reserved for Types and ClassNames.  So movesNeeded should be moves_needed and PegDict should be peg_dict, and so on.

Commas

All commas should be followed by exactly one space. {'A': A,'B': B,'C': C} violates this.

Binary operators

Binary operators should be surrounded by one space.  You mostly follow this, except for the print('Moves: '+ str(moves)) statements at the end.

Exponentiation

movesNeeded = pow(2, discs) - 1

Python has the ** operator, for exponentiation.  Thus, this could be written slightly more compactly:

moves_needed = 2 ** discs - 1

Initial list generation

A = []

for i in range(discs, 0, -1):
    A.append(i)

This is a little verbose.  You are already using the range() method to generate the disc numbers; you could simply create a list directly from the result:

a = list(range(discs, 0, -1))

Moving a Disc

def move(fromm, to):
    to.append(fromm[-1])
    fromm.pop()

I'm going to assume fromm is not a spelling error, but rather avoiding the from keyword.  The PEP-8 recommendation is a trailing underscore: from_.  My personal preference is to use synonyms.

.pop() returns the item removed from the list, which is the value you used fromm[-1] to retrieve.  Therefore, these operations could easily be combine into one statement:

def move(source, destination):
    destination.append(source.pop())

Repeated Code

    print(A)
    print(B)
    print(C)
    print()

You've repeated this code twice.  Once moving the small disc, once moving a larger disc.  Instead of repeating the code, you should move this into a function.  Then, if you change how the discs are shown (curses, GUI, ...), you only have to alter the code once.

def print_pegs(a, b, c):
    print(a)
    print(b)
    print(c)
    print()

Iterating over a container

        for key in PegDict:
            if PossibleMove(PegDict[key]) != None:
                fromPeg = PegDict[key]
                onePossibleMove = PossibleMove(PegDict[key])

In this code, you are iterating over the PegDict, fetching the keys, and using the key to look up the dictionary value.  In fact, you never use the key for anything else.  You do not need the key at all, and could simply iterate over the contents of the dictionary:

        for peg in peg_dict.values():
            if possible_move(peg) != None:
                from_peg = peg
                one_possible_move = possible_move(peg)

But notice we are computing using possible_move(peg) twice.  This is inefficient.  You should compute the result once, save it in a temporary, and use the temporary variable for further tests and assignments:

        for peg in peg_dict.values():
            move = possible_move(peg)
            if move != None:
                from_peg = peg
                one_possible_move = move

More Advanced Changes

Left or Right?

Each iteration, you check if the number of discs was even or odd, and call the moveLeft() or moveRight() function.  Since the number of discs is constant, you always make the same choice.  You could move this decision out of the loop.

move_smallest_disc = move_left if disc % 2 != 0 else move_right

while len(c) != discs:       # A simpler termination condition

    move_smallest_disc()
    print_pegs(a, b, c)
    moves += 1

    ...

But I've a different option...

Cyclic Peg Order

You always move the smallest disc either:

a -> b -> c -> a -> b -> c
a -> c -> b -> a -> c -> b

You can keep track of which order you need with a list:

    if discs % 2 == 1:
        peg = [a, c, b]
    else:
        peg = [a, b, c]

And move the smallest disc from peg[0] to peg[1], without having to hunt for which peg the smallest disc is on:

    move(peg[0], peg[1])

And later rotate the peg list:

    peg = peg[1:] + peg[:1]   # [a, b, c] -> [b, c, a] -> [c, a, b] -> [a, b, c]

After moving the smallest disc onto peg[1], the only possible moves for the larger disc will be peg[0] -> peg[2] or peg[2] -> peg[0], so you can greatly simplify the possible move determination, by just looking at those two pegs:

    source, destination = possible_move(peg[0], peg[2])
    move(source, destination)

Refactored Code

from pathlib import Path
import gettext
gettext.install('hanoi', Path(__file__).parent)

def move(source, destination):
    destination.append(source.pop())

def possible_move(peg1, peg2):
    if peg1 and (not peg2 or peg1[-1] < peg2[-1]):
        return peg1, peg2
    else:
        return peg2, peg1

def print_pegs(a, b, c):
    print(a)
    print(b)
    print(c)
    print()

def tower_of_hanoi(discs):
    a = list(range(discs, 0, -1))
    b = []
    c = []

    minimum_moves = 2 ** discs - 1

    if discs % 2 == 1:
        peg = [a, c, b]
    else:
        peg = [a, b, c]

    moves = 0
    while len(c) != discs:
        if moves % 2 == 0:
            move(peg[0], peg[1])      # Smallest disc now on peg[1]
        else:
            source, destination = possible_move(peg[0], peg[2])
            move(source, destination)
            peg = peg[1:] + peg[:1]   # Rotate the peg ordering

        print_pegs(a, b, c)
        moves += 1

    print()
    print(_('Moves:'), moves)
    print(_('Minimal moves:'), minimum_moves)

if __name__ == '__main__':
    discs = int(input(_('Enter the number of disks: ')))
    tower_of_hanoi(discs)

If you run pygettext on this, you can make a hanoi.pot template file, copy it to hanoi.po and put translations into it:

msgid "Moves:"
msgstr "Liczba ruchów:"

msgid "Minimal moves:"
msgstr "Minimalna liczba ruchów:"

msgid "Enter the number of disks: "
msgstr "Podaj ilość dysków: "

Run msgfmt on that to generate an hanoi.mo file, and store it the subdirectory: pl/LC_MESSAGES.

Running LANG="pl" ./hanoi.py on my machine, gives:

Podaj ilość dysków: 2
[2]
[1]
[]

[]
[1]
[2]

[]
[]
[2, 1]

Liczba ruchów: 3
Minimalna liczba ruchów: 3

With luck, I haven't butchered the translated strings too badly.


Preprocessing Markdown Documents for Keywords I recently added a feature to my application to serve arbitrary markdown documents from a directory. This is designed to allow authors to populate a folder full of help documents, and be able to view them without any code changes. However, because this is an MVC application, I needed a few extra features. Straight to it, here's my controller:

public class DocumentationController : Controller
{
    private const string DefaultDocPage = "Overview";
    public ActionResult Index(string id = null)
    {
        ViewBag.HomeLinkPage = string.IsNullOrEmpty(id) || id == DefaultDocPage ? string.Empty : DefaultDocPage;
        if (string.IsNullOrEmpty(ViewBag.HomeLinkPage))
        {
            id = DefaultDocPage;
        }
        var filePath = Server.MapPath(Url.Content("~/Content/Documentation/" + id.Trim("/".ToCharArray()) + ".md"));
        if(!System.IO.File.Exists(filePath))
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return null;
        }
        var contents = new StringBuilder(System.IO.File.ReadAllText(filePath));

        contents.Replace("{{AppRoot}}/", Url.Content("~"));
        contents.Replace("{{Documentation}}", Url.Content("~/Documentation"));
        contents.Replace("{{DocumentationImages}}", Url.Content("~/Content/Documentation/images"));
        contents.Replace("{{SupportLink}}", ConfigurationManager.AppSettings["SupportLink"]);
        return View("Index", (object)contents.ToString());
    }
}

In short, it allows passing a file name (without ".md") called "id" (poor name is my fault for lazy routing), assigns a default document if a file name was not passed, sets a ViewBag link to the homepage if we're not on the default document, maps the file name to a markdown document in the directory, replaces some preprocessed keywords, and returns the view with the contents of the document.

My view renders the homepage link, if applicable, then the document using MarkdownSharp. I haven't seen my idea of "preprocessed keywords" in markdown before, so I was wandering what others think. It's really useful for resolving links in documents, without worrying about them while writing. It allows document writers to write:

  To view your user page [click here]({{AppRoot}}/User/Me) and here's an image: ![image]({{DocumentationImages}}/UserPageImage.png)

Which is transformed to this, on localhost, without the author worrying about the actual path to the application, or the content directory:

  To view your user page [click here](http://localhost/MyApp/User/Me) and here's an image: ![image](http://localhost/MyApp/Content/Documentation/images/UserPageImage.png)

I also added one for the support link, so I could pull in that setting from ConfigurationManager.AppSettings.

My questions, succinctly:

Are there any realistic cases that I may not be anticipating?
Is there a best practice that I'm not aware of, for having pre-processed text replaced in markdown?
Is there a better way than StringBuilder.Replace for processing each of my keywords?

A few minor nit-picks:

I'd change the id checking code around a bit to avoid some redundant checks by first sanitizing the input:

id = string.IsNullOrEmpty(id) ? DefaultDocPage : id;
ViewBag.HomeLinkPage = id == DefaultDocPage ? string.Empty : DefaultDocPage;

Consider making DefaultDocPage a configurable property so you don't have to change the code if when someone asks to have a different name
Trim takes a params array so there is no need to do the ToCharArray, you can just pass in all the trim characters directly like this:

id.Trim('/')

Replacing

var filePath = Server.MapPath(Url.Content("~/Content/Documentation/" + id.Trim("/".ToCharArray()) + ".md"));

with string.format makes it a bit easier to read:

var filePath = Server.MapPath(Url.Content(string.format("~/Content/Documentation/{0}.md", id.Trim('/'))));

1. There is no need to cast to object here:

return View("Index", (object)contents.ToString());


Propagating table cell border colors to adjoining cells I have a JavaScript function (which uses the jQuery library but that should not be relevant here) that takes as input an ID (integer), a color, and a side (all, top, right, bottom, or left). For each side, a computation is run in an if-clause. For instance, of borderSide == "top" and anId >= width, do something.

Even though it's not important for the problem, it might help to understand what is going on: the idea is that in a table with a width and height of cells, a user can "color" a cell's border. However, in HTML/CSS it might be necessary to also color another cell's border to make the effect visible. E.g. if you want to color a cell's top border, you may need to paint the cell right above it in the same color as well.

"all" is a special case, as that means all sides of a cell need to be painted, and with respect to its neighbours all surrounding cells need to undergo modification as well (top's bottom border, right's left, bottom's top, left's right). The disjunction between the case with all and all others makes me use a lot of duplicate code, however I feel that the only way I could minimise this is by using separate if's (instead of if...else if's). However, that would mean that every if is evaluated and needs computation, even though in the cases without all there can only be one if active at any given time. So my question is, how can I re-write the following and getting rid off duplication, without evaluating each if-clause if borderSide is not all?

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    if (cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - width);
    }
    if (cellId % width - 1 !== 0) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + 1);
    }
    if (cellId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    }
    if (cellId % width !== 0) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + 1);
    } else if (selectedBorderSide === "bottom" && cellId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}

So if borderSide === "all", all conditions after the &&'s should be evaluated. However, if it's not all, there can only be one at a time (hence the use of else if). So when it's not "all", I do not want to evaluate all if-clauses. So when borderSide === "top" there is no chance that any of the following if-clauses will be true, so I don't want to evaluate them and thus save computations.

Recursion is a handy way to remove repetition...

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    ['top','bottom','left','right'].forEach(side=>
        changedCells.push(...paintConnectedBorder(cellId, selectedBorderColor, side)));
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + anId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + anId + 1);
    } else if (selectedBorderSide === "bottom" && anId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}

Basically if 'all' is selected the function will call itself once for each of the individual selections.

As requested, here's the ES5 version for older browsers...

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    var sides = ['top','bottom','left','right'];
    for(var i=0, side; side=sides[i]; i++)
        changedCells.push.apply(changedCells, paintConnectedBorder(cellId, selectedBorderColor, side)));
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + anId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + anId + 1);
    } else if (selectedBorderSide === "bottom" && anId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}


Finding questions to answer - Part 2 I've refactored my previous question finder, and added multi-tag support, and support for searching for keywords in the question titles. Essentially, what it does is find questions that could be answered based on the following parameters.

-- @MinimumQuestionVotes - The minimum amount of votes on a question.
-- @MaximumQuestionAnswers - The maximum amount of answers to a question.
-- @QuestionTags - The question's tags. Blank string is a wildcard.
-- @TitleContains - Words in the title. Blank string is a wildcard.

If you feel that any parameters aren't needed, or can be improved, just mention it. I'm open to any suggestions. Anyways, here's the code, and here's the SEDE query link.

-- User parameters for finding questions. Here is
-- a brief description of what each parameter does.

  -- @MinimumQuestionVotes - The minimum amount of votes on a question.
  -- @MaximumQuestionAnswers - The maximum amount of answers to a question.
  -- @QuestionTags - The question's tags. Blank string is a wildcard.
  -- @TitleContains - Words in the title. Blank string is a wildcard.
DECLARE @MinimumQuestionVotes INT = ##MinimumQuestionVotes:int?0##;
DECLARE @MaximumQuestionAnswers INT = ##MaximumQuestionAnswers:int?0##;
DECLARE @QuestionTags NVARCHAR(150) = ##QuestionTags##;
DECLARE @TitleContains NVARCHAR(250) = ##TitleContains##;

-- Final results are SELECTed based on the following
-- conditions.

  -- ClosedDate  IS EQUAL TO              null
  -- PostTypeId  IS EQUAL TO              question
  -- Score       GREATER THAN OR EQUAL TO @MinimimQuestionVotes
  -- AnswerCount LESS THAN OR EQUAL TO    @MaximumQuestionAnswers
  -- Tags        CONTAIN                  @QuestionTags
SELECT
    [Posts].Id AS [Post Link]
  , [Posts].OwnerUserId AS [User Link]
  , [Posts].Score
  , [Posts].Tags
  , [Posts].ViewCount
  , [Posts].AnswerCount
  FROM Posts WHERE
        [Posts].ClosedDate IS NULL
    AND [Posts].PostTypeId = 1
    AND [Posts].Score >= @MinimumQuestionVotes
    AND [Posts].AnswerCount <= @MaximumQuestionAnswers
    AND [Posts].Tags LIKE '%' + REPLACE(@QuestionTags, ' ', '%%') + '%'
    AND [Posts].Title LIKE '%' + REPLACE(@TitleContains, ' ', '%%') + '%'
  ORDER BY Score DESC;

Finally, here's some example input for the parameters. Do note, in the @QuestionTags and @TitleContains fields, you need to put single quotes, '', and space-separate each tag/word.

@MinimumQuestionVotes:   1
@MaximumQuestionAnswers: 0
@QuestionTags:           'python beginner'
@TitleContains:          'web'

There are some usability issues with @QuestionTags:

The ordering of tags matters. I think in the typical use case that's not the desired behavior
The input format is hackish (the implementation too) and unintuitive

I have an alternative suggestion that has different downsides:

Use multiple tag input fields, for example @Tag1, @Tag2, and so on
The advantage is that you could enter tags in any order, and without funky input rules
The disadvantage is that the number of tags you can enter will be limited to the number of fields you provide
Note that this approach will also open the possibility to choose the condition for for matching tags: they can be AND-ed or OR-ed. Your choice, or give another input to users to let them decide

The numbered fields are not exactly pretty, but I think the query will be easier to use this way. (Can be subjective.)

You could do similarly for matching keywords in the title.

Note that I dropped "Question" from the parameter names, to simplify to @TagN. On the network only questions can have tags, so this is obvious.

Other notes:

The semicolons at the end of variable declarations are unnecessary
It would be nice to make title optional
The repeated [Posts]. prefix of fields are not necessary, and a bit of a noise

Example implementation with some of the improvements explained above:

DECLARE @MinimumQuestionVotes INT = ##MinimumQuestionVotes:int?0##
DECLARE @MaximumQuestionAnswers INT = ##MaximumQuestionAnswers:int?0##
DECLARE @Tag1 NVARCHAR(50) = RTRIM(LTRIM(##Tag1:string? ##))
DECLARE @Tag2 NVARCHAR(50) = RTRIM(LTRIM(##Tag2:string? ##))
DECLARE @Tag3 NVARCHAR(50) = RTRIM(LTRIM(##Tag3:string? ##))
DECLARE @TitleContains NVARCHAR(250) = RTRIM(LTRIM(##TitleContains:string? ##))

SELECT
    Id AS [Post Link]
  , OwnerUserId AS [User Link]
  , Score
  , Tags
  , ViewCount
  , AnswerCount
  FROM Posts WHERE
        ClosedDate IS NULL
    AND PostTypeId = 1
    AND Score >= @MinimumQuestionVotes
    AND AnswerCount <= @MaximumQuestionAnswers
    AND (@Tag1 = '' OR Tags LIKE '%' + @Tag1 + '%')
    AND (@Tag2 = '' OR Tags LIKE '%' + @Tag2 + '%')
    AND (@Tag3 = '' OR Tags LIKE '%' + @Tag3 + '%')
    AND (@TitleContains = '' OR Title LIKE '%' + REPLACE(@TitleContains, ' ', '%%') + '%')
  ORDER BY Score DESC;


Is this the right way to work with callbacks and the EventEmitter? I'm creating a small online multiplayer game in NodeJS and I'm wondering if I'm "doing it right".
Here is a bit of my code:

// app.js
// if I give an id as argument we assume it's an existing player.
var Player = new player();

Player.on('playerLoaded', function (err, result) {

    if (result) {

        Player.setName('somename');

        Player.on('setName', function (err, result) {

            console.log('Name changed');

        });

    } else {

        // couldn't load the player

    }

});

This is my player object:

function Player(id) {

    // if we don't have a id, this player needs to be created
    this.id = (typeof id !== 'number') ? this.createPlayer() : this.setPlayer(id);
    this.name = "";
    EventEmitter.call(this);

}

This is the createPlayer method:

Player.prototype.createPlayer = function () {

    var self = this;

    // we only need a datetime to insert
    connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {

        if (result) {

            process.nextTick(function () {

                if (result.insertId) {

                    console.log("Successfully found player no. " + result.insertId);

                    self.id = result.insertId;

                    // everything was successful
                    self.emit('playerLoaded', false, true);

                } else {

                    console.log("Trouble inserting a new player");

                    self.emit('playerLoaded', true, false);

                }

            });

        } else {

            process.nextTick(function () {

                console.log("Trouble with the mysql while inserting player: " + err);

                self.emit('playerLoaded', err, null);

            });

        }

    });

};

And this is the setName method:

Player.prototype.setName = function (name) {

    var self = this;

    connection.query("UPDATE players SET ? WHERE ?", [
        { name: name },
        { id: self.id }
    ], function (err, result) {

        if (result) {

            process.nextTick(function () {

                self.name = name;

                console.log("Successfully updated name of player no. " + self.id);

                self.emit('setName', false, true);

            });

        } else {

            process.nextTicket(function () {

                console.log("Trouble with the mysql while changing player name: " + err);

                self.emit('setName', err, false);

            });

        }

    });

};

Basically my question is if this is the right way to deal with callbacks?

Interesting question,

I am assuming you know that usually, in essence, the setting of the name would be written like this:

Player.setName('somename' , function( err, result ) {
  console.log('Name changed');
});

and in essence setName would be

Player.prototype.setName = function( name, callbackFunction ) {

    var self = this;

    connection.query("UPDATE players SET ? WHERE ?", [
        { name: name },
        { id: self.id }
    ], function (err, result) {

        if (result) {
            process.nextTick(function () {
                self.name = name;
                console.log("Successfully updated name of player no. " + self.id);
                callbackFunction( false, true );
            });
        } else {
            process.nextTicket(function () {
                console.log("Trouble with the mysql while changing player name: " + err);
                callbackFunction( err, false );
            });
        }
    });
};

I like that with your approach you avoid "callback hell". Since your project is a small game  I would advise you to see how far you can go with this scheme.

Other than that, I hope you are not planning to write a whole function including SQL code for each property. In my mind you should only have 1 function that takes care of updating the whole of the player object.

Finally, easy up on the new lines, it makes your code too hard to read.


.NET - Get a DateTime from a pointer to an OLE Date So I have this SDK I'm working with, which lives in unmanaged land, and when it wants to tell me something in particular it sends me a particular Windows API message and passes a pointer to a Date in the LParam of that message. I figured out that the date is OA-compatible (a double representing a fractional number of days since the epoch), and so after some playing around I came up with this:

Dereference the pointer by marshalling the raw bits at the address into an Int64.
Perform a bitwise conversion of the Int64 into a Double.
Treat that double as an OA Date and pass it to the static methods on DateTime to get the answer.

It totally works, but conceptually it sounds really kludgy; pointer, to long, to double (bitwise to boot), to DateTime. Other than inlining these three lines with only the final result being stored, is there any more direct way in .NET to turn an IntPtr to an OLE Date into a DateTime?

private void GetDateFromWinMsg(Message message)
    {
        ...
        var dateAsULong = Marshal.ReadInt64(message.LParam);
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong);
        var dateTime = DateTime.FromOADate(dateAsDouble);
        ...
    }

I agree with @IAbstract that the inline code looks fine. I would wrap it and name it differently since nothing in the current code reveals that it is a pointer to an OLE/OA Date.

public DateTime DateTimeFromOLEDatePointer(Int64 oaDate)
    {
        var dateAsULong = Marshal.ReadInt64(oaDate);
        var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong);
        var dateTime = DateTime.FromOADate(dateAsDouble);
    }

Usage:

private void GetDateFromWinMsg(Message message)
    {
        return DateTimeFromOLEDatePointer(message.LParam);
    }

Could also make it an extension method.


Getting an array from one property of an associative array best practice I have an array of objects eg.

[
   array(
    'id' => 1,
   'name' => "simon"
),
...
]

and I need to get an array of IDs eg.
[1,2,3,4,5];

Currently I'm doing this:

    $entities = $this->works_order_model->get_assigned_entities($id);

    $employee_ids = array();

    foreach ($entities as $entity) {
        array_push($employee_ids, $entity->id);
    }

Is there a best practice way of doing this?

I think array_map is what you are looking for:

php > $aa = array (array ("id" => 1, "name" => 'what'), array('id' => 2));
php > function id($i) { return $i['id'];};
php > print_r(array_map ('id', $aa));
Array
(
    [0] => 1
    [1] => 2
)


C++ class for disjoint-set/union-find on integers I have implemented the disjoint-set data structure. The purpose is to group integers together. For example, if I want to find out the groups of integers where each adjacent neighbors are same:

vector<vector<int>> test = {
{1,0,0,1},
{0,0,0,1},
{0,3,3,1}};

There are 4 groups of integers, namely:

Group 1: 1 at (0,0)
Group 2: 0's at (0,1), (0,2), (1,0), (1,1), (1,2), (2,0)
Group 3: 1's at (0,3), (1,3), (2,3)
Group 4: 3's at (2,1), (2,3)

Here is the code in C++:

//This union-find class implements two optimization ideas:
//1)path compression
//2)union by rank

class DisjointSet {
    public:
    DisjointSet(int num_nodes);
    int find(int element);
    void do_union(int elment_a, int element_b);
    void dup(vector<int> &v);
    private:
    vector<int> parent_, rank_;
};

DisjointSet::DisjointSet(int num_nodes):
    parent_(num_nodes),rank_(num_nodes, 0)
{
    for(int i=0; i<num_nodes; ++i) parent_[i] = i;
}

int DisjointSet::find(int element)
{
    if(parent_[element] == element) return element;
    //1)path compression
    return parent_[element] = find(parent_[element]);
}

void DisjointSet::do_union(int a, int b)
{
    if(parent_[a] == parent_[b]) return;
    int fa = find(a), fb = find(b);
    //2)union by rank
    if(rank_[fa] < rank_[fb]) {
    parent_[fa] = fb;
    } else {
    parent_[fb] = fa;
    if(rank_[fa] == rank_[fb]) rank_[fa]++;
    }
}

Seems pretty straightforward. By the way, "disjoint-set" is a less common name for this data structure than "union-find", at least in my experience.

You have several typos in your code; you should always fix those. Sure, the computer doesn't care, but we don't write C++ code for the computer; we write it for the human reader. elment_a should be element_a; you should either implement dup or remove its declaration; and you should use proper indentation.

class DisjointSet {
public:
    DisjointSet(int num_nodes);
    int find(int element);
    void do_union(int element_a, int element_b);
private:
    std::vector<int> parent_;
    std::vector<int> rank_;
};

Notice also that I added the missing std::s to your vectors (and by the way you should #include <vector>), and split each member variable declaration onto its own line so that the struct layout is easier to see at a glance.

Who says using rank_ is an optimization? It feels to me like a pessimization, because you're trading O(N) extra space (and more convoluted code) for something like O(lg N) faster lookups. I do see that e.g. Boost.DisjointSet implements "union by rank" as well, but I'd be interested in seeing some benchmark numbers on your particular use-case.

return parent_[element] = find(parent_[element]);

Modern C++ (like modern any-other-language) strongly prefers not to mix side effects into the middle of expressions, except in idiomatic cases such as *p++ = .... Prefer to put the assignment in its own statement.

parent_[element] = find(parent_[element]);
return parent_[element];

int fa = find(a), fb = find(b);

Same deal as above: prefer to put each variable declaration on its own line for readability.

int fa = find(a);
int fb = find(b);

And then use proper indentation in what follows:

if (rank_[fa] < rank_[fb]) {
    parent_[fa] = fb;
} else {
    parent_[fb] = fa;
    if (rank_[fa] == rank_[fb]) rank_[fa]++;
}

Basically, though, looks good. Looks like you picked the right level of abstraction for this particular problem: not too scattered (keeping related things in a nice neat class), but not too libraryish (you hard-code int, for example, instead of going all in with templates).


Append the first half of the first line of /etc/hosts to a conf file I have to edit a config automatically before starting a service in a docker container (a storm supervisor), and I want to append something like this in /opt/storm/conf/storm.yaml: storm.local.hostname: 1.1.1.1 (extracted from /etc/hosts)

What I currently do is that:

echo -n "storm.local.hostname: " >> /opt/storm/conf/storm.yaml && head -1 /etc/hosts | awk -F ' ' {'print $1'} | xargs echo >> /opt/storm/conf/storm.yaml

How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^

Disclaimer: this runs inside a docker container, so there's only access to classic bash.

How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^

You're not naive, it looks obfuscated ;-)

A couple of general tips first:

When you find yourself writing the same path twice, put it in a variable

to avoid duplicated hard coded strings
to make it easy to change the path later if needed
to give it a meaningful descriptive name

Avoid echo -n. In general, avoid all echo statements that use any flags like -n, -e, because these are not portable. When you need those extra functions, printf is more portable. Plain echo with no flags, just stuff to print is nice, short and sweet
When you see head and awk in the same pipeline, usually you can rewrite with just awk. It saves the execution of one process.
I think head -NUM is deprecated. To be safe, I suggest to use head -n NUM instead.
To avoid extremely long lines, break the line with a \

A couple of specific tips in the context of your example:

The one-liner first appends some fixed text to the config file,
and then appends some more text by way of awk.
Since awk can print fixed text too, the echo is not needed at all.
xargs seems pointless: you could just redirect the output of awk
The separator ' ' you used with awk seems both unnecessary and error prone. The hosts file might have entries separated by tab. Simply by not specifying a separator, awk will work with both cases, space or tab separated.

Following the suggestions above, the one-liner could be simplified to:

awk '{print "storm.local.hostname: " $1; exit}' < /etc/hosts >> /opt/storm/conf/storm.yaml


Exporting a list of projects in Node.JS I am using the following code in a Node.js / React project. It works fine but it looks like it could be consolidated a little more using a OO pattern.

import projectsData from '../data/index.js';

function Project(project) {
  this.name = project.name;
  this.order = project.order;
  this.title = project.title;
  this.date = project.date;
  this.tags = project.tags;
  this.logo = project.logo;
  this.html = project.html;
  this.agency = project.agency;
  this.slides = Object.values(project.slides).map(slide => slide);
  this.path = `projects/${this.name}`;
  this.route = `/projects/${this.name}`;
  this.slidesPath = `/projects/${this.name}/slides/`;
  this.hiDefAffix = '@2x';
};

const all = {};
Object.values(projectsData).map(project => all[project.name] = new Project(project));

const projects = {
  all,
  sorted(){ return Object.values(this.all).sort((a, b) => a.order - b.order) },
  get(project) {
    try {
      if (this.all[project]){
        return this.all[project];
      } else {
        throw new Error(`Project "${project}" not found.`);
      }
    } catch (error) {
      return false;
    }
  },
  toJSON() {
    return JSON.stringify(this.all);
  }
};

export default projects;

Basically I have a constructor and an exported object that ends up having a bunch of objects created by the constructor above it. Can these be consolidated in some way?

function Project(project) {
  this.name = project.name;
  this.order = project.order;
  this.title = project.title;
  this.date = project.date;
  this.tags = project.tags;
  this.logo = project.logo;
  this.html = project.html;
  this.agency = project.agency;
  this.slides = Object.values(project.slides).map(slide => slide);
  this.path = `projects/${this.name}`;
  this.route = `/projects/${this.name}`;
  this.slidesPath = `/projects/${this.name}/slides/`;
  this.hiDefAffix = '@2x';
};

If all this does is just set props to an instance, then you probably don't even need a constructor. You can simply use a factory function that accepts a project object and returns an object with properties.

function createProject({name, order, title, date, tags, logo, html, agency, slides, name}){
  return {
    name,
    order,
    title,
    date,
    tags,
    logo,
    html,
    agency,
    slides: Object.values(project.slides),
    path: `projects/${this.name}`,
    route: `/projects/${this.name}`,
    slidesPath: `/projects/${this.name}/slides/`,
    hiDefAffix: '@2x'
  };
}

Object.values(project.slides).map(slide => slide);

Looks like project.slides is an object. Object.values creates an array of values. array.map just creates a copy of that array, which is useless.

const all = {};
Object.values(projectsData).map(project => all[project.name] = new Project(project));

You are misusing array.map. array.map is for transforming one array into another in a 1-to-1 transformation. What you are doing here is creating an object. This is a job for array.reduce.

const all = Object.values(projectsData).reduce((all, project) => {
  return { ...all, [project.name]: createProject(project)};
}, {});

try {
  if (this.all[project]){
    return this.all[project];
  } else {
    throw new Error(`Project "${project}" not found.`);
  }
} catch (error) {
  return false;
}

The try-catch is pointless. You are immediately catching the error and simply returning false. Why not return false in the first place?

return this.all[project] || false;

toJSON() {
  return JSON.stringify(this.all);
}

I believe this is a practice commonly done by Java developers to have an intermediate function to handle special properties. But this is unnecessary in most cases since any simple JS object is immediately serializable by JSON.stringify, and you don't appear to use any of the new data types.

  How can I make this Javascript code more OO

This is the wrong way to think in terms of programming, locking yourself to a paradigm. What you should be asking is "How to make this code simpler?" or "How to make this code easier to understand?".

Also, OO isn't about classes, or constructors or methods and properties. It's about working with objects, whether they are instances of classes or simple data structures like object literals or arrays. You can do a lot with just object literals and arrays. You aren't going to need the class and methods fluff in most cases.


"Nothing" interpreter/compiler This is an implementation of the Nothing programming language. The language spec is as follows:

  Design philosophy

  In the current software industry focus lays on solving complex
  problems by using complicated algorithms. The language "Nothing" was
  created to shift this focus from complex problems towards the
  expectations of the programmer and the user. This way even the most
  complicated programming challenges swiftly disappear as if they never
  have existed before. Basically, the main strengths of the language
  "Nothing" are:

  to create bug-free and portable software https://esolangs.org/wiki/Nothing
  to shift focus from complex technical solutions towards the expectation of the programmers and users

  Program structure

  Nothing has a very simple and straightforward structure. It is a
  typeless language which does not use any of the known programming
  constructs like loops, choices and the like. It is the only language
  which can be considered 1GL, 2GL, 3GL, 4GL and 5GL all at the same
  time.

What I would like to know:

Does my program conform to the language specs?
Does it follow the design philosophy?
Readability, performance, etc. Any improvements welcome

Source code:

/*
 * A 'Nothing' compiler
 * <http://www.turtle.dds.nl/nothing/>
 * September 2010, RoPe Development Inc.
 *
 * Author: authorname
 */

#include <iostream>
#include <fstream>
#include <cstdlib> // EXIT_FAILURE
#include <string> // std::char_traits<char>::eof

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cerr << "nothing: fatal error: no input files\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    std::ifstream program(argv[1]);

    if (!program)
    {
        std::cerr << "nothing: error: " << argv[1] << ": No such file or directory\n";
        std::cerr << "nothing: fatal error: no input files\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    if (program.peek() != std::char_traits<char>::eof())
    {
        std::cerr << "nothing: fatal error: program is not empty\n";
        std::cerr << "compilation terminated.";
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

Example:

# bash
$ touch helloworld.not
$ ./nothing helloworld.not
$

This line here:

return EXIT_SUCCESS

Is equivalent to this:

return 0;

Which is automatically inserted by the compiler if it isn't found. In short, return EXIT_SUCCESS can be removed.

In addition, a few of your error messages don't include a newline at the end, as seen in this line here, and two other places:

std::cerr << "compilation terminated.";

I'd just add a newline to the end of the output string to not annoy the user when the program completes/fails, like this:

std::cerr << "compilation terminated.\n";

Instead of requiring the user to provide a file in the command line arguments, you can just do, well, nothing. This is the language Nothing after all. This means that this piece of code here:

if (argc < 2)
{
    std::cerr << "nothing: fatal error: no input files\n";
    std::cerr << "compilation terminated.";
    return EXIT_FAILURE;
}

Can just become this:

if (argc < 2)
{
    return 0;
}

Other than those two nitpicks, there really isn't much else for me to review here. As far as I can tell, you've followed the language specification just fine, and produced some readable code.


Entity Framework - Table structure, navigating many descendants, etc Someone suggested to try asking this here instead of stackoverflow, so I'm taking their advice.

So I'm rewriting a dated application and trying to structure things the right way. I have a Category > Product > Part > Options basic structure, but there are multiple layers in each and I don't know how to simplify my data structure, and navigate children effectively.

I feel like it's a little complicated for e-commerce, but we have a multitude of product, part, and part options.

So just for kicks I tried to see if I could round up all the data from a top level category all the way down to the swatches for the different part options to see if an entire page could display the entire category/product line at once (I know not to do this in production). The immediate problem I ran into was including all the descendants in my LINQ queries, as there are several that require intermediary objects due to the extra columns in the relational tables. That's necessary, I understand, but it gets messy quickly as this is setup to have a potentially unlimited number of category/subcategory levels. For example:

IQueryable<Category> Categories = Context.CategoryHierarchies
    .Where(w => w.ParentCategoryId == null)
    .Where(w => w.Active == true)
    .OrderBy(o => o.Sort)
    .Select(s => s.Category)
    .Include(x => x.ParentCategories)
    .Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .Include(x => x.CategoryProducts).ThenInclude(x => x.Products)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartStyles).ThenInclude(x => x.Swatch)

    // I can follow the chain down but will need a second one to
    // get to other parts of the tree, such as product themes and the
    // two other part options, and currently this is only for the
    // current category. Doing sub categories would be ideal, but that,
    // assuming there's never more than 2 sub-category levels, still
    // triples the size of this stupid-large query.

    .Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .Include(x => x.CategoryProducts).ThenInclude(x => x.Products)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartStyles).ThenInclude(x => x.Swatch)

    // etc..

I didn't do lambas on the includes to keep things shorter for the paste. Now obviously this could go on even longer as I didn't get into the part options, but from there, I would potentially need to have 3 more lines for each level of part option, right? Like:

.Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .ThenInclude(x => x.CategoryProducts).ThenInclude(x => x.Product)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartMaterials).ThenInclude(x => x.Swatch))

.Include(x => x.SubCategories).ThenInclude(x => x.Category)
    .ThenInclude(x => x.CategoryProducts).ThenInclude(x => x.Product)
    .ThenInclude(x => x.ProductParts).ThenInclude(x => x.Part)
    .ThenInclude(x => x.PartFinishes).ThenInclude(x => x.Swatch))

All the way down. Yikes. So for my question, when I'm loading my ViewModels into a view, and I want to access categories, products, and potentially parts, is there a better way to do this? I have a view that does a foreach on each level that I can, but it starts getting tedious real fast. Do I just load them all as separate objects in the view model and access them directly, and populated through separate queries? I'm pretty new to this and would really appreciate anyone's suggestions.

I did see the .NET Core .ThenInclude() stuff, which does look helpful, but I wasn't completely sure it would clean things up that much. It's a lot of descending.

edit: put lambdas back in. Still not a full query, but readers can use their imaginations as to how large it could potentially be for my hypothetical.

I also work on an e-commerce platform that has tons of data in it.  What I've found is that if you have more than a very basic query, write the query yourself.  EF speeds up saving records and very basic selects, but as soon as you start doing something a bit complicated, EF will spit out thousands of lines of SQL for something you could have done yourself in 100.  You are better off just trying to create the SQL for it and use Dapper or just create an object that you can map directly back to from the query.  Use context.Database.SqlQuery(sql, parameters).ToList() and you'll be able to get exactly what you need.  Though, naturally, it is going to be way more work on your part since you have to do all the joins manually and type that out, but if you need it to perform, then I would really recommend just typing it out.  I've had calls go from 60 seconds down to < 4 by just doing it myself instead of relying on EF.


Matching a pattern in many lines of text This is the relevant piece of my code (false is returned if the whole cycle is finished, pattern is a String passed to the function):

for (FileLine fileLine : fileLines) {
    itemText = fileLine.getText();

    itemStrings = new ArrayList<String>();
    itemStrings.addAll(Arrays.asList((itemText).split(" ")));
    for (String itemString : itemStrings) {
        if (itemString.equalsIgnoreCase(pattern)) {
            return true;
        }
    }
}

How can I speed this up? I've tried using regex, something like:

//before the for cycle
Pattern regexPattern = Pattern.compile(pattern);

//in the cycle
if (regexPattern.matcher(itemText).matches())
    return true;

But it doesn't work for some reason. Maybe I'm doing it wrong, or there's a completely different way of accomplishing this?

You should probably be using find() instead of matches() (source).

I would recommend using regexpal to test out your pattern, just in case.

Whether or not the Regex solution is faster, you'd have to run some tests, but I suspect it's MUCH faster.


Coding convention when using differential inheritance Ever since reading Crockford's "Good Parts" and Johansen's TDD book, I have wanted to use more of the differential inheritance pattern in my coding at work (as in avoiding new by using Object.create()), but I find that I am having a hard time argumenting for the clearness of the code when trying to make "types" that can be used for object creation. Most of my co-workers are "classically" inclined.

I guess this question somehow boils down to these points

downcasing/UpperCasing (i.e. "car" vs "Car")
prefixing the base instances (i.e "prototypeCar"). This practice is for instance seen in the code of the author of Fluent Javascript
init() methods VS factory methods.

// init style
car.init = function(brand) {
    this.brand = brand;
}
myCar = Object.create(car).init("Nissan");

// versus

// factory method
function createCar(brand) {
    var o = Object.create(car);
    o.brand = brand;
    return o;
}

// alternative factory method
function createCar(brand) {
    var o = Object.create(car, { brand : brand } )
    return o;
}

myCar = createCar("nissan")

My problem with having lower cased car types is that for someone glancing over parts of the code, they might think that car is an instance of some kind of 'class' Car, and get confused when I suddenly start creating new instances from it. In my opinion, the notion of using a prefix, such as "prototype", seems to more clearly state my intentions with the instance. So do saying Car, but that implies that it should be used together with new, so one should perhaps refrain from that ... (?)

I see a conceptual issue with this approach: it is nice to inherit from objects, but these entities are not the "real" object. In other words, there is no much sense in using them outside of initialization code. If you need new [Cc]ar then it will not be wise to take any car that is nearby and just modify it and enjoy numerous side effects - you probably need some "etalon" of cars. The Car.

To be honest, I frequently have an intention to use only factory methods in JavaScript and not use the operator new at all. But then I look on how many should I rewrite for that and give up because I do not see the real benefits from this approach - it is not a big task to rename the constructor Something to factory method createSomething and replace it within the code, but what is next?


Scala Direction enum with Enumeration and collection usage I've just implement direction enum

object Direction extends Enumeration {
  type Direction = Value
  val Up, Right, Down, Left = Value

  val pairs = HashSet() ++ List((HashSet() ++ List(Up, Down)), (HashSet() ++ List(Right, Left)))

  def isOpposite(one: Direction, other: Direction): Boolean = {
    pairs.contains(HashSet() ++ List(one, other))
  }
}

Usages

direction match {
  case Right => ...
  case Left => ...
  case Up => ...
  case Down => ...
}

if(Direction.isOpposite(d1, d2))...

Can I improve it some how?

Use an Algebraic Data Type (ADT):

abstract class Direction(val opposite: Direction)
case object Up extends Direction(Down)
case object Down extends Direction(Up)
case object Left extends Direction(Right)
case object Right extends Direction(Left)

or:

abstract class Direction {
  def isOpposite(d: Direction): Boolean
}
case object Up extends Direction {
  def isOpposite(d: Direction) = d == Down
}
case object Down extends Direction {
  def isOpposite(d: Direction) = d == Up
}
case object Left extends Direction {
  def isOpposite(d: Direction) = d == Right
}
case object Right extends Direction {
  def isOpposite(d: Direction) = d == Left
}


Find the highest occurring digit in the prime numbers present between L and R (both inclusive) Given two numbers L and R, find the highest occurring digit in the
  prime numbers present between L and R (both inclusive). If multiple
  digits have the same highest frequency print the largest of them. If
  there are no prime no.s between L and R, print -1.

How can I optimize this code further in terms of running time?

package com;

import java.util.Arrays;

/**
 * Created by ankur on 19/7/15.
 */
public class HighestOccuringDigit {
    private static int MAX = 1000000;
    private static boolean[] isPrime = generatePrime();
    public static void main(String...strings){

        int index = getMaxOccuredDigit(13,13);
        if (index != 0){
            System.out.println(index);
        }else{
            System.out.println(-1);
        }
    }

    private static int getMaxOccuredDigit(int lower, int higher){
    int[] highestDigitCount = new int[10];
    int max = 0;
    int maxIndex = 0;
    if (lower < 3){
        highestDigitCount[2] = 1;
        lower = 3;
    }
    for (int i = lower; i <= higher; i++){
        //System.out.println(i);
        int index = (i - 3) >> 1;
        //System.out.println(i);
        if (((i & 1) != 0)   && isPrime[index]){
            //System.out.println(i);
            int[] digitsCount = getDigitCount(i);
            for (int j = 0; j < 10; j++){
                highestDigitCount[j] = highestDigitCount[j] + digitsCount[j];
                if (highestDigitCount[j] > max){
                    max = highestDigitCount[j];
                }
            }
        }
    }
    if (max == 0){
        return 0;
    }
    for(int i = 0; i < 10; i++){
        if (highestDigitCount[i] == max){
            maxIndex =  i;
        }
    }
    return maxIndex;
}

    private static int[] getDigitCount(int prime){
        int[] digitsCount = new int[10];
        Arrays.fill(digitsCount, 0);
        while(prime != 0){
            int lastDigit = prime % 10;
            digitsCount[lastDigit] += 1;
            prime /= 10;
        }

        return digitsCount;
    }

    private static boolean[] generatePrime(){
        int root = (int) Math.sqrt(MAX) + 1;
        root = (root >> 1) - 1;
        int limit = (int) ((MAX - 1) >> 1);
        boolean[] isPrime = new boolean[limit];
        Arrays.fill(isPrime, true);
        for( int i = 0; i< root; i++){
            if(isPrime[i]){
                for(int j = ((i * (i + 3) << 1) + 3), p = (i << 1) + 3; j < limit; j += p){
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }
}

In the code:

if (index != 0){
    System.out.println(index);
 }else{
    System.out.println(-1);
}

Using a ternary reduces clutter and improves readibility:

System.out.println(index == 0 ? -1 : index);


Find Pythagorean Triple with Perimeter == 24 Learn You a Haskell gives this exercise:

  Here's a problem that combines tuples and list comprehensions: which
  right triangle that has integers for all sides and all sides equal to
  or smaller than 10 has a perimeter of 24? First, let's try generating
  all triangles with sides equal to or smaller than 10:

Here's my solution in Scala. Note that I'm ignoring the right triangle part.

val a = List.range(1,11)
val b = List.range(1,11)
val c = List.range(1,11)

def sumsEqualsTo24(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] =
                           if(x + y + z == 24) Some( (x,y,z) ) else None

def pythagTriple(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] = {
                             if( Math.pow(x, 2) + Math.pow(y, 2) == Math.pow(z, 2) )
                                  Some( (x,y,z) )
                             else None
}

Using flatMap

val xs: List[(Int, Int, Int)] = a.flatMap(x =>
                                 b.flatMap(y =>
                                  c.flatMap(z => sumsEqualsTo24(x, y, z) ) ) )

val ys: List[(Int, Int, Int)] = xs.flatMap{a => pythagTriple(a._1, a._2, a._3)}

Using for-comprehension

for {
  a <- List.range(1, 11)
  b <- List.range(1, 11)
  c <- List.range(1, 11)
  xs <- sumsEqualsTo24(a,b,c)
  _ <- pythagTriplebar(xs._1, xs._2, xs._3)
} yield (a,b,c)

Could you please critique my code?

There is no need for Lists a,b, and c, only one of them is needed.

So the flatmap could just use a three times:

a.flatMap(x =>
  a.flatMap(y =>
    a.flatMap(z => sumsEqualsTo24(x, y, z))))

For comprehensions can use extractors as you would in pattern matching or declaring a val.
You may find this more readable:

  ...
  c <- List.range(1, 11)
  (x,y,z) <- sumsEqualsTo24(a,b,c)
  _ <- pythagTriplebar(x,y,z)
} yield (a,b,c)

Likewise you can have

val ys = xs.flatMap{case (x,y,z) => pythagTriple(x,y,z)}


Merge two sorted lists in Rust I wrote the following code to merge two sorted lists. Is there a way I can improve it?

Possible ideas (not sure how to implement them):

Remove code duplication (setting the returning list node and moving to the next)
Avoid the use of the infinite loop
Avoid the use of panic!

This is the data structure:

type Link = Option<Box<Node>>;

pub struct Node {
    elem: i32,
    next: Link,
}

impl Node {
    fn new(elem: i32) -> Node {
        Node { elem, next: None }
    }
}

And this is the method:

fn merge_sorted_lists(list1: &Link, list2: &Link) -> Link {
    if list1.is_none() || list2.is_none() {
        return None;
    }
    let mut res = None;
    {
        let mut node3 = &mut res;
        let mut node1 = list1;
        let mut node2 = list2;
        loop {
            if let (Some(link1), Some(link2)) = (node1, node2) {
                if link1.elem > link2.elem {
                    *node3 = Some(Box::new(Node::new(link2.elem)));
                    node2 = &link2.next;
                } else {
                    *node3 = Some(Box::new(Node::new(link1.elem)));
                    node1 = &link1.next;
                }
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else if let Some(link1) = node1 {
                *node3 = Some(Box::new(Node::new(link1.elem)));
                node1 = &link1.next;
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else if let Some(link2) = node2 {
                *node3 = Some(Box::new(Node::new(link2.elem)));
                node1 = &link2.next;
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else {
                break;
            }
        }
    }
    res
}

One problem in your current code is that you allocate the merged list, that could be what the user want but that not very flexible, a better way would be to consume the list, and let the user do a copy before if needed.

One other problem is that you have spaghetti code, it's very difficult to maintain and error prone.

you should also use generic to allow an user to have any type in your linked list.

To solve these problem you could use recursion, the typical use case match yours, so I would simply rework all your code to use it:

type Link<T> = Option<Box<Node<T>>>;

#[derive(Debug, Clone)]
pub struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    // rework of new to make it more flexible
    fn new(elem: T, next: Link<T>) -> Self {
        Self { elem, next }
    }

    // next allow to change to linked node and to return the old one
    fn next(&mut self, next: Link<T>) -> Link<T> {
        std::mem::replace(&mut self.next, next)
    }

    fn elem(&self) -> &T {
        &self.elem
    }

    // now we take by value and allow user to have a flexible control with f
    fn merge_by<F>(a: Link<T>, b: Link<T>, accu: Link<T>, f: F) -> Link<T>
    where
        F: Fn(&T, &T) -> bool,
    {
        match (a, b) {
            (Some(mut a), Some(mut b)) => {
                if f(a.elem(), b.elem()) {
                    Self::merge_by(a.next(accu), Some(b), Some(a), f)
                } else {
                    Self::merge_by(Some(a), b.next(accu), Some(b), f)
                }
            }
            (Some(a), None) => Self::rev(accu, Some(a)),
            (None, Some(b)) => Self::rev(accu, Some(b)),
            (None, None) => Self::rev(accu, None),
        }
    }

    // rev is needed when you deal with list
    fn rev(list: Link<T>, accu: Link<T>) -> Link<T> {
        match list {
            Some(mut list) => Self::rev(list.next(accu), Some(list)),
            None => accu,
        }
    }

}

fn main() {
    let a = Some(Box::new(Node::new(21, Some(Box::new(Node::new(42, None))))));
    println!("{:#?}", a);

    let b = Some(Box::new(Node::new(1, Some(Box::new(Node::new(2, None))))));
    println!("{:#?}", b);

    let c = Node::merge_by(a, b, None, std::cmp::PartialEq::eq);
    println!("{:#?}", c);
}


Create a divisors list and identify primary numbers I tackled a beginners' exercise: "asks the user for a number and then prints out a list of all the divisors of that number."
The workflow I established is: input an integer number, say x; add a variable which value is x/2, say y; declare a divisors list.
If x is greater than 4 iterate between 2 and y+1; if the remainder is zero append it the the divisors list.
If divisors list is empty or if the input number is smaller than 4 return: this is a primary number.
else, return divisors list.
I ended up with the following solution. It does the job, but isn't good enough, as it has the following issues:
What is the python's input number limit? Currently, I have no limit which is wrong as it beyond the computational capacities of any computer.
I suspect my else statement isn't tidy enough. It can be shorter... but how?
If the number is lower than 4, the script returns twice the message "the number you entered is a primary number". I could fix it with an ad-hoc solution - but it should be solved through an algorithm not in a manual manner (...at least if I try to learn coding).
I ended up iterating in range of 2 and y+2 rather y+1 as I thought. I solved it manually but I don't understand why it isn't y+1.
num = int(input("Please select a number between: "))
y = num/2
if not y==0:
    y=int(y-0.5)

list_range = list(range(2,y+2))

divisors_list = []
if num < 4:
    print("The number you entered is a primary number")
else:
    for i in list_range:
        if num%i ==0:
            divisors_list.append(i)

if not divisors_list:
    print("The number you entered is a primary number")
else:
    print(divisors_list)

This program has 4 parts: (1) get raw user input; (2) validate the input and
convert it to its proper data type (int in this case), halting program if
invalid; (3) compute the divisors; and (4) report them to the user. However,
your current code has those things jumbled up. While collecting raw input you
try to convert it to int (which could fail) and then you turn to preparing
some variables needed to compute the divisors and then you do a little bit of
validation. Here's your code with virtually no changes other than reordering
the existing lines so we can see the conceptual boundaries better. It's very
easy to get confused when writing code, especially if the language is new to
you; a disciplined, orderly approach to keeping different things clearly
separated will help you reduce the confusion.
import sys

# Get user input.
num = input("Please select a number between: ")

# Convert and validate. Stop if invalid.
num = int(num)
if num < 4:
    print("The number you entered is a primary number")
    sys.exit()

# Compute divisors.
y = num/2
if not y==0:
    y=int(y-0.5)
list_range = list(range(2,y+2))
divisors_list = []
for i in list_range:
    if num%i ==0:
        divisors_list.append(i)

# Report.
if not divisors_list:
    print("The number you entered is a primary number")
else:
    print(divisors_list)

Regarding Python's number limit, don't worry about it. The only applicable
limit for a program like this is your patience. Just decide and
validate.
Perhaps there are different ways of defining a divisor, but my understanding is
that every integer N above 1 has at least two divisors -- namely [1, N].
If you were to embrace that idea, your code would simplify because there would
be no need for special handling for prime numbers. The code below starts
looking for divisors at 1; switch it to 2 to stay with your current approach.
When computing divisors, each time you find one, you usually get a second for
free. For example, if the input is 24, when you find 4 you also know that
6 is one too. Also, there's no need to check for divisors beyond the number's
square root.
Regarding your question about the list_range needing y + 1 or y + 2, I
suspect that's because Python ranges have a non-inclusive endpoint: for
example, range(1, 4) is analogous to a list of [1, 2, 3]. The divisor_rng
in the code below also has to use a +1.
Here's an illustration of those comments.
import sys
import math

# Some constants.
MIN = 1
MAX = 1000

# Get user input.
reply = input(f'Enter an integer in the range {MIN}-{MAX}: ')

# Convert and validate.
try:
    num = int(reply)
    if num not in range(MIN, MAX + 1):
        raise ValueError()
except ValueError:
    print(f'Invalid reply: {reply}')
    sys.exit()

# Compute divisors.
divisors = []
divisor_rng = range(1, int(math.sqrt(num)) + 1)
for d in divisor_rng:
    if num % d == 0:
        # Store divisor.
        divisors.append(d)
        # Store its mate, unless d is the square root.
        d2 = num // d
        if d2 != d:
            divisors.append(num // d)
divisors.sort()

# Prime check.
is_prime = num > 1 and divisors == [1, num]

# Report.
print(is_prime, divisors)


Construct a numpy array by repeating a 1 dimensional array sliced at different indices I have a pandas dataframe (called base_mortality) with 1 column and n rows, which is of the following form:
    age   |   death_prob
---------------------------
    60    |   0.005925
    61    |   0.006656
    62    |   0.007474
    63    |   0.008387
    64    |   0.009405
    65    |   0.010539
    66    |   0.0118
    67    |   0.013201
    68    |   0.014756
    69    |   0.016477

age is the index and death_prob is the probability that a person who is a given age will die in the next year. I want to use these death probabilities to project the expected annuity payment that would be paid to an annuitant over the next t years.
Suppose I have 3 annuitants, whose names and ages are contained in a dictionary:
policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}

Then I would want to construct a new dataframe whose index is time (rather than age) which has 3 columns (one for each annuitant) and t rows (one for each time step). Each column should specify the probability of death for each policy holder at that time step. For example:
         John      Mike      Alan
0    0.010539  0.013201  0.020486
1    0.011800  0.014756  0.022807
2    0.013201  0.016477  0.025365
3    0.014756  0.018382  0.028179
4    0.016477  0.020486  0.031269
..        ...       ...       ...
96   1.000000  1.000000  1.000000
97   1.000000  1.000000  1.000000
98   1.000000  1.000000  1.000000
99   1.000000  1.000000  1.000000
100  1.000000  1.000000  1.000000

At present, my code for doing this is as follows:
import pandas as pd

base_mortality = pd.read_csv('/Users/joshchapman/PycharmProjects/VectorisedAnnuityModel/venv/assumptions/base_mortality.csv', index_col=['x'])
policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}

out = pd.DataFrame(index=range(0,101))

for name, age in policy_holders.items():
    out[name] = base_mortality.loc[age:].reset_index()['age']
out = out.fillna(1)
print(out)

However, my aim is to remove this loop and achieve this using vector operations (i.e. pandas and/or numpy functions). Any suggestions on how I might improve my code to work in this way would be great!

Enter pandas.cut. It returns the bin in which each event lies. You can even pass the labels directly. This way you can reduce it to a Python loop over the people:
import pandas as pd
import numpy as np

age_bins = range(59, 70)   # one more than the probabilities
death_prob = [0.005925, 0.006656, 0.007474, 0.008387, 0.009405, 0.010539, 0.0118,
              0.013201, 0.014756, 0.016477]

policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}

values = {name: pd.cut(range(age, age + 101), age_bins, labels=death_prob)
          for name, age in policy_holders.items()}

out = pd.DataFrame(values, dtype=np.float64).fillna(1)
print(out)

#          John      Mike  Alan
# 0    0.010539  0.013201   1.0
# 1    0.011800  0.014756   1.0
# 2    0.013201  0.016477   1.0
# 3    0.014756  1.000000   1.0
# 4    0.016477  1.000000   1.0
# ..        ...       ...   ...
# 96   1.000000  1.000000   1.0
# 97   1.000000  1.000000   1.0
# 98   1.000000  1.000000   1.0
# 99   1.000000  1.000000   1.0
# 100  1.000000  1.000000   1.0
#
# [101 rows x 3 columns]

Note that the hin edges need to be one larger than the labels, because technically, this is interpreted as (59, 60], (60, 61], ..., i.e. including the right edge.


Recording user response times for a quiz I am working on a simple quiz-type game in which the user basically is asked a series of questions and needs to provide an answer.

I'm trying to find a solid/robust way of recording how long it takes for the user to answer each question. This is a web-based game so I am using JavaScript and PHP. I am very inexperienced, so I suspect this is not the best way to do it; at least I hope it's not because it seems very weak. I would appreciate any suggestions as to how to go about making a more full-proof solution. It's not critical that the time be accurate to the millisecond I'm just looking to build something that will be consistent and accurate to within a second or two.

The reason I'm doing it like this rather than just recording the time in the browser is because, as I understand it, the data could theoretically be altered by the user. This is also why I don't send that correct and answers to the browser until the user provides an answer.

Here is my current approach:

<?php
/* get_game_data.php
 *
 * user clicks button to start game
 * and triggers ajax request sent to this file
 */
session_start();

if($_SERVER['REQUEST_METHOD'] === 'GET')
{
    if(isset($_GET['gamesettings'])){///check certian user defined game options are set

        require 'classes/Database.php';

        date_default_timezone_set("UTC");

        $_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts
        $_SESSION['app_index'] = 0;

        if($_GET['app'] === 'aural') {

           $db = new Database();

           $gameData = getGameData($db);///just an example
           //etc...
           //query database for game data, i.e. the questions,
           echo json_encode($gameData['questions]);//then send back to browser

           $_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later

        }

    }
}
?>

<?php
/* post_game_data.php
 *
 * user answers question in a textbox etc.
 * then clicks a submit button which posts the answer to
 * this file via ajax again
 */
session_start();

function getTimeTaken($startDTO) {

    $endDTO     = new DateTime('NOW');
    $timeDiff   = $startDTO->diff($endDTO);
    $timeTaken  = $timeDiff->format('%s');

    return $timeTaken;
}

date_default_timezone_set("UTC");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if(
       isset($_POST['user_answer']) &&
       isset($_SESSION['app_index'])
    )
    {
        $index = $_SESSION['app_index'];///current question in the game
        $len = count($_SESSION['words']);///number of questions in the game
        $userAns = $_POST['user_answer'];
        $rightAns = $_SESSION['right_answers'];

        if(isset($_SESSION['app_start']))////if this is the first question
        {
            $responseTime = getTimeTaken($_SESSION['app_start']);
            unset($_SESSION['app_start']);
            $_SESSION['question_start'] = new DateTime('NOW');
        }
        else if(isset($_SESSION['question_start']))///not the first question
        {
            $responseTime = getTimeTaken($_SESSION['question_start']);
            $_SESSION['question_start'] = new DateTime('NOW');
        }

        if($index < $len)
        {
            $crtAns = $rightAns[$index];
            $mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer
            $_SESSION['app_index']++;
            echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time
        }

    }

}
?>

This works pretty much as I would like it to right now but I don't have a live server to test it on, only Apache local host.

Just some simple stuff,
a common.php file for common code used by both files. DRY don't repeat yourself.

Writing a script like you have is fine, the points i have noted will help you if you come back to maintain it in a year or so, and have forgotten how it works.

The bulk of programming jobs are about maintaining a code base, not creating new stuff, so if you can learn how to make maintenance easier, it will be beneficial for you in the long run. (I wish i had learnt this stuff much earlier on)

I have added inline comments explaining the changes i made

<?php
/* common.php */
require 'classes/Database.php';

session_start();
date_default_timezone_set("UTC");

?>

<?php
/* get_game_data.php
 *
 * user clicks button to start game
 * and triggers ajax request sent to this file
 */

require 'common.php';

// moved into common.php
// session_start();

if($_SERVER['REQUEST_METHOD'] === 'GET')
{
    if(isset($_GET['gamesettings'])){///check certian user defined game options are set

        // moved into common.php
//        require 'classes/Database.php';

        // moved into common.php
//        date_default_timezone_set("UTC");

        $_SESSION['app_start'] = new DateTime('NOW');////store time at which game/first question starts
        $_SESSION['app_index'] = 0;

        // warning if $_GET['app'] not set this will get a warning notice, we can never trust GET/POST data
        // if($_GET['app'] === 'aural') {
        if(isset($_GET['app']) && $_GET['app'] === 'aural') {

            $db = new Database();

            $gameData = getGameData($db);///just an example
            //etc...
            //query database for game data, i.e. the questions,

            // i prefer to do my internal logic before i output data. this way if something fails i can handle it prior to responding to the user
            $_SESSION['right_answers'] = $gameData['answers'];///store the right answers to varify against user answers later

            echo json_encode($gameData['questions']);//then send back to browser

        }

    }
}
?>

<?php
/* post_game_data.php
 *
 * user answers question in a textbox etc.
 * then clicks a submit button which posts the answer to
 * this file via ajax again
 */

require 'common.php';

// moved into common.php
//session_start();

// moved into common.php
// date_default_timezone_set("UTC");

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    // what you have done is not bad, i just prefer to have all user supplied data handled in one place, POST/GET
    // so i know that everything beyond here has been sanitized
//    if(
//       isset($_POST['user_answer']) &&
//       isset($_SESSION['app_index'])
//    )

    $userAns = isset($_POST['user_answer']) ? $_POST['user_answer'] : null;

    // good variable names can also help reduce the need for comments
    // which of these two following variable names are easier to understand

    // $index = $_SESSION['app_index'];///current question in the game
    $current_question_index = isset($_SESSION['app_index']) ? $_SESSION['app_index'] : null;

    if($userAns != null && $current_question_index != null)
    {

        // same here with variable naming
        // if you are going to maintain these scripts over time, you need to make it easier to remember what is going on

        // $len = count($_SESSION['words']);///number of questions in the game
        $num_questions = count($_SESSION['words']);

        // handled above, no need to repeat
        //      $userAns = $_POST['user_answer'];

        $rightAns = $_SESSION['right_answers'];

        // why use a comment here that could change over time when you can make an easily understandable function name instead
        // if(isset($_SESSION['app_start']))////if this is the first question
        if (is_first_question())
        {
            $responseTime = getTimeTaken($_SESSION['app_start']);
            unset($_SESSION['app_start']);

            // $_SESSION['question_start'] = new DateTime('NOW');
            start_question_timer();
        }
        // else if(isset($_SESSION['question_start']))///not the first question
        else if(is_question_started())///not the first question
        {
            $responseTime = getTimeTaken($_SESSION['question_start']);

           // $_SESSION['question_start'] = new DateTime('NOW');
            start_question_timer();
        }

        // which of these two is going to be easier to understand next year when you come back to maintain your script
        if ($current_question_index < $num_questions) {
    //    if($index < $len)
        {
            $crtAns = $rightAns[$current_question_index];

            // this is probably overkill in this case, but again why write a comment when you can write a nice function name
            // $mark = ($userAns == $crtAns)?1:0;///check user answer against correct answer
            $mark = mark_user_answer($userAns, $crtAns);

            // easy function names to make the code more understandable
            // $_SESSION['app_index']++;
            move_to_next_question();

            // given your if {} elseif {} statement above, $responseTime may not have been set, as there is no default case
            // this should be handled properly
            echo json_encode(array($crtAns, $mark, $responseTime));////send right answer to broswer with mark and response time
        }

    }

}

// move functions below main code as what is most important should come first
// perhaps this function could be called elapsedTimeInSeconds,
// get infers you are getting a value, and there is no indication what the return type might be
function getTimeTaken($startDTO) {

    // good variable naming, easy to understand what is happening
    $endDTO     = new DateTime('NOW');
    $timeDiff   = $startDTO->diff($endDTO);
    $timeTaken  = $timeDiff->format('%s');

    return $timeTaken;
}

function is_first_question() {
    return isset($_SESSION['app_start']);
}

function is_question_started() {
    return isset($_SESSION['question_start'];
}

//
function mark_user_answer($user_answer, $correct_answer) {
    return ($user_answer == $correct_answer) ? 1 : 0;
}

function move_to_next_question() {
    $_SESSION['app_index']++;
}

function start_question_timer() {
    $_SESSION['question_start'] = new DateTime('NOW');}
}

?>