texts: Nginx configuration, with global defaults and support for a PHP site

texts:
The following code is an Nginx default conf file. The conf file itself includes another server block which holds a site's configuration.
While this combination works and the sites appears fine on web, I have a feeling that my code doesn't follow the DRY standard.
server {
    server_name _;
    return 301 https://$host$request_uri;

    root /var/www/html;
    index index.php index.html index.htm;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass 127.0.0.1:9000;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ /\.ht {
        deny all;
    }

    # notes {
        # 443 ssl http2;
        # [::]:443 ssl http2;
    # }
}

server {
    listen 80;
    listen [::]:80;
    server_name contfix.co.il www.contfix.co.il;

    ssl_certificate /etc/nginx/conf.d/ssl/contfix.co.il.crt;
    ssl_certificate_key /etc/nginx/conf.d/ssl/contfix.co.il.key;
    ssl_dhparam /etc/nginx/conf.d/ssl/dhparam.pem;

    root /var/www/html/contfix.co.il;

    location / {
        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass 127.0.0.1:9000;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff)$ {
        expires 365d;
    }

    location ~*  \.(pdf)$ {
        expires 30d;
    }
}

Given that my code seems to be a bit repetitive, I want to ask: Can it be made a bit less repetitive?


texts:
I'm currently writing Report's system. I have about 20 different users with different access.
Am I doing it correctly? Can I improve my style of writing this code? All my reports based on the same structure.

In my Report's Controller:

function my_report_name()
    {
        //current week by default
        $dates['from'] = $this->uri->segment(3,date('Y-m-d',strtotime(date('o-\\WW'))-60*60*24*7));
        $dates['to'] = $this->uri->segment(4,date("Y-m-d", strtotime($dates['from']) + 6 * 24* 60 * 60));

        $data['report_name']=$this->Reports_model->getMyReportDescriptionSummary($dates);

        $data['title'] = "My Report Name Description";
        //view in 'view/report' folder to use
        //name of view always the same as name of function
        $data['main'] = "report/my_report_name";
        $data['menuReport'] = "class='current'";
        $data['panel'] = "panel/panel";

        $this->load->vars($data);
        //load template
        $this->load->view('template/t_main_full', $data);

    }

In my Model:

function getMyReportDescriptionSummary($dates)
    {
        $this->db->select("some_data,
                           some_data_2,
                           some_data_3"
                          );
        $this->db->join("table1");
        $this->db->join("table2");
        $this->db->where("some_params");
        $Q = $this->db->get();

        if($Q->num_rows() > 0)
        {
            return $Q->result_array();
        }
        else
        {
            return false;
        }
    }

In my repots layout page:

//function to check permissions
<? if($this->Model_Users->accessVerify('my_report_name')) {?>

My report

<?}?>


texts:
I'm learning websockets and wanted to make a websocket onmessage logger which writes the received data in a mongodb.

I'm starting my script with

node listner.js

listner.js:

'use strict';

let DBAbstract = require('./db-controller');
const WebSocket = require('ws');

// getting an instance of a mongodb connection
let mongoInstance = new DBAbstract();

const ws = new WebSocket('ws://ws-url');

ws.onopen = function() {
  console.log('Open')
};
ws.onmessage = function(d) {
  console.log(d.data)
  mongoInstance.insertOne(JSON.parse(d.data)) //Promise which add the data
};

ws.onclose = function() {
  console.log('Close')
  //maybe a reconnect attempt ?
};

ws.onerror = function(e) {
  console.log(e.code)
};

I made this script so far and it works.

When there is an onmessage Event I'm getting a small JSON like this.

{ "event":2,
  "value": 12,
  "item": 'Spoon' }

I was just wondering if this is might be enough in terms of scalability of the received onmessage Events.

I mean there is no problem when I receive three times of small-JSON's in 10 seconds. What will happen when I'm receiving 1000 small-JSON's in 10 seconds ?

Can I improve this code ?


texts:
I've decided to implement a simple smart pointer:

#pragma once
//simple and basic reference by Aldrigo Raffaele
#include "Common.h"
#include "Exceptions.h"

class MemWrp {
        private:
        uint numref;
        public:
        void* content;

        MemWrp(void* content) {
                this->content = content;
                numref = 1;
        }

        void AddRef() { numref++; }
        uint RemoveRef() { return --numref; }

        destructor MemWrp() { delete content; }
};

template< class T >
class Ref {
        private:
        MemWrp* wrp = NULL;
        public:
        Ref() {}
        Ref(T* ptr) {
                wrp = NULL;
                if (ptr != NULL) wrp = new MemWrp(ptr);
        }
        Ref(const Ref<T>& r) {
                wrp = r.wrp;
                if (wrp != NULL) wrp->AddRef();
        }
        Ref(MemWrp* w) {
                wrp = w;
                wrp->AddRef();
        }

        T* Get() const {
                if (wrp == NULL) return NULL;
                return (T*)wrp->content;
        }

        template<class F>
        bool is() { return dynamic_cast<F*>(Get()) != NULL; }

        template<class F>
        Ref<F> as() {
                if (!this->is<F>()) return Ref<F>::Ref();
                return Ref<F>::Ref(this->wrp);
        }

        Ref<T>& operator=(Ref<T>& rhs) {
                if (this == &rhs) return *this;
                if (rhs.wrp == NULL && wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
                wrp = rhs.wrp;
                if (wrp != NULL) wrp->AddRef();
                return *this;
        }

        Ref<T>& operator=(T* rhs) {
                if (Get() == rhs) return *this;
                if (rhs == NULL && wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
                else if (rhs != NULL) wrp = new MemWrp(rhs);
                return *this;
        }

        bool operator==(const Ref<T>& other) const {
                return (this->Get() == other.Get());
        }

        bool operator==(const int other) const {
                return (this->Get() == (void*)other);
        }

        bool operator!=(const Ref<T>& other) const {
                return !(*this == other);
        }

        bool operator!=(const int other) const {
                return !(*this == other);
        }

        T* operator->() {
                if (this->Get() == NULL) throw NullPointerException();
                return this->Get();
        }
        const T* operator->() const {
                if (this->Get() == NULL) throw NullPointerException();
                return this->Get();
        }

        destructor Ref() {
                if (wrp != NULL && wrp->RemoveRef() == 0) delete wrp;
        }
};

What do you think?  How can I subdivide it into .h and .cpp?


texts:
Wondering if this is fully in C++, and if not can someone help me tell the differences. This was submitted by me last semester, and received a good grade. I'm currently trying to ensure I can tell C++ and C apart.

#include <fstream>
#include <stack>
#include <stdlib.h>  //Not neccessary in C++
#define swap(type, a, b) {type t = a; a = b; b = t;}
using namespace std;

typedef struct {
    int degree, *adjList, //arraySize = degree
        nextToVisit, //0 <=nextToVisit < degree
        parent, dfLabel, nodeName;
} GraphNode;

int numNodes, startNode = 1;
GraphNode *nodes;

void readGraph();
void depthFirstTraverse(int startNode);

int main() {
    readGraph();
    depthFirstTraverse(startNode);
}

void depthFirstTraverse(int startNode) {
    int nextNode, dfLabels[numNodes], nextToVisit[numNodes], parents[numNodes], lastDFLabel = 0;
    stack<int> stackArray;
    for (int i = 0; i < numNodes; i++) dfLabels[i] = nextToVisit[i] = 0;
    stackArray.push(startNode);
    printf("startNode = %d, dfLabel(%d) = %d\n",startNode,startNode,1);
    while (!stackArray.empty()) {
        if (0 == dfLabels[stackArray.top()]) {
            lastDFLabel++;
            dfLabels[stackArray.top()] = lastDFLabel; }
        if (nextToVisit[stackArray.top()] == nodes[stackArray.top()].degree) {
            if (lastDFLabel < numNodes) {
                printf("backtracking %d", stackArray.top());
                stackArray.pop();
                printf(" -> %d\n", stackArray.top()); }
            else { printf("backtracking %d -> %d\n", stackArray.top(), startNode);
                stackArray.pop(); }
        }
        else { nextNode = nodes[stackArray.top()].adjList[nextToVisit[stackArray.top()]];
            nextToVisit[stackArray.top()]++;
            if (0 == dfLabels[nextNode]) {
                parents[nextNode] = stackArray.top();
                printf("processing (%d, %d): tree-edge, dfLabel(%d) = %d\n",
                    stackArray.top(), nextNode, nextNode, lastDFLabel+1);
                stackArray.push(nextNode); }
            else if (dfLabels[nextNode] < dfLabels[stackArray.top()]) {
                if (nextNode != parents[stackArray.top()])
                    printf("processing (%d, %d): back-edge\n", stackArray.top(), nextNode);
                else printf("processing (%d, %d): tree-edge 2nd-visit\n", stackArray.top(), nextNode); }
            else printf("processing (%d, %d): back-edge 2nd-visit\n", stackArray.top(), nextNode);
        }
    } for (int i = 0; i < 30; i++) printf("-");
}

void readGraph() {
    char ignore;
    ifstream digraph("digraph.data");
    digraph >> numNodes;
    nodes = new GraphNode[numNodes];
    for (int i = 0; i < numNodes; i++) {
        digraph >> nodes[i].nodeName >> ignore >> nodes[i].degree >> ignore;
        nodes[i].adjList = new int[nodes[i].degree];
        for (int j = 0; j < nodes[i].degree; j++) digraph >> nodes[i].adjList[j];
    } digraph.close();
    printf ("Input Graph:\nnumNodes = %d\n", numNodes);
    for (int i = 0; i< numNodes; i++) {
        printf("%d (%d): ", nodes[i].nodeName, nodes[i].degree);
        for (int j = 0; j < nodes[i].degree; j++)
            for (int k = 0; k < j; k++)
                if (nodes[i].adjList[j] < nodes[i].adjList[k])
                    swap(int, nodes[i].adjList[j], nodes[i].adjList[k]);
        for (int j = 0; j < nodes[i].degree; j++) printf("%d ", nodes[i].adjList[j]);
        printf("\n");
    } for (int i = 0; i < 30; i++) printf("-");
    printf ("\n");
}


texts:
Here's my solution for finding the digital root of a number. Just for purposes of completion, a digital root is:

  "If you take the digits of any number and add them together, and then
  add the digits of the resulting number together, and continue doing
  that until you get a single digit, that single digit is the digital
  root of the original number."

What I was hoping for, is if you guys could take a look and provide a cleaner solution. I'm trying to better myself for an upcoming competition.

import java.util.Scanner;
import java.util.StringTokenizer;

public class DigialRoot {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        System.out.println();

        String str = sc.nextLine();
        String[] numbers = str.split("");
        int[] myList = new int[numbers.length];
        for(int i=0; i < numbers.length; i++){
            myList[i] = Integer.parseInt(numbers[i]);
        }
        //add all numbers together
        int sum = 0;
        for(Integer x : myList){
            sum += x;
        }

        //break down and add sum
        String sumStr = Integer.toString(sum);
        String[] nums = sumStr.split("");
        int[] nxtList = new int[nums.length];
        for(int i=0; i < nums.length; i++){
            nxtList[i] = Integer.parseInt(nums[i]);
        }

        //calculating final result of digital root
        int result = 0;
        for(Integer x : nxtList){
            result += x;
        }

        System.out.println("Original number: " + str);
        System.out.println("Digital root: " + result);

    }

}


texts:
I have a function that converts an integer to its binary representation. I am wondering if there is any way I can improve the function.

