texts:
How does this recursive selection sort look to everyone here? Am I missing anything 'pythonic' about the way I have done it?

def selection_sort(li, out=None):
    if out is None:
        out = []
        li = li[:]

    if len(li) == 0:
        return out

    small = min(li)
    li.remove(small)
    out.append(small)
    return selection_sort(li, out)


texts:
I have a list of resources which can be voted on. There are 3 voting states: upvoted, downvoted and no vote.

In a fashion identical to Stack Exchange voting, it follows these rules:

If you upvote a post you've already upvoted, it will set it to 'no vote'
If you upvote a post set to 'no vote' it will set it to upvote
if you downvote a post you've upvoted, it will set it to 'downvote' (I bolded this because in another post everyone gave me grief that this way is 'stupid', yet every voting site I have seen uses this style... Reddit, Digg. Stack Overflow, etc)

The exact same rules (except inverse) hold true for downvote.

Here's how I call my sendVote() function, when you click on upvote or downvote:

  // Voting
  $('.res-list').delegate('.vote .up', 'click', function() {
    flashColor($(this),'#fffc00');
    sendVote($(this).parent(),'upvoted');
    return false;
  });

  $('.res-list').delegate('.vote .down', 'click', function() {
    flashColor($(this),'#fffc00');
    sendVote($(this).parent(),'downvoted');
    return false;
  });

I believe that above code is fine, but his code below is what I feel is awful and could really be refactored, but I don't know how. I'm kind of new to JavaScript and jQuery.

function sendVote(object, direction) {

  var votesContainer = $(object).find('.m p');
  var votes = parseInt($(votesContainer).html());

  // UPVOTED
  if (direction == 'upvoted') {

    if ($(object).hasClass('downvoted')) {
      // Overwrite Downvote
      $(votesContainer).html(votes + 2);
      $(object).removeClass('downvoted');
      $(object).addClass(direction);
    } else if ($(object).hasClass(direction)) {
      // Undo Upvote
      $(votesContainer).html(votes - 1);
      $(object).removeClass(direction);
    } else {
      // Do Upvote
      $(votesContainer).html(votes + 1);
      $(object).addClass(direction);
    };

    // Ajax function here to /votes/upvote?id=x

  // DOWNVOTED
  } else {

    if ($(object).hasClass('upvoted')) {
      // Overwrite Upvote
      $(votesContainer).html(votes - 2);
      $(object).removeClass('upvoted');
      $(object).addClass(direction);
    } else if ($(object).hasClass(direction)) {
      // Undo Downvote
      $(votesContainer).html(votes + 1);
      $(object).removeClass(direction);
    } else {
      // Do Downvote
      $(votesContainer).html(votes - 1);
      $(object).addClass(direction);
    };

    // Ajax function here to /votes/downvote?id=x

  }
}


texts: Separating logic and presentation in wordpress

texts:
Recently, I've been thinking about better ways to make my WP themes more maintainable. What I've tried on one of my last projects is to separate out the presentation and logic as much as I can. First, I created a function with the loop in it and has all of the logic. It returns all of the data into an array. In the template page, I call the function, loop through the array, and output the HTML.

At the most basic level, this is what it looks like. In functions.php (or a plugin):

function get_data(){
    if (have_posts()) :
        while (have_posts()) : the_post();
            $results['title'] = get_the_title();
            $results['field'] = get_field('field');
        endwhile;
    endif;
    return $results;
}

In the template file:

query_posts( 'posts_per_page=5' );
$results = get_data();
foreach ($results as $result) :

echo $result['title'];

        echo $result['field'];

endforeach;

Is this a good practice? From what I can see, it's a good solution but I haven't seen any other developers use it. Is there something better that other people are doing?


texts: Initializing characters in a visual novel game

texts:
I am making a visual novel game and I was wondering is there a better way of setting character attributes and initializing than the way that I have done down below. As you can see I did an abstract class so that I can call each character without rewriting a bunch of code. I also have an array that initializes everything. What I was wondering, is there a better way of initializing them instead of using an array, it is just tiring to type in

Init.C[1].getAge();

every time that you want to get or set a variable.

What i want specifically is a way to initialize all these Character Objects without cluttering up my code and if possible automaticly initialize all of them, as you can see i tried to do in my init peice of code.

If anyone has any suggestions on how to initialize all these Character Objects I would be grateful, Also Any other comments or suggestions are welcome.

package visualnovel;

import Characters.*;

public class VisualNovel {

public static void main(String[] args) {
    Init Init = new Init();
    Init.Init();
    Init.C[1].getAge();
}
}

Here is my Init peice of code

package visualnovel;

import Characters.*;

public class Init {
Characters C[] = new Characters[3];

public void Init(){
    Characters();
}

public void Characters() {
    C[0] = new Main();
    C[1] = new Secondary();

    for (int i = 0; i < 2; i++) {
        C[i].Init();
    }
}
}

Here is the Character Abstract Class

package Characters;

public abstract class Characters {

private String FirstName;
private String LastName;
private String EyeColor;
private String SkinColor;
private String Sex;
private String Age;
private String HairColor;
private static int NumofCharacters;

public Characters(){
    FirstName = null;
    LastName = null;
    EyeColor = null;
    SkinColor = null;
    Sex = null;
    Age = null;
    HairColor = null;
}

 // mutators

public void setFirstName(String F){
    FirstName = F;
}
public void setLastName(String L){
    LastName = L;
}
public void setEyeColor(String E){
    EyeColor = E;
}
public void setSkinColor(String S){
    SkinColor = S;
}
public void setSex(String S){
    Sex = S;
}
public void setAge(String A){
    Age = A;
}
public void setHairColor(String H){
    HairColor = H;
}
public void setDetails(String FirstName, String LastName, String Sex,
String EyeColor, String HairColor, String SkinColor, String Age){
        setFirstName(FirstName);
        setLastName(LastName);
        setSex(Sex);
        setEyeColor(EyeColor);
        setSkinColor(SkinColor);
        setAge(Age);
        setHairColor(HairColor);
        NumofCharacters++;
}

  // Accessors
public String getDetails(){
    String D;
        D = LastName + ", " + FirstName;
        D += "\nSex: " + Sex;
        D += "\nAge: " + Age;
        D += "\nEyes: " + EyeColor;
        D += "\nSkin: " + SkinColor;
        D += "\nHair: " + HairColor;
        return D;
}

public String getFirstName(){
    return FirstName;
}
public String getLastName(){
    return LastName;
}
public String getEyeColor(){
    return EyeColor;
}
public String getSkinColor(){
    return SkinColor;
}
public String getSex(){
    return Sex;
}
public String getAge(){
    return Age;
}
public String getHairColor(){
    return HairColor;
}
public int getNumberOfCharacters(){
    return NumofCharacters;
}

public String toString(){
    String S;
    S = LastName + ", " + FirstName;
    S += "\nSex: " + Sex;
    S += "\nAge: " + Age;
    S += "\nEyes: " + EyeColor;
    S += "\nSkin: " + SkinColor;
    S += "\nHair: " + HairColor;
    return S;
}

@Override
public abstract void Init();
}

Charcter Example Code

package Characters;

public class Main extends Characters{

public void Init() {

setDetails("Allyson","Carter","Female","Green","Blonde","White","27");
}

}


texts: Using Java stream to filter a list and create a map

texts:
In List<Hotel>, I'd like to extract Hotels which has OTAProperty with a specific otaName, as Map<Long, Hotel>. The map's key is the id for the OTAProperty named given otaName, and the value for the map is the Hotel instance.

I made a method createHotelMapByOtaName working as intended. But I think it's possible to remove nested forEach block by using Java 8's stream and related operations such as map, flatMap, and Collectors.toMap. Can anyone get some advice or code snippets?

package com.example;

import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HotelService {

    public static Map<Long, Hotel> createHotelMapByOtaName(List<Hotel> hotels, String otaName) {
        Map<Long, Hotel> map = new HashMap<>();
        hotels.forEach(h -> {
            h.getOtaProperties().forEach(op -> {
                if (otaName.equals(op.getOtaName())) map.put(op.getId(), h);
            });
        });
        return map;
    }

    public static void main(String[] args) {
        List<Hotel> hotels = Lists.newArrayList(
                new Hotel("Hilton",
                        Lists.newArrayList(
                                new OTAProperty(1L, "expedia"),
                                new OTAProperty(2L, "agoda"))),
                new Hotel("Ramada",
                        Lists.newArrayList(
                                new OTAProperty(4L, "agoda"))),
                new Hotel("Hyatt",
                        Lists.newArrayList(
                                new OTAProperty(5L, "expedia")))
        );
        // expected: {1=Hotel{name=Hilton, otaProperties=[OTAProperty{id=1, otaName=expedia}, OTAProperty{id=2, otaName=agoda}]}, 5=Hotel{name=Hyatt, otaProperties=[OTAProperty{id=5, otaName=expedia}]}}
        System.out.println(HotelService.createHotelMapByOtaName(hotels, "expedia"));
    }
}

Followings are codes for 2 models:

Hotel.java:

package com.example;

import com.google.common.base.MoreObjects;

import java.util.List;

public class Hotel {
    private String name;
    private List<OTAProperty> otaProperties;

    public Hotel(String name, List<OTAProperty> otaProperties) {
        this.name = name;
        this.otaProperties = otaProperties;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<OTAProperty> getOtaProperties() {
        return otaProperties;
    }

    public void setOtaProperties(List<OTAProperty> otaProperties) {
        this.otaProperties = otaProperties;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("name", name)
                .add("otaProperties", otaProperties)
                .toString();
    }
}

OTAProperty.java:

package com.example;

import com.google.common.base.MoreObjects;

public class OTAProperty {
    private Long id;
    private String otaName;

