texts: Create a stream request for Transaction history by client id on Braintree vault

texts:
I have been trying to create a transaction history request from Braintree using a client ID on Braintree vault, and it took far too long to figure out how, so here is the code on server that I eventually used. Let me know if it can be improved.

Nodejs server side:

    exports.transaction_histroy = function(req, res) {
  if (req.user) {
      //where req.user.braintree id is the id saved on the local mongodb server.
      if (req.user.braintreeid) {
        var stream = require("stream");
        var customerStream = gateway.transaction.search(function (search) {
          search.customerId().is(req.user.braintreeid)
        });
        res.write("[");
        var first = true;
        customerStream.on("data", function (customer) {
          if (first) {
            first = false;
            var temp =  JSON.stringify(customer);
          } else {
            var temp =  "," + JSON.stringify(customer);
          }
          res.write(temp);
        });
        customerStream.on("end", function () {
          res.write("]");
          res.end();
        });
      }
    } else {
      res.redirect('/signin');
    }
  };

JQuery browser request:

function streamTransactions(){
$.ajax({
    url: '/users/'+user+'/transaction_histroy',
    success: function(data) {
        console.log(JSON.parse(data))
        $('#transaction_histroy').append(
            data
            )
    },
    error : function(err){
        console.log(err)
    }
});

HTML:


texts:
I started with Haskell some months ago, but didn't really use it since then. As a simple training I implemented Conways game of life. What/How could it be improved?

module Main where

import Control.Monad.State

data CellState = Dead | Alive deriving (Eq)
data Cell = Cell CellState Int deriving (Eq)
data Row = Row [Cell] Int deriving (Eq)
data Grid = Grid [Row]
data NextError = EmptyListError

type GridState a = State Grid a

instance Show Grid where
        show (Grid rows) = unlines $ map show rows

instance Show Row where
        show (Row cells n) = (show n) ++ ": " ++ (unwords $ map show cells)

instance Show Cell where
        show (Cell color _) = show color

instance Show CellState where
        show c = case c of
                Dead -> "_"
                Alive -> "#"

main::IO()
main = print $ run (execState initializeGrid (createGrid 20 20)) 100

run :: Grid -> Int -> [Grid]
run g n = scanl (\s f -> f s) g $ replicate n playRound

initializeGrid :: GridState ()
initializeGrid = do
        setPositionToColor 0 0 Alive
        setPositionToColor 1 1 Alive
        setPositionToColor 1 2 Alive
        setPositionToColor 2 0 Alive
        setPositionToColor 2 1 Alive
        setPositionToColor 4 4 Alive
        setPositionToColor 5 4 Alive
        setPositionToColor 6 4 Alive
        setPositionToColor 5 5 Alive
        setPositionToColor 5 4 Alive
        setPositionToColor 5 6 Alive

createGrid :: Int -> Int -> Grid
createGrid x y = Grid $ map createRow (take x [0,1..]) where
                        createRow = Row (map createCell (take y [0,1..]))
                        createCell = Cell Dead

setPositionToColor :: Int -> Int -> CellState -> GridState ()
setPositionToColor x y color = do
        grid <- get
        let rows = getRows grid
            cells = getCells (rows !! x)
            newState = Grid $ replaceListElement rows x $ Row (replaceListElement cells y $ Cell color y) x
        put newState

getCells :: Row -> [Cell]
getCells (Row c _) = c

getRows :: Grid -> [Row]
getRows (Grid r) = r

replaceListElement :: [a] -> Int -> a -> [a]
replaceListElement list position replacement =
        let (x, _:xs) = splitAt position list
        in x ++ replacement : xs

playRound :: Grid -> Grid
playRound (Grid rows) = Grid $ map (updateRow rows) rows

updateRow :: [Row] -> Row -> Row
updateRow rows row@(Row cells p) = Row (map (updateCell rows row) cells) p

updateCell :: [Row] -> Row -> Cell -> Cell
updateCell rows row cell@(Cell _ position) =
        let upperRowCells = getCells $ previous rows row
            upperCell = upperRowCells !! position
            lowerRowCells = getCells $ next rows row
            lowerCell = lowerRowCells !! position
            neighbourCells = [upperCell, lowerCell] ++
                getNextPrevious (getCells row) cell ++
                getNextPrevious upperRowCells upperCell ++
                getNextPrevious lowerRowCells lowerCell
            countLivingNeighbours = length $ filter (==Alive) $ map getCellColor neighbourCells
            isLiving = getCellColor cell == Alive
        in Cell (calcCellState isLiving countLivingNeighbours) position

getCellColor :: Cell -> CellState
getCellColor (Cell c _) = c

calcCellState :: Bool -> Int -> CellState
calcCellState living livingNeighbours
        | living && livingNeighbours < 2 = Dead
        | living && livingNeighbours <= 3 = Alive
        | living && livingNeighbours > 3 = Dead
        | not living && livingNeighbours == 3 = Alive
        | otherwise = Dead

getNextPrevious :: Eq a => [a] -> a -> [a]
getNextPrevious l e = [next l e, previous l e]

next :: Eq a => [a] -> a ->  a
next l@(x:_) e = case dropWhile (/= e) l of
                   (_:y:_) -> y
                   _ -> x

previous :: Eq a => [a] -> a -> a
previous l e = case takeWhile (/=e) l of
                [] -> last l
                x -> last x


texts: Type conversion between Node, Const_node, and their views

texts:
Each node is a location within a layer. A Location may be a pointer or an index. A Layer is a container.

There are 4 types of node per Layer and Location types:

Node: Can change content of layer. Not a view of another node.
Const_node: Cannot change content of layer. Not a view of another node.
Node_view: Can change content of layer. A view of a Node.
Const_node_view: Cannot change content of layer. A view of a Const_node.

The code implements the types, their conversions, and traits.

Thanks for reviewing this.

Code:

#include <type_traits>
#include <vector>
#include <iostream>

// Node
template<typename Layer, typename Location=typename Layer::size_type>
class Node {
public:
    Node(Layer& lay, Location loc)
            : layer(layer), location(loc) {}

    auto content() { return layer[location]; }

    template<typename Other_layer, typename Other_location,
            typename=std::enable_if_t<
                    std::is_constructible<Layer, Other_layer>::value
                    && std::is_constructible<Location, Other_location>::value
            >
    >
    operator Node<Other_layer, Other_location>() {
        return Node<Other_layer, Other_location>(
                layer, location
        );
    };

    Node& operator=(const Node& n) { location = n.location; }

private:
    Layer& layer;
    Location location;
};

template<typename L, typename Loc=typename L::size_type>
using Node_view=Node<L, Loc&>;
template<typename L, typename Loc=typename L::size_type>
using Const_node=Node<const L, Loc>;
template<typename L, typename Loc=typename L::size_type>
using Const_node_view=Node<const L, Loc&>;

// Traits
template<template<typename...> class, typename...>
struct can_instantiate_to : public std::false_type {
};

template<template<typename...> class U, typename... T>
struct can_instantiate_to<U, U<T...>> : public std::true_type {
};

template<typename T>
struct is_node : std::integral_constant<
        bool, can_instantiate_to<Node, T>::value> {
};

template<typename T, typename=std::enable_if_t<is_node<T>::value>>
void foo(T node) {}

int main() {
    using V = std::vector<int>;
    V v(10u);
    // Node n1(v, 0);  // Error as Location type is deduced to be int.
    Node<V> n1(v, 0u);
    Node_view<V> n2(n1);
    Const_node<V> n3(n1);
    Const_node_view<V> n4(n1);

    foo(n1);
    foo(n2);
    foo(n3);
    foo(n4);

    return 0;
}


texts: Project Euler 21: Sum of Amicable Numbers

texts:
Problem 21:

  Let \$d(n)\$ be defined as the sum of proper divisors of \$n\$ (numbers less than \$n\$ which divide evenly into \$n\$).
  If \$d(a) = b\$ and \$d(b) = a\$, where \$a ≠ b\$, then \$a\$ and \$b\$ are an amicable pair and each of \$a\$ and \$b\$ are called amicable numbers.

  For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore \$d(220) = 284\$. The proper divisors of 284 are 1, 2, 4, 71 and 142; so \$d(284) = 220\$.

  Evaluate the sum of all the amicable numbers under 10000.

Am I abusing reduce or itertools here? I'm concerned this solution could be more readable. Also, is there a more efficient solution rather than calculating everything up front?

from itertools import chain, count
from operator import mul

def factorize(n):
    for factor in chain((2,), count(start=3,step=2)):
        if factor*factor > n:
            break

        exp = 0
        while n % factor == 0:
            exp += 1
            n //= factor
        if exp > 0:
            yield factor, exp

    if n > 1:
        yield n, 1

def sum_of_factors(n):
    """
    >>> sum_of_factors(220)
    284
    >>> sum_of_factors(284)
    220
    """
    total = reduce(mul,
        ((fac**(exp+1)-1)/(fac-1) for fac,exp in factorize(n)),
        1)
    return total - n

if __name__ == '__main__':
    cache = {k: sum_of_factors(k)
        for k in xrange(1, 10000)
    }

    print sum(k for k, v in cache.iteritems()
        if cache.get(v, None) == k
        and v != k)


texts:
I want to check if the given string is a Panagram or not.

  A Panagram is a sentence containing every letter of the alphabet at least once.

This is what I've come up with as solution:

import java.util.Scanner;

public class Panagram {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String inputString = "";

        System.out.print("Enter the input: ");
        inputString = sc.nextLine();
        sc.close();

        if (inputString != null && inputString.length() > 0) {
            System.out.print("The given string, \"" + inputString + "\", is " + (isPanagram(inputString) ? "" : ("not ")) + "a Panagram");
        } else {
            System.out.print("Not a valid string!");
        }
    }

    /**
     * Checks if the given input is a panagram.
     *
     * @param inputString
     * @return boolean
     */

    private static boolean isPanagram(String inputString) {

        if (inputString.length() < 26) {
            return false;
        }

        inputString = inputString.toLowerCase();

        for (char i = 'a'; i <= 'z'; i++) {
            if (!(inputString.contains(i + ""))) {
                return false;
            }
        }

        return true;
    }

}

Any review comments or suggestions?

List of well known Panagrams.


texts:
The 'friendly form' of a number is written as a sum of reciprocals of distinct positive integers. eg. $$\frac{4}{5} = \frac{1}{2} + \frac{1}{4} +\frac{1}{20}$$

I have written a python program that calculates the friendly form of an inputted fraction.

import math
from fractions import Fraction

def decompose(x):
    if x.numerator == 1:
        return [x]

    # Finds the largest fraction m = 1/p which is less than or equal to x
    m = Fraction(1, math.ceil(float(1 / x)))
    x = x - m

    #Recursively returns a chain of fractions
    return decompose(x) + [m]

def main():
    inp = input("Enter positive fraction in form \"a/b\": ")

    try:
        x = Fraction(inp)
    except ValueError:
        print("Invalid input.")
        return

    if float(x) == 0:
        print("Enter non-zero value.")
        return

    if float(x) < 0:
        print("Converting to positive value.")
        x = -x

    if float(x) >= 1:
        print("Enter valid fraction")
        return

    answer = decompose(x)
    for a in answer:
        print(a)

if __name__ == "__main__":
    main()


texts: Printing removed items using lambdas and streams

texts:
I'm struggling to make my lambdas readable.

I've seen various approaches.  Below are three different examples that all do the same thing.