 public List<string> Conversion(int x)
    {
        var bitConversion = new List<string>();
        var result = x;
        while (result >= 0)
        {
            if (result == 0)
            {
                bitConversion.Add("0");
                break;
            }
            bitConversion.Add((result % 2).ToString(CultureInfo.InvariantCulture));
            result = result / 2;

        }
       bitConversion.Reverse();

       return bitConversion;
    }


texts:
As a beginner, I tried to implement TicTacToe in Haskell. How can I improve my code?

I have refactored my code: General TicTacToe in Haskell

Utils

module Data.List.Utils where

import Data.List (intersperse)

surround :: a -> [a] -> [a]
surround x ys = x : intersperse x ys ++ [x]

nth :: Int -> (a -> a) -> [a] -> [a]
nth _ _ [] = []
nth 0 f (x:xs) = f x : xs
nth n f (x:xs) = x : nth (n - 1) f xs

TicTacToe

module TicTacToe where

import Data.List (transpose)
import Data.Foldable (asum)
import Data.List.Utils (nth, surround)

data Tile = Empty | O | X deriving (Show, Eq)

showTile :: Tile -> String
showTile Empty = " "
showTile O     = "O"
showTile X     = "X"

type Board = [[ Tile ]]

showBoard :: Board -> String
showBoard = unlines
          . surround vert
          . map (concat . surround horiz . map showTile)

    where vert  = "+-+-+-+"
          horiz = "|"

whoWon :: Board -> Maybe Tile
whoWon xs = asum . map winner $ diag : anti : rows ++ cols

    where rows = xs
          cols = transpose xs
          diag = zipWith (!!) xs [0..]
          anti = zipWith (!!) xs [2,1..]

          winner [O, O, O] = Just O
          winner [X, X, X] = Just X
          winner _         = Nothing

fillTile :: Int -> Int -> Tile -> Board -> Board
fillTile row col = nth row . nth col . const

isOver :: Board -> Bool
isOver = all (all (/= Empty))

overMsg :: Maybe Tile -> String
overMsg (Just x) = "Winner: " ++ (showTile x)
overMsg Nothing  = "Game Over! No winner."

inRange :: Int -> Bool
inRange x = x >= 0 && x <= 2

gameLoop :: Tile -> Board -> IO ()
gameLoop player board
    | isOver board || winner /= Nothing = putStrLn $ overMsg winner
    | otherwise    = do

        putStrLn $ showBoard board
        putStrLn $ "Now player " ++ showTile player

        putStr "Row: "
        row <- fmap read getLine

        putStr "Col: "
        col <- fmap read getLine

        if inRange row && inRange col && (board !! row !! col == Empty)

            then gameLoop (if player == O then X else O) $
                     fillTile row col player board

            else do
                putStrLn "Invalid position, please try again."
                gameLoop player board

    where winner = whoWon board

startBoard :: Board
startBoard = replicate 3 (replicate 3 Empty)

main = gameLoop O startBoard


texts: Javascript class to geocode Dutch addresses

texts:
I am relatively new to javascript ES6, the code I've written is working fine. However I am curious if this would be the best approach. I am trying to write a reusable module that I can use in multiple projects. On top of an API I've written a simple module to geocode adresses in the Netherlands. The suggest function will provide related adresses to a specific query. The lookup function provides information about a specific adress.

class Geocoder {
    // Class to geocode adresses to coordinates or find related adresses
    // suggest(), lookup() both return a promise
    // geocoder.lookup('adr-54e85361e27f833dd8331fd85bc46ac6').then((data) => {console.log(data)});

    constructor() {
        this.url = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/";
    }

    async suggest(query) {
        let url = `${this.url}suggest?q=${query}`;
        return await this._get(url);
    }

    async lookup(id) {
        let url = `${this.url}lookup?id=${id}`;
        return await this._get(url);
    }

    _get(url) {
        return new Promise ((resolve, reject) => {
            fetch(url).then((response) => {
                return response.json();
            }).then((json) => {
                resolve(json);
            }).catch((err) => {
                reject(err);
            })
        })
    }
}


texts:
I've created a form to choose the settings. These settings are automatically saved in a file from the game client in this form:

["Setting"] = {
    ["track"] = "Water Shield",
    ["duration"] = {
        ["minimum"] = {
            ["enabled"] = 1,
            ["value"] = 50,
        },
        ["maximum"] = {
        },
    },
    ["stack"] = {
        ["minimum"] = {
        },
        ["maximum"] = {
            ["enabled"] = 1,
            ["value"] = 2,
        },
    },
}

I had previously asked a similar question on how to save the data, but now to load the data I created this function:

function loadSettings()
    local options = { 'duration', 'stack' }
    for i=1, #options do
        local option = options[i]

        if not db[option] then
            db[option] = { minimum = {}, maximum = {} }
        end

            local enabled
            local value

            enabled = db[option].minimum.enabled
            if (enabled) then _G["min"..option].cbutton:SetChecked(1) else _G["min"..option].cbutton:SetChecked(0) end
            value = db[option].minimum.value
            if (value) then _G["min"..option].ebox:SetText(value) else _G["min"..option].ebox:SetText("\00") end

            enabled = db[option].maximum.enabled
            if (enabled) then _G["max"..option].cbutton:SetChecked(1) else _G["max"..option].cbutton:SetChecked(0) end
            value = db[option].maximum.value
            if (value) then _G["max"..option].ebox:SetText(value) else _G["max"..option].ebox:SetText("\00") end

    end
end

Where

db = The "Setting" table
SetChecked(enable) = True to check the button; false to uncheck (boolean)
SetText("text") = Text to be placed in the edit box (string)

Could you help me to make the code less repetitive and more clean and elegant?


texts:
The following code converts a number into Indian numbering system format.

I know locale can also help in getting similar format but I wanted something that can work on any system because not all locales are present in all OSs.

The code was written for Python 3.5 hence no variable annotations.

from decimal import Decimal
from itertools import islice, zip_longest
from typing import Any, Iterable, Iterator, Sequence, Tuple, TypeVar, Union  # noqa: ignore=F401

_T = TypeVar('_T')

def grouper(iterable: Iterable[_T], n: int, fillvalue: Any = None) -> Iterator[Tuple[_T, ...]]:
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)

def indian_numbering_format(
    amount: Union[Decimal, int, str], places: int = 2,
    curr: str = '', pos: str = '', neg: str = '-'
) -> str:
    """
    Formats a number and returns it in Indian numbering format
    https://en.wikipedia.org/wiki/Indian_numbering_system

    places:  optional number of places after the decimal point
    curr:    optional currency symbol before the sign
    pos:     optional sign for positive numbers: '+' or blank
    neg:     optional sign for negative numbers: '-' or blank

    Note that if the fractional part only contains 0 it will be
    dropped.
    """
    q = Decimal(10) ** -places  # type: Decimal
    amount = Decimal(amount).quantize(q)
    sign, digits, exponent = amount.as_tuple()
    integer_part, fractional_part = (), ()  # type: Sequence[int], Sequence[int]
    exponent = exponent or len(digits)
    integer_part = digits[:exponent]
    # If fractional part only contains 0s then ignore it.
    if set(digits[exponent:]) != {0}:
        fractional_part = digits[exponent:]
    integer_part_digits = reversed(''.join(map(str, integer_part)))
    thousand = ''.join(islice(integer_part_digits, 3))[::-1]
    hundreds = ','.join(map(''.join, grouper(integer_part_digits, 2, fillvalue='')))[::-1]
    sep = ',' if hundreds else ''
    fractional_part_digits = '.' + ''.join([str(d) for d in fractional_part]) if fractional_part else ''
    return '{sign}{curr}{hundreds}{sep}{thousand}{fractional_part}'.format(
        sign=neg if sign else pos,
        curr=curr,
        thousand=thousand,
        sep=sep,
        hundreds=hundreds,
        fractional_part=fractional_part_digits
    )

I was wondering if the code can be refactored in any way to make it much more simpler.


texts: Optimizing this method (HashSet.RemoveWhere performance issue)

texts:
I have the following method:

public static HashSet<PathDetails> GetDeletedPaths(HashSet<PathDetails> old, HashSet<PathDetails> current)
{
    var deleted = new HashSet<PathDetails>(old);
    deleted.RemoveWhere(x => current.Any(y => y.Path == x.Path));
    return deleted;
}

PathDetails is a struct that, among other things, contains Path of type String. This method takes the longest in my application and I was wondering if there were any good ways of improving its performance. These hash sets are used elsewhere in a more hashset-friendly way, so the method must take in two sets and return a set.


texts: Determining the maximum value that can be obtained from a loot

texts:
A thief finds much more loot than his bag can fit. We have to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag.

For example has a bag which can fit at most 50 Kg of items. He has 3 items to choose from: the first item has a total value of $60 for 20 Kg, the second item has a total value of $100 for 50 Kg and the last item has a total value of $120 for 30 Kg.

So, if the thief takes the most of the item that costs more per unit Kg, he/she can make a better profit out of his/her thievery. In that case, he/she would take 30 Kgs of the third item, and 20 Kgs of the first item, resulting in a total of 50 Kgs (full capacity) with the total value of $180.

// THIS IS AN EXAMPLE OF THE FRACTIONAL KNAPSACK PROBLEM

#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
double get_max_index(vector<int>, vector<int>);
double get_max_value(vector<int>, vector<int>, int);

int main() {

    int num_items, bag_capacity;
    cout << "Enter the number of items: " << endl;
    cin >> num_items;
    cout << "Enter the total capacity that the bag can support: " << endl;
    cin >> bag_capacity;

    vector<int> values;
    vector<int> weights;

    for (int i = 0; i < num_items; i++)
    {
        int buff_val = 0, buff_wgt = 0;
        cout << "Enter the value and weight of Item " << i + 1 << ": " << endl;
        cin >> buff_val >> buff_wgt;
        values.push_back(buff_val);
        weights.push_back(buff_wgt);
    }

    cout.precision(10);
    cout << "The maximum loot value that can be acquired is " << fixed << get_max_value(values, weights, bag_capacity) << "." << endl;          // Always display 'precision' number of digits

    return 0;
}

double get_max_index(vector<int> vals, vector<int> wgts){
    int max_index = 0;
    double max_val_per_wgt = 0;
    for (int i = 0; i < wgts.size(); i++)
    {
        if (wgts[i] != 0 && (double) vals[i] / wgts[i] > max_val_per_wgt)
        {
            max_val_per_wgt = (double) vals[i] / wgts[i];
            max_index = i;
        }
    }
    return max_index;
}

double get_max_value(vector<int> vals, vector<int> wgts, int capacity){

    double max_val = 0.0;
    for(int i = 0; i < wgts.size(); i++) {
        if (capacity == 0)
        {
            return max_val;             // There's no space left in the bag to carry
        }
        int max_value_index = get_max_index(vals, wgts);     // See which item has the best value per weight index
        double taken = capacity > wgts[max_value_index] ? wgts[max_value_index] : capacity;     // get the minimum of the item's weight and capacity left in the bag
        max_val += taken * (double) vals[max_value_index] / wgts[max_value_index];      // calculate value for the item's weight taken
        capacity -= taken;          // reduce capacity of the bag by the amount of weight of item taken
        wgts[max_value_index] -= taken;         // reduce the item's weight by the amount taken
    }
    return max_val;
}

Please review this code in terms of complexity or in other areas that might result in this code failing. Also, looking forward to criticism and if you decide to post criticism, kindly include relevant details that a not-so-experienced programmer might find helpful in solving the problem.


texts:
I created a simple program to simulate the Ant's path.  The Ant moves north, west, east and south. Each time the Anth moves to an "uncharted" location, I build a Square and give it a color. Each time the Ant steps in a square, the square changes color and the Ant rotates 90° and keeps her track. I use a Stack where I push my Squares. The steps list is something I need to keep track of the path of the Ant. I need to find when the Path stabilizes (Roughly after 10000 steps) and the Ant moves in a uniform manner.