    public OTAProperty(Long id, String otaName) {
        this.id = id;
        this.otaName = otaName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getOtaName() {
        return otaName;
    }

    public void setOtaName(String otaName) {
        this.otaName = otaName;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("id", id)
                .add("otaName", otaName)
                .toString();
    }
}


texts: Load images embedded in DOM events performantly

texts:
if you visit site , you can see page loading time is too much.

I am using the below code to display single image, we are using same kind of code for all 16 images, please review code and guide me to improve performance.

.links1234 { color : #908983;}
.links1234:hover { color : #f85700;}

.grow {
  height: auto;
  padding: 5px 5px 5px 10px;
  border-radius: 10px;
  width: 23%;
  margin: 5px 1% 5px 1%;
  float: left;
  position: relative;
  transition: height 0.5s;
  -webkit-transition: height 0.5s;
  text-align: center;
  background-color : #fff;

}
.grow:hover ul{
  display: block;
}
.grow:hover {
  box-shadow: 0px 0px 5px 1px rgba(0,0,0,.25);
}

.grow ul {
  margin-top: -3px;
  padding: 5px;
  padding-top:10px;
  border-radius:0px 0px 10px 10px;
  list-style: none;
  display: none;
  position: absolute;
  z-index: 1;
  background: #fff;
  box-shadow: 0 5px 5px 1px rgba(0,0,0,.25);
  left: 0;
  right: 0;
}

.grow img{
  width: 100%;
}

.expand
{
    position:relative;
    right:8px;
    top:4px;
}

iPhone 4

iPhone 4s

iPhone 5

iPhone 5C

iPhone 5S

iPhone 6

iPhone 6 Plus


texts:
I have the following table definition:

CREATE TABLE ProductPointValues (
    id          INT,
    effective   DATE,
    minPoints   INT,
    maxPoints   INT,

    CONSTRAINT PK PRIMARY KEY (id, effective),
    CONSTRAINT FK FOREIGN KEY (id) REFERENCES Products(id)
)
;

INSERT INTO ProductPointValues
VALUES
    (1, '1/1/2015', 100, 200),
    (1, '2/1/2015',  50, 250),
    (1, '3/1/2015',   0, 300),
    (1, '1/1/2016', 500, 900)

And am running this query to select values for the most recent version of an id:

SELECT P.id, P.minPoints, P.maxPoints
FROM ProductPointValues P
INNER JOIN
    (
        SELECT id, MAX(effective) effective
        FROM ProductPointValues
        WHERE effective <= GETDATE()
        GROUP BY id
    ) T
ON P.id = T.id AND P.effective = T.effective

returns

id          minPoints    maxPoints
----------- -----------  -----------
1           0            300

is there an equivalent, more elegant way to write this using aggregate functions?


texts:
I wrote this code to append Maybe's:

ghci> (:) <$> Just 5 <*> ((:) <$> Just 100 <*> Just [])
Just [5,100]

Similarly:

ghci> (:) <$> Just 5 <*> ( (:) <$> Just 10 <*> ((:) <$> Just 100 <*> Just []) )
Just [5,10,100]

Is this code idiomatic? Perhaps there's a more concise way to append a bunch of Maybe's together?


texts: Finite state machine written in OCaml to test for the sequence 0,1

texts:
I got inspired by Stack Overflow to build a simple state machine which can test if a sequence contains 0,1. I have two questions:

How can I get rid of line | _ -> (function `q0 -> `q0 | `q2 ->
`q2 | `q1 -> `q1)
How can I improve that code?

(If it is matters, I came from Python and many things in OCaml seem unusual to me).

(*
--->  q0  ---0-->  q2  ---1--->   q1
    /  \         /  \          /    \
    -1->         -0->          -0,1->
*)

type ('state, 'number) state_machine = {
    initial: 'state;
    final: 'state -> string;
    transition: 'number -> 'state -> 'state;
};;

let state_machine_01 sequence =
    let machine_01 = {
        initial = `q0;
        final = (function `q0 -> "Init" | `q2 -> "Found zero" | `q1 -> "END" );
        transition = (function
            | 0 -> (function `q0 -> `q2 | `q2 -> `q2 | `q1 -> `q1)
            | 1 -> (function `q0 -> `q0 | `q2 -> `q1 | `q1 -> `q1)
            | _ -> (function `q0 -> `q0 | `q2 -> `q2 | `q1 -> `q1)
        );
    } in

    let state = ref machine_01.initial in
    for i = 0 to (List.length sequence) - 1 do
        state := (machine_01.transition (List.nth sequence i)) !state
    done;
    machine_01.final !state;
;;

let () =
    Printf.printf "------------- start --------------- \n";

    Printf.printf "%s\n" (state_machine_01 [1; 1; 0; 0; 0; 1; 0; 1]);
    Printf.printf "%s\n" (state_machine_01 [1; 1; 0; 0; 0]);
    Printf.printf "%s\n" (state_machine_01 [1; 1; 1]);

    Printf.printf "-------------- end ---------------- \n";
;;


texts:
A thread-safe queue suspending/resuming the producer when respectively upper/lower watermark has been crossed. Intended usage - interchange between a non-blocking IO loop thread and a consumer running in a different thread/pool. High performance is not a key requirement, but comments in this direction are very welcome.

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

public final class WatermarkQueue<E> extends AbstractQueue<E> {
    private final Queue<E> queue = new ArrayDeque<>();

    private final int lowerWatermark;
    private final int upperWatermark;

    private final Runnable onSuspend;
    private final Runnable onResume;

    private final AtomicBoolean producerSuspended = new AtomicBoolean(false);

    public WatermarkQueue(int lowerWatermark, int upperWatermark,
                          Runnable onSuspend, Runnable onResume) {
        this.queue = new ArrayDeque<>();
        this.lowerWatermark =lowerWatermark;
        this.upperWatermark = upperWatermark;
        this.onSuspend = onSuspend;
        this.onResume = onResume;
    }

    public WatermarkQueue(int initialQueueCapacity, int lowerWatermark, int upperWatermark,
                          Runnable onSuspend, Runnable onResume) {
        this.queue = new ArrayDeque<>(initialQueueCapacity);
        this.lowerWatermark =lowerWatermark;
        this.upperWatermark = upperWatermark;
        this.onSuspend = onSuspend;
        this.onResume = onResume;
    }

    @Override
    public synchronized Iterator<E> iterator() {
        return new ArrayList<>(queue).iterator();
    }

    @Override
    public synchronized int size() {
        return queue.size();
    }

    @Override
    public synchronized boolean offer(E e) {
        final boolean wasEmpty = queue.isEmpty();
        queue.offer(e);

        if (queue.size() == upperWatermark) {
            if (!producerSuspended.getAndSet(true)) {
                onSuspend.run();
            }
        }

        if (wasEmpty) {
            notify();
        }

        return true;
    }

    @Override
    public synchronized E poll() {
        while (queue.isEmpty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
        }

        final E e = queue.poll();
        if (e != null) {
            if (queue.size() == lowerWatermark) {
                if (producerSuspended.getAndSet(false)) {
                    onResume.run();
                }
            }
        }

        return e;
    }

    @Override
    public synchronized E peek() {
        return queue.peek();
    }
}


texts:
I know there have been a lot of post, blog article answer on Stack Overflow (but the validation does return true on a tab character) about this. But I'm still looking for a neat way to validate if a value is a number.

I wrote the following. Does that cover the 99% of the cases? Is there a better way to do that?

function validateNumber(valueToCheck){
    var checkSum = 0;
    var isValid = true;

    if(typeof valueToCheck === "number"){
        return true;
    }
    if(typeof valueToCheck === "string"){
        if(valueToCheck.replace(/ /g,'') !== valueToCheck){
            return false;
        }

        if(valueToCheck.charAt(0) == '-'){
            valueToCheck = valueToCheck.substr(1); // remove minus sign
        }
        valueToCheck = valueToCheck.replace('.',''); // allow one decimal point

    }

    for(var i=0;i<valueToCheck.length; i++){
        if(!(valueToCheck.charCodeAt(i) >= 48 && valueToCheck.charCodeAt(i) <= 57)){
            isValid = false;
            break;
        }
    }

    return isValid;
}

Here is the jsfiddle with tests cases.


texts:
Question:

  The old system stored a list of letters per score:

  1 point: "A", "E", "I", "O", "U", "L", "N", "R", "S", "T",

  2 points: "D", "G",

  3 points: "B", "C", "M", "P",

  4 points: "F", "H", "V", "W", "Y",

  5 points: "K",

  8 points: "J", "X",

  10 points: "Q", "Z",

  The shiny new scrabble system instead stores the score per letter, which makes it much faster and easier to calculate the score for a word. It also stores the letters in lower-case regardless of the case of the input letters:

  "a" is worth 1 point.

  "b" is worth 3 points.

  "c" is worth 3 points.

  "d" is worth 2 points.

  Etc.

  Your mission, should you choose to accept it, is to write a program that transforms the legacy data format to the shiny new format.

Code:

import java.util.Map;
import java.util.List;
import java.util.HashMap;

import com.google.inject.AbstractModule;

public class Etl extends AbstractModule {
  public Map transform(Map<Integer, List<String>> oldData) {
    Map<String, Integer> items = new HashMap<String, Integer>();

    for(Map.Entry<Integer, List<String>> entry: oldData.entrySet()) {
      for(String chr: entry.getValue()) {
       items.put(chr.toLowerCase(), entry.getKey());
      }
    }
    return items;
  }
}

Can the above code be made more readable and optimized?


texts:
I tested creating 1 billion (1,000,000,000) nodes and lookups are fast. You can ask for a node by node_id.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct node {
    int node_id;
    int data;
    char *name;
    struct node *left;
    struct node *right;
} node;

node *newNode(int data, char *name, int node_id) {
    node *new_node = malloc(sizeof(node));
    new_node->data = data;
    new_node->name = name;
    new_node->node_id = node_id;
    new_node->right = new_node->left = NULL;
    return new_node;
}

node *insert_node(node *root, int data, int node_id, char *name) {
    if (root == NULL)
        return newNode(data, name, node_id);
    else {
        node *cur;
        if (node_id < root->node_id) {
            cur = insert_node(root->left, data, node_id, name);
            root->left = cur;
        } else if (node_id > root->node_id) {
            cur = insert_node(root->right, data, node_id, name);
            root->right = cur;
        }
    }
    return root;
}

node *find_node_data(node *root, int node_id) {
    if (root == NULL)
        return NULL;
    else if (root->node_id == node_id)
        return root;
    else if (root->node_id > node_id)
        return find_node_data(root->left, node_id);
    else
        return find_node_data(root->right, node_id);
}

void print(node *np) {
    if (np) {
        print(np->left);
        printf("(%d, %d, %s)", np->node_id, np->data, np->name);
        print(np->right);
    }
}

int main() {
    int T = 1000000000; //test case 1000000000 nodes
    int data, node_id;
    //printf("Input number of nodes:");
    //scanf("%d", &T);
    node *root = NULL;
    srand(time(NULL));
    while (T-- > 0) {
        //printf("Input data. %d:", T);
        //scanf("%d %d", &data, &node_id);
        int r = rand() % 1000000000;
        int r2 = rand() % 1000000000;
        root = insert_node(root, r, r2, "Rosencrantz");
    }
    //print(root);
    printf("\n");
    printf("Find data at node:");
    scanf("%d", &T);
    printf("node data %d %s", find_node_data(root, T)->data, find_node_data(root, T)->name);
    return 0;
}


texts:
In the ROOT framework (originally a C++ framework, but python bindings are also supplied), colors are objects (ROOT.TColor) identified with an integer index.

This short class creates a new such color, given the r, g, b values which stores the object inside an int sub-type (to prevent the gc from deleting it).

#colors.py
import ROOT

class Color(int):
    """Create a new ROOT.TColor object with an associated index"""
    __slots__ = ["object"]

    def __new__(cls, r, g, b):
        """Constructor. r, g, b are in [0, 1]"""
        self = int.__new__(cls, ROOT.TColor.GetFreeColorIndex())
        cls.set_rgb(self, r, g, b)
        return self

    def set_rgb(self, r, g, b):
        self.object = ROOT.TColor(self, r, g, b)

black = Color(0, 0, 0)
orange = Color(0.9, 0.6, 0)
sky_blue = Color(0.35, 0.7, 0.9)
bluish_green = Color(0, 0.6, 0.5)
yellow = Color(0.95, 0.9, 0.25)
blue = Color(0, 0.45, 0.7)
vermillion = Color(0.8, 0.4, 0)
reddish_purple = Color(0.8, 0.6, 0.7)

colors = [black, orange, sky_blue, bluish_green,
          yellow, blue, vermillion, reddish_purple]

Usage example:

#draw_histograms.py
from colors import colors
import ROOT

names = "hist 1", "hist 2", "hist 3"
histograms = []
for name, color in zip(names, colors):
    hist = ROOT.TH1D(name, name, 100, -50, 50)
    hist.FillRandom("gaus", 1000)
    hist.SetLineColor(color)
    histograms.append(hist)

histograms[1].Draw()
...

I'm looking for comments on the class itself as well as recommendations regarding making the initialization of all the colors easier.

Further explanation:

The need for this class arose, because ROOT cannot convert a ROOT.TColor object directly to an int. It needs the global color index in functions such as hist.SetLineColor(1).

Otherwise it raises errors such as:

...
  File "test.py", line 43, in plot_2D_stacked
    h.SetLineColor(color)
TypeError: void TAttLine::SetLineColor(short lcolor) =>
    could not convert argument 1 (short int converion expects an integer object)


texts: Function to check if folder path is valid

texts:
It is a function that validates a string is a correct windows path to a directory.
It returns negative numbers if it isn't, 0 if it is correct and 1 if it also exists:

int path_is_correct_directory (char *path)
{
    size_t  szPath          = 0U;

    if(path == NULL)
        return -1;
    if(*path == '\0')
        return -2;

    szPath = strlen(path);

    if(szPath < 3 || szPath > MAX_PATH)
        return -3;

    char    driveLetter[3]      = { path[0], path[1], '\0' };
    BOOL    validDriveLetter    = PathIsDirectory(driveLetter);

    if(validDriveLetter == 0)
        return -4;

    if(path[2] != '\\')
        return -5;

    int i;
    for(i = 3; i < szPath; i++)
    {
        if(path[i] == '/')  return -6;
        if(path[i] == ':')  return -7;
        if(path[i] == '*')  return -8;
        if(path[i] == '"')  return -9;
        if(path[i] == '<')  return -10;
        if(path[i] == '>')  return -11;
        if(path[i] == '|')  return -12;
        if(path[i] == '?')  return -13;
    }

    if(PathIsDirectory(path))
        return 1;

    return 0;
}


texts: Functional K-way merge (Merge k sorted sequences)

texts:
I've implemented a functional k way-merge algorithm to merge k sorted sequences of any type T. I used scalaz's Heap since the Scala standard library does not provide an immutable heap. Any suggestions to make this more performant/concise/idiomatic are welcome :-

import scala.annotation.tailrec
import scalaz.Heap
import scalaz.Order.fromScalaOrdering

def kWayMerge[T: Ordering](allSequences: IndexedSeq[IndexedSeq[T]]): IndexedSeq[T] = {
    case class PQNode(elem: T, indexInList: Int, indexOfList: Int)

    implicit val pqOrdering = fromScalaOrdering(Ordering.by[PQNode, T](_.elem))
    val pqNodes = allSequences.zipWithIndex.map {
      case (list, indexOfList) =>
        list.zipWithIndex.map { case (a, b) => PQNode(a, b, indexOfList) }
    }

    @tailrec
    def loop(priorityQueue: Heap[PQNode], sortedList: IndexedSeq[T]): IndexedSeq[T] = {
      if (priorityQueue.isEmpty) sortedList
      else {
        val minNode = priorityQueue.minimum
        val newPq = priorityQueue.deleteMin
        val finalPQ = pqNodes(minNode.indexOfList).lift(minNode.indexInList + 1).fold(newPq)(newPq.insert(_))
        loop(finalPQ, sortedList :+ minNode.elem)
      }
    }

    val priorityQueue = pqNodes.foldLeft(Heap.Empty[PQNode])((heap, list) => heap.insert(list(0)))
    loop(priorityQueue, IndexedSeq.empty[T])
  }


texts: Counting the number of primes in C and C++11

texts:
I found this old piece of code that I wrote while I was learning C a while back:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <N>\n", argv[0]);
        return 1;
    }

