texts:
I am new to ML and I wanted to implement a Linear Regression to predict a golfer's scores based on certain feature supplied to my model. I would like a review to see if I'm implementing this correctly and any tips to make my model more efficient. Here is my code
import pandas as pd
import numpy as np
from sklearn.linear_model import LassoCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("/Users/aus10/Desktop/PGA/History/Workday_Charity/PGA_TEST_FEAT.csv")
df_model = df.copy()
scaler = StandardScaler()

features = [['SG:ATG', 'FH', 'SG:APP', 'AVG:Putts:GIR', 'SG:Putting']]
for feature in features:
    df_model[feature] = scaler.fit_transform(df_model[feature])

SG_data = pd.read_csv("/Users/aus10/Desktop/PGA/History/Workday_Charity/SG.csv")
x = df.iloc[:,1:6]  #independent columns
y = df.iloc[:,-1]    #target column i.e price range

results = []

# fit final model
model = LassoCV(cv=5, random_state=0)
model.fit(x, y)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=2)

model.fit(x_train, y_train)

y_pred = model.predict(x_test)

print( round(r2_score(y_test, y_pred),2) )

# define one new data instance

index = 0
count = 0

while count < len(SG_data):
    name = SG_data.loc[index].at['Name']
    strokes_gained_atg = SG_data.loc[index].at['SG:ATG']
    fairways_hit = SG_data.loc[index].at['FH']
    strokes_gained_approach = SG_data.loc[index].at['SG:APP']
    average_putts_gir = SG_data.loc[index].at['AVG:Putts:GIR']
    strokes_gained_putting = SG_data.loc[index].at['SG:Putting']

    Xnew = [[ strokes_gained_atg, fairways_hit, strokes_gained_approach, average_putts_gir, strokes_gained_putting ]]
    # make a prediction
    ynew = model.predict(Xnew)
    # show the inputs and predicted outputs
    results.append(
        {
            'Name': name,
            'Projection': (round(ynew[0],2))
        }
        )
    index += 1
    count += 1
sorted_results = sorted(results, key=lambda k: k['Projection'], reverse=True)

df = pd.DataFrame(sorted_results, columns=[
    'Name', 'Projection'])
writer = pd.ExcelWriter('/Users/aus10/Desktop/PGA/Regressions/Linear_Regressions/Results/Workday_Projections_LR_Lasso.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.style.set_properties(**{'text-align': 'center'})
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.width', 1000)
writer.save()

attached are the two csv files.
https://docs.google.com/spreadsheets/d/1BH7_3Z0o2_VAI81p0ZuVZ3-0kO0n7ZrU5iBHF-WTAaw/edit?usp=sharing


texts: Eliminate redundancy from session authentication

texts:
I have a session authentication script and it works, but I can't find a way to eliminate the redundancy where the two database queries are. One checks if the cookie has a corresponding entry, and the other retrieves user information (if the user is logged on) based on the cookie.

$con = new Database();
if(isset($_COOKIE["session"])) {
    $stmt = $con->query("select null from `sessions` where session_id like :1 and ip_address like :2 and user_agent like :3",
        $_COOKIE["session"],
        $_SERVER["REMOTE_ADDR"],
        $_SERVER["HTTP_USER_AGENT"]
    );
    if($stmt->rowCount() === 1) { // Session is valid
        $stmt = $con->query(
            "select users.user_id, users.nickname, users.email, users.analytic_bool, users.chat_bool,".
            "users.news_bool, users.custom_bool, users.entry_time from `sessions`, `users` ".
            "where users.user_id like sessions.user_id and sessions.session_id like :1 and sessions.ip_address ".
            "like :2 and sessions.user_agent like :3",
                $_COOKIE["session"],
                $_SERVER["REMOTE_ADDR"],
                $_SERVER["HTTP_USER_AGENT"]
        ); // Set session data
        $_SESSION = $stmt->fetchAll()[0];
        $_SESSION["level_name"] = ucfirst(get_level_name($_SESSION["level"]));
    } else generate_new_session();
} else generate_new_session();

Note: The Database(), generate_new_session(), and get_level_name() have not been included because they are not relevant.

By the second query, I already know that the session is valid so there is no need to compare the values all over again. I just can't think of an alternative.


texts: Application for converting markdown to PDF

texts:
First time writing C in a long time and would like some code review to try and improve my code. I have some specific questions, but first an introduction to the code.

The application is a simple command line application for converting markdown to pdf.
The source code can be found in the repository on Github.
The main logic is in main.c, and is hopefully pretty straight forward.

My first question is, have I made any common C errors, like buffer overflows or unreleased memory?
I don't think so, I don't use any malloc calls in my code, but would like someone more experienced to take a look.

I'm compiling the application and dependencies statically, how common is this?
My main reason for this is that one of the dependencies (wkhtmltopdf) is a bit tricky to compile, so I want to be able to provide a binary release that doesn't depend on a shared library.

I have added the dependencies to the repository, not what I'm used to from Ruby or Go, but it seems like the most straight forward way. One other solution I tried was to download the dependencies using git in the Makefile, like this. So they did not have to be added, but that did not feel like a good C solution. Feels a bit like a "roll you own" solution. How would you do this?

Is there anything in the Makefile I could do to make it easier to build for various package managers? E.g. apt-get, homebrew, ports, pkg?

Are there anything else I should do to be a good *nix citizen? E.g. the man page.

This block in main.c feels a bit clunky, and I would like to extract it to a couple of methods instead, to get a better flow when reading the main application logic. But I could not find a good way to do so. The logical parts are read_markdown, create_renderer, generate_filename and write_html. But the code seems to be doing to much for a simple extract method. Do you have any suggestions?

/* Read SOURCE(s) */

hoedown_buffer *ib = hoedown_buffer_new(HOEDOWN_IUNIT);
if (n_files == 1) {
    int error_code = read_file_to_buffer(ib, in);
    if (error_code > 0) {
        fprintf(stderr, "I/O errors found while reading input.\n");
        hoedown_buffer_free(ib);
        fclose(in);
        exit(error_code);
    }
} else {
    int i;
    for (i = 0; i < n_files-1; i++) {
        FILE *ir = fopen(file[i], "r");
        int error_code = read_file_to_buffer(ib, ir);
        if (error_code > 0) {
            fprintf(stderr, "I/O errors found while reading input.\n");
            hoedown_buffer_free(ib);
            fclose(ir);
            exit(error_code);
        }
        if (page_break_between_sources) {
            if (i < n_files-1) {
                hoedown_buffer_puts(ib, "\n\n

\n\n");
            }
        }
        fclose(ir);
    }
}

hoedown_renderer *renderer = hoedown_html_renderer_new(0, 0);
hoedown_document *document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, HOEDOWN_MAX_NESTING);

hoedown_buffer *ob = hoedown_buffer_new(HOEDOWN_OUNIT);
hoedown_document_render(document, ob, ib->data, ib->size);
hoedown_buffer_free(ib);
fclose(in);

/* Generate a tmpfile for html output */
char nameBuff[23];
char filePath[30];
int filedesc = -1;
memset(nameBuff, 0, sizeof(nameBuff));
memset(filePath, 0, sizeof(filePath));

strncpy(nameBuff, "/tmp/mdpdf-XXXXXX.html", 22);

filedesc = mkstemps(nameBuff, 5);
FILE *out = fdopen(filedesc, "w");

/* Use tmp file to build a file:// path for wkhtml */
sprintf(filePath, "file://%s", nameBuff);

/* Write tmp html output to file */
write_html_to_file(out, ob, verbose, stylesheet);
fclose(out);

/* Cleanup hoedown */
hoedown_buffer_free(ob);
hoedown_document_free(document);
hoedown_html_renderer_free(renderer);


texts:
I have written a program to parse a string depending on the string the user provides.
Any advise/criticism is appreciated.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define DEFAULT_SIZE 10
#define RESIZE_MULTI 2

/*compares value to see if it exists in parse. return 0 if exists*/
static uint8_t compare(const char value, const char *parse)
{
   size_t i;

   i = 0;
   while(*(parse + i) != '\0')
   {
      if(*(parse + i) == value)
         return 0;
      i++;
   }
   return 1;
}

/*string must be null terminated. the string that needs to be split*/
/*parse must be null terminated. contains value that the string will be split at*/
/*matrix contains all the string that was split based on parse. the function return how how many string there are*/
size_t parse_string(const char *string, const char *parse, char *** const user_matrix)
{
   /*how many spots there are*/
   size_t temp_matrix_size;
   /*how many acctually string there are*/
   size_t temp_matrix_length;
   char **temp_matrix;
   size_t i;
   size_t counter;

   /*allocate initial memory. array of pointers*/
   temp_matrix = malloc(sizeof(*temp_matrix) * DEFAULT_SIZE);
   if(temp_matrix == NULL)
      goto FAIL0;
   temp_matrix_size = DEFAULT_SIZE;
   /*since right now there 0 string aka pointers to strings*/
   temp_matrix_length = 0;

   i = counter = 0;
   while(*(string + i) != '\0')
   {
      /*resize array of pointers*/
      if(temp_matrix_length >= temp_matrix_size)
      {
         char **temp = realloc(temp_matrix, sizeof(*temp_matrix) * temp_matrix_size * RESIZE_MULTI);
         if(temp == NULL)
            goto FAIL0;
         temp_matrix = temp;
         temp_matrix_size = temp_matrix_size * RESIZE_MULTI;
      }

      if(compare(*(string + i), parse) == 0)
      {
         char *temp;
         if(counter > 0)
         {
            /*need the plus 1 for terminating char*/
            temp = malloc(sizeof(*temp) * (counter + 1));
            if(temp == NULL)
               goto FAIL0;

            /*setting terminating char*/
            *(temp + counter) = '\0';
            /*copy over the string before the parsing char*/
            memcpy(temp, string + (i - counter), counter);

            /*store the string*/
            *(temp_matrix + temp_matrix_length) = temp;
            temp_matrix_length++;
         }

         /*store only the parsing char with null terminated char*/
         temp = malloc(sizeof(*temp) * 2);
         if(temp == NULL)
            goto FAIL0;
         *(temp + 0) = *(string + i);
         *(temp + 1) = '\0';

         *(temp_matrix + temp_matrix_length) = temp;
         temp_matrix_length++;

         i++;
         counter = 0;
      }
      else
      {
         i++;
         counter++;
      }
   }

   /*special case*/
   if(counter != 0)
   {
      char *temp = malloc(sizeof(*temp) * (counter + 1));
      if(temp == NULL)
         goto FAIL0;

      /*setting terminating char*/
      *(temp + counter) = '\0';
      /*copy over the string before the parsing char*/
      memcpy(temp, string + (i - counter), counter);

      /*store the string*/
      *(temp_matrix + temp_matrix_length) = temp;
      temp_matrix_length++;
   }

   *user_matrix = temp_matrix;

   return temp_matrix_length;

   FAIL0:
   if(temp_matrix != NULL)
   {
      /*free all the strings*/
      for(i = 0; i < temp_matrix_length; i++)
      {
         free(*(temp_matrix + i));
      }
      /*free the array of pointers*/
      free(temp_matrix);
   }
   *user_matrix = NULL;
   return 0;
}

int main(void)
{
   char **matrix;
   size_t size;

   /*can have anything you want*/
   char *str = "Hello Word!!!";
   /*can have any char you want*/
   char *parse = "! ";

   size = parse_string(str, parse, &matrix);

   for(size_t i = 0; i < size; i++)
   {
      printf("%s\n", *(matrix + i));
   }

   for(size_t i = 0; i < size; i++)
   {
      free(*(matrix + i));
   }
   free(matrix);

   return 0;
}


texts: Web Service implementation on the client

texts:
I will be creating a web service as part of a group project for university, which will be developed using Java within the Eclipse IDE.

Having no prior experience using web services, I managed to find some tutorials that were useful, but struggled to find enough database code examples which suited my needs (though, perhaps I was looking in the wrong places).

My team member has failed to produce even the slightest example of a web service client, so I have taken it upon myself to develop both the web service and client.

I would like to know whether or not my web service example method is suitable for client-side implementation: i.e - Do I have to change the method in order for the client to execute the method or is it acceptable as is?

(I have been creating basic web services using the axis2 framework and running them on the Apache Tomcat server. However, I am open to any suggestions or recommendations in regards to alternative servers and frameworks.)

/**
* Adds a new product to the database
*
* @param name -- name of the game product (e.g - call of duty, grand theft auto)
* @param genre -- genre of the game product (e.g - action, adventure)
* @param platform -- platform of the game product (e.g - playstation 4, xbox one)
* @param developer -- developer of the game product (e.g - sledgehammer games, rockstar north)
* @param publisher -- publisher of the game product (e.g - activision, rockstar games)
* @param ageRating -- age rating of the game product (based on the PEGI rating system)
* @param price -- price of the game product in pounds (£)
* @param quantity -- quantity of the game products
* @param description -- brief description of the game product
*/
public void addProduct(String name, String genre, String platform, String developer, String publisher,
int ageRating, double price, int quantity, String description)
{
try
{
// 1. Connects to the database
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/Products", "root", "root");

// 2. Executes SQL query
String SqlString = "INSERT INTO Games(Game_Name, Genre, Platform, Developer, Publisher, Age_Rating, Price, Quantity, Description) VALUES(?,?,?,?,?,?,?,?,?)";

PreparedStatement prepStatement = connection.prepareStatement(SqlString);
prepStatement.setString(1, name);
prepStatement.setString(2, genre);
prepStatement.setString(3, platform);
prepStatement.setString(4, developer);
prepStatement.setString(5, publisher);
prepStatement.setInt(6, ageRating);
prepStatement.setDouble(7, price);
prepStatement.setInt(8, quantity);
prepStatement.setString(9, description);

// 3. Updates the database using the SQL query
prepStatement.executeUpdate();

// 4. Closes database connection
connection.close();
}
catch(Exception e)
{
System.out.println("Problems were encountered when trying to insert new records to the database. (Ref. to SQL statements)");
}
}
}