It works great until 106 (takes 5 minutes to run). After that it takes more than 14 hours to get to the 107 mark. I don't get why it takes so much more time, shouldn't it just take 10 × time it took to get to 106 iterations assuming my algorithm is o(n)?

I would like to keep the approach single threaded.  What can I optimize?

enum Orientation{
  NORTH, WEST, SOUTH, EAST
}

public class Square {
        public int x, y;
        // White = 0, Black = 1
        public int color = 0;
}

int color = 0;
int x = 0, y = 1;
Stack<Square> squares = new Stack<Square>();
Orientation orientation = Orientation.NORTH;
List<Orientation> steps = new List<Orientation>();
for (int i = 0, counter = 0; i < 10000000; ++i, ++counter)
{

    // First
    if(i == 0)
    {
        squares.Push(new Square() { x = 0, y = 1, color = 1 });
        // Rotate
        orientation = Rotate(orientation, color == 0 ? true : false);
        steps.Add(orientation);
        continue;
    }
    // Move step
    if (orientation == Orientation.NORTH) y += 1;
    if (orientation == Orientation.EAST) x -= 1;
    if (orientation == Orientation.WEST) x += 1;
    if (orientation == Orientation.SOUTH) y -= 1;

    // Check what the step has
    Square s = squares.Where(square => square.x == x && square.y == y).DefaultIfEmpty(null).FirstOrDefault();

    // if null create one and rotate
    if (s == null)
    {
        squares.Push(CreateSquare(x, y, 1));
        orientation = Rotate(orientation, true);
        steps.Add(orientation);
    }else if(s.color == 1)
    {
        s.color = 0;
        orientation = Rotate(orientation, false);
        steps.Add(orientation);
    }else
    {
        s.color = 1;
        orientation = Rotate(orientation, true);
        steps.Add(orientation);
    }

    // 10^6 mark
    if (i == 999999)
    {
            blackSquaresAt100k = squares.Where(sqa => sqa.color == 1).Count();
            Console.WriteLine(blackSquaresAt100k);
    }

    // 10^7 mark
    if (i == 9999999)
    {
        blackSquaresAt1M = squares.Where(sqa => sqa.color == 1).Count();
        int totalNrOfBlackSquares = (blackSquaresAt1M - blackSquaresAt100k) * 12 + blackSquaresAt1M;
        Console.WriteLine(totalNrOfBlackSquares);
    }
}


texts: Function to determine the appropriate dimensions for a close button

texts:
How can I reduce the cyclomatic complexity of this CloseButtonDimensions function?

export function isMobile():boolean {
    return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|iemobile|Windows Phone/i.test(navigator.userAgent) );
}

get CloseButtonDimensions(): Size {
    const IS_MOBILE: Boolean = isMobile();

    let mediaType:String     = this.options.tag.media_type;
    let adWidth:number       = this.options.tag.size.width;
    let adHeight:number      = this.options.tag.size.height;

    let closeButtonHeight:number;
    let closeButtonWidth:number;

    if( (mediaType == "VIDEO") && !IS_MOBILE && ((adWidth >= 640 && adHeight >= 480) || (adWidth >= 480 && adHeight >= 360)) ) {
        closeButtonWidth  = 15;
        closeButtonHeight = 15;
    } else if( ((mediaType == "VIDEO")  && (adWidth >= 300 && adHeight >= 250)) ||
               ((mediaType == "BANNER") && (adWidth == 300 && adHeight == 250)) ||
               ((mediaType == "BANNER") && !IS_MOBILE && (adWidth == 468 && adHeight == 60)) ) {
        closeButtonWidth  = 11;
        closeButtonHeight = 11;
    } else if( (mediaType == "VIDEO")  &&  IS_MOBILE && (adWidth >= 320 && adHeight >= 240) ||
               (mediaType == "BANNER") && !IS_MOBILE && (adWidth == 728 && adHeight == 90) ) {
        closeButtonWidth  = 13;
        closeButtonHeight = 13;
    } else if((mediaType == "BANNER") && !IS_MOBILE && (adWidth == 468 && adHeight == 60)) {
        closeButtonWidth  = 13;
        closeButtonHeight = 13;
    } else if( (mediaType == "BANNER") && IS_MOBILE && ((adWidth == 320 && adHeight == 50) || (adWidth == 300 && adHeight == 50)) ) {
        closeButtonWidth  = 8;
        closeButtonHeight = 8;
    }

    return {
        width: closeButtonWidth,
        height: closeButtonHeight
    }
}

mediaType that I can get in the function are VIDEO and BANNER.

Ad dimensions (widthxheight) for video are (these can be greater than or equal to):

Desktop: "640x480", "480x360", "300x250"
Mobile:  "300x250", "320x240"

Ad dimensions (widthxheight) for banner are (these will be exact not greater nor equal):

Desktop: "728x90", "468x60", "300x250"
Mobile:  "300x250", "320x50", "300x50"

IS_MOBILE will be true/false depending on the device.

Questions:

How can I approach such complex if else statements while coding?
How can I make code more readable especially for junior developers or when I make commits to repos so others can understand better?


texts: Lattice path from Project Euler with Python solution

texts:
I was trying to solve this problem called lattice path from Project Euler:

  Count the number of unique paths to travel from the top left to the bottom right of a lattice of squares.

How many such routes are there through a 20×20 grid? It takes me forever to get an answer...

(source: projecteuler.net)

    #  Input:     An interger N (which is the size of the lattice)
    #  Output:    An interger (which represents the number of unique paths)
    #
    #  Example:   input: 2
    #
    #             (2 x 2 lattice of squares)
    #              __ __
    #             |__|__|
    #             |__|__|
    #

When moving through the lattice, you can only move either down or to the right.

I currently have 1 solution, and I am not sure how much better if we memoize it. But I wanted to ask for code review for my solution below:

def lattice_paths(m, n):
    if m == 0 and n == 0:
        return 1
    if m < 0 or n < 0:
        return 0
    return lattice_paths(m - 1, n) + lattice_paths(m, n - 1)

Here is the time complexity and space complexity of my first solution.
# Time Complexity: O(2^(M+N))
# Auxiliary Space Complexity: O(M+N)

Dynamic approach with the memorized solution:

def lattice_paths(m, n): # m rows and n columns

    def helper(x, y):

      if x > helper.m or y > helper.n:
        return 0
      if helper.cache.get((x, y)) is not None:
        return helper.cache[(x, y)]

      helper.cache[(x, y)] = helper(x + 1, y) + helper(x, y + 1)
      return helper.cache[(x, y)]
    helper.cache = {}

    helper.m = m
    helper.n = n
    helper(0,0)

    if m  ==  0 and n == 0:
      return 1
    elif m < 0 or n < 0:
      return 0
    else:
      return helper.cache[(0, 0)]


texts:
I had a file that looked like this:

