texts:
I'm currently developing a new version of ExpressGenGen Using TDD. While I'm rewriting the new version of my Code Generator Generator.
I'm using its old version to generate code to be used by the new version.
This is how I'm creating new classes: when a new class is created,
it will generate a .cpp and .h file and then add them to CMakeLists.txt,
and also TestHelper.h is updated with new headers.

What I want reviewed are the bash scripts. (You are also welcome to review the ExpressGenGen templates)

Bash Scripts

gen

#!/bin/bash

cd ..
cat Samples/template_bash_CMakeLists.txt | xgengen bash | bash - > CMakeLists.txt
cat Samples/template_bash_TestHelper.txt | xgengen bash | bash - > Tests/TestHelper.h

new_class

#!/bin/bash

echo 'Create New Class'
echo '--------------------------'
echo 'Type Class Name : '
read _class
# convert Upper Camel case to header guard, ex: NewClass -> _NEW_CLASS_H_
_guard=`echo $_class | sed -e 's/\([A-Z]\)/_\1/g' | awk '{printf toupper($0)} END{printf "_H_";}'`
# export the variables so they are visible to the child shell
export guard=$_guard
export class=$_class
cat template_bash_CPP.txt | xgengen bash | bash - > "../Src/$class.cpp"
cat template_bash_H.txt | xgengen bash | bash - > "../Src/$class.h"
./gen

Templates

template_bash_CMakeLists.txt

project(ExpressGenGen)

cmake_minimum_required(VERSION 2.6)
include_directories($ENV{BOOST_ROOT} $ENV{LUA_ROOT} $ENV{GMOCK_HOME}/include $ENV{GMOCK_HOME}/gtest/include .)
link_directories($ENV{LUA_ROOT} $ENV{BOOST_ROOT}/stage/lib $ENV{GMOCK_HOME}/build $ENV{GMOCK_HOME}/build/gtest)
set(CMAKE_CXX_FLAGS "${CMAXE_CXX_FLAGS} -Wall -Wpedantic -std=gnu++11")

set(sources
$$$find . -name '*.cpp' | sed 's/\.\//  /'
    $$$find . -name '*.h' | sed 's/\.\//  /'
  WindowsRsrc/WindowsRes.rc)
add_executable(xgengen ${sources})
target_link_libraries(xgengen lua)
target_link_libraries(xgengen boost_program_options)
target_link_libraries(xgengen pthread)
target_link_libraries(xgengen gmock)
target_link_libraries(xgengen gtest)

template_bash_CPP.txt

//--------------------------------------------
// Definition
#include "{$$$class$$}.h"
//--------------------------------------------
// Uses
//
//--------------------------------------------

{$$$class$$}::{$$$class$$}()
{

}

//--------------------------------------------

template_bash_H.txt

#ifndef {$$$guard$$}
#define {$$$guard$$}

//--------------------------------------------
// Has
//
//--------------------------------------------
// Inherits
//
//--------------------------------------------
// Uses
//
//--------------------------------------------

class {$$$class$$} {
public:
    {$$$class$$}();
    virtual ~{$$$class$$}() {}

private:
};

//-------------------------------------------

#endif // {$$$guard$$}

template_bash_TestHelper.txt

//--------------------------------------------
// TestHelper
//
// This header is basically an include all type helper for Test*.cpp files
// therefore greatly reducing duplication
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wpedantic"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <gmock/gmock.h>
#pragma GCC diagnostic pop

#include <iostream>
#include <istream>
#include <sstream>
#include <memory>
// AutoGenerated
$$$find Src -name "*.h" | sed -e 's/\(.*\)/#include \"\.\.\/\1\"/g'
// End AutoGenerated
//--------------------------------------------


texts:
I like the fact that I can create a class and have the connection details in one file if I need to update them and then pass them to the method I create in the class that defines my specific use of mysqli. I was thinking also that I may give an option to pass the connection details if I need to use a different db in one page. Is this a good idea. Any adverse problems?

Basic Example (Note the values defined in __constructor)

public function __construct($host = 'localhost', $user = 'myuser', $pass = 'mypass', $db = 'mydb') {
    // Connect to Database
    $this->mydb = new mysqli($host, $user, $pass, $db);
}


texts:
I'm trying to make it so that a string generates n keys, and all of those are required to recover the original string. For this, I generate n-1 random strings, XOR them all together with the original string to get the nth one. XORing these n strings reproduces the original strings

How secure is this? Is there any better method?

Also, is the code itself good enough? What can I do to improve it in terms of security/speed/readability/best practices?

package crypto;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

/**
 * Created by hooda on 2/3/2015.
 */
public class XOR {

    //Testing the functionality.
    public static void main(String[] args) throws Exception {
        XOR xor = new XOR();

        String text = "Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.";
        String[] pieces = xor.encrypt(text, 5);
        System.out.println(pieces[0]);
        System.out.println(pieces[1]);
        System.out.println(pieces[2]);
        System.out.println(pieces[3]);
        System.out.println(pieces[4]);
        String test = xor.decrypt(pieces);
        System.out.println(test);

    }

    public String[] encrypt(String s, int n) throws Exception {
        int length = s.length();
        String[] pieces = new String[n];

        for (int i = 0; i < n - 1; i++) {
            pieces[i] = keyGen(length);
        }

        String nth = s;
        for (int i = 0; i < n - 1; i++) {
            nth = doXOR(pieces[i], nth);
        }

        pieces[n - 1] = nth;
        return pieces;
    }

    public String decrypt(String[] pieces) {

        String decrypted = new String(new char[pieces[0].length()]).replace("\0", Character.toString((char) 0));
        for (String piece : pieces) {
            decrypted = doXOR(piece, decrypted);
        }
        return decrypted;
    }

    public String toBinary(String s) throws Exception {
        byte[] bytes = s.getBytes("ASCII");
        StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
        }
        return binary.toString();
    }

    public String keyGen(int length) throws UnsupportedEncodingException {
        SecureRandom srand = new SecureRandom();
        byte[] bytes = new byte[length];
        srand.nextBytes(bytes);
        return new String(bytes, "ASCII");
    }

    public String doXOR(String s1, String s2) throws IllegalArgumentException {

        String ret;
        if (s1.length() != s2.length()) {
            throw new IllegalArgumentException("The bit strings must have equal length!");
        } else {
            ret = "";
            for (int i = 0; i < s1.length(); i++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(i);
                int i1 = (int) c1;
                int i2 = (int) c2;
                int i3 = i1 ^ i2;
                char c3 = (char) i3;
                ret += c3;
            }
        }
        return ret;
    }
}


texts:
I have a Java game development framework. Certain classes, such as Texture, need to be disposed as soon as you don't need them - we cannot depend on the Garbage Collector.

For this, I have decided to enforce reference counting like Objective-C. You call retain() when you want to own something, and release() when not anymore. This increases/decreases a counter. When the counter hits 0, dispose() is called - at which point, Texture will gladly free its resources such as pixel data etc.

NOTE

The reason I can't depend on the Garbage Collector, is because things like the pixel data aren't stored in Java, but rather by OpenGL in some bindings. Similar things happen with audio data. So it is necessary to call OpenGL to free that data manually.

On my first attempt, I made an interface:

public interface Retainable {
    void retain();
    void release();
    void dispose();
}

So a class that wants to be part of this MRC scheme would be like

class Texture implements Retainable {
    int retainCount = 1;    // 1 because I want it to begin retained
    public void retain() {
        retainCount += 1;
    }
    public void release() {
        if (--retainCount == 0) {
            dispose();
        }
    }
    public void dispose() {
        // Free pixel data
    }
}

This works and is OK.

However, every class that wants to do be part of the MRC scheme would need to:

Create an int field
Implement retain()
Implement release()
Implement dispose()

From the four points, the only non-redundant point is the last one. Obviously dispose() will differ from one class to another. But all the other points won't differ from class to class - I am repeating code, and I don't like that.

On an attempt to improve the simplicity of this scheme, I decided to make a manager class to keep track of all Retainable objects. The class will have a map, where the keys are the Retainable objects and the values are their integer counts. The class will have retain(obj) and release(obj), which increase/decrease the count in the map. When the count hits 0 it will call dispose() and then remove the object from the map.

public abstract class Manager {
    private static HashMap<Object, Integer> data = new HashMap<Object, Integer>();
    public static void retain(Retainable object) {
        if (data.containsKey(object)) {
            data.put(object, data.get(object) + 1);
        }else{
            data.put(object, 1);
        }
    }
    public static void release(Retainable object) {
        if (data.containsKey(object)) {
            int count = data.get(object);
            if (count == 1) {
                data.remove(object);
                object.dispose();
            }else{
                data.put(object, count - 1);
            }
        }
    }
}

While I understand that "global" stuff isn't likeable, I decided to sacrifice that for the sake of simplifying this scheme as much as possible.

I really like this approach, because now my classes don't need to implement so much redundant stuff. They only need to implement dispose().

There is one thing that still bugs me