texts: Java Console version of Conway's Game of Life

texts:
This is another out-of-the-head-and-into-the-compiler exercise.  This was straight from the editor to code review.  I would like suggestions on things to keep in mind when doing such exercises.

class Cell {
boolean isAlive;
int numberOfNeighbors;
}
public class Conwayv2 {
Cell [][] grid;
int gridHeight;
int gridWidth;
static final int [][] directions = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};

Conwayv2(int height,int width) {
    gridHeight = height;
    gridWidth = width;
    grid = new Cell[height][width];
    for (int row = 0; row < gridHeight; row ++) {
        for (int col = 0; col < gridWidth; col++) {
            Cell cell = new Cell();
            cell.isAlive = (Math.random() > .7) ? true : false;
            grid[row][col] = cell;
        }
    }
}
int countNeighbors(int r, int c) {
    int neighborsCount = 0;
    int x = 0;
    int y = 0;
    for (int [] dir:directions) {
        x = dir[0];
        y = dir[1];
        x = r + x;
        y = c + y;
        if (x >= gridHeight) {
            x -= x;
            else if (x < 0) {
                x += gridHeight;
            }
            if (y >= gridHeight) {
                y -= y;
            } else if (y < 0) {
                y += gridWidth;
            }
            if (grid[x][y].isAlive) neighborsCount++;
        }
        return neighborsCount;
    }
    boolean updateIsAlive(int r, int c) {
        if (!grid[r][c].isAlive && grid[r][c].numberOfNeighbors == 3) {
            return true;
        } else if (grid[r][c].isAlive && grid[r][c].numberOfNeighbors > 3) {
            return false;
        } else if (grid[r][c].isAlive && grid[r][c].numberOfNeighbors < 2) {
            return false;
        }
        return grid[r][c].isAlive;
    }
    void updateGrid() {
        for (int row = 0; row < gridHeight; row++) {
            for (int col = 0; col < gridWidth; col++) {
                grid[row][col].numberOfNeighbors = countNeighbors(row, col);
                grid[row][col].isAlive = updateIsAlive(row, col);
            }
        }
    }
    void displayGrid() {
        for (int row = 0; row < gridHeight; row++) {
            for (int col = 0; col < gridWidth; col++) {
                System.out.print((grid[row][col].isAlive) ? "x|" :  " |");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        Conwayv2 c = new Conwayv2(10,10);
        while (true) {
            c.updateGrid();
            c.displayGrid();
        }
}

}


texts:
I am learning Dyalog APL. I implemented a binary heap, which seems to work. How could I make it look more like APL (and less like Python)?

⎕io←0
heappush←{(⍺,⍵)siftdown 0(≢⍺)}

heappop←{
 heap←⍵
 last←⊃¯1↑heap ⋄ rest←¯1↓heap
 0=≢rest:rest last
 r←heap[0]
 (((last@0)rest)siftup 0)r
}

siftdown←{
 heap←⍺
 start pos←⍵
 item←pos⌷heap
 newpos←{
  ⍵≤start:⍵
  parentpos←⌊(⍵-1)÷2
  parent←parentpos⌷heap
  item<parent:∇ parentpos⊣heap[⍵]←parent
  ⍵
 }pos
 (item@newpos)heap
}

siftup←{
  heap←⍺
  p←{
   pos←⍵
   chp←1+2×pos
   chp≥≢heap:pos
   rpos←1+chp
   chp←((rpos<≢heap)∧~heap[chp]<heap[rpos])⊃chp rpos
   heap[pos]←heap[chp]
   ∇ chp
  }⍵
  heap[p]←⍺[⍵]
  heap siftdown ⍵ p
 }

heap←0 1 2 5 6 8 9
heappop heap

┌→────────────────┐
│ ┌→──────────┐   │
│ │1 5 2 9 6 8│ 0 │
│ └~──────────┘   │
└∊────────────────┘

heap heappush 3
┌→──────────────┐
│0 1 2 3 6 8 9 5│
└~──────────────┘


texts: “Space and Time Efficient” way of finding all anagram groups

texts:
I have written a program to find all anagram groups in a text file. I used first 26 Prime numbers as a mapper for 26 characters for finding anagram groups (Since character_set of all anagrams of a particular word are same, the products of the anagrams are also same ). After finding product of anagram I put (product, anagrams) pair into HashMap for retrieving later. But I think my solution of retrieving anagrams for particular character_set is not efficient although it is working. I need best practice for my case for iterating through HashMap. Here is the code:

public class Find_All_Anagrams_In_File {

// First 26 Primes for corresponding Alphabet letters
private static final int[] PRIMES = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
                                        61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113 };

private static long calcProduct(char[] letters) {
    long res = 1L;
    for (char c: letters) {
        if (c < 65) { // ASCII A = 65
            return -1L;
        }
        int index = c - 65;
        res = res * PRIMES[index];
    }
    return res;
}

public static Map<Long, StringBuffer>  findAllAnagrams(String[] file) {

    Map<String, Long> anagrams = new HashMap<String, Long>();
    Map<Long, StringBuffer> result = new HashMap<Long, StringBuffer>();

    for (String word: file) {
        long product = calcProduct( word.toUpperCase().toCharArray() );
        anagrams.put(word, product);
    }

    StringBuffer sb = new StringBuffer();

    for (String word: file) {
        long product = calcProduct( word.toUpperCase().toCharArray() );

        if (result.get(product) == null)
            result.put(product, sb.append("" + word));
        else
            result.put(product, sb.append(result.get(product) + "," + word));
        sb = new StringBuffer();
    }
    return result;
}

@SuppressWarnings({"rawtypes" })
public static void main(String[] args) {

    /*
     *  for,fro,rof
     *  tentak,takten
     *  aks,kas
     *  xew,wex,xwe
     *  marza,maraz
     *  nakra,karan
     *  simple,mislep
     *
     */
    String[] file = {"for", "fro", "aks", "ten", "xew", "kas",
                     "uvn", "marza", "take", "random", "tentak", "nakra",
                     "recursion", "basket", "simple", "karan", "rof", "bike",
                     "wex", "xwe", "takten", "mislep", "maraz", "kasal"};

    Map<Long, StringBuffer> result = findAllAnagrams(file);

    Iterator iter = result.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry pair = (Map.Entry) iter.next();
        String[] anagrams = pair.getValue().toString().split(",");
        if (anagrams.length > 1) {
            for (int i=0;i<anagrams.length; i++) {
                System.out.print(anagrams[i] + " ");
            }
            System.out.println();
        }

    }

  }
}

Result :
> nakra karan
> tentak takten
> xew wex xwe
> marza maraz
> for fro rof
> aks kas
> simple mislep


texts: Determine whether to push or update object in array based on unique ID

texts:
I am trying to write a basic function that will decide whether the object already exists in array of objects based on unique id that is inside this object as a property. Upon searching I came up with this code, and it seems to be doing the job fine, but I can imagine there is a better and faster way to determine whether to push or update the object. If you could share your best answer for this please...

var myArray = [
  {
    id: 1,
    car: "Ford"
  },
  {
    id: 2,
    car: "Honda"
  }
];

var objToOverwrite = {
  id: 1,
  car: "Bentley" // to overwrite car: "Ford"
};

var objToPush = {
  id: 3,
  car: "Toyota"
};

function pushToArray ( arr, obj ) {

  var existingIds = arr.map((obj) => obj.id);

    if (! existingIds.includes(obj.id)) {
      arr.push(obj);
    } else {
      arr.forEach((element, index) => {
        if (element.id === obj.id) {
          arr[index] = obj;
        };
      });
    };
};

pushToArray ( myArray, objToPush );

console.log(myArray);


texts: All permutations with known letter on one place

texts:
Following code is doing what I want but I am looking for a way how to make it nicer and more effective

for i in c:
  for j in c:
    for k in c:
        for l in c:
            for m in c:
             if (i != j and i != k and i != l and j != k and j != l and k != l and i != m and j != m and k != m and l !=m):
                print i + j + 'u' + k + l + m

odusdi
odusdt
odusit
odusti
oduids
oduidt
oduist
oduits
odutds
odutdi
odutsi
...

I tried filters, lambdas and generators but that makes everything just worse.

I am new to python so I also have problems with copying and sending python code any hint with comment would be nice.


texts: Breadth-First Search heuristics to find solution to Water Jug Challenge

texts:
I started learning AI recently. In AI, searches should be avoided and everything in AI is a search problem.