    size_t limit = strtoul(argv[1], (char **) NULL, 10);
    size_t i, j, res = 0;
    size_t isqrt = (size_t) sqrt(limit);
    char* numbers = calloc(limit, 1);

    for (i = 2; i <= isqrt; i++) {
        if (numbers[i]) continue;
        for (j = i*i; j < limit; j += i) numbers[j] = 1;
    }

    for (i = 2; i < limit; i++) {
        if (!numbers[i]) ++res;
    }
    printf("%lu\n", res);
    free(numbers);
    return 0;
}

It's a sieve of Erathosthenes. Since now I started learning C++, I decided to rewrite it in C++11:

#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <math.h>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <N>" << std::endl;
        return 1;
    }

    size_t limit = std::stoul(argv[1]);
    size_t i, j, res = 0;
    size_t isqrt = size_t (sqrt(limit));
    std::unique_ptr<std::vector<bool> > sieve(new std::vector<bool>(limit));

    for (i = 2; i <= isqrt; ++i) {
        if (sieve->at(i)) continue;
        for (j = i*i; j < limit; j += i) sieve->at(j) = 1;
    }

    for_each(sieve->cbegin() + 2, sieve->cend(), [&res](bool i) { res += !i; });
    std::cout << res << std::endl;
    return 0;
}

Is this the most idiomatic way to code in C++? I also tried to replace the first for loop with a for_each and a functor that accepts sieve, but in the end I decided it wasn't worth it and left it like that.

In both versions I am allocating on the heap because the sieve array/vector gets too big for the stack.

Interestingly, the C++ version is faster! I thought they were pretty much identical, but instead the C++ version wins by a large margin:

$ gcc --std=c99 -O3 erat.c -lm -o erat
$ time ./erat 1000000000
50847534
./erat 1000000000  11.50s user 0.41s system 99% cpu 11.927 total
$ g++ --std=c++14 -O2 erat.cpp -o erat2
$ time ./erat2 1000000000
50847534
./erat2 1000000000  8.52s user 0.02s system 99% cpu 8.554 total

Feedback on the C version is also welcomed!


texts: Is this the correct way to create a route to a specific .hbs file?

texts:
This is my /forums page

2019/2020 Premier League Forum

  View

For the above code you can see the href pointing to a directory to premierLeague.hbs.
This is how my file structure looks.
├── app.js
├── views/
│   ├── index.hbs
│   ├── forums.hbs
│   ├── login.hbs
│   ├── Leagues/
│       ├── EnglishDivision/
│           ├── PremierLeague.hbs
│
├── routes/
│   ├── Pages.js

This is my app.js
// Public dir
var publicDir = path.join(__dirname, './public');
app.use(express.static(publicDir));

// Define routes
app.use('/', require('./routes/pages'));

This is my pages.js
// Forum
router.get('/forums', authController.isLoggedIn, function(req, res) {
  if(req.user) {
    res.render('forums');
  } else {
    res.redirect('login');
  }
});

// English Division //

// Premier League
router.get('/Leagues/EnglishDivision/PremierLeague', authController.isLoggedIn, function(req, res) {
  if(req.user) {
    res.render('./Leagues/EnglishDivision/PremierLeague');
  } else {
    res.redirect('login');
  }
});

Question:
In order for premier league html file to be accessed via the a tag from forums page, have I set the routing correctly?


texts: Extend API of complex source-code parsing CPAN module

texts:
I am working on a source line parser using PPI. After working a while, I realized that
it would be nice if the PPI API had included such and such functionality. As a very simple example, the PPI::Element contains a class method that returns the class name of the current element. This method must be called quite often and results in statements like

if ( $elem->class eq 'PPI::Token::Symbol' ) { ... }

Now all these statements contain strings with prefix PPI::, so it would be nice if there was a an alternative to the class method that would omit the prefix. For exmple a name method:

if ( $elem->name eq 'Token::Symbol' ) { ... }

How can this best be achieved? In general, the question is how to extend a complex CPAN module like PPI with user defined methods? I think sub classing the PPI::Element method would not work (see example below)  since other PPI methods like find or snext_sibling would still return PPI::Element objects (see below example) and not objects of my sub class. Here is what I came up with:

use feature qw(say);
use strict;
use warnings;

BEGIN {
    require PPI;
    require PPI::Dumper;
    require My::PPI::Extensions;

    *{PPI::Element::name} = \&My::PPI::Extensions::name;
}

my $line = 'f( $q->{key}[$var + 4] );';
my $doc = PPI::Document->new( \$line );
my $dumper = PPI::Dumper->new( $doc );
$dumper->print;
my $symbols = $doc->find('PPI::Token::Symbol');
my $elem = $symbols->[0];
say "";
say "Start elem: " . $elem->class;
$elem = $elem->snext_sibling;
say "Next elem: " . $elem->class;

# This first test is how it would be done originally,
# here I have to include the "PPI::" prefix
if ( $elem->class eq 'PPI::Token::Operator')  {
    say "First test ok..";
}
# This second test is to show how it could be done without
# modifying the `PPI::Element` API
if ( is_elem( $elem, name => 'Token::Operator') ) {
    say "Second test ok..";
}
# This last test shows the new method "name":
if ( $elem->name eq 'Token::Operator') {
    say "Third test ok..";
}

sub is_elem {
    my ( $elem, %opt ) = @_;

    my $class = $elem->class;
    $class =~ s/^PPI:://;
    return $class eq $opt{name};
}

where My/PPI/Extensions.pm is:

package My::PPI::Extensions;
use feature qw(say);
use strict;
use warnings;

sub name {
    my $self = shift;

    my $name = $self->class;
    $name =~ s/^PPI:://;
    return $name;
}

1;

Note: the code I am working on might turn into an open source project at some point. It could also become somewhat complex. So it will be important that it will be maintainable in the long run, also by others in addition to myself.

References:

Chapter 9: Modifying and Jury-Rigging Modules
of Mastering Perl.


texts: Data transfer objects vs Entities in JAVA REST server application

texts:
I am quite new in web application back-end development and I have an architectural question.
I have defined Hibernate entities in my application and I want to send them to client. Currently for each entity I have defined data transfer object, that is almost the same as entity. Is it good practice to create DTO for each entity? Or should I send Hibernate entity for it? I find it quite redundant to make another class that is the same, but on the other hand - it is for different purpose.
Here is the example of what I mean:

User user = userPreferenceService.getUser(userLogin.getEmail(), userLogin.getPassword());
        UserDto userDto = new UserDto();
        userDto.setId(user.getId());
        userDto.setName(user.getName());
        userDto.setSurname(user.getSurname());
        userDto.setEmail(user.getEmail());
        userDto.setPhone(user.getPhone());
        userDto.setCountryId(user.getCountry().getId());

Here the User object is entity in database and userDto is the one that I send to the client. They contain the same info. Should I do it that way? Or should I just send the User?


texts: Getting NTFS permissions of all shared folders on the local machine

texts:
How can I improve the speed of the script?

$Excel = New-Object -Com Excel.Application
$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()

$wSheet = $Excel.Worksheets.Item(1)
$wSheet.Cells.item(1, 1) = "Folder Path:"
$wSheet.Cells.Item(1, 2) = "Users/Groups:"
$wSheet.Cells.Item(1, 3) = "Permissions:"
$wSheet.Cells.Item(1, 4) = "Permissions Inherited:"

$WorkBook = $wSheet.UsedRange
$WorkBook.Interior.ColorIndex = 8
$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True

 ####Change the path to the folder or share you want NTFS perms on####
 $dirToAudit = Get-ChildItem -Path "c:\inetpub" -recurse | Where { $_.psIsContainer -eq $true }

 $intRow = 1
 foreach ($dir in $dirToAudit)
 {
     $colACL = Get-Acl -Path $dir.FullName

foreach ($acl in $colACL)
 {
    $intRow++
    $wSheet.Cells.Item($intRow, 1) = $dir.FullName

    foreach ($accessRight in $acl.Access)
    {
        $wSheet.Cells.Item($intRow, 2) = "$($AccessRight.IdentityReference)"
        $wSheet.Cells.Item($intRow, 3) = "$($AccessRight.FileSystemRights)"
        $wSheet.Cells.Item($intRow, 4) = $acl.AreAccessRulesProtected
        $intRow++
    }
}

}
 $WorkBook.EntireColumn.AutoFit()


texts: CUDA program that emulates a kind of cellular automata slower on the GPU than on the CPU

