texts:
This is a LeetCode.com problem.
https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/

  You are given an integer array nums and you have to return a new
  counts array. The counts array has the property where counts[i] is the
  number of smaller elements to the right of nums[i].

  Example:

  Given nums = [5, 2, 6, 1]

  To the right of 5 there are 2 smaller elements (2 and 1). To the right
  of 2 there is only 1 smaller element (1). To the right of 6 there is 1
  smaller element (1). To the right of 1 there is 0 smaller element.

  Return the array [2, 1, 1, 0].

Following is my solution which is accepted. But I noticed my run time is lot higher than many other submissions. I am curious to know if there is a better algorithm to this problem or is it something in the implementation that I can improve? How pythonic is my code? Do you see issues with any logic that could be done in a better way (both performance and code beauty wise)

Algorithm:
I start traversing the input list from the end. I take each element and insert it into a BST. While inserting I also track for each node in the BST, how many nodes are left of it (the size of left subtree) which denotes elements that are strictly smaller than current node. I also compute a position variable that starts at zero at root and gets incremented by X, each time a node is visited with value less than the given node where X is the count of its left subtree size plus one. If the number is equal, I only increment it by the node's left subtree count.

class bst_node(object):

    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.left_count = 0 # less than

# Name of this class is given by LeetCode, not my choice.
class Solution(object):

    def add_node(self, bst_pointer, new_node, position):
        if bst_pointer == None:
            return position, new_node
        if new_node.val < bst_pointer.val:
            bst_pointer.left_count += 1
            position, bst_pointer.left = self.add_node(bst_pointer.left, new_node, position)
        else:
            if new_node.val > bst_pointer.val:
                position += 1
            position += bst_pointer.left_count
            position, bst_pointer.right = self.add_node(bst_pointer.right, new_node, position)
        return position, bst_pointer

    # This method signature is also given by Leetcode.
    def countSmaller(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        res = []
        bst = None

        for n in nums[::-1]:
            smaller_after, bst = self.add_node(bst, bst_node(n), 0)
            res.append(smaller_after)

        return res[::-1]

# Few test cases ...
print(Solution().countSmaller([]))
print(Solution().countSmaller([5, 2, 6, 1]))


texts: Find all of the paths that lead to the minimum sum

texts:
"Find minimum path sum" in a 2D grid, is a very popular question which is solved by dynamic programming. But what if instead of the minimum sum value, we return all the actual paths that lead to the minimum sum path? This was an interview question which has been puzzling me.
The original problem is :
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Ex:
Input: grid =
[[1,3,1]
,[1,5,1]
,[4,2,1]]

output: 7
Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

But instead of 7 I want to return [1,3,1,1,1] and all other paths that lead to sum of sum (in this case there is only one path). My current solution has exponential time complexity which is not good. Does anyone has a good solution to this problem?
My current solution:
class Solution {
    void DFS(vector<vector<int>>& grid, vector<vector<int>>& dp, int r, int c, vector<int> path, vector<vector<int>>& result, int sum){
        int R = grid.size();
        int C = grid[0].size();

        path.push_back(grid[r][c]);
        sum += grid[r][c];

        if(r == R -1 && c == C -1){
            result.push_back(path);
            return;
        }

        int min_right = INT_MAX;
        if(c < C - 1) {
            min_right = dp[r][c + 1] + sum;
        }

        int min_down = INT_MAX;
        if(r < R - 1){
            min_down = dp[r + 1][c] + sum;
        }

        if(min_right < min_down){
            DFS(grid, dp, r, c + 1, path, result, sum);
        }
        else if(min_right > min_down){
            DFS(grid, dp, r + 1, c, path, result, sum);
        }
        else{
            DFS(grid, dp, r, c + 1, path, result, sum);
            DFS(grid, dp, r + 1, c, path, result, sum);
        }
    }

public:
    vector<vector<int>> minPathSum(vector<vector<int>>& grid) {
        if(grid.size() == 0){
            return 0;
        }

        int R = grid.size();
        int C = grid[0].size();

        vector<vector<int>> dp (R, vector<int>(C, 0));

        //O(m*n)
        for(int i = R - 1; i >= 0; i--){
            for(int j = C - 1; j >= 0; j--){
                int min_right = INT_MAX;
                if(j < C - 1){
                    min_right = dp[i][j + 1];
                }

                int min_down = INT_MAX;
                if(i < R - 1){
                    min_down = dp[i + 1][j];
                }

                int cur_min = min(min_down, min_right);

                if(cur_min == INT_MAX) {
                    cur_min = 0;
                }

                dp[i][j] = grid[i][j] + cur_min;

            }
        }

        vector<vector<int>> result;
        vector<int> path;
        int sum;
        //O(2^(m+n))
        DFS(grid, dp, 0, 0, path, result, sum);

        return result;
    }
};


texts:
I'm writing a function that returns all (nested) sequences reversed:

(defn my-reverse-v1 [input]
  (let [head (first input)
        tail (rest input)]
    (if head
      (conj (my-reverse-v1 (vec tail))
            (if (sequential? head)
              (my-reverse-v1 (vec head))
              head))
      [])))

(defn my-reverse-v2 [initial input]
  (let [head (first input)
        tail (rest input)]
    (if head
      (recur (cons (if (sequential? head) (my-reverse-v2 [] head) head) initial) tail)
      (vec initial))))

(defn test-my-reverse []
  (let [input [[1 2] 3 [4 [5 6]] 7 [8 [9 [10 11] 12]]]
        expected [[[12 [11 10] 9] 8] 7 [[6 5] 4] 3 [2 1]]]
    (println "my-reverse-v1:" (= expected (my-reverse-v1 input)))
    (println "my-reverse-v2:" (= expected (my-reverse-v2 [] input)))))

my-reverse-v2 is the tail-recursive version, whereas my-reverse-v1 isn't. These two functions work as expected, but I think there will be lots more succinct or Clojure-ish implementations for the requirements.


texts: Model-View-Controller-Service shared flat expenses interface

texts:
I'm new to php and OOP, and for learning I started writing an application that would help me and my flatmates to manage our expenses and debts to one another.

The full source is available at https://bitbucket.org/nicocool84/coloc-web/src. I tried to use the MVC(S) architecture without using a framework.

The project tree is as follows:

.
├── controllers
│   ├── DebtController.php
│   ├── DefaultController.php
│   └── UserController.php
├── models
│   ├── DebtList.php
│   ├── Debt.php
│   └── User.php
├── services
│   ├── Database.php
│   ├── DebtService.php
│   ├── RedirectService.php
│   └── UserService.php
├── views
│   ├── footer.php
│   ├── header_logged.php
│   ├── header_unlogged.php
│   ├── home_unlogged.php
│   ├── html_header.php
│   ├── jumbotron.php
│   └── list_debts.php
└── web
    ├── index.php
    └── .htaccess

.htaccess redirects all requests to index.php which decides which controller and which action to call based on the URI: http://mysite.my/controller/action.

To handle sessions, when a user is authenticated, I store a User instance with his details in $_SESSION. The related methods are stored in UserService, for instance getCurrentName. Is this a good practice? Should I create a SessionService? Should I do this completely differently?

Is creating a DebtList class to compute who owes what making any sense?

I know the HTML/CSS part is quite ugly, and I'm open to advice there too.

Thanks to anyone who will take the time to review it all.


texts: Find Euler totient of a large range of numbers

texts:
(Euler Totient Function)

Is there any way to make it faster/better in asymptotic complexity?

int phi (int n)
{
    if (memo[n]!=-1) return memo[n];
    int ans=n, k=n;
    for (int p=2; p*p<=n; p++)
    {
        if (n%p==0)
        {
            while (n%p==0) n/=p;
            ans-=ans/p;
        }
    }
    if (n>1) ans-=ans/n;
    memo[k]=ans;
    return ans;
}


texts: Calculating golf score against course par

texts:
This PHP script will translate shots on 18 holes to a total under par or E which is 0.

$course = array(0, 4, 5, 4, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 4, 5);

if ($totalpar == 0) {
    $score = 'E';
    $played = 0;
} else {
if(!empty($h1)) {
 $h1score = $course[1] - $h1;
} else {
 $h1score = 0;
 }
if (!empty($h2)) {
 $h2score = $course[2]- $h2;
} else {
 $h2score = 0;
 }
if (!empty($h3)) {
 $h3score = $course[3] - $h3;
} else {
 $h3score = 0;
 }
if (!empty($h4)) {
 $h4score = $course[4] - $h4;
} else {
 $h4score = 0;
 }
if (!empty($h5)) {
 $h5score = $course[5] - $h5;
} else {
 $h5score = 0;
 }
if (!empty($h6)) {
 $h6score = $course[6] - $h6;
} else {
 $h6score = 0;
 }
if (!empty($h7)) {
 $h7score = $course[7] - $h7;
} else {
 $h7score = 0;
 }
if (!empty($h8)) {
 $h8score = $course[8] - $h8;
} else {
 $h8score = 0;
 }
if (!empty($h9)) {
 $h9score = $course[9] - $h9;
} else {
 $h9score = 0;
 }
if (!empty($h10)) {
 $h10score = $course[10] - $h10;
} else {
 $h10score = 0;
 }
if (!empty($h11)) {
 $h11score = $course[11] - $h11;
} else {
 $h11score = 0;
 }
if (!empty($h12)) {
 $h12score = $course[12] - $h12;
} else {
 $h12score = 0;
 }
if(!empty($h13)) {
 $h13score = $course[13] - $h13;
} else {
 $h13score = 0;
 }
if(!empty($h14)) {
 $h14score = $course[14] - $h14;
} else {
 $h14score = 0;
 }
if (!empty($h15)) {
 $h15score = $course[15] - $h15;
} else {
 $h15score = 0;
 }
 if(!empty($h16)) {
 $h16score = $course[16] - $h16;
}else {
 $h16score = 0;
 }
if(!empty($h17)) {
 $h17score = $course[17] - $h17;
}else {
 $h17score = 0;
 }

if(!empty($h18)) {
 $h18score = $course[18] - $h18;
}else {
 $h18score = 0;
 }
}

$scoresum = ($h1score + $h2score + $h3score + $h4score + $h5score + $h6score + $h7score + $h8score + $h9score + $h10score + $h11score + $h12score + $h13score + $h14score + $h15score + $h16score + $h17score + $h18score) * -1;

if ($scoresum != 0) {
    $score = $scoresum;
}
else {
    $score = 'E';
}


texts: Google Foobar Challenge: Spy Snippets in Python

texts:
I am getting all the answers correct. But still the solution is not accepted as only 4/5 tests cases are passed.

I have not posted the whole problem statement but the problem is similar to this.

I want to know if there are any more optimizations possible.

import sys

class Queue(object):
    input_array = []

    def __init__(self, input_array=None):
        if not input_array:
            self.input_array = []
        else:
            self.input_array = input_array

    def enqueue(self, element):
        self.input_array.append(element)

    def dequeue(self):
        return self.input_array.pop(0)

    def first(self):
        return self.input_array[0]

    def last(self):
        return self.input_array[-1]

    def size(self):
        return len(self.input_array)

    def get_queue(self):
        return self.input_array

    def get_queue_after_first(self):
        return self.input_array[1:]

    def __str__(self):
        return "Current Queue: {0}".format(self.input_array)

def answer(document, searchTerms):
    no_of_search_terms = 0
    count = dict()
    for searchTerm in searchTerms:
        if searchTerm in count:
            count[searchTerm] += 1
        else:
            no_of_search_terms += 1
            count.update({searchTerm: 1})

    q = Queue()
    len_q = Queue()
    smallest_snippet_size = sys.maxint
    offsets = tuple()
    tokens = document.split()

    for position, token in enumerate(tokens, start=1):
        if count.get(token, 0):
            q.enqueue(token)
            len_q.enqueue(position)
            while q.first() in q.get_queue_after_first():
                q.dequeue()
                len_q.dequeue()
            current_block_len = len_q.last() - len_q.first() + 1
            if (q.size() >= no_of_search_terms) and (current_block_len < smallest_snippet_size):
                smallest_snippet_size = current_block_len
                offsets = (len_q.first() - 1, len_q.last())

    return " ".join(tokens[offsets[0]: offsets[1]])

if __name__ == '__main__':
    assert (answer("world there hello hello where world", ["hello", "world"]) == 'world there hello')
    assert (answer("many google employees can program", ["google", "program"]) == 'google employees can program')
    assert (answer("some tesla cars can autopilot", ["tesla", "autopilot"]) == 'tesla cars can autopilot')
    assert (answer("a b c d a", ["c", "d", "a"]) == 'c d a')
    assert (answer("the cats run very fast in the rain", ["cats", "run", "rain"]) == 'cats run very fast in the rain')
    assert (answer("the cats run very fast in the rain run cats", ["cats", "run", "rain"]) == 'rain run cats')
    assert (answer("hello", ["hello"]) == 'hello')


texts:
(Method signature is given with parameters)

Try to visualize me writing this code at an interview, and please be brutal while judging it.

  Problem:

  Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.  Return all such possible sentences.

  For example, given

s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"]

  A solution is

["cats and dog", "cat sand dog"]

Time complexity: I don't know how to analyze it, \$O(n)\$, since I visit each char of the string for sure, but since I am backtracking, I visit it again constant time.  I don't know, so please explain

Space Complexity: \$O(n)\$

public ArrayList<String> wordBreak(String s, Set<String> dict) {
    ArrayList<String> sentences = new ArrayList<String>();
    wordBreakHelper(s, dict, 0, new StringBuilder(), sentences);
    return sentences;
}
private static void wordBreakHelper(String givenSentence, Set<String> dictionary, int index, StringBuilder path, ArrayList<String> results){
    if(givenSentence.length() == 0){
        results.add(path.toString());
    }
    if(index > givenSentence.length()){
        return;
    }
    for(int i = index; i < givenSentence.length(); i++){
        boolean isSpace = false;
        if(dictionary.contains(givenSentence.substring(0, i+1))){
            if(i+1 == givenSentence.length()){
                path.append(givenSentence.substring(0, i+1));
            }else{
                path.append(givenSentence.substring(0, i+1) +" ");
                isSpace = true;
            }
            wordBreakHelper(givenSentence.substring(i+1), dictionary, 0, path, results);
            if(isSpace == true){
                path.replace(path.length() - givenSentence.substring(0, i+2).length() , path.length(), "");
            }else{
                path.replace(path.length() - givenSentence.substring(0, i+1).length() , path.length(), "");
            }
        }
    }
}


texts:
In keeping with using FizzBuzz as an introduction to a language, I present FizzBuzz with a Fortran95 twist:

For multiples of 3, print Fort, and for 5's multiples print Ran. For multiples of both, print FortRan.

Looking especially for style and common practice criticisms. A hint on how to left-justify the values in a standard way would be appreciated too.

The following code is presented in Ideone too:

program fizzbuzz
implicit none
integer ::i

! Loop through integers 1 through 100
! Multiples of 3 print Fort
! Multiples of 5 print Ran
! Multiples of both print FortRan
! 15 is the lowest common multiple of 3, and 5
!    and thus is a shortcut to FortRan

do i=1,100
    if (MODULO(i, 15) == 0) then
        write (*,'(A8)') 'FortRan'
    else if (MODULO(i, 3) == 0) then
        write (*,'(A8)') 'Fort'
    else if (MODULO(i, 5) == 0) then
        write (*,'(A8)') 'Ran'
    else
        write (*,'(I8)') i
    end if
end do

end program fizzbuzz


texts:
I have implemented Zeller's algorithm in Python to calculate the day of the week for some given date. I would like to get some feedback on how I can make the code shorter and more elegant:

def input_value(input_name, prompt, min_num, max_num):
    while True:
        data = raw_input(prompt)
        if data:
            try:
                input_name = int(data)
            except ValueError:
                print 'Invalid input...'
            else:
                if input_name >= min_num and input_name <= max_num:
                    return input_name
                    break
                input_name = 'Please try again: '
        else:
            print 'Goodbye!'
            break

month = 0
day = 0
year = 0
century = 0

month = input_value(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ", 1, 12)
day = input_value(day, "Please enter the day (from 1-31): ", 1, 31)
year = input_value(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ", 0, 99)
century = input_value(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ", 0, 99)

A = month
B = day
C = year
D = century

W = (13*A - 1) / 5
X = C / 4
Y = D / 4
Z = W + X + Y + B + C - 2*D
R = Z % 7

birthday = "You were born on " + str(B) + "/" + str(A+2) + "/" + str(D) + str(C) + " which was a "

if R == 0:
    print birthday + 'Sunday'
elif R == 1:
    print birthday + 'Monday'
elif R == 2:
    print birthday + 'Tuesday'
elif R == 3:
    print birthday + 'Wednesday'
elif R == 4:
    print birthday + 'Thursday'
elif R == 5:
    print birthday + 'Friday'
elif R == 6:
    print birthday + 'Saturday'

Thanks in advance for taking the time to look at this.


texts: Retrieve unique child objects from an array

texts:
I'm using TypeScript but this example is in plain JavaScript. I have a class rank with a child-class master. I need an ordered collection of unique masters. Here's what I have but it seems a little "kak":

function getMasters() {
    var gms = [];
    _.each(this.ranks, (r) => {
        if (gms[r.master.id])
            return;
        gms[r.master.id] = new ExtendedRank(r.master.id r.master.code, r.master.name);
    });

    return _.without(gms, undefined).sort(this.sort);
}

This is the sort function (which I'm relatively happy with):

function sort(l: ExtendedRank, r: ExtendedRank) {
    return l.sortString.localeCompare(r.sortString);
}


texts:
I want this to be similar to the STL algorithms but I don't find it elegant nor concise at all:

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

using E = double;
template <typename IT>
E std_dev(IT begin, IT end){
    auto N = std::distance(begin, end);
    E average = std::accumulate(begin, end, E()) / N;
    auto sum_term = [average](E init, E value)-> E{
        return init + (value - average)*(value - average);
    };
    E variance = std::accumulate(begin,  end, E(), sum_term);
    return std::sqrt(variance * 1.0 / (N - 1));
}

int main(){
    std::vector<double> stuff {3.5, 3.4, 3.6, 3.9, 3.5, 3.5, 3.5, 3.5, 3.5};
    std::cout << std_dev(stuff.begin(), stuff.end()) << "\n";
}


texts: Retrieving lists of consecutive capitalised words from a list

texts:
Ok, so given the string:

s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School"

I want to retrieve:

[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...]

Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was:

def retrieve(tokens):
    results = []
    i = 0
    while i < len(tokens):
        if tokens[i][0].isupper():
            group = [tokens[i]]
            j = i + 1
            while i + j < len(tokens):
                if tokens[i + j][0].isupper():
                    group.append(tokens[i + j])
                    j += 1
                else:
                    break
        i += 1
    return results

This is actually quite fast (well compared to some of my trying-to-be-pythonic attempts):

  Timeit: 0.0160551071167 (1000 cycles)

Playing around with it, the quickest I can get is:

def retrive(tokens):
    results = []
    group = []
    for i in xrange(len(tokens)):
        if tokens[i][0].isupper():
            group.append(tokens[i])
        else:
            results.append(group)
            group = []
    results.append(group)
    return filter(None, results)

  Timeit 0.0116229057312

Are there any more concise, pythonic ways to go about this (with similar execution times)?


texts:
I am struggling with commenting and variable naming. My teacher says my comments need to be more explanatory and explicit. He says my variable names are also sometimes confusing. I was just wondering whether you could go through my code and see whether you are able to understand the comments and add in comments/edit where you feel I should add comments or improve them. Lastly, are there any general rules to follow with commenting?

class PPM(object):
    def __init__(self, infile, outfile):
        self.infile=infile
        self.outfile=outfile

        #Read in data of image
        data= open(self.infile,"r")
        datain=data.read()
        splits=datain.split(None, 4)

        #Header info and pixel info
        self.type=splits[0]
        self.columns=int(splits[1])
        self.rows=int(splits[2])
        self.colour=int(splits[3])

        #(Return a new array of bytes)
        self.pixels=bytearray(splits[4])

    def grey_scale(self):
            for row in range(self.rows):
                for column in range(self.columns):
                    start = row * self.columns * 3 + column * 3
                    end = start + 3
                    r, g, b = self.pixels[start:end]
                    brightness = int(round( (r + g + b) / 3.0 ))
                    self.pixels[start:end] = brightness, brightness, brightness

    def writetofile(self):
        dataout= open(self.outfile, "wb")
        #Use format to convert back to strings to concatenate them and Those {} in the write function get's replaced by the arguments of the format function.
        dataout.write('{}\n{} {}\n{}\n{}'.format(self.type,
                                                 self.columns, self.rows,
                                                 self.colour,
                                                 self.pixels))

sample = PPM("cake.ppm", "Replica.ppm")
sample.grey_scale()
sample.writetofile()


texts: Controller method to do fuzzy search for companies

texts:
I would like some help to clean up this action, especially from @companies and downward. The comments should be enough to explain :)

def search
  @query = params[:query]
  unless @query.blank?
    @query.strip!
    #Get tags with fuzzy match
    tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)

    #Get vouchers with these tags
    @vouchers = Voucher.tagged_with(tags, :any => true)

    #Get companies with these tags, and add their vouchers to the list
    @companies = Company.tagged_with(tags, :any => true)
    @companies.each do |company|
      #Because can't merge with nil. Can this be re-written?
      if @vouchers.empty?
        @vouchers = company.vouchers
      else
        @vouchers.merge(company.vouchers)
      end
    end

    #Get every voucher's category. Can this be re-written?
    @categories = []
    @vouchers.each do |voucher|
      @categories << voucher.categories
    end
    #Because can't call .flatten on nil
    if @categories.any?
      #Need to flatten because the array will contain an arrays of categories [[],[],[]]
      @categories.flatten!.uniq # I don't really want .flatten.uniq in the view, or?
    end
  end
end


texts: Script to group files by extension and unzip archives

texts:
I am writing a shell script to sort my files by extension and unzip archives. It works in simple cases, but I haven't tested it extensively. How can I make it more robust against the set of file names that may be present?

#!/bin/bash
#File sorter
SECONDS=0
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
echo "trigger took place in $(pwd)"
for i in $( ls -1); do
  echo "processing $i ..."
  fileext=${i##*.}
  case ${i##*.} in
    zip)
      mkdir archive
      mkdir $(pwd)/archive/${i%%.*}
      unzip $i -d $(pwd)/archive/${i%%.*}
      ;;
    *) echo "nonzip"
      mkdir ${i##*.}
      mv $i $(pwd)/${i##*.}
      ;;
  esac
done
echo "Done in $SECONDS seconds!"


texts:
The following code is used to find the usual_gp(General Practitioner) from gpCollection variable of type TreeMap<Long(Date), SummableMap<String(GPId), Integer(GPCount)>> and store result (usual GP) along with date on usualGPCollection Map.

Does this code follow common best practices? Logic implemented on below code is

        Long startDate = gpCollection.firstKey();
        Long endDate = gpCollection.lastKey();

        TreeMap<Long, String> usualGPCollection = new TreeMap<Long, String>();

        for (Long i = startDate; i <= new DateTime(endDate).plusYears(1).getMillis(); i = i + new DateTime(i).plusMonths(1).getMillis()) {

            Long beforeOneYearDate = new DateTime(i).minusMonths(12).getMillis();
            Long beforeSixMonthDate = new DateTime(i).minusMonths(6).getMillis();
            Long beforeThreeMonthDate = new DateTime(i).minusMonths(3).getMillis();

            List<String> returnGPCollection = customSubMap(gpCollection, beforeOneYearDate, i);

            if(returnGPCollection.size() == 1) {

                usualGPCollection.put(i, returnGPCollection.get(0));

            } else if(returnGPCollection.size()>1){

                returnGPCollection = customSubMap(gpCollection, beforeSixMonthDate, i);

                if(returnGPCollection.size() == 1) {

                    usualGPCollection.put(i, returnGPCollection.get(0));

                }else  if(returnGPCollection.size()>1){

                    returnGPCollection = customSubMap(gpCollection, beforeThreeMonthDate, i);

                    if(returnGPCollection.size() == 1) {

                        usualGPCollection.put(i, returnGPCollection.get(0));

                    } else if(returnGPCollection.size()>1){

//                        returnGPCollection = customSubMap(gpCollection, i);//todo

                    }
                }

                returnGPCollection = customSubMap(gpCollection, beforeOneYearDate, i);
            }
    }

// customSubMap() Function is used to find max count GP on given date range.

private List<String> customSubMap(TreeMap<Long, SummableMap<String, Integer>>  gpCollectionMap, Long fromDate, Long toDate) {
        List<String> returnMap = null;

        SortedMap<Long, SummableMap<String, Integer>> temp = gpCollectionMap.subMap(fromDate, toDate);
        Collection values = temp.values();
        Iterator<SummableMap<String, Integer>> test = values.iterator();

        SummableMap<String, Integer> resultMap = new SummableMap<String, Integer>();
        TreeMap<Integer, List<String>> reverseTree = new TreeMap<Integer, List<String>>();

        while (test.hasNext()) {
            resultMap.putAll(test.next());
//            String  key = test.next().clone();
        }

        List mapValues = new ArrayList(resultMap.values());
        Collections.sort(mapValues);

        NavigableMap<String, Integer> resultMapUpdated = sortHashMapByValuesD(resultMap);

        String firstKey = resultMapUpdated.firstKey();
        String secondKey = resultMapUpdated.lowerKey(firstKey);

        Integer firstValue = resultMapUpdated.get(firstKey);
        Integer secondValue = resultMapUpdated.get(secondKey);

        if(firstValue == secondValue){
            returnMap.add(firstKey);
            returnMap.add(secondKey);
        }else {
            returnMap.add(firstKey);
        }

        return returnMap;
    }

    private List<String> customSubMap(TreeMap<Long, SummableMap<String, Integer>>  gpCollectionMap, Long toDate) {

        List<String> returnMap = null;
        Long beforeThreeMonthDate = new DateTime(toDate).minusMonths(3).getMillis();

        SortedMap<Long, SummableMap<String, Integer>> temp = gpCollectionMap.subMap(beforeThreeMonthDate, toDate);
        String latestGP = temp.get(temp.lastKey()).keySet().iterator().next();

        returnMap.add(latestGP);

        return returnMap;
    }


texts: Determine if Class B uses Class A ( Java Reflection)

texts:
Below is a function that determines if Class B uses Class A.

Currently, it tests for:

Fields
Superclass
Constructors
Methods

private boolean uses(Class<?> b, Class<?> a){
    // Test for Declared field
    for(Field f:b.getDeclaredFields()){
        if(f.getGenericType().equals(a))
            return true;
    }
    // Test for Inherietence
    if(b.getSuperclass().getName().equals(a.getName()))
        return true;

    // Test for constructors
    for(Constructor<?> c: b.getDeclaredConstructors()){
        for(Class<?> p : c.getParameterTypes())
            if(p.getName().equals(a.getName()))
                return true;
    }
    // Test for methods
    for(Method m:b.getDeclaredMethods()){
        for(Class<?> p:m.getParameterTypes())
            if(p.getName().equals(a.getName()))
                return true;
    }

    return false;
}

Is there a better way to write this function?

Is the name of the function terrible?

Are there any bugs in the code?

Is my test holistic, that is, did I test for everything?


texts:
I wrote a rock, paper, scissors program. It works fine, but I'm curious if there are any constructive critiques, tips, tricks, comments, or advice anyone may have on how the code operates, performs, looks, etc.

# This code is a PvC Rock-Paper-Scissors Game!
# Import Random Library for Computer Choice
import random

# Greeting & Introduction
print ("Hello! Let's play Rock-Paper-Scissors!");

# Just to Make things Smoother.
options = {1:'rock', 2:'paper', 3:'scissors'};
player_result = ["tie!", "win!", "lose!"];

# Obtain Player & CPU Inputs
def collection(user_choice = 42):
    # user_choice Collection
    while (user_choice not in ['1','2','3']):
        # Prompts the User for a number & Stores as raw_input
        print ("Pick a Number: \n 1) \t Rock \n 2) \t Scissors \n 3) \t Paper \n");
        user_choice = raw_input();
        # Checks to see if the choice is acceptable
        if (user_choice in ['1','2','3']):
            break;
        # If not acceptable, restart the loop (ask again).
        else:
            print("\nPlease pick either 1, 2, or 3!\n");

    # Convert user_choice to Int
    user_choice = int(user_choice);

    # choose comp_choice
    comp_choice = random.randint(1,3);
    return (user_choice, comp_choice);

# Translate Results into English
def translate_choices(user,comp):
    print ("\nYou chose " + options[user] +"!");
    print ("Computer chose " + options[comp] +"!");

# Comparison Function returns Game Results
def compare(x,y):
    result = player_result[ (x-y)%3 ];
    return result;

(user_choice,comp_choice) = collection();
translate_choices(user_choice,comp_choice);
result = compare (user_choice, comp_choice);
print ("You " + result);


texts:
I am starting to write a plugin that is aiming to validate a piece of mark up against requirements of schema.org.

I was hoping if I could get some more tips on how to improve the structure of my code. Is this how you would go about this if you were to do it?

    $.fn.hasAttr = function(name) {
       return this.attr(name) !== undefined;
    };

    $.fn.outerHTML = function(s) {
        return $(this).clone().wrap('
').parent().html();
    };

    $.fn.getOpeningTag = function (s) {
      return $(this).outerHTML().slice(0, $(this).outerHTML().indexOf(">") + 1)
    }

    $.fn.validateSchema = function(options) {

      var defaults = {
        // for a list of international postcode regex see: http://www.thalesjacobi.com/Regex_to_validate_postcodes
        // The one used in the example is from the UK
        localPostCodeFormat: new RegExp("^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$"),
        utilities : {
            missAtrr : function (target, attrName) {
              if (!target.hasAttr(attrName)){
                 defaults.returnError(target, "The element " + target.getOpeningTag()  + " is missing the required attribute " + attrName);
              }
            },
            isValidPostCode : function (target) {
              if (!defaults.localPostCodeFormat.test(target.text())) {
                defaults.returnError(target, target.getOpeningTag() + " does not have a valid post code");
              }

            }
        },
        returnError : function (target, errorMessage) {
          var errorContainer = $('');
          target.before(errorContainer);
          errorContainer.css({
            'color' : 'red',
            'border': 'solid 1px red'
            }).text(errorMessage);
        } // more utils to be added
      };
      // Extend our default options with those provided.
      var opts = $.extend(defaults, options);

      var schemaElements = {
            postalAddress : $(this).find('[itemtype*=PostalAddress]'),
            itemProps : $(this).find("[itemprop]"),
            emptyProps : $(this).find("[itemprop='']"),
            postCode : $(this).find("[itemprop=postalCode]"),
            email : $(this).find("[itemprop=email]"),
            outofplaceChild : $(this).find("[itemscope]").siblings("[itemprop]")// more dom refs to be added
        }

      // validation stuff
      //
      // PostalAddress should have itemsscope
      if (schemaElements.postalAddress){
        defaults.utilities.missAtrr(schemaElements.postalAddress, "itemscope");
      }
      // No itemscope can be left empty
      if (schemaElements.emptyProps){
        $.each(schemaElements.emptyProps, function () {
            defaults.returnError($(this), $(this).getOpeningTag() + " can not be left without a value");
        });
      }
      // postcode should match the post code format of that country
      if (schemaElements.postCode){
        defaults.utilities.isValidPostCode(schemaElements.postCode);
      }
      // No itemprop can exist without having a itemscope parent
      if (schemaElements.outofplaceChild){
        $.each(schemaElements.outofplaceChild, function () {
            defaults.returnError($(this), $(this).getOpeningTag() + " Does not have a itemscope parent");
        });
      }
      // more rules to be added
    };

    $(function(){
        $('body').validateSchema();
    });


texts:
I wrote this class a while ago to learn Kotlin and heaps, so any tips (on either my code style or my heap algorithm) would be appreciated!

class MaxHeap<T : Comparable<T>>() {
    private val items: MutableList<T?> = mutableListOf()
    var size: Int = 0
        private set

    fun push(item: T) {
        set(size++, item)
        siftUp(size - 1)
    }

    fun peek() = get(0)

    fun pop(): T? {
        // If there are no items in the heap, null is returned
        if (size == 0) {
            return null
        }

        // Get the max item, replace it with the last item in the heap,
        // then sift it down until the heap property is restored
        val max = peek()
        set(0, get(--size))
        items.removeAt(size) // Remove original reference to the last item
        siftDown(0)
        return max
    }

    private fun siftUp(i: Int) {
        assert(i >= 0 && i < size)

        // The root node has no parent, so we cannot sift up any more
        if (i == 0) {
            return
        }

        // If the current item is larger than the parent, swap them and
        // then repeat on the item, which is now in the parent position
        val iParent = parentIndex(i)
        if (get(i)!! > get(iParent)!!) {
            swap(i, iParent)
            siftUp(iParent)
        }
    }

    private fun siftDown(i: Int) {
        assert(i >= 0 && i < size)

        // Cannot sift down leaf nodes
        if (i >= size / 2) {
            return
        }

        // Find the larger child value.
        // Left child is guaranteed to exist because this is not a leaf node,
        // and because we add items to the heap by appending them to the end,
        // the left mode must be filled before the right node.
        val iLeft = leftChildIndex(i)
        val iRight = rightChildIndex(i)
        var iLargerChild = iLeft
        if (iRight < size && get(iLeft)!! < get(iRight)!!) {
            iLargerChild = iRight
        }

        // If this item is less than the larger child, sift it down
        if (get(i)!! < get(iLargerChild)!!) {
            swap(i, iLargerChild)
            siftDown(iLargerChild)
        }
    }

    private fun set(i: Int, value: T?) {
        if (i < items.size) {
            items[i] = value
        } else {
            items.add(value)
        }
    }

    private fun get(i: Int): T? {
        if (i < items.size) {
            return items[i]
        } else {
            return null
        }
    }

    private fun swap(i: Int, j: Int) {
        val temp = items[i]
        items[i] = items[j]
        items[j] = temp
    }

    private fun parentIndex(i: Int) = (i - 1) / 2
    private fun leftChildIndex(i: Int) = i * 2 + 1
    private fun rightChildIndex(i: Int) = i * 2 + 2
}


texts: Why is my Sieve of Eratosthenes using generators so slow

texts:
This is my prime sieve based on the Sieve of Eratosthenes.
import itertools
sieve = itertools.count(2)
primes = []
nprime = 0
for _ in range(10000):
    nprime = next(sieve)
    primes.append(nprime)
    sieve = filter(eval(f"lambda x: x % {nprime} != 0"), sieve)

On my computer this code takes 13.4 seconds to generate 10,000 primes.


texts: Making a grid for collision detection in a game that wraps

texts:
I'm making a 2D game which wraps (when you move off the right edge, you appear on the left, etc). The game area is square, all objects are circles (with AABB smaller than the game area, and in most cases, much smaller).

I'm dividing the game area into a grid to perform collision checks. I need to determine which cell(s) an object's AABB lives in.

Right now I have this awkward code to deal with cases when the object passes the left/right boundary... I feel like there must be a better way to write it.

gridX is x-dimension of the grid
x1 is the x-coord of the cell the object's left boundary lives in (before taking into account wrap)
x2 " " right boundary

if (x1 < 0) {
  for (let j = x1 + gridX; j < gridX; j++) someFunction(j)
  for (let j = 0; j < x2; j++) someFunction(j)
} else if (x2 >= gridX) {
  for (let j = x1; j < gridX; j++) someFunction(j)
  for (let j = 0; j < x2 - gridX; j++) someFunction(j)
} else {
  for (let j = x1; j <= x2; j++) someFunction(j)
}

someFunction would then contain the y coord version of the above and add to the grid.

Bear in mind I don't want to lose performance (as it will be run multiple times per second).

I want to write out someFunction instead of actually declaring a function so I hope there is a better way to do this - especially if I wanted to make my game 3 dimensional in future. That would be 25 pastes.


texts:
I decided to write a small script to make writing HTML interactive stories less tedious:

import doctest
import re
import sys

import tkinter
import tkinter.filedialog

HTML_START = """<!DOCTYPE html>

    <title>{}</title>

{}

     """

HTML_END = """

"""

SEPARATOR = '\n---\n\n'

def link_to_self(word):
    """
    Generates an html link to the given word.

    >>> link_to_self("spam")
    'spam'
    """
    return '{}'.format(word.capitalize(),word)

def inside_square_brackets(text):
    """
    Returns all the text inside square brackets.

    >>> inside_square_brackets('Some nice [brackets]')
    ['[brackets]']
    """
    return re.findall('\[.*?\]',text)

def insert_links(text):
    """
    Insert links from square brackets.

    >>> insert_links("A [cake]?")
    'A cake?'
    """
    for link in inside_square_brackets(text):
        text = text.replace(link,link_to_self(link.replace('[','').replace(']','')))
    return text

def html_page(title,page):
    """
    Generates an html page with title and text.
    """
    return HTML_START.format(title.capitalize(),title.capitalize()) + insert_links(page) + HTML_END

def create_html_file(filename,text):
    with open(filename+'.html','w+') as f:
        f.write(html_page(filename,text))

def gen_interactive_story(titles_and_texts):
    for title,text in titles_and_texts:
        create_html_file(title,text)

def parse_stories_and_titles(text):
    """
    Spits out tuples (title,text) from a text containg paragraphs
    separated by the SEPARATOR.
    """
    chunks = text.split(SEPARATOR)
    lines_from_chunks = [chunk.splitlines() for chunk in chunks]
    return [(line[0].capitalize(),''.join(line[1:]))
                for line in lines_from_chunks]

def find_txt_file(lst):
    """
    Returns the first '.txt' file in a list.

    >>> find_txt_file(['a.txt','b.foo','c.py'])
    'a.txt'
    """
    txts = [i for i in lst if '.txt' in i]
    if txts: return txts[0]

def contains_txt_file(lst):
    return bool(find_txt_file(lst))

def parse_and_generate_stories(filename):
    with open(filename) as f:
        titles_and_texts = parse_stories_and_titles(f.read())
    gen_interactive_story(titles_and_texts)

def ask_filename():
    root = tkinter.Tk()
    root.withdraw()
    return tkinter.filedialog.askopenfilenames()[0]

def _test():
    doctest.testmod()

def main():
    _test()
    if contains_txt_file(sys.argv):
        filename = find_txt_file(sys.argv)
    else:
        filename = ask_filename()
    parse_and_generate_stories(filename)

if __name__ == "__main__":
    main()

To simplify testing, I include a properly written story:

a scary choice

It was an extremely [dark] night and around me I could only
see a [cave] and a [wood].

---

dark

I mean, extremely dark, even without moon. But I could not lose time,
it was time to make [a scary choice].

---

cave

The cave was frightening, but I decided to go in nonetheless,
what is life without risk?

---

wood

The wood was emitting scary and creepy sounds but I decided
to enter it because it seemed less scary than the wood.


texts: Splitting one line into multiple ones given a separator

texts:
I have a file containing one long line:

"name surname" <name.surname@example.com>, 'name surname' <name.surname@example.com>, name surname <name.surname@example.com>, "'name surname'" <name.surname@example.com>, surname, <name.surname@example.com>, name <name.surname@example.com>

Note that that's 6 different forms.

I am splitting each email address into its own line, and saving the results into another file:

import sys

ifile = sys.argv[1]
ofile = sys.argv[2]

with open(ifile) as ifile, open(ofile, "w") as ofile:
    addresses = ifile.readline().split(">,")
    for n, address in enumerate(addresses):
        address = address.replace("'", "")
        address = address.replace('"', "")
        name, address = address.split("<")
        address = "<" + address
        if len(name) > 1:
            name = name.strip()
            name = '"{}" '.format(name)
            address = "".join(name + address)
        if n < len(addresses) - 1:
            ofile.write(address.strip() + ">\n")
        else:
            ofile.write(address.strip() + "\n")

Feels to me like hackery so am looking for a better solution.


texts: didSimulatePhysics to animate a ball, taking 45% of CPU

texts:
According to my time profiler this is taking 45% of my cpu usage: have tried to optimize, and someone on stack overflow -- recommended to post here. Time profiler says 99% of the time is spent on the closing brace of the world.enumerateChildNodesWithName

override func didSimulatePhysics() {

        world.enumerateChildNodesWithName("//ball*") {
            node, stop in
            let ball = node as! Ball
            ball.regulateSpeed()
            if let body = ball.physicsBody {
                if (body.velocity.speed() > 0.01) {
                    ball.zRotation = body.velocity.angle() - self.offset
                }
            }
        }

        if let p = currentPlayer {
            centerWorldOnPosition(p.centerPosition())
        } else if playerLayer.children.count > 0 {
            let p = playerLayer.children.first! as! Player
            centerWorldOnPosition(p.centerPosition())
        } else {
            centerWorldOnPosition(CGPoint(x: 0, y: 0))
        }
    }


texts:
The following code is intended to parse a string of the following format and return whether the current time falls in that window:

start_time-stop_time [(day|day-day[, ...])][; ...]

For example,

0900-1200 (mon-wed, sat); 0100-0200 (sun, tue)

The code for parsing that type of string is here:

days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
#grammar definition
hour = pp.Regex('[01]\d|2[0-3]')
minute = pp.Regex('[0-5]\d')
miltime = hour.setResultsName('hour') + minute.setResultsName('minute')
dayrange = pp.oneOf(days) + pp.Suppress('-') + pp.oneOf(days)                            #day-day
dayspec = '(' + pp.delimitedList(pp.Group(dayrange | pp.oneOf(days)), delim=',').setResultsName('dayspec') + ')'
window = miltime.setResultsName('start') + '-' + miltime.setResultsName('end') + pp.Optional(dayspec)
spec = pp.StringStart() + pp.delimitedList( pp.Group(window), delim=';' ) + pp.StringEnd()

#parse and act
#return True instead of return condition so that when it fails, it tries the next window
uptime_spec = uptime_spec.strip().lower()
for window in spec.parseString(uptime_spec):
  start = time(int(window.start.hour), int(window.start.minute))
  end = time(int(window.end.hour), int(window.end.minute))
  if start > end:
    raise pp.ParseBaseException('Start time after end time')
  if start < datetime.now().time() < end:
    if not window.dayspec:                #if there's no dayspec, any day is fine
      return True
    else:
      for day in window.dayspec:
        if len(day.asList()) == 1:        #a single day
          if datetime.now().strftime('%a').lower() == day[0]:
            return True
        else:                             #a range
          start = days.index(day[0])
          end = days.index(day[1])
          if start <= end:                #the range doesn't wrap
            if start <= datetime.now().weekday() <= end:
              return True
          else:                           #the range wraps, check that today isn't outside the range
            if not (end < datetime.now().weekday() < start):
              return True

return False

While this solution works, the parsing bit seems rather ugly, especially how I deal with days and day ranges. That part would be easier if I could just test if today's day of the week was in an allowed set of days, and I feel like that might be possible using setParseAction, but I have no idea how to do it.

Any other suggestions? I'm rather new at this parsing thing.


texts: Optimize printing massive strings to System.out with respect to time

texts:
I need to cut the time it takes to print a large string by ~50%.

I went from using s1 + s2 to using StringBuilder, and instead of making several calls to System.out.print for each line, I create one large string by appending newlines to the StringBuilder, and then print that large string just once with System.out.

But my code is still way too slow (this is for a homework assignment and the code is not accepted by the automated hand-in system because it takes too long).

When the StringBuilder is printed, the string has ~100k lines

The relevant part of my code looks like this:

public class Main {
    public static void main (String[] args){
        MyClass builder = new MyClass();
        new ClassThatBuildsOnBuilder(builder);
        System.out.println(builder.str.toString());
    }
}

public class MyClass {
    private double[] coordinates = new double[]{0, 0, 0, 0};

    public StringBuilder str = new StringBuilder();
    private DecimalFormat formatter = new DecimalFormat("#0.0000");

    public MyClass(){

    }

    public void changeValues(double[] coordinates){
        this.coordinates = coordinates;
        updateRow();
    }

    private void updateRow(){
        for (double d : coordinates){
            str.append(formatter.format(d));
            str.append(" ");
        }
        str.append("\n");
    }

Can this even be optimized further? I feel like this should be very close to a lower bound.


texts:
The following function is designed to accept a string of characters and an integer.  The function returns a string that's a reordered version of the original string.  The reordering process is controlled by the second variable.  If the function is called again with the same string and a different number, a different string will be returned.
However, if the string and the integer do not change, repeat calls to this function will always return the same string.  as the integer changes, the returned strings should not appear to be similar.  I have tested this function on the following string, with integer values between 0 and 40000 without finding a duplicate returned string.

"1234567890abcdefghijklmnopqrstuvwxyz"

Are there obvious improvements that can be made?
I am also curious about this function's limitations.
So far, it seems to perform rather well.

function shuffleString($inputString, $seed = 2000){

    $strLength = strlen($inputString);
    $newString = "";
    $factor = 3 + (int)($seed / $strLength);

    while($strLength > 0){

        $seed += $factor;

        if($seed >= $strLength){
            $seed = $seed % $strLength;
        }

        $newString .= $inputString[$seed];

        $copyStr = "";

        $strLength --;

        if($seed != 0){
            $copyStr = substr($inputString,0,$seed);
        }

        if($seed != $strLength){
            $copyStr .= substr($inputString,$seed+1);
        }

        $inputString = $copyStr;

    }

    return $newString.$inputString;

}

Example:

echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 1234), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '
';
echo shuffleString("1234567890abcdefghijklmnopqrstuvwxyz", 4567), '
';

returns

beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau
beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau
beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau
beint19kw0q7sf4xrpv3dyjgl2ozh58m6cau
g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze
g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze
g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze
g6yvx5fujbaitkdm2s3oqcnl074hr8wp19ze

also:

for($i=0; $i<5; $i++){
    $dataStr = "1234567890abcdefghijklmnopqrstuvwxyz";
    for($j=0; $j<2000; $j++){
        $dataStr = shuffleString($dataStr, ord($dataStr[0]));
    }
    echo $dataStr . '
';
}

returns:

gdwy63zmnjxharpovk50qulf2cei8t174bs9
gdwy63zmnjxharpovk50qulf2cei8t174bs9
gdwy63zmnjxharpovk50qulf2cei8t174bs9
gdwy63zmnjxharpovk50qulf2cei8t174bs9
gdwy63zmnjxharpovk50qulf2cei8t174bs9


texts: Averaging a set of percentages between certain important levels

texts:
I have a spreadsheet, called "To Do", with set of percentages in column E and importance levels in column A:

On another spreadsheet, I'm entering a formula to calculate the average of these percentages, but only those between certain importance levels:

See it on googledocs

This is the formula in question, indented for easier reading:

=TO_PERCENT(
     DIVIDE(
         SUMIF('To Do'!A3:A, "<2000", 'To Do'!E3:E)
       - SUMIF('To Do'!A3:A, "<=1000", 'To Do'!E3:E),
         MAX(
             COUNTIF('To Do'!A3:A, "<2000")
           - COUNTIF('To Do'!A3:A, "<=1000"),
             1
         )
     )
 )

Is there any better way to do this?

I originally wanted to use SUMIFS and COUNTIFS, but it said:

  error: Unknown function name


texts:
I did the following exercise from here to try out the openpyxl module for generating excel files:

  Create a program that takes a number N from the command line and creates an NxN multiplication table in an Excel spreadsheet.

  Row 1 and column A should be used for labels and should be in bold

Here is the code:

 multiplication_table.py

"""
Makes a Excel mulitplication table with user input.

e.g. input = 4

Output in Excel should look like this:
  A B C D E   -> column
1   1 2 3 4   -> titel column in bold (same for row)
2 1 1 2 3 4
3 2 2 4 6 8
4 3 3 6 9 12
5 4 4 8 12 16

r
o
w
"""

import sys
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font

def valid_input(input_string: str) -> bool:
    """Checks if input is valid to use for the excel file"""
    return input_string.isdigit() and int(input_string) >= 1

def get_number_from_user() -> int:
    """Asks user until he puts a valid input string."""
    while True:
        input_string: str = input("Enter positive number to make"
                                  " Excel chart\n")
        if valid_input(input_string):
            return int(input_string)

def get_max_number() -> int:
    """
    Asks from the command line or the user to get the max number for
    the excel file
    """
    if len(sys.argv) > 1:
        input_string: str = sys.argv[1]
        if valid_input(input_string):
            return int(input_string)
    return get_number_from_user()

def make_label_column(sheet, max_number: int, font: Font):
    """Make label column containing enumeration until max_number and
    variable font"""
    for number in range(1, max_number + 1):
        sheet['A' + str(number+1)].font = font
        sheet['A' + str(number+1)] = number

def make_label_row(sheet, max_number: int, font: Font):
    """Make label row containing enumeration until max_number and
    variable font"""
    for number in range(1, max_number + 1):
        sheet[get_column_letter(number+1) + "1"].font = font
        sheet[get_column_letter(number+1) + "1"] = number

def make_multiplication_field(sheet, max_number: int):
    """Make a field in excel with max_number*max_number elements"""
    for num_x in range(1, max_number + 1):
        for num_y in range(1, max_number + 1):
            sheet[get_column_letter(num_x + 1)
                  + str(num_y+1)] = num_x*num_y

def save_workbook_excel_file(workbook):
    """Trys to save created data to excel file"""
    try:
        workbook.save('result.xlsx')
    except PermissionError:
        print("No permission to save file.")

def make_excel_table():
    """Main loop to generate excel multiplication file"""
    workbook = openpyxl.Workbook()
    sheet = workbook['Sheet']
    max_number: int = get_max_number()
    font_with_bold = Font(name='Times New Roman', bold=True)
    make_label_column(sheet, max_number, font_with_bold)
    make_label_column(sheet, max_number, font_with_bold)
    make_multiplication_field(sheet, max_number)
    save_workbook_excel_file(workbook)

if __name__ == "__main__":
    make_excel_table()

Let me know what you think about the code. Is it good to read? What would you improve?

I tried the program with big numbers and it gets rather slow. Is there a way to fill the rows more efficiently?


texts:
Are there any aspects I could improve of my HttpSession wrapper class?

Other suggestions are also welcome.

namespace Http;

class HttpSession
{
    private $data;

    public function __construct($name = null, array $iniSettings = [])
    {
        if ($name) {
            session_name($name);
        }

        foreach ($iniSettings as $key => $value) {
            ini_set($key, $value);
        }
    }

    public function findParameter($name)
    {
        $this->start();

        return isset($this->data[$name]) ? $this->data[$name] : null;
    }

    public function setParameter($name, $value)
    {
        $this->start();

        $this->data[$name] = $value;
    }

    public function unsetParameter($name)
    {
        $this->start();

        unset($this->data[$name]);
    }

    public function regenerateId($deleteOldSessionFile = true)
    {
        $this->start();

        session_regenerate_id($deleteOldSessionFile);
    }

    public function destroy()
    {
        $this->start();

        $this->data = [];

        if (isset($_COOKIE[session_name()])) {
            $scParams = session_get_cookie_params();

            setcookie(
                session_name(), '', time() - 3600,
                $scParams['path'],
                $scParams['domain'],
                $scParams['secure'],
                isset($scParams['httponly'])
            );
        }

        session_destroy();
    }

    private function start()
    {
        if (isset($this->data)) {
            return null;
        }

        if (!isset($_SESSION)) {
            session_start();
        }

        $this->data = &$_SESSION;
    }
}


texts:
I wrote some code that resizes an image to fit in a given box. I think that some parts of the code are not needed (for example if it's a box image). Is there a more efficient way to do this? Is there something wrong with my code (from the results it looks ok)? Is there a "shorter" version to do this?

Bitmap original, resizedImage;

try
{
    using (FileStream fs = new System.IO.FileStream(imageLabel.Text, System.IO.FileMode.Open))
    {
        original = new Bitmap(fs);
    }

    int rectHeight = BOXHEIGHT;
    int rectWidth = BOXWIDTH;

    //if the image is squared set it's height and width to the smallest of the desired dimensions (our box). In the current example rectHeight<rectWidth
    if (original.Height == original.Width)
    {
        resizedImage = new Bitmap(original, rectHeight, rectHeight);
    }
    else
    {
        //calculate aspect ratio
        float aspect = original.Width / (float)original.Height;
        int newWidth, newHeight;

        //calculate new dimensions based on aspect ratio
        newWidth = (int)(rectWidth * aspect);
        newHeight = (int)(newWidth / aspect);

        //if one of the two dimensions exceed the box dimensions
        if (newWidth > rectWidth || newHeight > rectHeight)
        {
            //depending on which of the two exceeds the box dimensions set it as the box dimension and calculate the other one based on the aspect ratio
            if (newWidth > newHeight)
            {
                newWidth = rectWidth;
                newHeight = (int)(newWidth / aspect);
            }
            else
            {
                newHeight = rectHeight;
                newWidth = (int)(newHeight * aspect);
            }
        }
        resizedImage = new Bitmap(original, newWidth, newHeight);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


texts: More efficient way than creating scanner of .txt file twice

texts:
I am working on a simple personal project to build a Hoffman Tree. In my constructor, shown below, I am reading in a file, creating HoffmanNodes that represent each char in the file then I got through the file to encode it. I need to create a Scanner to go through the file once to find all the chars and their frequency, then I recreate the scanner of the same file and go through it again to encode it.

I have tried to do some research to find a more efficient way to do this, and I am coming up short. Is there an easier way to do this?

public HoffmanCoding(File inFile) {

    Scanner in = createScanner(inFile);
    //Check empty file
    if (in.hasNextLine() == false) {
        throw new IllegalArgumentException("Can not encode an empty file");
    }

    //Create a HashMap that holds all the HoffmanNodes in the HoffmanTree
    nodeHashMap = buildNodeHashMap(in);
    //Use the HashMap to create a Priority Que that I then can use to make the tree
    PriorityQueue<HoffmanTreeNode> allNodes = new PriorityQueue<>(nodeHashMap.values());
    //Build the HoffmanTree
    this.rootOfHoffmanTree = buildHoffmanTree(allNodes);
    //Assign a code to all the nodes based on their position in the tree.
    assignCode(this.rootOfHoffmanTree, "");

    // Recreate scanner reset it to the begging of the file
    in = createScanner(inFile);
    //Encode and Decode the message.
    this.encodedMessage = encodeMessage(in);
    in.close();
    this.decodedMessage = decodeMessage(this.encodedMessage);
}


texts: Safely & portably read a value into a predefined integral type of varying size like mode_t

texts:
I need to read a value from a text file and put it into a predefined type, in this particular case mode_t. This typedef can have a variety of types underlying it, so what is the portable way to read such a value and assign it to a variable of the predefined type.

Since you have no idea how large the type is, I was starting under the assumption that you should read using strtoimax/strtoumax and then range check somehow.  What I came up with "works" (seemingly) but looks ugly to my eye.

For example:

static mode_t parse_mode ( const char * s ) {
    char *       e = NULL;
    uintmax_t    u;
    uintmax_t    x;
    mode_t       m;
    int          c;

    if ( s == NULL) goto error_no_value;
    if (*s == '\0') goto error_no_value;
    if (*s == '-' ) goto error_negative;
    errno = 0;
    u = strtoumax(s, &e, 8);              /* value is in octal */
    if (errno) goto error_range;
    if (e == s) goto error_bogus;
    c = *e;
    if (c && !isspace(c)) goto error_bogus;   /* WS after is OK */

    /* now the question part -- better way??? */
         if (sizeof(mode_t) == 1) x = UINT8_MAX;
    else if (sizeof(mode_t) == 2) x = UINT16_MAX;
    else if (sizeof(mode_t) == 4) x = UINT32_MAX;
    else if (sizeof(mode_t) == 8) x = UINT64_MAX;
    else goto error_what_size;
    if (u > x) goto error_too_big;

    m = (mode_t)u;
    return m;
error_no_value: fprintf(stderr, "Error: no value\n");    return (mode_t)-1;
error_negative: fprintf(stderr, "Error: negative\n");    return (mode_t)-1;
error_range:    fprintf(stderr, "Error: range\n");       return (mode_t)-1;
error_bogus:    fprintf(stderr, "Error: bogus\n");       return (mode_t)-1;
error_what_size:fprintf(stderr, "Error: what size\n");   return (mode_t)-1;
error_too_big:  fprintf(stderr, "Error: too big\n");     return (mode_t)-1;
}

[I've totally glossed over the question of whether or not the type is signed or unsigned and just assumed unsigned here]

PS, yes, I have "secret knowledge" that no valid mode is likely to exceed 0177777; please ignore that as it is not necessarily true for other predefined types of its ilk.

PPS, junk like time_t which might not even be integral is not a part of this question

EDIT Added in the error goop.
Also, note that all leading whitespace has been skipped prior to this being called.


texts: Table class to fill array structure with values

texts:
The code creates a table and adds rows and columns.

Does it make sense to write the code like this?
Would you design it differently?
Is there a better OOP approach to this?

class Table
  attr_reader :grid

  def initialize(rows: , columns:)
    @grid = construct(rows, columns)
  end

  def construct(rows, columns)
    raise 'arguments must be arrays' unless rows.is_a?(Array) && columns.is_a?(Array)
    table = []
    rows = [] if rows.nil?
    rows.each do |row|
      table << columns.map do |c| c end
    end
    table
  end
end

Here are the specs which describe what it is doing:

require 'spec_helper'
require_relative '..\test'

RSpec.describe Table do

  it 'is empty' do
    table = Table.new(rows: [], columns: [])
    expect(table.grid).to eq []
  end

  it 'raises if no array is given' do
    expect {
      Table.new(rows: [], columns: 1) }.to raise_error RuntimeError
    expect {
      Table.new(rows: 1, columns:[]) }.to raise_error RuntimeError
  end

  it 'has several rows and columns' do
    row = double('row')
    column = double('column')
    col = Column.new.value = 14
    table = Table.new(rows: [1, 3, 3], columns: [1, col])
    expect(table.grid).to eq [
      [1, 2],
      [1, 2],
      [1, 2]
    ]
  end
end


texts: Best way to optimize this code so it takes up less space?

texts:
CRITICAL = 0
MEDIUM = 1
LOW = 0

test = {
    "version": "0",
    "id": "85fc3613-e913-7fc4-a80c-a3753e4aa9ae",
    "detail-type": "ECR Image Scan",
    "source": "aws.ecr",
    "account":
        "123456789012",
    "time": "2019-10-29T02:36:48Z",
    "region": "us-east-1",
    "resources": [
        "arn:aws:ecr:us-east-1:123456789012:repository/my-repo"
    ],
    "detail": {
        "scan-status": "COMPLETE",
        "repository-name": "my-repo",
        "finding-severity-counts": {
            "CRITICAL": 10,
            "MEDIUM": 9
        }
    }
}
resource = test["resources"][0]

finding_severity_counts = test["detail"]["finding-severity-counts"]

if "CRITICAL" in finding_severity_counts:
    critical_count = finding_severity_counts["CRITICAL"]
    if critical_count > CRITICAL:
        print("Resource {} has {} critical findings".format(resource, critical_count))

if "MEDIUM" in finding_severity_counts:
    medium_count = finding_severity_counts["MEDIUM"]
    if medium_count > MEDIUM:
        print("Resource {} has {} medium findings".format(resource, medium_count))

if "LOW" in finding_severity_counts:
    low_count = finding_severity_counts["LOW"]
    if low_count > LOW:
        print("Resource {} has {} low findings".format(resource, low_count))

I have got this code and am trying to optimize it so it is smaller and takes up less lines of code. Right now the code is kind of ugly and not at all efficient. Is there any way to make this more efficient?


texts: Is this the optimal way to write "find these IDs in a list of objects" using linq?

texts:
I've got a situation where I have a list of Organizations (code to follow), and a user has a list of OrganizationIds (ints). I want to filter down the full list of Organizations using the User's OrganizationId list for a dropdown list. The query works, but it feels like there may be a more optimal way to write it. Is there, or am I already pretty much optimized?

public class Organization
{
    public int Id { get; set; }
    public string Division { get; set; }
    public bool IsActive { get; set; }
    public bool IsDefault { get; set; }
    public string Name { get; set; }
}

Query

vm.locations = _organizations.GetOrganizations().Where(o => ((ApplicationUser)User).OrganizationIdList.Any(u => u == o.Id)).Select(org =>
    new SelectListItem
    {
        Text = org.Division + " - " + org.Name,
        Value = org.Id.ToString()
    }).OrderBy(item => item.Text);


texts: DSL for hierarchical class API definitions

texts:
What do you think about syntax of my strictly typed DSL snippet below? Does it look understandable and efficient to define object graphs at a first glance?

   def Person(Name Name, Age Age)
       def Name
           (string First, string Last)
               def Full = $"{First} ${Last}"
           (string First, string Middle, string Last)
               def Full = $"{First} {Middle[0]}. {Last}"
       def Age
           (Date born, Date? died = null) =>
               this(Died.Year ?? Date.Today.Year - Born.Year)
           (int years) =>
               years

It could be used as:

// implicit
val person = Person(
    ("Mark", "Twain"),
    ((1835, 11, 30), (1910, 04, 21)))

// or explicit like
val person1 = Person(
    Name("Mark", "Twain"),
    Age((1835, 11, 30), (1910, 04, 21)))

// or fully qualified to resolve ambiguities
val person2 = Person(
    Person.Name("Mark", "Twain"),
    Person.Age(Date(1835, 11, 30), Date(1910, 04, 21)))

Assert(true, person.Name is Person.Name)
Assert(person.Name("Mark", "Twain"), person.Name)
Assert("Mark", person.Name.First)
Assert("Twain", person.Name.Last)
Assert("Mark Twain", person.Name.Full)
Assert(74, person.Age);

One more example, closures:

def Greeter(string Salutation)
    def Greet(string name) =>
        $"{Salutation}, {name}!"

val greeter = Greeter("Hi")
val message = greeter.Greet("Tom")
Assert("Hi, Tom!", message)

// or like this (surprise :)
val greet = Greeter.Greet("Tom")
val greeter = Greeter("Hi")
val message = greeter(greet)
Assert("Hi, Tom!", message)

Would you personally find it useful?


texts:
I wanted to review my design strategy for CSV parser.
I have 4 CSV files, which have different layouts as shown below.
Each row of a CSV file will be mapped to a class. For example, if CSV_FILE_A has 10 rows, a list contains 10 objects of ObjA will be returned after calling parser function. For CSV_FILE_B of 5 entries, a list of 5 ObjB will be returned.

CSV_FILE_A: LONG, STR, STR
CSV_FILE_B: LONG, LONG
CSV_FILE_C: LONG, LONG, STR, LONG
CSV_FILE_D: LONG, LONG, LONG

I designed an interface like this.

public interface CSVParser<T> {
    public List<T> parseCSVFile(String fileName);
}

And I have created 4 different parsers, which implement the interface and have a different logic of parsing the CSV file. The code below is a complete implementation for CSV_FILE_B. The other three parsers will have the same structures but different if-else statements for setting object fields and different object types in the type of List.

public class csvBParser implements CSVParser {

    @Override
    public List<ObjectB> parseCSVFile(String fileName) {

        List<ObjectB> list = new ArrayList<ObjectB>();

        try {
            ClassLoader classLoader = Thread.currentThread()
                    .getContextClassLoader();
            InputStream is = classLoader.getResourceAsStream(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line = "";
            StringTokenizer token = null;
            int lineNum = 0, tokenNum = 0;

            while ((line = br.readLine()) != null) {
                if (lineNum == 0){
                    lineNum++;
                    continue;
                }

                token = new StringTokenizer(line, ",");
                ObjectB objB = new ObjectB();

                while (token.hasMoreTokens()) {
                    String nextToken = token.nextToken();

                    boolean isTokenNull = false;
                    if (nextToken.equalsIgnoreCase("null"))
                        isTokenNull = true;

                    if (!isTokenNull) {
                        if (tokenNum == 0) {
                            objB.setObjBId(Long.valueOf(nextToken));
                        } else if (tokenNum == 1) {
                            objB.setObjBSndId(Long.valueOf(nextToken));
                        } else {
                            System.err.println("Invalid Token Number "
                                    + tokenNum);
                        }
                    }
                    tokenNum++;
                }

                list.add(objB);
                tokenNum = 0;
                lineNum++;
            }
        } catch (Exception e) {
            System.err.println("Parse Error " + e.getMessage());
        }

        return list;
    }
}

And, I finally uses a factory to create an instance of a parser.

public class CSVParserFactory {

    public static CSVParser getParser(TableType type) {

        CSVParser parser = null;
        if(type == A){
            parser = new csvAParser();
        }
        else if(type == B){
            parser = new csvBParser();
        }
        else if(type == C){
            parser = new csvCParser();
        }
        else if(type == D){
            parser = new csvDParser();
        }
        /*
         * more parsers will be added later
         */
        else{
            throw new IllegalArgumentException ("No such table type");
        }
        return parser;
    }
}

The parser is being called like this. Each element in the list is corresponding to a row in the CSV file

CSVParser parser = CSVParserFactory.getParser(TableType.A);
List list = parser.parseCSVFile(CSV_FILE_A);

Do you guys have any suggestions of this design pattern?
If I consider a code factorization, what do I need to do?

Thanks in advance.


texts: Retrieve recognised text from JSON returned by Microsoft OCR

texts:
The Microsoft OCR API returns json, and if I want to extact the text data from this json:

response = \
{
  "language": "en",
  "textAngle": -2.0000000000000338,
  "orientation": "Up",
  "regions": [
    {
      "boundingBox": "462,379,497,258",
      "lines": [
        {
          "boundingBox": "462,379,497,74",
          "words": [
            {
              "boundingBox": "462,379,41,73",
              "text": "A"
            },
            {
              "boundingBox": "523,379,153,73",
              "text": "GOAL"
            },
            {
              "boundingBox": "694,379,265,74",
              "text": "WITHOUT"
            }
          ]
        },
        {
          "boundingBox": "565,471,289,74",
          "words": [
            {
              "boundingBox": "565,471,41,73",
              "text": "A"
            },
            {
              "boundingBox": "626,471,150,73",
              "text": "PLAN"
            },
            {
              "boundingBox": "801,472,53,73",
              "text": "IS"
            }
          ]
        },
        {
          "boundingBox": "519,563,375,74",
          "words": [
            {
              "boundingBox": "519,563,149,74",
              "text": "JUST"
            },
            {
              "boundingBox": "683,564,41,72",
              "text": "A"
            },
            {
              "boundingBox": "741,564,153,73",
              "text": "WISH"
            }
          ]
        }
      ]
    }
  ]
}

def check_for_word(ocr):
    # Initialise our subject to None
    print("OCR: {}".format(ocr))
    subject = None
    for region in ocr["regions"]:
        if "lines" in region:
          for lines in region["lines"]:
            if "words" in lines:
              for word in lines["words"]:
                if "text" in word:
                  subject = word["text"].lower()
                  break

    print("OCR word is {}".format(subject))
    return subject

print(response["regions"][0]["lines"][0]["words"][0]["text"]) # Should return this

print(check_for_word(response))

Each dictionary has arrays and we are unsure if the array contains any element
Also not sure if the dictionary has key

Let's say we just wish to return the first text it matched from the image file.

This code works but it has a deep nested structure that has bad smell. Is there a better practice to write this in a cleaner way?


texts: Validate the order of a List by custom strings

texts:
I have a test where I have to validate the order of items in a List based on a pre-defined hierarchy that is being given to me as part of my assignment. Here it is below.

Cat
Dog
Horse
Elephant

The items in the list would only ever be those four types, but the size of list is not limited. The list will be passed in as part of the method. There can be multiple of each or none at all. The below two list would be valid:

Cat
Cat
Dog
Elephant

This would not.

Elephant
Dog
Horse
Cat

Below is what I have so far, and I feel as though there is a much more elegant solution. In particular, I would like to minimize the amount of bools and if statements I am using.

public bool ValidateAnimalOrder(List<string> listOfAnimals)
{
    bool catExists = false;
    bool dogExists = false;
    bool horseExists = false;
    bool elephantExists = false;

    for (int x = 0; x < listOfAnimals.Count; x++)
    {
        if (listOfAnimals[x] == "Cat")
        {
            catExists = true;
            if(dogExists || horseExists || elephantExists)
            {
                return false;
            }
        }
        if (listOfAnimals[x] == "Dog")
        {
            dogExists = true;
            if (horseExists || elephantExists)
            {
                return false;
            }
        }
        if (listOfAnimals[x] == "Horse")
        {
            horseExists = true;
            if (elephantExists)
            {
                return false;
            }
        }
        if (listOfAnimals[x] == "Elephant")
        {
            elephantExists = true;
        }

    }

    return true;
}


texts:
I wrote a simple word-counter in Python a while ago, capable of processing DOCX, XLSX, TXT, and some PDF files. Now I gave it a simple GUI - this is my first tkinter program ever. What do you think?
import openpyxl
import docx2txt
import PyPDF2
import tkinter
from tkinter import filedialog

def excel_counter(filename):
    count = 0
    wb = openpyxl.load_workbook(filename)
    for sheet in wb:
        for row in sheet:
            for cell in row:
                text = str(cell.value)
                if text != "None":
                    word_list = text.split()
                    count += len(word_list)
    return count

def pdf_counter(filename):
    pdf_word_count = 0
    pdfFileObj = open(filename, "rb")
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
    number_of_pages = pdfReader.getNumPages() - 1
    for page in range(0, number_of_pages + 1):
        page_contents = pdfReader.getPage(page - 1)
        raw_text = page_contents.extractText()
        text = raw_text.encode('utf-8')
        page_word_count = len(text.split())
        pdf_word_count += page_word_count
    return pdf_word_count

def uploadaction(event=None):
    root = tkinter.Tk()
    root.destroy()
    filename = filedialog.askopenfilename()
    return filename

def wordcounter(file):
    extension = file.split(".")[-1]
    if extension == "xlsx":
        current_count = excel_counter(file)
        return current_count
    if extension == "docx":
        text = docx2txt.process(file)
        current_count = len(text.split())
        return current_count
    if extension == "txt":
        f = open(file, "r")
        text = f.read()
        current_count = len(text.split())
        return current_count
    if extension == "pdf":
        pdf_word_count = pdf_counter(file)
        return pdf_word_count

window = tkinter.Tk()
wordcount = wordcounter(uploadaction())
label = tkinter.Label(text=f"Word Count: {wordcount}")
label.pack()
window.mainloop()


texts:
This is a follow-up review to JavaScript queue implementation using linked list

I've run the code through a linter, fixed every style error, added const where it was possible, removed extraneous templates and changed the return policy for calling dequeue() on an empty queue to make it fail fast. I also implemented an empty() method for the user's convenience.

I'm still undecided as to whether to use single or double quotes for strings. The linter suggests single quotes, but I've read reviews suggesting double quotes might be better because they look less like backticks, which are used for template literals.

Is there anything I've missed?

function makeQueue() {
  // data
  let head = null;
  let size = 0;

  // methods
  function enqueue(x) {
    let newNode = {next: head, data: x};
    head = newNode;
    size++;
  }

  function dequeue() {
    if (size === 0) {
      throw new Error('dequeue() on an empty queue');
    }

    const x = head.data;
    head = head.next;
    size--;

    return x;
  }

  function getSize() {
    return size;
  };

  function isEmpty() {
    return size === 0;
  };

  // public
  return {
    enqueue,
    dequeue,
    size: getSize,
    empty: isEmpty
  };
}

var q0 = makeQueue();
var q1 = makeQueue();
var q2 = makeQueue();

for (var i = 0; i < 16; i++) {
  q0.enqueue(i);
}

console.log(q0.size());
console.log(q1.empty());
console.log(q2.size());

Edit

The goal here was to improve the JavaScript, I only realized now that I actually wrote a LIFO stack.


texts: Using Perl's fork() to parallelize processing

texts:
I use bash scripts to process last names through a Perl program, and I parallelize the execution like this, by name initials:

for alpha in a b c d e f g h i j
do
    perl process_names.pl -init $alpha &
done
wait

I've determined that ~10 parallel executions is about optimal, to complete the work quickly but also to leave the computer to do other work.

But this is inefficient, because some letters have more records to process than others, so sometimes 8 or 9 have finished and there's a lingering program execution during which I'd like to begin processing another batch of name initials.

So I wanted to use Perl's fork to keep 10 processes running at a time. Imagine that the following code block is run by a program invocation like this:
perl process_names.pl -all
Then the system() call would invoke the program as child processes, like this:
perl process_names.pl -init a, b, c, etc., processing 10 at a time until all are finished.

This seems to work fine. No zombie processes that I can tell, work gets done, and it's faster. But I've never used the bare fork interface like this. Am I doing it correctly? Are there any gotchas that I've overlooked?

my $data = {
  'remaining' => ['a' ... 'z'],
  'running'   => [],  # <- currently running list of child pids
  'children'  => [],  # <- all child pids; added to list as spawned, then waited on
  'cur_init'  => ''
};

while (scalar @{$data->{remaining}}) {
    if (scalar @{$data->{running}} < 10) {

        $data->{cur_init} = shift(@{$data->{remaining}});

        my $pid = fork();
        if (!$pid) {
            ## CHILD ##
            system('perl ' . abs_path($0) . ' -init ' . $data->{cur_init});
            exit;
        } else {
            ## PARENT ##
            push(@{$data->{running}}, $pid);
            push(@{$data->{children}}, $pid);
        }
    }

    my @new;
    foreach my $cpid (@{$data->{running}}) {
        my $is_running = kill(0, $cpid);
        if ($is_running) {
           push(@new, $cpid);
        }
    }
    $data->{running} = \@new;
}

foreach my $pid (@{$data->{children}}) {
    waitpid $pid, 0;
}


texts:
Consider I have many enums (Java) that looks somewhat like this:

@AllArgsConstructor
@Getter
public enum PopularPeriod {
  MONTHLY  ("MON"),
  BIMONTHLY ("BMN"),
  QUARTERLY  ("QTR"),
  SEMI_ANNUALLY  ("SMA"),
  ANNUALLY  ("ANL");

  private final String value;
}

Now, a usual use, I'd think, would be to get the enum object using its value (the string) - there's an input you're parsing and you want to turn the string into some nice objects that make the code more readable.

So I added this to the enum above -

public static PopularPeriod fromString(String value) {
  for (PopularPeriod pp : PopularPeriod.values()) {
    if (pp.getValue().equalsIgnoreCase(value)) return pp;
  }

  return null;
}

(don't mind the returning of null the casing).
This works quite good.
But if you have dozens of those enums - you need to write it for each one.

I tried approaches like adding something like this to a utility class -

public static <T extends Enum<T>> T safeEnumByValue(Class<T> enumType, Object value) { ... }

but there I don't know of the private field (value).

So I though of "implementing" an interface instead (as enum may not extend base classes), and make the search as a default method in the interface.

public interface IEnum<T> {
  T getValue();
}

@AllArgsConstructor
@Getter
public enum PopularPeriod implements IEnum<String> { ... }

and adding a default method in the interface - but that's impossible as I don't have the PopularPeriod.values() there to work with.

In the end, I combined the two approaches.
I have this method in a utility class:

public static <T extends IEnum> T safeEnumByValue(Class<T> enumType, Object value) {
  for (T enumConstant : enumType.getEnumConstants()) {
    if (enumConstant.getValue().equals(value)) return enumConstant;
  }

  return null;
}

Just got there.
It works.
I thought maybe I'd delete this question,but I would love to hear if there's any elegant way to do it.


texts: MySQL query in nested loop to get scores and averages for students

texts:
I am trying to get the scores and average for all assignments for records in a MYSQL database. The code below works but seems to take quite a bit of time to run because of the nested while loop. Any suggestions on how to combine the queries into one?

$query4 ="SELECT studentsisid,coursename,learningoutcomeid,learningoutcomename,
count(RecordID) as assessmentcount,
count(if(outcomescore >= 3,outcomescore, NULL)) as over3,
avg(outcomescore) as scoreavg
from studentscores
WHERE studentsisid LIKE '$studentid' AND coursename='$coursename'
Group by studentsisid,coursename, learningoutcomeid
ORDER BY studentname,   learningoutcomename";

$result4=mysql_query($query4);

if (mysql_numrows($result4) == 0){
die("No result.");
}

while ($row4 = mysql_fetch_assoc($result4)) {
  $learningoutcomeid = (int)$row4['learningoutcomeid'];
  $coursename = $row4['coursename'];
  $studentid = $row4['studentsisid'];
  $learningoutcomename = $row4['learningoutcomename'];
  $learningoutcomeid = (int)$row4['learningoutcomeid'];
  $assessmentcount = (int)$row4['assessmentcount'];
  $scoreavg = number_format($row4['scoreavg'], 1);
  $over3 = $row4['over3'];

$query5 ="SELECT count(if(outcomescore >= 3,outcomescore, NULL)) as recentover3,
    avg(outcomescore) as recentscoreavg
    FROM
    (
    SELECT outcomescore FROM studentscores
    WHERE
    studentsisid='$studentid' AND coursename='$coursename'
    AND learningoutcomeid='$learningoutcomeid'
    ORDER BY RecordID DESC LIMIT 3) as r";

$result5=mysql_query($query5);

while ($row5 = mysql_fetch_assoc($result5)) {
$recentscoreavg = number_format($row5['recentscoreavg'], 1);
$recentover3 = $row5['recentover3'];

I am trying to get the data below and the code above does accomplish the goal:

studentsisid;coursename;loid;loname;assessmentcount;over3;scoreavg;recentover3;recentscoretavg
1234";"Course1";"7982";"LearningOutcome1";"1";"1";"3.2";"1";"3.2"
1234;"Course1";"7995";"LearningOutcome2";"4";"4";"2.5";"2";"2.5"
1234;"Course1";"7991";"LearningOutcome3";"6";"6";"3.8";"3";"3.2"
1234;"Course1";"7889";"LearningOutcome4";"1";"1";"3.4";"1";"3.2"
1234;"Course1";"7839";"LearningOutcome5";"2";"2";"2,6";"1";"3.2"


texts: Advent of Code 2020 Day 1 in Clojurescript

texts:
This is a Clojurescript solution to parts 1 and 2 of Day 1 of Advent of Code 2020.
This code is written in Clojurescript to run on Node.js. It can be run simply using lumo and this command: lumo filename.cljs.
Here's a short version of the problem statement:
Part 1. Given a list of numbers, find the two entries that sum to 2020 and then multiply those two numbers together.
(ns day-01.core
  (:require [clojure.string]))

(def fs (js/require "fs"))

(def entries
  (set
   (map js/parseInt
        (clojure.string/split-lines
         (.readFileSync fs "puzzle.input" "utf8")))))

(println (reduce *
                 (filter (fn [entry]
                           (contains? entries (- 2020 entry))) entries)))

Part 2: what is the product of the three entries that sum to 2020?
;; Same boilerplate

(def match
  (first
   (filter #(= 2020 (reduce + %))
           (for [x entries y entries z entries] [x y z]))))

(println (reduce * match))


texts: Threadsafe oneshot-event which fires on subscription if the event was fired in the past

texts:
Assumptions

Basically, a Connection class has a "Disconnect" event. Subscribing to this event isn't thread-safe, because the disconnection may fire from another thread right before I subscribe. So checking before the subscription doesn't help.

Checking for the disconnect after subscription doesn't help either because the event may have fired in the meanwhile (2 threads might execute the same "observer" twice).

(My) Solution:

An event always fired once (and only once), even if the event itself already happened before Source is on GitHub as well.

Questions:

Are there other simpler solutions addressing this? (by simpler I mean from an outside or usage perspective)

Do you see any race conditions or things that could go wrong?

Maybe you have optimizations or simplifications to add?

Input is highly appreciated!

/// <summary>
/// Triggers if the event is invoked or was invoked before subscribing to it.
/// <para> Can be accessed safely by multiple threads.</para>
/// </summary>
public class AutoInvokeEvent<Sender, Args>
{
    public delegate void EventHandle(Sender sender, Args arguments);

    /// <summary>
    /// Handle will be invoked if the event was triggered in the past.
    /// <para>Unsubscribing happens automatically after the invocation and is redundant if done from the event handle.</para>
    /// </summary>
    public event EventHandle Event
    {
        add
        {
            if (!Subscribe(value))
                value(m_sender, m_eventArgs);
        }
        remove { InternalEvent -= value; }
    }

    private event EventHandle InternalEvent;

    // this is my personal lock implementation. in this case it is used like any other lock(object) so just ignore it
    private SafeExecutor m_lock = new SingleThreadExecutor();
    private volatile bool m_invoked = false;

    Sender m_sender;
    Args m_eventArgs;

    /// <summary>
    /// Invokes all subscribed handles with the given parameters.
    /// <para>All calls after the first are ignored.</para>
    /// </summary>
    public void Invoke(Sender sender, Args args)
    {
        GetEventHandle(sender, args)?.Invoke(m_sender, m_eventArgs);
    }

    private EventHandle GetEventHandle(Sender sender, Args args)
    {
        return m_lock.Execute(() =>
        {
            if (m_invoked)
                return null;

            m_sender = sender;
            m_eventArgs = args;
            m_invoked = true;
            EventHandle handle = InternalEvent;
            InternalEvent = null;
            return handle;
        });
    }

    /// <returns>Returns true if subscription was successful and false if handle needs to be invoked immediately.</returns>
    private bool Subscribe(EventHandle handle)
    {
        return m_lock.Execute(() =>
        {
            if (!m_invoked)
                InternalEvent += handle;

            return !m_invoked;
        });
    }
}

How the class could be used :

class Connection
{
    public AutoInvokeEvent<object, EndPoint> OnDisconnect = new AutoInvokeEvent<object, EndPoint>();

    public Disconnect()
    {
        OnDisconnect.Invoke(this, endpoint);
    }
}

void main()
{
    Connection connection = new Connection();
    connection.OnDisconnect.Event += DoStuffOnDisconnect;
}

void DoStuffOnDisconnect(object sender, EndPoint endpoint) { }


texts: Success page + data entry for a store page

texts:
The purpose of this code is to log the inputs of a form (which is a menu for a shop) to the database to be kept as records as well as printed out as a receipt at the store.

I have been learning how to code from the internet and tried to put together my knowledge in a project. The code is working, but I would like to adopt elegance and good coding practices.

<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>
<?php
require 'databaseaccess.php';
?>

<?php
//check order present
if(!($_POST))
{
    echo "error, order was not received!";
    echo "
";
    echo "return to  order page ";

}
else{
    $total = 0;
    $soba_size = $_POST['soba_size'];
    switch($soba_size){
    case "small":
    $total = $total + 4;
    break;
    case "reg":
    $total = $total + 6;
    break;
    case "large":
    $total = $total + 8;
    break;
    }
    $soba_type = $_POST['soba_type'];
    $dbtoppings = '';
    if ($_POST['topping']){
        foreach($_POST['topping'] as $topping){
            switch($topping){
            case "duck":
            $total = $total + 1;
            $dbtoppings = $dbtoppings.",".$topping;
            break;
            case "egg":
            $total = $total + 2;
            $dbtoppings = $dbtoppings.",".$topping;
            break;
            case "chicken":
            $total = $total + 3;
            $dbtoppings = $dbtoppings.",".$topping;
            break;
            case "teriyaki chicken":
            $total = $total + 4;
            $dbtoppings = $dbtoppings.",".$topping;
            break;
            }
        }
    }
    if($_POST['requests']){
    $request = $_POST['requests'];
    }
    else{
    $request = '';
    }
//begin data entry
$data1 = array('total' => $total);
$STH = $DBH->prepare("INSERT INTO orderlist(total) values (:total)");
$STH->execute($data1);
$lastId = $DBH->lastInsertId();
//dataentry2
$data2 = array('orderid' => $lastId, 'soba_size' => $soba_size, 'soba_type' => $soba_type, 'topping' => $dbtoppings,'request' => $request);
$STH = $DBH->prepare("INSERT INTO orderdetails(orderID,soba_size,soba_type,topping,request) values (:orderid,:soba_size,:soba_type,:topping,:request)");
$STH->execute($data2);
}
?>

Thank you for ordering. Your order has been printed.

Order Number: <?php echo $lastId; ?>

        Amount:$ <?php echo $total;  ?>

Please show this page at the cashier to confirm your order. Thank you!


texts: Python3 - Cropping PDF files according to coordinates

texts:
I have a python script, that is performing OCR on PDF pages.

I am trying to do so I can provide coordinates to the script - so it will only select the text within the provided coordinates (x, y, h, w).

This task in itself should be easy enough, however there is a caveat.

I am trying to do this on PDF files that are:

Scanned - just an image.
Not scanned - contains searchable text.

Imagine below coordinates are being provided:

{"h": "800", "w": "395", "x": "0","y": "0"}

If the PDF contains text, I will use the pdftotext command. The pdftotext command accepts a set of coordinates (x, y, H, W) - so selecting text from a specific area is straightforward.

Example - text.pdf

Width: 595px
Height: 842px
Output: My text on the PDF file.

However, if the exact same PDF file gets scanned, I will have to convert the PDF page to an image so I can perform OCR on the page. It's recommended to use 300 DPI when performing OCR on images [See link].

This means, that the same PDF file with the same coordinates as above will no longer output the same result. This is because, ultimately, when converting the PDF to an image with 300 DPI, the width/height will be changed accordingly.

Let's say I am cropping the image using Python, according to above coordinates:

area(0, 0, 395, 800)
pdf_image = Image.open(my_image_file)
output_image = pdf_image.crop(area)

Let's use the PDF file from above as an example:

Example - textscanned.pdf

Width: 2479
Height: 3508
Output: My t

As you can see, the output is different - because 395px on above page is not the same as 395px on my original PDF.

How to solve this?

As far as I see, I have one thing I can use to solve this in my script: the 300 DPI.

Get the scanned PDF files width/height.
Convert the scanned PDF to an image (resolution = 300 DPI).
Divide the original PDFs dimensions with the dimensions of the converted image.
Multiply the coordinates with above result.

# Get the scanned PDFs dimensions:

dimensions = PdfFileReader(open(pdf_file, 'rb'))
dimensions = dimensions.getPage(0).mediaBox

original_width = dimensions[2]
original_height = dimensions[3]

# Get the dimensions of the converted PDF file => image:

cropped_image = Image.open(converted_Image)
size = (cropped_image.size)
width, height = size

# Divide the original width & height width the converted:

width_factor = width / original_width # Outputs: 4,166386555
height_factor = height / original_height # Outputs: 4,166270784

# Multiply the factor with the coordinates:

width = int(coordinates['w'] * width_factor)
height = int(coordinates['h'] * height_factor)

This will result in a new width, height set:

width = 1645
height = 3333

When cropping the image using above width/height coordinates, the output is identical to the first text PDF file.

Am I on to something? Is my math correct using above?

I imagine I have to do something similar for the x, y coordinates - but not sure if the same math can be applied to these two?


texts: Create new columns using groupby in pandas

texts:
I'm running into a large bottleneck in my program that takes hours to perform.

I have a Dataframe that is very large. I need to take the columns of the Dataframe and create new columns within same Dataframe. The new columns need to grouped by a specific date once grouped they are ranked. After they are ranked they are divided by the total number of values in that day (this number is stored in counts_date). This gives me a range of 0-1. The dataframe is a mulitindex with date as the level 0 and a unique id is level 1.

Is there a way to do this so I don't have to do it column by column and still create new columns?

df=pd.read_hdf('data.h5')

ranks2=list(df.columns.values)

for i in ranks2:
    df[i+'_rank']=df.groupby('date')[i].rank()

for i in ranks2:
    df[i+'_rank']=df[i+'_rank']/df['counts_date']