Forgive the example: I suspect there are better actual solutions to this problem. I'm only concerned with readability (and ultimately supportability).

/** Output any items that are present in "existing" but not in "updated" */
private static void outputRemovedItems(List<String> existing, List<String> updated) {
    // #1 simple for-loop
    for (String item : existing) {
        if (!updated.contains(item)) {
            System.out.println("item " + item + " removed");
        }
    }

    // #2 fluid lambdas
    existing.stream()
        .filter(item -> !updated.contains(item))
        .forEach(item -> System.out.println("item " + item + " removed"));

    // #3 awful-looking middle-ground: functions split out
    Predicate<String> onlyRemovedItems = item -> !updated.contains(item);
    Consumer<String> outputItems = item -> System.out.println("item " + item + " removed");
    existing.stream().filter(onlyRemovedItems).forEach(outputItems);
}

Personally, I find the lambda approaches more difficult to read than the simple for-loop: they make me think too much, which detracts from the readability.  So this is stopping me from using them in actual production code.
The more complex the operation, the worse my lambdas seem to look!

Does anyone have any tips to make my lambdas more readable?

Or.. do people from a functional programming background actually find the lambdas above easier to read than the loop?


texts: JSON AsyncTask refactoring to improve quality?

texts:
I'm new to Android. I was wondering if anyone had any suggestions. It's basically an AsyncTask to get a remote JSON array and put it into a native array.

Would be very grateful for suggestions.

package com.example.test2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Hashtable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

private String                  strCategoryJsonUrl      = "http://www.mydomain.com/categories.json";
getCategories                   myCategories;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myCategories            = new getCategories();
    myCategories.execute();
}//onCreate

private class getCategories extends AsyncTask<Integer, Integer, String>{

    @Override
    protected String doInBackground(Integer... intMyGuessLevel) {
        String strJson  = "";

        try {
            URL url = new URL(strCategoryJsonUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            strJson = readStream(con.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strJson;
    } //doInBackground

    private String readStream(InputStream in) {
        BufferedReader  reader      = null;
        String          strContent  = "";

        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                strContent  = strContent + line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } //finally

        return strContent;
    } //readStream

    protected void onPostExecute(String strResult) {
        int i                   = 0;
        String strValue         = "";
        TextView txtDebug       = (TextView) findViewById(R.id.txtdebug);
        String arrCategories[]  = new String[1];

        //parse JSON data
        try{
            JSONArray   jArray  = new JSONArray(strResult);
            //JSONObject  menu = jObject.getJSONObject("menu");
            arrCategories       =   new String[jArray.length()];

            for(i=0; i < jArray.length(); i++) {
                JSONObject jObject  = new JSONObject(jArray.get(i).toString());

                strValue            = jObject.getString("name");

                //put value into array
                arrCategories[i]    = strValue;
            }

            //debug output the array
            txtDebug.setText(Arrays.toString(arrCategories));

        } catch (JSONException e) {
            e.printStackTrace();
            txtDebug.append("Error in categories json file \n");
            txtDebug.append(String.valueOf(e));
        } // catch

    } //onPostExecute
} //getJsonContent

}


texts:
We had a requirement to remove the port number from the Request.Url.AbsoluteUr i.e

Actual:

  https://mysitename:443/Home/Index

Expected:

  https://mysitename/Home/Index

The code I used for this is