texts:
I'm a very new to CUDA, so I'm still trying to understand how to make the best use of the GPU. I've ported a C algorithm to it. This algorithm works by loading the memory with an initial input, then calling a rewrite function, which rewrites 128 bits of memory, consecutively, until we arrive at an answer. Since rewrite is completely local, it is easy to parallelize, because you can call it at the same time in different memory positions.

This is how I tested it for the CPU:

#include <stdio.h>
#include "test_inputs.cu"
#include "rewriter.cu"

void process(int *mem, int len, int j){
    for (int i=j; i<len-2; i+=3)
        rewrite(mem+i*4, mem+i*4+4, mem+i*4+8);
};

int main(){
    // Loads initial input
    for (int i=0; i < memory_ints; ++i)
        memory[i] = i < program_nodes*4 ? program[i] : 0;

    // Prints it for visualization
    print(memory, 40);

    // Calls rewrite sequentially until the computation is done
    for (int k=0; k<clocks*3; ++k)
        for (int j=0; j<3; ++j) // for alternating alignments
            process(memory, memory_nodes, j);

    // Print the result (should have only 4 numbers)
    print(memory, 40);
}

This is how I tested it for the GPU:

#include <stdio.h>
#include "test_inputs.cu"
#include "rewriter.cu"

__global__ void process(int *mem, int len, int j){
    int i = (blockIdx.x*blockDim.x + threadIdx.x)*3 + j;
    if (i >= len-2) return;
    rewrite(mem+i*4, mem+i*4+4, mem+i*4+8);
};

int main(){

    // Loads initial input
    for (int i=0; i < memory_ints; ++i)
        memory[i] = i < program_nodes*4 ? program[i] : 0;

    // Prints it for visualization
    print(memory, 40);

    // Puts it on the GPU
    int *device_memory;
    cudaMalloc((void**)&device_memory, sizeof memory);
    cudaMemcpy(device_memory, memory, memory_size, cudaMemcpyHostToDevice);

    // Calls rewrite in parallel until the computation is done
    dim3 block_size(16, 1);
    dim3 grid_size(memory_nodes / block_size.x / 3, 1);
    for (int k=0; k<clocks; ++k)
        for (int j=0; j<3; ++j) // for alternating alignments
            process<<<block_size, grid_size>>>(device_memory, memory_nodes, j);

    // Gets data back from GPU
    cudaMemcpy(memory, device_memory, memory_size, cudaMemcpyDeviceToHost);
    cudaFree(device_memory);

    // Print the result (should have only 4 numbers)
    print(memory, 40);
}

Unfortunately, the parallel version is about 2 times slower than the sequential version. rewriter.cu and test_inputs.cu are on this repository. I'm aware this must be ridden of newbie mistakes, but that's why I'm asking here. What are the worst mistakes I made and how can I improve it?


texts: Guess a number, any number, between 1 and 10

texts:
I am learning Ruby and would like to know how I am doing as far as writing the actual code.

Please keep in mind that this is my first Ruby script program, but I am trying to learn ruby in a very short period of time.

I would like to know about nitpicks in the language that every Ruby writer should now, nuances in syntax, and other Ruby specific ... things.

$randomNumber = rand(10) + 1

def guessRandomNumber
    puts "Guess a number between 1 and 10"
    guess = gets
    if Integer(guess) == $randomNumber
        puts "Right on, good guess"
    elsif Integer(guess) < $randomNumber
        puts "too low"
        puts "please, guess again"
        guessRandomNumber
    elsif Integer(guess) > $randomNumber
        puts "too high"
        puts "please, guess again"
        guessRandomNumber
    else
        puts "is that even a number? please, guess again"
        guessRandomNumber
    end
end

guessRandomNumber

puts "bye"
gets


texts:
I wrote some code to generate list items for a menu in Clojurescript. The intention is that the code takes parsed Markdown (Hiccup) that has been filtered down to h2 and h3 elements, and then converts them into unordered lists where the h3 elements are nested inside their immediate h2 predecessor.

It turned out to be surprisingly difficult in CLJS, and I'm curious if there's a more Lispy and efficient way to do it.

Code

(defn listify-element [element]
  "Replaces element type with :li."
  (vec (concat [:li (last element))]))

