texts: Set a UITableViewAccessoryType in a single UITableViewController used for two different purposes

texts:
I have a UITableViewController that displays a list of lift names (think weightlifting) and it's used for two different things. It can be accessed from view A to select a lift that will be saved as a user default. It can also be accessed from view B to select a lift that will then filter a list of lift events. In each case, I want a checkmark on the appropriate cell to indicate the current default lift (if coming from view A) and a checkmark on the appropriate cell to indicate the currently selected filter (if coming from view B).

I created a view model for the table cells:

struct LiftCellViewModel: SelectionsRepresentable {

    let liftName: String!
    let liftsDictionary: [String: String]!

    var text: String {
        return liftName
    }

    var accessoryType: UITableViewCellAccessoryType {
        let defaultLiftUuid = UserDefaults.lift()
        let defaultLiftName = liftsDictionary[defaultLiftUuid]

        if liftName == defaultLiftName {
            return .checkmark
        } else {
            return .none
        }
    }
}

This works very, but only handles one of the scenarios (coming from view A). So, to try and get it to also work with the other scenario (coming from view B) I'm passing in a bool if the list is being used to select a filter and using that in a switch statement to determine what path to take in order to set the checkmark:

let liftName: String!
let liftsDictionary: [String: String]!
let selectForFilter: Bool!

var text: String {
    return liftName
}

var accessoryType: UITableViewCellAccessoryType {

    switch selectForFilter {
    case true:
        let filterLiftUuid = UserDefaults.logFilterLiftUuid()
        let filterLiftName = liftsDictionary[filterLiftUuid!]

        if liftName == filterLiftName {
            return .checkmark
            } else {
            return .none
            }
    case false:
        let defaultLiftUuid = UserDefaults.lift()
        let defaultLiftName = liftsDictionary[defaultLiftUuid]

        if liftName == defaultLiftName {
            return .checkmark
        } else {
            return .none
        }
    default:
        return .none
    }
}

This view is used to create each cell in didSelectRow:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellViewModel: SelectionsRepresentable
    let cell = tableView.dequeueReusableCell(withIdentifier: "liftCell", for: indexPath)
    let lift = viewModel.fetchedResultsController?.object(at: indexPath) as! Lift
    let liftName = lift.liftName

    cellViewModel = LiftCellViewModel(liftName: liftName, liftsDictionary: liftsDictionary, selectForFilter: selectForFilter)

    cell.textLabel?.text = cellViewModel.text
    cell.accessoryType = cellViewModel.accessoryType

    return cell
}

This works but the switch statement seems like a lot of code to do something so simple. Is there a Swiftier way to do this?


texts: Find duplicates in List where all the numbers in between is <= than the duplicates

texts:
My function is supposed to go through a given List<Integer> and find integers of same value, but only count them if the integers between them is <= the the integers that are equal:

public static int findPairs(List<Integer> arr) {
        int total = 0;

        for(int i = 0; i < arr.size(); i++) {
            for(int j = i+1; j < arr.size(); j++) {
                total += (arr.get(i) == arr.get(j)) ? 1 : 0;
                j = (arr.get(j) > arr.get(i)) ? arr.size() : j;
            }
        }
        return total;
    }

The array size can be between \$1 \le N \le 3 *10^5\$.

The numbers in the array can be between \$1 \le N \le 10^6\$.

This works, but is there any way to achieve the same thing, only a better solution performance-wise?


texts:
I have an Express router that is doing all the heavy lifting. Should the router be handling all this stuff or is a layer required between these two like maybe a service that makes these calls?

// Modules
import { Router } from 'express'
import Passport from 'passport'
import Sequelize from 'sequelize'
import _ from 'lodash'
import JWT from 'jsonwebtoken'
import process from 'process'

import User from '../models/User'
import JwtAuth from '../../config/authStrategy'

const router = new Router()

router.use(Passport.initialize())
JwtAuth(Passport)

router.post('/api/register', (req, res) => {
    User.create(req.body)
        .then(user =>
            res.status(201).json({
                success: true,
                message: `User ${user.name} with id ${
                    user.email
                } successfully created. Please login to continue.`
            })
        )
        .catch(Sequelize.UniqueConstraintError, err => {
            res.status(409).json({
                success: false,
                message: `User with id ${err.fields.email} already exists!`
            })
        })
        .catch(Sequelize.ValidationError, err => {
            const fields = _.capitalize(
                err.errors.map(error => error.path).join(', ')
            )
            res.status(400).json({
                success: false,
                message: `${fields} was not filled correctly. Please retry regestering.`
            })
        })
})

router.post('/api/login', (req, res) => {
    User.findOne({ where: { email: req.body.email } })
        .then(user => {
            if (user === null) {
                unsuccessfulLogin(res)
                return
            }
            user.comparePassword(req.body.password).then(isCorrect => {
                if (isCorrect) {
                    let token = JWT.sign(
                        user.dataValues,
                        process.env.JWT_SECRET,
                        { expiresIn: 10000 }
                    )
                    res.cookie('token', token)
                    res.status(303).json({
                        success: true,
                        message: 'Login successful',
                        token: `JWT ${token}`
                    })
                } else {
                    unsuccessfulLogin(res)
                }
            })
        })
        .catch(err => {
            console.error(err)
            unsuccessfulLogin(res)
        })
})

router.post(
    '/api/logout',
    Passport.authenticate('jwt', { session: false }),
    (req, res) => {
        req.logout()
        res.cookie('token', '')
        res.json({
            success: true,
            message: 'Successfully logged out'
        })
    }
)

function unsuccessfulLogin(res) {
    res.status(401).json({
        success: false,
        message: 'Login failed!'
    })
}

export default router


texts:
This is my solution to the competitive coding question on SPOJ here.  It gives a runtime of 0.24 but the best solutions posted have a 0.0 runtime. How could I possibly achieve better results than this?

#include<iostream>
#include<cstdio>

using namespace std;

int rev(int num)
{
    int rev_num=0;
    while(num)
    {
        rev_num= rev_num*10 + num%10;
        num/=10;
    }
    return rev_num;
}
int main()
{
    int n, n1, n2;
    scanf("%d",&n);
    while(n--)
    {
        cin>>n1>>n2;
        cout<<rev(rev(n1)+rev(n2))<<endl;

    }
    return 0;
}


texts: Determine if braces in a string are balanced in Clojure

texts:
I'm currently learning Clojure, and am working through a few exercises. The exercise that I'm working on right now is accept an arbitrary string and determine if the opening and closing parenthesis, curly brackets, and square brackets correctly nest and line up to each other.

For example, "hello { ( world ) } []" would be an example of a balanced string whereas "foo { [ bar ) [}" would be an example of an unbalanced string.

While I have previous experience in other programming languages like Python and Java, I'm very new to Clojure and functional languages in general, so am uncertain if my code is fully idiomatic or if there's a more cleaner or efficient way to complete the problem.

Here's what I have so far. The approach I've taken is to first filter out any characters that are not opening or closing braces. I then loop through the characters, adding the opening brackets to a stack and checking closing brackets against the stack to see if it matches.

Any feedback would be greatly appreciated.

; Given a N different open and close braces in a string ""( { [ } ] )"".
; Write a program to check to see if the braces in the string are balanced.

(ns braces
  (:require [clojure.string :as str]))