I would like that, when you construct a Retainable object, it will automatically have a retain count of 1 (so you don't need to call retain() every time you make a new object).

Then, this means that a Retainable class needs to call

Manager.retain(this);

In their constructor... for all classes. Ahh, if only there was a way to construct objects already retained without having to add this line in their constructor (I know this is a super small and almost meaningless thing, but heck...).

Do you have any ideas to improve this? And, very hopefully, a solution to the annoyance above?


texts: Python class to abstract the iptables Linux firewall

texts:
I've written the following Python class that fetches iptables rules using basic string processing in Linux. Am I doing this in the correct manner? I've tested the code and it's running fine.

I'm ultimately going to use this class in a GUI app that I'm going to write using Python + GObject.

#!/usr/bin/python
import sys, subprocess

class Fwall:
    currchain=""
    dichains={'INPUT':[],'OUTPUT':[],'FORWARD':[]}
    dipolicy=dict(INPUT=True,OUTPUT=True,FORWARD=True)
    dicolumns={}

def __init__(self):
    self.getrules()
    self.printrules()
    print "class initialized."

def getrules(self):
    s = subprocess.check_output("iptables --list --verbose",shell=True,stderr=subprocess.STDOUT)#.split('\n')
    print s
    for line in s.splitlines():
        if len(line)>0:
            self.parseline(line)

def parseline(self,line):
    line=line.strip()
    if line.startswith("Chain"): #this is the primary header line.
        self.currchain=line.split(' ')[1]
        allowed=not line.split('policy ')[1].startswith('DROP')
        self.dipolicy[self.currchain]=allowed
        #print "curr chain set to " + self.currchain
    else:
        items=line.split()
        if line.strip().startswith('pkts'): #this is the secondary header line, so fetch columns.
            if len(self.dicolumns)==0:
                for i,item in enumerate(items):
                    if len(item)>0:
                        self.dicolumns.setdefault(item,i)
                #print self.dicolumns
            else:
                return
        else:
            ditemp={}
            #print line
            self.dichains[self.currchain].append(ditemp)
            for k,v in self.dicolumns.iteritems():
                #idx= self.dicolumns[item]#,items[item]
                ditemp.setdefault(k,items[v])
                #print line
                #print k,v
                #print k,items[v]#,idx

def printrules(self):
    for k,v in self.dichains.iteritems():
        print k
        litemp=self.dichains[k]
        for item in litemp:
            print item

if __name__=="__main__":
    f=Fwall()


texts: Simple framework for Google Code Jam problems

texts:
My main concern is code style.  Could you review this?

#pragma once

#include <time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
#include <math.h>
#include <exception>
#include "InfInt.h"
#include "Array2d.h"

template <typename ContainerT>
ContainerT splitString(const std::string & source) {
    ContainerT cont;
    std::stringstream ss(source);
    typedef typename ContainerT::value_type ElementT;
    std::copy(std::istream_iterator<ElementT>(ss), std::istream_iterator<ElementT>(), std::back_inserter(cont));
    return cont;
}

template <typename T>
std::string joinString(const T & v, const std::string & delim = " ") {
    std::ostringstream s;
    bool empty = true;
    for (const auto & i : v) {
        if (empty)
            empty = false;
        else
            s << delim;
        s << i;
    }
    return s.str();
}

class CodeJam {
public:
    std::stringstream input;
    std::stringstream output;
    int curCase;

    int solveJam(const std::string & data) {

        int res = 0;
        std::cout << "Solving jam:" << std::endl << std::endl;
        try {
            input.clear();
            output.clear();
            auto inputFile = "Data\\" + data + ".in";
            std::ifstream finput(inputFile);
            if (!finput.is_open())
                throw std::runtime_error("Can not open input file " + inputFile);
            auto outputFile = "Data\\" + data + ".out";
            std::ofstream foutput(outputFile);
            if (!foutput.is_open())
                throw std::runtime_error("Can not open output file " + outputFile);
            input << finput.rdbuf();
            input.seekg(0);

            auto elapsedTime = clock();
            res = solveAll();
            elapsedTime = clock() - elapsedTime;

            foutput << output.rdbuf();
            finput.close();
            foutput.close();

            std::cout << std::endl;
            std::cout << "Success! Finished " << res << " tests in " << elapsedTime << " ms" << std::endl;
        } catch (const std::exception & e) {
            std::cout << "Error: " << e.what() << std::endl;
        }
        std::cout << std::endl;
        system("pause");

        return res;
    }
protected:

    virtual int solveAll() {
        int testCases;
        readln(testCases);

        for (curCase = 1; curCase <= testCases; ++curCase) {
            solve(curCase);
            std::cout << "Test " << curCase << " of " << testCases << std::endl;
        };
        return testCases;
    }

    virtual void solve(int task) = 0;

public:
    std::string readLine() {
        std::string line;
        std::getline(input, line);
        return line;
    }

    template<typename T>
    T readLine() {
        std::string line;
        std::getline(input, line);
        T list = splitString<T>(line);
        return list;
    }

    std::vector<int> readInts() {
        return readLine<std::vector<int>>();
    }

    std::vector<std::string> readStrings() {
        return readLine<std::vector<std::string>>();
    }

    std::vector<double> readDoubles() {
        return readLine<std::vector<double>>();
    }

    void readln() {
        readLine();
    }

    template <typename T>
    void readln(T & t) {
        input >> t;
        input.ignore();
    }

    template <typename First, typename... Rest>
    void readln(First & first, Rest &... rest) {
        input >> first;
        readln(rest...);
    }

    template <typename T>
    void writeResult(T value) {
        output << "Case #" << curCase << ": " << value << std::endl;
    };
};


texts:
We have multiple scripts which write into XLSX with the same format, into a different format or slide variation. I am trying to write an API which saves time for other programs, but I need input on restructuring the file.

import openpyxl
from xlsxwriter.workbook import Workbook

class xlsx_extend(object):
    """This class contain api of xlsx functionality"""
    def __init__(self, name):
        """create xls file"""
        self.xlsx_name = Workbook(name)
        self.create_format('blue', 12)

    def create_format(self, color, size):
        """write header"""
        self.xlsx_format = self.xlsx_name.add_format()
        self.xlsx_format.set_font_size(size)
        self.xlsx_format.set_bold()
        self.xlsx_format.set_color(color)
        self.xlsx_format.set_border()
        self.xlsx_format.set_center_across()
        self.xlsx_format.set_align('center')
        self.xlsx_format.set_rotation(90)

    def add_sheet(self, ws_name):
        """Adding worksheet name"""
        return self.xlsx_name.add_worksheet(ws_name)

    def rotate_text_format(self, angle):
        """rotate the text data"""
        self.xlsx_format.set_rotation(angle)

    def get_xlsx_name(self):
        """Returing xlsx name for derive class"""
        return self.xlsx_name

    def close_xlsx(self):
        """close xlsx File"""
        self.xlsx_name.close()

class xlsx_sheet:
    """This is xlsx worksheet class"""
    def __init__(self, excel_sheet, ws_name):
        """Initialze Base function and Create Worksheet"""
        self.excel_sheet = excel_sheet
        self.ws_name_worksheet = excel_sheet.add_sheet(ws_name)
        self.ws_name_worksheet.set_column(0, 0, 40)

    def write(self, row, col, data, format=None):
        """write Add in xlsx File"""
        self.ws_name_worksheet.write(row, col, data)

    def write_column(self, row, col, data, format=None):
        """write data in column than need pass data as list"""
        self.ws_name_worksheet.write_column(row, col, data)

    def write_row(self, row, col, data, format=None):
        """write data in row than need to pass as list"""
        self.ws_name_worksheet.write_row(row, col, data, self.excel_sheet.xlsx_format)

    def write_comment(self, row, col, data):
        """write comment in cell"""
        self.ws_name_worksheet.write_comment(row, col, data, {'width': 400, 'height': 400})

    def text_condition_format(self, first_row, first_col, last_row, last_col, value, format):
        """Adding text condition format"""
        self.ws_name_worksheet.conditional_format(first_row, first_col, last_row, last_col,
            {'type': 'text',
            'criteria': 'containing',
            'value': value,
            'format': format
            })

And another module with it's call API like:

report_xlsx = xlsxutils.xlsx_extend("report.xlsx")
red_format = report_xlsx.xlsx_name.add_format({'bg_color': '#FF0000'})
green_format = report_xlsx.xlsx_name.add_format({'bg_color':'#99CC32'})
gray_format = report_xlsx.xlsx_name.add_format({'bg_color':'#53868B'})
blue_format = report_xlsx.xlsx_name.add_format({'bg_color':'#3298FE'})
light_red_format = report_xlsx.xlsx_name.add_format({'bg_color':'#FF9999'})

report_worksheet = xlsxutils.xlsx_sheet(report_xlsx, "Report")

report_worksheet.text_condition_format(1, 1, row, col, 'P', green_format)
report_worksheet.text_condition_format(1, 1, row, col, 'F', red_format)
report_worksheet.text_condition_format(1, 1, row, col, 'AB', red_format)
report_worksheet.text_condition_format(1, 1, row, col, 'RU', light_red_format)
report_worksheet.text_condition_format(1, 1, row, col, 'QU', light_red_format)
report_worksheet.text_condition_format(1, 1, row, col, 'M', gray_format)
report_worksheet.text_condition_format(1, 1, row, col, 'UN', blue_format)
report_xlsx.close_xlsx()

Can you do code review and provide your input?


texts: Convert Integer to String without using Java API library

texts:
I have written a Java program that converts an integer to String digit by digit and concatenate them together using the + operator without touching the Stock Java API library.

I like to have feedback on my code. Where do I need to improve. If I need to deduct something. So please criticize me. Thank you.

import java.util.Scanner;

public class StrFromInteger {

    /*
     * a single digit is passed as an argument
     * And a matching digit of String type
     * is returned.
     */
    public static String returnDigitString(int digit) {
        String res = "";

        switch(digit) {
            case 0:
                res = "0"; break;

            case 1:
                res = "1"; break;

            case 2:
                res = "2"; break;

            case 3:
                res = "3"; break;

            case 4:
                res = "4"; break;

            case 5:
                res = "5"; break;

            case 6:
                res = "6"; break;

            case 7:
                res = "7"; break;

            case 8:
                res = "8"; break;

            case 9:
                res = "9"; break;
        }
        return res;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Scan the integer as int
        Scanner scn = new Scanner(System.in);
        int number = scn.nextInt();

        //find the number of digits using logarithm
        //if input number is not equal to zero because
        //log of zero is undefined otherwise if input
        // number zero length is equal to 1
        int input = number;
        int length = 0;
        if(number != 0) {
        length = ( int ) (Math.log10(number) + 1 );}
        else if(number ==0) {
            length = 1;
        }

        //Save each digit in String format by passing
        // the integer digit to the returnDigitString()
        //method one by one
        String[] reverseStr = new String[length];

        String digits = "0123456789";

        int remainder =0;
        int result = number ;
        --length;
        number = length;
        String strSeq = "";
        String valStr = "";

        // loop through the whole integer digit by digit
        //use modulo operator get the remainder
        //save it in remainder. then concatenate valStr
        //returned from returnDigitString()
        //method with previous String of Digits. Divide the result by 10. Again
        //repeat the same process. this time the modulo and the
        //number to be divided will be one digit less at each decremental
        //iteration of the loop.
        for(int i = number; i >= 0; --i) {

            remainder = result % 10;

            valStr = returnDigitString(remainder);
            strSeq = valStr + strSeq;

            result = result / 10;
        }

        //Print the string version of the integer
        System.out.println("The String conversion of " + input + " is: " + strSeq);
    }

}


texts: Determine how many bits are in a floating point value

texts:
I'm writing a program which determines how many bits are in a floating point value (this will be run on Unix).

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

void countbits(int k);

int main(){
    int input;
    // int a = (int) malloc(sizeof(int));
    printf("Please enter a number: ");
    scanf("%d",&input);
    // a = input;

    countbits(input);
}

void countbits(int k){
    int j,count;
    count = 0;
    for(j = 0; j < 31; j++){
        if(k & 0x000001 == 1){
        count++;
        }
        k >>= 1;
    }
    printf("%d has %d bits set\n",k,count);
    // count = 0;
}

Output example:

  2 has 1 bits set
  6 has 2 bits set
  32 has 1 bits set

I'll really appreciate any feedback or correction or if there is something I can do better.


texts: Printing multiple different shapes on the same line

texts:
Whilst scanning my C programming textbook, I saw this practice problem from a very early chapter:

I got to thinking that the problem probably wants you to draw each shape separately, which would be very easy.

But to do literally what the question asks (print them on the same line), I couldn't see any easy way! The rectangle is 9x9, but they seem 5 spaces apart, the oval is 7 wide, the arrow tip is 5x3, etc. Maybe if the arrow had tips on both ends, I could dissect the whole picture horizontally.

After dabbling with ways to produce the rectangle, oval, arrow, and diamond by themselves, and then to somehow print each row correctly with loops and ifs, I realized maybe I should just draw it literally.

#include <stdio.h>

int main() {

    puts("*********       ***         *           *");
    puts("*       *      *   *       ***         * *");
    puts("*       *     *     *     *****       *   *");
    puts("*       *     *     *       *        *     *");
    puts("*       *     *     *       *       *       *");
    puts("*       *     *     *       *        *     *");
    puts("*       *     *     *       *         *   *");
    puts("*       *      *   *        *          * *");
    puts("*********       ***         *           *");

    return 0;

}

I could have put it all in one puts with newlines but I found that was pretty unreadable.

Is there any better way to do this? Am I completely missing something / am I doing it in the most efficient way?


texts: Given a room number, find the floor on which the room lies

texts:
I came across a question where I had to find the floor by using given room no. And given no data structure to hold the data. What we know is distribution of the rooms across the floors.

I have given below solution for it but, I think it may break as number of floors increases.

int queryRoom = 37;
int totalFloor = 6;

int currentRm = 0;
int floorInQuestion = 1; // staring floor

while (floorInQuestion != totalFloor) {
    if (floorInQuestion % 2 != 0) {
        currentRm = currentRm + 5;
    } else {
        currentRm = currentRm + 10;
    }
    if (queryRoom <= currentRm)
        break;
    floorInQuestion++;
}

System.out.println(floorInQuestion);


texts:
I have written the following code and I am new to Python.
Please let me know if I can make improvements to the following program:

import math

X = [12,11,13,13, 9,10,10,13, 5,10,10,13,10,10, 5, 8, 9, 8, 8, 9, 9,10,11, 5,12]
Y = [11,10,10,10, 9,13,10,11, 6, 7,13,14,14,11,11,10,10, 7, 8,12,11,11, 8, 7,13]

Xmean = sum(X)/len(X)
Ymean = sum(Y)/len(Y)

x = [var-Xmean for var in X]
y = [var-Ymean for var in Y]

xy =[a*b for a,b in list(zip(x,y))]
sum_xy = sum(xy)

x_square = [a*a for a in x]
y_square = [b*b for b in y]

sum_x_square = sum(x_square)
sum_y_square = sum(y_square)

sum_x_square_sum_y_square = sum_x_square*sum_y_square
sqrt_sum_x_square_sum_y_square = math.sqrt(sum_x_square_sum_y_square)

r = sum_xy/sqrt_sum_x_square_sum_y_square

print(r)

The above code is written for this formula :


texts:
I'm relatively young in Java, and am familiar with only the basics of the language, yet. I've started studying data structures, and I've made an attempt to create a solution for the selection sort algorithm. After many attempts with errors and exceptions, I've managed to come up with what looks like a working solution.

I realize that having the swap implemented as a separate method call in the sort function causes some additional overhead, instead of having the swap directly in the loop. But this version helps me follow along the logic clearly, as I'm not that experienced yet.

 package Chap_3;

/**
 * Created by user1 on 8/7/15.
 * my selection sort version
 */

class MySelSort {

    //reference to array
    private int[] arr;
    //num. of elements
    private int n;

    //constructor
    public MySelSort(int max) {
        //create array with size
        arr = new int[max];
        //set current items to 0
        n = 0;
    }

    //--------------------------------------------------
    //insert()
    public void insert(int key) {

        //insert key to relevant place in array
        arr[n] = key;
        //increase size of array
        n++;
    }

    //--------------------------------------------------
    //display()
    public void display() {
        System.out.println("The items in the array are: ");
        for(int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    //-------------------------------------------------
    //sort() using selection sort
    public void selSort() {
        int in, out;
        //int min = 0;
        for(out = 0; out < n - 1; out++) {
            int min = out;
            for(in = out+1; in < n; in++) {

                if(arr[min] > arr[in]) {
                    min = in;
                }

            }

            if(arr[out] > arr[min]) {
                swap(out, min);
            }
        }
    }

    //------------------------------------------------
    //swap()
    public void swap(int one, int two) {
        int temp = arr[one];
        arr[one] = arr[two];
        arr[two] = temp;
    }
}

public class MySelSortApp {

    public static void main(String[] args) {
        //create array
        MySelSort sel = new MySelSort(100);

        //insert 8 items
        sel.insert(40);
        sel.insert(60);
        sel.insert(90);
        sel.insert(10);
        sel.insert(80);
        sel.insert(70);
        sel.insert(20);
        sel.insert(50);

        //display items
        sel.display();

        //sort items
        sel.selSort();

        //display again
        sel.display();

    }
}


texts:
In an effort to learn as much as possible about best development practices and software architecture, I created my own MVC framework using PHP (github: https://github.com/alemmedia/miniMVC).
I've found that this has resulted in phenomenal improvements in my programming skills, but I'm still limited by my own limited experience when it comes to reviewing my code.

I'd like to get your critique on one of my least favorite classes (I always feel like there is something off about them):

Here is my Session singleton I use to access/manage session data.

class Session{

/**
 * @var object Holds the single instance of Session
 */
private static $instance;

/**
 * @var string The session id of the current session
 */
protected $id;

/**
 * @var mixed The data to be held in session.
 */
public $data;

/**
 * __construct - Starts session
 *
 *  Establishes Session::data reference to $_SESSION superglobal array, and sets session id.
 *  Privately held an called only by Session::open for singleton functionality
 */
private function __construct(){
    session_start();
    $this -> id   = session_id();
    $this -> data =& $_SESSION;
}

/**
 * open - Creates singleton instance of Session object
 *
 * @return object
 */
public static function open() {
    if ( !isset(self::$instance) )
        self::$instance = new self();
    return self::$instance;
}

/**
 * set - Recieves variables to set to $_SESSION array
 *
 * @param string $property   The property to set to the session
 * @param mixed  $value      The balue to set to the property
 * @param bool   $make_array If set to true the property will be an numeric array
 */
public static function set($property, $value = null, $make_array = false){
    if ( is_array( $property) ){
        foreach($property as $key => $single_property)
            Session::open() -> set($key, $single_property);
    }else{
        if ($make_array == false)
            Session::open() -> data[$property] = $value;
        else
            Session::open() -> data[$property][] = $value;
    }
}

/**
 * del - Recieves variables to delete in $_SESSION array
 *
 * @param string $property   The property to delete from the session
 */
public static function del($property){
    if ( is_array( $property) ){
        foreach($property as $key => $single_property)
            Session::open() -> del($key);
    }else
        unset(Session::open() -> data[$property]);
}

/**
 * get - Returns variables from $_SESSION array.
 *
 * @param string $property   The property to retrieve from the session
 * @return mixed|bool        The retrieved property or false.
 */
public static function get($property){
    if ( isset( Session::open() -> data[$property] ) )
        return Session::open() -> data[$property];
    else
        return false;
}

/**
 * get - Returns variables from $_SESSION array and subsequently deletes them.
 *
 * @param string $property   The property to retrieve and delete from the session
 * @return mixed             The retrieved property.
 */
public static function getThenDel($property){
    $result = Session::open() -> get ($property);
    Session::open() -> del ($property);
    return $result;
}

}

Let me know if you've spotted any mistakes or have any suggestions.
Also, if you've found any code in the GitHub repository to be sub-optimal, I'd be happy to hear your comments.


texts: Invocation list implementation (signals/slots)

texts:
This class is mostly an educational exercise for me using some C++11 constructs. I wanted to create something similar to an "invocation list" in C#, i.e., a list of zero or more function objects which should be called when the invocation list as a whole is invoked. I'm certain there's room for improvement here and I'm hoping I didn't mess anything up TOO badly.

Some key implementation notes:

Variadic templates are used to specify the parameters passed to the target(s) of the invocation list.
The subscribe() function returns an "opaque" subscription object which can be used to unsubscribe() from the invocation list. This is done because std::function is not equality-comparable (so passing in a std::function to unsubscribe is problematic).
The subscription object that gets returned can be copied, and is designed so that instances of it are still well-behaved in a "detached" state when the original invocation_list instance has been destroyed; this is accomplished by sharing a pointer to the underlying target list using std::shared_ptr to do the reference counting on that pointer. The pointer is nulled when the invocation list is destroyed, detaching any associated lingering subscription instances.
No attempt has been or will be made to make this thread-safe.

#pragma once

#include <functional>
#include <list>
#include <memory>

template <class... Args>
class invocation_list
{
    private:

        typedef std::function<void(Args...)> func_type;
        typedef std::list<func_type> list_type;

    public:

        class subscription
        {
            public:

                void unsubscribe()
                {
                    if (_targets && *_targets)
                    {
                        (*_targets)->erase(_it);
                        _targets.reset();
                    }
                }

            private:

                subscription(
                        std::shared_ptr<list_type *> targets,
                        typename list_type::iterator it)
                    : _targets(targets), _it(it) { }

                std::shared_ptr<list_type *> _targets;
                typename list_type::iterator _it;

            friend class invocation_list;
        };

    public:

        invocation_list() : _token(new list_type *)
        {
            *_token = &_targets;
        }

        ~invocation_list()
        {
            *_token = nullptr;
        }

        invocation_list(const invocation_list&) = delete;
        invocation_list& operator=(const invocation_list&) = delete;

        subscription subscribe(func_type func)
        {
            _targets.push_back(func);
            return subscription(_token, --_targets.end());
        }

        void operator()(Args... args) const
        {
            for (auto it = _targets.begin(); it != _targets.end(); ++it)
                (*it)(args...);
        }

    private:

        list_type _targets;
        std::shared_ptr<list_type *> _token;
};

This would be used like:

invocation_list<int> foo;
auto a = foo.subscribe([](int x) { std::cout << "hello: " << x << std::endl; });
auto b = foo.subscribe([](int x) { std::cout << "world: " << x << std::endl; });
foo(42); // prints "hello: 42" "world: 42"
a.unsubscribe();
foo(54); // prints only "world: 54"

Future changes I've considered and am interested in feedback on:

Overload operators for subscribing and unsubscribing instead of an explicit subscribe() function?
Extending the subscription type to optionally operate in an RAII mode where the target is automatically unsubscribed when the subscription object goes out of scope?


texts: Can this "syntax sweetener" be improved?

texts:
I have a Lua project that uses some syntax sugar described in DecoratorsAndDocstrings, near the bottom of the page. It looks like this:

random =
  docstring[[Compute random number.]] ..
  function(n)
    return math.random(n)
  end

Notice how the function definition is concatenated to the result of the function previous function call. I also have similar sugar like this:

something = foo.bar "Blah" { a = 1, b = 2 }

Basically, the idea is that instead of foo.bar taking two arguments (a string and a table), it only takes the first argument, and returns a function that finishes the operation (like a continuation). In the first example, instead of returning a function, we'd return a table with a __concat meta method.

I ended up with a handful of functions in my project that use syntax like this. The problem is:

The code is not straightforward.
It's difficult to document properly.
Adding support for non-sugared calls compounds the previous two problems.

So, I had the idea to just write them as normal functions, and create a "sweeten" function that takes two arguments: a function to "sweeten," and the number of args it wants. It returns a wrapper for the function. If you call the wrapper with at least the required number of arguments, it will simply tail-call the wrapped function. If you call it with less arguments, it will instead return a sort of "continuation table" with both __call and __concat metamethods set up as wrappers to the wrapper -- calling them will invoke the wrapper again with the previous args and the new args.

local function sweeten(fn, argc)
  local wrapper

  argc = tonumber(argc) or 2

  local function unpack_plus(t, i, ...)
    i = i or 1
    if i <= #t then
      return t[i], unpack_plus(t, i + 1, ...)
    else
      return ...
    end
  end

  local function resume(t, ...)
    return wrapper(unpack_plus(t, 1, ...))
  end

  local meta = { __call = resume, __concat = resume }

  wrapper = function(...)
    if select('#', ...) >= argc then
      return fn(...)
    else
      return setmetatable({...}, meta)
    end
  end

  return wrapper
end

To test if out, you can do something like:

function foo(a, b, c) print(a, b, c) end
function sweet_foo = sweeten(foo, 3)
sweet_foo "qwe" "asd" "zxc" -- prints stuff

I feel like I should be able to simplify sweeten and still get the same result. I'd especially like to get rid of unpack_plus, but I can't see a way to do it. Any thoughts?


texts:
I'm trying to come up with the most basic example of making a JQuery slide show where you click on the current image you're viewing and you cycle through a gallery of photos. I know its probably not the most basic example, because if I want to add a new image I have to code more JQuery. Is there a more abstract approach where I don't have to code JQuery in terms of div id's and let classes take care of the work?
Here is my JQuery

$(document).ready(function() {
$("#pic1").click(function() {
    $("#pic1").hide();
    $("#pic2").show();
});
$("#pic2").click(function() {
    $("#pic2").hide();
    $("#pic3").show();
});
$("#pic3").click(function() {
    $("#pic3").hide();
    $("#pic1").show();
});
});

The rest is here.
http://jsfiddle.net/XjdTX/3/


texts:
Okay, so I just started learning Haskell around a week ago and this is my first real program that I worked on all of yesterday with a lot of help from IRC. I know that using indicies and arrays is not very "Haskellish" but I found constantly manipulating lists and traversing them was extremely slow and sometimes the program took over 10 minutes to execute while this version is instant.

Afterwards I found you can do it with some Zipper package in 10 lines of code trivially but I didn't want to use anything too fancy.

I find that when I'm writing Haskell because there is no state I find myself simulating state with function parameters (saving variables and mutating them in a recursive call). I'm pretty sure I took it too far because most of these functions take four parameters and rarely change them but I'm not sure about many alternatives.

I haven't gotten to monads, functors, or applicatives yet, so while I'm sure they could solve this quite elegantly, they're still just magic to me. Unless the explanation is quite simple, I'd prefer if replies didn't mention them. I'm mostly looking for refactorings, style-advice, and better ways of implementing some things.

import qualified Data.Sequence as S
import Data.Char (chr, ord)
import Data.Array

-- Current Index, Indentation Depth, Program Array -> Bracket Index
prevBracketIndex :: Int -> Int -> Array Int Char -> Int
prevBracketIndex i depth cs
    | cs ! i == '[' = if (depth - 1) == 0 then i else prevBracketIndex (i - 1) (depth - 1) cs
    | cs ! i == ']' = prevBracketIndex (i - 1) (depth + 1) cs
    | otherwise = prevBracketIndex (i - 1) depth cs

nextBracketIndex :: Int -> Int -> Array Int Char -> Int
nextBracketIndex i depth cs
    | cs ! i == '[' = nextBracketIndex (i + 1) (depth + 1) cs
    | cs ! i == ']' = if (depth - 1) == 0 then i else nextBracketIndex (i + 1) (depth - 1) cs
    | otherwise = nextBracketIndex (i + 1) depth cs

execCode :: Int -> S.Seq Int -> Int -> Array Int Char -> IO ()
execCode tapePos ts codePos cs
    | codePos == (snd . bounds $ cs) = return ()
    | cmd == '+' = execCode tapePos (S.update tapePos (value + 1) ts) nextPos cs
    | cmd == '-' = execCode tapePos (S.update tapePos (value - 1) ts) nextPos cs
    | cmd == '>' = execCode (tapePos + 1) ts nextPos cs
    | cmd == '<' = execCode (tapePos - 1) ts nextPos cs
    | cmd == '[' && value == 0 = execCode tapePos ts (nextBracketIndex codePos 0 cs + 1) cs
    | cmd == ']' && value /= 0 = execCode tapePos ts (prevBracketIndex codePos 0 cs + 1) cs
    | cmd == '.' = putStr [chr $ S.index ts tapePos] >> execCode tapePos ts nextPos cs
    | cmd == ',' = do { c <- getChar; let newTape = S.update tapePos (ord c) ts in execCode tapePos newTape nextPos cs }
    | otherwise = execCode tapePos ts nextPos cs
    where value = S.index ts tapePos
          cmd = cs ! codePos
          nextPos = codePos + 1

tape = S.fromList $ replicate 30000 0

main = do
    file <- readFile "example.bf"
    execCode 0 tape 0 (listArray (0, length file - 1) file)


texts: How I can short my code when request have many parameters

texts:
Brief:

I've create simple filter in my laravel project. I'll send parameters with ajax request.

Code:

public function specialitiesAjaxLoadMore(Request $request)
{
    $city = null;
    if(isset($request->city_id)) {
        $city = City::find($request->city_id);
        if($city !== null) {
            $city = $city->id;
        }
    }

    $sex = null;
    if((isset($request->sex) && is_numeric($request->sex)) && $request->sex == 1 || $request->sex == 2) {
        $sex = $request->sex;
    }

    $ageFrom = null;
    if((isset($request->ageFrom) && is_numeric($request->ageFrom)) && $request->ageFrom > 7) {
        $ageFrom = $request->ageFrom;
    }

    $ageTo = null;
    if((isset($request->ageTo) && is_numeric($request->ageTo)) && $request->ageTo > 7) {
        $ageTo = $request->ageTo;
    }

    if(isset($city)) {
        $candidates = Candidate::where('city_id', $city)->get();
    }

    if(isset($sex)) {
        $candidates = Candidate::where('sex', $sex)->get();
    }

    if(isset($ageFrom)) {
        $candidates = Candidate::where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))->get();
    }

    if(isset($ageTo)) {
        $candidates = Candidate::where('birthday', '>=', date('Y-m-d', strtotime("-$ageTo years")))->get();
    }

    if(isset($city, $sex)) {
        $candidates = Candidate::where('city_id', $city)->where('sex', $sex)->get();
    }

    if(isset($city, $sex, $ageFrom)) {
        $candidates = Candidate::where('city_id', $city)
                               ->where('sex', $sex)
                               ->where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))
                               ->get();
    }

    if(isset($city, $sex, $ageFrom, $ageTo) && $ageTo < $ageFrom) {
        $candidates = Candidate::where('city_id', $city)
                               ->where('sex', $sex)
                               ->where('birthday', '<=', date('Y-m-d', strtotime("-$ageFrom years")))
                               ->where('birthday', '>=', date('Y-m-d', strtotime("-$ageTo years")))
                               ->get();
    }

}