(defn listify-headings [headings-list]
  "Takes subitems (in :h2 :h3) and creates sub :uls out of the :h3 lists."
  (vec
   (concat
    [:ul]
    (map-indexed
     (fn [ind headings]
       (if (= 0 (mod ind 2))
         (map listify-element headings)
         (vec (concat [:ul] (map listify-element headings)))))
     (partition-by #(= :h2 (first %)) headings-list)))))

(defn nest-listified-headings [vector-list]
  "Nests sub-:uls inside their preceding :lis."
  (vec (concat [:ul]
          (reduce
           (fn [acc el] (if (= (first el) :ul)
                          (conj (pop (vec acc)) (conj (last acc) el))
                          (concat acc el)))
           vector-list))))

Test case

(nest-listified-headings
  (listify-headings [[:h2 "Foo"] [:h2 "Bar"] [:h3 "Baz"] [:h3 "Bat"]])

[:ul
  [:li "Foo"]
  [:li "Bar"
  [:ul
    [:li "Baz"]
    [:li "Bat"]]]]


texts: Javascript 5 Module Pattern internal name

texts:
I'm learning about the Javascript module pattern from an array of online sources. The following suits my basic needs at the moment:

var module = function(){

    // Create the return module and its configuration
    var module = {},
    config = {
        css:{
            classes:{
                heading:'h1',
                navbar:'nav-bar'
            },
            ids:{
                widget:'widget',
                block:'block'
            }
        },
        userName:'user',
        token:'UUID'
    };

    // Private methods
    function _moduleMethod() {
        console.log(config.userName);
    }

    // Add functionality to the module's init()-ialising method
    function init() {
        _moduleMethod();
    }

    // Add init, and any other methods, to obj
    module["init"] = init;

    // Return a the module as a Public API
    return module;

}();

// When the DOM is ready, run the module
document.addEventListener("DOMContentLoaded", function() {
    module.init();
});

My question is regarding the naming of the internal return object the same as the external variable "module". My thinking is that it's OK given closure and scoping but most of the examples I've seen name the internal object something like "obj" or "my". Am I going to run into issues down the line, say with the Augmenting module pattern?


texts: Functions between certain times of the day

texts:
I'm working on something for my school's laptops that will disable videos/games between 8:00 AM and 3:15 PM. Due to the giant time gap, I will not be waiting to see if the code functions properly or not. What I want to know is if my code will function properly, as I'm not good enough at JavaScript to know myself.

function timer() {
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();

    if (minutes < 10) {
        var minutes = "0" + minutes;
    } else {}

    $(".time").html(hours + ":" + minutes),
        setInterval(timer, 1000);

    // Disable stuff
    if (hours > 8 & hours < 15) {
        $("video").hide();
        $("video").parent().html("Can you do us all a favor and not eat up all the bandwidth with your video watching?" + "
" + "Thank you!" + "
" + "
");
        $("embed").hide();
        $("embed").parent().html("This is no time for childish games." + "
" + "Shouldn't you be studying or doing something related to school?" + "
" + "
");
    } else if(hours > 15 & hours < 8) {
        $("video").show();
        $("embed").show();
    }
}


texts: Is my MySQL library wrapper neat? How can I do better?

texts:
I'm moderately new to programming in C and I'm not sure about programming practices with code; suddenly I have had fears that my code is messy and disorganized. I can read it when I come back a month later yet I'm still nervous if I'm doing anything that's considered taboo.

This isn't all the code that I've done with this project, I think my other code is fine.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include "functions.h"
#include "errh.h"
#include "mysqlerr.h"

void FIRST_TIME_HANDLER(MYSQL *conn)
{
    printw("[+] Doing initialization checks...\n");
    SEND_MYSQL_QUERY(conn, "create table IF NOT EXISTS user_2(username varchar(25) not null, passwd varchar(25) not null)");
    printw("[+] Handler has checked tables.\n");
    refresh();
}

void INThandler(int sig)
{
    signal(sig, SIG_IGN);
    printw("Closing server...\n");
    refresh();
    sleep(5);
    endwin();
    exit(0);
}

MYSQL_INFO *CONNECTION_INIT()
{
    MYSQL_INFO *info = malloc(sizeof(*info));
    info->IP = "IPADDRGOHERE"; info->user = "Hello";
    info->pass = "World"; info->DB = "DBGOHERE";
    return info;
}

int EXIT_SERVER(MYSQL *connection)
{
    mysql_close(connection);
    printw("MySQL session has now closed.\n");
    refresh();
    return KILL_SIGNAL;
}

MYSQL *MYSQL_CONNECT_DB(MYSQL_INFO *info)
{
    MYSQL *connection;
    const char *server = info->IP;
    const char *user = info->user;
    const char *password = info->pass;
    const char *database = info->DB;

    connection = mysql_init(NULL);

    if(!mysql_real_connect(connection, server, user, password, database, 0,
        NULL, 0))
    {
        //printw("[-] Error: %s\n", mysql_error(connection));
        MYSQL *f = KILL_SIGNAL;
        refresh();
        return f;
    }

    printw("[+] Connected to MySQL server.\n");
    FIRST_TIME_HANDLER(connection);
    return connection;
}

void SEND_MYSQL_QUERY(MYSQL *conn, const char *query)
{
    refresh();
    if(mysql_query(conn, query))
    {
        ERROR err;
        throw_error_init(err, 0, 1, NONFATAL, "MySQL QUERY ERROR",
            "ERROR IN THE PROCESS OF QUERY.", MySQL_query_error);
    }
    else
    {
        printw("Query sent.\n");
    }
}

int init_connection()
{
    MYSQL *conn;
    MYSQL_INFO *info = CONNECTION_INIT();

    if((conn = MYSQL_CONNECT_DB(info)) == (MYSQL *) 0)
    {
        ERROR err;
        throw_error_init(err, 1, 1, FATAL, "INIT CONNECTION ERROR",
            "Failed to connect to server.", MySQL_init_failure);
    }
    else {
        int key;
        nodelay(stdscr,TRUE);

        signal(SIGINT, INThandler);

        while(1)
        {
            if((key = getch()) == ERR)
            {
                if(mysql_ping(conn) == 1)
                {
                    printw("Error!\n");
                    refresh();
                    return 1;
                }
            }
            else
            {
                if(key == EOF) break;
            }
        }

        free(info);
        EXIT_SERVER(conn);
        return 0;
    }
    return 0;
}


texts: Converting Integers to roman between 1 and 1000

texts:
Below is my code for the problem:
ItoR = {
1: 'I',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M'
}

def convertItoR(number):
    number_str = str(number)
    number_len = len(number_str)

    rom_str = ''
    for i in range(number_len):
        # Extracting the digit
        digit = int(number_str[i])
        position = number_len - i - 1
        num_pos = digit * 10 ** position

        print(num_pos)

        # Converting digit to roman string
        if num_pos in ItoR.keys():
            rom_str += ItoR[num_pos]

        elif digit > 1 and digit < 4:
            first = 1 * 10 ** position
            rom_str += ItoR[first] * digit

        elif digit > 5 and digit < 9:
            first = 1 * 10 ** position
            fifth = 5 * 10 ** position
            rom_str += ItoR[fifth] + ItoR[first] * (digit - 5)

        print(rom_str)

    return rom_str

Can it be optimized?


texts: Check if a binary tree is a binary search tree or not

texts:
This checks if both the left and right subtrees are binary search trees. If they are, then it compares the nodes data with the maximum element in the nodes' left subtree and minimum element in the nodes' right sub tree.

class Node{
    int data;
    Node left;
    Node right;
    Node(int x){
        data = x;
    }
}
public class isBST {

    public static Node getMin(Node root)
    {
        while(root.left != null)
        {
            root = root.left;
        }

        return root;
    }
    public static Node getMax(Node root)
    {
        while(root.right != null)
        {
            root = root.right;
        }

        return root;
    }
    public static boolean isBST(Node root)
    {
        // for null node
        if(root == null )
        {
            return true;
        }
        // for single node
        if(root.left == null && root.right == null)
        {
            return true;
        }
        // for a non null node
        if(isBST(root.left ) && isBST(root.right) )
        {
            if(root.left != null && root.right != null)
            {
            return root.data < getMin(root.right).data && root.data > getMax(root.left).data;
            }
            else
            {
                if(root.left != null)
                {
                    return root.data > getMax(root.left).data;
                }
                else
                {
                    return root.data < getMin(root.right).data;
                }
            }
        }
        else
        {
            return false;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Node root = new Node(5);
        root.left = new Node(3);
        root.right = new Node(7);
        root.left.left = new Node(2);
        root.left.right = new Node(4);
        root.right.left = new Node(6);
        root.right.right = new Node(9);
        System.out.println(isBST(root));
    }

}


texts: Classify the urgency by comparing the current time to two timestamps

texts:
I'm currently working on a typescript-class with this method:

  /**
   * Gets the state of a package. The state is determined based on two timestamps stored as fields in the {@link
    * Package}. As the current time equals or passes a timestamp, the state changes.
   *
   * @param currentTime The time to compare the timestamps with
   * @param sourcePackage The package containing the two timestamps to compare the currentTime with
   * @returns {CardState} The calculated state of the package
   */
  static determineStateOfPackage(currentTime: Date, sourcePackage: Package): CardState {
    if (sourcePackage.targetTime.getTime() <= currentTime.getTime()) {
      return CardState.URGENT;
    }
    if (sourcePackage.warningTime.getTime() <= currentTime.getTime()) {
      return CardState.WARNING;
    }
    return CardState.FRIENDLY;
  }

It bugs me that the two ifs are repetitive but I can't really figure out how to improve this. How can I improve this code especially to avoid calling the two ifs with nearly the same content twice?


texts:
In the code below, I have a dictionary of attributes and values. I am checking to see if the value if an attribute is True, and if so adding the attribute to a list for later processing (it becomes part of a SQL group by).

This code works fine, but I was wondering how it could be more "Pythonic". Note that the col_map dict is actually a lot bigger.

   col_map = {
        'dim_3a_group_checkbox': 'pn_group',
        'dim_3a_family_checkbox': 'pn_family',
        'dim_3a_root_checkbox': 'pn_root',
    }
    # get an object with the attributes (eg:dim_3a_root_checkbox) as True / False
    supply_kpi = self.browse(cr, uid, ids, context=None)[0]
    group_by = []
    for key, value in col_map.iteritems():
        x = getattr(supply_kpi,key)
        if x:   # only add if attribute is True
            group_by.append(value)
    print group_by

Example results

    ['pn_family', 'order_type', 'pn_group', 'categ']


texts: Mixin both instance and class methods in Ruby

texts:
I have a Ruby class into which I want to include both class and instance methods. Following the pattern described in "Ruby Pattern: Extend through Include", I'm currently using the following:

class SomeObject

  include SomeObject::Ability

  def self.some_builder_method(params)
    # use some_class_method ...
  end

end

module SomeObject::Ability

  module ClassMethods

    def some_class_method(param)
      # ...
    end

  end

  def self.included(klass)
    klass.extend(ClassMethods)
  end

  def some_instance_method
    # ...
  end

end

I'd rather not make two separate modules, one being included and the other being extended, because all the methods in my module logically fit together. On the other hand, this pattern requires me to:

Define an additional ClassMethods module.
Write a boilerplate self.included method for every module.

Is this the most idiomatic way to approach this?


texts: C++ class template for notification management

texts:
Recently, I found myself frequently writing notification managing facilities. That is, one can register as a receiver by providing a callback, and another can send a notification to all registrants by invoking their corresponding callbacks. I had been bothered by re-writing this similar code again and again. Finally, I decided to write a generic one once and for all. Following is the version for cases where the maximum number of registrants is known and limited. So I don't bother using advanced data structures for managing the registered callbacks. Comments pertaining to any aspect of the code are welcome :)

#include <array>
#include <functional>
#include <mutex>
#include <stdexcept>
#include <utility>

template <typename Sig, int max_reg = 16, typename Func = std::function<Sig>>
class NotifyRegistry;

template <int max_reg, typename Func, typename R, typename... Args>
class NotifyRegistry<R(Args...), max_reg, Func>
{
  static_assert(max_reg > 0, "");
public:
  template <typename F>
  int Register(F&& f) {
    std::lock_guard<std::mutex> lock(mut_);
    int i = -1;
    while (++i < max_reg && reg_[i]);
    if (i == max_reg) throw std::length_error("");
    reg_[i] = std::forward<F>(f);
    return i;
  }
  void Unregister(int id) {
    if (id < 0 || id >= max_reg) throw std::invalid_argument("");
    std::lock_guard<std::mutex> lock(mut_);
    reg_[id] = nullptr;
  }
  void Notify(Args... args) const {
    std::lock_guard<std::mutex> lock(mut_);
    for (auto& f : reg_) {
      if (f) (void)f(std::forward<Args>(args)...);
    }
  }
private:
  std::array<Func, max_reg> reg_;
  mutable std::mutex mut_;
};


texts:
I wrote this script a few days ago to find all files which were taking up over a certain threshold of memory on the hard drive.  A hard drive on one of my computers had just 6 GB left, so I needed to clean some space up.  I used this to identify bulky folders to find out where the problem was.

Is there anything I could have done better?  I'm particularly displeased with the exception handling in the get_folder_size function, since I ended up handling the same exception twice, just at different levels.  Couldn't think of a way around it off hand, though.  Also, efficiency was an issue with this script.  I know I could've invented some framework to keep track of all the folders previously scanned, but that seemed like a bit too monumental of an effort to make for such a trivial script.  The recursion was much easier to implement.

Any and all suggestions are welcome!

import os

BYTES_IN_GIGABYTE = 1073741824
GIGABYTE_DISPLAY_LIMIT = 2
ACCESS_ERROR_CODE = 13

def get_folder_size(filepath):
    size = os.path.getsize(filepath)
    try:
        for item in os.listdir(filepath):
            item_path = os.path.join(filepath, item)
            try:
                if os.path.isfile(item_path):
                    size += os.path.getsize(item_path)
                elif os.path.isdir(item_path):
                    size += get_folder_size(item_path)
            except OSError as err:
                if err.errno == ACCESS_ERROR_CODE:
                    print('Unable to access ' + item_path)
                    continue
                else:
                    raise
    except OSError as err:
        if err.errno != ACCESS_ERROR_CODE:
            raise
        else:
            print('Unable to access ' + filepath)
    return size

def get_all_folder_sizes(root_filepath):
    folders = []
    for item in os.walk(root_filepath):
        if os.path.isdir(os.path.join(root_filepath, item[0])):
            folders.append([item[0], get_folder_size(item[0])])
    return folders

def convert_bytes_to_gigabytes(bytes):
    return bytes / BYTES_IN_GIGABYTE

def main():
    folder_sizes = get_all_folder_sizes('C:\\')
    folder_sizes.sort()
    for folder in folder_sizes:
        gigabytes = convert_bytes_to_gigabytes(folder[1])
        if gigabytes > GIGABYTE_DISPLAY_LIMIT:
            print(folder[0] + ' = ' + format(gigabytes, '.2f') + ' GB')

if __name__ == '__main__':
    main()


texts: make_auto implementation for C++03 compilers

texts:
I want to provide, in the the spirit of C++11/boost make_shared and C++14 make_unique, a production-ready make_auto for C++03 compilers.

So, inspired boost's make_shared implementation for C++03 compilers, I provide N overloads (0 to 10, currently) of the same make_auto function.

template <typename T>
inline std::auto_ptr<T> make_auto()
{
   return std::auto_ptr<T>(new T()) ;
}

template <typename T, typename T_0>
inline std::auto_ptr<T> make_auto(const T_0 & p_0)
{
   return std::auto_ptr<T>(new T(p_0)) ;
}

template <typename T, typename T_0, typename T_1>
inline std::auto_ptr<T> make_auto(const T_0 & p_0, const T_1 & p_1)
{
   return std::auto_ptr<T>(new T(p_0, p_1)) ;
}

// etc.

Is there something wrong with this code?

Implementation details:

the const reference is inspired by boost's shared_ptr. After trying multiple alternatives (including GManNickG's excellent answer here), I had to gave up because of some challenged compilers. To pass non-const references, I'll use boost::ref.
the inline keyword is mandatory for reasons that have nothing to do with the problem.

Background info:

I need this for multiple reasons, among them:

I am stuck with C++03 compilers (and I suspect some of them of not even being that... I'm looking at you, SunStudio). This means even C++03 emulations of unique_ptr don't work (we tried)
avoiding writing new/delete in my C++ code (see Stroustrup's C++11 style video)
offering my coworkers the means to use a more modern C++ coding style despite aforementioned compilers limitations (RAII, that is)
more exception safety
I need a lightweight smart pointer with unique-ownership semantics, able to transfer ownership, so boost::shared_ptr and boost::scoped_ptr are not an option


texts: Project Euler 11: Largest product in a grid, Python3

texts:
Project Euler #11

  What is the greatest product of four adjacent numbers in the same
  direction (up, down, left, right, or diagonally) in the 20×20 grid?

I've seen some of the solutions of the problem and although they are in Python3, my solution has some differences.

Pylint rates it 7.27/10 and I will add docstring eventually. Some of the lines are too long(104/100) and fl is not a good name for a file and I agree.

The main issues are comparing product and product_temp and calculating the sum for a diagonal from down left to upper right is inconsistent with the calculating the other products.

The code:

#!/bin/env python3

"""
https://projecteuler.net/problem=11

In a 20x20 matrix iterate over all the rows, columns,
diagonals(left up -> down right, down left -> upper right)
and find the largest product of 4 numbers in the same direction

"""

def list_ints():
    with open('./textfiles/grid2020.txt') as fl:
        array = [[int(x) for x in line.split()] for line in fl]
    return array

def biggest_product():
    grid = list_ints()
    product = 0
    product_temp = 0

    col = 20
    row = 20
    for i in range(row):
        for j in range(col):
            #for row
            if i + 3 < 20:
                product_temp = grid[i][j] * grid[i + 1][j] * grid[i + 2][j] * grid[i + 3][j]

                if product < product_temp:
                    product = product_temp

            #for column
            if j + 3 < 20:
                product_temp = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3]

                if product < product_temp:
                    product = product_temp

            #for diagonal from upper left to down right
            if i + 3 < 20 and j + 3 < 20:
                product_temp = grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3]

                if product < product_temp:
                    product = product_temp

    #another loop from the other diagonal
    #diagonal left to upeer right
    for i in range(20, -1, -1):
        for j in range(20):
            if i + 3 < 20 and j - 3 >= 0:
                product_temp = grid[i][j] * grid[i + 1][j - 1] * grid[i + 2][j - 2] * grid[i + 3][j - 3]

                if product < product_temp:
                    product = product_temp
    return product

if __name__ == '__main__':
    print(biggest_product())

Edit:  Now I see the comments for calculating row and col comments are reversed.


texts: Subclasses instantiating superclass of class Human

texts:
I have a test which looks like this:

Create a base class Human
Human class needs to have a method Talk
The Human class needs to have to descendant class Man and Woman
Both Man and Woman should have their own Talk method (basically rewrite the method)
The Man class should have a private property _foo
It should have a method getInfo (which needs to be an Ajax call and log the response)
I need to make 1000 instances of the Women class in the window namespace (I mean global)
On document.body single click, a random Woman should call the Talk method
On document.body double click, the Man's getInfo method should be called

function Human(){};

Human.prototype.talk = function(){
    console.log('Make an Human sound');
}

function Woman(){
    Human.call(this);
}

Woman.prototype = Object.create(Human.prototype);
Woman.prototype.constructor = Woman;

Woman.prototype.talk = function(){
    console.log('Miau');
}

function Man(){
    var foo = 10;
    Human.call(this);
}

Man.prototype = Object.create(Human.prototype);
Man.prototype.constructor = Man;

Man.prototype.talk = function(){
    console.log('Wuff');
}

Man.prototype.getInfo = function(method, url){
    var xhr = new XMLHttpRequest();

    xhr.open(method, url);
    xhr.send(null);

    xhr.onreadystatechange = function() {
        console.log('Ajax response: ' + xhr.readyState);
    };
}

var woman = new Woman();

console.log('woman instance of Woman ' + (woman instanceof Woman));
console.log('woman instance of Human ' + (woman instanceof Human));

woman.talk();

var man = new Man();

console.log('man instance of Man ' + (man instanceof Man));
console.log('man instance of Human ' + (man instanceof Human));

man.talk();

womans = [];
for(var i = 0; i < 1000; i++) {

    womans[i] = new Woman();
}

document.body.onclick = function(){
    var randNr = Math.floor((Math.random()*1000)+1);
    womans[randNr].talk();
    console.log('Random Woman: ' + randNr);
 }
 document.body.ondblclick = function(){
          Man.prototype.getInfo();
    }


texts: Validation Error Handling - DRY Pattern Implementation

texts:
The Country, State and City functions accepts the Integer as Parameter and returns the relevant error code if the validation fails in ValidateNotExist Class.

Therefore, I have enhanced the ValidateNotExist class with a slight different implementation (using switch) and named it as ValidateNotExistImproved.

But I think, the entire code can be improved further. Can someone help me figure out what mistakes am I doing and how can I improve it?

The entire code is provided with a little explanation for every class.

NotExistErrorCodeConfig

  Error codes configuration.

public static class NotExistErrorCodeConfig
{
    public const string Country = "COUNTRY_NOT_EXIST";
    public const string State = "STATE_NOT_EXIST";
    public const string City = "CITY_NOT_EXIST";
}

EntityTypeEnum

  Enum Configuration, this is being used in the ValidateNotExistImproved class.

public enum EntityTypeEnum
{
    Country = 1,
    State = 2,
    City = 3
}

ExistsHelper

  The actual logic is implemented and it has dedicated functions.

public static class ExistsHelper
{
    public static bool Country(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool State(int id)
    {
        return (id > 10) ? true : false;
    }

    public static bool City(int id)
    {
        return (id > 10) ? true : false;
    }
}

ValidateNotExist

  A helper class, the implementation calls this class. This class is responsible to check the value and return the relevant error message.

public static class ValidateNotExist
{
    public static string Country(int id)
    {
        return (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
    }

    public static string State(int id)
    {
        return (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
    }

    public static string City(int id)
    {
        return (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
    }
}

ValidateNotExistImproved

  I have combined the three functions into single function but using Switch statement. This is supposed to be improved version of ValidateNotExist.

public class ValidateNotExistImproved
{
    public static string Validate(EntityTypeEnum type, int id)
    {
        string errorCode = string.Empty;

        switch (type)
        {
            case EntityTypeEnum.Country:
                errorCode = (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
                break;

            case EntityTypeEnum.State:
                errorCode = (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
                break;

            case EntityTypeEnum.City:
                errorCode = (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
                break;

            default:
                break;
        }

        return errorCode;
    }
}

ImplementationClass

  The actual implementation class, it returns the same error code.

public class ImplementationClass
{
    public ImplementationClass()
    {
        var error = ValidateNotExist.Country(2);                                         //Throws an error COUNTRY_NOT_EXIST
        var extendedError = ValidateNotExistImproved.Validate(EntityTypeEnum.Country, 2);        //Throws an error COUNTRY_NOT_EXIST

        Console.WriteLine(error);
        Console.WriteLine(extendedError);
        Console.ReadKey();
    }
}


texts: Delete all elements from list whose sum with preceding element equals target value

texts:
Let me start off by saying that the question specifically implies using std::list<int> and not anything else AND you are allowed to iterate over the list only once. Taking this into account, we assume the target sum value to be 10.

The task is:

  You are given a list of integers (std::list<'int'>). Iterating over the list only once, delete all elements that give a sum of 10 with the preceding element.

I was wondering how I can make my code more efficient and clear, because my application was rejected immediately.

#include <list>
#include <iostream>
#include <conio.h>

bool target_sum(const int i, const int j)
{
    return (i+j) == 10;
}

void print(const std::list<int> &nmbrs)
{
    for (const int p : nmbrs)
        std::cout << p << " ";
    std::cout << std::endl;
}

int main()
{
    // initialises a list that holds the numbers
    std::list<int> nmbrs = {5, 5, 3, 7, 7, 7, 3, 3, 1, 2, 3, 7, 4, 6};

if (nmbrs.size() > 1)                     //if there are at least 2 numbers
{
    std::list<int>::iterator i = nmbrs.begin();
    while (i != std::prev(nmbrs.end()))   //we compare number *i to the following number *(i+1),
    {                                     //while incrementing the iterator at the same time
        if (target_sum(*i, *(i++)))
        {
            i = nmbrs.erase(i);
            i--;                          //move back in case the numbers repeat
        }

        //print(nmbrs);
    }
} else
{
    //print(nmbrs);
}

print(nmbrs);

_getch();

return 0;
}


texts: Image processing using multiprocessing in Python

texts:
I have an image stack. I am trying to use multiprocessing to do some process on each image in stack to get new image, and then bitwise_or with the old image.

Since multiprocessing won't keep the original order, I pass image index as args.

Later I bitwise_or the new image and old image by a for loop.

Is there a way to avoid for-loop for bitwise_or to have a better performance? Thanks

import cv2 as cv
import numpy as np
from multiprocessing import Pool

def process_img(idx, img):
    new_img = do_something(img)
    return idx, new_img

def main()
    # ...

    output_stack = np.copy(img_stack)

    with Pool() as pool:
        args = zip(
            range(len(img_stack)),
            img_stack)

        new_imgs_with_idx = pool.starmap(process_img, args)

        for i, new_img in new_imgs_with_idx:  # Any better ways?
            output_stack[i] = cv.bitwise_or(output_stack[i], new_img)

    # ...

    return output_stack


texts:
I am solving interview questions from here.

  Problem : Print concentric rectangular pattern in a 2d matrix. The outermost rectangle is formed by A, then the next outermost is formed by A-1 and so on. You will be given number as an argument to the function you need to implement, and you need to return a 2D array.

  Example 1: Input: A = 4.

        Output:

        4 4 4 4 4 4 4
        4 3 3 3 3 3 4
        4 3 2 2 2 3 4
        4 3 2 1 2 3 4
        4 3 2 2 2 3 4
        4 3 3 3 3 3 4
        4 4 4 4 4 4 4

How can I make this code better?

def pretty_print(num):

    m = n = 2*num -1 ##    m x n matrix , length of each row and column
    k = 0 # row start counter
    l = 0 # column start counter
    i = 0 # iterator

    matrix = [[0 for _ in range(n)] for _ in range(m)]

    while k < m and l < n :
        #insert the first row
        for i in range(l, n) :
            if matrix[k][i] == 0:
                matrix[k][i] = num   # row index constt, change values in columns

        k += 1   # first row printed, so increment row start index

        #insert the last column
        for i in range(k, m) :
            if matrix[i][n-1]==0:
                matrix[i][n-1] = num   # column index constt, change values in rows
        n -= 1   # last column printed, so decrement num of columns

        #insert the last row
        if (k<m):   #  if row index less than number of rows remaining
            for i in range(n-1, l-1, -1):
                if matrix[m-1][i] == 0:
                    matrix[m-1][i] = num   # row index constt, insert in columns
        m -= 1   # last row printed, so decrement num of rows

        #insert the first column
        if (l<n):    #  if column index less than number of columns remaining
            for i in range(m-1, k-1, -1):
                if matrix[i][l] == 0:
                    matrix[i][l] = num # column index constt, insert in rows
        l += 1      # first column printed, so increment column start index

        num -= 1    # all elements of value A inserted , so decrement

    return matrix

print pretty_print(6)


texts: "options" binding with an enum as data source

texts:
I need to bind a dropdown to an enum. For this I've made a key_value_pair class and I manually go through each enum option to add it. Is there a more elegant way to achieve this?

HTML:

<select data-bind="options: regions, value: region, optionsValue: 'key', optionsText: 'value'"></select>

TypeScript:

class key_value_pair<key_type, value_type>
{
    key: key_type;

    value: value_type;

    constructor(key: key_type, value: value_type)
    {
        this.key = key;

        this.value = value;
    }
}

class calculator
{
    regions: KnockoutObservableArray<key_value_pair<number, string>>;

    region: KnockoutObservable<API.region>;

    constructor()
    {
        this.regions = ko.observableArray();
        this.regions.push(new key_value_pair(API.region.US, API.region[API.region.US]));
        this.regions.push(new key_value_pair(API.region.Europe, API.region[API.region.Europe]));
        this.regions.push(new key_value_pair(API.region.Korea, API.region[API.region.Korea]));
        this.regions.push(new key_value_pair(API.region.Taiwan, API.region[API.region.Taiwan]));
        this.regions.push(new key_value_pair(API.region.China, API.region[API.region.China]));

        this.region = ko.observable();
    }
}


texts: Hover on list items to change map marker styling

texts:
I'm struggling to make a React/JS map I have more efficient. Essentially, I have a list of cards, and then a map of markers. When I hover on one of the cards, it changes the styling of the marker.

Here’s what it looks like:

But the way I'm doing this...I'm pretty sure is really inefficient, so here's how I have it setup in a couple of components:

//LocationsGrid.js
class LocationsGrid extends React.Component {
  state = {
    hoveredCardId: ""
  };

  setCardMarkerHover = location => {
    this.setState({
      hoveredCardId: location.pageid
    });
  };

  resetCardMarkerHover = () => {
    this.setState({
      hoveredCardId: ""
    });
  };

render() {
    const { locations } = this.props;

{locations.map((location, index) => (
    <LocationCard
      setCardMarkerHover={this.setCardMarkerHover}
      resetCardMarkerHover={this.resetCardMarkerHover}
      location={location}
    />
 ))}
   // map stuff

          <MapAndMarkers
            locations={locations}
            hoveredCardId={this.state.hoveredCardId}
          />

//LocationCard.js
class LocationCard extends React.Component {
  render() {
    const { classes, location } = this.props;

    return (
      <Card
        className={classes.card}
        onMouseEnter={e => this.props.setCardMarkerHover(location)}
        onMouseLeave={e => this.props.resetCardMarkerHover()}
       >
        <CardContent className={classes.cardContentArea}>

        </CardContent>
      </Card>
    );
  }
}

// MapAndMarkers.js

class MapAndMarkers extends React.Component {
  render() {
    const { locations, hoveredCardId, pageid } = this.props;

    let MapMarkers = locations.map((location, index) => {
      return (
        <MapMarker
          key={location.id}
          lat={location.lat}
          lng={location.lng}
          pageid={location.pageid}
          hoveredCardId={hoveredCardId}
        />
      );
    });

    return (

        <GoogleMapReact>
          {MapMarkers}
        </GoogleMapReact>

    );
  }
}

// MapMarker.js
import classNames from 'classnames';
class MapMarker extends React.Component {
  render() {
    const { classes, pageid, hoveredCardId } = this.props;

    return (

      {this.props.name}

    );
  }
}

The problem with doing it this way is I'm pretty sure there's a whole bunch of wasted rendering. When I pulled out the mouse events from my LocationCard, everything else runs faster.

What would be a more efficient way of tracking hovered list items so that I can change the map marker style?

GitHub

Demo


texts:
I have a string str ="/Users/user/Desktop/task/U6342_Account_20150112.txt"

I need return only U6342_Account_20150112 as an array ['U6342','Account','20150112']

I did

str.split('/')[-1].gsub('.txt','').split('_')

which gives me ['U6342','Account','20150112']

Is there any more convenient solution to do it?


texts: .Net BouncyCastle - CSR and Private Key Generation

texts:
The purpose of this code is to generate the CSR and the Private Key.

The scenario is that we have some clients for whom we run websites and for the SSL component we want to have a page on our site where they can input the fields like domain name, company name etc and then the system will generate the CSR (and return it to them on the screen so they can get it signed by a third party, e.g. geotrust) and the private key will automatically be put into the correct spot on the web server ready for use.

The 'main' part of this is below.

        /// <summary>
        ///     Generates certificate request in PKCS#10 format defined by RFC 2986.
        ///     This will also output the private key at the same time.
        ///     *******************************************
        ///     Notes / Handy references:
        ///     http://www.keylength.com/en/compare/
        ///     http://csrc.nist.gov/publications/nistpubs/800-57/sp800-57_part1_rev3_general.pdf
        /// </summary>
        private void GeneratePkcs10
            (string domainName, string companyName, string division, string city, string state,
             string countryIso2Characters, string email, RootLenght rootLength, out string csr, out string privateKey)
        {
            csr = null;
            privateKey = null;

            try
            {
                var rsaKeyPairGenerator = new RsaKeyPairGenerator();

                // Note: the numbers {3, 5, 17, 257 or 65537} as Fermat primes.
                // NIST doesn't allow a public exponent smaller than 65537, since smaller exponents are a problem if they aren't properly padded.
                // Note: the default in openssl is '65537', i.e. 0x10001.
                var genParam = new RsaKeyGenerationParameters
                    (BigInteger.ValueOf(0x10001), new SecureRandom(), (int) rootLength, 128);

                rsaKeyPairGenerator.Init(genParam);

                AsymmetricCipherKeyPair pair = rsaKeyPairGenerator.GenerateKeyPair();

                IDictionary attrs = new Hashtable();

                attrs.Add(X509Name.CN, domainName);
                attrs.Add(X509Name.O, companyName);
                attrs.Add(X509Name.L, city);
                attrs.Add(X509Name.ST, state);
                attrs.Add(X509Name.C, countryIso2Characters);

                if (division != null)
                {
                    attrs.Add(X509Name.OU, division);
                }

                if (email != null)
                {
                    attrs.Add(X509Name.EmailAddress, email);
                }

                var subject = new X509Name(new ArrayList(attrs.Keys), attrs);

                var pkcs10CertificationRequest = new Pkcs10CertificationRequest
                    (PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id, subject, pair.Public, null, pair.Private);

                csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded());

                var pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
                privateKey = Convert.ToBase64String(pkInfo.GetDerEncoded());
            }
            catch (Exception ex)
            {
                // Note: handles errors on the page. Redirect to error page.
                ErrorHandler(ex);
            }
        }

        private enum RootLenght
        {

            RootLength2048 = 2048,

            RootLength3072 = 3072,

            RootLength4096 = 4096,

        }

Because the documentation for BouncyCastle for .net is limited, I am unsure if the above is 'correct'. It does compile, however:

Is it safe to always use BigInteger.ValueOf(0x10001)? This seems to be the default for OpenSSL so I presume this is correct. Or should this be the actual number 65537?
NIST does not have a 'certainty' recommendation for 4096 keys. Is it safe to use 128 always for the three lengths in the enum? I saw this answer but it is a bit dated. Should I be switching the value depending on the length of the key?
Am I missing anything?


texts:
I have a DataService, which should talk to the server and store vars (for complicated calls, for example).

Last time, I ended up with this approach (for the example, I'm working with a list):

GetList() - returns cached data (just a property)
SetList() - sets a property
ReadList() - read data from file from IsoStorage
WriteList() - write data to file
PullList() - pull data from the server
PushList() - push data to the server

NB: I'm using my old IsoStorage approach (IsoSettingsManager).

Now, after some time, I understood that I can merge first two stages: caching and writing to IsoStorage. Now I'm thinking of something like

    private int? deliveryId = null;
    public int DeliveryId
    {
        get { return deliveryId ?? IsoSettingsManager.GetProperty<int>("DeliveryId"); }
        set { deliveryId = value; IsoSettingsManager.SetProperty("DeliveryId", value); }
    }

Where setting property is

public static void SetProperty(string propertyName, object content)
    {
        if (System.ComponentModel.DesignerProperties.IsInDesignTool)
            return;

        if (content == null)
            RemoveProperty(propertyName); // if (isoSettings.Contains(propertyName)) isoSettings.Remove(propertyName);

        isoSettings[propertyName] = content;
        isoSettings.Save();
    }

What do you think about it?

First thing that comes to my mind is to make SetProperty to return the setted value so I'd be able to use it like

public int DeliveryId
{
    set { deliveryId = IsoSettingsManager.SetProperty("DeliveryId", value); }
    ***

unsetting DeliveryId = null; is not working for ints (fair enough), and I couldn't yet find how to push/pull them effectively.


texts:
I have some enum classes for units, like Weight units (KG and LB). I am translating the code to Qt C++ from Java, and I'm wondering what the best way to do this is as enums cannot have constructors in C++ that same way they do in Java (as far as I know).

Here is the Java class:

public enum WeightUnit {
  LB(WEIGHT_UNIT_LB, 0.45359237), //"lb" 1lb = 0.45359237 kg.
  KG(WEIGHT_UNIT_KG, 1.0);        //"kg"

  private String displayName;
  private double scale;

  private WeightUnit(String displayNameKey, double scale) {
      this.displayName = getDataMessages().getString(displayNameKey);
      this.scale = scale;
  }

  public String getDisplayName() {
      return displayName;
  }

  public String toString() {
      return displayName;
  }

  public static WeightUnit valueByName(String unitName) {
      for (WeightUnit value : WeightUnit.values()) {
          if (value.getDisplayName().equals(unitName) ||
                  value.name().equals(unitName)) {
              return value;
          }
      }
      throw new IllegalArgumentException(unitName);
  }

  public static double convert(double value, WeightUnit from, WeightUnit to) {
      if (from == to) return value;
      return value * from.scale/to.scale;
  }
}

Here is my C++ translation. It is not as elegant or clean as the Java version.

class WeightUnit {
  public:
    enum Value
    {
        LB,
        KG
    };

    WeightUnit() = default;
    constexpr WeightUnit(Value weightUnit) : value(weightUnit) {}

    bool operator==(WeightUnit a) const { return value == a.value; }
    bool operator!=(WeightUnit a) const { return value != a.value; }

    static double convert(double value, WeightUnit fromUnit, WeightUnit toUnit){
        return value * val(fromUnit.value)/val(toUnit.value);
    }

    static WeightUnit fromStr(QString str){
        if (str.compare(toStr(Value::LB)) == 0)
            return WeightUnit::LB;
        else if (str.compare(toStr(Value::KG)) == 0)
            return WeightUnit::KG;
        else
            throw QException();
    }

    static QString toStr(WeightUnit unit){
        if (unit == WeightUnit::LB)
            return "lb";
        else if (unit == WeightUnit::KG)
            return "kg";
        else
            throw QException();
    }

private:
    Value value;

    static double val(Value value){
        switch(value){
        case KG:
            return 1.0;
        case LB:
            return 0.45359237; //1 lb = 0.45359237 kg
        }
        throw QException(); //if not found, throw exception
    }
};

Is there any better way to tie values to each enum value in C++? In Java it is easy, because you can specify a constructor that requires certain parameters so you can be sure each enum value has an appropriate String and double value. Is there a way to do this in Qt/C++?


texts: Compute intersections of all combinations of vectors in a list of vectors in R

texts:
My goal is to compute the intersections of several vectors (sets of identifiers, gene-names to be specific). I start with a list of vectors and run the function below, which loops through 1:n where n is the number of sets and then uses combn to generate all combinations of my sets taken m at a time.

I paste together a name and then reduce by intersection over my sets yielding a named list of character vectors holding the elements in common between each combination of sets.

My question is, of course, is there a better way to accomplish this?

## Compute the intersection of all combinations of the
## elements in the list of vectors l. Might be useful
## for generating Venn/Euler diagrams.
## There might be better ways to do this!
overlap <- function(l) {
  results <- list()

  # combinations of m elements of list l
  for (m in seq(along=l)) {

    # generate and iterate through combinations of length m
    for (indices in combn(seq(length(l)), m, simplify=FALSE)) {

      # make name by concatenating the names of the elements
      # of l that we're intersecting
      name <- do.call(paste, c(as.list(names(l)[indices]), sep="_"))

      # adding the init=l[indices[1]] parameter helps with the case
      # where we're only dealing with one set, i==1 and length(indices)==1,
      # and we want only unique items in that set.
      # Reduce(intersect, list(c(1,2,3,3))) => c(1,2,3,3)
      # Reduce(intersect, list(c(1,2,3,3)), init=l[[indices[1]]]) => c(1,2,3)
      results[[name]] <- Reduce(intersect, l[indices], init=l[[indices[1]]])
    }
  }
  results
}

overlap( list(foo=c('a','b','c','d','e','e'),
              bar=c('a','c','e','f','g'),
              bat=c('a','b','c','d','g')))


texts: VBA macro which filters and splits dataset into new workbooks

texts:
This VBA macro uses a worksheet (source_data_worksheet) to filter and split out the records based on about a dozen unique column (D) values in a dataset of about to separate workbooks which are saved to a folder.

There are over 10,000 records x 18 columns total with text and numbers (the overall file size of source worksheet is about 1.3MB). The number of records per unique value of filtering variable range from over 100 to over 5000. The source dataset is sorted by the variable used for filtering/splitting out.

In addition to creating the worksheet in the new workbook with the filtered subset of the data, the macro also copies two worksheets from the source workbook to the destination workbook next to the newly output subset worksheet.

One of the worksheets is very simple/small (SheetA), but another one (SheetB) has a table of about 100 rows by 9 columns which are using VLOOKUP and INDIRECT functions to cross-reference in data from the newly created subset worksheet based on some criteria.

The macros works and the data is populated as expected. It starts out fairly quick with the first subset (about 300 rows) populating in a few seconds.

However, things slow down substantially (10 minutes or longer for some of the larger subsets) and the number of output records itself does not seem proportionate to the longer time duration. The macro also seems to tax the system a lot as it nearly locks up Excel so that it's best to save and close all other worksheets before it runs. I am wondering if there is something in the code that reduces efficiency and causes undue system load during execution.

The output file formal is .xlsm (as opposed to .xlsx default) because some of the copied worksheets contain worksheet-level VBA that needs to be preserved in the new output files.

System: Office Pro 2010, 32-bit running on 64-bit Win i5 3Ghz 8GB.

    Option Explicit

Sub Create_by_keyrecord()

Dim r As Long, rng As Range, ws As Worksheet, wb As Workbook

Dim lastRow As Integer

Application.DisplayAlerts = False
Application.ScreenUpdating = False

With Sheets("Sheet1")
    Sheets.Add().Name = "temp"
    .Range("D7", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("temp").Range("D7"), Unique:=True
     For Each rng In Sheets("temp").Range("D7", Sheets("temp").Range("D7").End(xlDown))
        .AutoFilterMode = False
        .Range("D7").AutoFilter Field:=3, Criteria1:=rng
        Set ws = Sheets.Add

        lastRow = .Range("B7:I7").End(xlDown).Row
        .Range("B7:S" & lastRow).SpecialCells(xlCellTypeVisible).Copy
        ws.Range("B7").PasteSpecial xlPasteColumnWidths
        ws.Range("B7").PasteSpecial xlPasteAll
        .Range("B2:S6").Copy ws.Range("B2")
        Columns("A:A").ColumnWidth = 1

        For r = 1 To lastRow
            ws.Rows(r).RowHeight = .Rows(r).RowHeight
        Next r

        'ws.Name = rng
        ws.Name = "source_data_worksheet"
        ws.Move
        .AutoFilterMode = False
        Rows.Hidden = False
        Columns.Hidden = False
        ActiveWindow.DisplayGridlines = False
        Range("G7").Select
    ActiveWindow.FreezePanes = True

    Range("B6:S6").AutoFilter

'copy additional worksheets to new workbook
    Set wb = ActiveWorkbook
        Windows("sourseworksheet.xlsm").Activate
        Sheets("SheetA").Select
        Sheets("SheetA").Copy After:=wb.Sheets(1)
        wb.Sheets("SheetA").Visible = xlSheetHidden

        Windows("sourseworksheet.xlsm").Activate
        Sheets("SheetB").Select
        Sheets("SheetB").Copy After:=wb.Sheets(1)
'end new code'

        ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True

        ActiveWorkbook.SaveAs _
        Filename:="C:\...\" & rng & "filename.xlsm ", _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled

        ActiveWorkbook.Close 'SaveChanges:=True

    Next rng
      Sheets("temp").Delete

End With

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub


texts:
I have written this code for BubbleSort in F#. Can you review and let me know how I can do this in most functional way.

let rec getHighest list =
    match list with
    | [x] -> x
    | [x; y] when x > y -> x
    | [x; y] -> y
    | hd1 :: hd2 :: tl when hd1 > hd2 -> getHighest (hd1 :: tl)
    | hd1 :: tl -> getHighest tl
    | _ -> failwith "unknown pattern"

let bubbleSort list =
    let rec innerBubbleSort sorted = function
    | [] -> sorted
    | l ->
        let x = getHighest l
        let (a, b) = List.partition (fun i -> i = x) l
        innerBubbleSort (a @ sorted) b
    innerBubbleSort [] list

[<EntryPoint>]
let main args =
    let input = [10; 7; 1; 0; -1; 9; 33; 12; 6; 2; 3; 33; 34;]
    let output = bubbleSort input
    printfn "%s" (List.fold (fun acc x -> acc + " " + x.ToString()) "" output)
    0


texts: A better approach to parsing this file name in Java?

texts:
I am creating a file uploader, and one function of the uploader will parse the file name to make sure that it is in the correct format.

This is the proper format of the file name: FILENAME_USERNAME_YYYYMMDD.csv,
where FILENAME and USERNAME are any chars of any length.

Specifically, I must extract the date from the file name and compare it to a date given in the .csv file content. (comparing to a date: MM/DD/YYYY).

Below is the way that I have approached the problem: but if the user happens to input a file with a random, arbitrary file name, it's very possible for the method to throw a null pointer exception.. Hoping for a suggestion for a more elegant solution.

public boolean compareDate(File file, String cellDate)
{
    String date;
    String tempDate;
    String year, month, day;

    int startIndex = file.getName().lastIndexOf("_");
    int lastIndex = file.getName().lastIndexOf(".");

            if (startIndex > 0 && lastIndex > 0)
            {
                tempDate = file.getName().substring(startIndex+1, lastIndex);

                if (tempDate.length() < 8) // 8 == chars in date
                    return false;
            }

            year = tempDate.substring(0,4);
            month = tempDate.substring(4,6);
            day = tempDate.substring(6,8);

            date = month + "/" + day + "/" + year;

            if (date.equals(cellDate) || date.contains(cellDate)) // (ex. 01/25/2013 == 1/25/2013
                return true;
            else
                return false;
}


texts: Python coding style from Java background

texts:
I am pretty new to Python and just wanted to make sure I am going in the right direction with my coding style.

After reading this, I'm not so sure.

The following is a convenience class that has operations used a lot in my main code.

import requests

try: import simplejson as json
except ImportError: import json

"""
Basic operations involving users
"""

#The URL of the API
api_root = "http://api.stuff.com/v1/core";

class UserOperations(object):
    def __init__(self, headers):
        self.headers = headers

    def move_user(self,source_account,destination_account, user_id):

        user_id = str(user_id)

        #Get user
        user = self.get_user(source_account, user_id)

        if user is not None:

            #Remove user from source account
            self.remove_user(source_account, user_id)

            #Add user to destination account
            self.add_user(destination_account, user)

    def get_user(self, account_id, user_id):

        #Get user
        user = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)

        #Throw exception if non-200 response
        user.raise_for_status()

        print "\nGet User " + user_id + ": " + user.text

        #Check user exists
        if user.json()['Data'] is None:
            return None

        #Return user
        return user.json()['Data']

    def remove_user(self,account_id, user_id):

        #Delete a user
        result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
        #Throw exception if non-200 response
        result.raise_for_status()
        #Result of delete operation
        print "\nDelete Result " + result.text

    def add_user(self,account_id, user):

        #Add user to new account
        result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
        #Throw exception if non-200 response
        result.raise_for_status()
        #Result of add operation
        print "\nAdd User: " + result.text

Does this seem on the right track or are there any Python mantra's I'm missing out on.

Edit

Function to replace below code duplication

variable = requests.get(api_root + "/accounts/"....)
variable.raise_for_status()

Function:

def request(self, request, account_id, user):

    if request is 'get':
        #Get user
        result = requests.get(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)
    elif request is 'post':
        #Add user to new account
        result = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
    elif request is 'delete':
        #Delete user from account
        result = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user_id, headers=self.headers)

    #Throw exception if non-200 response
    result.raise_for_status()
    return result

Edit
Function attempt 2:

def request(self, request, account_id, user):

    function_dict = {}
    function_dict['get'] = requests.get(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)
    function_dict['post'] = requests.post(api_root + '/accounts/' + account_id + '/users', data=json.dumps(user), headers=self.headers)
    function_dict['delete'] = requests.delete(api_root + "/accounts/" + account_id + "/users/" + user, headers=self.headers)

    result = function_dict.get(request)

    #Throw exception if non-200 response
    result.raise_for_status()
    return result


texts:
I have written a simple state machine. Comments and feedback are welcome.

#include <stdio.h>
#include <stdlib.h>

typedef enum Event
{
    eEVENT_X,
    eEVENT_Y,
    eEVENT_Z,
}Event;

typedef enum States
{
    eSTATE_X,
    eSTATE_Y,
    eSTATE_Z
}States;

int e = eEVENT_X;
int s = eSTATE_X;

struct state_transition
{
  Event EventId;
  States StateId;
  void (*function)(void); //call back utility
};

#define NSTATES 3
#define NEVENTS 3
#define STATE_END 3
#define EVENT_END 3

void function_eXsX(void)
{
    printf("\n xx \n");
    e = eEVENT_X;
    s = eSTATE_Y;

}
void function_eXsY(void)
{
    printf("\n xy \n");
    e = eEVENT_X;
    s = eSTATE_Z;
}

void function_eXsZ(void)
{
    printf("\n xz \n");
    e = eEVENT_Y;
    s = eSTATE_X;
}
void function_eYsX(void)
{
    printf("\n yx \n");
    e = eEVENT_Y;
    s = eSTATE_Y;
}
void function_eYsY(void)
{
    printf("\n yy \n");
    e = eEVENT_Y;
    s = eSTATE_Z;
}
void function_eYsZ(void)
{
    printf("\n yz \n");
    e = eEVENT_Z;
    s = eSTATE_X;
}
void function_eZsX(void)
{
    printf("\n zx \n");
    e = eEVENT_Z;
    s = eSTATE_Y;
}
void function_eZsY(void)
{
    printf("\n zy \n");
    e = eEVENT_Z;
    s = eSTATE_Z;
}
void function_eZsZ(void)
{
    printf("\n zz \n");
    e = EVENT_END;
    s = STATE_END;

}

struct state_transition stateTrans[NEVENTS][NSTATES] =
{
      {{eEVENT_X,eSTATE_X,function_eXsX},{eEVENT_X,eSTATE_Y,function_eXsY},{eEVENT_X,eSTATE_Z,function_eXsZ}},
      {{eEVENT_Y,eSTATE_X,function_eYsX},{eEVENT_Y,eSTATE_Y,function_eYsY},{eEVENT_Y,eSTATE_Z,function_eYsZ}},
      {{eEVENT_Z,eSTATE_X,function_eZsX},{eEVENT_Z,eSTATE_Y,function_eZsY},{eEVENT_Z,eSTATE_Z,function_eZsZ}},
};

int main(int argc,char *argv[])
{

    while(1)
    {
        stateTrans[e][s].function();
        if(e == STATE_END && s == EVENT_END)
            break;
    }
    return 0;
}


texts: MIPS assembly program to read integer byte by byte

texts:
I try to learn assembly by writing small programs. This MIPS program is supposed to read an integer from the terminal and print it byte by byte in hexadecimal. I think it works but I didn't check everything.

.data
prompt:     .asciiz "Enter an integer (positive or negative): "
s1:     .asciiz "B1:
s2:     .asciiz " B2:
s3:     .asciiz " B3:
s4:     .asciiz " B4:
MyNumber:       .word 0

.text
main:
    addi $v0, $zero, 4  #code 4 is to print string
    la $a0, prompt      #loads string into register
    syscall

    addi $v0, $zero, 5  #code 5 is to read an integer
    syscall

    sw $v0, MyNumber        #stores value from $v0 to input

    addi $v0, $zero, 4  #code 4 is to print string
    la $a0, s1      #loads string into register
    syscall

    la $t1, MyNumber
    lb $a0, 0($t1)
    lb $t0, MyNumber
    addi $v0, $zero, 34
    syscall

    addi $v0, $zero, 4  #code 4 is to print string
    la $a0, s2      #loads string into register
    syscall

    lb $a0, 1($t1)
    addi $v0, $zero, 34 #print in hexadecimal
    syscall

    addi $v0, $zero, 4  #code 4 is to print string
    la $a0, s3      #loads string into register
    syscall

    lb $a0, 2($t1)
    addi $v0, $zero, 34
    syscall

    addi $v0, $zero, 4  #code 4 is to print string
    la $a0, s4      #loads string into register
    syscall

    lb $a0, 3($t1)
    addi $v0, $zero, 34
    syscall