(def braces #{\( \) \[ \] \{ \}})

(def pairs { \) \(,
             \] \[,
             \} \{ })

(defn remove-non-braces
  "Takes a string and removes any characters that is not a brace."
  [raw-string]
  (filter #(braces %) raw-string))

(defn is-balanced?
  "Returns true if all the braces in the string are balanced; returns false otherwise."
  ([raw-string] (is-balanced? (remove-non-braces raw-string) []))
  ([string stack]
    (let [[first-char & other] string]
      (cond
        ; if we're done, but the stack is non-empty, we still have opening braces left.
        (empty? string) (empty? stack)
        ; if we encounter a closing brace, check it against the top of the stack.
        (pairs first-char) (if (= (pairs first-char) (peek stack))
                               (is-balanced? other (pop stack))
                               false)
        ; if we encounter an opening brace, add it to the stack.
        :else (is-balanced? other (conj stack first-char))))))

(defn test-strings
  "Tests the given strings and prints the results."
  [& strings]
  (let [format-str (fn [s] (str (is-balanced? s) " : " s))]
    (println (str/join "\n" (map format-str strings)))))

(defn main
  "The main entry point of the program."
  []
  (println "SHOULD PASS")
  (test-strings
    "Hello { ( world ) } [] end"
    ""
    "{[] () {[{{ }}]} ([{}])}")
  (println "")
  (println "SHOULD FAIL")
  (test-strings
    "Hello { world"
    "{{"
    "])"
    "}}{{"
    "{[))"))

(main)


texts:
I've created two simple methods: one to instantiate a new XMLHttpRequest object and open the request and another to handle the request.

Can you please point out improvements that can be made or any shortcomings in my code?

ajax: function(opts) {

  var xhr, method, body, constructor;

  xhr = new XMLHttpRequest();
  method = opts.body ? 'POST' : opts.method ? opts.method.toUpperCase() : 'GET';

  if(opts.body) {
    constructor = opts.body.constructor;
    if(constructor === Object || constructor === String) {
      body = opts.body;
    }
  }

  this.ajaxComplete.call(xhr, opts);

  xhr.open(method, opts.url, (opts.async === undefined ? true : false));

  // Set the default request headers
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  if(opts.headers) {
    for(var prop in opts.headers) {
      xhr.setRequestHeader(prop, opts.headers[prop]);
    }
  }

  xhr.send(body || null);
},

ajaxComplete: function(opts) {
  var that = this,
      data, complete;

  that.onreadystatechange = function() {
    if(that.readyState == 4) {
      if(that.status == 200) {
        data = (that.responseXML || that.responseText);
        opts.success.call(that, data);
      }
      else {
        data = (that.responseXML || that.responseText);
        opts.error.call(opts, data, that.statusText, that.status);
      }
    }
  }
}


texts: Implementing a linked list as practice for a coding interview

texts:
I am practicing LinkedList problems. How do I make it production level code as is mostly expected in a coding interview? Any other Suggestions?

package LinkedList;

/**
 * @author Amogh Antarkar
 * @email antarkar.amogh@gmail.com
 */
import java.util.*;

public class LinkedList{

    public static void main(String[]args){

        switchCase();
        System.out.println("Successful completion of the LinkedList program");
    }

    /* Note: Here a singleton pattern has been used for the Scanner in
     * as only one instance is created during the entire implementation
     */

    public static void switchCase(){
        int cont;
        Scanner in = new Scanner(System.in);
        LinkedListNode list = new LinkedListNode();

        do{
            System.out.println("Enter the option you want to run");
            System.out.println("1. remove duplicates\n2. Print List\n 3. Make List\n 4.kth to last element");
            int option = in.nextInt();
            switch(option){
            case 1: // remove duplicates
                System.out.println("option chosen:"+option);
                list.removeDuplicates();
                break;

            case 2:
                list.printList();
                break;

            case 3:
                list.makeList(list,in);
                break;

            case 4:
                System.out.println(" Enter k");
                int j = list.kthLastElement(list,in.nextInt());
                break;

            default:
                break;
            }
            System.out.println("Do you want to continue ?");
            cont = in.nextInt();

        }while(cont == 1);

        in.close();
    }
}

class LinkedListNode{

    private int data;
    private LinkedListNode next = null;

    public LinkedListNode(int d){
        data = d;
        next = null;
    }

    public LinkedListNode() {
    }

    // appends data to the List
    void appendData(int d){
        LinkedListNode end = new LinkedListNode(d);
        LinkedListNode n = this;
        while(n.next != null){
            n = n.next;
        }
        n.next = end;
    }

    // creates the LinkedList taking the input
    void makeList(LinkedListNode list, Scanner in){

        System.out.println("Enter the list");
        int len = in.nextInt();
        while(len-- > 0){
            list.appendData(in.nextInt());
        }
    }

    //implementing the recursive solution
    int kthLastElement(LinkedListNode head,int k){

        if(head == null){
            return 0;
        }
        else{
            int i = kthLastElement(head.next,k)+1;
            if(i==k)
                System.out.println(head.data);
            return i;
        }

    }

    // print the entire LinkedList O(n) time
    void printList(){
        LinkedListNode  n = this;
        while(n.next!= null){
            n = n.next;
            System.out.print(n.data+" -> ");
        }
        System.out.print("NULL\n");
    }

    // remove duplicates from the linkedList using Hashtable method
    void removeDuplicates(){

        Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
        LinkedListNode current = this, prev = null;

        while(current != null){
            if(table.containsKey(current.data)){
                prev.next = current.next;
            }else{
                table.put(current.data,true);
                prev = current;
            }
            current = current.next;
        }
    }
}


texts:
Could I have a couple people look over my code for a general readability check?  Just make sure it is following Python standards.

def casear_cipher(letter, num):
    """ This function acts like a Casear Cipher.

    Replaces an input letter with another letter a fixed

    number of spaces farther down the alphabet

    Args:

    * letter (string) - any upper case or lower case letter

    * num (integer) - any integer value to shift to a new letter
        """

    #Range 65 to 91 is ASCii values for uppercase alphabet
    if ord(letter) in range (65, 91):
        x = ord(letter) - ord('A')
        num_mod_26 = (x + num) % 26
        final_output = chr(ord('A') + num_mod_26)
        return final_output

    #Range 97 to 123 is ASCii values for lowercase alphabet
    elif ord(letter) in range (97, 123):
        x = ord(letter) - ord('a')
        num_mod_26 = (x + num) % 26
        final_output = chr(ord('a') + num_mod_26)
        return final_output


texts:
I have a recursive statement that removesactivities that don't have a resource type for a certain OrganizationID. I was wondering if there was a better way to do this where I can eliminate some of the for loops and use a little more linq

    private IEnumerable<SubProjectDto> GetProjectAndActivitiesForByOrg(IEnumerable<SubProjectDto> children, Guid? organiazaitonId)
    {
        var subProjects = new List<SubProjectDto>();
        subProjects.AddRange(children);
        for (var i = 0; i < subProjects.Count; i++)
        {

            var activities = new List<ActivityDto>();
            activities.AddRange(subProjects[i].Activities);
            for (var j = 0; j < activities.Count; j++)
            {
                var resourceTypesForOrgs = activities[j].ActivityPersons.Where(x => x.ResourceType.OrganizationId == organiazaitonId).Count();

                if (resourceTypesForOrgs == 0)
                    activities.Remove(activities[j]);
            }

            subProjects[i].Activities = activities;

            if (subProjects[i].Children.Any())
                GetProjectAndActivitiesForByOrg(subProjects[i].Children, organiazaitonId);

        }
        children = subProjects;
        return children;
    }


texts: pulling specific data from XML from inside 3rd party application

texts:
Another script that is used as a token to extract information from a 3rd party application,  the application does other things in the background that I don't specifically know about.

This code does work inside the parent application and produces the expected output.

Is there a nicer way to write this code?

Public Function GetParameterXml()
    GetParameterXml = _
        "<Parameters>" &_
        "<Parameter Value='Age' Code='A' Description='Age' Type='Combo' Tooltip='Would you like the newest or oldest Reason?'>" &_
        "    <Options>" &_
        "   <Option Code='O' Description='Oldest' Value='OLD' />" &_
        "   <Option Code='N' Description='Newest' Value='NEW' />" &_
        "    </Options>" &_
        "</Parameter>" &_
        "</Parameters>"
End Function

'Parameter Variables
Dim Age : Set Age = Parameters.Item( Bookmark , "Age" )

' PlaceHolder Variables
Dim oNodes
Dim oNode

Set oNodes = XmlDoc.SelectNodes("Record/CelloXml/Integration/Case/ServiceEvent")

'''stop here and look around
stop

If (Age.Value = "OLD") Then
    For Each iNode in oNodes(0).childNodes
        If iNode.nodeName = "Service" Then
            For Each jNode in iNode.childNodes
                If jNode.nodeName = "Comment" Then
                    ReturnData = ReturnData & jNode.text & MD & ""
                End If
            Next
        End If
    Next
    If Len(ReturnData) > 0 Then
        ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))
    Else
        ReturnData = ""
    End if
ElseIf (Age.Value = "NEW") Then
    For Each iNode in oNodes(oNodes.length - 1).childNodes
        If iNode.nodeName = "Service" Then
            For Each jNode in iNode.childNodes
                If jNode.nodeName = "Comment" Then
                    ReturnData = ReturnData & jNode.text & MD & ""
                End If
            Next
        End If
    Next

    If Len(ReturnData) > 0 Then
        ReturnData = Left(ReturnData, Len(ReturnData) - Len(MD))
    Else
        ReturnData = ""
    End If
Else
    ReturnData = " Hit the Else Statement "
End If


texts:
I came up with this jQuery snippet to add/remove a class on <label> tags that contain either checkboxes or radio buttons, in order to improve usability so users can see what item(s) they have selected.

But I would like to know if there's a way to optimize the code (or not if that's the case).

$('label input[type=radio], label input[type=checkbox]').click(function() {
  $('label:has(input:checked)').addClass('active');
  $('label:has(input:not(:checked))').removeClass('active');
});


texts: Random game code id generator in typescript

texts:
Below is a simple typescript class used to generate a room code for an online lobby-based game (for example, https://jackbox.tv/ uses 4 digit codes to join rooms)
The goal of the class is to quickly generate unique 4-letter codes for game lobbies, and release them after the lobby is closed. Typically, less than 100 lobby codes will be used at once so using up all 26^4 codes will likely never happen.
Concerns:

Is the method for generating codes efficient? Currently it just picks a random code and keeps incrementing until an unused code is found
Is the method for encoding a number to an alphabet efficient? (converting a number to base 26)

const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function randInt(min: number, max: number) {
  return Math.floor(Math.random() * (max - min)) + min;
}

export class RoomCodeManager {
  codeLength: number;
  usedCodes: Set<string>;
  // Generate 4-letter codes by default
  constructor(codeLength = 4) {
    this.codeLength = codeLength;
    this.usedCodes = new Set();
  }
  generateCode() {
    const min = 0;
    const max = Math.pow(ALPHABET.length, this.codeLength);
    let code = randInt(min, max);

    // If every code is already in use, just return a random code
    if (this.usedCodes.size >= max) {
      return this.encodeAlphabet(code);
    }

    // Keep incrementing by 1 until an unused code is found
    while (this.usedCodes.has(this.encodeAlphabet(code))) {
      code = (code + 1) % max;
    }
    this.usedCodes.add(this.encodeAlphabet(code));
    return this.encodeAlphabet(code);
  }
  encodeAlphabet(num: number) {
    let str = "";
    const len = ALPHABET.length;
    while (num > 0) {
      let radix = num % len;
      str = ALPHABET[radix] + str;
      num = Math.floor(num / len);
    }
    return str.padStart(this.codeLength, ALPHABET[0]);
  }
  releaseCode(code: string) {
    this.usedCodes.delete(code);
  }
}


texts: Generating a list of primes of a given length

texts:
After considerable effort, I've come up with the following code to generate a list of primes of a given length.

I would be very interested to see how an experienced coder would modify my code to make it more readable, more concise, or somehow better.  I won't be able to follow fancy-pants coding that doesn't involve basic iterations of the type I have used, so please keep it simple for me.  I've been learning the language only a few months.

Function returns number of primes indicated in call.

Algorithm: Add two to last candidate in list (starting with [2, 3, 5]) and check whether other members divide the new candidate, iterating only up to the square root of the candidate.

import math
def primeList(listLength):
    plist = [2, 3]
    j = 3
    while listLength > len(plist):
        prime = 'true'
        i = 0
        j +=2
        plist.append(j)
        while plist[i] <= math.sqrt(j) and prime == 'true':
            if j%plist[i] == 0:
                prime = 'false'
            i +=1
        if prime == 'false':
            plist.pop(-1)
    return plist


texts:
I am currently preparing for my exam and I am trying to implement some abstract data types with linked lists as preparation for the exam. I found an older exam from my prof. and he wants us to implement an ADT stack with an inner class ListElement.

He has given us the interface, so it doesn't need to be implemented. He wants us to use his given methods, so we are not allowed to change them. This is what I did and I am not sure whether it is right or wrong.

public class Stack<T> implements ADTStack<T> {
    private ListElement<T> firstElement;
    int size = 0;

    public Stack() {
        firstElement = null;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }

    @Override
    public void push(T element) {
        if (empty()) {
            firstElement = new ListElement(element);
            size++;
        }
        else {
            firstElement.nextElement = firstElement;
            firstElement = new ListElement(element);
            size++;
        }
    }

    @Override
    public void pop() {
        if (empty()) {
            throw new RuntimeException("stack is empty");
        }
        else {
            T element = top();
            firstElement = firstElement.nextElement;
            size--;
        }
    }

    @Override
    public T top() {
        if (empty()) {
            return null;
        }
        else {
            return firstElement.element;
        }
    }

    @Override
    public boolean empty() {
        return (firstElement == null);
    }

    @Override
    public int size() {
        return size;
    }

    public class ListElement<T> {
        private T element = null;
        private ListElement<T> nextElement = null;

        public ListElement(T element) {
            this.element = element;
        }

        public T getElement() {
            return element;
        }

        public ListElement<T> getNextElement() {
            return nextElement;
        }

        public void setNextElement(ListElement<T> element) {
            this.nextElement = nextElement;
        }
    }
}


texts: Let's Break Down the Party by Breaking the Party Down Recursively

texts:
This is a rags-to-riches an overdue alternative implementation on my previous question: Let's Break Down the Party

This alternative uses the int internal representation suggested by @janos and recursion to arrive at the same results. For starters, here are the changes in Denomination enum to support the internal representation:

public enum Denomination {
    // values;

    static final int MULTIPLIER = 100;

    private final BigDecimal value;
    private final int centValue; // internal representation
    private String description;

    private Denomination(double value, final String description) {
        this.value = BigDecimal.valueOf(value);
        this.centValue = (int) (MULTIPLIER * value);
        this.description = Objects.requireNonNull(description);
    }

    /**
     * @return the value in cents
     */
    public int getCentValue() {
        return centValue;
    }

    ...

}

(I've kept the original BigDecimal value parts of code intact since I am  treating the new internal representation as an addition rather than a replacement to the original)

MULTIPLIER_VALUE uses the default (package) access modifier as it is only meant to be visible within the same package, i.e. the Calculator:

public class Calculator {

    /**
     * Break down the input into {@link Denomination} values by recursion.
     *
     * @param input the value to break down
     * @return an unmodifiable {@link Map} with the {@link Denomination} as keys and a
     *         positive integer, the multiplier, as values
     */
    public static Map<Denomination, Integer> getBreakdownRecursively(double input) {
        return Collections.unmodifiableMap(
                recurse(Stream.of(Denomination.values()).iterator(),
                        (int) (input * Denomination.MULTIPLIER),
                        new EnumMap<>(Denomination.class)));
    }

    private static Map<Denomination, Integer> recurse(Iterator<Denomination> iterator,
            int input, Map<Denomination, Integer> result) {
        if (input == 0 || !iterator.hasNext()) {
            return result;
        }
        Denomination current = iterator.next();
        int nextInput = input;
        int units = input / current.getCentValue();
        if (units != 0) {
            result.put(current, Integer.valueOf(units));
            nextInput = input % current.getCentValue();
        }
        return recurse(iterator, nextInput, result);
    }

    ...

}

Rather than continuing encumbering my Denomination enum with the logic to do the 'break down', I have put the very simple calculations within the recurse() method. To showcase the results with the recursion method in the unit test, I have the following changes inside CalculatorTest:

public class CalculatorTest {

    @DataProvider(name = "test-cases")
    public Iterator<Object[]> getTestCases() {
        // return test cases as new Object[] { Double, CaseBuilder }
    }

    @Test(dataProvider = "test-cases")
    public void test(final Double testValue, final CaseBuilder builder) {
        doTest(testValue, builder, Calculator::getBreakdown);
    }

    @Test(dataProvider = "test-cases")
    public void testRecursion(final Double testValue, final CaseBuilder builder) {
        doTest(testValue, builder, Calculator::getBreakdownRecursively);
    }

    private void doTest(final Double testValue, final CaseBuilder builder,
            final DoubleFunction<Map<Denomination, Integer>> function) {
        Stream.of(testValue, builder).forEach(Objects::requireNonNull);
        final Map<Denomination, Integer> expected = builder.getExpected();
        assertThat(function.apply(testValue.doubleValue()), equalTo(expected));
        assertThat(Double.valueOf(Calculator.compute(expected)), equalTo(testValue));
    }

    ...

}

Question

Are there any other improvements for this implementation?


texts: Cook and Felderman analysis to perform data reduction on heated surfaces

texts:
This is a "pain", but I wonder if I can get any real speedup with the follow Python script - it is taking well over 10 minutes to calculate the way it is written now. (And that's only when feeding around 1-2 promille of the data).

I have an with shape (roughly): [260, 300, 300]

Now I am doing a cougar=feldermann analysis on this:

import numpy as np
import math
#COOK AND FELDERMAN
def CandF(dT, time, rho, c, k):
    sqrt = np.sqrt
    sumdata=np.zeros(len(time))
    for n in range(len(time)):
        for data in range(1,n+1):
            sumdata[n] += dT[data] / (sqrt(time[n]-time[data])+sqrt(time[n]-time[data-1]))

    qs = (2*sqrt(rho*c*k))/(sqrt(math.pi)) * sumdata
    return qs

def data_reduction_constant_time(dT, timestep, rho, cp, k):
    #print (len(dT), timestep)
    time = np.linspace(0, len(dT)*timestep, int(len(dT)))
    return data_reduction(dT, time, rho, cp, k )

def data_reduction(dT, time, rho, cp, k):
    return CandF(dT, time, rho, cp, k)

class data:
    def __init__(self):
        #normally lots of file reading

        self.integration = 400
        self.cols = 320
        self.rows = 260
        self.depth = 300
        self.readData()

    def readData(self):
        self.ml_delta_temp = 3 * np.random.random_sample((self.cols, self.rows, self.depth))

    def calcQML(self):
        print("--- Calculating q ---")
        print (self.cols, self.rows, self.depth)
        v = np.zeros([self.cols,self.rows,self.depth])
        T = 590
        P = 28 * 100000
        R = 287
        c = 1005
        k = 1.4
        q = 20
        rho = P/(R*T)
        print(v)

        print("-------------")
        for x in range(self.cols ):
            print ("calculating column: ", x)
            for y in range(self.rows ):
                v_tmp = data_reduction_constant_time(self.ml_delta_temp[x,y,:],
                                                                self.integration,
                                                                rho, c, k)
                v[x,y,:] = v_tmp
        print("--- q done ---")
        print(v)

if (__name__ == "__main__"):
    dat = data()
    dat.calcQML()

self.ml_delta_temp is a (260, 300, 300) shaped numpy array. cols, and rows are the size of the array, and integration is the step size (how much time is between each 3rd axis slice).

Now the problem is: on my computer it takes almost a minute to calculate a single row.

How can I speed it up, or as the same question: in what part is this function losing the most time?

I can show the mathematical formula for the Cook and Felderman equation:

$$qCF = \frac{2\sqrt{\rho ck}}{\sqrt{\pi}}\sum_{i=1}^n \frac{T_i-T_{i-1}}{\sqrt{t_n-t_i}+\sqrt{t_n-t_{i+1}}}$$

Berry, S.A. and Horvath, T.J. Discrete
Roughness Transition for Hypersonic Flight Vehicles. Journal of Spacecraft and Rockets, 2:216{
227, March-April 2008. DOI 10.2514/1.30970.

Now this is to get the total heat at time "t_n", I am however interested in the heat flux profile, how it changes over time. So I need to calculate this formula for each n. Also I do know not T, but only delta-T (but as one can see that is only beneficial).


texts:
I just want to checking if this kind of routing is good or bad?

I implement the routing of my web appl to something like this.

All page will be pointing to the index.php

in index.php I have this code

$url = array_values(array_filter( explode( '/', strtolower($_SERVER["REQUEST_URI"]) ) ) );
switch( $url[0] ) {
    case "admin"    : {
        if( !$this->us->isAdmin ) {
            $this->GoToLoginPage();
        }
        array_shift( $uri );
        $department = new Admin( $uri );
    } break;
    case "article"  : {
        if( count( $uri ) == 2 ) {
            displayArticle( $uri[1] );
        }
        else {
            displayError();
        }
    } break;
    default : {
        displayIndex();
    } break;
}

I just want to know is there any pro and con of doing something like this.


texts:
(From Project Euler)

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

  Find the sum of all the primes below two million.

Can someone please help me improve this code?

import math

def main():
    lim = 2000000
    i = 2
    now = []
    total = 0
    for i in range(2,lim+1):
        for x in range(1,int(math.sqrt(i))+1):
            if len(now) ==2:
                break
            elif i % x == 0:
                now.append(x)

        if len(now) == 1:
            total += i
            print(total)
        now = []
    print(total)


texts:
This is a Tic Tac Toe game I wrote in Java (Swing). It fully works when detecting the winner or a tie. I'm wondering if there's any way I can improve it or clean it up.

I'm trying to achieve a 3 by 3 simple Tic Tac Toe game. The first player is X and the second player is O.

My X and O buttons are images. When a button is pressed, the value goes up. If it's odd, it's X. If it's even, it's O.

Because I didn't know how to compare images, I stored a parallel String array to compare the values. Should I be using a 2-D array?

/* Tic Tac Toe */

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class TicTacToe implements ActionListener {
    JFrame window = new JFrame("Tic Tac Toe");
    JButton b[] = new JButton[9];

    String letter = "";
    ImageIcon X;
    ImageIcon O;
    ImageIcon ltr;
    int value = 0;
    boolean win = false;
    String[] letters = new String[9];

    public TicTacToe() {
        // Initialize Array
        for (int i = 0; i < 9; i++) {
            letters[i] = "";
        }

        // Assign images
        X = new ImageIcon(getClass().getResource("X.png"));
        O = new ImageIcon(getClass().getResource("O.png"));
        // Create the Window
        window.setSize(500,500);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new GridLayout(3,3));

        // Add Buttons
        for (int i = 0; i < 9; i++) {
            b[i] = new JButton();
            window.add(b[i]);
        }

        // Add ActionListener
        for (int i = 0; i < 9; i++) {
            b[i].addActionListener(this);
        }

        window.setVisible(true);
    }

    public void actionPerformed(ActionEvent a) {
        value++;
        // Who's Turn
        if (value % 2 == 1) {
            ltr = X;
            letter = "X";
        }
        if (value % 2 == 0) {
            ltr = O;
            letter = "O";
        }

        // Display Letters
        for (int i = 0; i < 9; i++) {
            if (a.getSource() == b[i]) {
                b[i].setIcon(ltr);
                b[i].setDisabledIcon(ltr);
                b[i].setEnabled(false);
                letters[i] = letter;
            }
        }

        // Who Won

        // Horizontal
        if (letters[0].equals(letters[1]) && letters[1].equals(letters[2]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[3].equals(letters[4]) && letters[4].equals(letters[5]) && !letters[3].equals("")) {
            win = true;
        } else if (letters[6].equals(letters[7]) && letters[7].equals(letters[8]) && !letters[6].equals("")) {
            win = true;
        }

        // Vertical
        if (letters[0].equals(letters[3]) && letters[3].equals(letters[6]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[1].equals(letters[4]) && letters[4].equals(letters[7]) && !letters[1].equals("")) {
            win = true;
        } else if (letters[2].equals(letters[5]) && letters[5].equals(letters[8]) && !letters[2].equals("")) {
            win = true;
        }

        // Diagonal
        if (letters[0].equals(letters[4]) && letters[4].equals(letters[8]) && !letters[0].equals("")) {
            win = true;
        } else if (letters[2].equals(letters[4]) && letters[4].equals(letters[6]) && !letters[2].equals("")) {
            win = true;
        }

        if (win) {
            JOptionPane.showMessageDialog(null, "Player " + letter + " wins!");
            for (JButton i : b) {
                i.setEnabled(false);
            }
        } else if (!win && value == 9) {
            JOptionPane.showMessageDialog(null, "The game ended in a tie.");
        }
    }

    public static void main(String[] args) {
        new TicTacToe();
    }
}


texts: Reading Data from XML and storing them into SQL Database

texts:
I am developing a C# Windows forms application. In that, I am reading data from XML which is coming from a web API and storing that XML data into SQL database. I am able to achieve this. But my only concern is, In Production environment, this application will be in service and there will a lot of data to synchronize from XML to SQL Database. So, can anyone review my code and tell me whether it is an efficient way or not. Any sugggestions are welcome.

Because it's the first time I am working on the API and even in coding, I am a fresher.

I have done all to achieve my requirement. I would like a code review from experts.

public void save_vendor_info()
    {
    SqlConnection con = new SqlConnection(@"server=localhost;Database=TEST;integrated security=true");
    con.Open();
    DataTable dt = new DataTable();
    XmlDocument doc = new XmlDocument();
    doc.Load("https://testdata/api/vendordata");

    try
    {
        XmlNode node = doc.DocumentElement.ChildNodes.Cast<XmlNode>().ToList()[0];
        foreach (XmlNode column in node.ChildNodes)
        {
            dt.Columns.Add(column.Name, typeof(String));
        }

        XmlNode Filas = doc.DocumentElement;
        foreach (XmlNode Fila in Filas.ChildNodes)
        {
            List<string> Valores = Fila.ChildNodes.Cast<XmlNode>().ToList().Select(x => x.InnerText).ToList();

           SqlCommand cmd = new SqlCommand(("IF NOT EXISTS (Select Vendorcode From Vendors where Vendorcode = @Vendorcode) INSERT INTO Vendors VALUES (@Vendorcode, @STCD3, @Name1, @Name2, @Name3, @street1, @street2, @street3, @city1, @city2, @city3, @state1, @state2, @state3, @zip1, @zip2, @zip3, @countrycode, @BussinessUnitId, @VATID, @nationalVATID, @IBAN, @BankAccount, @BankCode)"), con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Vendorcode", Valores[0]);
            cmd.Parameters.AddWithValue("@STCD3", Valores[1]);
            cmd.Parameters.AddWithValue("@Name1", Valores[2]);
            cmd.Parameters.AddWithValue("@Name2", Valores[3]);
            cmd.Parameters.AddWithValue("@Name3", Valores[4]);
            cmd.Parameters.AddWithValue("@street1", Valores[5]);
            cmd.Parameters.AddWithValue("@street2", Valores[6]);
            cmd.Parameters.AddWithValue("@street3", Valores[7]);
            cmd.Parameters.AddWithValue("@city1", Valores[8]);
            cmd.Parameters.AddWithValue("@city2", Valores[9]);
            cmd.Parameters.AddWithValue("@city3", Valores[10]);
            cmd.Parameters.AddWithValue("@state1", Valores[11]);
            cmd.Parameters.AddWithValue("@state2", Valores[12]);
            cmd.Parameters.AddWithValue("@state3", Valores[13]);
            cmd.Parameters.AddWithValue("@zip1", Valores[14]);
            cmd.Parameters.AddWithValue("@zip2", Valores[15]);
            cmd.Parameters.AddWithValue("@zip3", Valores[16]);
            cmd.Parameters.AddWithValue("@countrycode", Valores[17]);
            cmd.Parameters.AddWithValue("@BussinessUnitId", Valores[18]);
            cmd.Parameters.AddWithValue("@VATID", Valores[19]);
            cmd.Parameters.AddWithValue("@nationalVATID", Valores[20]);
            cmd.Parameters.AddWithValue("@IBAN", Valores[21]);
            cmd.Parameters.AddWithValue("@BankAccount", Valores[22]);
            cmd.Parameters.AddWithValue("@BankCode", Valores[23]);

            cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {

    }
}


texts: Parse output of Google Cloud command into PHP associative array

texts:
This is my idea on how to turn Shell exec output in PHP to array output. I just want to share it and get feedback in case there is any better way.

Below is a code example to get server info from GCE.

$shell_command  = "gcloud compute instances list";
$result = shell_exec($shell_command);
//echo "\n$result\n";
$data = explode("\n",$result);
//print_r($data);
$headers = turn_linux_row_to_array($data[0]);
unset($data[0]);
$servers_array = array();
foreach($data as $row){
  $server_data = turn_linux_row_to_array($row,$headers);
   if(!empty($server_data)){
     $servers_array[] = $server_data;
   }
}
//function to move text out put to array
function turn_linux_row_to_array($row,$headers=array()){
$final_data_array = array();
$data_array_position = 0;
$row_length = strlen($row);
$current_word = '';
//echo "\nRow length is :: $row_length\n";
for($i=0; $i<$row_length; $i++){
   $char = substr( $row, $i, 1 );
    if($char != ' '){
     //This is a part of a value
     $current_word .=$char;
    }else{
    if($current_word!=''){
       if(!empty($headers) && isset($headers[$data_array_position]) ){
          $final_data_array[$headers[$data_array_position]] =
    $current_word;
       }else{
         $final_data_array[] = $current_word;
       }
       $data_array_position++;
   }
   $current_word = '';
 }
}
//print_r($final_data_array);
return $final_data_array;
}


texts: Collecting files from a particular directory

texts:
I'm writing an object oriented package, and one problem I am trying to solve is a class that will get all PHP files in a particular directory and instantiate the classes but not abstracts or interface types.

From an object oriented perspective, is this class SOLID?

<?php namespace Massculator;

class Collector
{
    public function collect($path, $gatewayNamespace)
    {
        $classes = new \RecursiveDirectoryIterator(dirname(__FILE__) . $path);

        foreach(new \RecursiveIteratorIterator($classes) as $file) {
            $class = basename($file);
            $class = str_replace('.php', '', $class);
            if(class_exists($gatewayNamespace . $class)) {
                $constructedClass = $gatewayNamespace . $class;
                if((new \ReflectionClass($constructedClass))->isAbstract())
                    $return[] = new $constructedClass;
            }
        }

        return $return;
    }
}

The class has one method and that method has a couple of tasks:

get files
parse only PHP files
instantiate non abstracts

It seems like this breaks the single responsibility principle, but creating another class simply to do a str_replace seems pointless. What do you think?


texts: Split a list into equal parts that using LINQ in a way that has good performance

texts:
So I have a method that looks like this:

   public static List<List<List<string>>> Split(List<List<string>> source, int chunksize)
   {
       return source
           .Select((x, i) => new { Index = i, Value = x })
           .GroupBy(x => x.Index / chunksize)
           .Select(x => x.Select(v => v.Value).ToList())
           .ToList();
   }

While this is nice and elegant and readable, unfortunately that groupby is killing performance because of the implicit sort. I need a way to rewrite this to be more performant, while still being reasonably elegant.


texts:
Can anything be improved in this code?

#include <iostream>
using namespace std;

void print(int *a, int n)
{
    int i=0;
    while(i<n){
        cout<<a[i]<<",";
        i++;
    }
}

void swap(int i,int j, int *a){
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

void quicksort(int *arr, int left, int right){
    int min = (left+right)/2;
    cout<<"QS:"<<left<<","<<right<<"\n";

    int i = left;
    int j = right;
    int pivot = arr[min];

    while(left<j || i<right)
    {
        while(arr[i]<pivot)
        i++;
        while(arr[j]>pivot)
        j--;

        if(i<=j){
            swap(i,j,arr);
            i++;
            j--;
        }
        else{
            if(left<j)
                quicksort(arr, left, j);
            if(i<right)
                quicksort(arr,i,right);
            return;
        }
    }
}

int main() {
    int arr[8] = {110, 5, 10,3 ,22, 100, 1, 23};
    quicksort(arr, 0, (sizeof(arr)/sizeof(arr[0]))-1);
    print(arr, (sizeof(arr)/sizeof(arr[0])));
    return 0;
}


texts: Logging a message and the stack trace of caught exceptions

texts:
Using Spring's JdbcTemplate to load a specific object by ID if exists, I have this code:

Person person = null;
try {
    person = jdbcTemplate.queryForObject(sql, new Object[]{ id }, new PersonMapper());
} catch (EmptyResultDataAccessException e) {
    LOGGER.warn("Could not find person with id " + id);
}

A Sonar rule (squid:S1166) complains about this piece of code, basically saying that logging a message is not enough, I should also log the exception. But in this case, I don't see the point. Adding the exception as a 2nd parameter to the logger will put a completely pointless stack trace in my logs that doesn't contain anything that I don't already know.

Would you agree that this is a false positive or am I missing something? Or is there another way of writing this code that complies better with Sonar or code quality analysis tools in general?


texts:
I have an array of objects that each have a name/value property.  The array can contain multiple objects with the same name property. I want to serialize this array into the form:

name:value,value|name:value|name:value,value,value

So basically each property is separated by a | and each value by a ,. The above example is not exactly how I want it to look, just an example of the syntax, results will vary based upon input.

Here is an example of the array:

var objs = [
    {name:"name1", value: "value1"},
    {name:"name4", value: "value4"},
    {name:"name3", value: "value3"},
    {name:"name2", value: "value2"},
    {name:"name2", value: "value2"},
    {name:"name2", value: "value3"}
];

I wrote some code to perform this serialization, but I wanted to see if anyone could suggest improvements to this code, I know there are some Javascript experts on this site and wanted to get their opinion:

function serialize(objs){
    var out = "";
    for(var i = 0; i < objs.length; i++){
        var propKey = objs[i].name + ":";

        if (out.indexOf(propKey) == -1){
            out += "|" + propKey;
        }

        var position = out.indexOf(propKey) + propKey.length;
        out = out.substring(0, position) + objs[i].value + "," + out.substring(position);
    }
    return out.substring(1,out.length-1).replace(/\,\|/g,"|");
}

JS Fiddle: http://jsfiddle.net/BHsuM/

BTW jQuery is acceptable.


texts:
I wrote two functions to read multi-line user input.

from os import linesep

def input_lines(prompt=None):
    """Yields input lines from user until EOFError is raised."""

    while True:
        try:
            yield input() if prompt is None else input(prompt)
        except EOFError:
            break
        else:
            prompt = None   # Only display prompt while reading first line.

def multiline_input(prompt=None):
    """Reads a multi-line input from the user."""

    return linesep.join(input_lines(prompt=prompt))

if __name__ == '__main__':
    print(multiline_input('Gimme your lines: '))

Is there something I can improve by maybe invoking some library method I overlooked?


texts: Validating input next token has a double

texts:
I was getting a NoSuchElementException when parsing my double so I had to refine my code to validate the input. Is there anything you recommend?

The reason it was throwing a NoSuchElementException was due to new Scanner(extractFieldValue( inputValues, input)); not having a double in the next token so if the input does not contain a double in the next token then I want to skip it. If it does then proceed with the code.

Code prior to the validation:

public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {
    Scanner scan = new Scanner(extractFieldValue( inputValues, input));
    String formatString = extractFieldValue( inputValues, format);
    DecimalFormat formatter = new DecimalFormat(formatString);
    return fillResult(formatter.format(number));
 }

Code after change that does validation on the input:

public List<Map<Field, List<String>>> dataLookup(Map<Field, List<String>> inputValues) {
    Scanner scan = new Scanner(extractFieldValue( inputValues, input));
    double number = 0;
    if(scan.hasNextDouble()) {
        number = scan.nextDouble();
    }
    String formatString = extractFieldValue( inputValues, format);
    DecimalFormat formatter = new DecimalFormat(formatString);
    return fillResult(formatter.format(number));
 }

extractFieldValue returns a String.


texts: Sorting a list of names by greatest lexicographical order

texts:
This is a puzzle I found online that I have been trying to optimize and make the best version. I've tested it and it works great but I'm curious how it can be improved in any way.

Instructions:

  "You forgot to give Professor Boolean's favorite rabbit specimen a
  name? You know how picky the professor is! Only particular names will
  do! Fix this immediately, before you're... eliminated!"

  Luckily, your minion friend has already come up with a list of
  possible names, and we all know that the professor has always had a
  thing for names with lots of letters near the 'tail end' of the
  alphabet, so to speak. You realize that if you assign the value 1 to
  the letter A, 2 to B, and so on up to 26 for Z, and add up the values
  for all of the letters, the names with the highest total values will
  be the professor's favorites. For example, the name Annie has value 1
  + 14 + 14 + 9 + 5 = 43, while the name Earz, though shorter, has value 5 + 1 + 18 + 26 = 50.

  If two names have the same value, Professor Boolean prefers the
  lexicographically larger name. For example, if the names were AL
  (value 13) and CJ (value 13), he prefers CJ.

  Write a function answer(names) which takes a list of names and returns
  the list sorted in descending order of how much the professor likes
  them.

  There will be at least 1 and no more than 1000 names.  Each name will
  consist only of lower case letters. The length of each name will be at
  least 1 and no more than 8.

  Test cases:

  Inputs:

(string list) names = ["annie", "bonnie", "liz"]

  Output:

(string list) ["bonnie", "liz", "annie"]

  Inputs:

(string list) names = ["abcdefg", "vi"]

  Output:

(string list) ["vi", "abcdefg"]

  Your code will run inside a Python 2.7.6 sandbox.

  Standard libraries are supported except for bz2, crypt, fcntl, mmap,
  pwd, pyexpat, select, signal, termios, thread, time, unicodedata,
  zipimport, zlib.

My answer:

def answer(names):
    # Sort names by reverse alphebetical order
    names = sorted(names, reverse=True)
    # Evaluate the value of each name and build a list with name,value pairs
    name_with_values = sorted([((current_name,value(current_name))) for current_name in names],
        key=lambda value: value[1], reverse=True)
    # Return the list only containing the names
    return [name[0] for name in name_with_values]

def value(name):
    # Evaluate and return value of the name
    return sum([ord(letter) - 96 for letter in name])

print answer(names = ["annie", "bonnie", "liz", "bpnnid"])

Feedback I'm interested in:

Is my logic easy to understand?
How can it be styled or named better?
Is it more complex or more computationally expensive than it needs to be?
How is the general readability/clarity?


texts: Using Comprehensions to Handle a Large Dataset in Python 2.7

texts:
I have a Python 2.7.6 script parsing large files (~60MB to ~2GB) containing lines of the following format:

  componentA componentB < floating point value >

My goal is to sum the floating point values for duplicate pairs of components and reflected pairs, reducing each pair to a single entry in the output file. For example, if I have the following three lines in the input file:

  componentA componentB 1.5
  componentB componentA 2.0
  componentA componentB 0.5

The output file should combine them into one entry:

  componentA componentB 4.0

Other notes:

The output also needs to be sorted by the lesser of each component pair.
I am not very concerned about the memory footprint of the routine because it will be run on a server with substantial amounts of RAM available. I am optimizing for speed and code maintainability.

The code I currently have accomplishes this by storing component names in nested dictionaries. The top-level dictionary maps component names to a second dictionary. The second-level dictionary maps the second half of each component pair to the floating-point value corresponding to the pair.

Example:

base_dict = {componentA: {componentB: 1.2,
                          componentC: 0.7}}

Output from this example would look like this:

  componentA componentB 1.2
  componentA componentC 0.7

Here is my code:

base_dict = {}

with open(input_file_name, 'r') as fi:
    for line in fi:
        component1, component2, value = line.split()
        (min, max) = (component1, component2) if (component1 < component2) else (component2, component1)

        if not min in base_dict:
            base_dict[min] = {max:float(value)}

        elif not max in base_dict[min]:
            base_dict[min][max] = float(value)

        else:
            base_dict[min][max] += float(value)

out_list = []
for component1, nested_dict in base_dict.iteritems():
    for component2, value in nested_dict.iteritems():
        out_list.append("{0}\t{1}\t{2}\n".format(component1, component2, value))

with open(output_file_name), 'w') as fo:
    fo.writelines(sorted(out_list))

In addition to a general code review for this snippet, there are two sections that I would like to convert to comprehensions if possible:

Constructing the nested dictionaries - I may be dealing with close to 10 million lines in the input file, and I would like to utilize implicit loops to do this.
Constructing the output list for sorting

If anyone has any completely different approaches to the problem of summing duplicate and reflected pairs, I'm all ears.


texts: What is the optimal way to write this small Todo List app

texts:
Hello I don't have any specific problem but I'm just interested how someone who is experienced in JavaScript would write this small toy program. it's a simple Todo List app, there are many approaches to writing something like this but I'm not sure if the way I wrote it is the most optimal.
I want to see how others would write this, and maybe learn something new.
I'm not very experienced programmer so any criticism  is welcome :)

const TodoList = document.getElementById("TodoList");
const AddTodo = document.getElementById("AddTodo");
let ToggleBtns = []; let RemoveBtns = [];

let MyTodos = [
    {todoText: "hello world", Completed: true},
    {todoText: "hello world", Completed: false},
    {todoText: "hello world", Completed: false}
];

function CreateItems(text, index){
    const TodoItem = document.createElement("li");
    const ToggleButton = document.createElement("button");
    const TodoText = document.createElement("p");
    const RemoveButton = document.createElement("button");

    TodoItem.className = "TodoItem";
    ToggleButton.className = "ToggleButton";
    TodoText.ClassName = "TodoText";
    RemoveButton.className = "RemoveButton";
    TodoText.innerText = text;
    TodoText.style.textDecoration = (MyTodos[index].Completed === true ? "line-through" : "none");
    TodoItem.appendChild(ToggleButton);
    TodoItem.appendChild(TodoText);
    TodoItem.appendChild(RemoveButton);
    TodoList.appendChild(TodoItem);

    ToggleBtns.push(ToggleButton);
    RemoveBtns.push(RemoveButton);
};
for (i in MyTodos) { CreateItems(MyTodos[i].todoText, i); }

AddTodo.addEventListener("keypress", function(e){
    if(e.keyCode === 13){
            MyTodos.push({todoText: AddTodo.value, Completed: false});
            CreateItems(MyTodos[MyTodos.length -1].todoText, (MyTodos.length -1))
     }
});
document.addEventListener("click", function(e){
        if(e.target.className === "ToggleButton"){
            ToggleIndex = ToggleBtns.indexOf(e.target);
            MyTodos[ToggleIndex].Completed =
            (MyTodos[ToggleIndex].Completed === true ? false : true);
            e.target.parentElement.children[1].style.textDecoration = (MyTodos[ToggleIndex].Completed === true ?  "line-through" : "none");
        }
        else if (e.target.className === "RemoveButton"){
            RemoveIndex = RemoveBtns.indexOf(e.target);
            if(RemoveIndex !== 0){
                MyTodos.splice(RemoveIndex, RemoveIndex);
                ToggleBtns.splice(RemoveIndex, RemoveIndex);
                RemoveBtns.splice(RemoveIndex, RemoveIndex);
            } else {
                MyTodos.splice(0, 1);
                ToggleBtns.splice(0, 1);
                RemoveBtns.splice(0, 1);
            }
            e.target.parentElement.remove();
        }
    });
 #TodoList {
            display: flex;
            flex-direction: column;
            padding: 0  ;
        }
        .TodoItem {
            display: flex;
            flex-direction: row;
        }
        .TodoItem button {
            width: 50px;
        }
        .TodoItem p {
            width: 300px;
            text-align: center;
        }
        #Todos {
            display: table;
            margin: 0 auto;
        }
        #AddTodo {
            display: table;
            height:35px;
            width: 70%;
            padding: 0 20px;
            margin: 0 auto;
        }

    <input type="text" name="" id="AddTodo">


texts: Better Design Pattern For Terminal-Like GUI

texts:
I am working on a java swing project that looks like a Terminal (but with less functionality).

The GUI contains a jTextArea to display output and a jTextField for user input.

Here is an application of the my GUI to perform a simple task.

Ask the user to enter a number.
If successful, ask the user to enter a smaller
If successful, prompt out the text "done!".

Is there a better way to do this other than state machine?

Here is the code:

package com.TerminalPanelGUI;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TerminalPanel extends javax.swing.JPanel
{
    private int state;

    /**
     * Creates a new Terminal Panel
     */
    public TerminalPanel()
    {
        state = 0;
        initComponents();

        textArea.setText("Enter a number: \n");

        textField.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                System.out.println("In action performed: state is " + state);
                switch(state)
                {
                    case 0:
                        State0();
                        break;
                    case 1:
                        State1();
                        break;
                }
            }
        });
    }

    private int dummy;

    private void State0()
    {
        try
        {
            dummy = Integer.parseInt(textField.getText());
            state = 1;

            //prompt for next state
            textArea.append("Enter a smaller number: \n");
        }
        catch(NumberFormatException e)
        {
            textArea.append("Invalid entry. Try again \n");
            state = 0;
        }
    }

    private void State1()
    {
        try
        {

            if(Integer.parseInt(textField.getText()) < dummy)
            {
                state = 2;

                //prompt for next state
                textArea.append("done!");
            }
            else
            {
                state = 1;

                //prompt for next state
                textArea.append("Enter a smaller number: \n");
            }
        }
        catch(NumberFormatException e)
        {
            textArea.append("Invalid entry. Try again \n");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        scrollPane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        textField = new javax.swing.JTextField();

        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        textArea.setEditable(false);
        textArea.setColumns(20);
        textArea.setRows(5);
        scrollPane.setViewportView(textArea);

        add(scrollPane, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 250));
        add(textField, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 270, 400, 30));
    }// </editor-fold>

    // Variables declaration - do not modify
    private javax.swing.JScrollPane scrollPane;
    protected javax.swing.JTextArea textArea;
    protected javax.swing.JTextField textField;
    // End of variables declaration
}


texts: Can the performance of this canvas drawImage() test be improved?

texts:
I have a quite simple loop that draws an 8px by 8px image many times in a canvas in a tiling fashion. Currently it's drawing 7500 images each loop.

See the jsfiddle.

var img = new Image();
img.src = 'http://i.imgur.com/3dzaMlv.png';

var W = 8;
var H = 8;
var R = 800/W;
var C = 600/H

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var fps = document.getElementById('fps');
var timePrev = new Date().getTime();
var fpsInterval = 30;
var i = 0;

window.setInterval(function() {

    ctx.clearRect(0, 0, 800, 600);

    for (var r=0 ; r<R ; r++) {
        for (var c=0 ; c<C ; c++) {
            ctx.drawImage(img, r*W, c*H);
        }
    }

    // fps
    if (i % fpsInterval == 0) {
        var timeNow = new Date().getTime();
        var spf = (timeNow - timePrev) / fpsInterval / 1000;
        fps.innerHTML = (1/spf).toFixed(2);
        timePrev = timeNow;
    }
    i++;

}, 1000/60);

On my I7-2700K (3.5GHz) processor and ATI Radeon HD7970, I am getting the following framerates:

Chrome 36.0.1985.143 m  :  ~40 FPS
Firefox 30.0            :  ~55 FPS
IE 11.0.9600.17239      :  ~35 FPS

Is there any way to improve FPS performance here, assuming I do actually need to draw this many tiles on each update?

To clarify, I'm requiring that they be drawn as individual tiles on each update. So, rendering them all to an off-screen canvas wouldn't work. I am essentially disappointed in the number of drawImage() calls that seems to perform well.


texts:
I know I can use the unix column function to replicate 90% of the functionality here, so this is mostly just to practice python. I find a misaligned fstab file really hard to read. This script parses the file and aligns the columns by determining the longest entry in each column and then padding each entry in the column to that length (plus an offset). Newlines are passed over and comment lines (starting with #) are formatted to ensure there is a space between the first '#' and the comment content.

Is there anything I'm missing that could make this code better or more readable?

from pathlib import Path
from typing import NamedTuple

FSTAB = Path('/etc/fstab')
OFFSET = 4 # number of spaces desired between columns

class FstabLine(NamedTuple):
    device_spec: str
    mount_point: str
    fs_type: str
    options: str
    dump: int
    pass_: int

def format_line(len_dict: dict, line: FstabLine) -> str:
    return (
        f"{line.device_spec:{len_dict['device_spec']}}"
        f"{line.mount_point:{len_dict['mount_point']}}"
        f"{line.fs_type:{len_dict['fs_type']}}"
        f"{line.options:{len_dict['options']}}{line.dump:{len_dict['dump']}}"
        f"{line.pass_}\n"
    )

def get_longest(lines: list) -> dict:
    d = {}
    for field in FstabLine._fields:
        if field == 'pass_':
            continue

        d[field] = max(
            [len(getattr(l, field)) for l in lines if isinstance(l, FstabLine)]
        ) + OFFSET

    return d

def parse(content: list) -> list:
    parsed_content = []
    for line in content:
        if line.startswith('#'):
            parsed_content.append(f'# {line.lstrip("#").strip()}\n')
        elif line.startswith('\n'):
            parsed_content.append(line)
        else:
            parsed_content.append(FstabLine(*line.split(maxsplit=6)))

    return parsed_content

def main() -> None:
    with FSTAB.open() as f:
        lines = f.readlines()

    lines = parse(lines)

    len_dict = get_longest(lines)

    with FSTAB.open('w+') as f:
        for line in lines:
            if isinstance(line, FstabLine):
                f.write(format_line(len_dict, line))
            else:
                f.write(line)

if __name__ == '__main__':
    main()


texts: Calculate food company sales for the year

texts:
I am working on a Python project where a food processing company is trying to calculate its total sales for the year. Python has to read from a text file where its divided into for categories split by commas.

The first category is the Type of product, which can be cereal, chocolate candy etc produced by the company.

The second category is the brand of the said product, for example, Kaptain Krunch for cereal or Coco Jam for chocolate. The third category is the sales for the last fiscal year (2014) and the last category is sales for this fiscal year(2015). Note that only sales for fiscal year 2015 are to be calculated. The 2014 has no use in this program but it is there.

Here is how the text file looks like, called product.txt:

  Cereal,Magic Balls,2200,2344

  Cereal,Kaptain Krunch,3300,3123

  Cereal,Coco Bongo,1800,2100

  Cereal,Sugar Munch,4355,6500

  Cereal,Oats n Barley,3299,5400

  Sugar Candy,Pop Rocks,546,982

  Sugar Candy,Lollipop,1233,1544

  Sugar Candy,Gingerbud,2344,2211

  Sugar Candy,Respur,1245,2211

  Chocolate,Coco Jam,3322,4300

  Chocolate,Larkspur,1600,2200

  Chocolate,Mighty Milk,1234,2235

  Chocolate,Almond Berry,998,1233

  Condiments,Peanut Butter,3500,3902

  Condiments,Hot Sauce,1234,1560

  Condiments,Jelly,346,544

  Condiments,Spread,2334,5644

What we are looking to do is to add the sales for Fiscal year 2015 by products and then the total sales for everything in 2015.

The output should look something like this in the written text file:

  Total sales for cereal in 2015 : {Insert total number here}

  Total sales for Sugar Candy in 2015 : {Insert total number here}

  Total sales for Chocolate in 2015 : {Insert total number here}

  Total sales for Condiments in 2015 : {Insert total number here}

  Total sales for the company in 2015: {Insert total for all the
  products sold in 2015}

Along with that, it should also print the grand total on the Python run screen in the IDE along with the text file:

  Total sales for the company in 2015: {Insert total for all the
  products sold in 2015}

Can I expand the program without using collections? Can I also expand the main function?

import collections

PRODUCT_FILE = "products.txt"
REPORT_FILE = "report.txt"

def main():
    # Easy way to get a dictionary where lookup defaults to 0
    categorycounts = collections.defaultdict(int)

    #open the files using with statements to ensure they're closed properly
    # without the need for an explicit call to close, even on exceptions
    with open(PRODUCT_FILE, newline='') as productfile,\
         open(REPORT_FILE, "w") as reportfile:
        rows = (line.rstrip().split(',')
        for line in productfile if line.rstrip())

        # Sum sales by product type letting csv parse
        # Filter removes empty rows for us; assume all other rows complete
        for category, brand, sales_lastyear, sales_thisyear in rows:
            categorycounts[category] += int(sales_thisyear)

        # Print categories in sorted order with their total sales
        for category, sales in sorted(categorycounts.items()):
            print('Total sales for', category, 'in 2015:', sales, file=reportfile)

        print('-'*80, file=reportfile) # Separator line between categories and total

        # Sum and print total sales to both file and screen
        totalsales = sum(categorycounts.values())
        print("Total sales for the company in 2015:", totalsales, file=reportfile)
        print("Total sales for the company in 2015:", totalsales)

if __name__ == '__main__':
    main()


texts: Stream JSON from Azure Cosmos DB to browser in Web API

texts:
I have an HTTP endpoint for returning data directly from Azure Cosmos DB. The endpoint is basically a database access point (this seems like a common case). Since I'm returning the data unmodified, there's no need to deserialize it, even though I have an object for Project on the server that is used elsewhere. I'm wondering if there are any ways to make this code more efficient, or tighter.

[Route("")]
public async Task<IHttpActionResult> GetProjects()
{
    await ValidateUser();
    var cosmosDb = await Storage.GetCosmosDb();
    var queryDefinition = new QueryDefinition($"SELECT * FROM projects project WHERE project.organization = '{CurrentUser.Organization}'");
    var projectsQuery = cosmosDb.Containers[typeof(Project)]
        .GetItemQueryStreamIterator(queryDefinition);
    var projects = new JArray();
    while (projectsQuery.HasMoreResults)
    {
        var responseMessage = await projectsQuery.ReadNextAsync();
        if (!responseMessage.IsSuccessStatusCode)
        {
            return InternalServerError(new Exception(
                $"Query item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}"));
        }

        using (var streamReader = new StreamReader(responseMessage.Content))
        using (var jsonTextReader = new JsonTextReader(streamReader))
        {
            var project = JObject.Load(jsonTextReader);
            ((JArray)project["Documents"]).ForEach(projects.Add);
        }
    }

    return Ok(projects);
}


texts:
I wrote this script to download images from Reddit. I would like to hear from others on how can I improve this script.

import requests as _requests
import os as _os

class Redpy:

    def __init__(self, user):
        """Enter a user agent"""
        print("hello")
        self.user = user

    def download(self, subreddit, number=5, sort_option=None):
        """Downloads images from subreddit.
            subreddit="Name of subreddit"
            number=Number of images to be downloaded
            sort_option=new/hot/top
        """
        subreddit.strip('/')
        if sort_option == None:
            sort_option = ''

        self.url = 'https://www.reddit.com/r/' + subreddit + '/'+  sort_option  +  '.json'

        self.user = {'user-agent':self.user}
        res = _requests.get(self.url, headers=self.user)

        if res.status_code != 200:
            print("Could not download")
            print(res.status_code)
            return

        self._DownloadFiles(res.json(), number)

    def _DownloadFiles(self, jsonfile, number_of_files):
        image_links = self._getImages(jsonfile, number_of_files)

        if not self.createFolder():
            print("Error creating folder")
            return

        index = 0 #used to name the files
        for image_link in image_links:
            image_link = image_link.replace('amp;', '')
            f = _requests.get(image_link)

            if f.status_code==200:
                media_file = open(f'{_os.getcwd()}/red_media/{index}.jpg', 'wb')

                for chunk in f.iter_content(100000):
                    media_file.write(chunk)
                media_file.close()
                print("Downloaded")
                index+=1
        print("Download complete")
        global flag
        flag=1

    def _getImages(self, jsonfile, number_of_files):

        images = [] #contains links of images
        for index in range(number_of_files):
            try:
                images.append(jsonfile['data']['children'][index]['data']['preview']['images'][0]['source']['url'])
            except Exception as e:
                print(e)
        return images

    @staticmethod
    def createFolder():
        try:
            if not _os.path.exists(f'{_os.getcwd()}\\red_media'):
                _os.mkdir(f'{_os.getcwd()}\\red_media')
                return True
            return True
        except Exception as e:
            print(e)
            return False

Things I would like to know:

Is there anything that I can do to improve the performance of the code
What can I do to improve the code styling. I have tried to follow the PEP standards as much as I could.
Anything else to improve the code.


texts: How to set multiple variables at once in JavaScript?

texts:
I have been setting multiple variables like this

function doSomething() {

    var FirstName = $FirstName.data("ov");
    var LastName = $LastName.data("ov");
    var Company = $Company.data("ov");
    var Website = $Website.data("ov");

}

I just read some reviewed code and both reviewers advised setting the variables in a single statement, like this:

function doSomething() {

    var FirstName = $FirstName.data("ov"),
        LastName = $LastName.data("ov"),
        Company = $Company.data("ov"),
        Website = $Website.data("ov");

}

What would be the advantage of doing it the second way? Is there a performance benefit? Is it that there is less code?


texts: Stopping Google from tracking Search results

texts:
I've created a brief UserScript (GitHub repository) for TamperMonkey to stop Google from hijacking Search results URLs for tracking purposes when you click them:

// ==UserScript==
// @include     http*://www.google.*/*
// @run-at      document-start
// ==/UserScript==
(function () {
    'use strict';
    function handleNodes(nodes) {
        for (var i = 0, j = nodes.length; i < j; i++) {
            handleNode(nodes[i]);
        }
    }
    function handleNode(node) {
        if (node.tagName === 'A' && node.onmousedown) {
            node.onmousedown = null;
        }
        handleNodes(node.childNodes);
    }
    document.onclick = null;
    var observer = new MutationObserver(function (mutations, observer) {
        for (var i = 0, j = mutations.length; i < j; i++) {
            var mutation = mutations[i];
            for (var k = 0, l = mutation.addedNodes.length; k < l; k++) {
                handleNode(mutation.addedNodes[k]);
            }
        }
    });
    observer.observe(document, { childList: true, subtree: true });
} ());

The script seems to work for both Google "Classic" and Google Instant doing its job.

Since I'm not a UserScript or DOM guru I'd like some feedback on it. Did I make any mistake or inefficiency? Is there something that can be improved?


texts:
I'm using the following code to unzip file which is working OK.
I'm getting file with the request (express) and  unzip it in specified folder

_unzip: function (req) {
        return new Promise((resolve, reject) =>{
            var noOfFiles = 0;
            let filePath = path.join(req.file.destination, req.file.filename);
            logger.info("Unzip filePath: " + filePath);
            if (req.file) {
                yauzl.open(filePath, function (err, zipFile) {
                    if (err) throw err;
                    zipFile.on('entry', (entry) =>{
                        //console.log(entry.fileName);
                        if (/\/$/.test(entry.fileName)) {
                            return;
                        }
                        zipFile.openReadStream(entry, (err, readStream) => {
                            if (err) {
                                logger.info(err);
                                reject(err);
                            } else {
                                // ensure parent directory exists, and then:
                                let destinationFileName = "./" + entry.fileName;

                                let directoryName = path.dirname(destinationFileName);
                                if (!fs.existsSync(directoryName)) {
                                    mkdirp(directoryName, (err) =>{
                                        if (err) {
                                            logger.info(err);
                                            reject(err);
                                        } else {
                                            writeIntoFile(readStream, destinationFileName, reject);
                                            noOfFiles++;
                                        }
                                    });
                                } else {
                                    writeIntoFile(readStream, destinationFileName, reject);
                                    noOfFiles++;
                                }
                            }
                        });
                    }).once('error', (err) =>{
                        logger.info(err);
                        reject(err);
                    }).once('close', () =>{
                        logger.info("Unpacked " + noOfFiles + " files");
                        resolve();
                    });
                });
            }
    });
}

https://github.com/thejoshwolfe/yauzl


texts:
I am a relatively new Python programmer and made a simple Pig Latin to English translator and vice versa. I would just like it if someone reviewed my code and see if anything can be done to make it more Pythonic or efficient.

from time import sleep

def main():
    to_piglatin = input("Do you want to translate something to piglatin[P], or to english[E]: ")

    while to_piglatin not in("p", "e"):
        to_piglatin = input("[P/E]")

    to_piglatin = ("e", "p").index(to_piglatin.lower())

    if to_piglatin:
        lang = "pig latin"
    else:
        lang = "english"
    question = "Enter a sentence to translate it into {}: ".format(lang)
    sentence = input(question)

    if not sentence.isalpha():
        print("Invalid input, please do not use numbers or punctuation marks")
        sleep(1)
        main()

    split_sentence = sentence.split()

    if to_piglatin:
        translated_sentence = [translate_to_piglatin(word) for word in split_sentence]
    else:
        translated_sentence = [translate_to_english(word) for word in split_sentence]

    translated_sentence = " ".join(translated_sentence)
    print(translated_sentence)
    input()
    return True

def translate_to_piglatin(word):
    vowels = 'aeiou'
    list_word = list(word)
    list_word = [x.lower() for x in word]
    first_letter = list_word[0]
    last_letter = list_word[-1]

    if last_letter.isalpha() == False:
        list_word.remove(last_letter)
    if first_letter in vowels:
        list_word.append('y')
        list_word.append('a')
        list_word.append('y')
    else:
        list_word.remove(list_word[0])
        list_word.append(first_letter)
        list_word.append('a')
        list_word.append('y')

    translated_word = "".join(list_word)
    return translated_word

def translate_to_english(word):
    list_word = list(word)
    last_three_letters = list_word[-3:]
    last_three_letters = "".join(last_three_letters)

    if last_three_letters == 'yay':
        vowel = True
    else:
        vowel = False

    if vowel:
        for i in range(0,2):
            del list_word[-1]
    else:
        del list_word[-1]
        del list_word[-1]
        last_letter = list_word[-1]
        list_word.remove(last_letter)
        list_word.insert(0, last_letter)

    translated_word = "".join(list_word)
    return translated_word

main()


texts:
This code is meant to find the median of a list of integers. The list is assumed to be of odd length.

This is based of this HackerRank question.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

from heapq import heappush, heappop

def median(l):
    heap = []
    for i in l:
        heappush(heap, i)
    cur_int = None
    mid = len(l) // 2
    for i in range(0, mid+1):
        cur_int = heappop(heap)
    median = cur_int
    return median

I think this algorithm is \$O(n)\$ time and space complexity. Please correct me if I'm wrong. I'm also open to any suggestions to improving its complexities or general performance.


texts:
I have a code that calls many times a function returning a list of the dates between two dates formatted as

  ('0001-01-01 00:01:00'),('0001-01-02 00:01:00'), ...

The current solution is:

import numpy as np
import time
from datetime import datetime

beg = datetime.strptime('01 01 0001', '%d %M %Y') #datetime
end = datetime.strptime('01 01 2001', '%d %M %Y')

def get_days(date1, date2):
    day_diff = (date1 - date2).days + 1
    days = [str(start_date + dt.timedelta(d)) for d in range(day_diff)]
    dates = "('" + "'),('".join(days) + "')"
    return dates

Is there a faster way to achieve this?

 #timing
 t0 = time.time()

dates_list = get_days(beg, end) #feed datetime

t1 = time.time()
total_create = t1-t0
print("list comprehension: ", total_create,'s')


texts:
I'm creating a program to determine whether or not a given year is a leap year. I just wanted to get anyone's feedback on it. I am aware of the calendar module in Python. I just wanted to try it from scratch.

year=int(raw_input("Input year:"))

if (year%4==0 and year%100==0 and year%400==0)or (year%4==0 and year%100 !=0 and year%400==0)or(year%4==0 and year%100 !=0 and year%400!=0):
  print str(year)+" is a leap year"
else:
    print str(year)+" is NOT a leap year"


texts: JavaScript plugin architecture for multiple methods with the same parameters

texts:
I am writing a JavaScript plugin for fun. The plugin allows the user to pass options to initialize the plugin and perform actions. It is a simple alert/confirm plugin just for fun.

I am hoping to receive some architecture help with a little bit of code I am working on. It works as is, but I feel like there is a better or more efficient way of doing what I am doing below.

The ideal syntax that the user would use (when utilizing the plugin) would go something like this:

new Bulletin('success', 'a title', 'a description', { duration: 2000 }).notify();

Or:

new Bulletin('warning', 'a title', 'a description', { duration: 2000 }).ask();

The plugin has 2 parts:

Get a few base parameters (color, title, description) as well as some optional parameters (duration, size, class, etc.)
Pass what type of notification is being initialized: notify (alert) or ask (confirm)

The current plugin implementation is this:

import Notify from './notify';
import Ask from './ask';

var default = {};

var Bulletin = function(color, message, title, options) {
  this.settings = Object.assign(defaults, options);
  this.color = color;
  this.message = message;
  this.title = title;

  return this;
};

Bulletin.prototype.notify = function() {
    Notify(this.color, this.message, this.title, this.settings);
};

Bulletin.prototype.ask = function() {
    Ask(this.color, this.message, this.title, this.settings);
};

Question/Problem

As you can see, the code works. I am wondering if there is a better, more efficient way of achieving this though.

Put simple, is there a way to do something like this (maybe ES6 has something?):

Use the constructor's properties without just referencing them with this
Depending on which method is called from the constructor (i.e. .notify()), perform different logic

The user of the plugin will be able to call either a notify or ask method which will either show an alert or confirm (ask for user input) box - think native JavaScript alert() and confirm(). Therefore, the code that performs those actions would be different. One would simply show a div and the other would show a div but with buttons for the user to select yes or no. But at the end of the day, they would share a lot of the same options. So what I am trying to avoid is duplicating code that is shared between the notify and ask methods, if possible.

The code for these features (notify & ask) is not written yet. I maybe should've waited before asking for a review, but really what I am after, and what will possible drive the rest of the development, is how to create a public JavaScript API that shares parts of "setup" code (gathering params, merging objects, etc.) but then has separate logic depending on which method is called.

Another option is to make the usage something like Bulletin.notify(params), but then I would want to be able to perform things like extend on the options, without writing that code twice for the 2 different types (notify and ask).

My inspiration (if you haven't guessed by now) is notie.js if that gives you an idea of where I'm headed. That may provide a clearer picture of what this code will do eventually.


texts: Send message with SignalR to client(s) from injected (IoC) method

texts:
I am new with SignalR and still a newbie with IoC Container SimpleInjector and I am wondering if there are any side effects and/or if I'm save with my chosen approach.

In my web app I have a SetupHub that invokes a method on an object resolved with SimpleInjector. This method may do anything that I'm not aware about. Maybe it contains Tasks and it may consume x units of time.

During this Setup process I want to inform the client of the progress. This is my current implementation and it works fine:

public class SetupHub : Hub
{
    public void Start()
    {
        // My SimpleInjector resolve wrapper
        IocContainer.Instance.GetInstance<ISetup>().Start(UpdateProgress);
    }

    private void UpdateProgress(double percentage)
    {
        Clients.Caller.updateProgress(percentage);
    }
}

public class Setup : ISetup
{
    public void Start(Action<double> updateProgress)
    {
        Task.Factory.StartNew(() =>
                              {
                                  updateProgress(10); // Bogus progress
                                  Thread.Sleep(100);  // Simulate x units of time
                                  CreateRoles();
                                  updateProgress(25);
                                  Thread.Sleep(400);
                                  CreateUsers();
                                  updateProgress(60);
                                  Thread.Sleep(200);
                                  CreateRelations();
                                  updateProgress(100);
                                  //CreateRelationGroups();
                              });
    }
}

public interface ISetup
{
    void Start(Action<double> updateProgress);
}


texts:
The following is my Ruby attempt at a (very) basic CSV file parser class, inspired by an exercise from the book Seven Languages in Seven Weeks. I'm a Ruby novice and will be grateful for any suggestions for improvement.

#!/usr/local/bin/ruby -w

# CSV file parser.
#
# USAGE:
# CsvFile.new('data.csv').each { |row| puts row.firstname }
#
class CsvFile

  # Parses the given CSV file into a collection of rows.
  #
  def initialize file
    @rows = []
    headers = file.gets.chomp.split(", ")
    file.each do |line|
      values = {}
      headers.zip(line.chomp.split(", ")).each do |key, value|
        values[key] = value
      end
      @rows << CsvRow.new(values)
    end
  end

  # Iterates over all rows.
  #
  def each
    @rows.each { |row| yield(row) }
  end

  # Returns the index-th row, or null if no such row exists.
  #
  def [] index
    @rows[index]
  end
end

# CSV row.
#
class CsvRow

  # Creates a new CSV row with the given values.
  #
  # * *Args*    :
  #   - +values+ -> a hash containing the column -> value mapping
  #
  def initialize values
    @values = values
  end

  # Returns the value in the column given as method name, or null if
  # no such value exists.
  #
  def method_missing name, *args
    @values[name.to_s]
  end
end

# TEST CASES
#

class AssertionError < RuntimeError
end

def assert &block
    raise AssertionError unless yield
end

require 'stringio'

file = StringIO.new(
"firstname, lastname, age, sex
Andrej, Beles, 25, male
Delia, Marin, 20, female
Henry, Prahanth, 33, male"
)

csvFile = CsvFile.new(file)

row = csvFile[0]
assert { row.firstname == "Andrej" }
assert { row.lastname == "Beles" }
assert { row.age == "25" }
assert { row.sex == "male" }

row = csvFile[1]
assert { row.firstname == "Delia" }
assert { row.lastname == "Marin" }
assert { row.age == "20" }
assert { row.sex == "female" }

row = csvFile[2]
assert { row.firstname == "Henry" }
assert { row.lastname == "Prahanth" }
assert { row.age == "33" }
assert { row.sex == "male" }

puts "DONE."


texts:
I was trying another approach of sorting a linked list. Aside from the available methods, I've decided to take each node from the linked list and place it into an array.  With that, I would be able to compare the data variables easily. I applied quickSort() on the array, and this is what I have.  I would appreciate any feedback/comments on my code.

    public static void main(String[] args) {

        MyLinkedList list = new MyLinkedList();

        Student s = new Student(1, "John", 20, "Italy", "2011");
        list.addStudent(s);
        Student s2 = new Student(2, "Mark", 19, "UAE", "2010");
        list.addStudent(s2);
        Student s3 = new Student(3, "Sally", 35, "UAE", "2000");
        list.addStudent(s3);

        System.out.println("Students in the list: ");
        list.print();

        Node[] n = list.convertA(list);
        quickSort(n, 0, (n.length-1));
        System.out.println("Sorted list is:");

        for(int q =0;q<n.length;q++){
            System.out.println(n[q] + " ");
        }
    }

    public static int partition(Node arr[], int left, int right) {

        int i = left, j = right;

        Node tmp;

        Node pivot = arr[(left + right) / 2];

        while (i <= j) {

            while (arr[i].getStudent().getAge() < pivot.getStudent().getAge()) {
                i++;
            }

            while (arr[j].getStudent().getAge() > pivot.getStudent().getAge()) {
                j--;
            }

            if (i <= j) {

                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i++;
                j--;

            }

        }
        return i;

    }

    public static void quickSort(Node arr[], int left, int right) {

        int index = partition(arr, left, right-1);

        if (left < index - 1) {
            quickSort(arr, left, index - 1);
        }

        if (index < right) {
            quickSort(arr, index, right);
        }
    }


texts:
When Page_Load is executed I assign the ImageUrl which is a IHTTPHandler:

imgView.ImageUrl = "ImageHandler.ashx" + "?rezeptId=" + rezeptId.ToString() +"&imageId=0";

Which looks like this:

public class ImageHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        int rezeptId = Int32.Parse(context.Request.QueryString["rezeptId"]);
        int imageId = Int32.Parse(context.Request.QueryString["imageId"]);

        List<Image> images = DBManager.GetRezeptImages(rezeptId);
        context.Response.ContentType = "image/png";
        context.Response.BinaryWrite(Helper.ImageToByteArray(images[imageId]));
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

The handler call is a static method from DBManager, a custom static class which provides LINQ-To-SQL queries. The method is called GetRezeptImages():

 public static List<Image> GetRezeptImages(int rezeptId)
    {
        using (CookBookDataContext ctx = new CookBookDataContext(Resources.ResourceFile.DBConnection))
        {
            IEnumerable<RezeptBilder> bilder = from b in ctx.RezeptBilders where b.FKRezept == rezeptId select b;
            List<Image> imageList = new List<Image>();

            foreach (RezeptBilder b in bilder)
            {
                imageList.Add(Helper.ByteArrayToImage(b.Bild.ToArray()));
            }

            return imageList;
        }
    }

This method simply loads image binaries from the database and converts them to Images:

public static Image ByteArrayToImage(byte[] byteArrayIn)
{
    using (MemoryStream ms = new MemoryStream(byteArrayIn))
    {
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
}

So basically this is all that happens when loading images. It is possible that GetRezeptImages() will return a List with more than one image but it is always only one that is loaded to image control.

But now I am experiencing some delays when loading an image:

Now i wonder what the reason is, here are some things I think could be the reason:

Images have to be compressed
My method implementation requires re-engineering.
Images are simply to big, which is somehow the same as they need to be compressed.
I am using a trial that my Webhoster provides. I haven't figured out if there is some speed limitations or somkething yet.

So I was hoping that someone with more experience in webdevelopement could give me some advice on this issue.


texts: Is there another way / proper way of  parsing this JSON array ?

texts:
I have a JSON object which holds some json_array like this: (with org.codehaus.jettison.json.*)

json array:[{"C1":["S1","S2"]},{"C2":["S1","S2"]},{"C3":["S1","S2"]},{"C4":["S1","S2"]}]

I have to get two list,one for keys,another for the elements of each key.I have done like this:

//sample: clusterIdList:[C1, C2, C3, C4] and serviceIdList:[S1, S2, S1, S2, S1, S2, S1, S2]

    //get jsonarray by key = serviceCode
    JSONArray array = incident.getJSONArray("serviceCode");

    List<String> clusterIdList = new ArrayList<String>();
    List<String> serviceIdList = new ArrayList<String>();
    String key="";

    for (int i = 0,length=array.length(); i < length; i++) {
        JSONObject b = array.getJSONObject(i);
        key = b.names().getString(0);
        clusterIdList.add(key);
        JSONArray sublist = b.getJSONArray(key);
        for (int j = 0,sublistLength = sublist.length(); j < sublistLength; j++) {
            serviceIdList.add(sublist.getString(j));
        }
    }

Is this a proper way to do this? or can it be improved? I am trying to improve my code quality and readability.


texts: Implementation of Point, Velocity and Acceleration in Haskell

texts:
I'm trying to implement point, velocity and acceleration types.

They should be connected by some derive function which:

takes time and velocity and returns a point increment;
takes time and acceleration and returns a velocity increment.

In pseudocode, it should look like this:

derive :: Time -> Velocity -> Point
derive :: Time -> Acceleration -> Velocity

Time is a type representing a time as floating value.

Point, Velocity and Acceleration are vectors.

So I don't want to

mix time values with any other floating values;
mix vectors representing points with velocity vectors and etc.

I came up with following solution.

{-# LANGUAGE KindSignatures, DataKinds, TypeOperators #-}

import Control.Comonad

import GHC.TypeLits
import Linear
import Linear.V2

-- Type of real numbers.
type R = Double

-- Type of vectors.
type Vector = V2

-- Wrapper to distinguish time values from other values.
newtype Time a = Time { fromTime :: a }

-- Time is intended to be a wrapper. But to implement a derive function,
-- I need a common way to extract value from wrapper. That's why Time
-- must be a Comonad's instance:

instance Functor Time where
    fmap f = Time . f . fromTime

instance Comonad Time where
    extract = fromTime
    duplicate = Time

{- Type of derivative.

     Type (D r v u a) means a derivation of (u a) by (v a) with rank r.

-}
newtype D (r :: Nat) (v :: * -> *) (u :: * -> *) a = D { fromD :: (u a) }

-- Using type D the point, velocity and acceleration types can be defined:
type Pnt = D 0 Time Vector R
type Vel = D 1 Time Vector R
type Acc = D 2 Time Vector R

-- Even if I don't want to mix points with velocities,
-- I do want them to behave like vectors. So I want
-- them to be Additive:

instance Functor u => Functor (D r v u) where
    fmap f = D . fmap f . fromD

instance Additive u => Additive (D r v u) where

    -- I didn't found a way how to make this Additive instance better.
    -- Applicative instance for (D r v u) doesn't help.

    zero = D $ zero

    x ^+^ y = D $ (fromD x) ^+^ (fromD y)
    x ^-^ y = D $ (fromD x) ^-^ (fromD y)

    lerp a x y = D $ lerp a (fromD x) (fromD y)

    liftU2 f x y = D $ liftU2 f (fromD x) (fromD y)
    liftI2 f x y = D $ liftI2 f (fromD x) (fromD y)

-- Now derive function can be implemented:
derive ::
    (Comonad v, Functor u, Num a) =>
        v a -> D (r + 1) v u a -> D r v u a

derive dv du = D $ (extract dv) *^ (fromD du)

This solution pretty mush does what I want:

I can't call derive on Pnt;
derive on Vel returns Pnt;
derive on Acc returns Vel.

I don't like:

the way how Additive instance for D r v u is implemented.
the fact that to derive a vector of real numbes I need to extract time value from a wrapper. It doesn't feel natural.

So ...

How can I edit an Additive instance for D r v u to avoid using common code with fromD?
Am I wrong about naturality which I meantioned above; is it ok to use wrappers like Time like I did in derive function?

Any suggestions are appreciated.