Mar 06 22:00:00 [10.251.132.246] logger: 10.64.69.219 - - [06/Mar/2011:22:.....
Mar 06 22:00:00 [10.251.132.246] logger: 10.98.137.116 - - [06/Mar/2011:22:0....

that I wanted to split into smaller files using the ip address after "logger"

This is what I came up with:

file = ARGV.shift
split_file = {}
pattern = /logger: ([^\s]*)/
File.open(file, 'r') do |f|
    f.each do |l|
        match = l[pattern]
        if match
            list = split_file[$1]
            list = [] if list == nil
            list << l
            split_file[$1] = list
        end
    end
end

split_file.each_pair do |k, v|
    File.open("#{file}.#{k}", "a+") do |f|
        v.each do |l|
            f.print l
        end
    end
end

Suggestions, warnings, improvements are very welcome :)

One thing I noticed is that the new files are created in the same directory as the original file, not at the current working directory (so ./logsplitter.rb ../log.log creates files in the .. directory).

Thank you

[edit: typo]


texts: Displaying a letter grade based on a percentage

texts:
Here is a class I made that is able to ask a teacher what percentage their student has in a class and gives them back a grade. The code is very repetitive and I am wondering what I can do to simplify the class below before inputting any more grades.

import java.util.Scanner;

public class Grades{
    public static void main(String [] args){
        Scanner grades = new Scanner(System.in);

        int x = 0;

        System.out.print("What is the percentage of the student: ");
        x = grades.nextInt();

        if (x > 100 || x < 0){
                System.out.println("Please put in a percent from 0 - 100!\n");
        }

        while (x > 100 || x < 0 ){

            System.out.print("What is the percentage of the student: ");
            x = grades.nextInt();
            if (x > 100 || x < 0){
                System.out.println("Please put in a percent from 0 - 100!\n");
            }
        }
        if (x <= 100 && x >= 96){
             System.out.print("A+");
        }
         if (x <= 95 && x >= 92){
             System.out.print("A");
        }
         if (x <= 91 && x >= 90){
             System.out.print("A-");
        }
         if (x <= 89 && x >= 50){
             System.out.print("B+");
        }
         if (x <= 49 && x >= 0){
             System.out.print("B");
        }
        // so on and so forth down the grading scale
    }
}


texts:
I have written a code in Haskell that calculates the determinant of a matrix using the laplace expansion.
As I have just started learning Haskell, I would like some opinions on how well (structured) the code is written and where I could be able to boost the performance.

This is the code:

det :: (Num a, Ord a) => [[a]] -> a
det [[]] = error "Cannot calculate Det from [[]]"
det x
    | lfex /= lx                     = error "Cannot calculate Det from non square matrix"
    | lfex == 2 && (length s) == 2    = a*d - b*c
    | otherwise = foldl (\acc y -> let ind = index y in
                                      acc + (sign ind) * f!!ind * (det $ genLaplaceMatrix x ind)) 0 [0 .. lx-1]
    where
          [[a,b],[c,d]] = x
          f:s:xr = x
          lx      = length x
          lfex    = length f
          sign y  = (-1)^(1+lx-y)
          index y = lx-1-y

--pivotrow = 1
--pivotcol 0 based!
genLaplaceMatrix :: (Num a) => [[a]] -> Int -> [[a]]
genLaplaceMatrix (_:x) pivotCol = foldr (\y -> (conVecs y:)) [] [0..((length x)-1)]
    where
      parts vec = splitAt pivotCol vec
      conVecs row = let y = x!!row in (fst $ parts y) ++ (tail $ snd $ parts y)

It can also be found here.

I already looked at this question and tried to implement it as good as possible. Do you have any further advice?


texts:
I'm solving a problem on HackerRank where I'm required to implement a simple stack.

It's passing all the tests except for the last 4 where it fails due to surpassing the time constraint of 10s.  These 4 failing tests are running 200,000 operations on the stack.
How can I optimize my code below:
# operations of the form ['push -36', 'pop', 'push 16', 'pop', 'inc 1 -17', ...]

from collections import deque

def superStack(operations):

    def push(v):
        S.append(int(v))

    def pop():
        return S.pop()

    def inc(i,v):
        i, v = int(i), int(v)
        for pos in range(i):
            S[pos] += v

    S = deque()
    funcs = locals()

    for operation in operations:
        op, *args = operation.split(' ')
        funcs[op](*args)

        print(S[-1] if S else "EMPTY")

A few notes:

Some constraints:

I've chosen deque over list, to avoid the "contiguous memory block" problem that lists  may encounter.

Since pop and append are both O(1), the heaviest operation is the inc (especially so if i is large). So I keep all items as integers to avoid conversion from string to int multiple times in the inc loop


texts:
I wish to create a database for a webpage where users are able to add their own events to a timetable. Users will be able to decide if the events should be recurring (weekly) or not. Users should be able to query other groups of users to organize a time for a meeting. That is it.

What I have so far is as follows:

Users (
  userID INT NOT NULL AUTO_INCREMENT,
  username VARCHAR(80),
  PRIMARY KEY (user_id)
);

Groups {
  GroupID INT NOT NULL AUTO_INCREMENT,
  GroupName NVARCHAR(100)
  private BOOLEAN
}

Membership {
  UserID (FOREIGN KEY, UNIQUE),
  GroupID( FOREIGN KEY, UNIQUE)
 }

Events (
    event_id INT NOT NULL AUTO_INCREMENT,
    title VARCHAR(80) NOT NULL,
    description VARCHAR(200),
    start_time DATETIME,
    end_time DATETIME,
    group_id INT NOT NULL,
    recurring BOOLEAN
);

Group (
    group_id INT NOT NULL,
    user_id INT NOT NULL
);

When a user wants to arrange a meeting using my database, I will be forced to use 3 queries and 2 loops, is there a better way than this? It all seems extremely complicated.

int i = 0;
String[] names = { Request.Form["usernames"]Split(' ') }; //retrieving names from form
List<int> user_ids = new List<int>();
foreach(string name in names){
    int user_id = db.QueryValue("SELECT user_id FROM users WHERE username = name");
    user_ids.Add(user_id); //now I have a list of all user_ids
}
db.Execute("INSERT INTO group(groupName) values(Request.Form["Group name"])");
int groupID = db.QueryValue("SELECT groupid from group where            groupname="Request.Form["Group name "]");
foreach (string user_id in user_ids) {
      db.Execute("INSERT INTO membership(userid,groupid) values(user_id, groupID);"
}


texts: JavaScript function for to toggle multiple CSS-classes at once

texts:
The method toggle of Element.classList expects a parameter which names a CSS-class.

You can't assign multiple classes at once by using for example an array.

So you have to write something like ...

div.classList.toggle("hidden-element");
div.classList.toggle("border-defs");
div.classList.toggle("green-theme");

Therefore I've made an function to which a list of classes can be passed.

var toggleButton = document.querySelector('.toggle-classes');

/**
 * Adds / removes CSS-class(es) from an HTML-element.

 * 1. String: CSS-class or a list of CSS-classes. Within a list
 *   the single values have to be separated by a space.
 * 2. String: A CSS-selector pointing to the HTML-element upon
 *   which the class(es) shall be added / removed.

 * Returns true to indicate success.
 * Throws Error in case of failure.
*/

function toggleClasses(cssSelector, listOfClasses) {
  var element;
  var classes;

  if (arguments.length !== toggleClasses.length)
    throw new Error('Lack of required parameter.');

  if (typeof listOfClasses !== 'string' || listOfClasses.length === 0)
    throw new Error('List of CSS-classes is not valid.');

  classes = listOfClasses.split(/\s/);

  if (typeof cssSelector !== 'string' || cssSelector.length === 0)
    throw new Error('Given CSS-selector is not valid.');

  element = document.querySelector(cssSelector);

  if (element === null)
    throw new Error('No HTML-element with selector ' + cssSelector + ' found.');

  classes.forEach(function(classItem, i) {
    element.className.indexOf(classItem) === -1
      ? element.classList.add(classItem)
      : element.classList.remove(classItem);
  });

  return true
}

// ------ USAGE EXAMPLE --------------------------------------------
var listPos = 'shadows font-special red-theme blue-theme misc-foo';

toggleButton.addEventListener('click', function() {
  try {
    toggleClasses('.demo', listPos);
  } catch (e) {
    console.error(e.message);
  }
});
.wrap {
  margin: 20px auto;
  width: 900px;
  background-color: rgba(245, 245, 245, 1.0);
  padding: 20px 30px;
}

.demo {
  width: 150px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  margin: 10px 0;
}

.blue-theme {
  border: 3px solid pink;
  background-color: teal;
  color: white;
  font-weight: 800;
}

.red-theme {
  border: 3px solid teal;
  background-color: pink;
}

.shadows {
  text-shadow: 3px 3px 3px white;
  box-shadow: 3px 3px 3px grey;
}

.font-special {
  color: grey;
  font-weight: bold;
  font-family: georgia;
}

.misc-foo {
  border-radius: 12px;
  transform: skewY(5deg);
}

  <button class="toggle-classes">Toggle classes</button>

Demonstration

I'm still not sure if I shall stay with the way of assigning the classes. One could also use an array instead of a space-separated string.

Or make it optional?
If an array is assigned then that is used. If an string is assigned then it is separated.

Or would it be rather confusing to offer multiple options and better to stick with just one?

I also ask myself if my approach of throwing errors isn't a bit too drastically.

The CSS-classes are just for styling. So an application could go on with it's main purpose even if the function fails. It isn't really necessary to react so hard. Should I use something else instead? Returning, for example, a specified value?

Any hints and suggestions concerning flaws and possible improvements welcome.


texts: Create a directed graph and compute in degrees in Python

texts:
I have implemented a couple of functions in python as part of an online course. Although the functions seem to work fine I feel that the code is inefficient with a lot of nested loops. Are there any improvements I can make? I am new to the language so any advice is welcome.

Here is the code and some simple tests:

def make_complete_graph(num_nodes):
    """
    Takes the number of nodes num_nodes
    and returns a dictionary corresponding to a complete directed graph
    with the specified number of nodes
    """

    result = dict()
    for i in range(num_nodes):
        set_per_node = set()
        for num in range(num_nodes):
            if num != i:
                set_per_node.add(num)
        result[i] = set_per_node

    return result

def compute_in_degrees(digraph):
    """
    Takes a directed graph digraph (represented as a dictionary) and computes
    the in-degrees for the nodes in the graph.
    Returns a dictionary with the same set of keys (nodes) as digraph
    whose corresponding values are the number of edges
    whose head matches a particular node.
    """
    result = dict()
    count = 0
    for key in digraph:
        count = 0
        for key2, value in digraph.iteritems():
            if key != key2:
                for val in value:
                    if val == key:
                        count += 1
        result[key] = count
        count = 0

    return result

class TestStringMethods(unittest.TestCase):

    def test_make_complete_graph(self):
        expected_dict_one = {0: set([1, 2]), 1: set([0, 2]), 2: set([0, 1])}
        expected_dict_two = {}

        actual_dict_one = at_project1.make_complete_graph(3)
        actual_dict_two = at_project1.make_complete_graph(0)

        self.assertEquals(actual_dict_one, expected_dict_one)
        self.assertEquals(actual_dict_two, expected_dict_two)

    def test_compute_in_degrees(self):
        given_dict_one = {0: set([1, 2]), 1: set([0, 2]), 2: set([0, 1])}
        given_dict_two = {0: set([1, 2]), 1: set([]), 2: set([])}

        expected_dict_one = {0: 2, 1: 2, 2: 2}
        expected_dict_two = {0: 0, 1: 1, 2: 1}

        actual_dict_one = at_project1.compute_in_degrees(given_dict_one)
        actual_dict_two = at_project1.compute_in_degrees(given_dict_two)

        self.assertEquals(actual_dict_one, expected_dict_one)
        self.assertEquals(actual_dict_two, expected_dict_two)

if __name__ == '__main__':
    unittest.main()


texts:
I am trying to make a loading screen but my code isn't DRY.  How could I make it DRY? I have thought about using CSS3 keyframes but I might have problems cross-platform.

$(document).ready(function() {

var lc = $('.loaderContainer'),
    wh = $('.welcomeH'),
    th = $('.toH'),
    meeuh = $('.meeuH'),
    se = $('.siteEnter'),
    sc = $('.seContainer');

lc.delay(3500).fadeOut('slow');
wh.delay(3800).fadeIn('slow').delay(2000).fadeOut('slow');
th.delay(6800).fadeIn('slow').delay(2000).fadeOut('slow');
meeuh.delay(9800).fadeIn('slow');

sc.delay(11800).queue(function(){
    sc.css('left', '-120%');
    sc.dequeue();
});

se.delay(12000).queue(function(){
    se.css('margin-left', '-120%');
    se.dequeue();
});
});

I have tried to use callbacks, but I don't know if I have done it correctly. I have only done callbacks to the first block of code, not the second two; I'm still stuck on it.

lc.delay(3500).fadeOut(400, function() {
    wh.delay(800).fadeIn(400, function() {
        $(this).delay(800).fadeOut(400, function() {
            th.delay(800).fadeIn(400, function() {
                $(this).delay(800).fadeOut(400, function() {
                    meeuh.delay(800).fadeIn(400)
                });
            });
        });
    });
});

sc.delay(12000).queue(function(){
    sc.css('left', '-120%');
    sc.dequeue();
});

se.delay(12300).queue(function(){
    se.css('margin-left', '-120%');
    se.dequeue();
});


texts: Function to check truth value of a specific statement

texts:
I want to check the truth of A + B - (A & B) == A | B for N-bit numbers. For example, here's a "truth" table for 2-bit numbers. (I know I'm taking liberty with the concept of a "truth" table.)

Here's the simple code I threw together in Python.

def check_truth(bits):

    for x in range(2**bits):
        for y in range(bits*2):
            if x + y - (x & y) != x | y:
                return "False for {} bits".format(bits)

    return "True for {} bits".format(bits)

It spits out the correct answer, but it's obviously really inefficient. I am not good at algorithm analysis, but it's something like \$O(2^N)\$ right?

It's pretty much just a one-time-use function, but I'm curious how it could be improved. For example, I figure you could skip over number pairs that had been tested before. Any other ideas?


texts: Standard way of reading file contents to a buffer

texts:
I have been trying to write a sample code block to read file contents into a buffer.

I am assuming that:

Code must be platform independent
Should work in all cases(or report proper error)
It should be readable and maintainable
It shouldn't be over-complex and shouldn't have errors

Do you think the return of fseek should be tested as well?

void
die( int error_code, char* message )
{
    fprintf( stderr, message );
    exit( error_code );
}

char *
read_certificate_file ( char *file_location )
{
    FILE *file_descriptor = NULL;
    size_t file_size = 0;
    size_t bytes_read = 0;
    char *certificate_content = NULL;
    file_descriptor = fopen ( file_location, "r" );
    if ( file_descriptor == NULL ) {
        perror ( "Opening certificate file" );
        die ( EXIT_FAILURE, "Error opening certificate file." );
    }
    fseek (file_descriptor, 0, SEEK_END);
    file_size = ftell ( file_descriptor );
    if ( file_size == 0 ) {
        fclose ( file_descriptor );
        die ( EXIT_FAILURE, "Certificate file is empty." );
    }
    certificate_content = (char *) malloc ( file_size+1 );
    if ( certificate_content == NULL ) {
        fclose( file_descriptor );
        die( EXIT_FAILURE, "Error allocating memory for " \
                          " certificate." );
    }
    certificate_content[ file_size ] = '\0';
    fseek ( file_descriptor, 0, SEEK_SET );
    bytes_read = fread ( certificate_content, 1, file_size,
                         file_descriptor );
    if ( bytes_read != file_size ) {
            perror ( "Reading Certificate file" );
            fclose( file_descriptor );
            die ( EXIT_FAILURE, "Error reading "
                                "certificate file." );
    }
    fclose ( file_descriptor );
    return certificate_content;
}

int main()
{
    printf( "%s", read_certificate_file ( "./certificate.pem" ));
    return EXIT_SUCCESS;
}


texts:
I've built a custom control that generates a tab style navigation.  Each page might have different tabs to display, the aim was to modularise it so I can make global changes to all the tabs.

TabMenu.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TabMenu.ascx.cs" Inherits="TabMenu" %>

<asp:Panel runat="server" ID="TabMenuWrapper" CssClass="tabWrapper">

</asp:Panel>

TabMenu.ascx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class TabMenu : System.Web.UI.UserControl
{
    public string TabGroup { get; set; }    // The tab group this control belongs to
    public int SelectedTab { get; set; }    // Index of selected tab

    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList tabCollection = new ArrayList();
        MenuTab myTab;

        // Artorking tab group
        if (this.TabGroup.ToLower() == "artwork")
        {
            myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "First!" };
            tabCollection.Add(myTab);

            myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "Second!" };
            tabCollection.Add(myTab);

            myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "3rd!" };
            tabCollection.Add(myTab);

            myTab = new MenuTab() { linkURL = "artworkHome.aspx", linkText = "Fourth!" };
            tabCollection.Add(myTab);
        }

        // Add tabs to the page
        for (int i = 0; i < tabCollection.Count; i++)
        {
            MenuTab thisTab = ((MenuTab)(tabCollection[i]));
            thisTab.CreateTab();

            if (i == this.SelectedTab)
            {
                thisTab.tabPanel.CssClass = "tab tabSelected";
            }

            TabMenuWrapper.Controls.Add(thisTab.tabPanel);
        }
        TabMenuWrapper.Controls.Add(new Panel(){CssClass = "clear"});

    }
}