One of the easiest problem where we could use general AI search techniques is the water jug problem which states:

  You are given two jugs, a 4-gallon one and a 3-gallon one. Neither has any measuring markers on it. There is a tap that can be used to fill the jugs with water. How can you get exactly 2 gallons of water into the 4-gallon jug?

I solved it using the BFS technique:

#include <bits/stdc++.h>

using namespace std;

vector <pair<int,int> > newStatesSet(pair<int,int> state){
  //generating all possible states from a given initial state
  vector<pair<int,int> > newStates;
  if(state.first==0 && state.second==0){
    newStates.push_back(make_pair(3,0));
    newStates.push_back(make_pair(0,4));
    newStates.push_back(make_pair(3,4));
  }
  if(state.first!=0 && state.second==0){
    newStates.push_back(make_pair(state.first,4));
    newStates.push_back(make_pair(0,state.first));
    if(state.first<3){
      newStates.push_back(make_pair(3,0));
      newStates.push_back(make_pair(3,4));
    }
  }
  if(state.first==0 && state.second!=0){
    int transferQuantity;
    if(state.second>3)
      transferQuantity=3;
    else
      transferQuantity=state.second;
    newStates.push_back(make_pair(transferQuantity,state.second-transferQuantity));
    newStates.push_back(make_pair(3,state.second));
  }
  if(state.first!=0 && state.second!=0){
    newStates.push_back(make_pair(0,state.second));
    newStates.push_back(make_pair(state.first,0));
    if(state.second<4){
      int transferQuantity1=state.second+state.first;
      int transferQuantity2;
      if(transferQuantity1>4){
        transferQuantity2=transferQuantity1-4;
        transferQuantity1=4;
      }
      else
        transferQuantity2=0;
      newStates.push_back(make_pair(transferQuantity2,transferQuantity1));
    }
    if(state.first<3){
      int transferQuantity1=state.second+state.first;
      int transferQuantity2;
      if(transferQuantity1>3){
        transferQuantity2=transferQuantity1-3;
        transferQuantity1=3;
      }
      else
        transferQuantity2=0;
      newStates.push_back(make_pair(transferQuantity1,transferQuantity2));
    }
  }
  return newStates;
}

bool checkGoal(pair<int,int> x,int sum){
  if(x.second==sum)
    return true;
  return false;
}

void reverseTraversal(map <pair<int,int>,pair<int,int> > parent,pair<int,int> initialState,pair<int,int> goalState){
  if(initialState != goalState){
    reverseTraversal(parent,parent[initialState],goalState);
  }
  cout<<"("<<initialState.first<<","<<initialState.second<<")"<<endl;
}

int main()
{
  //capacity (3,4)
  //open list
  queue <pair<int,int> > Q;
  pair <int,int> parNode;
  //contains all the states
  map < pair<int,int> ,int > occured;
  //contains parent
  map < pair<int,int>,pair<int,int> > parent;

  Q.push(make_pair(0,0));
  while(Q.empty()!=true){
    parNode=Q.front();
    Q.pop();
    if(checkGoal(parNode,2))
      break;
    occured[parNode]++;
    vector <pair<int,int> > leafs = newStatesSet(parNode);
    for(int i=0;i<leafs.size();i++){
      if(occured[leafs[i]]==0){
        Q.push(leafs[i]);
        parent[leafs[i]]=parNode;
      }
    }
  }
  reverseTraversal(parent,parNode,make_pair(0,0));
}

What do you think is wrong with this code, and how can it be improved? What corner case have I overlooked, if any? How can I make it less complicated?

Improvements based on suggestion can be found here


texts: Storing statistics as JSON in a simulation game

texts:
I am working on a choice-based simulation and players have to choose between different locations, I am pushing those choices to an array locationLog and my MakeStats() function below builds an array from it. I tend to break code into bits because it helps me, but want to make sure others can understand it.

var hasAttorney = false;
var hasMoney = true;
var hasAC = true;
var currentlocation = "home";
var locationLog = []; //push locations

//Builds a JSON object with game stats
function MakeStats() {
    let home = 0,
        motel = 0,
        relative = 0,
        shelter = 0,
        apartment = 0;

    for (var i = 0; i < locationLog.length; i++) {
        if (locationLog[i] === "home")
            home++;
        else if (locationLog[i] === "motel")
            motel++;
        else if (locationLog[i] === "relative")
            relative++;
        else if (locationLog[i] === "shelter")
            shelter++;
        else if (locationLog[i] === "apartment")
            apartment++;
    }

    let tempJSON = {
        "location": {
            "home": home,
            "motel": motel,
            "relative": relative,
            "shelter": shelter,
            "apartment": apartment
        },
        "moneyLeft": money,
        "ACLeft": AC,
        "finalDestination": currentlocation,
        "hasAttorney": hasAttorney,
        "hasAC": hasAC,
        "hasMoney": hasMoney
    };
    statJSON = tempJSON;
    localStorage.setItem("playerStats", JSON.stringify(statJSON));
    console.log(statJSON);
}


texts:
Flambe is a really neat tool, even though developer dissapeared around march, and the proper camera access is missing (I could move to openFL, but I'm way too deep at the moment). This is my take at creating hybrid camera recorder (webcam for JS and frontal camera for AIR). Note that's early development, missing error handling, and lack of options such as different source coordinates and scaling.

package ps.component;

import flambe.Component;
import flambe.Entity;
import flambe.System;
import flambe.display.ImageSprite;
import flambe.display.Texture;

#if air
import flash.display.BitmapData;
import flash.media.Video;
import flash.media.Camera;
#end

#if js
import js.html.Element;
#end

class CameraAccess extends Component
{
    public var texture:Texture;
    public var sprite:ImageSprite;
    public var width:Int;
    public var height:Int;

    #if air
    private var canvas:BitmapData;
    private var video:Video;
    #end

    #if js
    private var captureStarted:Bool = false;
    private var ctx:Dynamic;
    private var canvas:Element;
    private var video:Element;
    #end

    public function new(?captureWidth:Int, ?captureHeight:Int)
    {
        width = captureWidth == null ? System.stage.width : captureWidth;
        height = captureHeight == null ? System.stage.height : captureHeight;
    }

    override public function onStart()
    {
        texture = flambe.System.renderer.createTexture(width, height);

        #if js
        (untyped navigator.webkitGetUserMedia({
            video: true
        }, function(stream) {
            video = document.createElement('video');
            video.src = URL.createObjectURL(stream);

            canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;

            ctx = canvas.getContext("2d");
            ctx.fillStyle = 'black';
            ctx.fillRect(0, 0, width, height);

            video.play();
            video.addEventListener('canplay', function() {
                captureStarted = true;
            }, false);
        }, function(err) {
            trace(err);
        }));
        #end

        #if air
        var camera = Camera.getCamera('1');
        camera.setMode(width, height, 30, true);

        video = new Video(width, height);
        video.attachCamera(camera);
        #end

        sprite = new ImageSprite(texture);
        owner.addChild(new Entity().add(sprite));
    }

    override public function onUpdate(dt:Float)
    {
        #if air
        canvas = new BitmapData(width, height);
        canvas.draw(video);
        #end

        #if js
        if (!captureStarted) return;

        ctx.drawImage(video, 0, 0, 640, 480, 0, 0, width, height);
        #end

        texture.graphics.drawTexture(System.renderer.createTextureFromImage(canvas), 0, 0);
    }
}


texts:
I've been designing UIChessboardView in the likeness of UITableView using protocols and delegates.

UIChessboardView.h

@interface UIChessboardView : UIView

@property (retain) id chessdelegate;

-(void) selectChesstileWithID:(NSInteger) tileID;
-(void) deselectChesstileWithID:(NSInteger) tileID;

@end

@protocol ChessboardViewDelegate <NSObject>

-(UIImage*) chessboardView:(UIChessboardView*)chessboardView imageForChesstile:(NSInteger) tileID;

-(void)chessboardView:(id)chessboardView mouseDown_chessTileWithID:(NSInteger)tileID;
-(void)chessboardView:(id)chessboardView mouseUp_chessTileWithID:(NSInteger)tileID;

@end

UIChessboardView.m

@implementation UIChessboardView
{
    NSDictionary* chessTileViews;
    NSArray *tileKeys;
}

-(id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        tileKeys = @[@"A1",@"A2",@"A3",@"A4",@"A5",@"A6",@"A7",@"A8",
                     @"B1",@"B2",@"B3",@"B4",@"B5",@"B6",@"B7",@"B8",
                     @"C1",@"C2",@"C3",@"C4",@"C5",@"C6",@"C7",@"C8",
                     @"D1",@"D2",@"D3",@"D4",@"D5",@"D6",@"D7",@"D8",
                     @"E1",@"E2",@"E3",@"E4",@"E5",@"E6",@"E7",@"E8",
                     @"F1",@"F2",@"F3",@"F4",@"F5",@"F6",@"F7",@"F8",
                     @"G1",@"G2",@"G3",@"G4",@"G5",@"G6",@"G7",@"G8",
                     @"H1",@"H2",@"H3",@"H4",@"H5",@"H6",@"H7",@"H8"];

        [self buildChessTileViews];
        [self createBackgroundWithImageNamed:@"darkwoodenback.png"];
    }
    return self;
}

-(void) buildChessTileViews
{
    NSMutableArray *tiles = [[NSMutableArray alloc] init];
    CGFloat tileHeight = self.frame.size.height/8;
    CGFloat tileWidth = self.frame.size.width/8;
    int index;
    BOOL darkBackround = false;
    for(int row = 0; row < 8; row++)
    {
        for(int column = 0; column < 8; column++)
        {
            index = (row*8)+column;
            UIView* tileView = [[UIView alloc] initWithFrame:CGRectMake((column*tileHeight), (row*tileWidth), tileWidth, tileHeight)];

            darkBackround = (column == 0) ? darkBackround : !darkBackround;
            [tileView setBackgroundColor:(darkBackround == true) ? [UIColor blackColor] : [UIColor lightGrayColor]];
            [tileView setTag:index];
            [tileView setBackgroundColor:[UIColor clearColor]];
            [self addSubview:tileView];
            [tiles addObject:tileView];
        }
    }

    chessTileViews = [[NSDictionary alloc] initWithObjects:tiles forKeys:tileKeys];
}

-(void) createBackgroundWithImageNamed:(NSString*) imageName
{
    UIImageView* image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    image.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);

    [self addSubview:image];
    [self sendSubviewToBack:image];
}

-(void) selectChesstileWithID:(NSInteger)tileID
{
    [[chessTileViews objectForKey:tileKeys[tileID]] setBackgroundColor:[UIColor redColor]];
}

-(void) deselectChesstileWithID:(NSInteger)tileID
{
    [[chessTileViews objectForKey:tileKeys[tileID]] setBackgroundColor:[UIColor clearColor]];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [[touches allObjects] firstObject];
    UIView* view = [touch view];

    [self.chessdelegate chessboardView:self mouseDown_chessTileWithID:[view tag]];
}

@end

I think this would be a good time to use Key-Value Observing to have the model directly update the UI? This is my first real project that I want to carry to completion and I'm not sure if this is a good approach to its design. I figure by trying to keep the API as primitive as possible it would make interfacing with other objects easier later on.