In my case there will be a lot of parameters from the request and if I continue to write everything in such a way as seisai then there will be a lot of combinations. So is it possible to improve or shorten my current code?


texts:
Goal

Return a deep copy of a double LinkedList.
Each node also contains an additional random pointer, potentially to any node or null.

Code to start
data class Node<T>(
    var data: T?,
    var previous: Node<T>? = null,
    var next: Node<T>? = null,
    var random: Node<T>? = null

class LinkedList {
    // TODO: Implement deep copy here.
}

Implement
fun main() {
    // Setup
    val node1 = Node(1)
    val node2 = Node(2)
    val node3 = Node(3)
    node1.next = node2
    node1.random = node3
    node2.previous = node1
    node2.next = node3
    node3.previous = node2
    node3.random = node1

    val linkedList = LinkedList()
    val deepCopy = linkedList.nextDeepCopy(node1)
    // LinkedList data changed.
    node1.data = 101
    node2.data = 202
    node3.data = 303
    val shallowCopy = linkedList.shallowCopy(node1)
    println("Deep copy made")
    linkedList.print(deepCopy)
    println()
    println("Shallow copy made")
    linkedList.print(shallowCopy)
}

data class Node<T>(
        var data: T?,
        var previous: Node<T>? = null,
        var next: Node<T>? = null,
        var random: Node<T>? = null
)

class LinkedList {
    fun <T> nextDeepCopy(node: Node<T>?): Node<T>? {
        if (node != null) {
            return Node(
                    data = node.data,
                    previous = newDeepCopy(node.previous),
                    next = nextDeepCopy(node.next),
                    random = newDeepCopy(node.random)
            )
        } else return null
    }

    fun <T> newDeepCopy(node: Node<T>?): Node<T>? {
        if (node != null) {
            return Node(
                    data = node.data,
                    previous = node.previous,
                    next = node.next,
                    random = node.random
            )
        } else return null
    }

    fun <T> shallowCopy(node: Node<T>?) = node!!.copy()

    fun <T> print(node: Node<T>?){
        if (node != null){
            println("Node data:${node.data} previous:${node.previous?.data} next:${node.next?.data} random:${node.random?.data}")
            print(node.next)
        }
    }
}


texts:
Challenge:

  You are given a line of N cells with positive integers written in them. Initially a chip is placed on the leftmost cell. Each time it can be moved in any direction (to the left or to the right) on a neighboring cell or across the neighboring cell on the next one. The move is valid if the two numbers - the one the chip is standing on and the one the chip is going to be moved onto - have a common divisor greater than one. How far to the right is it possible to move a chip?

I have a working (I think) method of passing this challenge by recursively checking this method until it finds the optimum solution. I know this is probably the slowest way to do this (\$O(n!)\$?), and it seems that this isn't good enough, because the website I'm submitting my answer to says that I've exceeded my time limit.

Is there any way I can speed up this code?

int chipMoving(int[] a) {

   if(a.length == 1)return 0; //base case
   int b = a[0], c = a[1],d = b;
   while (c!=0){
     int f = c;
     c = b%c;
     b = f;
   }//b is now gcd of a[0] and a[1]

   if(a.length == 2)return b<=1?0:1; //if there are only two terms, return whether we can use the next number one or not
   int e = a[2];
   while (e!=0){
     int f = e;
     e = d%e;
     d = f;
   }//e is now the gcd of a[0] and a[2]

   int leftMax = chipMoving(Arrays.copyOfRange(a,1,a.length));
   int rightMax = chipMoving(Arrays.copyOfRange(a,2,a.length));

   //if only one is available, use that one
   if(b>1 && d<=1)return 1+leftMax;
   if(d>1 && b<=1)return 2+rightMax;

   //check which is better and return that
   if(leftMax > rightMax)return 1+leftMax;
   return 2+rightMax;
}


texts: PHP Validation with functions and list()

texts:
I have multiple form validation checks around my site so I decided to write them as functions to simplify the process of creating the validation pages, here is a snippet for an understanding of what I'm doing.

// Declare regex variables

   $regex_email = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
   $regex_password = "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*\W).*$/";

// Declare validation functions

    function checkEmail($regex, $email) {

        if (!preg_match($regex, $email)) {

            $error = "The format of that Email Address is invalid";
            $solution = "Please go back and try again";

        }

        return array($error, $solution);

    }

    function checkPassword($regex, $password) {

        if (!preg_match($regex, $password)) {

            $error = "Your Passwords does not meet our requirements";
            $solution = "Please go back and try again";

        }

        return array($error, $solution);

    }

I was hoping that when I come to validate it I could simply use:

// Values for $email and $password are fetched from `$_POST` before hand...

// Validate form

    list ($error, $solution) = checkEmail($regex_email, $email);
    list ($error, $solution) = checkPassword($regex_password, $password);

// Display error

    echo("Error:
".$error."
Solution:
".$solution."");

But alas, it doesn't work and no errors at all are displayed and I'm having to do error checks after each one like this:

// Validate form

    list ($error, $solution) = checkEmail($regex_email, $email);

    if (!$error) {

        list ($error, $solution) = checkPassword($regex_password, $password);

    }

// Display error

    echo("Error:
".$error."
Solution:
".$solution."");

I don't mind doing it like this, but when I have say 10+ check*VALUE* functions being called, each one wrapped in an if statement within an if statement and so on, it looks a little messy, I wasn't sure if there was a different approach which would work more like the first way I tried without all the if statement's.


texts: Add an edge to a directed acyclic graph such that it stay acyclic

texts:
My code doesn't actually do that per se, but rather it find every possible edge that can be added without creating a cycle. The return value of the function FindNodesToConnect is a map, where the key is a node and the value is a list of all the nodes we can direct an edge to from the key without introducing cycles.
Another quirk is that this is not a stand-alone function, but part of a bigger neuro-evolution project, so the input is not a graph but a genome that has a graph encoded in it, however the genome is immediately translated to a other data structures so no prior knowledge is necessary (but I'd be glad to clarify further as needed).
My main worry is performance, this function could be called hundreds of times every generation for hundreds or thousands of generations, but it contains nested loops and a recursive function. Is there any way to optimize this? or maybe a completely different way of doing this?
Another minor point is readability which is something I'm always trying to improve.
The code:
'use strict';

if (!window.Neat) window.Neat = {};

Neat.GenomeGraph = (function () {
    const genomeToNodeMap = genome => {
        // return value is a map that maps every node to its direct predecessors
        const result = new Map()
        for (let nodeGene of genome.nodeGenes)
            result.set(nodeGene.id, [])
        for (let connectionGene of genome.connectionGenes)
            result.get(connectionGene.outId).push(connectionGene.inId)
        return result
    }

    const getDependencies = (nodeMap, nodeId) => {
        // return value is all the predecessors of a node (found recursively)
        return [].concat.apply(nodeMap.get(nodeId), nodeMap.get(nodeId).map(nextNodeId => getDependencies(nodeMap, nextNodeId)))
    }

    const setDifference = (A, B) => A.filter(x => !B.includes(x))

    return {
        FindNodesToConnect: genome => {
            const nodeMap = genomeToNodeMap(genome)
            const graphNodes = genome.nodeGenes.map(nodeGene => nodeGene.id)
            const result = new Map()

            for (let currentNodeId of graphNodes) {
                const cannotConnectTo = getDependencies(nodeMap, currentNodeId);
                cannotConnectTo.push(currentNodeId)
                for (let [nodeId, dep] of nodeMap)
                    if (dep.includes(currentNodeId))
                        cannotConnectTo.push(nodeId)

                const canConnectTo = setDifference(graphNodes, cannotConnectTo)

                if (canConnectTo.length > 0)
                    result.set(currentNodeId, canConnectTo)
            }
            return result;
        }
    }
})()

Example function call:
Neat.GenomeGraph.FindNodesToConnect({
    nodeGenes: [1, 2, 3, 4, 5, 6, 7].map(x => ({ id: x })),
    connectionGenes: [
        { inId: 1, outId: 2},
        { inId: 2, outId: 3},
        { inId: 3, outId: 6},
        { inId: 5, outId: 6},
        { inId: 4, outId: 3},
        { inId: 4, outId: 7},
    ]
})


texts: Is there a simpler way of copying and pasting one inputs value into other input with the same name

texts:
I am trying to write something that will copy the current <input>s value and enter it into any <input> that start with the same name.

<input> names will follow this pattern: price-0, price-1, price-2, upc-0, upc-1, upc-2.

So if a user enters a value in <input name="price-0"> and hits copy the value should be transferred over to all input whos name start with price

This is the code I've written:

$(document).on('click', '.--copy', function () {
    var input_name = $(this).closest('div').find('input').attr('name').split('-')[0];
    $('input[name^=' + input_name + ']').val($(this).closest('div').find('input').val());
});

A fiddle to make everyones life easier: http://jsfiddle.net/6jGLD/

I feel like there are too many selectors being called upon and the code is somewhat difficult to read.


texts:
This is a simple blackjack game I finished making using Python. I hope you like it and I'm open to any suggestions or critiques you would give me.

from random import shuffle
import sys

def deal(deck, player, dealer):
    shuffle(deck)

    for _ in range(2):
        player.append(deck.pop())
        dealer.append(deck.pop())

def score(hand):
    non_aces = [c for c in hand if c != 'A']
    aces = [c for c in hand if c == 'A']

    total = 0

    for card in non_aces:
        if card in 'JQK':
            total += 10
        else:
            total += int(card)

    for card in aces:
        if total <= 10:
            total += 11
        else:
            total += 1

    return total

def display_info(player, dealer, stand):
    print("Your cards: [{}] ({})".format(']['.join(player), score(player)))
    if stand:
        print("Dealer cards: [{}] ({})".format(']['.join(dealer), score(dealer)))
    else:
        print("Dealer cards: [{}] [?]".format(dealer[0]))

def results(player, dealer, hand, stand):
    if score(player) == 21 and hand:
        print("Blackjack! You won!")
        sys.exit()
    elif score(player) > 21:
        print("Busted. You lost!")
        sys.exit()
    if stand:
        if score(dealer) > 21:
            print("Dealer busted. You won!")
        elif score(player) > score(dealer):
            print("You beat the dealer! You won!")
        elif score(player) < score(dealer):
            print("You lost!")
        else:
            print("Push. Nobody wins or losses.")
        sys.exit()

def hit_stand(deck, player, dealer, hand, stand):
    print("What would you like to do")
    print("[1] - Hit\n[2] - Stand")
    choice = input("> ")
    hand = False
    if choice == '1':
        player.append(deck.pop())
    elif choice == '2':
        stand = True
        while score(dealer) <= 16:
            dealer.append(deck.pop())
        display_info(player, dealer, stand)
        results(player, dealer, hand, stand)

if __name__ == '__main__':
    deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']*4
    player = []
    dealer = []
    standing = False
    first_hand = True
    deal(deck, player, dealer)
    while True:
        display_info(player, dealer, standing)
        results(player, dealer, first_hand, standing)
        hit_stand(deck, player, dealer, first_hand, standing)

The follow-up is "Blackjack game - follow-up".


texts: General way to add persistence to a class in Python

texts:
The idea here is to write a function that gives you back a persistent version of a class that you supply. So you if you run

PersistentList = make_persistent(list, "PersistentList", ['append', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort'])

You will get back a class that behaves like a list but automatically persists itself after each operation. So given this test code:

import time
def get_hhmmss():
    return time.strftime('%H:%M:%S', time.localtime())

def test_list():
    PersistentList = make_persistent(list, "PersistentList", get_mutators(list, tuple))
    filepath = os.path.expanduser("~/Desktop/test_list")
    with contextlib.closing(PersistentList(filepath)) as pl:
        pl.append(get_hhmmss())
        pl += ['foo']
        pl += ['bar']
        print(pl)

def test_set():
    PersistentSet = make_persistent(set, "PersistentSet", get_mutators(set, frozenset))
    filepath = os.path.expanduser("~/Desktop/test_set")
    with contextlib.closing(PersistentSet(filepath)) as ps:
        ps.add(get_hhmmss())
        ps.add('spam')
        print(sorted(ps))

You can get this output:

>>> test_set()
['21:38:27', 'spam']
>>> test_set()
['21:38:27', '21:38:31', 'spam']
>>> test_set()
['21:38:27', '21:38:31', '21:38:34', 'spam']
>>> test_list()
['21:38:39', 'foo', 'bar']
>>> test_list()
['21:38:39', 'foo', 'bar', '21:38:43', 'foo', 'bar']
>>> test_list()
['21:38:39', 'foo', 'bar', '21:38:43', 'foo', 'bar', '21:38:47', 'foo', 'bar']

Here's the code that accomplishes it. I ask in part because I'm tempted to try to share this but assume that if it were a reasonable way to do things it would be out there by now.

import pickle, errno, os, functools, contextlib

def touch_new(filepath):
    "Will fail if filepath already exists, or if relevant directories don't already exist"
    os.close(os.open(filepath, os.O_WRONLY | os.O_CREAT | os.O_EXCL))

def get_mutators(mutable_class, frozen_class):
    "Convenience function for identifying mutators. Methods such as __iadd__ won't wrap properly so this function throws them out; you'll need to call `_save` or `close` to sync after such operations"
    def qualifying_methodname(methodname):
        return not(methodname.startswith("__") and methodname.endswith("__"))
    return sorted(mn for mn in set(dir(mutable_class)) - set(dir(frozen_class)) if qualifying_methodname(mn))

# Inspiration: http://stackoverflow.com/a/9449852/2829764
def make_persistent(original_class, new_classname, mutator_methodnames):
    class NewClass(original_class):
        def __init__(self, filepath):
            self._filepath = filepath
            self._closed = False
            try:
                with open(filepath, "rb") as ifile:
                    loaded = pickle.load(ifile)
                if type(loaded) != original_class: # Don't even allow subclasses
                    raise TypeError("{} exists but does not contain a {}".format(filepath, original_class))
                original_class.__init__(self, loaded)
            except IOError as ioe:
                if ioe.errno != errno.ENOENT:
                    raise
                touch_new(filepath)
                original_class.__init__(self)
            for attr in mutator_methodnames:
                setattr(self, attr, self._autosave(getattr(self, attr)))
        def _autosave(self, func):
            @functools.wraps(func)
            def _func(*args, **kwargs):
                if self._closed:
                    raise ValueError("Invalid operation on closed "+self.__class__)
                ret = func(*args, **kwargs)
                self._save()
                return ret
            return _func
        def _save(self):
            pickle.dump(original_class(self), open(self._filepath, "wb"))
        def close(self):
            if not self._closed:
                self._save()
                self._closed = True
    NewClass.__name__ = new_classname
    return NewClass


texts: Recursively list files within a directory

texts:
I have the following code to recursively list files within a directory:

from fnmatch import filter
from os      import path, walk

def files_within(directory_path):
  files_within = []
  for root, directory_path, files_path in walk(directory_path):
    for file_path in filter(files_path, "*"):
      files_within.append(path.join(root, file_path))
  return files_within

I want change it to avoid side affects. Is it possible?

I'm not using the glob because I'm using Python 2.5 because of a legacy code.


texts: Java Matrix multiplication using Multithreading

texts:
I am trying to achieve matrix multiplication using the concept of concurrency and cyclic barrier.

Here is the code snippet:-

import Jama.Matrix;
public class Application {
public final CyclicBarrier cyclicBarrier;
public Matrix A = new Matrix(200,120);
public Matrix B = new Matrix(120,100);
public Matrix C = new Matrix(200,100);

public Application() {
    initializeMatrix(A,A.getRowDimension(),A.getColumnDimension());
    initializeMatrix(B,B.getRowDimension(),B.getColumnDimension());
    cyclicBarrier = new CyclicBarrier(4, new Runnable() {
        @Override
        public void run() {
            display(C);
        }
    });

    new Thread(new Task(50,25)).start();
    new Thread(new Task(100,50)).start();
    new Thread(new Task(150,75)).start();
    new Thread(new Task(200,100)).start();
}

public void initializeMatrix(Matrix X,int row,int col){
    for (int i=0;i<row;i++)
        for (int j=0;j<col;j++)
            X.set(i,j,Math.random());
}

public void Multiply(int rowend, int col){

    for (int i=0;i<rowend;i++){
        for (int j=0;j<col;j++){
            double sum = 0;
            for (int k=0;k<B.getRowDimension();k++){
                sum += A.get(i,k)*B.get(k,j);
            }
            C.set(i,j,sum);
        }
    }
    display(C);
}

public void display(Matrix X){
    System.out.print("C = [");
    for (int i=0;i<X.getRowDimension();i++){
        for (int j=0;j<X.getColumnDimension();j++){
            System.out.print(X.get(i,j) + ",");
        }
        System.out.println();
    }
    System.out.print(" ]\n\n");
}

private class Task implements Runnable{
    int row = 0;
    int col = 0;

    public Task(int row, int col){
        this.row = row;
        this.col = col;
    }

    @Override
    public void run() {
        Multiply(row, col);
        try {
            cyclicBarrier.await();
        } catch (InterruptedException iex) {
            System.out.println(iex.getMessage());
        } catch (BrokenBarrierException bbex) {
            System.out.println(bbex.getMessage());
        }
    }
}

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

The need of concurrency in this is that the Matrix are huge and I need to do the computation fast. Is this the correct way of doing it? and Can I optimize it further?


texts: Simplified if return suggestion from Android Studio

texts:
I have this very simple method:

private boolean isTheParticipantTalking(ParticipantID participantId){
    if(mCurrentParticipant != null) {
        return participantId.equals(mCurrentParticipant.getId());
    }
    return false; // no one is talking
}

I receive a warning stating that I can simplify the code in the following manner:

private boolean isTheParticipantTalking(ParticipantID participantId){
    return mCurrentParticipant != null && participantId.equals(mCurrentParticipant.getId());
}

In your opinion, is this change desirable? I understand that we go from 4 lines of code to just 1, but I find my way more understandable in one blick.


texts: Validating an input string against some enum fields

texts:
I have this enum below:

public enum TestEnum {
    h1, h2, h3, h4;

    public static String forCode(int code) {
    return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

    public static void main(String[] args) {
        System.out.println(TestEnum.h1.name());
        String ss = "h3";

        try {
           TestEnum.valueOf(ss); // but this validates with all the enum values
           System.out.println("valid");
        } catch (IllegalArgumentException e) {
           System.out.println("invalid");
        }
    }
}

I need to check if the enum value represented by my string ss is one of my enum values h1, h2 or h4. So if h3 is being passed as a string, I would like to return false or throw IllegalArgumentException. I won't need to validate ss with h3 in the enum.

I came up with the below code to do this with the enum, but I believe there is a more elegant solution.

public enum TestEnum {
    h1, h2, h3, h4;

    public static boolean checkExcept(String el, TestEnum... except){
        boolean results = false;
        try{
            results = !Arrays.asList(except).contains(TestEnum.valueOf(el));
        }catch (Exception e){}
        return results;
    }

    public static String forCode(int code) {
        return (code >= 0 && code < values().length) ? values()[code].name() : null;
    }

    public static void main(String[] args) {

        String ss = "h3";

        if(TestEnum.checkExcept(ss,TestEnum.h1, TestEnum.h2, TestEnum.h3)){
           System.out.println("valid");
        }else{
           System.out.println("invalid");
        }
    }
}

Is there any better way of solving this problem?


texts:
This script checks specific directories for *.pgp files. It returns a list of the filenames and modified dates. It then returns a list of the filenames and modified dates, each on a new line. I'm new to Python, like literally two weeks now and this script was written for a specific work purpose, but I'm betting it could be tweaked.

import glob
import os
from datetime import datetime

monitor_files = []

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/adr01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("adr01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/chpt/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("chpt | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/emb01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("emb01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/exp01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("exp01 | " + file + (" | ") + str(last_modified_date) + "\n")

os.chdir("/home/skeer/Documents/Projects/Python_temp/home/iix01/upload/")
for file in glob.glob("*.pgp"):
    if os.path.isfile(file):
        last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
    else:
        last_modified_date = datetime.fromtimestamp(0)
    monitor_files.append("iix01 | " + file + (" | ") + str(last_modified_date) + "\n")

print("\n".join(monitor_files))


texts:
Here's my solution for the Leet Code's Three Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting. This is Python 3.

Problem:

  Given an array nums of n integers, are there elements a, b, c in nums
  such that a + b + c = 0? Find all unique triplets in the array which
  gives the sum of zero.

  Note:

  The solution set must not contain duplicate triplets.

  Example:

  Given array nums = [-1, 0, 1, 2, -1, -4],

  A solution set is: [   [-1, 0, 1],   [-1, -1, 2] ]

My solution:

def threeSum(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """

    def _twoSum(nums_small, target):
        '''
        INPUT: List of numeric values, int target
        OUTPUT: list: pair(s) from nums_small that add up to target and -1*target
        '''
        nums_dict = {}
        return_lst = []

        for indx, val in enumerate(nums_small, target):
            if target - val in nums_dict:
                return_lst.append([val, target - val, -1*target])
            nums_dict[val] = indx
        return return_lst

    return_dict = {}

    for indx, val in enumerate(nums):
        for solution in _twoSum(nums[:indx] + nums[indx+1:], -1*val):
            if sorted(solution) not in return_dict.values():
                return_dict[str(indx)+str(solution)] = sorted(solution) # ... hacky way of storing multiple solutions to one index ...

    return list(return_dict.values())


texts: Implementing a Steepest Descent Algorithm

texts:
I am teaching myself some coding, and as my first "big" project I tried implementing a Steepest Descent algorithm to minimize the Rosenbrock function:

$$f(x, y) = 100 (y - x^2)^2 + (1 - x)^2$$

The algorithm goes like this: We start with an initial guess \$x_0\$ (vector). We update the guess using the formula

$$x_{k+1} = x_k - alpha (\nabla f(x_k) \cdot \nabla f(x_k))$$

where alpha is to be chosen so that is satisfies the Armijo condition. We keep repeating until we reach a point where the gradient is less than 0.1 in both components.

Could you please tell me any ways in which I could improve my algorithm? In particular, I'm looking to increase its speed. From the current starting point, it takes about 30 seconds to run on my computer (16GM ram, i7 processor).

Remark: The reason I keep using np.array([[1, 2, 3]]) for vectors is so that I can transpose and matrix multiply them at will. I'm not sure if this is a good practice.

# This program uses the Steepest Descent Method to
# minimize the Rosenbrock function
import numpy as np

# Define the Rosenbrock Function
def f(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return 100 * (y - x**2)**2 + (1 - x)**2

# Gradient of f
def gradient(x_k):
    x, y = x_k[0, 0], x_k[0, 1]
    return  np.array([[-400*x*(y-x**2)-2*(1-x), 200*(y-x**2)]])

def main():
    # Define the starting guess
    x_k = np.array([[10, 5]])
    # Define counter for number of steps
    numSteps = 0

    # Keep iterating until both components of the gradient are less than 0.1 in absolute value
    while abs((gradient(x_k)[0, 0])) > 0.1 or abs((gradient(x_k))[0, 1]) > 0.1:
        numSteps = numSteps + 1

        # Step direction
        p_k = - gradient(x_k)
        gradTrans = - p_k.T

        # Now we use a backtracking algorithm to find a step length
        alpha = 1.0
        ratio = 0.8
        c = 0.01 # This is just a constant that is used in the algorithm

        # This loop selects an alpha which satisfies the Armijo condition
        while f(x_k + alpha * p_k) > f(x_k) + (alpha * c * (gradTrans  @ p_k))[0, 0]:
            alpha = ratio * alpha

        x_k = x_k + alpha * p_k

    print("The number of steps is: ", numSteps)
    print("The final step is:", x_k)
    print("The gradient is: ", gradient(x_k))

main()


texts:
Below I have some code that I use to handle incoming socket data, this is not full thing but its the part I am worried about, is there any way to improve this?

int packetPosition = 0;
                while (packetPosition < packetData.Length)
                {
                    try
                    {
                        int MessageLength = Apple.Encoding.DecodeInt32(new byte[] { packetData[packetPosition++], packetData[packetPosition++], packetData[packetPosition++] });
                        uint MessageId = Apple.Encoding.DecodeUInt32(new byte[] { packetData[packetPosition++], packetData[packetPosition++] });

                        byte[] Content = new byte[MessageLength - 2];

                        for (int i = 0; i < Content.Length && packetPosition < packetData.Length; i++)
                        {
                            Content[i] = packetData[packetPosition++];
                        }

                        IncomingPacket incomingPacket = new IncomingPacket(MessageId, Content);
                    }
                    catch (Exception e)
                    {
                        _log.Error(e);
                        Apple.Game.PlayerManager.DisposePlayer(_playerData.PlayerId);
                    }
                }


texts:
im using the following code which is working.
The code provide range of random values but unique one i.e. it doesn't return  the same values until the full range was provided ,what do you think and doest in ES6 there is shorter way to achieve this?

var range = [10, 20];
var not = [];

function randomRange(range, n) {
  if (not.length >= range[1] - range[0]) {
    not.length = 0;
  }
  var curr = [];
  var res = [];
  for (let i = range[0]; i < range[1]; i++) {
    if (!not.some(function(num) {
      return i == num
    }) && not.length < range[1] - range[0]) {
      curr.push(i)
    }
  }
  for (let i = 0; i < n; i++) {
    var j = curr.splice(Math.floor(Math.random() * curr.length), 1)[0];
    res[i] = not[not.length] = j;
  }

  return res.filter(Boolean)
}

function log(result) {
  document.body.innerHTML += JSON.stringify(result) + "<br>"
}

window.onload = function() {

log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
log(randomRange(range, 3));
}


texts: Remove the second number from every group of three numbers

texts:
I have this simple loop that prints numbers from 0 to 29 (30 in total). I want to "split" the results in threes and remove the middle number. So the first set is 0,1,2 and I only want 0,2. The second set is 3,4,5 and I only want 3,5. This works as it supposed too, but is there a way to make it more simpler?

z = 1
for i in range(0,30):
    if z == 1:
        print(i, end=' ')
        z+=1
    elif z == 3:
        print(i, end=' ')
        z=1
    else:
        z+=1

This is the result:

0 2 3 5 6 8 9 11 12 14 15 17 18 20 21 23 24 26 27 29


texts: Minimum window substring using python containing substr in any order

texts:
Given an array of unique characters arr and a string str, implement a function getShortestUniqueSubstring that finds the smallest substring of str containing all the characters in arr. Return "" (empty string) if such a substring doesn’t exist.

This algorithm is used.

import collections
import sys

def get_shortest_unique_substring(substring, string):
  def trim_left(substring, window, count):
    ''' find how much left pointer can be moved in a window where all substring is present'''
    for left, c in enumerate(window):
      if c in count and count[c] > 1:
        count[c] -= 1
      elif c not in count:
        continue
      else:
        return left
    return 0

  substring = set(substring)
  ''' validating input '''
  if not substring or not string:
    return ""
  if len(substring) == len(string) and substring == set(string):
    return string

  window, min_window, min_window_len = [], [], sys.maxint
  left, right, count = 0, 0, collections.Counter()
  # to check if the initial minimum window has been found which has all the substring
  substr_found = set(substring)

  for right, c in enumerate(string):
    if c in substring:
      count[c] += 1
      if c in substr_found:
        substr_found.remove(c)
      # window has been found and now trim left pointer as much as possible maintaining the invariant that substr is still present between left and right pointers
      if not substr_found:
        left += trim_left(substring, string[left:right+1], count)
        # update the minimum window
        if right - left + 1 < min_window_len:
          min_window_len, min_window = right - left + 1, string[left:right+1]
        # we can't find better window than the length of substr
        if len(min_window) == len(substring):
          return "".join(min_window)
  return "".join(min_window)


texts: Extract incomplete weeks from a DateTime collection

texts:
The code below attempts to extract incomplete weeks from a List<DateTime>.

For example, a list containing all the days in Jan 2015 would result in the 5th to the 25th inclusive.

I know the list going in will contain unique dates, and are in date order. It seems to be working but I can't help but think this could be done better.

private IEnumerable<DateTime> extractIncompleteWeeks(IEnumerable<DateTime> dates)
{
    var mondays = dates
        .Where((d, i) => d.DayOfWeek == DayOfWeek.Monday)
        .Select(d => d.Date);

    var results = new List<DateTime>();

    foreach (var monday in mondays)
    {
        var fullWeek = new HashSet<DateTime>(dates.SkipWhile(d => d < monday).Take(7).Select(d => d.Date));

        if (fullWeek.Last().Date == monday.AddDays(6).Date)
            results.AddRange(fullWeek);
    }

    return results;
}


texts:
I have a CSV file which looks like this:

ID | Name | Date
"1","Foo1","2013-08-03 21:00:08"
"1","Foo2","2013-08-03 21:00:08"
"2","Foo3","2013-08-03 21:00:08"
...

I need to write a method which returns a list of the lines with same ID and date, for reading the CSV file I am using OpenCSV. My question is whether or not this method can be rewritten in more elegant way.

private String[] currentWorkerLine;
private String relationIdentifier;
private String currentStartDate;
private int rowCount;

private List<String[]> getWorkers(CSVReader reader) throws Exception{
    List<String[]> workers = new ArrayList<>();
    if (currentWorkerLine == null && rowCount == 0){
        currentWorkerLine = reader.readNext();
        relationIdentifier = currentWorkerLine[0];
        currentStartDate = currentWorkerLine[2];
        workers.add(currentWorkerLine);
        rowCount++;
    }

    while ((currentWorkerline = reader.readNext()) != null) {
        if (!isRelatedLine(currentWorkerline[0]) || !isCurrentDateLine(currentWorkerline[2])){
            lastLine = currentWorkerline;
            return workers;
        }
        relationIdentifier = currentWorkerline[0];
        currentStartDate = currentWorkerline[2];
        workers.add(currentWorkerline);
        lastLine = currentWorkerline;
        rowCount++;
    }
    if (currentWorkerline == null && lastLine != null) {
        workers.add(lastLine);
        rowCount++;
        lastLine = null;
    }
    return workers;
}

private boolean isRelatedLine(String rel) {
    return rel.equals(relationIdentifier);
}

private boolean isCurrentDateLine(String date) {
    return date.equals(currentStartDate);
}


texts: Counting the number of bits of a positive integer

texts:
How can I improve this code for counting the number of bits of a positive integer n in Python?

def bitcount(n):
    a = 1
    while 1<<a <= n:
        a <<= 1

    s = 0
    while a>1:
        a >>= 1
        if n >= 1<<a:
            n >>= a
            s += a
    if n>0:
        s += 1

    return s


texts: Using iTextSharp and AddDocument/FreeReader to create a PDF document in streaming fashion

texts:
I have a directory of PDF files I want to merge into a single PDF.  The number of files in the directory could be 10s, 100s, or even 1000s, so I'm trying to make sure my process is streaming as much as possible.

MergePDFDocuments is passed an output Stream and I'm hoping the process below never has more than 1 PDF file loaded in memory at a time.

I had an incorrect version of this written originally, and was told on my Stackoverflow question not to use PdfWriter but instead use PdfSmartCopy.  Is FreeReader() going to release memory consumed by each PDF file as it is processed?

private void MergePDFDocuments( string batchFilesFolder, Stream outputStream )
{
    using ( var batchDocument = new iTextSharp.text.Document() )
    using ( var smartCopy = new iTextSharp.text.pdf.PdfSmartCopy( batchDocument, outputStream ) )
    {
        batchDocument.Open();

        foreach ( var file in new DirectoryInfo( batchFilesFolder ).GetFiles( "*.pdf" ) )
        {
            // we create a reader for the document
            using ( var reader = new iTextSharp.text.pdf.PdfReader( file.FullName ) )
            {
                smartCopy.AddDocument( reader );
                smartCopy.FreeReader( reader );
            }
        }
    }
}


texts: Exporting doc types using queues and multithreading

texts:
For a while I have been interested in seeing if some tasks work well when split across multiple threads.

On the one project I have been busy with I have been creating a lot of small utility apps, to do single tasks for me, so this morning while modifying one I thought I would give it a try.

What I wrote seems to work, although I am not sure if it is the best way, or recommended way to do something like this, so I want to ask what is wrong with my code and how could it be done better. What it is doing is not really important, and I am not interested if this sort of task should be split up, but more along the lines of how good or bad is the code that I have written.

private static void ExportDocTypes(IEnumerable<string> docTypes)
{
    var queue = new Queue<string>(docTypes);
    var tasks = new List<Task>();
    for (byte i = 0; i < threadCount; i++)  //threadCount is a const set to 4.
    {
        Action a = () =>
        {
            while(queue.Count() > 0) {
                var type = queue.Dequeue();
                ExportDocuments(type, i);  //i is only sent for response.write
            }
        };
        var t = new Task(a);
        t.Start();
        tasks.Add(t);
        System.Threading.Thread.Sleep(10);
    }
    while (tasks.Count() > 0)
    {
        foreach (var t in tasks)
        {
            if (t.IsCompleted)
            {
                t.Dispose();
                tasks.Remove(t);
            }
        }
        System.Threading.Thread.Sleep(1000);
    }
}


texts:
I'm a complete beginner to Python, and wanted to get some feedback on my first app. I tried to make a clone of the 'evolution of text' app found on the Using Python website.

  Enter some text, and watch the program 'evolve' the answer. The program just prints a load of random text, but keeps the correct bits each time.

I wrote my program without looking at the solution on the website. My solution is a little different, so I wanted to ask some more experienced developers what they think of it, what might be bad style and what could be improved.

import random
import string

target = list(raw_input("Enter your target text: "))
current = [random.choice(string.ascii_letters + string.digits + string.punctuation + ' ') for n in range(len(target))]
index = 0
counter = 0

while current != target:
    if current[index] != target[index]:
        current[index] = random.choice(string.ascii_letters + string.digits + string.punctuation + ' ')
        counter += 1
        print ' '.join(current)
    if index == len(target) - 1:
        index = 0
    else:
        index += 1

print("Done! Match took {0} generations.".format(counter))


texts: Cloning Windows Forms controls from a template

texts:
In a recent project I needed a way to clone windows forms controls from a template which had predefined Size, Font, etc.

Since there is no Clone() method in the Control class, I created my own object that does that:

public class ControlTemplate<TSource>
    where TSource : Control
{
    private readonly List<Action<TSource>> _controlActions;

    public ControlTemplate()
    {
        _controlActions = new List<Action<TSource>>();
    }

    public ControlTemplate<TSource> WithArgument(Action<TSource> action)
    {
        if (action == null)
        {
            throw new ArgumentNullException(nameof(action));
        }
        _controlActions.Add(action);
        return this;
    }

    public TSource Clone()
    {
        TSource control = Activator.CreateInstance<TSource>();
        foreach (var action in _controlActions)
        {
            action.Invoke(control);
        }
        return control;
    }
}

It works somewhat like the Builder pattern, you can call WithArgument multiple times and all of the changes to the control will be saved in a list, to be later executed in the Clone method, on a fresh object in order to apply all of the changes.

The problem with this class is that it's not immutable and that's something really important here in order to have the same object every time you clone it.

If you have an instance of it stored somewhere that works as a template, outside classes can access the Clone method to create new object but they can also make modifications to the template using the WithArgument method, which will cause problems.

In order to fix that I made a "wrapper" class that only exposes the Clone method and operates with an instance of ControlTemplate internally which makes the template more immutable:

public class ControlTemplateCreator<TSource>
    where TSource : Control
{
    private readonly ControlTemplate<TSource> _sourceOfTemplate;

    public ControlTemplateCreator(ControlTemplate<TSource> sourceOfTemplate)
    {
        if (sourceOfTemplate == null)
        {
            throw new ArgumentNullException(nameof(sourceOfTemplate));
        }
        _sourceOfTemplate = sourceOfTemplate;
    }

    public TSource Clone()
    {
        return _sourceOfTemplate.Clone();
    }
}

Example usage would be:

public static class Settings
{
    private static readonly ControlTemplate<Label> _templateLabel;
    public static ControlTemplateCreator<Label> TemplateLabel { get; }

    static Settings()
    {
        _templateLabel = new ControlTemplate<Label>()
            .WithArgument(label => label.TextAlign = ContentAlignment.MiddleLeft)
            .WithArgument(label => label.AutoSize = false)
            .WithArgument(label => label.Size = new Size(135, 20))
            .WithArgument(label => label.Margin = new Padding(0))
            .WithArgument(label => label.Font = new Font("Aerial", 9));

        TemplateLabel = new ControlTemplateCreator<Label>(_templateLabel);
    }
}

public class Foo
{
    public void Bar()
    {
        Label clonedLabelFromTemplate = Settings.TemplateLabel.Clone();
    }
}

The code looks pretty good to me, it's extendable, you can create various templates from the same class, outside classes cant modify the original template.

Here are some of my questions:

I wonder why isn't there a Clone method in the Control class are there any bad sides to cloning controls this way?
Are there any flaws in the code?
I'm not sure if WithArgument is a good name.


texts:
I am working through Automate the Boring Stuff. How can I make this code cleaner/better?

#madlibs.py : ABS Chapter 8 Project
#Make mad libs using madlibtemplate.txt file that will prompt user for parts of speech
#Will return new file with replacements called madlib.txt

import re, os

#Create template.txt file if doesn't exist

print("Let's play MadLibs! \n Note: Your current working directory is ", os.getcwd())
if os.path.exists('madlibtemplate.txt') == False:
    print("No template file found. Using default 'madlibtemplate.txt'")
    template = open('madlibtemplate.txt', 'w+')
    template.write("""The ADJECTIVE girl walked to the NOUN and then VERB.
    A nearby NOUN was upset by this.""")
else:
    print("Using your 'madlibtemplate.txt' file:")
    template = open('madlibtemplate.txt', 'r')

#Extract text from template file & turn into list of words

template.seek(0) #reset pointer to beginning of file
text = (template.read()).lower() #make lowercase to match parts of speech

wordregex = re.compile(r'\w+|\s|\S')
words = re.findall(wordregex, text)

#Find and replace parts of speech

for i, word in enumerate(words):
    for part_of_speech in ['adjective', 'noun', 'adverb', 'verb', 'interjection']:
        if word == part_of_speech:
            print('Enter a(n) %s ' % part_of_speech)
            words[i] = input()

madlib_text_unformatted = ''.join(words)

#Capitalize first letter in each sentence (Function found on stackoverflow)

def sentence_case(text):
    # Split into sentences. Therefore, find all text that ends
    # with punctuation followed by white space or end of string.
    sentences = re.findall('[^.!?]+[.!?](?:\s|\Z)', text)

    # Capitalize the first letter of each sentence
    sentences = [x[0].upper() + x[1:] for x in sentences]

    # Combine sentences
    return ''.join(sentences)

madlib_text = sentence_case(madlib_text_unformatted)

#Print result and save to a new file

print('Here we go... \n')
print(madlib_text)

madlib = open('madlib.txt', 'w')
madlib.write(madlib_text)
madlib.close()
template.close()

print("\n This has been saved to file 'madlib.txt'")


texts: Print out all possible letter combinations a given phone number can represent

texts:
I am working on a problem in which given a 7 digit telephone number, we need to print out all possible combinations of letters that each number could represent.

I came up with below code and I was wondering if there is any way to optimize it or if there is any better way? As of now complexity is O(n3).

public class LetterCombinationsOfPhoneNumber {
  private static final HashMap<Character, String> map = new HashMap<>(8);
  static {
    map.put('2', "abc");
    map.put('3', "def");
    map.put('4', "ghi");
    map.put('5', "jkl");
    map.put('6', "mno");
    map.put('7', "pqrs");
    map.put('8', "tuv");
    map.put('9', "wxyz");
  };

  public static List<String> letterCombinations(String digits) {
    LinkedList<String> results = new LinkedList<>();
    results.add("");

    for (int i = 0; i < digits.length(); i++) {
      String letters = map.get(digits.charAt(i));
      for (int j = results.size(); j > 0; j--) {
        String intermediateResult = results.poll();
        for (int k = 0; k < letters.length(); k++) {
          results.add(intermediateResult + letters.charAt(k));
        }
      }
    }
    return results;
  }

  public static void main(String[] args) {
    System.out.println(letterCombinations("23"));
  }
}


texts:
I've built this small jQuery plugin to work with HTML5 History State functions. It's my first jQuery plugin, so I'm not sure if it's up to the best practices, or what could be done better. Keeping it simple and small is my main concern.

If you have any suggestions on how to improve it, I'd love to see them.

// FunkyHistory Plugin
(function ( $, window, document, undefined ) {
jQuery.fn.FunkyHistory = function( options, callback ) {

    // Don't do anything if History not supported
    if (!window.history && !window.history.pushState) {
        return this;
    }

    // These are the defaults.
    var settings = jQuery.extend({
            target: null,
            selector: "body"
    }, options );

    // Prepare
    var FunkyHistory = {};
        FunkyHistory.selector = this.selector;
        FunkyHistory.clickedEl = null;

    // Update content on page
    FunkyHistory.loadNewContent = function(target, url, selector){

        jQuery.get(url, function(data) {

            // Update content on page
            var newContent = jQuery(data).find(selector);

            // Only update content if a target is set
            if( settings.target ) {
                jQuery(target).replaceWith(newContent);
            }

            // Callback
            if (typeof callback == 'function') { // make sure the callback is a function
                callback.call(FunkyHistory.clickedEl, data); // brings the scope to the callback
            }

        }, 'text');
    }

    // When browser back/forward button is pressed
    FunkyHistory.bindPopState = function(){
        jQuery(window).on('popstate',function(event){
            // Load in correct conetent
            FunkyHistory.loadNewContent(settings.target, location.href, settings.selector);
        });
    }

    // Bind to click of tags
    FunkyHistory.bindClicks = function(){

        jQuery(document).on('click', FunkyHistory.selector, function(e){
            e.preventDefault();

            // Cahce the clicked elements "this"
            FunkyHistory.clickedEl = this;

            // Set State to history
            var stateObj = {
                selector: settings.selector,
                url: jQuery(this).attr('href')
            };
            history.pushState(stateObj, null, stateObj.url);
            FunkyHistory.loadNewContent( settings.target, stateObj.url, settings.selector );
        });
    }

    // Do stuff
    FunkyHistory.bindPopState();
    FunkyHistory.bindClicks();

    // Return tags to be chainable
    return this;

};
 })( jQuery, window, document );

And you'd call it like this:

jQuery('#menu a').FunkyHistory({
    target: '#content', // This is replaced by AJAX content
    selector: "#content.new" // This is what to look for in the AJAX content
}, function(data){
    // Callback in here
    console.log(this, data);
});

I have a working example of it here.


texts:
This is code I wrote for calculating bezier curves as quickly and RAM efficiently as possible.

I would like to know if there are faster ways to optimize anything, because I am very new to C++ and efficiency methods.

Lastly, if there is a variable that could be more explicitly named, also let me know.

#include <vector>

double* bezier_interp (double* points, double* temp_space, int temp_space_size, int points_total, double t_step_t) {
    memcpy(temp_space, points, temp_space_size);
    for (int pointsi = points_total; pointsi > 1; --pointsi){
        for (int pointsj = 1; pointsj < pointsi; pointsj++) {
            points[pointsj-1] -= (points[pointsj-1] - points[pointsj]) * t_step_t;
        }
    }
    return points;
}

double* bezier_t (double* numbers, int points_total, int definition) {
    double *result = new double[definition];

    double t_step = 1 / ((double) definition - 1);
    double t_step_t;
    double* temp_space = new double[points_total];
    int temp_space_size = sizeof(*temp_space) * points_total;
    for (int t = 0; t < definition; t++) {
        t_step_t = t * t_step;
        result[t] = *bezier_interp(numbers, temp_space, temp_space_size, points_total, t_step_t);
    }
    delete[] temp_space;
    return result;
}

#include<iostream>

int main() {
    double numbers_x[] = {
        0, 0, 4, 4
    };
    double numbers_y[] = {
        0, 4, 4, 0
    };
    int definition = 8;
    double* xs = bezier_t(numbers_x, 4, definition);
    double* ys = bezier_t(numbers_y, 4, definition);
    for (int dix = 0; dix < definition; dix++){ std::cout << xs[dix] << "\t"; }
    std::cout << "\n";
    for (int diy = 0; diy < definition; diy++){ std::cout << ys[diy] << "\t"; }
    std::cin.get();
    return 0;
}


texts: Project Euler problem 14 (longest Collatz sequence) in Swift 3

texts:
I was trying to solve Project Euler:Problem 14 using Swift 3, but it takes ages to give me an answer, which is a sign that my code is absolute garbage performance-wise. What could I do to increase the performance of the code?

import UIKit

/* The following iterative sequence is defined for the set of positive integers:

 n → n/2 (n is even)
 n → 3n + 1 (n is odd)

 Using the rule above and starting with 13, we generate the following sequence:

 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

 Which starting number, under one million, produces the longest chain?

 NOTE: Once the chain starts the terms are allowed to go above one million. */

func collatzSeq(starting: Int) -> [Int] {

    var collatzArray = [starting]

    while collatzArray.last != 1 {
        if collatzArray.last! % 2 == 0 {
            collatzArray.append(collatzArray.last!/2)
        } else {
            collatzArray.append((3*collatzArray.last!)+1)
        }
    }
    return collatzArray
}

var longestChain = 0
for index in 1...999999 {
    if collatzSeq(starting: index).count > longestChain {
        longestChain = index
        print("Starting at \(longestChain) produces the longest chain.")
    }
    }