// A menu tab
public class MenuTab
{
    public string linkURL;
    public string linkText;
    public HyperLink tabLink;
    public Panel tabPanel;

    // Create internal controls
    public void CreateTab()
    {
        this.tabLink = new HyperLink() { NavigateUrl = this.linkURL, Text = this.linkText };
        this.tabPanel = new Panel() { CssClass = "tab" };
        this.tabPanel.Controls.Add(this.tabLink);
    }
}

Used as follows:

<CrystalControls:TabMenu runat="server" ID="TopMenu" TabGroup="Artwork" SelectedTab="1" />

And renders like:

  First!

  Second!

  3rd!

  Fourth!

Is this a good design?


texts:
Say I have an array with 60 elements, and I want to select 40 elements from this array. The subset should consist of elements with evenly spaced indices. In theory I would need to select every 1.5th point, which is obviously not possible.

I tried doing it with a recursive function, kind of a divide & conquer approach. It selects the point in the middle between two boundaries and adds it to the result, then it splits this range up into two sub-ranges and executes the function again for these ranges:

Private Sub AddMiddlePoint(ByRef data() As Double, ByRef Result As List(Of Double), Lowerindex As Integer, Upperindex As Integer, MaxVals As Integer, MinSize As Integer)
    Dim middle As Integer = CInt((Upperindex + Lowerindex) / 2)
    Dim newBorderLower1 As Integer = Lowerindex
    Dim newBorderUpper1 As Integer = middle
    Dim newBorderLower2 As Integer = middle + 1
    Dim newBorderUpper2 As Integer = Upperindex
    If Result.Count < MaxVals Then
        Result.Add(data(middle))
        If newBorderUpper1 - newBorderLower1 > MinSize Then AddMiddlePoint(data, Result, newBorderLower1, newBorderUpper1, MaxVals, MinSize)
        If newBorderUpper2 - newBorderLower2 > MinSize Then AddMiddlePoint(data, Result, newBorderLower2, newBorderUpper2, MaxVals, MinSize)
    End If
End Sub

I call this function like this:

Private Function ThinOutData(source() As Double, Percentage As Integer) As Double()
    Dim newData As New List(Of Double)
    Dim amount As Integer = CInt(Percentage / 100 * source.Count)
    AddMiddlePoint(source, newData, 0, source.Count - 1, amount, CInt(Int(1 / Percentage) + 1))
    Return newData.ToArray
End Function

It basically works, but the subset that is selected isn't very evenly spaced. Some huge gaps, some small gaps and so on.

Does anyone have a suggestion how this can be improved? I am of course aware that you can't get perfectly even spacing for fractional steps, but my method returns uneven points even if it needs to pull every second or third value from the array.

My code is in VB.NET but feel free to use other languages that you are familiar with. It shouldn't be too hard to translate, I guess.


texts:
I have written the following query to figure out activity streaks on a per-user basis. I find it... Ugly... And would love to improve it!
Limitations
Those are explained as commented text at the very top of the query.
Problems

Can this be done without a loop?

Is there a better way to do this than #TempTables?

Bonus!
If it is possible to do this for multiple users, e.g., a top 10 or top 50, I'll award a 100 rep bounty to whoever solves it first!
/*
There are certain limitations to the usefulness of this query.
It cannot track if a user has just visited the site without "significant" activity
"Significant" would be defined as a Comment, Post, Suggest edit, Approve or Reject edit, Vote on suggested edit, Vote on a post
Also, Up-votes and Down-votes on Posts are anonymous, as such they cannot be included in the query
*/

DECLARE @UserId INT;
SET @UserId = ##UserId##;

-- Temp table to hold all relevant activity dates
CREATE TABLE #UserActiveDays
(
    UserId INTEGER
  , ActivityDate DATE
  , Source VARCHAR(50)
);

INSERT INTO #UserActiveDays
(
    UserId
  , ActivityDate
  , Source
)
  SELECT DISTINCT
      OwnerUserId
    , CAST(CreationDate AS DATE)
    , 'PostCreation'
  FROM Posts
  WHERE OwnerUserId = @UserId
UNION
  SELECT DISTINCT
      UserId
    , CAST(CreationDate AS DATE)
    , 'CommentCreation'
  FROM Comments
  WHERE UserId = @UserId
UNION
  SELECT DISTINCT
      UserId
    , CAST(CreationDate AS DATE)
    , 'PostHistoryCreation'
  FROM PostHistory
  WHERE UserId = @UserId
UNION
  SELECT DISTINCT
      OwnerUserId
    , CAST(CreationDate AS DATE)
    , 'SuggestedEditCreation'
  FROM SuggestedEdits
  WHERE OwnerUserId = @UserId
UNION
  SELECT DISTINCT
      OwnerUserId
    , CAST(ApprovalDate AS DATE)
    , 'SuggestedEditApproval'
  FROM SuggestedEdits
  WHERE OwnerUserId = @UserId
UNION
  SELECT DISTINCT
      OwnerUserId
    , CAST(RejectionDate AS DATE)
    , 'SuggestedEditRejection'
  FROM SuggestedEdits
  WHERE OwnerUserId = @UserId
UNION
  SELECT DISTINCT
      UserId
    , CAST(CreationDate AS DATE)
    , 'SuggestedEditVote'
  FROM SuggestedEditVotes
  WHERE UserId = @UserId
UNION
  SELECT DISTINCT
      UserId
    , CAST(CreationDate AS DATE)
    , 'VoteCreation'
  FROM Votes
  WHERE UserId = @UserId;

CREATE TABLE #ConsecDaysCount
(
    UserId INT
  , DaysCount INT
  , DateStreakEnded DATE
);

DECLARE @FirstDay DATE;
  SET @FirstDay = ( SELECT MIN(CreationDate) FROM Users WHERE Id = @UserId );
DECLARE @LastDay DATE;
  SET @LastDay = ( SELECT MAX(LastAccessDate) FROM Users WHERE Id = @UserId );
DECLARE @ConsecDaysCounter INT;
  SET @ConsecDaysCounter = 0;

WHILE (@FirstDay < @LastDay)
BEGIN
  IF ( SELECT DATEADD(DAY, 1, @FirstDay) ) IN (SELECT ActivityDate FROM #UserActiveDays)
    BEGIN
    SET @ConsecDaysCounter = @ConsecDaysCounter + 1;
    SET @FirstDay = DATEADD(DAY, 1, @FirstDay);
    END;
  ELSE
    BEGIN
    INSERT INTO #ConsecDaysCount (UserId, DaysCount, DateStreakEnded)
      VALUES (@UserId, @ConsecDaysCounter, @FirstDay);
    SET @ConsecDaysCounter = 0;
    SET @FirstDay = DATEADD(DAY, 1, @FirstDay);
    END;
END;

SELECT
    UserId AS [User Link]
  , DaysCount
  , DateStreakEnded
FROM #ConsecDaysCount
ORDER BY DaysCount DESC;


texts:
My code finds the maximum subarray sum and the starting and ending index of that subarray.

int Max(int a,int b){return (a>b)?a:b;}
int Max(int a,int b,int c){return Max(Max(a,b),c);}
int MaxAcrossSubArray(int arr[],int l,int m,int r,int &Start,int &End)
{
    Start=m;//initialize start index
    int sum=arr[m];
    int sum_l=arr[m];
    for(int i=m-1;i>=l;--i)//include mid(---------|)
    {
        sum+=arr[i];
        if(sum>sum_l)
        {
            Start=i;
            sum_l=sum;
        }

    }
    End=m+1;//initialize end index
    sum=arr[m+1];
    int sum_r=arr[m+1];
    for(int i=m+2;i<=r;++i)//include mid(|-----------------)
    {
        sum+=arr[i];
        if(sum>sum_r){
            End=i;
            sum_r=sum;
        }
    }
    return sum_l+sum_r;//(-----------|---------------------)

}
int MaxSubArray(int arr[],int l,int r,int &Start,int &End)
{
    if(l==r)
    {
        Start=l;
        End=r;
        return arr[l];
    }

    else
    {
       int mid=(l+r)/2;
        int sA=-1,eA=-1,sB=-1,eB=-1,sC=-1,eC=-1;
        int a=MaxSubArray(arr,l,mid,sA,eA);
        int b=MaxSubArray(arr,mid+1,r,sB,eB);
        int c=MaxAcrossSubArray(arr,l,mid,r,sC,eC);
        int Maximum=Max(a,b,c);

        if(Maximum==a)
        {
            Start=sA;
            End=eA;
            return a;
        }

        else if(Maximum==b)
            {
                Start=sB;
                End=eB;
                return b;
            }
        else
            {
                Start=sC;
                End=eC;
                return c;
            }
    }
    }

}
int main()
{
    int arr[9]={-2, 1, -3, 4, -1, 2, 1, -5, 4};
    int Start=-1;
    int End=-1;

    cout<<MaxSubArray(arr,0,8,Start,End)<<"\n";
    cout<<Start<<"\n";
    cout<<End<<"\n";
    for(int i=Start;i<=End;++i)
    {

        cout<<arr[i]<<"\t";
    }
    cout<<"\n";
    return 0;
}

Is there any way to optimize this?


texts: Get a stock quote from a web page using F#

texts:
I want to extract a price for a single index fund, the price of which is available on dynamic web pages.

Being new to this, my original idea was to download the single page of static HTML and get the price from that.  How hard could it be?  Inspired by an article on F# for fun and profit I imagined it would be easy.

Of course, the data isn't in the static page, as anyone who is familiar with web site development knows.  Just look at the huge amount of content on w3schools that describes how a modern page is built.  Much of it is dynamic and runs client code in the browser, like javascript.

Given that a simple HTTP request doesn't work, I opted to use a web browser control.

I found inspiration from these stackoverflow questions: How to use WebBrowser control DocumentCompleted event in C#?, View Generated Source (After AJAX/JavaScript) in C# and C# how to wait for a webpage to finish loading before continuing.

open System
open System.Windows.Forms
open System.Threading
open System.Text.RegularExpressions

let wb = new WebBrowser()
wb.ScrollBarsEnabled <- false
wb.ScriptErrorsSuppressed <- true

let rec GetPrice (wb:WebBrowser) =
    Application.DoEvents()  // Get the browser to do work