Also what should I be focusing on to keep the UI responsive? I've been reading about constraints and layouts from apple's documentation.


texts:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.

  #include <stdio.h>
  int main(){
    int i=0,j,k,l,sum=0;
    scanf("%d",&i);
    if(i<=100000&&i>0){
    for(j=0;j<i;j++){
        scanf("%d",&k);
        if(k<=1000000000&&k>0){
        for(l=3;l<k;l++){
            if(l%3==0||l%5==0)
                {sum+=l;}
        }}
    printf("%d\n",sum);
    sum=0;
    }}

The above code does satisfy all the test cases but it has been rejected citing that it is very slow. Please suggest improvements to the code.


texts:
I made a simple Universal-File-Duplicator (Example: make 125 duplicates of one file).
Very useful if you want to fill a whole USB flash drive or an old harddisk with an important file (Example: Bitcoin wallet.dat or privatekey) and you don't want to hit Ctrl+V all the time...

Suggestions? Improvements?

#include "stdafx.h"
#include "stdio.h"
#include <stdlib.h>
#include <strstream>
#include <string>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;

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

    char nummer[1000000], sourcefile[255], targetfile[255], targetfileneu[255], endung[255];
    int i = 0;
    int anzahl = 0;
    ifstream Quelldatei;

    printf("Welcome! You are using UNIVERSAL-DATEI-DUPLIKATOR v1.0\n");
    printf("Filename? (Example: test.txt)\n");
    gets(sourcefile);
    printf("New Filename without ending? (Example: filename)\n");
    gets(targetfile);
    printf("Ending? (Example: .txt)\n");
    gets(endung);

    printf("How many times do you want to create the file?\n");
    scanf("%d", &anzahl);

    for (i = 0; i < anzahl; i++)
    {
        sprintf(nummer, "%ld", i);
        strcpy(targetfileneu, targetfile);
        strcat(targetfileneu, nummer);
        strcat(targetfileneu, endung);
        printf("Targetfilename: %s\n", targetfileneu);

        Quelldatei.open(sourcefile, ios::binary);
        if (!Quelldatei)
        {
            cerr << "ERROR!\n";
            return 0;
        }
        ofstream Zieldatei(targetfileneu, ios::binary);
        if (!Zieldatei)
        {
            cerr << "ERROR!\n";
                    return 0;
        }
        else
        {
            int c;
        while ((c = Quelldatei.get()) >= 0) { Zieldatei.put(c); }
        }
        memset(&targetfileneu[0], 0, sizeof(targetfileneu));
        Quelldatei.close();
        Zieldatei.close();
    }
    printf("SUCCESS!\n");
    system("pause");
    return 0;
}


texts: Pig Latin translator with too many `push_str`s

texts:
I'm learning Rust and one of the challenges in the book was to build a pig latin translator.

  Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”).

I came up with the code below and I'm looking for ways to improve it, specifically reducing the push_strs and improving the starts_with_a_vowel method. How can the code be improved?

main.rs

extern crate unicode_segmentation;
use unicode_segmentation::UnicodeSegmentation;

fn main() {
    println!("{}", pig_latinify("String me".to_string()));
}

fn transform_word(word: &str) -> String {
    let mut new_word = String::new();
    new_word.push_str(&word[1..]);
    new_word.push_str(&word[..1]);
    if starts_with_a_vowel(word) {
        new_word.push_str("h");
    }
    new_word.push_str("ay");
    new_word
}

fn starts_with_a_vowel(word: &str) -> bool {
    let vowels = ["a", "e", "i", "o", "u"];
    for vowel in &vowels {
        if word.starts_with(vowel) {
            return true;
        }
    }
    false
}

fn pig_latinify(statement: String) -> String {

    let mut transformed_statement = String::new();
    if !statement.is_ascii() {
        panic!("statement must be ascii");
    }
    let iter = statement.split_word_bounds();
    for word in iter {
        if word.trim().len() > 0 {
            transformed_statement.push_str(&transform_word(word));
            transformed_statement.push_str(" ");
        }
    }
    transformed_statement.trim();
    transformed_statement
}

Cargo.toml

...
[dependencies]
unicode-segmentation = "1.2.0"


texts:
I've just written this Twisted resource base class for serving files. It's part of a larger application, this is just for serving its images, JavaScript files, etc.

Is it okay? I wonder if checking for .. in the path is enough -- all the files that exist in self.directory are intended to be served, to anyone, so this should be all that's needed, I think. Should these it be a Unicode string? Should they all be Unicode strings?

Will return open(file).read() be enough? I would think the resource would be closed when the function goes out of scope, but I'm not completely sure.

"""
Base class for resources serving files to the browser.

This doesn't use the `Page` class because it doesn't need to set up templates
or anything, just serve the file.
"""
from twisted.web.resource import Resource
import os.path

class File(Resource):
    """
    Serves a certain type of file from the server.

    It could be images, javascript, etc. It serves files from a single
    directory which have a single extension.

    members:
    content_type -- the HTTP content type of the files to be served
    directory -- the local directory the files are stored in
    extension -- the extension which the files are saved with.
    """
    content_type = None
    directory = None
    extension = None

    def render_GET(self, request):
        """
        Serve the requested file.

        Makes sure the file exists and the request doesn't contain '..'
        to escape the file directory.
        """
        file = request.path.strip("/")
        file = file.split("/", 1)[1]
        file = "{directory}/{filepath}.{extension}".format(
            directory=self.directory, filepath=file, extension=self.extension)

        request.responseHeaders.setRawHeaders("content-type", [self.content_type])

        if ".." in file:
            request.setResponseCode(400)
            return ""

        if not os.path.isfile(file):
            request.setResponseCode(404)
            return ""

        return open(file).read()


texts:
This is a challenge question from codeeval.com:

  Write a program which reads a file and prints to stdout the specified
  number of the longest lines that are sorted based on their length in
  descending order. Input sample:

  Your program should accept a path to a file as its first argument. The
  file contains multiple lines. The first line indicates the number of
  lines you should output, the other lines are of different length and
  are presented randomly. You may assume that the input file is
  formatted correctly and the number in the first line is a valid
  positive integer.

  For Example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

  Output sample:

  Print out the longest lines limited by specified number and sorted by
  their length in descending order.

  For example:

San Francisco
Hello World

I think my code is pretty readable.

lines = IO
  .readlines(ARGV.first)

puts lines
  .drop(1)
  .sort_by(&:length)
  .last(lines.first.to_i)
  .reverse


texts:
I'm using Struts2 and Google App Engine. Below is my program for getting the country based on the IP of the visitor of the website.

In my Struts2 action:

HttpServletRequest request = ServletActionContext.getRequest();
String IP = request.getRemoteAddr();
String countryCode = Utilities.fetchUrl( "http://api.hostip.info/country.php?ip=" + IP );
if ( countryCode != null){
    String country = CountryUtil.COUNTRY_MAP.get( countryCode );
    System.out.println("COUNTRY: " + country);
}

My fetchUrl static function:

public static String fetchUrl(String strUrl){
    String output = "";
    String line = null;
    try {

        URL url = new URL( strUrl );
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((line = reader.readLine()) != null) {
            output += line;
        }
        reader.close();

    } catch (MalformedURLException e) {
        System.out.println("ERROR CATCHED: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("ERROR CATCHED: " + e.getMessage());
        return null;
    }

    return output;
}

My COUNTRY_MAP:

public static final Map<String, String> COUNTRY_MAP;
static {
    Map<String, String> map = new HashMap<String, String>();
    map.put("AF", "afghanistan");
    map.put("AL", "albania");
    ...
    map.put("ZW", "zimbabwe");
    COUNTRY_MAP = Collections.unmodifiableMap( map );
}

Any suggestion on improving its speed?  I also need suggestions for the coding.


texts: Process N lists simultaneously by doing permutations

texts:
I'm trying to see if someone can come up with a better solution for this algorithm.

I have an input of three lists/queues and I have to group/sort the elements of xpn, tu, and efx — depending on the presence (or not) of UniqueKey. For instance, if UniqueKey exists, I have to try to form a list/tuple of xpn, tu, and efx (if they exists for that UniqueKey)...and so on.

This is the "main" class:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public final class Request {
  private Map<String, List<Tuple3<Node, Node, Node>>> result;

  private Queue<Node> xpn;

  private Queue<Node> tu;

  private Queue<Node> efx;

  public Map<String, List<Tuple3<Node, Node, Node>>> transform() {
    final int max = estimateSize();
    result = new LinkedHashMap<>(max / 3);
    for (int i = 0; i < max; i++) {
      pollFrom(xpn).ifPresent(it -> process(it, Category.XPN));
      pollFrom(tu).ifPresent(it -> process(it, Category.TU));
      pollFrom(efx).ifPresent(it -> process(it, Category.EFX));
    }
    return Collections.unmodifiableMap(result);
  }

  private int estimateSize() {
    final int[] sizes = { sizeOf(xpn), sizeOf(tu), sizeOf(efx) };
    int max = sizes[0];
    for (int i = 1; i < sizes.length; i++) {
      if (sizes[i] > max) { max = sizes[i]; }
    }
    return max;
  }

  private Optional<Node> pollFrom(final Queue<Node> collection) {
    return (null != collection) ? Optional.ofNullable(collection.poll()) : Optional.empty();
  }

  private void process(final Node thiz, final Category category) {
    if (result.containsKey(thiz.getUniqueKey())) {
      final List<Tuple3<Node, Node, Node>> values = result.get(thiz.getUniqueKey());
      final Optional<Tuple3<Node, Node, Node>> optional = values.stream()
        .filter(tuple3 -> emptyBucket.apply(tuple3, category))
        .findFirst();
      if (optional.isPresent()) {
        final Tuple3<Node, Node, Node> tuple3 = optional.get();
        if (Category.XPN == category) {
          tuple3.update1(thiz);
        } else if (Category.TU == category) {
          tuple3.update2(thiz);
        } else {
          tuple3.update3(thiz);
        }
      } else {
        result.get(thiz.getUniqueKey()).add(tupleFrom(thiz, category));
      }
    } else {
      final List<Tuple3<Node, Node, Node>> list = new LinkedList<>();
      list.add(tupleFrom(thiz, category));
      result.put((null != thiz.getUniqueKey()) ? thiz.getUniqueKey() : IdGen.uuid(), list);
    }
  }

  private BiFunction<Tuple3<Node, Node, Node>, Category, Boolean> emptyBucket = (tuple, category) -> {
    if (Category.XPN == category) {
      return null == tuple._1();
    } else if (Category.TU == category) {
      return null == tuple._2();
    } else { // EFX
      return null == tuple._3();
    }
  };

  private Tuple3<Node, Node, Node> tupleFrom(final Node thiz, final Category category) {
    final Tuple3<Node, Node, Node> empty = new Tuple3<>(null, null, null);
    switch (category) {
      case XPN:
        return empty.update1(thiz);
      case TU:
        return empty.update2(thiz);
      case EFX:
        return empty.update3(thiz);
    }
    return empty;
  }

  private int sizeOf(final Collection<Node> collection) {
    return (null != collection) ? collection.size() : 0;
  }

  private enum Category {
    XPN, // 1st element in tuple
    TU,  // 2nd element in tuple
    EFX  // 3rd element in tuple
  }
}

The content of Node and Tuple3 are irrelevant, but I can post it if that may help. I'm just trying to see if there is a better way of doing this. The reason you don't see a constructor is because that class is being constructed/deserialized via Jackson. I would really like to avoid having result at class level.

PS: Don't mind about the method/variable names.


texts: Show all records when current user is admin

texts:
I have the following. How best to refactor it:

  def self.search(search, organization_id, is_admin)
    if is_admin == false
      where("record_no LIKE ?", "%#{search}%").
        where("organization_id = ?", organization_id)
    else
      where("record_no LIKE ?", "%#{search}%")
    end
  end

Basically this means, I want it to show all records without the organization_id when user is an admin.


texts: Finding the second highest version using bash array script and clean up files

texts:
The goal is to print the highest version and second highest version of the list of files. The version is based on the first three digit places of the version. For example, version 2.3.0.1 version is just 2.3.0 (ignoring the last digit).

Once it can print the highest version and the second highest version of the list, it should remove all other versions which will essentially clean up the folders in that location by only keeping the current and last version.

The EXAMPLE folders that I created are:

AAA_6.6.4.12.TEST
AAA_7.6.4.12.TEST
AAA_75.6.4.12.TEST
AAA_75.7.4.12.TEST
CCC_81.0.0.0.TEST
CCC_81.2.0.0.TEST
CCC_81.2.3.0.TEST
DDD_1.0.0.0.TEST
DDD_1.0.0.1.TEST
DDD_1.0.0.6.TEST
DDD_1.1.0.0.TEST
DDD_2.0.0.0.TEST
DDD_2.0.0.1.TEST
DDD_2.0.0.3.TEST
DDD_3.0.0.0.TEST

This is the array that I have to compute the highest and second highest version:

new_var=( $(for arr in "${var[@]}"
do
    echo $arr
done | sort) )

for folder in *
do
    if [[ $folder =~ ([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.[0-9]{1,3} ]]
    then
        if [[ "$new_var" < "${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.${BASH_REMATCH[3]}" ]]
        then
            new_var="${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.${BASH_REMATCH[3]}"
        fi
    else
        echo "failed"
    fi

done;

echo "The highest version is: $new_var"
echo "The second highest version is: ${new_var[-2]}"

This prints the highest version correctly. However, I don't know how to get the second highest version and I don't know how to go about removing the rest of the versions from the directory.


texts:
Lets preface this by saying that when it comes to javascript, I am a hack. I make what I need happen by cobbling together crappy, inefficient, redundant code. I want to get better.
Recently I was asked if I could make a set of elements on a page sort-able by price, A-Z and Z-A. The code on the page looks something like the below:

<select id="sorting" onchange="selectionChange()">
      <option value="Sort By">Sort Products</option>
      <option value="Sort By Price" id="price">Sort By Price</option>
      <option value="Sort By A-Z" id="az">Sort By A-Z</option>
      <option value="Sort By Z-A" id="az">Sort By Z-A</option>
</select>

                 text link

$item price

                 text link

$item price

I was able to make things work by assigning a sort class to the text link and the price "p" tag, listen for onchange from the dropdown and when it fired either the price or the name of the item was assigned as an attribute to the containing product wrapper, then the wrappers are sorted using a simple sort function. My working but embarrassing attempt is below.

jQuery(document).ready(function( $ ) {
sortPrice = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sortprice").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');
        var numberA = Number(an.replace(/[^0-9\.]+/g,""));
        var numberB = Number(bn.replace(/[^0-9\.]+/g,""));
        an = numberA;
        bn = numberB;

        if(an > bn) {
        return 1;
    }
    if(an < bn) {
        return -1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};

sortA = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sort1").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');

        if(an > bn) {
        return 1;
    }
    if(an < bn) {
        return -1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};

sortZ = function(){
$('.product-wrapper').each(function(){
    var data1 = $(this).find(".sort1").text();
    $(this).attr('data-name', data1);

});

var $products = $('.products'),
    $singleProduct = $('.product-wrapper');

$singleProduct.sort(function(a,b){
        var an = a.getAttribute('data-name');
        var bn = b.getAttribute('data-name');

        if(an > bn) {
        return -1;
    }
    if(an < bn) {
        return 1;
    }
    return 0;
});

$singleProduct.detach().appendTo($products);

};
selectionChange = function(){
var selectResult = $("#sorting").val();

if(selectResult == "Sort By Price"){
    sortPrice();

} else if(selectResult == "Sort By A-Z"){
    sortA();

} else if(selectResult == "Sort By Z-A"){
    sortZ();

}
};
});

I would be eternally indebted to whoever will show me what an elegant version would look like and maybe how and where I would add error handling.


texts:
I am creating a simple template engine that uses Regex to find special expressions, which are parsed and processed. They are enclosed in Ruby-style opening tags and have the format:

    <% label %>  OR:
    <% function(arg1, arg2, arg3) %>

However the problem is that I cannot have multiple entries on the same line, so I can't have this:

<% name %> - <% age %> - <% gender %>

Instead I have to write it like this:

<% name %> -
       <% age %> -
       <% gender %>

How can I fix this? Below I included the code for the function that handles this. Basically what it does is read from a file, split everything line by line, then iterate through each line and do a regex match and return the results.

public function content()
{
    if (!file_exists($this->path))
        return;

    /* 0 = before, 1 = entry #1, 2 = entry #2, 3 = after */
    $content = file_get_contents($this->path);
    $pattern = '/^(.*)\<\%\s*(.+)\s*\%\>(.*)$/';
    $lines = explode("\n", $content);

    foreach ($lines as $line)
    {
        // Pattern match the line
        preg_match($pattern, $line, $matches);

        $result = '';

        // If there are no matches, then don't parse it and add the raw string to output
        if (count($matches) == 0)
        {
            continue;
        }

        // Parse the matches and run the appropriate action
        $before = $matches[1];
        $after = $matches[3];
        $entry = $matches[2];
        $return = '';

        // Process the entry
        $return = $this->processEntry($entry);

        // Add the processed line to the final result if not empty
        $result = $before . $return . $after;
        if (!empty($result)) $final .= $result . "\n";
    }
    return $final;
}


texts:
This code works alright, but it's very difficult to get the dimensions right and takes a bunch of trial and error. I'm wondering how I could improve it. It's meant to cut up board game pieces from a single sheet to then be used for Vassal modules.

It takes a counter sheet (I'll provide a link with an example) and cuts out / exports the individual pieces to be used by another program, which requires each piece to have its own image.

This is an example of a typical countersheet:

############################################
#
#
#       WARGAME COUNTER-CUTTER
#       Programmed by Ray Weiss
#       lerugray@gmail.com
#
#
############################################

#  imports

import os
from PIL import Image
from sys import argv

save_dir = "results"
filename = argv[1]  # Your counter sheet
img = Image.open(filename)

if not os.path.exists(save_dir):
    os.makedirs(save_dir)

coord_input = input("Enter coordinates of first cell x, y: ")
start_pos = start_x, start_y = [int(x) for x in coord_input.split(",")]

counter_input = input("Enter the size of the counters x, y: ")
counter_size = w, h = [int(x) for x in counter_input.split(",")]

major_columns = int(input("Number of Pages: "))
major_columns_w = int(input("Width between cell to cell on the next page: "))
major_rows = int(input("Number of blocks per page: "))
major_rows_h = int(input("height between cell to cell on the next block: "))
columns = int(input("Number of columns inside a block: "))
rows = int(input("Number of rows inside a block: "))

###################################
#
#  End of user supplied arguments
#  Start of program
#
###################################

frame_num = 1

w, h = counter_size

for col_m in range(major_columns):
    for row_m in range(major_rows):
        for row in range(rows):
            for col in range(columns):
                x = w * col + start_x + major_columns_w * col_m
                y = h * row + start_y + major_rows_h * row_m
                crop = img.crop((x, y, x + w, y + h))
                save_at_template = os.path.join(save_dir, "counter_{:03}.png")
                crop.save(save_at_template.format(frame_num))
                frame_num += 1


texts: Calculate all anagrams of a word with Perl

texts:
In order to become more familiar with Perl I have implemented a code kata from here.

The task was to write a program which prints out all anagrams for a given word. I'd appreciate your review of my solution:

get_anagrams.pl

use strict;
use warnings;

require 'anagrams.pm';

use feature 'say';

my $number_of_arguments = $#ARGV + 1;
if ($number_of_arguments != 1) {
    say 'Usage: get_anagrams.pl word';
    exit 1;
}

foreach my $word (get_permutations($ARGV[0])) {
    say $word;
}

anagrams.pm

use strict;
use warnings;

sub get_permutations
{
    my $string = shift;

    my @permutations = ();
    my @letters = split //, $string;
    my $number_of_letters = scalar(@letters);

    if ( $number_of_letters == 1 ) {
        push @permutations, $letters[0];
    }
    elsif ( $number_of_letters == 2 ) {
        push @permutations, $letters[0] . $letters[1];
        push @permutations, $letters[1] . $letters[0];
    }
    elsif ( $number_of_letters > 2 ) {
        for ( my $i = 0 ; $i < $number_of_letters ; $i++ ) {
            my $first_letter_in_word = $letters[$i];
            my $other_letters = remove_letter_by_index($string, $i);
            foreach my $sub_permutation ( get_permutations($other_letters) ) {
                push @permutations, $first_letter_in_word . $sub_permutation;
            }
        }
    }

    return @permutations;
}

sub remove_letter_by_index
{
    my ( $string, $index ) = @_;
    my $result = '';

    my @letters = split //, $string;
    my $number_of_letters = scalar(@letters);

    for ( my $i = 0 ; $i < $number_of_letters ; $i++ ) {
        if ( $i != $index ) {
            $result = $result . $letters[$i];
        }
    }
    return $result;
}

sub is_element_in_list
{
    my ( $element, @list ) = @_;

    if ( not $element ) {
        return 0;
    }

    foreach my $item (@list) {
        if ( $item eq $element ) {
            return 1;
        }
    }
    return 0;
}

return 1;

anagrams.t

use strict;
use warnings;

require "anagrams.pm";

use feature 'say';

use Test::More tests => 20;

my $sample_string = 'a';
my @retrieved_permutations = get_permutations($sample_string);
ok(is_element_in_list('a', @retrieved_permutations));
ok(scalar(@retrieved_permutations) == 1);

$sample_string = 'ab';
@retrieved_permutations = get_permutations($sample_string);
ok(is_element_in_list('ab', @retrieved_permutations));
ok(is_element_in_list('ba', @retrieved_permutations));
ok(scalar(@retrieved_permutations) == 2);

$sample_string = 'abc';
@retrieved_permutations = get_permutations($sample_string);
ok(is_element_in_list('abc', @retrieved_permutations));
ok(is_element_in_list('acb', @retrieved_permutations));
ok(is_element_in_list('bac', @retrieved_permutations));
ok(is_element_in_list('bca', @retrieved_permutations));
ok(is_element_in_list('cab', @retrieved_permutations));
ok(is_element_in_list('cba', @retrieved_permutations));
ok(scalar(@retrieved_permutations) == 6);

$sample_string = 'abcd';
@retrieved_permutations = get_permutations($sample_string);
ok(is_element_in_list('abcd', @retrieved_permutations));
ok(is_element_in_list('acbd', @retrieved_permutations));
ok(is_element_in_list('dbac', @retrieved_permutations));
ok(scalar(@retrieved_permutations) == 24);

$sample_string = 'abcdefg';
@retrieved_permutations = get_permutations($sample_string);
ok(is_element_in_list('abcdefg', @retrieved_permutations));
ok(is_element_in_list('abcedfg', @retrieved_permutations));
ok(is_element_in_list('acbdefg', @retrieved_permutations));
ok(scalar(@retrieved_permutations) == 5040);


texts: Spotfire: Creating filtering relationships by passing filters between tables

texts:
I am using the code below to pass filter selections from table A to table B in Spotfire. I am doing this to create a filtering relationship between the tables, but skipping the creation of a traditional Spotfire table relationship, as this is not advisable in this setting.

The code is associated with a document property which itself is driven by a simple data function, following the instructions found here.

After it is triggered, the code finds a specific filter in table A. It reads the content and creates a list. It checks the length of the list, and if greater than zero, it takes the filter object and passes it to the matching filter in table B. If nothing is selected (len = 0), then the matching filter in table B is reset. The process is repeated for multiple filters.

As far as I can tell it works on my machine. But even as a complete beginner, I can tell it is poorly written. I would appreciate suggestions and feedback on how I can make it better.

from Spotfire.Dxp.Application.Filters import *
from Spotfire.Dxp.Application.Visuals import VisualContent
from System import Guid

#Get the active page and filterPanel
page = Application.Document.ActivePageReference
filterPanel = page.FilterPanel

##########################reasons#############################################
#get information for the first filter
theFilter = filterPanel.TableGroups[0].GetFilter("Reason")
lbFilter = theFilter.FilterReference.As[ListBoxFilter]()
#get information for the second filter
theFilter2 = filterPanel.TableGroups[1].GetFilter("Reason")
lb2Filter = theFilter2.FilterReference.As[ListBoxFilter]()

#check if any selections are made in the first filter
n = []
for value in lbFilter.SelectedValues:
    n.append(value)
if len(n)>0:
    lb2Filter.IncludeAllValues = False
    lb2Filter.SetSelection(lbFilter.SelectedValues)
#if no selections are made, reset the second filter
else:
    lb2Filter.Reset()

#########################Type#####################################################
theFilterPT = filterPanel.TableGroups[0].GetFilter("Type")
lbFilterPT = theFilterPT.FilterReference.As[ListBoxFilter]()

theFilter2PT = filterPanel.TableGroups[1].GetFilter("Type")
lb2FilterPT = theFilter2PT.FilterReference.As[ListBoxFilter]()

n = []
for value in lbFilterPT.SelectedValues:
    n.append(value)
if len(n)>0:
    lb2FilterPT.IncludeAllValues = False
    lb2FilterPT.SetSelection(lbFilterPT.SelectedValues)
else:
    lb2FilterPT.Reset()


texts:
public abstract class Element
{
    // Removed for verbosity ...

    protected abstract byte[] GetBytes();
}

I'm attempting to create an engine that can create a document in a very specific format. The document itself is composed of various elements, and each element has a very specific binary representation.

I originally thought that perhaps I should have an abstract method that returns a byte[] of the byte data will be written to a stream (file, memory, whatever). For example, one element would be formatted as so:

public sealed class ElementX : Element
{
    // Removed for verbosity ...

    public override byte[] GetBytes()
    {
        var nl      = Encoding.GetBytes("\r\n");
        var opening = Encoding.GetBytes("begin-elem-x");
        var closing = Encoding.GetBytes("end-elem-x");

        var data   = Encoding.GetBytes(Data);
        var result = Encoding.GetBytes(Result);

        return Util.BlockCopy(new[] { opening, nl, data, nl, closing, nl, result });
    }
}

The problem is that it just doesn't feel right to have a method that is meant for serialization. I thought about creating a custom serializer, but since each element is serialized in a very specific format (too much variation from element to element), I think that each element needs to own the code that allows it to determine the binary representation of itself; I don't know if a class exclusively for serialization of this format will work, as it would simply consist of a large if-else/switch branch and it would force me to expose private members as internal/protected/public so that this serializer could properly serialize the element.

I'm also not sure if there are any interfaces that specifically deal with this that are part of the Portable Class Libraries (ISerializable is not).

Additionally, I know there is a Code Analysis rule stating not to return a byte[] as a public property getter (CA1819: Properties should not return arrays). I don't think this necessarily applies to methods though.

I was thinking about using ImmutableArray from the Immutable Collections NuGet instead of byte[]. This seems to make sense because the value returned is immutable at the time; the value returned will only be different if a property value on the class is changed.


texts: File input control with rounded buttons and styled textbox

texts:
We have orange rounded buttons as a standard on our site. For our purposes, we switched everything over to use an anchor tag, instead of input type=button. The exception to this was the File Upload Control. For security reasons, you can't write your own, and since buttons in IE can't be rounded with pure CSS, I decided to use a combination of other people's solutions. I set the Opacity to 0, for the real File Input, and the z-index to 999. For the fake anchor and textbox, which are styled properly, I moved them to the same space that the File Input takes up, but they're underneath it in the layers. So, the File Input doesn't show up, but when people think they're clicking the anchor tag, they're really getting the File Input.

I've tested this in the browsers that we require support for, and it's definitely functional and looks good. I'm curious as to whether this has any glaring holes that I've missed.

    <input type="file" name="file" id="file" class="hide-file-input" />
    <input type="text" id="file-fake" class="k-textbox fileinput-textbox" />
    Browse

Here is the associated script:

And finally, here is the relevant CSS for positioning and hiding these elements:

input.fileinput-textbox {
    float: left;
    position: absolute;
    width: 158px !important;
    left: 117px;
    display: inline-block;
}

.file-button-wrapper {
    float: left;
    background-color: #ffffff;
    position:absolute;
    margin: 0;
    padding: 5px;
    width: 70px;
    height: 20px;
    left: 273px;
    display: inline-block;
}

.hide-file-input {
    opacity: 0;
    filter: alpha(opacity = 0);
    -ms-filter: "alpha(opacity=0)";
    z-index: 999;
    line-height: 0;
    position: relative;
    overflow:hidden;
    width: 240px;
}

The only drawback I've found is that the script only shows the file name, not the path, like the real File Input would. This isn't a problem for our business unit, though, so I haven't even checked to see if I could show the full path. (I think it's a benefit, personally). Other solutions seem to want to throw the File Input off the screen altogether, but I couldn't see a reason not to do it this way.


texts:
Here is my attempt at a floaty Bar module, used in a mobile application. There are several "bars", which stick to the top of the browser window once they are passed. When the next bar is reached, it takes over that sticky position...
Based on: http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-css.html

CMBi.floatyBar = (function(){
    var dayGroups = [];

    function getPositions() {
        var that = this;
        $.each( $('.day-group'), function(i, day) {
            if ($(this).length >= 1) {
                // Add the initial starting Y position to the object
                this.initialYPosition = $(this).offset().top;
                that.dayGroups[i] = this;
            }
        });
    }

    function setPositionsOnScroll() {
        var _daygroups = dayGroups, that = this;

        if ( window.scrollY < _daygroups[0].initialYPosition) {
            this.restoreInitialPosition(_daygroups[0]);
        }

        for ( var i = 0; i < _daygroups.length; i++ ) {
            // Get the next floaty bar position
            var _nextYposition = _daygroups[i+1] ? _daygroups[i+1].initialYPosition : config.vars.docHeight;
            // Between two bars, or betweem the last bar and the end of the doc
            if ( window.scrollY > _daygroups[i].initialYPosition && window.scrollY < _nextYposition) {
                // Stick the bar to the top
                that.setTop(_daygroups[i]);
                // Restore initial positions of the other bars
                $.each(_daygroups, function(index, day) {
                    if (index !== i) {
                        that.restoreInitialPosition(day);
                    }
                });
            }
        }
    }

    function setTop(element) { // Called when it's time for the floaty bar to move
        var _yPos = window.scrollY - element.initialYPosition;
        element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)';
    }

    function restoreInitialPosition(element) { // Called when the floaty bar is dismissed
        var _yPos = 0;
        element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)';
    }

    return {
        init : getPositions,
        setPositions : setPositionsOnScroll
    };

}());


texts: Two java classes with different annotation values only

texts:
Consider two classes:

First

@Path("/first/{param}") // 1st line
public class First {

    @GET
    @Path("/{data}/difference") // 5th line
    public Response doStuff(
            @Context HttpServletRequest request,
            @Context UriInfo uri,
            @Context HttpHeaders httpHeaders,
            @PathParam("param") String param,
            @PathParam("data") String data
    ) {

        // whatever
        return new Response();

    }

}

Second

@Path("/second/{param}") // 1st line
public class Second extends First {

    @GET
    @Path("/{data}") // 5th line
    public Response doStuff(
            @Context HttpServletRequest request,
            @Context UriInfo uri,
            @Context HttpHeaders httpHeaders,
            @PathParam("param") String param,
            @PathParam("data") String data
    ) {

        return super.doStuff(
            request,
            uri,
            httpHeaders,
            param,
            data
        );

    }

}

The only differences between this two block of code are:

@Path() annotation value in the 1st line of both of them
@Path() annotation value in the 5th line of both of them

How can I remove all the redundant code from it?


texts:
Maze puzzle

  A 1 in input matrix means "allowed"; 0 means "blocked". Given such a matrix, find the route from the 1st quadrant to the last (n-1, n-1).

I would like to get some feedback to optimize and make this code cleaner. Also let me know if O(n!) is the complexity, where n is the dimension of the maze.

final class Coordinate {
    private final int x;
    private final int y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

public class Maze {

    private final int[][] maze;

    public Maze(int[][] maze) {
        if (maze == null) {
            throw new NullPointerException("The input maze cannot be null");
        }
        if (maze.length == 0) {
            throw new IllegalArgumentException("The size of maze should be greater than 0");
        }

        this.maze = maze;
    }

    public List<Coordinate> solve() {
        return getMazePath(0, 0, new Stack<Coordinate>());
    }

    private List<Coordinate> getMazePath(int row, int col, Stack<Coordinate> stack) {
        assert stack != null;

        stack.add(new Coordinate(row, col));

        if ((row == maze.length - 1) && (col == maze[0].length - 1)) {
            Coordinate[] coordinateArray = stack.toArray(new Coordinate[stack.size()]);
            return Arrays.asList(coordinateArray);
        }

        for (int j = col; j < maze[row].length; j++) {

            if ((j + 1) < maze[row].length && maze[row][j + 1] == 1) {
                return getMazePath(row, j + 1, stack);
            }

            if ((row + 1) < maze.length && maze[row + 1][col] == 1) {
                return getMazePath(row + 1, col, stack);
            }
        }

        return Collections.emptyList();
    }

    public static void main(String[] args) {
        int[][] m = {  {1, 0, 0},
                       {1, 1, 0},
                       {0, 1, 1} };

        Maze maze = new Maze(m);

        for (Coordinate coord :  maze.solve()) {
            System.out.println(coord.getX() + " : " + coord.getY());
        }
    }
}


texts: Immutable pure data classes with public setters on properties

texts:
I'm putting together some classes as a model for some information (that I'm currently pulling from a website).

The classes are implemented in C# - because in the current version of F# there are no autoimplemented properties. The logic to fill these classes from the website is going to be writen in F#. (Because I like F#, and it works nice for webscraping.)

So since I'm working functionally (I seems to always work functionally there days even in C#).
I don't want these objects to be mutable. Setting mutable fields is ugly in F# (and for good reason, mutable objects are evil).

So all there data fields have only private setters but this makes my constructors long.
I planned to be using named arguments in them anyway, but still 5 arguments is a lot.
And I don't think F# supports object property initialisers anyway.

public class PopularitySplitClassOptionSet : IClassOptionsSet
{
    public PopularitySplitClassOptionSet (string description, IEnumerable<ClassOption> popularClasses, IEnumerable<ClassOption> unpopularClasses, int reqPreferences, int minUnpopularPreferences)
    {
        PopularClasses  = popularClasses;
        UnpopularClasses = unpopularClasses;
        RequiredPrefereces = reqPreferences;
        MinUnpopularPrefereces = minUnpopularPreferences;
    }

    public IEnumerable<ClassOption> Classes
    {
        get
        {
            return PopularClasses.Concat(UnpopularClasses);
        }
    }

    public int RequiredPrefereces { get; private set; }
    public int MinUnpopularPrefereces { get; private set; }

    public int MaxPopularPrefereces {
        get
        {
            return RequiredPrefereces - MinUnpopularPrefereces;
        }
    }

    public  IEnumerable<ClassOption> PopularClasses { get; private set; }
    public  IEnumerable<ClassOption> UnpopularClasses { get; private set; }

}

Edit: Is this good practice? Am I thinking this right?

Also: I wonder if:

public readonly int RequiredPrefereces { get; private set; }

would be better? Or is that not actually a thing you can do?

Related questions:

C#, immutability and public readonly fields
How to avoid “too many parameters” problem in API design?


texts:
This is some code which prints a hexdump of a list of 16 bit numbers, at 16 bytes distance for each, after the "print data" comment:

#!/usr/bin/python3

# creating test data
data = []
for i in range(500):
    data = data + [ i & 0xff, i >> 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

# print data
c = 0
out = ""
for i in range(int(len(data) / 16)):
    if i == 512: break
    low = data[i * 16]
    high = data[i * 16 + 1]
    d = low | (high << 8)
    out = out + ("%04x " % d)
    if (i % 16) == 15: out = out + "\n"
print(out)

It works, but I think I can write it simpler with "join" and maybe list comprehension? But shouldn't be a cryptic one-liner or something, I'm just looking for a more idiomatic Python solution. I want to print the first 512 numbers, but the data array can be shorter or longer.


texts:
I have written a todo list app. I want to understand how to improve it.

Here's what I'm trying to understand:

My problem is when user clicks on task to edit, because it passed by reference, so if user edit task, it will change directly the task object.
(see the code below).

My questions:

In my code I wrote one way to fix the above mentioned problem by cloning the object every time.
Is it a good practice ? If no, how do you recommend me to fix it?
I do not want my code to just work, I want it be efficient and improve my skills.
Can you please suggest any areas of improvement to the code?

Link to plunker: https://plnkr.co/edit/CA99iiydbD4TWaGtJZZf?p=preview

(function() {
    var Task = (function() {
        var counter = 0;
        return function(content, isDone) {
            this.id = counter++;
            this.content = content;
            this.isDone = isDone || false;
        }
    }());
    var app = angular.module('todos',[])
    .service('todosBL', function() {
        this.tasks = [];
        this.add = function(content) {
            this.tasks.push(new Task(content));
        }

        this.update = function(editedTask) {
            var i = this.tasks.findIndex(function(task){
                return task.id === editedTask.id
            });
            this.tasks[i] = editedTask;
        }

    })
    .controller('main', function($scope, todosBL) {
        $scope.todosBL = todosBL;
        $scope.add = function(task) {
            todosBL.add(task);
            $scope.task = null;
        }
        $scope.editMode = {
            task: {},
            edit: function(task) {
                this.task = task;
                //BECAUSE I PASS TASK BY REFERNCE WHEN USER EDIT TASK IT CHANGE TASK DIRECTLY ,
                // IF I CLONE OBJECT EVERY TIME, IT FIX BY REFERENCE PROBLEM.
                // MY QUESTION IF HAVE OTHER WAY TO SLOVE THIS. MABY OTHER WAY TO THINK ABOUT APP LIKE THIS.
                // for(key in task) {
                //     this.task[key] = task[key];
                // }
            },
            save: function(task) {
                todosBL.update(task);
                this.task = {};
            }
        };
    });
}());

{{ task.content}}

        <input type="text" ng-model="task">
        <input type="button" value="add task" ng-click="add(task)">

            <input type="text" ng-model="editMode.task.content">
            <input type="button" value="save task" ng-click="editMode.save(editMode.task)">


texts: Error handling techniques for nested methods that can throw exceptions

texts:
I have 2 different approaches I'm using to handle error state or Exceptions from within nested functions.  Take the following code for example:

public void Func1()
{
    try
    {
        Func2();
        //... continued logic if no exception was encountered
    }
    catch (Exception ex)
    {
        log(ex.Message);
        return;
    }

}

public void Func2()
{
    try
    {
        Func3();
    }
    catch (Exception ex)
    {
        log(ex.Message);
        throw;
    }
}

In the above sample, Func1 needs to know if Func2 (and other methods Func2 calls) have thrown an exception, so that it can continue with execution.  This appears to me to be an obvious code-smell and it's something I'd like to avoid doing.  Here's the next option I've tried:

public void Func1()
{
    try
    {
        bool success = Func2();
        if (!success)
        {
            //... continued logic if no exception was encountered
        }
    }
    catch (Exception ex)
    {
        log(ex.Message);
        return;
    }
}

public bool Func2()
{
    try
    {
        bool success = Func3();
        if (!success) return false;
        return true;
    }
    catch (Exception ex)
    {
        log(ex.Message);
        return false;
    }
}

Using this second method, the nested functions return a boolean to determine state and whether or not the calling function should continue.  This also doesn't feel right to me.  I'd really like suggestions on ways to handle situations like this where I'm calling nested functions (particularly when they return void because they do unrelated processing to the class).  Thanks!

EDIT: updated from pseudo-code to valid C#.


texts: Apply a function to each element of a tuple ("map" a tuple)

texts:
C++ doesn't (yet) have a 'map' higher-order function, certainly not one which applies to a compile-time sequence of values like a tuple. We have std::transform, and there's an equivalent of it for tuples listed on SO, but that's iterator-based, and anyway - I don't want to use any reference to the output. I want to pass a tuple and a function / variadic lambda, and get another tuple of the same length with the function applied to each element.

I'm also sure this has been implemented multiple times, but since I want to build up some "tuple confidence", I've done it myself. Here's what I got:

namespace detail {

template <class F, typename Tuple, size_t... Is>
auto transform_each_impl(Tuple t, F f, std::index_sequence<Is...>) {
    return std::make_tuple(
        f(std::get<Is>(t) )...
    );
}

} // namespace detail

template <class F, typename... Args>
auto transform_each(const std::tuple<Args...>& t, F f) {
    return detail::transform_each_impl(
        t, f, std::make_index_sequence<sizeof...(Args)>{});
}

And this works in the cases I've tried - I haven't tested extensively.

I'd like general feedback/suggestions, but also:

When is the function resolved or instantiated in the case of different-type arguments? In what cases will it be the same (instantiated) function with forced conversion, as opposed to different instantiations for the different types? Am I really getting the latter at all?
Is there any std::forward'ing that I need to do?
Can I avoid a helper function somehow?
What do you think about the name?


texts:
I have a couple of jQuery animations running in a sequence after certain resources are loaded:

$(".loading").delay(2600).fadeOut({
    useTranslate3d: true,
});

$(".zip").delay(1900).slideDown({
    useTranslate3d: true,
});

$("#zip").delay(2800).slideDown({
    useTranslate3d: true,
});

Is there a better way to combine all of these animations? It feels superfluous having to write them all out like this...


texts:
I've decided to start working on a budget application for the purposes of enhancing my Python skills. In its current form this program takes given expenses and income and tells the user whether they have a surplus, a deficit, or if they are breaking even. I will add more functionality to this program as I move along in the development process.

import os
import sys

class Application():
    def __init__(self):
        self.income = 0
        self.expenses = 0
        self.expense_list = []
        self.expense_name = []
        self.income_name = []
        self.income_list = []
        self.prompt_income()

    def income_ask(self):
        add_income = input('Add income? [y/n]: ')
        return add_income

    def income_sum(self):
        self.income = sum(self.income_list)

    def expense_ask(self):
        add_expense = input('Add expense? [y/n]: ')
        return add_expense

    def expense_sum(self):
        self.expenses = sum(self.expense_list)

    def income_check(self):
        if not self.income_list:
            print('Please enter atleast one source of income. ')
            self.prompt_income()
        else:
            return

    def expense_check(self):
        if not self.expense_list:
            print('Please enter atleast one expense. ')
            self.prompt_expense()
        else:
            return

    def prompt_income(self):
        x = False
        while not x:
            result = self.income_ask()
            if result == 'y':
                income_input = int(input('Enter source of income. [Numbers Only]: '))
                self.income_list.append(income_input)
                income_name = input('Enter income name. [Name Only]: ')
                self.income_name.append(income_name)
            else:
                self.income_check()
                x = True
        self.income_sum()
        name = [name for name in self.income_name]
        income = [income for income in self.income_list]
        incomedict = dict(zip(name, income))
        for k in incomedict:
            print(k + ': ', '$' + str(incomedict[k]))
        print('Total user income: ', '$' + str(self.income))
        self.prompt_expense()

    def prompt_expense(self):
        x = False
        while not x:
            result = self.expense_ask()
            if result == 'y':
                expense_input = int(input('Enter expense amount. [Numbers Only]: '))
                self.expense_list.append(expense_input)
                expense_name = input('Enter expense name. [Name Only]: ')
                self.expense_name.append(expense_name)
            else:
                self.expense_check()
                x = True
        self.expense_sum()
        name = [name for name in self.expense_name]
        expense = [income for income in self.expense_list]
        expensedict = dict(zip(name, expense))
        for k in expensedict:
            print(k + ': ', '$' + str(expensedict[k]))
        print('Total user expenses: ', '$' + str(self.expenses))
        self.uservalue()

    def uservalue(self):
        valoutput = self.income - self.expenses
        if valoutput < 0:
            print('You are in the negative, you have a deficit of ' + '$' + str(valoutput))
        if valoutput == 0:
            print('You have broken even, you are spending exactly as much as you make.')
        if valoutput > 0:
            print('You are in the positive, you have a surplus of ' + '$' + str(valoutput))
        another = input('Would you like to run another analysis? [y/n]: ')
        if another == 'y':
            self.reset_program()
        else:
            self.close_program()

    def reset_program(self):
        self.income = 0
        self.expenses = 0
        del self.expense_list[0:]
        del self.expense_name[0:]
        del self.income_name[0:]
        del self.income_list[0:]
        self.prompt_income()

    def close_program(self):
        print('Exiting Program.')
        sys.exit(0)

if __name__ == '__main__':
Application()


texts: Buffered RNG-wrapper using openmp in c++

texts:
I wrote a class around a UniformRandomBitGenerator, which in turn also satisfies the concept of a UniformRandomBitGenerator. It uses a buffer and parallelism (openmp) to quickly generate large amounts of random numbers.

I'm happy about all kinds of feedback, but I'm most unsure about my use of openmp and ensuring that the same seed always generates the same sequence of pseudo-random numbers.

Here's the class:

#pragma once
#include <random>
#include <vector>
#include <omp.h>

template<class RNG_type>
class BP_RNG {
public:

    using unsigned_t = unsigned;
    using result_type = typename RNG_type::result_type;
    constexpr static result_type min() { return RNG_type::min(); };
    constexpr static result_type max() { return RNG_type::max(); };

    BP_RNG(int seed = 42, unsigned_t buffer_size = 1e8, unsigned_t nthreads = 4);

    result_type operator()();
private:
    using buffer_t = std::vector<result_type>;
    using iter_t = typename std::vector<result_type>::iterator;

    void refill();

    RNG_type engine_;
    buffer_t buffer_;
    iter_t position_;
    const unsigned_t nthreads_;
};

template<class RNG_type>
BP_RNG<RNG_type>::BP_RNG(int seed, unsigned_t buffer_size, unsigned_t nthreads):
    engine_(seed),
    buffer_(buffer_size),
    position_(buffer_.begin()),
    nthreads_(nthreads)
{
    refill();
}

template<class RNG_type>
void BP_RNG<RNG_type>::refill()
{
    // Get seeds for RNGs in parallel section beforehand to ensure determinism
    buffer_t seedvals(nthreads_);
    for (auto& seed : seedvals) seed = engine_();

    #pragma omp parallel num_threads(nthreads_)
    {
    RNG_type local_engine( seedvals[omp_get_thread_num()] );
    #pragma omp for
    // Pedestrian vector-iteration so that omp works
    for (unsigned_t i = 0; i < buffer_.size(); ++i) buffer_[i] = local_engine();
    }

    position_ = buffer_.begin();
}

template<class RNG_type>
typename BP_RNG<RNG_type>::result_type BP_RNG<RNG_type>::operator()()
{
    if (position_ == buffer_.end()) refill();
    return *(position_++);
}

And the main.cpp I used to test it:

#include <iostream>
#include <chrono>

#include "buffered_parallel_rng.hpp"

template<class RNG>
void time_rng(RNG& eng, unsigned long iter, std::string name)
{
    typename RNG::result_type a;

    auto start = std::chrono::high_resolution_clock::now();
    for (unsigned long i = 0; i < iter; ++i)
    {
        a = eng();
    }
    auto stop = std::chrono::high_resolution_clock::now();
    double elapsed = static_cast<std::chrono::duration<double> >(stop-start).count();

    std::cout << name << " : " << elapsed << "\n";
}

void test_determinism(unsigned ntests)
{
    BP_RNG<std::mt19937_64> seeder(42);
    for (unsigned j = 0; j < ntests; ++j)
    {
        int seed = seeder();
        BP_RNG<std::mt19937_64> myeng1(seed),myeng2(seed);

        for (unsigned i = 0; i < 10; ++i)
        {
            if (myeng1() != myeng2()) {
                std::cout << "Different results from same seed!\n"
                    << "Seed is: " << seed << "\n";
                return;
            }
        }
    }
}

int main() {
    unsigned iter = 1e9;
    std::mt19937_64 ref_eng;
    ref_eng.seed(100);
    BP_RNG<std::mt19937_64> my_eng(100);

    time_rng(ref_eng, iter, "Other");
    time_rng(my_eng , iter, "Mine ");
    test_determinism(100);
}


texts: Retrieving a list, by iterating through a list

texts:
I'm using VB.Net, MVC 5, EF 6, and Linq.  I have a list of Integers (category attribute IDs).  I need to create a second list of String (values).  There will be one string for each integer.

I am currently accomplishing my task like this:

Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String)
    Dim db As New Model1
    Dim values = New List(Of String)

    For i As Integer = 0 To catAttIDs.Count - 1
        Dim catAttID = catAttIDs(i)

        Dim currentValue = (From row In db.tblEquipment_Attributes
                     Where row.Category_Attribute_Identifier = catAttID _
                     And row.Unique_Item_ID = itemID
                     Select row.Value).SingleOrDefault()

        values.Add(currentValue)
    Next

    Return values
End Function

I have a strong feeling that there is a better way to do this, but I have not been able to find the information I'm looking for.

I'm particularly interested in changing this code so that the database is called once for the list, instead of calling the database 5 or 6 times as I work my way through the list.


texts:
I am looking to make the below code a bit more efficient / OOP based. As can be seen by the X, Y & Z variables, there is a bit of duplication here. Any suggestions on how to make this code more pythonic?

The code functions as I wish and the end result is to import the dictionary values into a MySQL database with the keys being the column headers.

import fnmatch
import os
import pyexiv2

matches = []
dict1 = {}

# The aim of this script is to recursively search across a directory for all
# JPEG files. Each time a JPEG image is detected, the script used the PYEXIV2
# module to extract all EXIF, IPTC and XMP data from the image. Once extracted
# the key (ie. "camera make" is generated and it's respective value
# (ie. Canon) is then added as the value in a dictionary.
for root, dirnames, filenames in os.walk('C:\Users\Amy\Desktop'):
  for filename in fnmatch.filter(filenames, '*.jpg'):
      matches.append(os.path.join(root, filename))
      for entry in matches:
          metadata = pyexiv2.ImageMetadata(entry)
          metadata.read()
          x = metadata.exif_keys
          y = metadata.iptc_keys
          z = metadata.xmp_keys
          for key in x:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in y:
              value = metadata[key]
              dict1[key] = value.raw_value
          for key in z:
              value = metadata[key]
              dict1[key] = value.raw_value
              print dict1


texts: Python implementation of a singly linked list

texts:
This is my code for the implementation of a singly linked list in Python:

class SList:
    def __init__(self):
        self.root = None
        self.size = 0

    def insert(self, item):
        try:
            if not item:
                raise ValueError
            self.size += 1
            if self.root is None:
                self.root = Node(item)
            else:
                p = Node(item)
                p.next = self.root
                self.root = p
        except ValueError:
            raise ValueError('Cannot add None item to a list')

    def remove(self, index):
        try:
            if index < 0 or index >= self.size:
                raise ValueError

            current = self.root
            count = 0
            while count < index:
                current = current.next
                count += 1
            current.next = current.next.next
            self.size -= 1
        except ValueError:
            raise ValueError('Index cannot be negative or greater than the size of the list')

    def __sizeof__(self):
        return self.size

class Node:
    def __init__(self, data):
        try:
            if not data:
                raise ValueError
            self.data = data
            self.next = None
        except ValueError:
            raise ValueError('Node cannot be instantiated without an item')


texts: Go program to find duplicated files in a directory (recursively)

texts:
This is my first Go program. I'm learning the language but it's a bit difficult to understand all the concepts so in order to practice I wrote this. It's a simple program which recursively check for duplicated files in a directory.

It uses a SHA256 hash on files in order to identify if two files are the same or not. I spawn multiple workers to handle this hashing.

Here is how it works:

n workers (goroutine) are spawned, each of them waiting for file paths to process on the same channel, named input in my code.
1 goroutine is spawned to recursively search for files in the direvtory, and populate the input channel with file names.
The main goroutine process the results as soon as they are available and add them to a map of sha256->[file, file, ...].

Finally we just display the duplicates.

Please feel to comment on anything, I really want to progress in Go, and especially "idiomatic" Go.

EDIT: Improved my initial code with flags and error management.

package main

import (
    "crypto/sha256"
    "encoding/hex"
    "fmt"
    "os"
    "path/filepath"
    "sync"
    "flag"
    "runtime"
    "io"
)

var dir string
var workers int

type Result struct {
    file   string
    sha256 [32]byte
}

func worker(input chan string, results chan<- *Result, wg *sync.WaitGroup) {
    for file := range input {
        var h = sha256.New()
        var sum [32]byte
        f, err := os.Open(file)
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
            continue
        }
        if _, err = io.Copy(h, f); err != nil {
            fmt.Fprintln(os.Stderr, err)
            f.Close()
            continue
        }
        f.Close()
        copy(sum[:], h.Sum(nil))
        results <- &Result{
            file:   file,
            sha256: sum,
        }
    }
    wg.Done()
}