 string newUrl = context.Request.Url.AbsoluteUri.Replace(":" + context.Request.Url.Port, string.Empty);

This is working fine. but I'm eager to know is there any better way to do this?


texts:
I have been building a weather app that changes the background colour depending on the weather temperature and description.
This is the code I have to get it to work.
const body = document.querySelector('body');

const colorList = [
  {weather: 'Clear', color1: '#7AE7C7', color2: '#72C1E1'},
  {weather: 'Clouds', color1: '#F981BB', color2: '#7F7E84'},
  {weather: 'Drizzle', color1: '#b2c9c8', color2: '#698b8b'},
  {weather: 'Fog', color1: '#C5B2A6', color2: '#7F7E84'},
  {weather: 'Rain', color1: '#504AC4', color2: '#59AED1'},
  {weather: 'Snow', color1: '#bfc9cf', color2: '#77BDE0'},
  {weather: 'Thunderstorm', color1: '#314F71', color2: '#4A4176'},
  {weather: 'Tornado', color1: '#939393', color2: '#e47977c5'}

 ]

const colorList2 = [
      {color1: '#C94926', color2: '#BB9F34'},
      {color1: '#89a1dd', color2: '#E4E5E7' }
   ]

if(weather.list[0].main.temp < 5 && weather.list[0].weather[0].main == 'Clear') {
      body.style.backgroundImage = `linear-gradient(to bottom right,
      ${colorList2[1].color1}, ${colorList2[1].color2})`;
   } else if(weather.list[0].main.temp > 15 && weather.list[0].weather[0].main == 'Clear'){
        body.style.backgroundImage = `linear-gradient(to bottom right,
        ${colorList2[0].color1}, ${colorList2[0].color2})`;
     } else {
          colorList.forEach(color => {
             if(color.weather == weather.list[0].weather[0].main) {
                body.style.backgroundImage = `linear-gradient(to bottom right,
                ${color.color1}, ${color.color2})`;
   }

Is there a more efficient way of doing the same thing? Are forEach loops overkills? Should I use if else statements? Should I be doing it at all in JavaScript?
Many thanks in advance.


texts: Encode unicode codepoints to UTF-8 manually

texts:
I want to encode unicode codepoints to UTF-8 manually. I wrote the following C# code. I tested it with some cases I know, but I would like to know if it's correct for all inputs. I know that Unicode codepoints are undefined beyond 0x10FFFF ,but I don't care about that. Therefore the output of my method might be more than 4 bytes.

private byte[] CodePointToUtf8 (int codepoint)
{
    if (codepoint < 0x80) {
        return new byte[]{
            (byte)(codepoint)
        };
    } else if (codepoint < 0x800) {
        return new byte[]{
            (byte)(0xC0 | (codepoint << 21 >> 27)),
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x10000) {
        return new byte[] {
            (byte)(0xE0 | (codepoint << 16 >> 28)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x200000) {
        return new byte[] {
            (byte)(0xF0 | (codepoint << 11 >> 29)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x4000000) {
        return new byte[] {
            (byte)(0xF8 | (codepoint << 6 >> 30)),
            (byte)(0x80 | (codepoint << 8 >> 26)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else {
        return new byte[] {
            (byte)(0xFC | (codepoint << 1 >> 31)),
            (byte)(0x80 | (codepoint << 2 >> 26)),
            (byte)(0x80 | (codepoint << 8 >> 26)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    }
}

Bonus question: Is there an build in way to do that?


texts: Homework / toy program - character matching

texts:
Given a string A = "Hello world" and another string B = "wor", I have to print ("TRUE" or "FALSE") whether the characters in B are present in A. For example, if B = "ollw l" the result should be TRUE; if B = "worlds" the result should be FALSE; if B = "ww", result is FALSE. It has to be done in O(n) time complexity.

My solution is given below. Although this runs in O(n) time I would like some suggestions on how to improve.

int main(void)
{
        char *A = "Hello world";
        char *B = "ollw l";
        int table['z'] = {0};

        while (*A != '\0') {
                table[*A] += 1;
                A++;
        }

        while (*B != '\0') {
                table[*B] -= 1;
                if (table[*B] < 0) {
                        printf("%s\n", "FALSE");
                        return 0;
                }
                B++;
        }
        printf("%s\n", "TRUE");
}


texts: Find nearest k points from the central point

texts:
The task:

  Given a list of points, a central point, and an integer k, find the
  nearest k points from the central point.

  For example, given the list of points [(0, 0), (5, 4), (3, 1)], the
  central point (1, 2), and k = 2, return [(0, 0), (3, 1)].

My solution:

const lst = [[0, 0], [5, 4], [3, 1]];
const center = [1, 2];
const k = 2;

const findNearestPoints = ({lst, center, k}) => {
  // I assume the data are valid; no error checks
  const calcHypo = x => Math.sqrt((x[0] - center[0])**2
                                + (x[1] - center[1])**2);
  const sortPoints = (a,b) => calcHypo(a) - calcHypo(b);
  return lst
   .sort(sortPoints)
   .slice(0,k);
};

console.log(findNearestPoints({lst, center, k}));


texts:
I have written the following function to concatenate the parts of a name to produce the full name:

/**
 * Returns the full name of the Person.
 * @param boolean $includeTitle Whether to include the Person's title.
 * @param boolean $includeMiddleNames Whether to include the Person's middle names.
 * @param string $separator Separator character.
 * @return string Full name of the Person.
 */
public function getFullName($includeTitle = false, $includeMiddleNames = false, $separator = ' ') {
  if ($includeTitle && $this->getTitle()) {
    $name = $this->title;
  } else {
    $name = '';
  }
  if ($this->forename) {
    if ($name) {
      $name .= $separator;
    }
    $name .= $this->forename;
  }
  if ($includeMiddleNames && $this->middlenames) {
    if ($name) {
      $name .= $separator;
    }
    if ($separator != ' ') {
      // multiple middle names will be separated by spaces and so will need to be converted to $separator
      $name .= str_replace(' ', $separator, $this->middlenames);
    } else {
      $name .= $this->middlenames;
    }
  }
  if ($this->surname) {
    if ($name) {
      $name .= $separator;
    }
    $name .= $this->surname;
  }
  return $name;
}

I changed it to use an array and implode the parts - which has made it less lines, but I'm not really sure if it is written better as a result:

$nameParts = array();
if ($includeTitle && $this->getTitle()) {
  $nameParts[] = $this->title;
}
if ($this->forename) {
  $nameParts[] = $this->forename;
}
if ($includeMiddleNames && $this->middlenames) {
  if ($separator != ' ') {
    $middlenames = str_replace(' ', $separator, $this->middlenames);
  } else {
    $middlenames = $this->middlenames;
  }
  $nameParts[] = $middlenames;
}
if ($this->surname) {
  $nameParts[] = $this->surname;
}
return implode($separator, $nameParts);

I'm sure there must also be a better way but I can't think what. Any suggestions?


texts:
I have tried to create the async task using the RxJAVA2. The code is working fine. WHat enhancement can I do in this code?

private void createObservable(){

         progressDialog =new ProgressDialog(ProductActivityRx.this);
        progressDialog.setTitle("Data fetching...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        Observable<List<Product>> booksObservable =Observable.fromCallable(new Callable<List<Product>>() {
            @Override
            public List<Product> call() throws Exception {
                return getProductList();
            }
        }).doOnNext(new Consumer<List<Product>>() {
            @Override
            public void accept(List<Product> strings) throws Exception {
            }
        });

        productSubscription = booksObservable.
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Consumer<List<Product>>() {
                    @Override
                    public void accept(List<Product> productList) throws Exception {

                        displayData(productList);
                    }
                });

    }

I am updating the UI in displayData().


texts: Updating list of string while other threads are reading from it

texts:
I have a logging solution that writes down the hashes of messages. I consider some of these hashes to be safe and I want to skip logging those. I have implemented a whitelist that is a directory containing whitelisted hashes. There is a timer task that updates that list every 10 minutes.

I have tried testing it from multiple angles, but experience shows that it is near to impossible to generate the load with the diversity that I see in the wild. So could someone point out any shortcomings in my approach, only relevant parts showed:

public class MyLogger {

    private volatile AtomicReference<List<String>> whitelist = new AtomicReference<List<String>>();

    private void startWhitelistListener() {
        new Timer().scheduleAtFixedRate(
                new TimerTask() {
                    @Override
                    public void run() {
                        updateWhitelist();
                    }
                }, 1000, 60 * 10 * 1000
        );
    }

    private void updateWhitelist() {
        try{
            ArrayList<String> tempList = new ArrayList<String>();
            for (File f : scriptWhitelistDirectory.listFiles()){
                tempList.add(f.getName());
            }
            whitelist.set(tempList);
        } catch (Throwable ignore){}
    }
....
}

Now there will be threads accessing the whitelist like:

if (whitelist.get().contains(hash)) return null;

Is the implementation thread safe?


texts:
I wrote a simple program to sum the digits of a number in Clojure for learning purpose. Not very complex (I hope) so not adding any explanation. I am a beginner in Clojure so please don't mind pointing out even the most obvious mistakes.

NOTE: It recursively calculates the sum of digits in the result until a single digit result is obtained. For example, given "4312", 1 is returned (4312 -> 10 -> 1).

(defn sum-once [x]
  (reduce +
          (map
            #(Integer/parseInt (str %))
            (seq (char-array x)))))

(defn sum-digits [x]
  (let [y (sum-once x)]
    (if (< y 10) y
                 (sum-digits (str y)))))


texts:
My teacher gave us an exercise. We have to sort as quickly as possible. The fastest one gets a reward. On my own system, I am sorting 125000 words within 1.2 seconds. On my teacher's system that is 0.6s.

In my main.cpp I wrote the following code:

#include "FileStructure.h"
#include "Value.h"

template<typename T>
T* Merge(T* firstNode, T* secondNode)
{
  if (!firstNode) return secondNode;
  else if (!secondNode) return firstNode;

  else if (firstNode->getText() >= secondNode->getText())
  {
    firstNode->setPrev(Merge(firstNode->getPrev(), secondNode));
    return firstNode;
  }
  else
  {
    secondNode->setPrev(Merge(firstNode, secondNode->getPrev()));
    return secondNode;
  }
}

template<typename T>
T* Split(T* my_node)
{
  if (!my_node || !my_node->getPrev()) return NULL;
  T* secondNode = my_node->getPrev();
  my_node->setPrev(secondNode->getPrev());
  secondNode->setPrev(Split(secondNode->getPrev()));
  return secondNode;
}

template<typename T>
T* MergeSort(T* my_node)
{
  if (!my_node) return NULL;
  else if (!my_node->getPrev()) return my_node;
  return Merge(MergeSort(my_node), MergeSort(Split(my_node)));
}

int main(void)
{
  FileStructure f;
  Key* head = new Key();
  f.loadFile("data/gibberish.bin", *head);

  head = MergeSort(head);
  Key* tempHead = head; //values

  while (tempHead)
  {
    tempHead->setValuePtr(MergeSort(tempHead->getValuePtr()));
    tempHead = tempHead->getPrev();
  }
  // save sorted data into a new file called sorted.bin
  f.saveFile(*head, "sorted.bin");

  delete head;
  //newHead = NULL;

  return 0;
}

The key.h and value.h only have getters and setters. Key also has another method called AddValue().

This one is:

void Key::addValue(std::string word)
{
    if (key == word.substr(0, 2))
    {
        Value *temp = valueTail;
        valueTail = new Value(word);
        valueTail->setPrev(temp);
        return;
    }
    else if (prevKey)
    {
        prevKey->addValue(word);
        return;
    }
    prevKey = new Key();
    prevKey->setText(word.substr(0, 2));
    prevKey->valueTail = new Value(word);
}

All the other functions are inline functions.
As you can see it's dirty code. I removed as much as possible variables. I think it can be faster, but I don't know how.

I ran Gprof on my code:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  us/call  us/call  name
 72.73      0.24     0.24                             Key::addValue(std::string)
 12.12      0.28     0.04   151883     0.26     0.26  Value* Split<Value>(Value*)
  9.09      0.31     0.03   151883     0.20     0.20  Value* Merge<Value>(Value*, Value*)
  6.06      0.33     0.02      522    38.31    38.31  Value::~Value()
  0.00      0.33     0.00      522     0.00     0.00  Key* Merge<Key>(Key*, Key*)
  0.00      0.33     0.00      522     0.00     0.00  Key* Split<Key>(Key*)

Help me out please!
Btw: I have no memory leaks, thanks to valgrind.


texts: Implementing boost::upgrade_mutex using only standard locks

texts:
Is this my_upgrade_mutex class a valid implementation of boost::upgrade_mutex semantics? (Ignoring the try_* and *_for/*_until part.)

class my_upgrade_mutex
{
    std::mutex xmutex;
    std::shared_mutex smutex;
public:
    void lock_shared()//u->s
    {
        smutex.lock_shared();
    }
    void unlock_shared()//s->u
    {
        smutex.unlock_shared();
    }
    void lock()//u->x
    {
        xmutex.lock();
        smutex.lock();
    }
    void unlock()//x->u
    {
        smutex.unlock();
        xmutex.unlock();
    }
    void lock_upgrade()//u->g
    {
        xmutex.lock();
        smutex.lock_shared();
    }
    void unlock_upgrade()//g->u
    {
        smutex.unlock_shared();
        xmutex.unlock;
    }
    void unlock_upgrade_and_lock()//g->x
    {
        smutex.unlock_shared();
        smutex.lock();
    }
    void unlock_and_lock_upgrade()//x->g
    {
        smutex.unlock();
        smutex.lock_shared();
    }
    void unlock_and_lock_shared()//x->s
    {
        smutex.unlock();
        smutex.lock_shared()
        xmutex.unlock();
    }
    void unlock_upgrade_and_lock_shared()//g->s
    {
        xmutex.unlock();
    }
};


texts: Which one should I choose to work with, Facebook PHP-SDK or Graph Api with Curl?

texts:
I am new at facebook development using their PHP-SDK and Graph API. I am at the stage that I need to find which road should I take for a better/faster and efficient results.

I display the pages a user administrates in both ways. My question is which one should I choose?
Thank you community.

Using Facebook PHP-SDK

require 'src/facebook.php';
$results = $facebook->api('/fql', array('q'=>'SELECT page_id FROM page_admin WHERE uid = me()'));

    foreach($results['data'] as $result) {
        echo $result['page_id'], '
';
    }

Using CURL & Graph Api

$query = "SELECT page_id FROM page_admin WHERE uid = me()";
$encodedQuery = urlencode($query);

$url = "https://graph.facebook.com/fql?q=".$encodedQuery."&access_token=".$_SESSION['fb_100515270076928_access_token'];
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$results = curl_exec($ch);
$results = json_decode($results);

foreach ($results->data as $result) {
    echo $result->name, '
';
}


texts: Haskell 99, Problems 1-10 (simple list processing)

texts:
I'm just learning Haskell and I wanted to know if I'm going in the right direction with my solving of the Haskell 99 problems.  The file of interest is here which I've also reproduced below.

module OneToTen where

{-- Problem 1: Find the last element of a list. --}
myLast :: [a] -> a
myLast [] = error "Empty list."
myLast [x] = x
myLast (x:xs) = myLast xs

{-- Problem 2: Find the last but one element of a list. --}
myButLast :: [a] -> a
myButLast [] = error "Empty list."
myButLast [x] = error "One element list."
myButLast [x,y] = x
myButLast (x:xs) = myButLast xs

{-- Problem 3: Find the Kth element of a list. The first element in the list
 -- is number 1 --}
elementAt :: [a] -> Int -> a
elementAt [] _ = error "Empty list."
elementAt (x:_) 1 = x
elementAt (_:xs) n = elementAt xs (n-1)

{-- Problem 4: Find the number of elements of a list. --}
myLength :: [a] -> Int
myLength xs = myLengthAux xs 0

myLengthAux :: [a] -> Int -> Int
myLengthAux [] acc = acc
myLengthAux (_:xs) acc = myLengthAux xs (acc+1)

{-- Problem 5: Reverse a list. --}
myReverse :: [a] -> [a]
myReverse xs = myReverseAux xs []

myReverseAux :: [a] -> [a] -> [a]
myReverseAux [] acc = acc
myReverseAux (x:xs) acc = myReverseAux xs (x:acc)

{-- Problem 7: Flatten a nested list structure. --}
data NestedList a = Elem a | List [NestedList a]

flatten :: NestedList a -> [a]
flatten xs = flattenAux xs []

flattenAux :: NestedList a -> [a] -> [a]
flattenAux (List []) acc = acc
flattenAux (Elem x) acc = x:acc
flattenAux (List (x:xs)) acc = flattenAux (List xs) (acc ++ (flattenAux x []))

{-- Problem 8: Eliminate consecutive duplicated of list elements. --}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress (x:xs) = compressAux xs x [x]

compressAux :: (Eq a) => [a] -> a -> [a] -> [a]
compressAux [] y acc = acc
compressAux (x:xs) y acc | x == y = compressAux xs y acc
                         | x /= y = compressAux xs x (acc ++ [x])

{-- Problem 9: Pack consecutive duplicates of list elements into sublists. If a
 -- list contains repeated elements they should be placed in separate sublists.
 --}
pack :: (Eq a) => [a] -> [[a]]
pack [] = error "Empty list."
pack (x:xs) = packAux xs x [x] []

packAux :: (Eq a) => [a] -> a -> [a] -> [[a]] -> [[a]]
packAux [] _ xs acc = acc ++ [xs]
packAux (x:xs) y ys acc | x == y = packAux xs y (y:ys) acc
                        | x /= y = packAux xs x [x] (acc ++ [ys])

{-- Problem 10: Run-length encoding of a list.  Use the result of problem P09
 -- to implement the so-called run0length encoding data compression method. --}
encode :: (Eq a) => [a] -> [(Int,a)]
encode [] = error "Empty list."
encode xs = map (\ys -> (length ys, head ys)) (pack xs)

I'm most curious if implementing all of these auxiliary methods is standard practice?  It's easier for me to think of a recursive problem using an accumulator, consequently, I write most of them this way.  Is this correct?  Should I be writing them differently?


texts: Raise a list of integers to powers and return uniques

texts:
Problem (inspired by Project Euler 29):

  Consider all integer combinations of ab for X ≤ a ≤ Y
  and X ≤ b ≤ Y

  Return a sequence of distinct terms in numerical order

Input is a list of 2 integers separated by a space (" "), representing the lower and upper bounds (X Y). Input is read from txt file.
Output is a numerically sorted list of all unique numbers generated by the function (ab) , separated by space. Output is written to txt file.

Example:

Input:  2 5
Output: 4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125

And the code:

Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Imports System
Imports System.IO
Imports System.Windows.Forms
Module ProjectEuler29

    Sub Main()
        Dim myBounds = GetInput("C:\temp\square.txt")
        Dim myResults = UseBoundsToCreateList(myBounds)
        WriteToFile("C:\temp\square-answer.txt", myResults)
    End Sub

    Private Function GetInput(ByVal inputPath As String) As Integer()
        Dim returnText As String = File.ReadAllText(inputPath)
        Dim returnArray As String() = returnText.Split(New String() {}, StringSplitOptions.None)
        Return ConvertStringToIntegerArray(returnArray)
    End Function

    Private Function ConvertStringToIntegerArray(ByVal arrayOfStrings As String()) As Integer()
        Return Array.ConvertAll(arrayOfStrings, Function(str) Int32.Parse(str))
    End Function

    Private Function UseBoundsToCreateList(ByVal myBounds As Integer()) As String
        Dim numberOfIntegers = myBounds(myBounds.Length - 1) - myBounds(0) + 1
        Dim resultList As New List(Of Double)
        Dim i As Integer
        Dim myResult As Double
        For i = myBounds(0) To myBounds(0) + numberOfIntegers - 1
            For j = myBounds(0) To myBounds(0) + numberOfIntegers - 1
                myResult = i ^ j
                If Not resultList.Contains(myResult) Then resultList.Add(myResult)
            Next
        Next
        resultList.Sort()
        Return ChangeListDblToString(resultList)
    End Function

    Private Function ChangeListDblToString(ByVal resultList As List(Of Double)) As String
        Return String.Join(" ", resultList.ToArray)
    End Function

    Private Sub WriteToFile(ByVal outputPath As String, ByVal returnData As String)
        Dim fileAuthor As New StreamWriter(outputPath)
        If Not File.Exists(outputPath) Then File.CreateText(outputPath)
        fileAuthor.WriteLine(returnData)
        fileAuthor.Close()
    End Sub

End Module


texts:
I'm creating a simple registration form for a Linux installation party I'm organizing.

Although I'm a decent programmer, I rarely create HTML files. I want to know if this form is safe for my users and if it will work on most devices. Am I following all the good web development practices? Is my code pure HTML5?

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="UTF-8">
  <meta name="description" content="Installation fest inscription form">
  <meta name="author" content="name - email@example.com">
  <title>Installfest Inscription</title>

Installfest Inscription

  <form action="/action_page" method="post">
        First name:

        <input type="text" name="firstname">

        Last name:

        <input type="text" name="lastname">
        Laptop model:

        <input type="text" name="model">
  </form>

Thanks!


texts:
Over the past few weeks, I've been doing the Google Foobar challenges and I've been progressing quite well. I'm currently 1/3 of the way through the third level. However, there were plenty of times over the past few weeks where I felt that my code could have been a lot better. So today I stumbled upon this community and I think that it will be a good idea to ask you guys to review my code.

So this is what I was instructed to do:

  The fuel control mechanisms have three operations:

  Add one fuel pellet
  Remove one fuel pellet
  Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)

  Write a function called answer(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.

This is my solution:

    public static int answer(String n) {
        //convert n to BigInteger
        BigInteger x = new BigInteger(n);
        BigInteger two = new BigInteger("2");
        BigInteger three = new BigInteger("3");
        BigInteger y, z;
        int counter = 0;

        //Loop for as long as x is not equal to 1
        while(!x.equals(BigInteger.ONE)){
            //Check if x is divisible by 2
            if(x.mod(two).equals(BigInteger.ZERO)){
                //divide x by 2
                x = x.divide(two);
            } else {
                //subtract x by 1 and then divide by 2 store in variable z
                y = x.subtract(BigInteger.ONE);
                z = y.divide(two);
                //check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
                if(z.mod(two).equals(BigInteger.ZERO) || x.equals(three)){
                    x = y;
                } else {
                    x = x.add(BigInteger.ONE);
                }
        }
        counter++;
    }
    return counter;
}

For this challenge, I'm a lot more confident and happy with the cleanliness of my code compared to the previous challenges. But seeing that I'm still very much a newbie and this being my first time using BigInteger, I'd very much like a review.


texts:
This program adds an element to the end of a linked list of integers, which is previously keyed in by the user. This works fine on my computer, but I am wondering:

If there is a simpler way to do this (three procedures seems a lot for this)
If any of the code could potentially become problematic during future usage

program InserElement(input, output);
{Has the user type in integers and forms a linked list out of them,
then inserts an element at the end of that linked list and prints the
linked list with the added new element}

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes;

type
  tRefList = ^tList;
  tList = record
             info : integer;
             next : tRefList
            end;
var
 RefBeginning: tRefList;
 RefEnd : tRefList;
 Number : integer;

   procedure CreateList(var outRefBeginning: tRefList; var OutRefEnd: tRefList);
   { Creates a linear list through user input }
  var
   RefNew : tRefList;

  begin
   writeln('Please key in natural numbers. Key in 0 once you are done. ');
   readln(Number);
   while Number <> 0 do
   begin
     new (RefNew);
     RefNew^.info := Number;
     RefNew^.next := nil;
     if outRefBeginning = nil then
      begin
      outRefBeginning := RefNew;
      OutRefEnd := RefNew;
      end
     else
     begin
       outRefEnd^.next := RefNew;
       outRefEnd := RefNew
     end;
     readln (Number)
   end; { while-loop }
  end; {CreateList}

procedure InsertElement(inNumber : integer; var outRefBeginning : tRefList; var outRefEnd : tRefList);
  { Inserts a new element at the end of the list. outRefBeginning points to the first
  element of that list, outRefEnd points to the last element of it. The Value of inNumber is
  assigned to the record component info of the new element}

  var
   RefNew : tRefList;

  begin
  { Create and initialise new element }
  new(RefNew);
  RefNew^.info := inNumber;
  RefNew^.next := nil;
  { Insert element at the end of the linear list }
  if outRefBeginning = nil then
     begin
     outRefBeginning := RefNew;
     outRefEnd := RefNew
     end
     else
         begin
           outRefEnd^.next := RefNew;
           outRefEnd := RefNew;
         end;
  end;{ InsertElement }

  procedure PrintList;
  { Prints all elements of the linked list }

  var
   RefNew : tRefList;

  begin
   RefNew := RefBeginning;
   while RefNew <>  nil do
   begin
     writeln (RefNew^.info);
     RefNew := RefNew^.next
   end;
  end;

begin
  RefBeginning := nil;
  RefEnd := nil;
  CreateList(RefBeginning, RefEnd);
  InsertElement(5,RefBeginning,RefEnd);
  PrintList;
  readln;
end.


texts:
I have the following js code:

if (typeof errorCallback === "function") {
    var result = errorCallback.apply(this, arguments);
    // if errorCallback returns a non-false value, end execution
    if (result) {
        return result;
    }
}

// if there's no errorCallback or errorCallback returned 'false',
// 'null', 'undefined', '', 0, hell-knows-what-else ...
// note, that we don't return anything here
defaultErrorCallback.apply(this, arguments);

So far I came up with this:

return (typeof errorCallback=== "function"
    ? errorCallback.apply(this, arguments)
    : void 0) || defaultErrorCallback.apply(this, arguments);

But this will return (in some cases) the result of defaultErrorCallback whereas I want it to return undefined.

Can this code be shortened without changing functionality?


texts: Find and replace text inside text boxes in MS Word

texts:
I have this procedure to realise a find and replace on a word document. Since I have text boxes, using this way to do this is a bit a slower than what I'd like it to be, if it were just text on a plain doc document or tables and using  just:

Document.Content.Find.Execute(FindText:=Find, MatchWholeWord:=True, ReplaceWith:=Replace, Replace:=Word.WdReplace.wdReplaceAll)

It goes really fast. Any ideas please?

Sub ReplaceWord(Find As String, Replace As String, Document As Word.Document)
    Dim myStoryRange = Document.Range()
'Iterates thru all the storyranges and finds and replace with the parameters of the sub Find, Replace in Document
    For Each myStoryRange In Document.StoryRanges
        If myStoryRange.StoryType <> Word.WdStoryType.wdMainTextStory Then
            With myStoryRange.Find
                .Text = Find
                .Replacement.Text = Replace
                .Wrap = Word.WdFindWrap.wdFindContinue
                .Execute(Replace:=Word.WdReplace.wdReplaceAll)
            End With
            Do While Not (myStoryRange.NextStoryRange Is Nothing)
                myStoryRange = myStoryRange.NextStoryRange
                With myStoryRange.Find
                    .Text = Find
                    .Replacement.Text = Replace
                    .Wrap = Word.WdFindWrap.wdFindContinue
                    .Execute(Replace:=Word.WdReplace.wdReplaceAll)
                End With
            Loop
        End If
    Next myStoryRange
End Sub


texts: Checking if a number is a palindrome and is incrementing

texts:
Edit: Ok, this was a disaster of a question. I'll make sure to use timeit in the future

I solved a Codewars problem that had the user check if a number was a palindrome, was incrementing, and etc. After I solved it, I noted how the top solutions were much more simple, intuitive, and elegant than mine, although they were less efficient. I figured this was because code golf is more important in Codewars than efficiency, but after Googling around it seemed to me that perhaps a logically intuitive and elegant solution was more important in Python than an efficient but less elegant solution. Is there any truth to this?

To make this post more appropriate for the scope of Code Review, I will include two solutions for two problems, is_palindrome and is_incrementing. The first solution is the more elegant and logically intuitive one, and the second solution is my attempt at a more efficient one. I would like to know which solution is more appropriate for Python, and also what improvements could be made to my solution.

In Python, it is regularly suggested to use the following to determine if a string is a case-sensitive palindrome:

def is_palindrome(word):
    return word == word[::-1]

Here is my attempt at a more efficient way to accomplish this:

def is_palindrome(word):
    low = 0
    high = len(word) - 1
    while low < high:
        if word[low] != word[high]:
            return False
        low += 1
        high -= 1
    return True

As another example, to determine if a number is incrementing, such as 234 but not 231 it is suggested to use:

def is_incrementing(number):
    return str(number) in '0123456789'

Instead of something like:

def is_incrementing(number)
    number = str(number)
    prev = number[0]
    for char in number[1:]:
        if int(char) != int(prev) + 1:
            return False
        prev = str(int(prev) + 1)
    return True


texts:
I made a program that uses the Adafruit pressure sensor, and the DHT22 temperature and humidity sensor to log pressure, temperature and humidity every 30 minutes. I left it outside my house overnight yesterday in the hopes that it would have logged all the data overnight but it had logged only once. I'm guessing it drained the whole 9V battery in 30 minutes due to some inefficiency in my program? The program works when the sampling rate is at 2 seconds or something small like that. Please tell me how to make the program more efficient so it can do the logging every 30 minutes successfully.

    #include "DHT.h"
    #define DHTPIN 3
    #define DHTTYPE 22

    DHT dht (DHTPIN,DHTTYPE);

#include <SD.h>
#include <SPI.h>

#include "Wire.h"
#include "Adafruit_BMP085.h"

Adafruit_BMP085 mySensor;
File myData;

int cs = 4;//chipSelect for SD reader/Writer
double tempC;//holds temperature reading (Celcius)
double pressure;//holds pressure reading (Pascals)
double humidity;
double DHTtemp;
double finalTemp;

void setup() {
  // put your setup code here, to run once:
  dht.begin();
  SD.begin(cs); //initialize cardReader/Writer
  mySensor.begin();//initialize pressure sensor
  pinMode(10,OUTPUT);//the SD library requires pin 10 to be reserved as OUTPUT and not to be used.

  myData=SD.open("PTDATA.txt",FILE_WRITE);
  myData.println("Logging start at  8:30PM, logging 30-minute intervals");
  myData.println("Time,Temperature,Pressure,Humidity");
  myData.close();

}

void loop() {
//   put your main code here, to run repeatedly:
  myData=SD.open("RLDATA.txt",FILE_WRITE);

  if(myData)
  {
  tempC=mySensor.readTemperature();//read Temperature
  pressure=mySensor.readPressure();//read Pressure
  humidity=dht.readHumidity();
  DHTtemp=dht.readTemperature();//read temp from DHT Sensor

  myData.print(tempC);
  myData.print(",");
  myData.print(pressure);
  myData.print(",");
  myData.println(humidity);
  myData.close();
  delay(1800000);//30 min delay;

  }

 }


texts: Dict lookup with type conversion and fallback

texts:
Given the following working code:

def get(self, key, default=None, type=None):
    """Return the default value if the requested data doesn't exist.
    If `type` is provided and is a callable it should convert the value,
    return it or raise a :exc:`ValueError` if that is not possible.  In
    this case the function will return the default as if the value was not
    found:

    >>> d = TypeConversionDict(foo='42', bar='blub')
    >>> d.get('foo', type=int)
    42
    >>> d.get('bar', -1, type=int)
    -1

    :param key: The key to be looked up.
    :param default: The default value to be returned if the key can't
                    be looked up.  If not further specified `None` is
                    returned.
    :param type: A callable that is used to cast the value in the
                 :class:`MultiDict`.  If a :exc:`ValueError` is raised
                 by this callable the default value is returned.
    """
    try:
        rv = self[key]
        if type is not None:
            rv = type(rv)
    except (KeyError, ValueError):
        rv = default
    return rv

While it is clear that if we attempt to get a the value of a non-existent key, we will get a KeyError, it is not immediately discernible what will lead to a ValueError. It's only when we pass a string that does not contain an int do we see that this is where type() fails, and a ValueError is caught and handled.

How many actions to try before calling except? Should it not be written more explicitly and with more granularity thus:

try:
    rv = self[key]
except KeyError:
    rv = default
try:
    if type is not None:
        rv = type(rv)
except ValueError:
    rv = default
return rv


texts: Hexadecimal number to decimal conversion

texts:
I am a semi-beginner in C++ and I have a project in C++ to convert a hexadecimal integer into decimal equivalent, but I extended it and now this program can also convert a fractional part.

Logic I have used:

First the whole program is inside a do-while loop so that the user can convert a number as many time as desired.
Another do-while loop checks if the inputted number is valid or invalid. If invalid, it again asks the user for input.
A for loop counts the number of characters before the decimal point (if any).
Another for loop  converts the characters before the decimal point into a decimal number.
Another for loop converts the characters after the decimal point into a decimal fraction and adds it to the original number.
It prints it and asks if the user wants to again run the loop.

I have knowledge on selection statements (if-else), loops (for, while, do-while), operators and other basic things in C++.

Note: This program is compiled with MinGW and CodeBlocks. My school teacher uses TurboC++.

Please provide advice on things which I can understand; don't get too advanced. I want to score full marks on my school project but also want to understand the code.

// This is a C++ project for Unit Test 2 (2015-16). This program can convert a hexadecimal number into decimal equivalent.

#include <iostream>
#include<string.h>
#include<math.h>

using namespace std;
int main()
{
char choice;
cout<<" *** HEXADECIMAL TO DECIMAL CONVERTER ***";
do{                  //The whole program is inside a do-while loop, so that user can convert a number as many times as they want.
char hexd[120];
                                                         //This string will store the hexadecimal number input by the user.
int validn_count=0,length,lcopy,p=1,num,i,countp=0;
double decimal=0;

do{                                 //This do-while loop checks if the inputed number is valid or not. If not valid it again asks to enter the number.
cout<<"\n Enter a hexadecimal number for conversion (0-F): ";
cin>>hexd;
length=strlen(hexd);
for(int i=0;i<length;++i)
{
    if( (hexd[i]>=48 and hexd[i]<=57) or (hexd[i]>=65 and hexd[i]<=70) or      (hexd[i]>=97 and hexd[i]<=102) or hexd[i]==46)
      ++validn_count;
    else
       {
        validn_count=0;
        cout<<"\n ! WARNING! Invalid HEXADECIMAL NUMBER!!!!";
        break;
       }
}

}while(validn_count==0);

for(i=0;i<length;i++)   //This for loop checks how many characters are there before the decimal point (.)
{
    if(hexd[i]==46)
     break;
   else
     ++countp;

}
lcopy=countp;          // Copying the value of countp for usage in the  conversion.

for(i=0;i<countp;++i)  // This for loop converts all the character before    the decimal point (.) into decimal number and stores it in the variable 'decimal'.
 {
  if(hexd[i]>=48 and hexd[i]<=57)
    num=((int)hexd[i]-48);
  else if(hexd[i]>=65 and hexd[i]<=70)
   num=((int)hexd[i]-55);
  else if (hexd[i]>=97 and hexd[i]<=102)
    num=((int)hexd[i]-87);

 decimal=decimal+(num*pow(16,--lcopy));
 }

for(i=(countp+1);i<length;i++) // This for loop converts all the character after the decimal point (.) into decimal number and further stores it in the variable 'decimal'.
    {

    if(hexd[i]>=48 and hexd[i]<=57)
    num=((int)hexd[i]-48);
   else if(hexd[i]>=65 and hexd[i]<=70)
   num=((int)hexd[i]-55);
   else if (hexd[i]>=97 and hexd[i]<=102)
   num=((int)hexd[i]-87);

   decimal=decimal+(num*pow(16,-p));
    ++p;                                    //p is used for the multiply with 16 with negative powers.
   }

   cout<<" \n The decimal equivalent of hexadecimal number "<<hexd<<" is "    <<decimal;
  cout<<"\n Do you want to convert another hexadecimal number into decimal?   (Y/N): ";  // Asks if the user again wants to do a conversion.
 cin>>choice;
 }while(choice=='Y' or choice=='y');
cout<<"\n\n **** THANK YOU FOR USING THIS SOFTWARE ****";
return 0;
}


texts: Avoid branching code for degenerate cases in Fibonacci generator

texts:
I was writing a simple function that would return the Fibonacci sequence up to the nth term and for whatever reason started wasting a lot of time on it. Here's what I came up with:

static IEnumerable<int> Fibonacci(int n)
{
    int last = 0,
        oneBefore = 0;

    if (n > 0) yield return oneBefore = 0;
    if (n > 1) yield return last = 1;
    if (n > 2)
    {
        while (n-- - 2 > 0)
        {
            yield return last = oneBefore + (oneBefore = last);
        }
    }
}

This is pretty close to what I want, but it has those three ugly if branches at the top level. Initially, I was trying to do something like this for the 0 and 1 case:

yield return (new[] { 0, 1 }).Take(n);

So that it would nicely handle cases where n was 0, 1 or greater. Unfortunately C# doesn't allow mixing of returning complete enumerables with yield statements, so that didn't work.

So here are my questions for what I want to improve:

Is there a way I can avoid the if branches there and somehow elegantly and concisely deal with both degenerate cases?
Is there a way I can avoid having that variable initialization statement at the beginning of the function, or even better, avoid having to keep the two variables at all?


texts: Check the address String for presence of a New Brunswick abbreviation

texts:
I need to check if there are any abbreviation of New Brunswick province in the address. Acceptable abbreviations are: "NB", "N.B.", "N-B", "N.-B." and any combination of upper-lower cases. It shouldn't be a part of another word, hence the "\b" separators.

The hardest part was checking the dot in the end, because of the greediness of the "\b". So, the part "\.\b" doesn't work, because the dot is within the word boundary, so it is being "attached" to "\b".

Is there a way to avoid such behaviour and are there other suggestions to improve on the regex?

return addressLine?.matches(".*\\b([nN]-?[bB]\\b|[nN]\\.-?[bB]\\.).*")


texts: Listing the differences between corresponding elements of two arrays or two objects

texts:
Mind the code below:

var deltaArray = function(a,b){
    var deltaPtrs = [];
    var deltaVals = [];
    for (var i=0, l=a.length; i<l; ++i)
        if (a[i] !== b[i])
            deltaPtrs[deltaPtrs.length] = i,
            deltaVals[deltaVals.length] = b[i];
    return [deltaPtrs,deltaVals];
};

var deltaHash = function(a,b){
    var deltaKeys = [];
    var deltaVals = [];
    for (var key in b)
        if (a[key] !== b[key])
            deltaKeys[deltaKeys.length] = key,
            deltaVals[deltaVals.length] = b[key];
    return [deltaKeys,deltaVals];
};

That code is obviously duplicated. Considering that the length of the involved arrays/objects is huge (>1kk elements), and that adding an if inside the loop would be detrimental to performance, is there any way to avoid this duplication?

Edit: here is a JSPerf for your enjoyment.


texts: Is brute force the accepted best practice for handling Excel COM 'busy' exceptions?

texts:
Following on from a question about handling-com-exceptions-busy-codes I would like to know if the following model is the accepted best practice of handling Excel COM busy messages when accessing the Excel COM object model:

private void AskExcelToDoSomething()
{
    bool retry = true;
    do
    {
        try
        {
            // Call Excel OM
            retry = false;
        }
        catch (COMException e)
        {}
    } while (retry);
}

Assuming that IMessageFilter has been implemented and catches the errors for which it is intended and retries, is the above model the 'accepted' way of handling these busy exceptions? If so, is it not vulnerable to hanging if for some reason it keeps being rejected? Is there no better way of doing this that guarantees success?


texts:
I have this string that I am sometimes double encoding it because it is coming from two different fields. I have build this method that will do a string StringComparison. It seems complicated wanted to know if there is a better way to do something like this.

 class Program
    {
        static void Main(string[] args)
        {

            string str1 = "This string is already encode &lt;0.1";

            Console.WriteLine(HTTPEncodeString(str1));

            string str2 = "This string needs to be encoded <0.01";
            Console.WriteLine(HTTPEncodeString(str2));

        }

        public static string HTTPEncodeString(string source)
        {
            if (EncodeText(source))
            {
                return source;

            }
            else
            {
                return HttpUtility.HtmlEncode(source);
            }

        }

        public static bool EncodeText(string val)
        {
            string decodedText = HttpUtility.HtmlDecode(val);
            string encodedText = HttpUtility.HtmlEncode(decodedText);

            return encodedText.Equals(val, StringComparison.OrdinalIgnoreCase);

        }
    }


texts:
Previous iteration.

I think this is about as good as it's gonna get, but just for kicks, let's do one more round of iterations.

As before, it's a very simple substitution from Brainfuck to Ruby, with fancy things like joining duplicate lines into one and indentation.

Some things that bug me:

The regex (/\++|-+|<+|>+|[.,\[\]]/) feels like it can be simplified, but I can't figure out how.
I feel like the map can be simplified, but I can't figure out how.
The constant repetition of #{'  ' * indent_level} bugs me, but I can't see how to get rid of it.
indent_level being declared outside of the scope of each feels like an anti-pattern, but AFAICT there's no better way to do it.

input_file, output_file = ARGV
code = IO.read(input_file).delete('^+-<>.,[]')

open(output_file, File::CREAT | File::WRONLY) do |output|
  output.puts <<-END.gsub(/^[ \t]*\||\s*#@.*$/, '')
    |#!/usr/bin/env ruby
    |class Mem < Hash #@ Hash because it's more memory-efficient and allows negative values.
    |  def initialize; super(0); end
    |  def []=(i, val); super(i, val & 255); end
    |end
    |data = Mem.new
    |pointer = 0
  END
  indent_level = 0
  code.scan(/\++|-+|<+|>+|[.,\[\]]/)
      .map do |string|
        case string[0]
          when '+' #String of "+"
            next "#{'  ' * indent_level}data[pointer] += #{string.length}"
          when '-' #String of "-"
            next "#{'  ' * indent_level}data[pointer] -= #{string.length}"
          when '<' #String of "<"
            next "#{'  ' * indent_level}pointer -= #{string.length}"
          when '>' #String of ">"
            next "#{'  ' * indent_level}pointer += #{string.length}"
          when '[' #Single "["
            ret = "#{'  ' * indent_level}until data[pointer] == 0"
            indent_level += 1
            next ret #Split it so that it's clear that indent is increased *after* the line
          when ']' #Single "]"
            indent_level -= 1
            next "#{'  ' * indent_level}end"
          when ',' #Single ","
            next "#{'  ' * indent_level}data[pointer] = $stdin.readbyte"
          when '.' #Single "."
            next "#{'  ' * indent_level}putc data[pointer]"
        end
      end.each { |line| output.puts(line) }
end


texts:
How can I make this code snippet better? Those for loops in if don't please me but they are covered with code lines that is dependent to if before and after.

public int hammingDistance(int x, int y) {
    String binx = Integer.toBinaryString(x);
    String biny = Integer.toBinaryString(y);

    int dif = 0;
    StringBuilder sb = new StringBuilder();

    if (binx.length() > biny.length()) {
        dif = binx.length() - biny.length();

        for (int i = 0; i < dif; i++) {
            sb.append(0);
        }

        biny = sb.toString().concat(biny);
    } else if (biny.length() > binx.length()) {
        dif = biny.length() - binx.length();

        for (int i = 0; i < dif; i++) {
            sb.append(0);
        }

        binx = sb.toString().concat(binx);
    }

    int dist = 0;

    for (int i = 0; i < binx.length(); i++) {
        if (binx.charAt(i) != biny.charAt(i)) {
            dist++;
        }
    }

    return dist;
}


texts:
I came across an interesting method of solution for the Tower of Hanoi puzzle
and wrote a short version of it as a programming exercise.

The program produces the correct results but I have two questions.

First is there simpler way to write the alternating step of determining the
only valid move which does not involve the smallest disk.

Second when I try to make the two primary routines (move smallest disk and
make alternating move) into functions the handling of variables becomes
unwieldy.

/* tower.c

   Tower of Hanoi -- mechanical solution

   Arrange the three rods to form a triangle.

   Alternate between moving the smallest disk and making the only valid move
   which does not involve the smallest disk.

   The following rule will make sure that the tower of disks end up on the
   destination rod: if the number of disks in the puzzle is an odd number
   always move the smallest disk counter-clockwise around the triangle; if
   the number of disks in the puzzle is an even number always move the
   smallest disk clockwise around the triangle.
*/

#include <stdio.h>
#include <stdbool.h>

int destinationCount (int array[], int numberOfElements)
{
    int count = 0, i;

    for ( i = 1; i <= numberOfElements; ++i )
        if ( array[i] == 3 )
            ++count;

    return count;
}

int main (void)
{
    int numberOfDisks, i, smallestDir, moveCount = 0;
    bool everyOtherMove = false;
    int rodFrom, rodTo, disk;
    int topDisk[4];
    int temp;

    printf ("\nTower of Hanoi puzzle\n");

    printf ("\nnumber of disks? ");
    scanf ("%i", &numberOfDisks);

    int rod[numberOfDisks + 1];

    // all disks start on rod 1

    for ( i = 1; i <= numberOfDisks; ++i )
        rod[i] = 1;

    // set direction to move smallest disk

    if ( (numberOfDisks & 1) == 0 )
        smallestDir = 1;
    else
        smallestDir = -1;

    printf("\nsolution\n\n");

    do {

        ++moveCount;

        if ( ! everyOtherMove ) {

            // move smallest disk

            rodFrom = rod[1];

            rodTo = rodFrom + smallestDir;
            if ( rodTo > 3 )
                rodTo = 1;
            if ( rodTo < 1 )
                rodTo = 3;

            disk = 1;

        }
        else {

            // make only valid move not involving the smallest disk

            // find disk at the top of each rod

            for ( i = 1; i <= 3; ++i )
                topDisk[i] = numberOfDisks + 1;

            for ( i = numberOfDisks; i >= 1; --i )
                topDisk[rod[i]] = i;

            // find which disk to move

            switch ( rod[1] )
            {
                case 1:
                    rodFrom = 2;
                    rodTo = 3;
                    break;
                case 2:
                    rodFrom = 1;
                    rodTo = 3;
                    break;
                case 3:
                    rodFrom = 1;
                    rodTo = 2;
                   break;
                default:
                    printf ("error");
                    break;
            }

            if ( topDisk[rodFrom] > topDisk[rodTo] ) {
                // swap values
                temp = rodFrom;
                rodFrom = rodTo;
                rodTo = temp;
            }

            disk = topDisk[rodFrom];

        }

        printf ("%i: disk %i rod %c to rod %c\n", moveCount, disk,
                 rodFrom + 64, rodTo + 64);

        // move disk

        rod[disk] = rodTo;

        // toggle everyOtherMove

        everyOtherMove = ! everyOtherMove;

    }
    while ( destinationCount (rod, numberOfDisks) != numberOfDisks );

    return 0;
}


texts: Parsing JSON in one go using state machine solution

texts:
I need to parse a simple JSON string (flat JSON, no hierarchy) for keys and values, and there is a system constraint that I cannot use any built-in JSON library and can only read a string once due to latency requirements. I need to use Python 2.7.x series and cannot use a higher version.

Note: This question is version 3 of my code to solve this problem.

Version 1 - answered by @holroy
Version 2 - answered by @Tersosauros

This is a new version of code based on guidance from @Tersosauros' post of the previous version. Note that I still do not handle some corner cases. I do not want to use two state variables as with @Tersosauros' code, but rewrote using only one state variable. I am not 100% confident if my code is correct logic and your advice is highly appreciated.

READY = 0
COLON = 1
COMMA = 2
STRING = 3
NUMBER = 4

numbers='0123456789.'
NoOps=' {'

def parse(strJSON):
    state = READY
    lastKey=''
    lastValue=''
    temp=''
    result={}
    for c in strJSON:
        if state == READY:
            if c in NoOps:
                continue
            elif c == '"':
                state = STRING
            elif c == ':':
                lastKey=temp
                temp=''
                state = READY
            elif c == ',' or c=='}':
                lastValue=temp
                temp=''
                if lastKey:
                    result[lastKey]=lastValue
                    lastValue=''
                    lastKey=''
                    state=READY
            elif c in numbers:
                state=NUMBER
        elif state == STRING:
            if c == '"':
                state = READY
            else:
                temp += c
        if state == NUMBER:
            if c in NoOps or c==',' or c=='}':
                lastValue=temp
                temp=''
                if lastKey:
                    result[lastKey]=lastValue
                    lastValue=''
                    lastKey=''
                state=READY
            else:
                temp+=c

    if lastKey:
            result[lastKey]=lastValue

    return result

if __name__ == "__main__":
    #JSONString = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": ["home", "green"]}'
    JSONString1 = '{ "id": "1", "name": "A green door", "price": "12.50", "tags": "home green"}'
    JSONString2 = '{ "id": 1, "name": "A green door", "price": 12.50, "tags": "home green"}'
    print parse(JSONString1)
    print parse(JSONString2)


texts: Multiplication of 3×3 and N×N square matrices

texts:
I recently wrote a matrix module in C++.

During the development process I quoted some source code and found a problem.

For example, matrix multiplication:

This way is suitable for all N×N matrices：

void multiplyMatrix(const float32* a, const float32* b, float32* dst,
                    int32 aColumns, int32 bColumns, int32 dstColumns, int32 dstRows) {

    for (int32 i = 0; i < dstRows; i++) {

        for (int32 j = 0; j < dstColumns; j++)
            dst[i * dstColumns + j] = dotMatrix(a, b, aColumns, bColumns, j, i);

    }
}

float32 dotMatrix(const float32* a, const float32* b,
                         int32 aColumns, int32 bColumns,
                         int32 column, int32 row) {

    float32 result = 0.0f;

    int32 index = aColumns * row;
    for (int32 i = 0; i < aColumns; i++) {
        result += a[index++] * b[column];
        column += bColumns;
    }

    return result;
}

Next, I wrote a 3x3 matrix class.

class Matrix3x3
{
public:
float32 m11, m12, m13,
        m21, m22, m23,
        m31, m32, m33;

float32 element[9];

void multiply(float32 ma11, float32 ma12, float32 ma13,
              float32 ma21, float32 ma22, float32 ma23,
              float32 ma31, float32 ma32, float32 ma33) {

    float32 temp1 = m11 * ma11 + m21 * ma12 + m31 * ma13;
    float32 temp2 = m12 * ma11 + m22 * ma12 + m32 * ma13;

    m13 = m13 * ma11 + m23 * ma12 + m33 * ma13;
    m11 = temp1;
    m12 = temp2;

    temp1 = m11 * ma21 + m21 * ma22 + m31 * ma23;
    temp2 = m12 * ma21 + m22 * ma22 + m32 * ma23;
    m23   = m13 * ma21 + m23 * ma22 + m33 * ma23;
    m21   = temp1;
    m22   = temp2;

    temp1 = m11 * ma31 + m21 * ma32 + m31 * ma33;
    temp2 = m12 * ma31 + m22 * ma32 + m32 * ma33;
    m31   = m13 * ma31 + m23 * ma32 + m33 * ma33;
    m32   = temp1;
    m33   = temp2;
}
}

Obviously the first one is very convenient.

Next, I tested the time it took to calculate：

        float32 e1[9];
        e1[0] = 2.1018f;   e1[1] = -1.81754f; e1[2] = 1.2541f;
        e1[3] = 0.54194f;  e1[4] = 2.75391f;  e1[5] = -0.1167f;
        e1[6] = -5.81652f; e1[7] = -7.9381f;  e1[8] = 4.2816f;

        float32 e2[9];
        e2[0] = 2.1018f;   e2[1] = -1.81754f; e2[2] = 1.2541f;
        e2[3] = 0.54194f;  e2[4] = 2.75391f;  e2[5] = -0.1167f;
        e2[6] = -5.81652f; e2[7] = -7.9381f;  e2[8] = 4.2816f;

        Matrix3x3 a;
        a.m11 = 2.1018f;   a.m12 = -1.81754f; a.m13 = 1.2541f;
        a.m21 = 0.54194f;  a.m22 = 2.75391f;  a.m23 = -0.1167f;
        a.m31 = -5.81652f; a.m32 = -7.9381f;  a.m33 = 4.2816f;

        Matrix3x3 b = a;

        float64 timeSpent = 0;
        LARGE_INTEGER nFreq;
        LARGE_INTEGER nBeginTime;
        LARGE_INTEGER nEndTime;

        QueryPerformanceFrequency(&nFreq); // statistical frequency
        QueryPerformanceCounter(&nBeginTime);// start timer

        for (int32 i = 0; i < 100000; i++) {
            multiplyMatrix(e1, e2, dst, 3, 3, 3, 3);
        }

    QueryPerformanceCounter(&nEndTime); //end timer
            timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart);

   printf("timeSpent1:%f\n", timeSpent);

   QueryPerformanceCounter(&nBeginTime);
   for (int32 i = 0; i < 100000; i++) {
            b.multiply(a.m11, a.m12, a.m13,
                       a.m21, a.m22, a.m23,
                       a.m31, a.m32, a.m33);
        }
   QueryPerformanceCounter(&nEndTime);
        timeSpent = (float64)(nEndTime.QuadPart - nBeginTime.QuadPart) / (nFreq.QuadPart);

printf("timeSpent2:%f\n", timeSpent);

Output：

timeSpent1:0.014277
timeSpent2:0.004649
timeSpent1:0.012684
timeSpent2:0.004522
.......
.......
timeSpent1:0.003414
timeSpent2:0.001166
timeSpent1:0.003407
timeSpent2:0.001242

Is this difference in efficiency significant or negligible?


texts:
Given a string sequence and a string, the function should output the next string of that sequence.

For example, for sequence "abc":

a
b
c
aa
ab
ac
ba
..
cc
aaa
aab

How can I improve my code while maintaining a balance between performance and readability?

data Sequence = Sequence {
    getSequence :: String,
    getFirst    :: Char,
    getLast     :: Char
} deriving (Show, Eq, Ord)

getNextChar :: Sequence -> Char -> Char
getNextChar s c
    | c == getLast s = getFirst s
    | otherwise      = findChar (getSequence s)
    where findChar (x:r@(y:xs))
            | x == c    = y
            | otherwise = findChar r

getNextStr :: Sequence -> String -> String
getNextStr s xs
    | l /= getLast s = init xs ++ [getNextChar s l]
    | otherwise      = nextAny
    where l       = last xs
          fstChar = getFirst s
          lstChar = getLast s
          (f, t)  = span (== lstChar) . reverse $ xs
          nextAny
            | length t == 0 = replicate (length f + 1) fstChar
            | otherwise     = reverse $ replicate (length f) fstChar ++ [getNextChar s (head t)] ++ tail t


texts: Jasmine unit tests for simple toggle class

texts:
Using JavaScript/jQuery I created a simple toggle and started writing unit tests for it using Jasmine. I am not sure, however, if I should be testing for things like e.g. if "click" listener is registered when object is instantiated. Should this be done as part of unit test or rather E2E test using WebDriver or something? At the moment, I'm mostly checking if e.g. toggle function changes content of HTML as expected but am a bit lost in how far I should take my unit testing.

MySwitch = function(options) {

    this.options = options;
    this._$el = $(options.element);
    this._status = 0;
    this._$el.data("value-on") ? this._valueOn = this._$el.data("value-on") : this._valueOn = "ON";
    this._$el.data("value-off") ? this._valueOff = this._$el.data("value-off") : this._valueOff = "OFF";
    if (!this._$el.text()) this._$el.text(this._valueOff);

    this._$el.on("click", $.proxy(this.toggle, this));
};

MySwitch.prototype.toggle = function(el) {

    this._status ? (this._$el.text(this._valueOff), this._status = 0) : (this._status = 1, this._$el.text(this._valueOn));

    if (typeof this.options.onToggle === "function")
        this.options.onToggle.call(this, this._status);
};

MySwitch.prototype.getStatus = function(el) {

    return this._status;
};

And tests:

describe("My switch", function() {

    var options, element, myToggle;

    beforeEach(function() {

    element = document.createElement("div");

    element.innerHTML = '"';

    $("body")[0].appendChild(element);

    function onToggleCallback() {};

    options = {

        element: $(element).find("span")[0],
        onToggle: onToggleCallback
    };

    myToggle = new MySwitch(options);
});

afterEach(function() {

    $("body > div")[0].remove();

});

it("Should set ON/OFF as default values", function() {

    $("body > div")[0].remove();

    element = document.createElement("div");

    element.innerHTML = '';

    $("body")[0].appendChild(element);

    options = {

        element: $(element).find("span")[0],
        onToggle: function(status) {}
    };

    myToggle = new MySwitch(options);
    $(element).removeAttr("data-value-on").removeAttr("data-value-off");

    expect($(element).text()).toMatch("OFF");

    myToggle.toggle();

    expect($(element).text()).toMatch("ON");

});

it("Should have AM as off value", function() {

    expect($(element).text()).toMatch("AM");

});

it("Should have PM as on value", function() {

    expect($(element).text()).toMatch("AM");

});

it("Should toggle AM->PM->AM", function() {

    myToggle.toggle();

    expect($(element).text()).toMatch("PM");

    myToggle.toggle();

    expect($(element).text()).toMatch("AM");
});

it("Should call onToggle callback", function() {

    spyOn(options, "onToggle");

    myToggle.toggle();

    expect(options.onToggle).toHaveBeenCalled();

    });

});


texts:
I am calculating the number of people within a given age range. This is my current approach.

Note:

The persons is a List<Person>
The getDiffYears() returns the number of years between now and DOB of the person. It includes the month and day as well.
The method will be returning a HashMap<String, Integer>() (Can be changed if there is a better alternative.)

The code has been tested and is working. I wanted to know if there is a more efficient approach without using this many if statements?

for (Person p: persons) {
 Date dob = p.getDob();
 if (dob != null) {
  years = getDiffYears(p.getDob());
  if (years < 10) {
   a++;
  } else if (years < 20) {
   b++;
  } else if (years < 30) {
   c++;
  } else if (years < 40) {
   d++;
  } else if (years < 50) {
   e++;
  } else if (years < 60) {
   f++;
  } else if (years < 70) {
   g++;
  } else if (years < 80) {
   h++;
  } else if (years < 90) {
   i++;
  } else if (years < 100) {
   j++;
  } else {
   k++;
  }
 } else {
  k++;
 }
}
map.put("00 - 09", a);
map.put("10 - 19", a);
map.put("20 - 29", b);
map.put("30 - 39", c);
map.put("40 - 49", e);
map.put("50 - 59", f);
map.put("60 - 69", g);
map.put("70 - 79", h);
map.put("80 - 89", i);
map.put("90 - 99", j);
map.put("Unknown", k);


texts: Using Java's Fork/Join library from Scala

texts:
I am a newbie trying to learn some Java and I am reading prof. Dan Grossman's introductory lecture notes on parallel and concurrent algorithms.

I wrote a version of a divide-and-conquer algorithm for summing an array of integers using both bare-bones Java Threads and one that uses the new (in Java 7) Fork/Join framework.

Since I am learning things, just for fun I tried the same summing array in Scala, but I feel that my implementation could use a lot of improvements (I am even more of a newbie in Scala than I am in Java, which says a lot).

package cc.cynic.jvmtests.threading

import java.util.concurrent.{ ForkJoinPool, RecursiveTask }

class ScalaSumArray(val lo: Int, val hi: Int, val arr: Array[Int]) extends RecursiveTask[Int] {
  val SEQUENTIAL_THRESHOLD = 1

  def mysum(lo: Int, hi: Int) = {
    val r = lo until hi
    (for (i <- r) yield arr(i)).sum
  }

  def compute: Int = {
      if (hi - lo <= SEQUENTIAL_THRESHOLD)
        mysum(lo, hi)
      else {
        val left = new ScalaSumArray(lo, (lo + hi) / 2, arr)
        val right = new ScalaSumArray((lo + hi) / 2, hi, arr)

        left.fork()
        val rightans = right.compute()
        val leftans = left.join()
        leftans + rightans
      }
  }
}

object ScalaSumArray {
  def main(args: Array[String]) {
    val fjpool: ForkJoinPool = new ForkJoinPool
    val lo = 0
    val hi = 10001
    val r = lo until hi
    val arr: Array[Int] = r.toArray

    // Without parallelism
    val foo = new ScalaSumArray(lo, hi, arr)
    println(foo.mysum(lo, hi))

    // With parallelism
    val s = new ScalaSumArray(lo, hi, arr)
    println(fjpool.invoke(s))
  }
}

The source code for this is available on my Github account, if you wish to see it there. The corresponding Java version is here.

Again, since I am a novice with Scala, Java and parallel programming, I would appreciate any kind of feedback to improve/simplify the code.


texts:
(See the next iteration.)
There was a question in Quora about an interview question that asks to write a function for computing integer square roots, so I rolled two of them for fun:
Main.java:
import java.util.Random;
import java.util.function.Function;

public class Main {

    public static long intSqrt1(long number) {
        long sqrt = 0L;

        while ((sqrt + 1) * (sqrt + 1) <= number) {
            sqrt++;
        }

        return sqrt;
    }

    public static long intSqrt2(long number) {
        if (number <= 0L) {
            return 0L;
        }

        long sqrt = 1L;

        while (4 * sqrt * sqrt <= number) {
            sqrt *= 2;
        }

        while ((sqrt + 1) * (sqrt + 1) <= number) {
            sqrt++;
        }

        return sqrt;
    }

    public static long intSqrt3(long number) {
        return (long) Math.sqrt(number);
    }

    private static void profile(Function<Long, Long> function, Long number) {
        long result = 0L;
        long startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; ++i) {
            result = function.apply(number);
        }

        long endTime = System.nanoTime();

        System.out.printf("Time: %.2f, result: %d.\n",
                          (endTime - startTime) / 1e6,
                          result);
    }

    private static final int ITERATIONS = 1000;
    private static final long UPPER_BOUND = 1_000_000_000_000L;

    public static void main(String[] args) {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        long number = Math.abs(random.nextLong()) % UPPER_BOUND;

        System.out.println("Seed = " + seed);
        System.out.println("Number: " + number);

        profile(Main::intSqrt1, number);
        profile(Main::intSqrt2, number);
        profile(Main::intSqrt3, number);
    }
}

The performance figures are as follows:

Seed = 137967850680858
Number: 18973198056
Time: 278.29, result: 137743.
Time: 15.65, result: 137743.
Time: 0.38, result: 137743.

(The first time of intSqrt1, the second time of intSqrt2, and so on.)
My main question here is: is it possible to make the two methods any faster while not actually using the Math.sqrt?


texts:
I'm looking to speed up this method. Ideally, I would like to cut the time in 1/2 or more. At the moment I have to draw the screen line-by-line as the font is 16 pixels high, but it is being drawn with an extra blank pixel on the bottom. If I could figure out how to set the line-height to 16 pixels I would imagine that drawing 1 string over 24 strings would help speed it up. Baring that what else can I do to increase the speed?

- (void)drawRect:(NSRect)dirtyRect
{
    NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext currentContext];
    CGContextRef context = (CGContextRef) [nsGraphicsContext graphicsPort];

    CGContextSetShouldSmoothFonts(context, false);

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@""];
    for (int y=24; y >= 0; y--) {
        [[string mutableString] setString:@""];;
        for (int x=0; x < 80; x++) {
            AnsiScreenChar *c = [self.screen objectAtIndex:(y*80)+x];
            [self.fontAttributes setValue:c.fgColor forKey:NSForegroundColorAttributeName];
            [self.fontAttributes setValue:c.bgColor forKey:NSBackgroundColorAttributeName];

            NSAttributedString *subString = [[NSAttributedString alloc] initWithString:c.data
                                                                            attributes:self.fontAttributes];
            [string appendAttributedString:subString];
        }
        [string drawAtPoint:NSMakePoint(0, self.frame.size.height - ((y+1)*16))];
    }
}

Profile

Running     Time  Self        Symbol Name
3276.0ms    9.5%  3276.0      -[AnsiView drawRect:]
1726.0ms    5.0%  1726.0      -[NSLayoutManager(NSTextViewSupport) showCGGlyphs:positions:count:font:matrix:attributes:inContext:]
1540.0ms    4.4%  1540.0      -[__NSCFDictionary setObject:forKey:]
1467.0ms    4.2%  1467.0      -[NSObject dealloc]
1118.0ms    3.2%  1118.0      -[NSView _drawRect:clip:]
1108.0ms    3.2%  1108.0      -[NSConcreteHashTable getItem:]
1106.0ms    3.2%  1106.0      -[NSLayoutManager(NSPrivate) _drawBackgroundForGlyphRange:atPoint:parameters:]
901.0ms     2.6%  901.0       -[NSLayoutManager(NSPrivate) _insertionPointHelperForGlyphAtIndex:]
779.0ms     2.2%  779.0       -[NSLayoutManager(NSPrivate) _drawGlyphsForGlyphRange:atPoint:]
704.0ms     2.0%  704.0       -[__NSCFString replaceCharactersInRange:withString:]
693.0ms     2.0%  693.0       -[NSATSGlyphStorage createCTTypesetter]
619.0ms     1.8%  619.0       -[NSAttributeDictionary objectForKey:]
599.0ms     1.7%  599.0       -[NSLayoutManager(NSPrivate) _rectArrayForRange:withinSelectionRange:rangeIsCharRange:singleRectOnly:fullLineRectsOnly:inTextContainer:rectCount:rangeWithinContainer:glyphsDrawOutsideLines:]
558.0ms     1.6%  558.0       -[NSLayoutManager locationForGlyphAtIndex:]
537.0ms     1.5%  537.0       +[NSObject allocWithZone:]


texts: Higher order component for verifying authentication

texts:
I am new to React.js. On the server side, I am using Passport.js for social authentication setting a cookie. With that cookie I am verifying on the client side with a higher order component (HOC). This component will check a specific value in the decoded cookie for every secure component that is being rendered. Is this the correct way to do it?

HOC.js

import React from 'react';
import jwt from 'jwt-simple';

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

export default function(ComposedComponent) {
    class Authentication extends React.Component{
        static contextTypes = {
            router:React.PropTypes.object
        };
        componentWillMount(){
            let specificCookie = readCookie('peace');
            if(specificCookie !== null ){
                let decoded = jwt.decode(token,'NONOE');

                if(decoded.verify !== "falseAlarm"){
                    this.context.router.push('/')

                }
            }else{
                this.context.router.push('/')
            }

        }
        render(){

            return <ComposedComponent {...this.props}/>
        }
    }

    return Authentication
}


texts:
This is my first time putting a code together for Java based on my own so i was hoping if you someone would be kind enough to review and provide feedback or constructive criticism on this code.

The goal is to roll 2 dice and 10k times. add pairs and display their frequency.

The code runs fine but maybe I am overlooking some logical error or a better way to do this.

/**
 * Use the Random Number generator to write a java application that simulates a pair of dice.
 * Throwing the pair of dice 10,000 times- Add the values for the pair
 * Print the frequency at the end of 10,000 runs
 * @author
 *
 */

import java.util.Random;

public class diceSimulation {

    public static void main(String[] args) {
        /**
         * Declare variables and store dice max roll in Thousand
         */
        final int THOUSAND = 10000;
        int counter, dice1, dice2;

        //initiate an array with elements to keep count
        int [] diceValue = new int [7];

        // display welcome message. no other purpose but trial
        welcome ();

        // create new instance of random
        Random rollDice = new Random();

        /**
         * Set counter to start from 1 and go till desired constant number
         * Rolling two separate dices and storing values in dice1 & dice 2 respectively
         */
        for (counter=1; counter<=THOUSAND;counter++){

            dice1=rollDice.nextInt(6) +  1;
            dice2=rollDice.nextInt(6) + 1;

            // If statement to check if values are the same or not
            if (dice1==dice2){
                // IF values are same then go into for loop and store value in array element
                for (int i=1; i<=6; i++){
                    if (dice1 == i && dice2 == i){
                        // add value for the number displayed into the array
                        diceValue [i] += 1;
                    }
                }
            }

        }
        // Display results totals of paired rolls
        for (int a=1; a<diceValue.length; a++){
            System.out.println(" You rolled set of " + a + " " + diceValue[a] + " times");
        }

    }

    public static void welcome () {
        System.out.println("welcome to dice world!");
    }

}


texts: Use of nested namespaces in 3D graphics engine library

texts:
I know that nested namespaces are used in C++ very rarely. But I think it's a nice solution to exclude types from global scope and sometimes it helps to write programs faster when we use things like "IntelliSense" or search for documentation (maybe it's similar for C# developers).

I've tried to organize my simple 3D graphics engine library in this way. Here is its main header file:

#ifndef RAZOR_H
#define RAZOR_H

#pragma warning (disable: 4482)

#include <Windows.h>
#include <fstream>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <map>

#include <gl\GL.h>
#include "Externals\wglext.h"
#include "Externals\gl3.h"

namespace Razor
{
    namespace Framework
    {
        #include "DisplayOrientation.h"
        #include "ButtonState.h"
        #include "GameTime.h"
        #include "Rect.h"
        #include "Point.h"
        #include "Color.h"
        #include "Vector2.h"
        #include "Vector3.h"
        #include "Vector4.h"
        #include "Matrix.h"

        #include "GameWindow.h"
        #include "Game.h"

        namespace IO
        {
            #include "File.h"
        }

        namespace Input
        {
            #include "ButtonState.h"
            #include "MouseState.h"
            #include "Keyboard.h"
            #include "Mouse.h"
            #include "TouchPanel.h"
        }

        namespace Graphics
        {
            #include "PrimitiveType.h"
            #include "VertexElementFormat.h"
            #include "VertexElementUsage.h"
            #include "VertexElement.h"
            #include "VertexDeclaration.h"
            #include "OpenGLExtensions.h"
            #include "DepthFormat.h"
            #include "BufferUsage.h"
            #include "PresentationParameters.h"
            #include "RenderTarget.h"
            #include "OpenGLVersion.h"
            #include "Viewport.h"
            #include "Shader.h"
            #include "VertexShader.h"
            #include "FragmentShader.h"
            #include "GeometryShader.h"
            #include "ShaderContainer.h"
            #include "VertexBuffer.h"
            #include "GraphicsDevice.h"
            #include "VertexBuffer.h"
            #include "GraphicsDeviceManager.h"
        }
    }
}

#endif // RAZOR_H

What kind of problems can I get in the future if I organize my library in this way? Do you think this is really a bad style of coding?


texts:
As xts objects are arrays, getting apply functions to work is a little tricky if you want to preserve the dates. For example, take the xts object xx below:

xx <- xts(replicate(6, sample(c(1:10), 10, rep = T)),
          order.by = Sys.Date() + 1:10)

Say we wish to apply a function to each column (to keep it simple say i wish to add 100 to each element of each column).

sapply(xx, function(col) col + 100)

Doing with with sapply loses the row names.

Using apply works -- but it is slow (see below).

apply(xx, 2, function(col) col + 100)

To address this, I wrote the following helper:

mapXts <- function(Xts, cFUN) {
        if(!is.xts(Xts)) stop("Must supply function with xts object")
        Z <- Xts
        for (j in 1:ncol(Xts)) {
            Z[,j] <- do.call(cFUN, list(Xts[,j]))
        }
        Z
}

The obligatory horse race:

set.seed(1)
xz <- xts(replicate(6, sample(c(1:100), 1000, rep = T)),
          order.by = Sys.Date() + 1:1000)

apFun <- function() apply(xz, 2, function(col) col + 100)
sapFun <- function() sapply(xz, function(col) col + 100)
mapXf <- function() mapXts(xz, function(col) col + 100)

op <- microbenchmark(
               app = apFun(),
               sap = sapFun(),
               mXf = mapXf(),
               times = 1000L)

This results in speedups of about 5x over apply and is about 3x faster than sapply (and it gives me back the data in the formate i most value).

Unit: microseconds
 expr      min        lq    median        uq      max neval
  app 3083.425 3206.0295 3287.1725 3496.9720 30678.90  1000
  sap 1669.384 1763.7945 1827.0265 1952.7490 24173.88  1000
  mXf  615.279  677.0005  709.4725  787.1635 24390.62  1000

Are there any further tricks i might use to speed things up? Also, any dark corners in the case that i've missed?


texts:
I have this code querying for some objects from my database with Flask-SQLAlchemy:

areas = Area.query.all()
subareas = Subarea.query.all()

And then I use it on html with Jinja template to display data:

{% for area in areas %}
    {% if area.number=='0' %}
        <select id="{{ area.number }}" class="subarea" onchange="ChangeDropdowns(this.value)">
    {% else %}
        <select id="{{ area.number }}" class="subarea" style="display: none;" onchange="ChangeDropdowns(this.value)">
    {% endif %}
        <option value="" disabled="disabled" selected="selected">Escolha uma Subárea</option>
    {% for subarea in subareas%}
        {% if subarea.areaNumber == area.number %}
            {% if subarea.disabled %}
                <option value="{{ subarea.number }}" disabled="disabled">{{ subarea.view }}</option>
            {% else %}
                <option value="{{ subarea.number }}">{{ subarea.view }}</option>
            {% endif %}
        {% endif %}
    {% endfor %}
    </select>
{% endfor %}

Database models:

class Area(db.Model):
areaID = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
number = db.Column(db.String(1))
view = db.Column(db.String)
disabled = db.Column(db.Boolean)

def __init__(self, name, number, view, disabled):
    self.name = name
    self.number = number
    self.view = view
    self.disabled = disabled

class Subarea(db.Model):
subareaID = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
number = db.Column(db.String(2))
view = db.Column(db.String)
disabled = db.Column(db.Boolean)
areaNumber = db.Column(db.String(1))

def __init__(self, name, number, view, disabled, areaNumber):
    self.name = name
    self.number = number
    self.view = view
    self.disabled = disabled
    self.areaNumber = areaNumber

Firstly, I would like to have subareas as a dictionary or a list of lists, that way I don't need to iterate areas length times over all subareas length.

But will that really improve the code? How many entries do I need to have on my database to see a substantial difference in time? Is there another way to improve this template?


texts: Python functions to save JSON and H5 to local files and S3

texts:
I'm trying to copy files to S3 after writing them locally:
I have 2 functions which I need to do this. What is the best way to refactor the code that exists in both.

    s3 = False
    if data_fp.lower().startswith('s3://'):
        s3_data_fp = data_fp
        data_fp = os.path.join(_TMP, os.path.basename(data_fp))
        s3 = True

def save_json(data_fp, data, sort_keys=True, indent=4):
    s3 = False
    if data_fp.lower().startswith('s3://'):
        s3_data_fp = data_fp
        data_fp = os.path.join(_TMP, os.path.basename(data_fp))
        s3 = True

    with open(data_fp, 'w') as output_file:
        json.dump(data, output_file, cls=NumpyEncoder, sort_keys=sort_keys,
                  indent=indent)
    if s3:
        save_in_s3(data_fp, s3_data_fp)

# def save_hdf5(data_fp: str, data: Dict[str, object]):
def save_hdf5(data_fp, data, metadata=None):
    s3 = False
    if data_fp.lower().startswith('s3://'):
        s3_data_fp = data_fp
        data_fp = os.path.join(_TMP, os.path.basename(data_fp))
        s3 = True

    if metadata is None:
        metadata = {}
    mode = 'w'
    if os.path.isfile(data_fp):
        mode = 'r+'
    with h5py.File(data_fp, mode) as h5_file:
        for key, value in data.items():
            dataset = h5_file.create_dataset(key, data=value)

    if s3:
        save_in_s3(data_fp, s3_data_fp)