//    The following doesn't work
//    while (wb.ReadyState <> WebBrowserReadyState.Complete) do Application.DoEvents()

    let m = Regex.Match(wb.Document.Body.InnerText, """£(?<VIGSCA>\d{3}\.\d{4})[^\d]""")
    if m.Success
    then
        // by definition, a sucessful match is a float32 (Single) so this parse will work
        Single.Parse(m.Groups.["VIGSCA"].Value)
    else
        // it takes several seconds to get a result, let's give the CPU a rest before we try again
        Thread.Sleep 100
        GetPrice wb

let stockURL = Uri "https://www.vanguard.co.uk/uk/portal/detail/mf/overview?portId=9158&assetCode=EQUITY##overview"
wb.Navigate(stockURL)
while (wb.ReadyState <> WebBrowserReadyState.Complete) do Application.DoEvents()

let price = GetPrice wb
printfn "Price is %A" price

wb.Dispose()

Can you suggest improvements?  For example:

More idiomatic f#
Use an event instead of a loop.  This code doesn't work

let downloadComplete = Async.AwaitEvent (wb.DocumentCompleted) |> Async.Ignore
Async.RunSynchronously downloadComplete

An alternative way to download the price that doesn't use a web browser control

These related questions, Use Webbrowser control to get and post data?, How to use System.Windows.Forms.WebBrowser in a web app?, are interesting but don't help.


texts:
I have this Book program that contains 2 classes: Book and Library.  I have the Book class done, but need some help on the Library class. Please help me check my code. I can provide the Book class if you need it.

Instruction here:

  Fields: A single private ArrayList of Book field is all that is
  necessary. This will hold all the Book objects in the library.

  Methods: public Library(ArrayList other)

  Throws a NullPointerException if other is null. Otherwise, the
  Library’s Book ArrayList should take on all the books in other.

  public Library( ) Creates an empty ArrayList of books.

  public boolean add(Book book)

  First checks for null or empty Strings and calls the appropriate
  exception. Otherwise it adds the Book argument to the end of the
  library ArrayList. Notice it returns a boolean (whether or not the add
  operation succeeded) See the add method of ArrayList:

  public ArrayList findTitles(String title)

  Generates an ArrayList of all books which have titles that match
  (exactly) with the passed argument and returns this list to the
  calling program. The String compareTo method is useful here.

  public void sort( )

  Sorts the library’s book ArrayList in ascending order according to the
  title field (sort these titles just as they are, i.e. don’t worry
  about articles such as The or A, etc.). As illustrated in the
  textbook, p. 666 (Don’t let this number concern you :) ), you will use
  the Collections sort.

  public String toString( )

  returns a properly formatted String representation of all the books in
  the library (Title followed by authors).

    import java.util.ArrayList;

import java.util.Collections;

public class Library {
    private ArrayList<Book> allBook = new ArrayList<Book>();

    public Library(ArrayList<Book> other) {
        if (other == null) {
            throw new NullPointerException("null pointer");
        } else
            this.allBook = other;
    }

    public Library() {
        this.allBook = new ArrayList<Book>();
    }

    public boolean add(Book book) {
        if (book != null && !book.equals("")) {
            throw new IllegalArgumentException("Can't be empty");
        }
        allBook.add(book);
        return true;
    }

    public ArrayList<Book> findTitles(String title) {
        for(Book b: allBook) {
            if(title.compareTo(b.getTitle())== 0) {
                return allBook;
            }
        }
        return null;
    }

    public void sort() {
        Collections.sort(allBook);
    }

    public String toString() {
        return Library.this.toString();
    }
}

    public class Book implements Comparable<Book> {
    private String bookTitle;
    private ArrayList<String> bookAuthor;

    public Book(String title, ArrayList<String> authors) {
        if(title == null && authors == null) {
            throw new IllegalArgumentException("Can't be null");
        }
        if(title.isEmpty() && authors.isEmpty()) {
            throw new IllegalArgumentException("Can't be empty");
        }
        bookTitle = title;
        bookAuthor = authors;
    }

    public String getTitle() {
        return bookTitle;
    }
    public ArrayList<String> getAuthors( ) {
        return bookAuthor;
    }

    public String toString( ) {
        return bookTitle + bookAuthor;
    }
    public int compareTo(Book other){
        return bookTitle.compareTo(other.bookTitle);
    }
    public boolean equals(Object o) {
         if(!(o instanceof Book)) {
             return false;
        }
         Book b = (Book) o;
         return b.bookTitle.equals(bookTitle)
                 && b.bookAuthor.equals(bookAuthor);
    }
}


texts:
4.2 Machine Epsilon

  Find the floating point number epsi that has
  the the following properties:

  1.0+epsi is greater than 1.0 and
  Let m b e  any number less than epsi. Then 1.0+m is equal to 1.0.

  epsi is called machine epsilon. It is of great importance in understanding floating point numbers.

I have written the following program to try and find my machine epsilon value to a given search depth (10).  Do you have any ideas how I could write this program better?

(defpackage :find-epsi (:use cl))
(in-package :find-epsi)

(defun smaller-scale (&OPTIONAL (epsi 1.0)) (if (> (+ 1.0 epsi) 1.0) (smaller-scale (/ epsi 10)) epsi))
(defun bigger (epsi inc-unit) (if (< (+ 1.0 epsi) 1.0) (bigger (+ epsi inc-unit) inc-unit) epsi))
(defun smaller (epsi dec-unit) (if (> (+ 1.0 epsi) 1.0) (smaller (+ epsi dec-unit) dec-unit) epsi))

(defun find-epsi (&OPTIONAL (search-depth 10) (epsi (smaller-scale)) (incdec-unit epsi))
  (if (= search-depth 0) epsi (find-epsi (1- search-depth) (bigger (smaller epsi incdec-unit) incdec-unit) incdec-unit)))

(format t "epsi: ~a ~%" (find-epsi))

It seems that it should be much simpler to find epsilon than I originally thought.  What do you think about the following program?

(defpackage :find-epsi (:use cl))
(in-package :find-epsi)

(defun find-epsi (&OPTIONAL (epsi 1.0))
  (if (> (+ 1.0 epsi) 1.0)  ; if the variable epsi is still significant
    (find-epsi (/ epsi 2)) ; halve it and try again
    epsi)) ; otherwise, we have found epsilon

(format t "epsi: ~a ~%" (find-epsi))


texts: Simple Duration calculator using es6 class syntax

texts:
I've written a simple script that calculates the distance between two points in time and returns the duration.

Example: Start - 11:00, End - 11:45, Duration - 0.75

I wanted to make use of ES6 classes and I'd like feedback on the Duration class in particular. For example, should the validation of the start and end arguments go in the constructor? Or should that be done later?

class Duration {
  constructor(start, end) {
    const reg = RegExp('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$');

    this.start = reg.test(start) ? start : '00:00';
    this.end = reg.test(end) ? end : '00:00';
  }

  _seconds(time = "00:00") {
    const split = time.split(':');

    return Number(split[0]) * 60 + Number(split[1]);
  }

  // See: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary
  _round(float) {
    return Math.round((float + 0.0001) * 100) / 100;
  }

  get difference() {
    const {
      _round: round,
      _seconds: seconds,
      start,
      end
    } = this;

    return round((seconds(end) - seconds(start)) / 60);
  }

}

function calcDuration(e) {
  e.preventDefault();

  const start = document.getElementById('time-start');
  const end = document.getElementById('time-end');
  const target = document.getElementById('target');

  const duration = new Duration(start.value, end.value);

  target.innerHTML += `<tr><td>${duration.start}</td><td>${duration.end}</td><td>${duration.difference}</td></tr>`;

  start.focus();
}

document.getElementById('time-submit').addEventListener('click', calcDuration);
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

Duration Calculator

Enter a start time and an end time and a conversion to a decimal will be given!

      <form class="time mx-auto">

            Start time:

            <input type="time" id="time-start" class="form-control" name="time-start" required autofocus/>

            End time:

            <input type="time" id="time-end" name="time-end" class="form-control" required/>

            <button id="time-submit" class="btn btn-primary" type="submit" value="Calculate">Calculate</button>

      </form>

            Start
            End
            Duration


texts: Evaluating association strengths of items

texts:
I have a list of animals with their counts:

import numpy as np
import pandas as pd
from random import randint

table = np.zeros((5,1), dtype=int)
for i in range(5):
    table[i]=randint(10, 20)

df1 = pd.DataFrame(columns=['Animal', 'Count'])
df1['Animal'] = animal_list
df1['Count'] = table
df1

And I have a matrix of how many times they appear together:

table = np.zeros((5,5), dtype=int)
animal_list = ['Monkey', 'Tiger', 'Cat', 'Dog', 'Lion']

for i in range(5):
    for j in range(5):
        table[i][j]=randint(0, 9)

df2 = pd.DataFrame(table, columns=animal_list, index=animal_list)
df2

I want to find the animals' association strength, which is defined like so - if Lion and Cat appear together 5 times, and Lion's count is 10 and Cat's count is 15, then Lion -> Cat association strength is 5/10=0.5, and Cat -> Lion association strength is 5/15=0.33.

I do it like so:

assoc_df = pd.DataFrame(columns=['Animal 1', 'Animal 2', 'Association Strength'])
for row_word in df2:
    for col_word in df2:
        if row_word!=col_word:
            assoc_df = assoc_df.append({'Animal 1': row_word, 'Animal 2': col_word,
                                        'Association Strength': df2[col_word][row_word]/df1[df1.Animal==row_word]['Count'].values[0]}, ignore_index=True)

assoc_df

The problem is, if I have a large number (say, 1000) of animals to loop on, it takes hours to finish computing the association strength table.

So, how to do I better optimize this last code block, the creation/generation process of this association table?

P.S.: In most practical use cases, df2 is a symmetric matrix, as "X appears together with Y" generally also means the same as "Y appears together with X". So, I am ok with solutions that assume that df2 is symmetric, and cut down the running time by half. In the above example, df2 is not a symmetric matrix, which is the more general case, and applicable for situations where we want to express meanings such as "X appears after Y" and "Y appears after X", which may not be the same.


texts:
This is a class in my React app. This code works and displays an appropriate icon and question for every description.

class myQuestion extends PureComponent {
  render() {
    const { description } = this.props.question;
    let icon = icon;
    let question = question;
    if (description === 'Happy') {
      icon = <FontAwesomeIcon icon={faSmile} />;
      question = 'You answered happy. Why?';
    } else if (description === 'OK') {
      icon = <FontAwesomeIcon icon={faMeh} />;
      question = 'You answered OK. Why?';
    } else if (description === 'Angry') {
      icon = <FontAwesomeIcon icon={faAngry} />;
      question = 'You answered angry. Why?';
    } else {
      icon = '';
      question = '';
    }
    return (
      <div>
        <Question
          icon={icon}
          description={description}
          question={question}
        />
      </div>
    );
  }
}

I'd like to know how would be a better way to write this if else statement, preferably removing the let.

'description' is a prop of the question, but 'icon' and 'question' are dependent on what the 'description' is. The 'description' comes from the ID of a previous answer to a question.

Is there a way I could put this logic before the render function?