func search(input chan string) {
    filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            fmt.Fprintln(os.Stderr, err)
        } else if info.Mode().IsRegular() {
            input <- path
        }
        return nil
    })
    close(input)
}

func main() {

    flag.StringVar(&dir, "dir", ".", "directory to search")
    flag.IntVar(&workers, "workers", runtime.NumCPU(), "number of workers")
    flag.Parse()

    fmt.Printf("Searching in %s using %d workers...\n", dir, workers)

    input := make(chan string)
    results := make(chan *Result)

    wg := sync.WaitGroup{}
    wg.Add(workers)

    for i := 0; i < workers; i++ {
        go worker(input, results, &wg)
    }

    go search(input)
    go func() {
        wg.Wait()
        close(results)
    }()

    counter := make(map[[32]byte][]string)
    for result := range results {
        counter[result.sha256] = append(counter[result.sha256], result.file)
    }

    for sha, files := range counter {
        if len(files) > 1 {
            fmt.Printf("Found %d duplicates for %s: \n", len(files), hex.EncodeToString(sha[:]))
            for _, f := range files {
                fmt.Println("-> ", f)
            }
        }
    }

}


texts:
Below code just for assemble data into network packet. but the code logic has many repeat parts to convert integer for byte array. what's the best method for such purpose to simplify below logic?

typedef struct _INFO {
    int pid;
    int score;
} INFO;

void send_packet(int connfd,INFO* info,int len) {
    int buflen = len*8 + 8;
    unsigned char* buf = (int*)malloc(buflen);
    int p = 0;
    buf[p++] = 0x55;
    buf[p++] = 0x55;
    buf[p++] = 0x55;
    buf[p++] = 0x55;

    buf[p++] = buflen & 0xFF;
    buf[p++] = (buflen >> 8) & 0xFF;
    buf[p++] = (buflen >> 16) & 0xFF;
    buf[p++] = (buflen >> 24) & 0xFF;
    for (int i=0;i<len;i++) {
        buf[p++] = info[i].pid & 0xFF;
        buf[p++] = (info[i].pid >> 8) & 0xFF;
        buf[p++] = (info[i].pid >> 16) & 0xFF;
        buf[p++] = (info[i].pid >> 24) & 0xFF;

        buf[p++] = info[i].score & 0xFF;
        buf[p++] = (info[i].score >> 8) & 0xFF;
        buf[p++] = (info[i].score >> 16) & 0xFF;
        buf[p++] = (info[i].score >> 24) & 0xFF;
    }
    write(connfd, buf, buflen);
    free(buf);
}