texts: Ways of forming multiple elements in a list comprehension without duplicates (Euler #109)

texts:
I was working on Project Euler #109 (Potential spoilers for people who haven't done so yet); I got the correct solution, but I'm not satisfied with how one of my lines of code ended up looking, and was wondering if someone knows a better or more idiomatic way to do this.

singles = [1..20]++[25]
doubles = map (*2) singles
triples = map (*3) [1..20]

alls = singles ++ doubles ++ triples

oneshots = doubles
twoshots = [a+b | a <- doubles , b <- alls]
threeshots = [a+(alls!!b)+(alls!!c) | a <- doubles, b <- [0..((length alls)-1)], c <- [b..((length alls)-1)]]

main = do
    print $ length $ filter (< 100) $ (++oneshots) $ (++twoshots) threeshots

Specifically, the line:

threeshots = [a+(alls!!b)+(alls!!c) | a <- doubles, b <- [0..((length alls)-1)], c <- [b..((length alls)-1)]]

which gives me all of the unordered pairs of elements in alls, gives me pause.  If it was a simple range, then I could just do something like:

threeshots = [a+b+c | a <- doubles, b <- [0..100], c <- [b..100]]

and if the list was sorted and each element unique, I could even do:

threeshots = [a+b+c | a <- doubles, b <- alls, c <- alls, c < b]`

However, none of these hold true and my line ends up looking pretty cluttered.  What would people recommend as far as reformatting this line (or is it just something I'll have to deal looking at)?


texts: Parent/child relationships: adding/updating details to an answer

texts:
Answer is the Parent table and AnswerDetail is the child.  Below works, but I'm wondering if there is a better way to do this using EF?

My Method Signature is this:

    [HttpPost]
    public ActionResult Evaluator(EvaluationVM evaluation, string command)

It is coming from a MVC 4 application.

Answer AnswerRecord;
AnswerRecord = (db.Answers).Where(x => x.TeacherID.Equals(evaluation.CurrentTeacher.ID)).Where(y => y.LeaderID != null).FirstOrDefault<Answer>();

if (AnswerRecord == null)
{
     //Add New Parent Record:
     AnswerRecord.CreatedBy = userName;
     AnswerRecord.CreateStamp = DateTime.Now;
     db.Entry(AnswerRecord).State = EntityState.Added;

     AnswerRecord.UpdatedBy = userName;
     AnswerRecord.UpdateStamp = DateTime.Now;
 }

 AnswerRecord.UpdatedBy = userName;
 AnswerRecord.UpdateStamp = DateTime.Now;

 //I use this block if I know the child record is new:
 adItem = db.AnswerDetails.Find(item.LeaderAnswerDetailKey);
  if (adItem != null)
  {
       adItem.Comment = item.LeaderComment;
       adItem.AnswerOptionKey = item.LeaderAnswerOptionKey.Value;
       adItem.UpdatedBy = userName;
       adItem.UpdateStamp = DateTime.Now;
       db.Entry(adItem).State = EntityState.Modified;
  }

 foreach (EvaluationObject item in evaluation.ResultSet)
 {
 //I use this block if I am updated the child record
 adItem = new AnswerDetail();
 adItem.QuestionID = item.QuestionID.Value;
 adItem.AnswerOptionKey = item.TeacherAnswerOptionKey.Value;
 adItem.Comment = item.TeacherComment;

 adItem.CreatedBy = userName;
 adItem.CreateStamp = DateTime.Now;
 adItem.UpdatedBy = userName;
 adItem.UpdateStamp = DateTime.Now;
 adItem.AnswerKey = AnswerRecord.AnswerKey;

 AnswerRecord.AnswerDetails.Add(adItem);
 db.Entry(adItem).State = EntityState.Added;

 //This is called at the end of my method:
 db.SaveChanges();

 }//End of ForEach Loop

EvaluationVM

public class EvaluationVM
{
    public bool IsAdmin { get; set; }
    public bool IsLeader { get; set; }
    public int TeacherStatus { get; set; }
    public int LeaderStatus {get;set;}

    public bool IsPublicTeacher { get; set; }
    public bool IsFinalTeacher { get; set; }
    public bool IsPublicLeader { get; set; }
    public bool IsFinalLeader { get; set; }

    public List<EvaluationObject> ResultSet {get; set;}
    public TeacherInfo CurrentTeacher {get; set;}
    public LeaderInfo CurrentLeader { get; set; }

    public List<EvaluationRating> RatingSet {get;set;}
}

EvaluationObject:

    public class EvaluationObject : IEvaluationObject
    {
        public int? QuestionID { get; set; }
        public string IndicatorID { get; set; }
        public string QuestionDescription { get; set; }

        public string TeacherID { get; set; }
        public int? TeacherStatusKey { get; set; }
        public int? TeacherAnswerKey { get; set; }
        public int? TeacherAnswerDetailKey { get; set; }
        public int? TeacherAnswerOptionKey { get; set; }
        public string TeacherComment { get; set; }

        public string LeaderID { get; set; }
        public int? LeaderStatusKey { get; set; }
        public int? LeaderAnswerKey { get; set; }
        public int? LeaderAnswerDetailKey { get; set; }
        public int? LeaderAnswerOptionKey { get; set; }
        public string LeaderComment { get; set; }

    }


texts: Cake Pattern with implicitly added functionality

texts:
I have a scenario where I want to implement a variant of a Cake Pattern, but adding implicit functionality to a class (a Spark DataFrame).

So, basically, I want to be able to run a code like the following:

trait Transformer {
  this: ColumnAdder =>

  def transform(input: DataFrame): DataFrame = {
    input.addColumn("newCol")
  }
}

val input = sqlContext.range(0, 5)
val transformer = new Transformer with StringColumnAdder
val output = transformer.transform(input)
output.show

With a result like the following:

+---+------+
| id|newCol|
+---+------+
|  0|newCol|
|  1|newCol|
|  2|newCol|
|  3|newCol|
|  4|newCol|
+---+------+

I am struggling between two choices of implementation:

1) The first one is defining the implicit classes only in the base traits:

trait ColumnAdder {
  protected def _addColumn(df: DataFrame, colName: String): DataFrame

  implicit class ColumnAdderRichDataFrame(df: DataFrame) {
    def addColumn(colName: String): DataFrame = _addColumn(df, colName)
  }
}

trait StringColumnAdder extends ColumnAdder {
  protected def _addColumn(df: DataFrame, colName: String): DataFrame = {
    df.withColumn(colName, lit(colName))
  }
}

And it works fine, but I am not very happy with this approach, because of the function signatures duplication.

2) The second one is using the (deprecated?) implicit def strategy:

trait ColumnAdder {
  protected implicit def columnAdderImplicits(df: DataFrame): ColumnAdderDataFrame

  abstract class ColumnAdderDataFrame(df: DataFrame) {
    def addColumn(colName: String): DataFrame
  }
}

trait StringColumnAdder extends ColumnAdder {
  protected implicit def columnAdderImplicits(df: DataFrame): ColumnAdderDataFrame = new StringColumnAdderDataFrame(df)

  class StringColumnAdderDataFrame(df: DataFrame) extends ColumnAdderDataFrame(df) {
    def addColumn(colName: String): DataFrame = {
      df.withColumn(colName, lit(colName))
    }
  }
}

(The full reproducible code, including an extra trait-module can be found here)

So, I wanted to ask which approach is the best and if there may be another better way to achieve what I want. Any additional feedback is welcome.


texts:
I want to build Git class where i can store integers. FilesSet is where I store current state of integers. Commits' key is basically commit number so I can checkout pretty fast. Hashes is used for quick search of hashes that I need in commit part.

Update is for updating current state of integers.

In Commit I want to save a copy of current state and do it fast. First of all I don't want to compare arrays of integers, so I calculate hash of current state. Then if Hashes already has that hash as a key, I add to Commits Pair of commitNumber and  integer array that corresponds to that hash so I won't have to store another copy of array. And in Hashes of this key I add commit Number so I can see which commits have that hash. This one is a bottleneck for my solution.

In Checkout I basically get int that I need by arguments. I think this method is already really fast.
I need this class to be fast but I can't really provide test cases as they are hidden at my college testing system. My current solution is too slow with int Commit() .
Here it is :

using System.Collections.Generic;
using System.Linq;
using System;

namespace GitTask
{
    public class Git
    {
        int[] FilesSet { get; set; }
        Dictionary<int, int[]> Commits { get; set; }
        SortedList<int, List<int>> Hashes { get; set; }

        public Git(int filesCount)
        {
            FilesSet = new int[filesCount];
            Commits = new Dictionary<int, int[]>();
            Hashes = new SortedList<int, List<int>>();
        }

        public void Update(int fileNumber, int value)
        {
            FilesSet[fileNumber] = value;
        }

        public int Commit()
        {
            var commitNumber = Commits.Count;
            var tempHash = GetMyHashCode(FilesSet);

            if (Hashes.TryGetValue(tempHash, out List<int> key))
            {
                Commits.Add(commitNumber, Commits[key[0]]);
                Hashes[tempHash].Add(commitNumber);
                return commitNumber;
            }
            Commits.Add(Commits.Count, FilesSet.Clone() as int[]);
            Hashes.Add(tempHash, new List<int>(new int[] { commitNumber }));
            return commitNumber;
        }

        public int Checkout(int commitNumber, int fileNumber)
        {
            if (commitNumber >= Commits.Count)
                throw new ArgumentException();
            else
            {
                var commit = Commits[commitNumber];
                return commit[fileNumber];
            }
        }

        private int GetMyHashCode(int[] array)
        {
            int result = 0;
            for (int i = 0; i < array.Length; ++i)
            {
                result = unchecked(result * 31 + array[i]);
            }
            return result;
        }
    }
}

I expect you to come up with tips on speeding it up or creating new kind of storing files. I also tried to measure performance of methods and it seems like calculating hash of big array is a problem and adding to SortedList<int,List<int>> is a problem as well.


texts: Generating a string with only one space between the words

texts:
I wrote a program that inputs a string with spaces between them and should allocate a new string with only 1 space between the words. I was wondering if there's a better way to write it (I rewrote it a couple of times and I'm trying to find the most effective way to write this code).

#define _CRT_SECURE_NO_WARNINGS
#define SIZE 80
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* UpgradeString(char* oldText);
void inputStr(char* str);
int main()
{
    char str[SIZE], *ans;
    printf("Enter string\n");
    inputStr(str);

    ans = UpgradeString(str);
    puts(ans);

}
void inputStr(char* str)
{
    int i = 0;
    fgets(str, SIZE - 1, stdin);
    while (str[i] != '\n')i++;
    str[i] = 0;

}
char* UpgradeString(char* oldText)
{
    char temp[SIZE], *ans;
    int i=0, k = 0;

    while (1)
    {
        if (oldText[i] == 0)break;
        if (oldText[i] != ' ')
        {
            temp[k] = oldText[i];
            k++;
        }
        if (oldText[i] == ' '&&(oldText[i + 1] != ' '&&oldText[i + 1] != 0))
        {
            temp[k] = oldText[i];
            k++;
        }
        if (oldText[i] == ' ')i++;
        else i++;
    }
    temp[k] = 0;
    ans = (char*)malloc(sizeof(char)*(strlen(temp) + 1));
    strcpy(ans, temp);
    return ans;

}


texts: Having children call parent's public events with data generated from a protected event

texts:
I don't know that my title describes the code I want reviewed. Hopefully the code is explanatory.

I have an abstract parent class with two children. The parent listens to some hardware notifications and, when the appropriate hardware is connected/removed/fried in butter etc.., raises an event to its children who perform some processing with the data from the change.

The children then raise a public event on the parent with the processed data, which is what I'm unsure of. Here are the (stripped down) classes.

public abstract class DeviceDetector<TEventArgs>
{
    public event Action<TEventArgs> DeviceArrived;
    public event Action<TEventArgs> DeviceRemoved;
    protected void OnDeviceChange(TEventArgs e)
    {
         if (e.Arrival && DeviceArrived != null)
             DeviceArrived(e);
         if (!e.Arrival && DeviceRemoved != null)
             DeviceRemoved(e);
    }

    protected event Action<string> DeviceArrival;
    protected event Action<string> DeviceRemoval;

}

Each of the two children is defined as follows:

public class SomeDescriptiveChildName: DeviceDetector<DeviceChild1EventArgs>
{
    public SomeDescriptiveChildName()
    {
        this.DeviceArrival += new Action<string>(HandleProtectedEvent);
        this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
    }
    private void HandleProtectedEvent(string e)
    {
         //Class names have been changed to protect the innocent.
         DeviceChild1EventArgs e = new DeviceChild1EventArgs();
         base.OnDeviceChange(e);
    }
}

public class AnotherDescriptiveChildName: DeviceDetector<DeviceChild2EventArgs>
{
    public AnotherDescriptiveChildName()
    {
        this.DeviceArrival += new Action<string>(HandleProtectedEvent);
        this.DeviceRemoval += new Action<string>(HandleProtectedEvent);
    }
    private void HandleProtectedEvent(string e)
    {
         DeviceChild2EventArgs e = new DeviceChild2EventArgs();
         base.OnDeviceChange(e);
    }
}

The DeviceChild1EventArgs and DeviceChild2EventArgs are classes inheriting from EventArgs to represent the data from each child.

My question is this: Is there a better way to represent the data passed to the children through DeviceArrival and DeviceRemoval (in this example I used string, it's not a string)  without the use of generics etc...

To me this seems somewhat like overkill, but it's the only way I could think of doing this.


texts: Unit test for a function that transforms a PANDAS dataframe

texts:
I am currently working on a project that uses many dataframe wrangling. The intention is to write test to check that the output functions are correct.

I have written a test for a dataframe function that transforms a dataframe of operations into another dataframe that contains the volumen of the operations for each of the containing days.

My question is:

Is this a good test for a function that receives a DataFrame and returns a DataFrame?

Should I do something different?

This is is my code:

import pandas as pd

class Operations:

    def disaggregate_ops_volume_date(self, df: DataFrame):
        """ Given a DataFrame with operations it generates an operation for each of the days it contains """

        if df.empty:
            return df

        ops = df.copy()

        ops['NDAYS'] = ops[['SEQ_PERIODSTART', 'SEQ_PERIODEND']].apply(
            lambda row: (row['SEQ_PERIODEND'] - row['SEQ_PERIODSTART']).days, axis=1)

        # Add a copy of each operation NDAYS times
        ops = ops.loc[np.repeat(ops.index, ops['NDAYS'])]

        # Correct the date based on the TradeId operation
        ops['SEQ_PERIODSTART'] += pd.to_timedelta(ops.groupby('TRADEID').cumcount(), unit='d')
        ops['SEQ_PERIODEND'] = ops['SEQ_PERIODSTART'] + pd.Timedelta(1, unit='d')

        ops = ops.reset_index(drop=True)

        return ops

This is the test I have developed:

from pandas.util.testing import assert_frame_equal
import unittest
import pandas as pd

class TestOperations(unittest.TestCase):

    def test_minimal(self):
        """To make sure at least a test is passed"""
        self.assertEqual('foo'.upper(), 'FOO')

    def test_disaggregate_ops_volume_date(self):
        input = pd.DataFrame(
            {'SEQ_PERIODSTART':
               ['2019-02-10', '2019-02-12', '2019-02-13'],
             'SEQ_PERIODEND':
               ['2019-02-11', '2019-02-14', '2019-02-18'],
             'ID': [0, 1, 2]})

        input['SEQ_PERIODSTART'] = pd.to_datetime(input['SEQ_PERIODSTART'])
        input['SEQ_PERIODEND'] = pd.to_datetime(input['SEQ_PERIODEND'])

        expected = pd.DataFrame(
            {'SEQ_PERIODSTART':
                 ['2019-02-10', '2019-02-12',                                                           '2019-02-13', '2019-02-13',                                              '2019-02-14', '2019-02-15',                                             '2019-02-16', '2019-02-17'],

              'SEQ_PERIODEND':
                  ['2019-02-11',  '2019-02-13',
                  '2019-02-14', '2019-02-14',                                               '2019-02-15', '2019-02-16',                                          '2019-02-17', '2019-02-18'],
               'ID': [0, 1, 2, 3, 4, 5, 6, 7],
               'NDAYS': [1, 2, 2, 5, 5, 5, 5, 5]
                               })
        expected['SEQ_PERIODSTART'] = pd.to_datetime(expected['SEQ_PERIODSTART'])
        expected['SEQ_PERIODEND'] = pd.to_datetime(expected['SEQ_PERIODEND'])

        myops = Operations()

        assert_frame_equal(expected, myops.disaggregate_ops_volume_date(input))

if __name__ == '__main__':
    unittest.main()


texts:
I wrote the following a while ago (using regex code I found on Stack Overflow), and I have the following concern I'd like addressed: should there be an std::move() around the passing of the string into the parameter in the second version of the function, ExpandEnv(std::string const &text), to the rvalue version? Conversely, is there any reason not to use it?

inline std::string GetEnv(char const var[])
{
#if defined _WIN32 // getenv() is deprecated on Windows
    char *buf{nullptr};
    size_t sz;
    std::string val;
    if (_dupenv_s(&buf, &sz, var) || buf == nullptr) return val;
    val = buf;
    free(buf);
    return val;
#else
    return getenv(var);
#endif
}

inline std::string ExpandEnv(std::string &&text)
{
    static const std::regex ENV{"\\$\\{([^}]+)\\}"};
    std::smatch match;
    while (std::regex_search(text, match, ENV)) text.replace(match.begin()->first, match[0].second, GetEnv(match[1].str().c_str()));
    return text;
}

inline std::string ExpandEnv(std::string const &text)
{
    return ExpandEnv(std::string(text));
}


texts: Getting the neighbors of a Point in a 2D grid

texts:
I am trying to find an algorithm to find all the defined neighbors of a 2D Point (efficiently would be nice, but does not make much of a difference).

Here is my existing code:

private static ArrayList<Point> getNeighborsOfPoint(int i, int j) {
        ArrayList<Point> neighbors = new ArrayList<Point>();
        if (CONSIDER_CORNERS) {
            if (i < rows && j < cols && i >= 1 && j >= 1 && array[i][j] != 0) {
                neighbors.add(new Point(i-1, j-1));
            }
            if (i < rows && j < cols-1 && i >= 1 && j >= 0 && array[i][j] != 0) {
                neighbors.add(new Point(i-1, j+1));
            }
            if (i < rows-1 && j < cols && i >= 0 && j >= 1 && array[i][j] != 0) {
                neighbors.add(new Point(i+1, j-1));
            }
            if (i < rows-1 && j < cols-1 && i >= 0 && j >= 0 && array[i][j] != 0) {
                neighbors.add(new Point(i+1, j+1));
            }
        }

        if (i < rows && j < cols && i >= 1 && j >= 0 && array[i][j] != 0) {
            neighbors.add(new Point(i-1, j));
        }

        if (i < rows && j < cols && i >= 0 && j >= 1 && array[i][j] != 0) {
            neighbors.add(new Point(i, j-1));
        }
        if (i < rows && j < cols-1 && i >= 0 && j >= 0 && array[i][j] != 0) {
            neighbors.add(new Point(i, j+1));
        }

        if (i < rows-1 && j < cols && i >= 0 && j >= 0 && array[i][j] != 0) {
            neighbors.add(new Point(i+1, j));
        }

        return neighbors;
    }

CONSIDER_CORNERS is a boolean that is settable by the user, and Point is just a simple class that has an x and y int value. rows and cols are the number of elements in each of the two dimensions.

What I'm looking for mainly is better readability.


texts:
I am trying to refactor these three methods into one:

    public StatusReturn UpdateProperty(int id, int onlineReportId)
    {
        //Yes I realize I should not be using ref variables but the queryPermissions is an external dll.
        var webQueryInputProperty = new WebQueryInputProperty();
        //This line is different
        _queryPermissions.GetInputPropertyByKey(id, ref webQueryInputProperty);
        webQueryInputProperty.WQI_Key = onlineReportId;
        webQueryInputProperty.WQIP_Key = id;
        var webQueryInputProperties = new List<WebQueryInputProperty>{webQueryInputProperty};
        return _queryPermissions.UpdateWQInputProperties(webQueryInputProperties);
    }

    public StatusReturn AddProperty(int id, int onlineReportId)
    {
       var webQueryInputProperty = new WebQueryInputProperty();
        webQueryInputProperty.WQIP_Key = id;
        webQueryInputProperty.WQI_Key = onlineReportId;
        var webQueryInputProperties = new List<WebQueryInputProperty> { webQueryInputProperty };
        return _queryPermissions.UpdateWQInputProperties(webQueryInputProperties);
    }

    public StatusReturn DeleteProperty(int id, int onlineReportId)
    {
        var webQueryInputProperty = new WebQueryInputProperty();
        _QueryPermissions.GetInputPropertyByKey(id, ref webQueryInputProperty);
        webQueryInputProperty.WQI_Key = onlineReportId;
        webQueryInputProperty.WQIP_Key = id;
        var webQueryInputProperties = new List<WebQueryInputProperty> { webQueryInputProperty };
        //this line is different
        return _QueryPermissions.DeleteWebQueryInputProperties(webQueryInputProperties);
    }

I want to refactor the methods, remove the one line from AddProperty and change the return statement. I would rather not copy and paste.


texts:
Here is my code to add a progress bar on every HTTP request. Can someone please point out to me whether I am doing it right or not?

Template for loader:

Processing..., Please Wait...

Interceptor:

.factory('authInterceptor', ['$rootScope', function($rootScope){
            return {
                request : function request (config) {
                    $rootScope.loaderState = true;
                    return config;
                },
                response : function response(response) {
                    $rootScope.loaderState = false;
                    return response;
                }
            };
        }])


texts: Object-oriented implementation on Expense Tracking App

texts:
I am creating a Expense Tracking Application in C# and right now I am trying to build its building blocks in a console app. I Would like to know your feedback if it is in a Object Oriented Design/Structure.

namespace ExpenseTrackerOOP
{
    class ExpenseTracker
    {
        static void Main(string[] args)
        {
            Account expense = new Expenses();
            expense.Initialize();

            Account earnings = new Earnings();
            earnings.Initialize();

        }
    }

    public enum ExpenseType
    {
        Food,
        Transportation,
        Utitlities
    }
    public enum AccountTypes
    {
        Expenses,
        Earnings
    }
    public class AccountType
    {
        public AccountTypes Type;
    }

    public abstract class Account
    {
        public decimal Value { get; set; }

        public AccountType Type;

        public abstract void Initialize();
    }

    public class Expenses : Account
    {
        public List<Expenses> Expenses_list { get; set; }

        public override void Initialize()
        {
            Expenses_list = new List<Expenses>(){
                new Expenses() { Value = 10, Type = (new AccountType{Type = AccountTypes.Expenses}) },
                new Expenses() { Value = 20, Type = (new AccountType{Type = AccountTypes.Expenses}) },
                new Expenses() { Value = 30, Type = (new AccountType{Type = AccountTypes.Expenses}) }
            };
        }
    }

    public class Earnings : Account
    {
        public List<Earnings> Earnings_list { get; set; }

        public override void Initialize()
        {
            Earnings_list = new List<Earnings>(){
                new Earnings() { Value = 10, Type = (new AccountType{Type = AccountTypes.Earnings}) },
                new Earnings() { Value = 20, Type = (new AccountType{Type = AccountTypes.Earnings}) },
                new Earnings() { Value = 30, Type = (new AccountType{Type = AccountTypes.Earnings}) }
            };
        }
    }
}